Evaluate() public method

Calculate color at a given time.

public Evaluate ( float time ) : Color
time float Time of the key (0 - 1).
return Color
Example #1
1
        /// <summary>
        /// Draws gradient rectangle on texture
        /// </summary>t
        public static void DrawGradientRect(this Texture2D texture, int x, int y, int blockWidth, int blockHeight,
            Gradient gradient, Directions progressionDirection)
        {
            Func<int, int, Color> getColor;
            switch (progressionDirection)
            {
                case Directions.Left:
                    getColor = (_x, _y) => gradient.Evaluate(1 - (float) _x/(float) blockWidth);
                    break;
                case Directions.Right:
                    getColor = (_x, _y) => gradient.Evaluate((float) _x/(float) blockWidth);
                    break;
                case Directions.Down:
                    getColor = (_x, _y) => gradient.Evaluate(1 - (float) _y/(float) blockHeight);
                    break;
                case Directions.Up:
                    getColor = (_x, _y) => gradient.Evaluate((float) _y/(float) blockHeight);
                    break;
                default:
                    Debug.LogError("Not supported direction: " + progressionDirection);
                    return;
            }

            var colors = new Color[blockWidth*blockHeight];
            for (int _y = 0; _y < blockHeight; _y++)
            {
                for (int _x = 0; _x < blockWidth; _x++)
                {
                    colors[_x + _y*blockWidth] = getColor(_x, _y);
                }
            }
            texture.SetPixels(x, y, blockWidth, blockHeight, colors);
        }
Example #2
0
    public void CreateHeightMap()
    {
        // Set up noise
        rigged = new RiggedMultifractal(frequency, lacunarity, octaves, seed, quality);
        perlin = new Perlin(frequency, lacunarity, persistence, octaves, seed, quality);
        billow = new Billow(frequency, lacunarity, persistence, octaves, seed, quality);

        //ModuleBase moduleBase = perlin;

        // Apply noise to the meshes
        foreach (Transform child in transform)
        {
            MeshFilter meshFilter = child.GetComponent <MeshFilter> ();
            Vector3[]  vertices   = meshFilter.sharedMesh.vertices;
            Vector3[]  normals    = meshFilter.sharedMesh.normals;

            Color[] colorMap = new Color[vertices.Length];

            for (int i = 0; i < vertices.Length; i++)
            {
                float magnitude = (float )perlin.GetValue(vertices[i].x / scale, vertices[i].y / scale, vertices[i].z / scale);
                //float magnitude = (float )rigged.GetValue(vertices[i].x / scale, vertices[i].y / scale, vertices[i].z / scale);
                vertices [i] = Vector3.MoveTowards(vertices [i], (vertices [i] + normals [i]), magnitude * heightMultiplier);
                colorMap [i] = gradient.Evaluate((magnitude + 1) * 0.5f);
            }

            meshFilter.sharedMesh.vertices = vertices;
            meshFilter.sharedMesh.colors   = colorMap;
            meshFilter.sharedMesh.RecalculateNormals();
        }
    }
    private Color[] ColorVertices(Mesh mesh)
    {
        int length = mesh.vertices.Length;

        Color[]   colors   = new Color[length];
        Vector3[] vertices = mesh.vertices;

        // Find maximum height to make color relative to highest point
        float max = -99999f;

        for (int i = 0; i < length; i++)
        {
            if (vertices[i].y > max)
            {
                max = vertices[i].y;
            }
        }

        for (int i = 0; i < length; i++)
        {
            colors[i] = gradient.Evaluate(vertices[i].y / max);
        }

        return(colors);
    }
 static public int Evaluate(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         UnityEngine.Gradient self = (UnityEngine.Gradient)checkSelf(l);
         System.Single        a1;
         checkType(l, 2, out a1);
         var ret = self.Evaluate(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Example #5
0
    void Update()
    {
        Header.text = Target.GetName();

        var actual = Target.Strength;

        Actual.fillAmount = actual;
        Actual.color      = ValueDisplayGradient.Evaluate(actual);

        if (!Target.UseMidi)
        {
            Target.Value.Multiplier = MultiplierSlider.value;
        }
        else
        {
            MultiplierSlider.value = Target.Value.Multiplier;
        }

        BuffDisplay.text = Target.Value.BufferSize.ToString();

        SmoothDisplay.text = Target.Value.Smooth.ToString("0.00");

        MultiplierSlider.interactable = !Target.UseMidi;

        if (!Target.UseMidi)
        {
            MidiChannelList.transform.parent.gameObject.SetActive(false);
            MidiIndex.transform.parent.gameObject.SetActive(false);
        }
        else
        {
            MidiChannelList.transform.parent.gameObject.SetActive(true);
            MidiIndex.transform.parent.gameObject.SetActive(true);
        }
    }
Example #6
0
        private UIVertex[] CreateLineSegment(Vector2 start, Vector2 end, SegmentType type, float startLifetime, float endLifetime)
        {
            Vector2 offset = new Vector2((start.y - end.y), end.x - start.x).normalized *lineThickness / 2;

            var v1 = start - offset;
            var v2 = start + offset;
            var v3 = end + offset;
            var v4 = end - offset;

            if (LineLifetime > 0f)
            {
                var startColor = lineColor.Evaluate(startLifetime / LineLifetime);
                var endColor   = lineColor.Evaluate(endLifetime / LineLifetime);
                //Return the VDO with the correct uvs
                switch (type)
                {
                case SegmentType.Start:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, startUvs, startColor, endColor));

                case SegmentType.End:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, endUvs, startColor, endColor));

                case SegmentType.Full:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, fullUvs, startColor, endColor));

                default:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, middleUvs, startColor, endColor));
                }
            }
            else
            {
                switch (type)
                {
                case SegmentType.Start:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, startUvs));

                case SegmentType.End:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, endUvs));

                case SegmentType.Full:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, fullUvs));

                default:
                    return(SetVbo(new[] { v1, v2, v3, v4 }, middleUvs));
                }
            }
        }
Example #7
0
 protected override Color EvaluateValue(float toEvaluate)
 {
     if (Colors == null)
     {
         Colors = new UnityEngine.Gradient();
     }
     return(Colors.Evaluate(toEvaluate));
 }
 public static void RefreshPreview(Gradient gradient, Texture2D preview)
 {
   Color[] colors = new Color[512];
   for (int index = 0; index < 256; ++index)
     colors[index] = colors[index + 256] = gradient.Evaluate((float) index / 256f);
   preview.SetPixels(colors);
   preview.Apply();
 }
Example #9
0
 public void TextureFromGradient()
 {
     for (int i = 0; i < LUTTextureWidth; i++)
     {
         m_lensFlareGradColor[i] = m_lensGradient.Evaluate(( float )i / ( float )(LUTTextureWidth - 1));
     }
     m_lensFlareGradTexture.SetPixels(m_lensFlareGradColor);
     m_lensFlareGradTexture.Apply();
 }
Example #10
0
    private Color[] GetVertexColors(double[,] vertCol, UnityEngine.Gradient gradient, int idx)
    {
        Color[] colors = new Color[vertCol.GetLength(0)];

        for (int i = 0; i < vertCol.GetLength(0); i++)
        {
            colors[i] = gradient.Evaluate((float)vertCol[i, idx]);
        }
        return(colors);
    }
Example #11
0
 public void Start()
 {
     tex = new Texture2D(1024, 1);
     for (int i = 0; i < tex.width; i++)
     {
         float t = (float)i / (float)tex.width;
         tex.SetPixel(i, 0, gradient.Evaluate(t));
     }
     tex.Apply();
     TextureBinding.Invoke(tex);
 }
Example #12
0
    public Gradient BlendGradient(Gradient terrain_gradient, Gradient object_gradient)
    {
        List<ColorHSV> targetPalette = new List<ColorHSV>();
        List<ColorHSV> currentPalette = new List<ColorHSV>();
        targetPalette = RandomE.TetradicPalette(0.25f, 0.75f);
        Debug.Log(targetPalette.Count);
        ColorHSV groundColor = new ColorHSV(terrain_gradient.Evaluate(0));
        ColorHSV newColor = new ColorHSV(object_gradient.Evaluate(1));
        targetPalette.Add(ColorHSV.Lerp(groundColor, newColor, 0.5f));
        var gradient = ColorE.Gradient(from: targetPalette[2].WithSV(0.8f, 0.8f),
            to: targetPalette[3].WithSV(0.8f, 0.8f));

        return object_gradient;
    }
Example #13
0
 static public int Evaluate(IntPtr l)
 {
     try {
         UnityEngine.Gradient self = (UnityEngine.Gradient)checkSelf(l);
         System.Single        a1;
         checkType(l, 2, out a1);
         var ret = self.Evaluate(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #14
0
 static public int Evaluate(IntPtr l)
 {
     try{
         UnityEngine.Gradient self = (UnityEngine.Gradient)checkSelf(l);
         System.Single        a1;
         checkType(l, 2, out a1);
         UnityEngine.Color ret = self.Evaluate(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
    public void ApplyNoiseToChild(GameObject patch)
    {
        MeshFilter meshFilter = patch.GetComponent <MeshFilter>();

        Vector3[] vertices = meshFilter.sharedMesh.vertices;
        Vector3[] normals  = meshFilter.sharedMesh.normals;

        Color[] colorMap = new Color[vertices.Length];

        noiseGenerator.SetFrequency(frequency);
        noiseGenerator.SetFractalGain(gain);
        noiseGenerator.SetNoiseType(noiseType);
        noiseGenerator.SetPositionWarpAmp(warpAmp);
        noiseGenerator.SetFractalLacunarity(lacunarity);
        noiseGenerator.SetFractalOctaves(octaves);
        noiseGenerator.SetNoiseType(noiseType);
        noiseGenerator.SetFractalType(fractalType);
        noiseGenerator.SetCellularDistanceFunction(distFunction);
        noiseGenerator.SetCellularReturnType(cellularReturnType);

        // Sample noise function
        for (int i = 0; i < vertices.Length; i++)
        {
            //int heightOffset = 1;
            for (int j = 0; j < vertices.Length; j++)
            {
                float magnitude = noiseGenerator.GetSimplexFractal(vertices[i].x, vertices[i].y, vertices[i].z);
                vertices[i] = Vector3.MoveTowards(vertices[i], normals[i].normalized, magnitude * heightMultiplier);
                colorMap[i] = gradient.Evaluate((magnitude + 1) * 0.5f);
            }
        }

        meshFilter.sharedMesh.vertices = vertices;
        meshFilter.sharedMesh.colors   = colorMap;
        meshFilter.sharedMesh.RecalculateNormals();
    }
Example #16
0
 static int Evaluate(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Gradient obj = (UnityEngine.Gradient)ToLua.CheckObject(L, 1, typeof(UnityEngine.Gradient));
         float             arg0   = (float)LuaDLL.luaL_checknumber(L, 2);
         UnityEngine.Color o      = obj.Evaluate(arg0);
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Example #17
0
		// Use this for initialization
		void Start () 
		{
			padGradient = PanelWaveform.GetColorGradient (lineAttributes.startColor, lineAttributes.endColor);

			for(int i = 0; i < numLines; i++)
			{
				float val = (float)i/(numLines-1);
				lines.Add(NewLine(padGradient.Evaluate(val)));
			}
			CreatePad ();

			//just in case someone changes the private var. rippleLines can't be > numLines
			if( rippleWidth > numLines)
			{
				rippleWidth = numLines;
			}
		}
Example #18
0
        /// <summary>
        /// Gives a list of colors where that maximises distance on 
        /// the gradient between consecutaive colors.
        /// </summary>
        /// <param name="colorCount"></param>
        /// <param name="gradient"></param>
        /// <returns></returns>
        public static List<Color> GenerateColorsGoldenRatioGradient(int colorCount, Gradient gradient)
        {
            var colors = new List<Color>();
            var t = Random.value;

            for (int i = 0; i < colorCount; i++)
            {
                var newColor = gradient.Evaluate(t);

                colors.Add(newColor);

                t += GoldenRatioConjugate;
                t %= 1.0f;

            }

            return colors;
        }
Example #19
0
        private void Generate()
        {
            gradient = RandomE.gradientHSV;

            var noiseOffset = new Vector2(Random.Range(0f, 100f), Random.Range(0f, 100f));
            draft.colors.Clear();
            for (int i = 0; i < draft.vertices.Count; i++)
            {
                var vertex = draft.vertices[i];
                var x = scale*vertex.x/xSegments + noiseOffset.x;
                var y = scale*vertex.z/zSegments + noiseOffset.y;
                var noise = Mathf.PerlinNoise(x, y);
                draft.vertices[i] = new Vector3(vertex.x, noise, vertex.z);
                draft.colors.Add(gradient.Evaluate(noise));
            }

            GetComponent<MeshFilter>().mesh = draft.ToMesh();
        }
Example #20
0
    public static Color Grad(float x)
    {
        /*
        // Terrain gradient color keys
        List<GradientColorKey> terrainColorKeys = new List<GradientColorKey>
        {
            new GradientColorKey(new Color(0, 0, 0.5f), 0),
            new GradientColorKey(new Color(0.125f, 0.25f, 0.5f), 0.4f),
            new GradientColorKey(new Color(0.25f, 0.375f, 0.75f), 0.48f),
            new GradientColorKey(new Color(0, 0.75f, 0), 0.5f),
            new GradientColorKey(new Color(0.75f, 0.75f, 0), 0.625f),
            new GradientColorKey(new Color(0.625f, 0.375f, 0.25f), 0.75f),
            new GradientColorKey(new Color(0.5f, 1, 1), 0.875f),
            new GradientColorKey(Color.white, 1)
        };

        // Generic gradient alpha keys
        var alphaKeys = new List<GradientAlphaKey> {new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1)};
        */

        Gradient g = new Gradient();
        GradientColorKey[] gck;
        GradientAlphaKey[] gak;

        // Populate the color keys at the relative time 0 and 1 (0 and 100%)
        gck = new GradientColorKey[2];
        gck[0].color = Color.red;
        gck[0].time = 0.0f;
        gck[1].color = Color.blue;
        gck[1].time = 1.0f;

        // Populate the alpha  keys at relative time 0 and 1  (0 and 100%)
        gak = new GradientAlphaKey[2];
        gak[0].alpha = 1.0f;
        gak[0].time = 0.0f;
        gak[1].alpha = 0.0f;
        gak[1].time = 1.0f;

        //g.SetKeys(terrainColorKeys.ToArray(), alphaKeys.ToArray());
        g.SetKeys(gck,gak);

        return g.Evaluate(x);;
    }
Example #21
0
    public static Texture CreateTexture(UnityEngine.Gradient gradient, int width, int height, bool invert)
    {
        if (gradient == null)
        {
            return(Texture2D.whiteTexture);
        }
        var gradTex = new Texture2D(1, height, TextureFormat.ARGB32, false);

        gradTex.hideFlags = HideFlags.DontSave;
        for (int y = 0; y < height; y++)
        {
            float t   = Mathf.Clamp01((float)(y / (float)height));
            Color col = gradient.Evaluate(t);
            gradTex.SetPixel(0, invert ? height - y : y, col);
        }
        gradTex.Apply();
        gradTex.filterMode = FilterMode.Bilinear;
        return(gradTex);
    }
Example #22
0
 public static Color[] GetPixelsFromGradient(Gradient gradient, int width, int height, Color[] pixels)
 {
     for (var x = 0; x < width; x++)
     {
         var delta = x / (float)width;
         if (delta < 0)
         {
             delta = 0;
         }
         if (delta > 1)
         {
             delta = 1;
         }
         var col = gradient.Evaluate(delta);
         for (int i = 0; i < height; i++)
         {
             pixels[x + i * width] = col;
         }
     }
     return(pixels);
 }
Example #23
0
    private void OnFrame(Frame frame)
    {
        if (frame.Profile.Stream == Intel.RealSense.Stream.Depth)
        {
            var depthFrame = frame as DepthFrame;
            if (depthFrame == null)
            {
                Debug.Log("Frame is not a depth frame");
                return;
            }

            UpdateParticleParams(depthFrame.Width, depthFrame.Height, depthFrame.Profile.Format);

            var points = pc.Calculate(frame);

            Points.Vertex[] vertices = new Points.Vertex[points.Count];
            points.CopyTo(vertices);
            for (int index = 0; index < vertices.Length; index += skipParticles)
            {
                var v = vertices[index];
                if (v.z > 0)
                {
                    particles[index].position   = new Vector3(v.x, v.y, v.z);
                    particles[index].startSize  = pointsSize;
                    particles[index].startColor = gradient.Evaluate(v.z);
                }
                else
                {
                    particles[index].position   = new Vector3(0, 0, 0);
                    particles[index].startSize  = (float)0.0;
                    particles[index].startColor = new Color32(0, 0, 0, 0);
                }
            }
        }
        else if (frame.Profile.Stream == Intel.RealSense.Stream.Color)
        {
            //pc.MapTexture(frame);
        }
    }
 /// <summary>
 /// Creates a texture map for the current content of the noise map.
 /// </summary>
 /// <param name="gradient">The gradient to color the texture map with.</param>
 /// <returns>The created texture map.</returns>
 public Texture2D GetTexture(Gradient gradient)
 {
     Texture2D texture = new Texture2D(this.m_width, this.m_height);
     Color[] pixels = new Color[this.m_width * this.m_height];
     for (int x = 0; x < this.m_width; x++)
     {
         for (int y = 0; y < this.m_height; y++)
         {
             float sample = 0.0f;
             if (!float.IsNaN(this.m_borderValue) && (x == 0 || x == this.m_width - m_ucBorder || y == 0 || y == this.m_height - m_ucBorder))
             {
                 sample = this.m_borderValue;
             }
             else
             {
                 sample = this.m_data[x, y];
             }
             pixels[x + y * this.m_width] = gradient.Evaluate((sample + 1) / 2);
         }
     }
     texture.SetPixels(pixels);
     texture.wrapMode = TextureWrapMode.Clamp;
     texture.Apply();
     return texture;
 }
	IEnumerator DrawTransparentCircles() {
		currentOverlay.SetPixels32(blankOverlay.GetPixels32());
		List<Vector2> convertedLocations = new List<Vector2>();

		foreach(AnomalousEvent anomaly in AEM.EventList.Values) {
			foreach(GridLocation gl in anomaly.gridNumToLocations) {
				Debug.Log ("GridLocation");
				if(gl.statusCode > 0) {
					float tempX = currentOverlay.width * ((-180 - gl.spawnLocation.y)/(-180 - 180));
					float tempY = currentOverlay.height * ((-90 - gl.spawnLocation.x)/(-90 - 90));
					convertedLocations.Add (new Vector2(tempX,tempY));
				}
			}
		}

		Gradient g = new Gradient();
		GradientColorKey[] gck = new GradientColorKey[2];
		gck[0].color = Color.red;
		gck[0].time = 0.0f;
		gck[1].color = Color.yellow;
		gck[1].time = 1.0f;
		GradientAlphaKey[] gak = new GradientAlphaKey[2];
		gak[0].alpha = 0.75f;
		gak[0].time = 0.0f;
		gak[1].alpha = 0.0f;
		gak[1].time = 1.0f;
		g.SetKeys(gck,gak);

		foreach(Vector2 loc in convertedLocations) {
			for(int x = (int)Mathf.Clamp(loc.x - tempCircleSize, 0,overlayWidth - 1); x < (int)Mathf.Clamp(loc.x + tempCircleSize, 0,overlayWidth - 1); x++) {
				for(int y = (int)Mathf.Clamp(loc.y - tempCircleSize, 0,overlayHeight -1); y < (int)Mathf.Clamp(loc.y + tempCircleSize, 0,overlayHeight - 1); y++) {
					float dist = Vector2.Distance(loc, new Vector2(x,y));

					if(dist<tempCircleSize) {
						Color temp = currentOverlay.GetPixel(x,y);
						Color blend;
						if (WaterLandMask.GetPixel(x,y) != Color.white){
							blend = Color.clear;
						} else {
							blend = Color.white;
						}

						if(temp != Color.clear) {
							if(temp.a > g.Evaluate(dist/tempCircleSize).a)
								currentOverlay.SetPixel(x,y,(temp * blend));
							else
								currentOverlay.SetPixel(x,y,(g.Evaluate(dist/tempCircleSize) * blend));
						} else {
							currentOverlay.SetPixel(x,y,(g.Evaluate(dist/tempCircleSize) * blend));
						}
					}


				}
				if( x % 10 == 0)
					yield return null;
			}
			currentOverlay.Apply();
			MapOverlay.GetComponent<Renderer>().material.SetTexture("_MainTex", currentOverlay);
		}
		//Debug.Log ("done");

		//currentOverlay = temp;


	}
Example #26
0
 /// <summary>
 /// Creates a texture map for the current content of the noise map.
 /// </summary>
 /// <param name="gradient">The gradient to color the texture map with.</param>
 /// <returns>The created texture map.</returns>
 public Texture2D GetTexture(Gradient gradient)
 {
     var texture = new Texture2D(_width, _height);
     var pixels = new Color[_width * _height];
     for (var x = 0; x < _width; x++)
     {
         for (var y = 0; y < _height; y++)
         {
             float sample;
             if (!float.IsNaN(_borderValue) &&
                 (x == 0 || x == _width - _ucBorder || y == 0 || y == _height - _ucBorder))
             {
                 sample = _borderValue;
             }
             else
             {
                 sample = _data[x, y];
             }
             pixels[x + y * _width] = gradient.Evaluate((sample + 1) / 2);
         }
     }
     texture.SetPixels(pixels);
     texture.wrapMode = TextureWrapMode.Clamp;
     texture.Apply();
     return texture;
 }
        /// <summary>
        /// Generates a texture containing the given graph's noise output.
        /// If this is being called very often, create a permanent render target and material and
        ///     use the other version of this method instead for much better performance.
        /// If an error occurred, outputs to the Unity debug console and returns "null".
        /// </summary>
        /// <param name="gradientRampName">The name of the gradient ramp texture param.</param>
        public static Texture2D GenerateToTexture(Graph g, GraphParamCollection c, int width, int height,
												  Gradient gradientRamp,
												  TextureFormat format = TextureFormat.RGBAFloat)
        {
            //Generate a shader from the graph and have Unity compile it.
            string shaderPath = Path.Combine(Application.dataPath, "gpuNoiseShaderTemp.shader");
            Shader shader = SaveShader(g, shaderPath, "TempGPUNoiseShader", "_MyGradientRamp14123");
            if (shader == null)
            {
                return null;
            }

            //Generate a texture from the gradient.
            Texture2D myRamp = new Texture2D(1024, 1, TextureFormat.RGBA32, false);
            Color[] cols = new Color[myRamp.width];
            for (int i = 0; i < cols.Length; ++i)
                cols[i] = gradientRamp.Evaluate((float)i / (float)(cols.Length - 1));
            myRamp.SetPixels(cols);
            myRamp.Apply(false, true);

            //Render the shader's output into a render texture and copy the data to a Texture2D.
            RenderTexture target = new RenderTexture(width, height, 16, RenderTextureFormat.ARGBFloat);
            target.Create();
            Texture2D resultTex = new Texture2D(width, height, format, false, true);

            //Create the material and set its parameters.
            Material mat = new Material(shader);
            mat.SetTexture("_MyGradientRamp14123", myRamp);
            c.SetParams(mat);

            GraphUtils.GenerateToTexture(target, mat, resultTex);

            //Clean up.
            target.Release();
            if (!AssetDatabase.DeleteAsset(StringUtils.GetRelativePath(shaderPath, "Assets")))
            {
                Debug.LogError("Unable to delete temp file: " + shaderPath);
            }

            return resultTex;
        }
        private static UnityEngine.Gradient Lerp(this UnityEngine.Gradient a, UnityEngine.Gradient b, float t, bool noAlpha, bool noColor)
        {
            keysTimes.Clear();

            if (a == b || a.Equals(b))
            {
                return(b);
            }

            GradientAlphaKey[] alphaKeys1 = a.alphaKeys;
            GradientColorKey[] colorKeys1 = a.colorKeys;
            GradientAlphaKey[] alphaKeys2 = b.alphaKeys;
            GradientColorKey[] colorKeys2 = b.colorKeys;

            if (alphaKeys1.Length == alphaKeys2.Length && colorKeys1.Length == colorKeys2.Length)
            {
                // full compare of all keys, save allocating memory if both gradients are equal
                bool equal = true;
                for (int i = 0; i < alphaKeys1.Length; i++)
                {
                    if (alphaKeys1[i].alpha != alphaKeys2[i].alpha || alphaKeys1[i].time != alphaKeys2[i].time ||
                        colorKeys1[i].color != colorKeys2[i].color || colorKeys1[i].time != colorKeys2[i].time)
                    {
                        equal = false;
                        break;
                    }
                }
                if (equal)
                {
                    return(b);
                }
                Gradient           gradient = new Gradient();
                GradientColorKey[] clrs     = new GradientColorKey[colorKeys1.Length];
                GradientAlphaKey[] alphas   = new GradientAlphaKey[colorKeys1.Length];
                for (int i = 0; i < colorKeys1.Length; i++)
                {
                    clrs[i]   = new GradientColorKey(Color.Lerp(colorKeys1[i].color, colorKeys2[i].color, t), Mathf.Lerp(colorKeys1[i].time, colorKeys2[i].time, t));
                    alphas[i] = new GradientAlphaKey(Mathf.Lerp(alphaKeys1[i].alpha, alphaKeys2[i].alpha, t), Mathf.Lerp(alphaKeys1[i].time, alphaKeys2[i].time, t));
                }
                gradient.colorKeys = clrs;
                gradient.alphaKeys = alphas;
                return(gradient);
            }
            else
            {
                for (int i = 0; i < colorKeys1.Length; i++)
                {
                    float k = colorKeys1[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }

                for (int i = 0; i < colorKeys2.Length; i++)
                {
                    float k = colorKeys2[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }
                for (int i = 0; i < alphaKeys1.Length; i++)
                {
                    float k = alphaKeys1[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }
                for (int i = 0; i < alphaKeys2.Length; i++)
                {
                    float k = alphaKeys2[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }

                GradientColorKey[] clrs   = new GradientColorKey[keysTimes.Count];
                GradientAlphaKey[] alphas = new GradientAlphaKey[keysTimes.Count];

                for (int i = 0; i < keysTimes.Count; i++)
                {
                    float key = keysTimes[i];
                    var   clr = Color.Lerp(a.Evaluate(key), b.Evaluate(key), t);
                    clrs[i]   = new GradientColorKey(clr, key);
                    alphas[i] = new GradientAlphaKey(clr.a, key);
                }

                Gradient gradient = new Gradient();
                gradient.SetKeys(clrs, alphas);
                return(gradient);
            }
        }
        public void OnRenderImage(Material material, RenderTexture source, RenderTexture dest, float cameraRot)
        {
            //NEED TO SET DESTINATION RENDER TARGET TO COMPLETELLY BLACK SO WE CAN SUM ALL THE GLARE/STAR PASSES ON IT
            Graphics.Blit(Texture2D.blackTexture, dest);

            if (m_isDirty ||
                m_currentWidth != source.width ||
                m_currentHeight != source.height)
            {
                m_isDirty       = false;
                m_currentWidth  = source.width;
                m_currentHeight = source.height;
            }
            else
            {
                OnRenderFromCache(source, dest, material, m_intensity, cameraRot);
                return;
            }

            GlareDefData glareDef    = null;
            bool         validCustom = false;

            if (m_currentGlareType == GlareLibType.Custom)
            {
                if (m_customGlareDef != null && m_customGlareDef.Length > 0)
                {
                    glareDef    = m_customGlareDef[m_customGlareDefIdx];
                    validCustom = true;
                }
                else
                {
                    glareDef = m_glareDefArr[0];
                }
            }
            else
            {
                glareDef = m_glareDefArr[m_currentGlareIdx];
            }


            m_amplifyGlareCache.GlareDef = glareDef;

            float srcW = source.width;
            float srcH = source.height;

            StarDefData starDef = (validCustom) ? glareDef.CustomStarData : m_starDefArr[( int )glareDef.StarType];


            m_amplifyGlareCache.StarDef = starDef;
            int currPassCount = (m_glareMaxPassCount < starDef.PassCount) ? m_glareMaxPassCount : starDef.PassCount;

            m_amplifyGlareCache.CurrentPassCount = currPassCount;
            float radOffset = glareDef.StarInclination + starDef.Inclination;

            for (int p = 0; p < m_glareMaxPassCount; p++)
            {
                float ratio = ( float )(p + 1) / ( float )m_glareMaxPassCount;

                for (int s = 0; s < MaxLineSamples; s++)
                {
                    Color chromaticAberrColor = _overallTint * Color.Lerp(m_cromaticAberrationGrad.Evaluate(( float )s / ( float )(MaxLineSamples - 1)), m_whiteReference, ratio);
                    m_amplifyGlareCache.CromaticAberrationMat[p, s] = Color.Lerp(m_whiteReference, chromaticAberrColor, glareDef.ChromaticAberration);
                }
            }
            m_amplifyGlareCache.TotalRT = starDef.StarlinesCount * currPassCount;

            for (int i = 0; i < m_amplifyGlareCache.TotalRT; i++)
            {
                _rtBuffer[i] = AmplifyUtils.GetTempRenderTarget(source.width, source.height);
            }

            int rtIdx = 0;

            for (int d = 0; d < starDef.StarlinesCount; d++)
            {
                StarLineData starLine = starDef.StarLinesArr[d];
                float        angle    = radOffset + starLine.Inclination;
                float        sinAngle = Mathf.Sin(angle);
                float        cosAngle = Mathf.Cos(angle);
                Vector2      vtStepUV = new Vector2();
                vtStepUV.x = cosAngle / srcW * (starLine.SampleLength * m_overallStreakScale);
                vtStepUV.y = sinAngle / srcH * (starLine.SampleLength * m_overallStreakScale);

                float attnPowScale = (m_aTanFoV + 0.1f) * (280.0f) / (srcW + srcH) * 1.2f;

                for (int p = 0; p < currPassCount; p++)
                {
                    for (int i = 0; i < MaxLineSamples; i++)
                    {
                        float lum = Mathf.Pow(starLine.Attenuation, attnPowScale * i);

                        m_amplifyGlareCache.Starlines[d].Passes[p].Weights[i] = m_amplifyGlareCache.CromaticAberrationMat[currPassCount - 1 - p, i] * lum * (p + 1.0f) * 0.5f;

                        // OFFSET OF SAMPLING COORDINATE
                        m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].x = vtStepUV.x * i;
                        m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].y = vtStepUV.y * i;
                        if (Mathf.Abs(m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].x) >= 0.9f ||
                            Mathf.Abs(m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].y) >= 0.9f)
                        {
                            m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].x = 0.0f;
                            m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i].y = 0.0f;
                            m_amplifyGlareCache.Starlines[d].Passes[p].Weights[i]  *= 0.0f;
                        }
                    }

                    // MIRROR STARLINE
                    for (int i = MaxLineSamples; i < MaxTotalSamples; i++)
                    {
                        m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i] = -m_amplifyGlareCache.Starlines[d].Passes[p].Offsets[i - MaxLineSamples];
                        m_amplifyGlareCache.Starlines[d].Passes[p].Weights[i] = m_amplifyGlareCache.Starlines[d].Passes[p].Weights[i - MaxLineSamples];
                    }

                    // APPLY SHADER
                    UpdateMatrixesForPass(material, m_amplifyGlareCache.Starlines[d].Passes[p].Offsets, m_amplifyGlareCache.Starlines[d].Passes[p].Weights, m_intensity, starDef.CameraRotInfluence * cameraRot);

                    //CREATED WEIGHTED TEXTURE
                    if (p == 0)
                    {
                        Graphics.Blit(source, _rtBuffer[rtIdx], material, ( int )BloomPasses.AnamorphicGlare);
                    }
                    else
                    {
                        Graphics.Blit(_rtBuffer[rtIdx - 1], _rtBuffer[rtIdx], material, ( int )BloomPasses.AnamorphicGlare);
                    }

                    rtIdx        += 1;
                    vtStepUV     *= m_perPassDisplacement;
                    attnPowScale *= m_perPassDisplacement;
                }
            }

            //ADD TO MAIN RT
            m_amplifyGlareCache.AverageWeight = Vector4.one / starDef.StarlinesCount;
            for (int i = 0; i < starDef.StarlinesCount; i++)
            {
                material.SetVector(AmplifyUtils.AnamorphicGlareWeightsStr[i], m_amplifyGlareCache.AverageWeight);
                int idx = (i + 1) * currPassCount - 1;
                material.SetTexture(AmplifyUtils.AnamorphicRTS[i], _rtBuffer[idx]);
            }

            int passId = ( int )BloomPasses.WeightedAddPS1 + starDef.StarlinesCount - 1;

            dest.DiscardContents();
            Graphics.Blit(_rtBuffer[0], dest, material, passId);

            //RELEASE RT's
            for (rtIdx = 0; rtIdx < _rtBuffer.Length; rtIdx++)
            {
                AmplifyUtils.ReleaseTempRenderTarget(_rtBuffer[rtIdx]);
                _rtBuffer[rtIdx] = null;
            }
        }
		public void SetStartColor(Gradient minGradient, Gradient maxGradient) {

			if (Application.isPlaying == false) return;

			if (this.startColor.minMaxState == MinMaxState.MinMaxGradient) {

				this.SetColor_REFLECTION(this.particleSystem, "minGradient", minGradient);
				this.SetColor_REFLECTION(this.particleSystem, "maxGradient", maxGradient);
				this.SetColor_PARTICLES(maxGradient.Evaluate(0f));

			}

		}
Example #31
0
 public static void RefreshPreview(Gradient gradient, Texture2D preview)
 {
     Color[] colors = new Color[0x200];
     for (int i = 0; i < 0x100; i++)
     {
         colors[i] = colors[i + 0x100] = gradient.Evaluate(((float) i) / 256f);
     }
     preview.SetPixels(colors);
     preview.Apply();
 }
Example #32
0
		public Porkchop(ManeuverParameters[,] nodes)
		{
			Gradient colours = new Gradient();
			var colourKeys = new GradientColorKey[6];
			colourKeys[0].color = new Color(0.25f, 0.25f, 1.0f);
			colourKeys[0].time = 0.0f;
			colourKeys[1].color = new Color(0.5f, 0.5f, 1.0f);
			colourKeys[1].time = 0.01f;
			colourKeys[2].color = new Color(0.5f, 1.0f, 1.0f);
			colourKeys[2].time = 0.25f;
			colourKeys[3].color = new Color(0.5f, 1.0f, 0.5f);
			colourKeys[3].time = 0.5f;
			colourKeys[4].color = new Color(1.0f, 1.0f, 0.5f);
			colourKeys[4].time = 0.75f;
			colourKeys[5].color = new Color(1.0f, 0.5f, 0.5f);
			colourKeys[5].time = 1.0f;

			var alphaKeys = new GradientAlphaKey[2];
			alphaKeys[0].alpha = 1.0f;
			alphaKeys[0].time = 0.0f;
			alphaKeys[1].alpha = 1.0f;
			alphaKeys[1].time = 1.0f;

			colours.SetKeys(colourKeys, alphaKeys);

			double DVminsqr = double.MaxValue;
			double DVmaxsqr = double.MinValue;
			for (int i = 0; i < nodes.GetLength(0); i++)
			{
				for (int j = 0; j < nodes.GetLength(1); j++)
				{
					if (nodes[i, j] != null)
					{
						double DVsqr = nodes[i, j].dV.sqrMagnitude;
						if (DVsqr < DVminsqr)
						{
							DVminsqr = DVsqr;
						}

						DVmaxsqr = Math.Max(DVmaxsqr, nodes[i, j].dV.sqrMagnitude);
					}
				}
			}

			texture = new Texture2D(nodes.GetLength(0), nodes.GetLength(1), TextureFormat.RGB24, false);
			double logDVminsqr = Math.Log(DVminsqr);
			double logDVmaxsqr = Math.Min(Math.Log(DVmaxsqr), logDVminsqr + 4);


			for (int i = 0; i < nodes.GetLength(0); i++)
			{
				for (int j = 0; j < nodes.GetLength(1); j++)
				{
					if (nodes[i, j] == null)
					{
						texture.SetPixel(i, j, colours.Evaluate(1));
					}
					else
					{
						double lambda = (Math.Log(nodes[i, j].dV.sqrMagnitude) - logDVminsqr) / (logDVmaxsqr - logDVminsqr);
						texture.SetPixel(i, j, colours.Evaluate((float)lambda));
					}
				}
			}

			texture.Apply();

#if DEBUG
			string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
			System.IO.File.WriteAllBytes(dir + "/Porkchop.png", texture.EncodeToPNG());
#endif
		}
Example #33
0
        static UnityEngine.Gradient Lerp(UnityEngine.Gradient a, UnityEngine.Gradient b, float t, bool noAlpha, bool noColor)
        {
            //list of all the unique key times
            var keysTimes = new List <float>();

            if (!noColor)
            {
                for (int i = 0; i < a.colorKeys.Length; i++)
                {
                    float k = a.colorKeys[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }

                for (int i = 0; i < b.colorKeys.Length; i++)
                {
                    float k = b.colorKeys[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }
            }

            if (!noAlpha)
            {
                for (int i = 0; i < a.alphaKeys.Length; i++)
                {
                    float k = a.alphaKeys[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }

                for (int i = 0; i < b.alphaKeys.Length; i++)
                {
                    float k = b.alphaKeys[i].time;
                    if (!keysTimes.Contains(k))
                    {
                        keysTimes.Add(k);
                    }
                }
            }

            GradientColorKey[] clrs   = new GradientColorKey[keysTimes.Count];
            GradientAlphaKey[] alphas = new GradientAlphaKey[keysTimes.Count];

            //Pick colors of both gradients at key times and lerp them
            for (int i = 0; i < keysTimes.Count; i++)
            {
                float key = keysTimes[i];
                var   clr = Color.Lerp(a.Evaluate(key), b.Evaluate(key), t);
                clrs[i]   = new GradientColorKey(clr, key);
                alphas[i] = new GradientAlphaKey(clr.a, key);
            }

            var g = new UnityEngine.Gradient();

            g.SetKeys(clrs, alphas);

            return(g);
        }
Example #34
0
        /// <summary>
        /// Generates a list of colours randomly sampled from a gradient.
        /// </summary>
        /// <param name="colorCount"></param>
        /// <param name="gradient"></param>
        /// <returns></returns>
        public static List<Color> GenerateColorsRandomGradient(int colorCount, Gradient gradient)
        {
            var colors = new List<Color>();

            for (int i = 0; i < colorCount; i++)
            {
                var color = gradient.Evaluate(Random.value);
                colors.Add(color);
            }

            return colors;
        }
		public static void RefreshPreview(Gradient gradient, Texture2D preview)
		{
			Color[] array = new Color[512];
			for (int i = 0; i < 256; i++)
			{
				array[i] = (array[i + 256] = gradient.Evaluate((float)i / 256f));
			}
			preview.SetPixels(array);
			preview.Apply();
		}
		/// <summary>
		/// 	Gets the color from gradient at time.
		/// </summary>
		/// <returns>The color from gradient at time.</returns>
		/// <param name="gradient">Gradient.</param>
		/// <param name="time">Time.</param>
		private Color GetColorFromGradientAtTime(Gradient gradient, float time)
		{
			if (!HydraMathUtils.Approximately(m_GradientLength, 0.0f))
				time /= m_GradientLength;

			return gradient.Evaluate(time, m_GradientWrapMode);
		}
		/// <summary>
		/// 	Gets a random color from the gradient.
		/// </summary>
		/// <returns>The random color from gradient.</returns>
		/// <param name="gradient">Gradient.</param>
		private Color GetRandomColorFromGradient(Gradient gradient)
		{
			return gradient.Evaluate(m_RandomColorGenerator.value);
		}
        /// <summary>
        /// Generates a textire from a gradient.. assumes the arrays values are nomalized between 0-1
        /// </summary>
        /// <returns>a texture 2d the length and width of the heightmap, all pixels will be based on the gradient provided.</returns>
        public static Texture2D generateTextureFromSingleGradient(float[,] heightMap,Gradient colorGradient)
        {
            int width = heightMap.GetLength(0);
            int height = heightMap.GetLength(1);
            Color[] pixels = new Color[height * width];
            bool debug = false;
            for(int y =0; y < height; y++)
            {
                for(int x =0; x < width; x++)
                {
                    pixels[x + y * width] = colorGradient.Evaluate(heightMap[x,y]);
                    if(debug == false)
                    {
                        debug = true;
                            Debug.Log(pixels[x + y * width].a);
                    }

                }
            }
            return buildTextureFromPixels(pixels,width,height);
        }
        public static MeshDraft TerrainDraft(Vector3 terrainSize, float cellSize, float noiseScale, Gradient gradient)
        {
            var noiseOffset = new Vector2(Random.Range(0f, 100f), Random.Range(0f, 100f));

            int xSegments = Mathf.FloorToInt(terrainSize.x/cellSize);
            int zSegments = Mathf.FloorToInt(terrainSize.z/cellSize);

            float xStep = terrainSize.x/xSegments;
            float zStep = terrainSize.z/zSegments;
            int vertexCount = 6*xSegments*zSegments;
            var draft = new MeshDraft
            {
                name = "Terrain",
                vertices = new List<Vector3>(vertexCount),
                triangles = new List<int>(vertexCount),
                normals = new List<Vector3>(vertexCount),
                colors = new List<Color>(vertexCount)
            };

            for (int i = 0; i < vertexCount; i++)
            {
                draft.vertices.Add(Vector3.zero);
                draft.triangles.Add(0);
                draft.normals.Add(Vector3.zero);
                draft.colors.Add(Color.black);
            }

            for (int x = 0; x < xSegments; x++)
            {
                for (int z = 0; z < zSegments; z++)
                {
                    int index0 = 6*(x + z*xSegments);
                    int index1 = index0 + 1;
                    int index2 = index0 + 2;
                    int index3 = index0 + 3;
                    int index4 = index0 + 4;
                    int index5 = index0 + 5;

                    float height00 = GetHeight(x + 0, z + 0, xSegments, zSegments, noiseOffset, noiseScale);
                    float height01 = GetHeight(x + 0, z + 1, xSegments, zSegments, noiseOffset, noiseScale);
                    float height10 = GetHeight(x + 1, z + 0, xSegments, zSegments, noiseOffset, noiseScale);
                    float height11 = GetHeight(x + 1, z + 1, xSegments, zSegments, noiseOffset, noiseScale);

                    var vertex00 = new Vector3((x + 0)*xStep, height00*terrainSize.y, (z + 0)*zStep);
                    var vertex01 = new Vector3((x + 0)*xStep, height01*terrainSize.y, (z + 1)*zStep);
                    var vertex10 = new Vector3((x + 1)*xStep, height10*terrainSize.y, (z + 0)*zStep);
                    var vertex11 = new Vector3((x + 1)*xStep, height11*terrainSize.y, (z + 1)*zStep);

                    draft.vertices[index0] = vertex00;
                    draft.vertices[index1] = vertex01;
                    draft.vertices[index2] = vertex11;
                    draft.vertices[index3] = vertex00;
                    draft.vertices[index4] = vertex11;
                    draft.vertices[index5] = vertex10;

                    draft.colors[index0] = gradient.Evaluate(height00);
                    draft.colors[index1] = gradient.Evaluate(height01);
                    draft.colors[index2] = gradient.Evaluate(height11);
                    draft.colors[index3] = gradient.Evaluate(height00);
                    draft.colors[index4] = gradient.Evaluate(height11);
                    draft.colors[index5] = gradient.Evaluate(height10);

                    Vector3 normal000111 = Vector3.Cross(vertex01 - vertex00, vertex11 - vertex00).normalized;
                    Vector3 normal001011 = Vector3.Cross(vertex11 - vertex00, vertex10 - vertex00).normalized;

                    draft.normals[index0] = normal000111;
                    draft.normals[index1] = normal000111;
                    draft.normals[index2] = normal000111;
                    draft.normals[index3] = normal001011;
                    draft.normals[index4] = normal001011;
                    draft.normals[index5] = normal001011;

                    draft.triangles[index0] = index0;
                    draft.triangles[index1] = index1;
                    draft.triangles[index2] = index2;
                    draft.triangles[index3] = index3;
                    draft.triangles[index4] = index4;
                    draft.triangles[index5] = index5;
                }
            }

            return draft;
        }