UnityEngine.Graphics.Blit(UnityEngine.Texture, UnityEngine.RenderTexture, UnityEngine.Material, int)

Here are the examples of the csharp api UnityEngine.Graphics.Blit(UnityEngine.Texture, UnityEngine.RenderTexture, UnityEngine.Material, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

50 Examples 7

19 View Source File : HistogramMonitor.cs
License : MIT License
Project Creator : liangxiegame

void ComputeHistogram(RenderTexture source)
        {
            if (m_Buffer == null)
            {
                CreateBuffer(256, 1);
            }
            else if (m_Buffer.count != 256)
            {
                m_Buffer.Release();
                CreateBuffer(256, 1);
            }

            if (m_Material == null)
            {
                m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Histogram Render")) { hideFlags = HideFlags.DontSave };
            }

            var channels = Vector4.zero;
            switch (m_MonitorSettings.histogramMode)
            {
                case HistogramMode.Red: channels.x = 1f; break;
                case HistogramMode.Green: channels.y = 1f; break;
                case HistogramMode.Blue: channels.z = 1f; break;
                case HistogramMode.Luminance: channels.w = 1f; break;
                default: channels = new Vector4(1f, 1f, 1f, 0f); break;
            }

            var cs = m_ComputeShader;

            int kernel = cs.FindKernel("KHistogramClear");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.Dispatch(kernel, 1, 1, 1);

            kernel = cs.FindKernel("KHistogramGather");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.SetTexture(kernel, "_Source", source);
            cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
            cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
            cs.SetVector("_Channels", channels);
            cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 16f), Mathf.CeilToInt(source.height / 16f), 1);

            kernel = cs.FindKernel("KHistogramScale");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.Dispatch(kernel, 1, 1, 1);

            if (m_HistogramTexture == null || m_HistogramTexture.width != source.width || m_HistogramTexture.height != source.height)
            {
                GraphicsUtils.Destroy(m_HistogramTexture);
                m_HistogramTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    wrapMode = TextureWrapMode.Clamp,
                    filterMode = FilterMode.Bilinear
                };
            }

            m_Material.SetBuffer("_Histogram", m_Buffer);
            m_Material.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height));
            m_Material.SetColor("_ColorR", new Color(1f, 0f, 0f, 1f));
            m_Material.SetColor("_ColorG", new Color(0f, 1f, 0f, 1f));
            m_Material.SetColor("_ColorB", new Color(0f, 0f, 1f, 1f));
            m_Material.SetColor("_ColorL", new Color(1f, 1f, 1f, 1f));
            m_Material.SetInt("_Channel", (int)m_MonitorSettings.histogramMode);

            int preplaced = 0;
            if (m_MonitorSettings.histogramMode == HistogramMode.RGBMerged)
                preplaced = 1;
            else if (m_MonitorSettings.histogramMode == HistogramMode.RGBSplit)
                preplaced = 2;

            Graphics.Blit(null, m_HistogramTexture, m_Material, preplaced);
        }

19 View Source File : ImageEffectUIBlur.cs
License : MIT License
Project Creator : XINCGer

void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (EnableUIBlur)
            {
                if (null == finalTexture)
                {
                    finalTexture = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0,
                        RenderTextureFormat.Default);
                }
                RenderTexture tempRenderTexture = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, RenderTextureFormat.Default);
                Graphics.Blit(source, tempRenderTexture, EffectMaterial, 0);
                Graphics.Blit(tempRenderTexture, finalTexture, EffectMaterial, 1);
                RenderTexture.ReleaseTemporary(tempRenderTexture);
                EnableUIBlur = false;
            }
        }

19 View Source File : GlobalFog.cs
License : Apache License 2.0
Project Creator : activey

[ImageEffectOpaque]
        void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false || (!distanceFog && !heightFog))
            {
                Graphics.Blit(source, destination);
                return;
            }

            Camera cam = GetComponent<Camera>();
            Transform camtr = cam.transform;

            Vector3[] frustumCorners = new Vector3[4];
            cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1), cam.farClipPlane, cam.stereoActiveEye, frustumCorners);
            var bottomLeft = camtr.TransformVector(frustumCorners[0]);
            var topLeft = camtr.TransformVector(frustumCorners[1]);
            var topRight = camtr.TransformVector(frustumCorners[2]);
            var bottomRight = camtr.TransformVector(frustumCorners[3]);

            Matrix4x4 frustumCornersArray = Matrix4x4.idenreplacedy;
            frustumCornersArray.SetRow(0, bottomLeft);
            frustumCornersArray.SetRow(1, bottomRight);
            frustumCornersArray.SetRow(2, topLeft);
            frustumCornersArray.SetRow(3, topRight);

            var camPos = camtr.position;
            float FdotC = camPos.y - height;
            float paramK = (FdotC <= 0.0f ? 1.0f : 0.0f);
            float excludeDepth = (excludeFarPixels ? 1.0f : 2.0f);
            fogMaterial.SetMatrix("_FrustumCornersWS", frustumCornersArray);
            fogMaterial.SetVector("_CameraWS", camPos);
            fogMaterial.SetVector("_HeightParams", new Vector4(height, FdotC, paramK, heightDensity * 0.5f));
            fogMaterial.SetVector("_DistanceParams", new Vector4(-Mathf.Max(startDistance, 0.0f), excludeDepth, 0, 0));

            var sceneMode = RenderSettings.fogMode;
            var sceneDensity = RenderSettings.fogDensity;
            var sceneStart = RenderSettings.fogStartDistance;
            var sceneEnd = RenderSettings.fogEndDistance;
            Vector4 sceneParams;
            bool linear = (sceneMode == FogMode.Linear);
            float diff = linear ? sceneEnd - sceneStart : 0.0f;
            float invDiff = Mathf.Abs(diff) > 0.0001f ? 1.0f / diff : 0.0f;
            sceneParams.x = sceneDensity * 1.2011224087f; // density / sqrt(ln(2)), used by Exp2 fog mode
            sceneParams.y = sceneDensity * 1.4426950408f; // density / ln(2), used by Exp fog mode
            sceneParams.z = linear ? -invDiff : 0.0f;
            sceneParams.w = linear ? sceneEnd * invDiff : 0.0f;
            fogMaterial.SetVector("_SceneFogParams", sceneParams);
            fogMaterial.SetVector("_SceneFogMode", new Vector4((int)sceneMode, useRadialDistance ? 1 : 0, 0, 0));

            int preplaced = 0;
            if (distanceFog && heightFog)
                preplaced = 0; // distance + height
            else if (distanceFog)
                preplaced = 1; // distance only
            else
                preplaced = 2; // height only
            Graphics.Blit(source, destination, fogMaterial, preplaced);
        }

19 View Source File : TiltShift.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources() == false) {
                Graphics.Blit (source, destination);
                return;
            }

            tiltShiftMaterial.SetFloat("_BlurSize", maxBlurSize < 0.0f ? 0.0f : maxBlurSize);
            tiltShiftMaterial.SetFloat("_BlurArea", blurArea);
            source.filterMode = FilterMode.Bilinear;

            RenderTexture rt = destination;
            if (downsample > 0f) {
                rt = RenderTexture.GetTemporary (source.width>>downsample, source.height>>downsample, 0, source.format);
                rt.filterMode = FilterMode.Bilinear;
            }

            int basePreplacedNr = (int) quality; basePreplacedNr *= 2;
            Graphics.Blit (source, rt, tiltShiftMaterial, mode == TiltShiftMode.TiltShiftMode ? basePreplacedNr : basePreplacedNr + 1);

            if (downsample > 0) {
                tiltShiftMaterial.SetTexture ("_Blurred", rt);
                Graphics.Blit (source, destination, tiltShiftMaterial, 6);
            }

            if (rt != destination)
                RenderTexture.ReleaseTemporary (rt);
        }

19 View Source File : NoiseAndGrain.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination)
		{
            if (CheckResources()==false || (null==noiseTexture))
			{
                Graphics.Blit (source, destination);
                if (null==noiseTexture) {
                    Debug.LogWarning("Noise & Grain effect failing as noise texture is not replacedigned. please replacedign.", transform);
                }
                return;
            }

            softness = Mathf.Clamp(softness, 0.0f, 0.99f);

            if (dx11Grain && supportDX11)
			{
                // We have a fancy, procedural noise pattern in this version, so no texture needed

                dx11NoiseMaterial.SetFloat("_DX11NoiseTime", Time.frameCount);
                dx11NoiseMaterial.SetTexture ("_NoiseTex", noiseTexture);
                dx11NoiseMaterial.SetVector ("_NoisePerChannel", monochrome ? Vector3.one : intensities);
                dx11NoiseMaterial.SetVector ("_MidGrey", new Vector3(midGrey, 1.0f/(1.0f-midGrey), -1.0f/midGrey));
                dx11NoiseMaterial.SetVector ("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier);

                if (softness > Mathf.Epsilon)
                {
                    RenderTexture rt = RenderTexture.GetTemporary((int) (source.width * (1.0f-softness)), (int) (source.height * (1.0f-softness)));
                    DrawNoiseQuadGrid (source, rt, dx11NoiseMaterial, noiseTexture, monochrome ? 3 : 2);
                    dx11NoiseMaterial.SetTexture("_NoiseTex", rt);
                    Graphics.Blit(source, destination, dx11NoiseMaterial, 4);
                    RenderTexture.ReleaseTemporary(rt);
                }
                else
                    DrawNoiseQuadGrid (source, destination, dx11NoiseMaterial, noiseTexture, (monochrome ? 1 : 0));
            }
            else
			{
                // normal noise (DX9 style)

                if (noiseTexture) {
                    noiseTexture.wrapMode = TextureWrapMode.Repeat;
                    noiseTexture.filterMode = filterMode;
                }

                noiseMaterial.SetTexture ("_NoiseTex", noiseTexture);
                noiseMaterial.SetVector ("_NoisePerChannel", monochrome ? Vector3.one : intensities);
                noiseMaterial.SetVector ("_NoiseTilingPerChannel", monochrome ? Vector3.one * monochromeTiling : tiling);
                noiseMaterial.SetVector ("_MidGrey", new Vector3(midGrey, 1.0f/(1.0f-midGrey), -1.0f/midGrey));
                noiseMaterial.SetVector ("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier);

                if (softness > Mathf.Epsilon)
                {
                    RenderTexture rt2 = RenderTexture.GetTemporary((int) (source.width * (1.0f-softness)), (int) (source.height * (1.0f-softness)));
                    DrawNoiseQuadGrid (source, rt2, noiseMaterial, noiseTexture, 2);
                    noiseMaterial.SetTexture("_NoiseTex", rt2);
                    Graphics.Blit(source, destination, noiseMaterial, 1);
                    RenderTexture.ReleaseTemporary(rt2);
                }
                else
                    DrawNoiseQuadGrid (source, destination, noiseMaterial, noiseTexture, 0);
            }
        }

19 View Source File : DepthOfField.cs
License : Apache License 2.0
Project Creator : activey

private void WriteCoc ( RenderTexture fromTo, bool fgDilate) {
            dofHdrMaterial.SetTexture("_FgOverlap", null);

            if (nearBlur && fgDilate) {

                int rtW = fromTo.width/2;
                int rtH = fromTo.height/2;

                // capture fg coc
                RenderTexture temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
                Graphics.Blit (fromTo, temp2, dofHdrMaterial, 4);

                // special blur
                float fgAdjustment = internalBlurWidth * foregroundOverlap;

                dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgAdjustment , 0.0f, fgAdjustment));
                RenderTexture temp1 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
                Graphics.Blit (temp2, temp1, dofHdrMaterial, 2);
                RenderTexture.ReleaseTemporary(temp2);

                dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgAdjustment, 0.0f, 0.0f, fgAdjustment));
                temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format);
                Graphics.Blit (temp1, temp2, dofHdrMaterial, 2);
                RenderTexture.ReleaseTemporary(temp1);

                // "merge up" with background COC
                dofHdrMaterial.SetTexture("_FgOverlap", temp2);
                fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
                Graphics.Blit (fromTo, fromTo, dofHdrMaterial,  13);
                RenderTexture.ReleaseTemporary(temp2);
            }
            else {
                // capture full coc in alpha channel (fromTo is not read, but bound to detect screen flip)
				fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected
                Graphics.Blit (fromTo, fromTo, dofHdrMaterial,  0);
            }
        }

19 View Source File : BloomOptimized.cs
License : GNU General Public License v3.0
Project Creator : MinhDin

void OnRenderImage (RenderTexture source, RenderTexture destination)
		{
            //if (!IsActive)
			//{
            //    Graphics.Blit (source, destination, Mat, 6);
            //    return;
            //}

            //Graphics.SetRenderTarget(source.colorBuffer, source.depthBuffer);

            int divider = 5;//resolution == Resolution.Low ? 4 : 4;
            float widthMod = resolution == Resolution.Low ? 0.5f : 1.0f;
            _parameter = new Vector4 (blurSize * widthMod, 0.0f, threshold, intensity);
            Mat.SetVector ("_Parameter", _parameter);
            source.filterMode = FilterMode.Bilinear;

            var rtW= source.width/divider;
            var rtH= source.height/divider;

            // downsample
            RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
            rt.filterMode = FilterMode.Bilinear;

            Graphics.Blit(source, rt, Mat, 1);
            //Graphics.Blit(rt, destination);
            //return;
            var preplacedOffs= blurType == BlurType.Standard ? 0 : 2;

            for(int i = 0; i < blurIterations; i++)
			{
                Mat.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + (i*1.0f), 0.0f, threshold, intensity));

                // vertical blur
                RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, Mat, 2 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;

                // horizontal blur
                rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, Mat, 3 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;
            }

            Mat.SetTexture ("_Bloom", rt);

            Graphics.Blit (source, destination, Mat, 0);

            RenderTexture.ReleaseTemporary (rt);
        }

19 View Source File : CameraMotionBlur.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (false == CheckResources ()) {
                Graphics.Blit (source, destination);
                return;
            }

            if (filterType == MotionBlurFilter.CameraMotion)
                StartFrame ();

            // use if possible new RG format ... fallback to half otherwise
            var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;

            // get temp textures
            RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat);
            int tileWidth = 1;
            int tileHeight = 1;
            maxVelocity = Mathf.Max (2.0f, maxVelocity);

            float _maxVelocity = maxVelocity; // calculate 'k'
            // note: 's' is hardcoded in shaders except for DX11 path

            // auto DX11 fallback!
            bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null;

            if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) {
                maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS);
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }
            else {
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }

            RenderTexture tileMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            RenderTexture neighbourMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            velBuffer.filterMode = FilterMode.Point;
            tileMax.filterMode = FilterMode.Point;
            neighbourMax.filterMode = FilterMode.Point;
            if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
            source.wrapMode = TextureWrapMode.Clamp;
            velBuffer.wrapMode = TextureWrapMode.Clamp;
            neighbourMax.wrapMode = TextureWrapMode.Clamp;
            tileMax.wrapMode = TextureWrapMode.Clamp;

            // calc correct viewprj matrix
            CalculateViewProjection ();

            // just started up?
            if (gameObject.activeInHierarchy && !wasActive) {
                Remember ();
            }
            wasActive = gameObject.activeInHierarchy;

            // matrices
            Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat);
            motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj);
            motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
            motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
			if(_camera.stereoEnabled)
			{
				Matrix4x4[] invStereoViewPrj = new Matrix4x4[2];
				invStereoViewPrj[0] = Matrix4x4.Inverse(currentStereoViewProjMat[0]);
				invStereoViewPrj[1] = Matrix4x4.Inverse(currentStereoViewProjMat[1]);

				Matrix4x4 combined = prevStereoViewProjMat[0] * invStereoViewPrj[0];
				motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined0", combined);
				motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined1", prevStereoViewProjMat[1] * invStereoViewPrj[1]);
			}

            motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
            motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
            motionBlurMaterial.SetFloat ("_Jitter", jitter);

            // texture samplers
            motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
            motionBlurMaterial.SetTexture ("_VelTex", velBuffer);
            motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
            motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax);

            if (preview) {
                // generate an artificial 'previous' matrix to simulate blur look
                Matrix4x4 viewMat = _camera.worldToCameraMatrix;
                Matrix4x4 offset = Matrix4x4.idenreplacedy;
                offset.SetTRS(previewScale * 0.3333f, Quaternion.idenreplacedy, Vector3.one); // using only translation
                Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
                prevViewProjMat = projMat * offset * viewMat;
                motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
                motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
            }

            if (filterType == MotionBlurFilter.CameraMotion)
            {
                // build blur vector to be used in shader to create a global blur direction
                Vector4 blurVector = Vector4.zero;

                float lookUpDown = Vector3.Dot (transform.up, Vector3.up);
                Vector3 distanceVector = prevFramePos-transform.position;

                float distMag = distanceVector.magnitude;

                float farHeur = 1.0f;

                // pitch (vertical)
                farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.x =  rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp)));

                // yaw #1 (horizontal, faded by pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                // yaw #2 (when looking down, faded by 1-pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) {
                    // forward (probably most important)
                    blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f);
                    // jump (maybe scale down further)
                    blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f);
                    // strafe (maybe scale down further)
                    blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f);
                }

                if (preview) // crude approximation
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView);
                else
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector);
            }
            else {
                // generate velocity buffer
                Graphics.Blit (source, velBuffer, motionBlurMaterial, 0);

                // patch up velocity buffer:

                // exclude certain layers (e.g. skinned objects as we cant really support that atm)

                Camera cam = null;
                if (excludeLayers.value != 0)// || dynamicLayers.value)
                    cam = GetTmpCam ();

                if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) {
                    cam.targetTexture = velBuffer;
                    cam.cullingMask = excludeLayers;
                    cam.RenderWithShader (replacementClear, "");
                }
            }

            if (!preview && Time.frameCount != prevFrameCount) {
                // remember current transformation data for next frame
                prevFrameCount = Time.frameCount;
                Remember ();
            }

            source.filterMode = FilterMode.Bilinear;

            // debug vel buffer:
            if (showVelocity) {
                // generate tile max and neighbour max
                //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
                motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale);
                Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1);
            }
            else {
                if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) {
                    // need to reset some parameters for dx11 shader
                    dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
                    dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
                    dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter);

                    // texture samplers
                    dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
                    dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer);
                    dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);

                    dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
                    dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0);
                    Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1);

                    // final blur
                    Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2);
                }
                else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) {
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    // final blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 4);
                }
                else if (filterType == MotionBlurFilter.CameraMotion) {
                    // orange box style motion blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 6);
                }
                else if (filterType == MotionBlurFilter.ReconstructionDisc) {
                    // dof style motion blur defocuing and ellipse around the princical blur direction
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    Graphics.Blit (source, destination, motionBlurMaterial, 7);
                }
                else {
                    // simple & fast blur (low quality): just blurring along velocity
                    Graphics.Blit (source, destination, motionBlurMaterial, 5);
                }
            }

            // cleanup
            RenderTexture.ReleaseTemporary (velBuffer);
            RenderTexture.ReleaseTemporary (tileMax);
            RenderTexture.ReleaseTemporary (neighbourMax);
        }

19 View Source File : SunShafts.cs
License : MIT License
Project Creator : XINCGer

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources()==false) {
                Graphics.Blit (source, destination);
                return;
            }

            // we actually need to check this every frame
            if (useDepthTexture)
                GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;

            int divider = 4;
            if (resolution == SunShaftsResolution.Normal)
                divider = 2;
            else if (resolution == SunShaftsResolution.High)
                divider = 1;

            Vector3 v = Vector3.one * 0.5f;
            if (sunTransform)
                v = GetComponent<Camera>().WorldToViewportPoint (sunTransform.position);
            else
                v = new Vector3(0.5f, 0.5f, 0.0f);

            int rtW = source.width / divider;
            int rtH = source.height / divider;

            RenderTexture lrColorB;
            RenderTexture lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);

            // mask out everything except the skybox
            // we have 2 methods, one of which requires depth buffer support, the other one is just comparing images

            sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius );
            sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));
            sunShaftsMaterial.SetVector ("_SunThreshold", sunThreshold);

            if (!useDepthTexture) {
#if UNITY_5_6_OR_NEWER
                var format = GetComponent<Camera>().allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
#else
                var format = GetComponent<Camera>().hdr ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
#endif
                RenderTexture tmpBuffer = RenderTexture.GetTemporary (source.width, source.height, 0, format);
                RenderTexture.active = tmpBuffer;
                GL.ClearWithSkybox (false, GetComponent<Camera>());

                sunShaftsMaterial.SetTexture ("_Skybox", tmpBuffer);
                Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 3);
                RenderTexture.ReleaseTemporary (tmpBuffer);
            }
            else {
                Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 2);
            }

            // paint a small black small border to get rid of clamping problems
            DrawBorder (lrDepthBuffer, simpleClearMaterial);

            // radial blur:

            radialBlurIterations = Mathf.Clamp (radialBlurIterations, 1, 4);

            float ofs = sunShaftBlurRadius * (1.0f / 768.0f);

            sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f));
            sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));

            for (int it2 = 0; it2 < radialBlurIterations; it2++ ) {
                // each iteration takes 2 * 6 samples
                // we update _BlurRadius each time to cheaply get a very smooth look

                lrColorB = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (lrDepthBuffer, lrColorB, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary (lrDepthBuffer);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );

                lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (lrColorB, lrDepthBuffer, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary (lrColorB);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );
            }

            // put together:

            if (v.z >= 0.0f)
                sunShaftsMaterial.SetVector ("_SunColor", new Vector4 (sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity);
            else
                sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection !
            sunShaftsMaterial.SetTexture ("_ColorBuffer", lrDepthBuffer);
            Graphics.Blit (source, destination, sunShaftsMaterial, (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4);

            RenderTexture.ReleaseTemporary (lrDepthBuffer);
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources()==false) {
                Graphics.Blit (source, destination);
                return;
            }

            if (smoothness < 0.1f)
                smoothness = 0.1f;

            // update needed focal & rt size parameter

            bokeh = bokeh && bokehSupport;
            float bokehBlurAmplifier = bokeh ? BOKEH_EXTRA_BLUR : 1.0f;

            bool  blurForeground = quality > Dof34QualitySetting.OnlyBackground;
            float focal01Size = focalSize / (_camera.farClipPlane - _camera.nearClipPlane);;

            if (simpleTweakMode) {
                focalDistance01 = objectFocus ? (_camera.WorldToViewportPoint (objectFocus.position)).z / (_camera.farClipPlane) : FocalDistance01 (focalPoint);
                focalStartCurve = focalDistance01 * smoothness;
                focalEndCurve = focalStartCurve;
                blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon));
            }
            else {
                if (objectFocus) {
                    var vpPoint= _camera.WorldToViewportPoint (objectFocus.position);
                    vpPoint.z = (vpPoint.z) / (_camera.farClipPlane);
                    focalDistance01 = vpPoint.z;
                }
                else
                    focalDistance01 = FocalDistance01 (focalZDistance);

                focalStartCurve = focalZStartCurve;
                focalEndCurve = focalZEndCurve;
                blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon));
            }

            widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
            oneOverBaseSize = 1.0f / 512.0f;

            dofMaterial.SetFloat ("_ForegroundBlurExtrude", foregroundBlurExtrude);
            dofMaterial.SetVector ("_CurveParams", new Vector4 (simpleTweakMode ? 1.0f / focalStartCurve : focalStartCurve, simpleTweakMode ? 1.0f / focalEndCurve : focalEndCurve, focal01Size * 0.5f, focalDistance01));
            dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height),0.0f,0.0f));

            int divider =  GetDividerBasedOnQuality ();
            int lowTexDivider = GetLowResolutionDividerBasedOnQuality (divider);

            AllocateTextures (blurForeground, source, divider, lowTexDivider);

            // WRITE COC to alpha channel
            // source is only being bound to detect y texcoord flip
            Graphics.Blit (source, source, dofMaterial, 3);

            // better DOWNSAMPLE (could actually be weighted for higher quality)
            Downsample (source, mediumRezWorkTexture);

            // BLUR A LITTLE first, which has two purposes
            // 1.) reduce jitter, noise, aliasing
            // 2.) produce the little-blur buffer used in composition later
            Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread);

            if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
            {
                dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast, bokehThresholdLuminance, 0.95f, 0.0f));

                // add and mark the parts that should end up as bokeh shapes
                Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11);

                // remove those parts (maybe even a little replacedtle bittle more) from the regurlarly blurred buffer
                //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10);
                Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10);

                // maybe you want to reblur the small blur ... but not really needed.
                //Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread);

                // bigger BLUR
                Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread * bokehBlurAmplifier);
            }
            else  {
                // bigger BLUR
                Downsample (mediumRezWorkTexture, lowRezWorkTexture);
                Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread);
            }

            dofBlurMaterial.SetTexture ("_TapLow", lowRezWorkTexture);
            dofBlurMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture);
            Graphics.Blit (null, finalDefocus, dofBlurMaterial, 3);

            // we are only adding bokeh now if the background is the only part we have to deal with
            if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
                AddBokeh (bokehSource2, bokehSource, finalDefocus);

            dofMaterial.SetTexture ("_TapLowBackground", finalDefocus);
            dofMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization

            // FINAL DEFOCUS (background)
            Graphics.Blit (source, blurForeground ? foregroundTexture : destination, dofMaterial, visualize ? 2 : 0);

            // FINAL DEFOCUS (foreground)
            if (blurForeground) {
                // WRITE COC to alpha channel
                Graphics.Blit (foregroundTexture, source, dofMaterial, 5);

                // DOWNSAMPLE (unweighted)
                Downsample (source, mediumRezWorkTexture);

                // BLUR A LITTLE first, which has two purposes
                // 1.) reduce jitter, noise, aliasing
                // 2.) produce the little-blur buffer used in composition later
                BlurFg (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 2, maxBlurSpread);

                if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
                {
                    dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast * 0.5f, bokehThresholdLuminance, 0.0f, 0.0f));

                    // add and mark the parts that should end up as bokeh shapes
                    Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11);

                    // remove the parts (maybe even a little replacedtle bittle more) that will end up in bokeh space
                    //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10);
                    Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10);

                    // big BLUR
                    BlurFg (lowRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread * bokehBlurAmplifier);
                }
                else  {
                    // big BLUR
                    BlurFg (mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread);
                }

                // simple upsample once
                Graphics.Blit (lowRezWorkTexture, finalDefocus);

                dofMaterial.SetTexture ("_TapLowForeground", finalDefocus);
                Graphics.Blit (source, destination, dofMaterial, visualize ? 1 : 4);

                if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
                    AddBokeh (bokehSource2, bokehSource, destination);
            }

            ReleaseTextures ();
        }

19 View Source File : CameraMotionBlur.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (false == CheckResources ()) {
                Graphics.Blit (source, destination);
                return;
            }

            if (filterType == MotionBlurFilter.CameraMotion)
                StartFrame ();

            // use if possible new RG format ... fallback to half otherwise
            var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;

            // get temp textures
            RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat);
            int tileWidth = 1;
            int tileHeight = 1;
            maxVelocity = Mathf.Max (2.0f, maxVelocity);

            float _maxVelocity = maxVelocity; // calculate 'k'
            // note: 's' is hardcoded in shaders except for DX11 path

            // auto DX11 fallback!
            bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null;

            if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) {
                maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS);
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }
            else {
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }

            RenderTexture tileMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            RenderTexture neighbourMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            velBuffer.filterMode = FilterMode.Point;
            tileMax.filterMode = FilterMode.Point;
            neighbourMax.filterMode = FilterMode.Point;
            if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
            source.wrapMode = TextureWrapMode.Clamp;
            velBuffer.wrapMode = TextureWrapMode.Clamp;
            neighbourMax.wrapMode = TextureWrapMode.Clamp;
            tileMax.wrapMode = TextureWrapMode.Clamp;

            // calc correct viewprj matrix
            CalculateViewProjection ();

            // just started up?
            if (gameObject.activeInHierarchy && !wasActive) {
                Remember ();
            }
            wasActive = gameObject.activeInHierarchy;

            // matrices
            Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat);
            motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj);
            motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
            motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);

            motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
            motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
            motionBlurMaterial.SetFloat ("_Jitter", jitter);

            // texture samplers
            motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
            motionBlurMaterial.SetTexture ("_VelTex", velBuffer);
            motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
            motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax);

            if (preview) {
                // generate an artifical 'previous' matrix to simulate blur look
                Matrix4x4 viewMat = _camera.worldToCameraMatrix;
                Matrix4x4 offset = Matrix4x4.idenreplacedy;
                offset.SetTRS(previewScale * 0.3333f, Quaternion.idenreplacedy, Vector3.one); // using only translation
                Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
                prevViewProjMat = projMat * offset * viewMat;
                motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
                motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
            }

            if (filterType == MotionBlurFilter.CameraMotion)
            {
                // build blur vector to be used in shader to create a global blur direction
                Vector4 blurVector = Vector4.zero;

                float lookUpDown = Vector3.Dot (transform.up, Vector3.up);
                Vector3 distanceVector = prevFramePos-transform.position;

                float distMag = distanceVector.magnitude;

                float farHeur = 1.0f;

                // pitch (vertical)
                farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.x =  rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp)));

                // yaw #1 (horizontal, faded by pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                // yaw #2 (when looking down, faded by 1-pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) {
                    // forward (probably most important)
                    blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f);
                    // jump (maybe scale down further)
                    blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f);
                    // strafe (maybe scale down further)
                    blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f);
                }

                if (preview) // crude approximation
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView);
                else
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector);
            }
            else {
                // generate velocity buffer
                Graphics.Blit (source, velBuffer, motionBlurMaterial, 0);

                // patch up velocity buffer:

                // exclude certain layers (e.g. skinned objects as we cant really support that atm)

                Camera cam = null;
                if (excludeLayers.value != 0)// || dynamicLayers.value)
                    cam = GetTmpCam ();

                if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) {
                    cam.targetTexture = velBuffer;
                    cam.cullingMask = excludeLayers;
                    cam.RenderWithShader (replacementClear, "");
                }
            }

            if (!preview && Time.frameCount != prevFrameCount) {
                // remember current transformation data for next frame
                prevFrameCount = Time.frameCount;
                Remember ();
            }

            source.filterMode = FilterMode.Bilinear;

            // debug vel buffer:
            if (showVelocity) {
                // generate tile max and neighbour max
                //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
                motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale);
                Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1);
            }
            else {
                if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) {
                    // need to reset some parameters for dx11 shader
                    dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
                    dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
                    dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter);

                    // texture samplers
                    dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
                    dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer);
                    dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);

                    dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
                    dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0);
                    Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1);

                    // final blur
                    Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2);
                }
                else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) {
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    // final blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 4);
                }
                else if (filterType == MotionBlurFilter.CameraMotion) {
                    // orange box style motion blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 6);
                }
                else if (filterType == MotionBlurFilter.ReconstructionDisc) {
                    // dof style motion blur defocuing and ellipse around the princical blur direction
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    Graphics.Blit (source, destination, motionBlurMaterial, 7);
                }
                else {
                    // simple & fast blur (low quality): just blurring along velocity
                    Graphics.Blit (source, destination, motionBlurMaterial, 5);
                }
            }

            // cleanup
            RenderTexture.ReleaseTemporary (velBuffer);
            RenderTexture.ReleaseTemporary (tileMax);
            RenderTexture.ReleaseTemporary (neighbourMax);
        }

19 View Source File : ScreenSpaceAmbientOcclusion.cs
License : Apache License 2.0
Project Creator : activey

[ImageEffectOpaque]
        void OnRenderImage (RenderTexture source, RenderTexture destination)
        {
            if (!m_Supported || !m_SSAOShader.isSupported) {
                enabled = false;
                return;
            }
            CreateMaterials ();

            m_Downsampling = Mathf.Clamp (m_Downsampling, 1, 6);
            m_Radius = Mathf.Clamp (m_Radius, 0.05f, 1.0f);
            m_MinZ = Mathf.Clamp (m_MinZ, 0.00001f, 0.5f);
            m_OcclusionIntensity = Mathf.Clamp (m_OcclusionIntensity, 0.5f, 4.0f);
            m_OcclusionAttenuation = Mathf.Clamp (m_OcclusionAttenuation, 0.2f, 2.0f);
            m_Blur = Mathf.Clamp (m_Blur, 0, 4);

            // Render SSAO term into a smaller texture
            RenderTexture rtAO = RenderTexture.GetTemporary (source.width / m_Downsampling, source.height / m_Downsampling, 0);
            float fovY = GetComponent<Camera>().fieldOfView;
            float far = GetComponent<Camera>().farClipPlane;
            float y = Mathf.Tan (fovY * Mathf.Deg2Rad * 0.5f) * far;
            float x = y * GetComponent<Camera>().aspect;
            m_SSAOMaterial.SetVector ("_FarCorner", new Vector3(x,y,far));
            int noiseWidth, noiseHeight;
            if (m_RandomTexture) {
                noiseWidth = m_RandomTexture.width;
                noiseHeight = m_RandomTexture.height;
            } else {
                noiseWidth = 1; noiseHeight = 1;
            }
            m_SSAOMaterial.SetVector ("_NoiseScale", new Vector3 ((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f));
            m_SSAOMaterial.SetVector ("_Params", new Vector4(
                                                     m_Radius,
                                                     m_MinZ,
                                                     1.0f / m_OcclusionAttenuation,
                                                     m_OcclusionIntensity));

            bool doBlur = m_Blur > 0;
            Graphics.Blit (doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount);

            if (doBlur)
            {
                // Blur SSAO horizontally
                RenderTexture rtBlurX = RenderTexture.GetTemporary (source.width, source.height, 0);
                m_SSAOMaterial.SetVector ("_TexelOffsetScale",
                                          new Vector4 ((float)m_Blur / source.width, 0,0,0));
                m_SSAOMaterial.SetTexture ("_SSAO", rtAO);
                Graphics.Blit (null, rtBlurX, m_SSAOMaterial, 3);
                RenderTexture.ReleaseTemporary (rtAO); // original rtAO not needed anymore

                // Blur SSAO vertically
                RenderTexture rtBlurY = RenderTexture.GetTemporary (source.width, source.height, 0);
                m_SSAOMaterial.SetVector ("_TexelOffsetScale",
                                          new Vector4 (0, (float)m_Blur/source.height, 0,0));
                m_SSAOMaterial.SetTexture ("_SSAO", rtBlurX);
                Graphics.Blit (source, rtBlurY, m_SSAOMaterial, 3);
                RenderTexture.ReleaseTemporary (rtBlurX); // blurX RT not needed anymore

                rtAO = rtBlurY; // AO is the blurred one now
            }

            // Modulate scene rendering with SSAO
            m_SSAOMaterial.SetTexture ("_SSAO", rtAO);
            Graphics.Blit (source, destination, m_SSAOMaterial, 4);

            RenderTexture.ReleaseTemporary (rtAO);
        }

19 View Source File : SunShafts.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources()==false) {
                Graphics.Blit (source, destination);
                return;
            }

            // we actually need to check this every frame
            if (useDepthTexture)
                GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;

            int divider = 4;
            if (resolution == SunShaftsResolution.Normal)
                divider = 2;
            else if (resolution == SunShaftsResolution.High)
                divider = 1;

            Vector3 v = Vector3.one * 0.5f;
            if (sunTransform)
                v = GetComponent<Camera>().WorldToViewportPoint (sunTransform.position);
            else
                v = new Vector3(0.5f, 0.5f, 0.0f);

            int rtW = source.width / divider;
            int rtH = source.height / divider;

            RenderTexture lrColorB;
            RenderTexture lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);

            // mask out everything except the skybox
            // we have 2 methods, one of which requires depth buffer support, the other one is just comparing images

            sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius );
            sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));
            sunShaftsMaterial.SetVector ("_SunThreshold", sunThreshold);

            if (!useDepthTexture) {
                var format= GetComponent<Camera>().hdr ? RenderTextureFormat.DefaultHDR: RenderTextureFormat.Default;
                RenderTexture tmpBuffer = RenderTexture.GetTemporary (source.width, source.height, 0, format);
                RenderTexture.active = tmpBuffer;
                GL.ClearWithSkybox (false, GetComponent<Camera>());

                sunShaftsMaterial.SetTexture ("_Skybox", tmpBuffer);
                Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 3);
                RenderTexture.ReleaseTemporary (tmpBuffer);
            }
            else {
                Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 2);
            }

            // paint a small black small border to get rid of clamping problems
            DrawBorder (lrDepthBuffer, simpleClearMaterial);

            // radial blur:

            radialBlurIterations = Mathf.Clamp (radialBlurIterations, 1, 4);

            float ofs = sunShaftBlurRadius * (1.0f / 768.0f);

            sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f));
            sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius));

            for (int it2 = 0; it2 < radialBlurIterations; it2++ ) {
                // each iteration takes 2 * 6 samples
                // we update _BlurRadius each time to cheaply get a very smooth look

                lrColorB = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (lrDepthBuffer, lrColorB, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary (lrDepthBuffer);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );

                lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (lrColorB, lrDepthBuffer, sunShaftsMaterial, 1);
                RenderTexture.ReleaseTemporary (lrColorB);
                ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f;
                sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) );
            }

            // put together:

            if (v.z >= 0.0f)
                sunShaftsMaterial.SetVector ("_SunColor", new Vector4 (sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity);
            else
                sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection !
            sunShaftsMaterial.SetTexture ("_ColorBuffer", lrDepthBuffer);
            Graphics.Blit (source, destination, sunShaftsMaterial, (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4);

            RenderTexture.ReleaseTemporary (lrDepthBuffer);
        }

19 View Source File : VectorscopeMonitor.cs
License : MIT License
Project Creator : liangxiegame

public override void OnMonitorGUI(Rect r)
        {
            if (Event.current.type == EventType.Repaint)
            {
                // If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the vectoscope data
                if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0))
                    InternalEditorUtility.RepaintAllViews();

                // Sizing
                float size = 0f;

                if (r.width < r.height)
                {
                    size = m_VectorscopeTexture != null
                        ? Mathf.Min(m_VectorscopeTexture.width, r.width - 35f)
                        : r.width;
                }
                else
                {
                    size = m_VectorscopeTexture != null
                        ? Mathf.Min(m_VectorscopeTexture.height, r.height - 25f)
                        : r.height;
                }

                m_MonitorAreaRect = new Rect(
                        Mathf.Floor(r.x + r.width / 2f - size / 2f),
                        Mathf.Floor(r.y + r.height / 2f - size / 2f - 5f),
                        size, size
                        );

                if (m_VectorscopeTexture != null)
                {
                    m_Material.SetFloat("_Exposure", m_MonitorSettings.vectorscopeExposure);

                    var oldActive = RenderTexture.active;
                    Graphics.Blit(null, m_VectorscopeTexture, m_Material, m_MonitorSettings.vectorscopeShowBackground ? 0 : 1);
                    RenderTexture.active = oldActive;

                    Graphics.DrawTexture(m_MonitorAreaRect, m_VectorscopeTexture);

                    var color = Color.white;
                    const float kTickSize = 10f;
                    const int kTickCount = 24;

                    float radius = m_MonitorAreaRect.width / 2f;
                    float midX = m_MonitorAreaRect.x + radius;
                    float midY = m_MonitorAreaRect.y + radius;
                    var center = new Vector2(midX, midY);

                    // Cross
                    color.a *= 0.5f;
                    Handles.color = color;
                    Handles.DrawLine(new Vector2(midX, m_MonitorAreaRect.y), new Vector2(midX, m_MonitorAreaRect.y + m_MonitorAreaRect.height));
                    Handles.DrawLine(new Vector2(m_MonitorAreaRect.x, midY), new Vector2(m_MonitorAreaRect.x + m_MonitorAreaRect.width, midY));

                    if (m_MonitorAreaRect.width > 100f)
                    {
                        color.a = 1f;

                        // Ticks
                        Handles.color = color;
                        for (int i = 0; i < kTickCount; i++)
                        {
                            float a = (float)i / (float)kTickCount;
                            float theta = a * (Mathf.PI * 2f);
                            float tx = Mathf.Cos(theta + (Mathf.PI / 2f));
                            float ty = Mathf.Sin(theta - (Mathf.PI / 2f));
                            var innerVec = center + new Vector2(tx, ty) * (radius - kTickSize);
                            var outerVec = center + new Vector2(tx, ty) * radius;
                            Handles.DrawAAPolyLine(3f, innerVec, outerVec);
                        }

                        // Labels (where saturation reaches 75%)
                        color.a = 1f;
                        var oldColor = GUI.color;
                        GUI.color = color * 2f;

                        var point = new Vector2(-0.254f, -0.750f) * radius + center;
                        var rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[R]", FxStyles.tickStyleCenter);

                        point = new Vector2(-0.497f, 0.629f) * radius + center;
                        rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[G]", FxStyles.tickStyleCenter);

                        point = new Vector2(0.750f, 0.122f) * radius + center;
                        rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[B]", FxStyles.tickStyleCenter);

                        point = new Vector2(-0.750f, -0.122f) * radius + center;
                        rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[Y]", FxStyles.tickStyleCenter);

                        point = new Vector2(0.254f, 0.750f) * radius + center;
                        rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[C]", FxStyles.tickStyleCenter);

                        point = new Vector2(0.497f, -0.629f) * radius + center;
                        rect = new Rect(point.x - 10f, point.y - 10f, 20f, 20f);
                        GUI.Label(rect, "[M]", FxStyles.tickStyleCenter);
                        GUI.color = oldColor;
                    }
                }
            }
        }

19 View Source File : BloomOptimized.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination)
		{
            if (CheckResources() == false)
			{
                Graphics.Blit (source, destination);
                return;
            }

            int divider = resolution == Resolution.Low ? 4 : 2;
            float widthMod = resolution == Resolution.Low ? 0.5f : 1.0f;

            fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod, 0.0f, threshold, intensity));
            source.filterMode = FilterMode.Bilinear;

            var rtW= source.width/divider;
            var rtH= source.height/divider;

            // downsample
            RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
            rt.filterMode = FilterMode.Bilinear;
            Graphics.Blit (source, rt, fastBloomMaterial, 1);

            var preplacedOffs= blurType == BlurType.Standard ? 0 : 2;

            for(int i = 0; i < blurIterations; i++)
			{
                fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + (i*1.0f), 0.0f, threshold, intensity));

                // vertical blur
                RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, fastBloomMaterial, 2 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;

                // horizontal blur
                rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, fastBloomMaterial, 3 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;
            }

            fastBloomMaterial.SetTexture ("_Bloom", rt);

            Graphics.Blit (source, destination, fastBloomMaterial, 0);

            RenderTexture.ReleaseTemporary (rt);
        }

19 View Source File : WaveformMonitor.cs
License : MIT License
Project Creator : liangxiegame

public override void OnMonitorGUI(Rect r)
        {
            if (Event.current.type == EventType.Repaint)
            {
                // If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the waveform data
                if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0))
                    InternalEditorUtility.RepaintAllViews();

                // Sizing
                float width = m_WaveformTexture != null
                    ? Mathf.Min(m_WaveformTexture.width, r.width - 65f)
                    : r.width;
                float height = m_WaveformTexture != null
                    ? Mathf.Min(m_WaveformTexture.height, r.height - 45f)
                    : r.height;

                m_MonitorAreaRect = new Rect(
                        Mathf.Floor(r.x + r.width / 2f - width / 2f),
                        Mathf.Floor(r.y + r.height / 2f - height / 2f - 5f),
                        width, height
                        );

                if (m_WaveformTexture != null)
                {
                    m_Material.SetFloat("_Exposure", m_MonitorSettings.waveformExposure);

                    var oldActive = RenderTexture.active;
                    Graphics.Blit(null, m_WaveformTexture, m_Material, 0);
                    RenderTexture.active = oldActive;

                    Graphics.DrawTexture(m_MonitorAreaRect, m_WaveformTexture);

                    var color = Color.white;
                    const float kTickSize = 5f;

                    // Rect, lines & ticks points
                    //  A B C D E
                    //  P       F
                    //  O       G
                    //  N       H
                    //  M L K J I

                    var A = new Vector3(m_MonitorAreaRect.x, m_MonitorAreaRect.y);
                    var E = new Vector3(A.x + m_MonitorAreaRect.width + 1f, m_MonitorAreaRect.y);
                    var I = new Vector3(E.x, E.y + m_MonitorAreaRect.height + 1f);
                    var M = new Vector3(A.x, I.y);

                    var C = new Vector3(A.x + (E.x - A.x) / 2f, A.y);
                    var G = new Vector3(E.x, E.y + (I.y - E.y) / 2f);
                    var K = new Vector3(M.x + (I.x - M.x) / 2f, M.y);
                    var O = new Vector3(A.x, A.y + (M.y - A.y) / 2f);

                    var P = new Vector3(A.x, A.y + (O.y - A.y) / 2f);
                    var F = new Vector3(E.x, E.y + (G.y - E.y) / 2f);
                    var N = new Vector3(A.x, O.y + (M.y - O.y) / 2f);
                    var H = new Vector3(E.x, G.y + (I.y - G.y) / 2f);

                    var B = new Vector3(A.x + (C.x - A.x) / 2f, A.y);
                    var L = new Vector3(M.x + (K.x - M.x) / 2f, M.y);
                    var D = new Vector3(C.x + (E.x - C.x) / 2f, A.y);
                    var J = new Vector3(K.x + (I.x - K.x) / 2f, M.y);

                    // Borders
                    Handles.color = color;
                    Handles.DrawLine(A, E);
                    Handles.DrawLine(E, I);
                    Handles.DrawLine(I, M);
                    Handles.DrawLine(M, new Vector3(A.x, A.y - 1f));

                    // Vertical ticks
                    Handles.DrawLine(A, new Vector3(A.x - kTickSize, A.y));
                    Handles.DrawLine(P, new Vector3(P.x - kTickSize, P.y));
                    Handles.DrawLine(O, new Vector3(O.x - kTickSize, O.y));
                    Handles.DrawLine(N, new Vector3(N.x - kTickSize, N.y));
                    Handles.DrawLine(M, new Vector3(M.x - kTickSize, M.y));

                    Handles.DrawLine(E, new Vector3(E.x + kTickSize, E.y));
                    Handles.DrawLine(F, new Vector3(F.x + kTickSize, F.y));
                    Handles.DrawLine(G, new Vector3(G.x + kTickSize, G.y));
                    Handles.DrawLine(H, new Vector3(H.x + kTickSize, H.y));
                    Handles.DrawLine(I, new Vector3(I.x + kTickSize, I.y));

                    // Horizontal ticks
                    Handles.DrawLine(A, new Vector3(A.x, A.y - kTickSize));
                    Handles.DrawLine(B, new Vector3(B.x, B.y - kTickSize));
                    Handles.DrawLine(C, new Vector3(C.x, C.y - kTickSize));
                    Handles.DrawLine(D, new Vector3(D.x, D.y - kTickSize));
                    Handles.DrawLine(E, new Vector3(E.x, E.y - kTickSize));

                    Handles.DrawLine(M, new Vector3(M.x, M.y + kTickSize));
                    Handles.DrawLine(L, new Vector3(L.x, L.y + kTickSize));
                    Handles.DrawLine(K, new Vector3(K.x, K.y + kTickSize));
                    Handles.DrawLine(J, new Vector3(J.x, J.y + kTickSize));
                    Handles.DrawLine(I, new Vector3(I.x, I.y + kTickSize));

                    // Labels
                    GUI.color = color;
                    GUI.Label(new Rect(A.x - kTickSize - 34f, A.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleRight);
                    GUI.Label(new Rect(O.x - kTickSize - 34f, O.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleRight);
                    GUI.Label(new Rect(M.x - kTickSize - 34f, M.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleRight);

                    GUI.Label(new Rect(E.x + kTickSize + 4f, E.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleLeft);
                    GUI.Label(new Rect(G.x + kTickSize + 4f, G.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleLeft);
                    GUI.Label(new Rect(I.x + kTickSize + 4f, I.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleLeft);

                    GUI.Label(new Rect(M.x - 15f, M.y + kTickSize - 4f, 30f, 30f), "0.0", FxStyles.tickStyleCenter);
                    GUI.Label(new Rect(K.x - 15f, K.y + kTickSize - 4f, 30f, 30f), "0.5", FxStyles.tickStyleCenter);
                    GUI.Label(new Rect(I.x - 15f, I.y + kTickSize - 4f, 30f, 30f), "1.0", FxStyles.tickStyleCenter);
                }
            }
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void BlurFg ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPreplaced, float spread) {
            // we want a nice, big coc, hence we need to tap once from this (higher resolution) texture
            dofBlurMaterial.SetTexture ("_TapHigh", from);

            RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height);
            if ((int)iterations > 1) {
                BlurHex (from, to, blurPreplaced, spread, tmp);
                if ((int)iterations > 2) {
                    dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f));
                    Graphics.Blit (to, tmp, dofBlurMaterial, blurPreplaced);
                    dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  0.0f, 0.0f, 0.0f));
                    Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
                }
            }
            else {
                dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f));
                Graphics.Blit (from, tmp, dofBlurMaterial, blurPreplaced);
                dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  0.0f, 0.0f, 0.0f));
                Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
            }
            RenderTexture.ReleaseTemporary (tmp);
        }

19 View Source File : Lutify.cs
License : MIT License
Project Creator : XINCGer

void RenderLut3D(RenderTexture source, RenderTexture destination, int preplaced)
	{
		if (LookupTexture.GetInstanceID() != m_BaseTextureIntanceID)
			ConvertBaseTexture3D();

		if (m_Lut3D == null)
			SetIdenreplacedyLut3D();

		m_Lut3D.filterMode = LutFiltering;

		// Uniforms
		float lutSize = (float)m_Lut3D.width;
		Material.SetTexture("_LookupTex3D", m_Lut3D);
		Material.SetVector("_Params", new Vector3((lutSize - 1f) / lutSize, 1f / (2f * lutSize), Blend));

		Graphics.Blit(source, destination, Material, preplaced);
	}

19 View Source File : Bloom.cs
License : Apache License 2.0
Project Creator : activey

private void BrightFilter (Color threshColor,  RenderTexture from, RenderTexture to)
        {
            brightPreplacedFilterMaterial.SetVector ("_Threshhold", threshColor);
            Graphics.Blit (from, to, brightPreplacedFilterMaterial, 1);
        }

19 View Source File : BloomAndFlares.cs
License : MIT License
Project Creator : XINCGer

void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false)
            {
                Graphics.Blit(source, destination);
                return;
            }

            // screen blend is not supported when HDR is enabled (will cap values)

            doHdr = false;
            if (hdr == HDRBloomMode.Auto)
#if UNITY_5_6_OR_NEWER
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR;
#else
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
#endif
            else
            {
                doHdr = hdr == HDRBloomMode.On;
            }

            doHdr = doHdr && supportHDRTextures;

            BloomScreenBlendMode realBlendMode = screenBlendMode;
            if (doHdr)
                realBlendMode = BloomScreenBlendMode.Add;

            var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
            RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat);
            RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
            RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
            RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);

            float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
            float oneOverBaseSize = 1.0f / 512.0f;

            // downsample

            Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
            Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample

            RenderTexture.ReleaseTemporary(halfRezColor);

            // cut colors (thresholding)

            BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
            quarterRezColor.DiscardContents();

            // blurring

            if (bloomBlurIterations < 1) bloomBlurIterations = 1;

            for (int iter = 0; iter < bloomBlurIterations; iter++)
            {
                float spreadForPreplaced = (1.0f + (iter * 0.5f)) * sepBlurSpread;
                separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPreplaced * oneOverBaseSize, 0.0f, 0.0f));

                RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
                Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial);
                src.DiscardContents();

                separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPreplaced / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
                thirdQuarterRezColor.DiscardContents();
            }

            // lens flares: ghosting, anamorphic or a combination

            if (lensflares)
            {

                if (lensflareMode == 0)
                {

                    BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor);
                    quarterRezColor.DiscardContents();

                    // smooth a little, this needs to be resolution dependent
                    /*
                    separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff));
                    Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                    separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff));
                    Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                    */
                    // no ugly edges!

                    Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor);
                    thirdQuarterRezColor.DiscardContents();

                    BlendFlares(secondQuarterRezColor, quarterRezColor);
                    secondQuarterRezColor.DiscardContents();
                }

                // (b) hollywood/anamorphic flares?

                else
                {

                    // thirdQuarter has the brightcut unblurred colors
                    // quarterRezColor is the blurred, brightcut buffer that will end up as bloom

                    hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f));
                    hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
                    thirdQuarterRezColor.DiscardContents();

                    Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
                    secondQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
                    thirdQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f);
                    Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
                    secondQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
                    thirdQuarterRezColor.DiscardContents();

                    if (lensflareMode == (LensflareStyle34)1)
                    {
                        for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++)
                        {
                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                            secondQuarterRezColor.DiscardContents();

                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                            thirdQuarterRezColor.DiscardContents();
                        }

                        AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
                        secondQuarterRezColor.DiscardContents();
                    }
                    else
                    {

                        // (c) combined

                        for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++)
                        {
                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                            secondQuarterRezColor.DiscardContents();

                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                            thirdQuarterRezColor.DiscardContents();
                        }

                        Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor);
                        secondQuarterRezColor.DiscardContents();

                        BlendFlares(thirdQuarterRezColor, secondQuarterRezColor);
                        thirdQuarterRezColor.DiscardContents();

                        AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
                        secondQuarterRezColor.DiscardContents();
                    }
                }
            }

            // screen blend bloom results to color buffer

            screenBlend.SetFloat("_Intensity", bloomIntensity);
            screenBlend.SetTexture("_ColorBuffer", source);
            Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode);

            RenderTexture.ReleaseTemporary(quarterRezColor);
            RenderTexture.ReleaseTemporary(secondQuarterRezColor);
            RenderTexture.ReleaseTemporary(thirdQuarterRezColor);
        }

19 View Source File : VignetteAndChromaticAberration.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination)
        {
            if ( CheckResources () == false)
            {
                Graphics.Blit (source, destination);
                return;
            }

            int rtW = source.width;
            int rtH = source.height;

            bool  doPrepreplaced = (Mathf.Abs(blur)>0.0f || Mathf.Abs(intensity)>0.0f);

            float widthOverHeight = (1.0f * rtW) / (1.0f * rtH);
            const float oneOverBaseSize = 1.0f / 512.0f;

            RenderTexture color = null;
            RenderTexture color2A = null;

            if (doPrepreplaced)
            {
                color = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);

                // Blur corners
                if (Mathf.Abs (blur)>0.0f)
                {
                    color2A = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format);

                    Graphics.Blit (source, color2A, m_ChromAberrationMaterial, 0);

                    for(int i = 0; i < 2; i++)
                    {	// maybe make iteration count tweakable
                        m_SeparableBlurMaterial.SetVector ("offsets",new Vector4 (0.0f, blurSpread * oneOverBaseSize, 0.0f, 0.0f));
                        RenderTexture color2B = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format);
                        Graphics.Blit (color2A, color2B, m_SeparableBlurMaterial);
                        RenderTexture.ReleaseTemporary (color2A);

                        m_SeparableBlurMaterial.SetVector ("offsets",new Vector4 (blurSpread * oneOverBaseSize / widthOverHeight, 0.0f, 0.0f, 0.0f));
                        color2A = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format);
                        Graphics.Blit (color2B, color2A, m_SeparableBlurMaterial);
                        RenderTexture.ReleaseTemporary (color2B);
                    }
                }

                m_VignetteMaterial.SetFloat("_Intensity", (1.0f / (1.0f - intensity) - 1.0f));		// intensity for vignette
                m_VignetteMaterial.SetFloat("_Blur", (1.0f / (1.0f - blur)) - 1.0f);					// blur intensity
                m_VignetteMaterial.SetTexture ("_VignetteTex", color2A);	// blurred texture

                Graphics.Blit (source, color, m_VignetteMaterial, 0);			// prepreplaced blit: darken & blur corners
            }

            m_ChromAberrationMaterial.SetFloat ("_ChromaticAberration", chromaticAberration);
            m_ChromAberrationMaterial.SetFloat ("_AxialAberration", axialAberration);
            m_ChromAberrationMaterial.SetVector ("_BlurDistance", new Vector2 (-blurDistance, blurDistance));
            m_ChromAberrationMaterial.SetFloat ("_Luminance", 1.0f/Mathf.Max(Mathf.Epsilon, luminanceDependency));

            if (doPrepreplaced) color.wrapMode = TextureWrapMode.Clamp;
            else source.wrapMode = TextureWrapMode.Clamp;
            Graphics.Blit (doPrepreplaced ? color : source, destination, m_ChromAberrationMaterial, mode == AberrationMode.Advanced ? 2 : 1);

            RenderTexture.ReleaseTemporary (color);
            RenderTexture.ReleaseTemporary (color2A);
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void AddBokeh ( RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget) {
            if (bokehMaterial) {
                var meshes = Quads.GetMeshes (tempTex.width, tempTex.height);	// quads: exchanging more triangles with less overdraw

                RenderTexture.active = tempTex;
                GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f));

                GL.PushMatrix ();
                GL.LoadIdenreplacedy ();

                // point filter mode is important, otherwise we get bokeh shape & size artefacts
                bokehInfo.filterMode = FilterMode.Point;

                float arW = (bokehInfo.width * 1.0f) / (bokehInfo.height * 1.0f);
                float sc = 2.0f / (1.0f * bokehInfo.width);
                sc += bokehScale * maxBlurSpread * BOKEH_EXTRA_BLUR * oneOverBaseSize;

                bokehMaterial.SetTexture ("_Source", bokehInfo);
                bokehMaterial.SetTexture ("_MainTex", bokehTexture);
                bokehMaterial.SetVector ("_ArScale",new Vector4 (sc, sc * arW, 0.5f, 0.5f * arW));
                bokehMaterial.SetFloat ("_Intensity", bokehIntensity);
                bokehMaterial.SetPreplaced (0);

                foreach(Mesh m in meshes)
                    if (m) Graphics.DrawMeshNow (m, Matrix4x4.idenreplacedy);

                GL.PopMatrix ();

                Graphics.Blit (tempTex, finalTarget, dofMaterial, 8);

                // important to set back as we sample from this later on
                bokehInfo.filterMode = FilterMode.Bilinear;
            }
        }

19 View Source File : Bloom.cs
License : Apache License 2.0
Project Creator : activey

private void Vignette (float amount, RenderTexture from, RenderTexture to)
        {
            if (lensFlareVignetteMask)
            {
                screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask);
                to.MarkRestoreExpected(); // using blending, RT restore expected
                Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3);
            }
            else if (from != to)
            {
                Graphics.SetRenderTarget (to);
                GL.Clear(false, true, Color.black); // clear destination to avoid RT restore
                Graphics.Blit (from, to);
            }
        }

19 View Source File : ScreenOverlay.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination)
		{
            if (CheckResources() == false)
			{
                Graphics.Blit (source, destination);
                return;
            }

            Vector4 UV_Transform = new  Vector4(1, 0, 0, 1);

			#if UNITY_WP8
	    	// WP8 has no OS support for rotating screen with device orientation,
	    	// so we do those transformations ourselves.
			if (Screen.orientation == ScreenOrientation.LandscapeLeft) {
				UV_Transform = new Vector4(0, -1, 1, 0);
			}
			if (Screen.orientation == ScreenOrientation.LandscapeRight) {
				UV_Transform = new Vector4(0, 1, -1, 0);
			}
			if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) {
				UV_Transform = new Vector4(-1, 0, 0, -1);
			}
			#endif

            overlayMaterial.SetVector("_UV_Transform", UV_Transform);
            overlayMaterial.SetFloat ("_Intensity", intensity);
            overlayMaterial.SetTexture ("_Overlay", texture);
            Graphics.Blit (source, destination, overlayMaterial, (int) blendMode);
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void BlurHex ( RenderTexture from, RenderTexture to, int blurPreplaced, float spread, RenderTexture tmp) {
            dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f));
            Graphics.Blit (from, tmp, dofBlurMaterial, blurPreplaced);
            dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  0.0f, 0.0f, 0.0f));
            Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
            dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  spread * oneOverBaseSize, 0.0f, 0.0f));
            Graphics.Blit (to, tmp, dofBlurMaterial, blurPreplaced);
            dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  -spread * oneOverBaseSize, 0.0f, 0.0f));
            Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
        }

19 View Source File : FadeEffect.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage(RenderTexture src, RenderTexture dest)
        {
            if (mat == null)
                mat = new Material(FadeShader);

            float sep = FadeSeparation * 0.66f;
            float r = eval(FadeFactor, 0f, 1f - sep);
            float g = eval(FadeFactor, sep * 0.5f, 1f - (sep * 0.5f));
            float b = eval(FadeFactor, sep, 1f);

            mat.SetColor("_FadeColor", FadeColor);
            mat.SetVector("_FadeFactor", new Vector4(r, g, b, 0.0f));

            Graphics.Blit(src, dest, mat, 0);
        }

19 View Source File : Tonemapping.cs
License : Apache License 2.0
Project Creator : activey

[ImageEffectTransformsToLDR]
        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false)
            {
                Graphics.Blit(source, destination);
                return;
            }

#if UNITY_EDITOR
            validRenderTextureFormat = true;
            if (source.format != RenderTextureFormat.ARGBHalf)
            {
                validRenderTextureFormat = false;
            }
#endif

            // clamp some values to not go out of a valid range

            exposureAdjustment = exposureAdjustment < 0.001f ? 0.001f : exposureAdjustment;

            // SimpleReinhard tonemappers (local, non adaptive)

            if (type == TonemapperType.UserCurve)
            {
                float rangeScale = UpdateCurve();
                tonemapMaterial.SetFloat("_RangeScale", rangeScale);
                tonemapMaterial.SetTexture("_Curve", curveTex);
                Graphics.Blit(source, destination, tonemapMaterial, 4);
                return;
            }

            if (type == TonemapperType.SimpleReinhard)
            {
                tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
                Graphics.Blit(source, destination, tonemapMaterial, 6);
                return;
            }

            if (type == TonemapperType.Hable)
            {
                tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
                Graphics.Blit(source, destination, tonemapMaterial, 5);
                return;
            }

            if (type == TonemapperType.Photographic)
            {
                tonemapMaterial.SetFloat("_ExposureAdjustment", exposureAdjustment);
                Graphics.Blit(source, destination, tonemapMaterial, 8);
                return;
            }

            if (type == TonemapperType.OptimizedHejiDawson)
            {
                tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f*exposureAdjustment);
                Graphics.Blit(source, destination, tonemapMaterial, 7);
                return;
            }

            // still here?
            // =>  adaptive tone mapping:
            // builds an average log luminance, tonemaps according to
            // middle grey and white values (user controlled)

            // AdaptiveReinhardAutoWhite will calculate white value automagically

            bool freshlyBrewedInternalRt = CreateInternalRenderTexture(); // this retrieves rtFormat, so should happen before rt allocations

            RenderTexture rtSquared = RenderTexture.GetTemporary((int) adaptiveTextureSize, (int) adaptiveTextureSize, 0, rtFormat);
            Graphics.Blit(source, rtSquared);

            int downsample = (int) Mathf.Log(rtSquared.width*1.0f, 2);

            int div = 2;
            var rts = new RenderTexture[downsample];
            for (int i = 0; i < downsample; i++)
            {
                rts[i] = RenderTexture.GetTemporary(rtSquared.width/div, rtSquared.width/div, 0, rtFormat);
                div *= 2;
            }

            // downsample pyramid

            var lumRt = rts[downsample - 1];
            Graphics.Blit(rtSquared, rts[0], tonemapMaterial, 1);
            if (type == TonemapperType.AdaptiveReinhardAutoWhite)
            {
                for (int i = 0; i < downsample - 1; i++)
                {
                    Graphics.Blit(rts[i], rts[i + 1], tonemapMaterial, 9);
                    lumRt = rts[i + 1];
                }
            }
            else if (type == TonemapperType.AdaptiveReinhard)
            {
                for (int i = 0; i < downsample - 1; i++)
                {
                    Graphics.Blit(rts[i], rts[i + 1]);
                    lumRt = rts[i + 1];
                }
            }

            // we have the needed values, let's apply adaptive tonemapping

            adaptionSpeed = adaptionSpeed < 0.001f ? 0.001f : adaptionSpeed;
            tonemapMaterial.SetFloat("_AdaptionSpeed", adaptionSpeed);

            rt.MarkRestoreExpected(); // keeping luminance values between frames, RT restore expected

#if UNITY_EDITOR
            if (Application.isPlaying && !freshlyBrewedInternalRt)
                Graphics.Blit(lumRt, rt, tonemapMaterial, 2);
            else
                Graphics.Blit(lumRt, rt, tonemapMaterial, 3);
#else
			Graphics.Blit (lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2);
#endif

            middleGrey = middleGrey < 0.001f ? 0.001f : middleGrey;
            tonemapMaterial.SetVector("_HdrParams", new Vector4(middleGrey, middleGrey, middleGrey, white*white));
            tonemapMaterial.SetTexture("_SmallTex", rt);
            if (type == TonemapperType.AdaptiveReinhard)
            {
                Graphics.Blit(source, destination, tonemapMaterial, 0);
            }
            else if (type == TonemapperType.AdaptiveReinhardAutoWhite)
            {
                Graphics.Blit(source, destination, tonemapMaterial, 10);
            }
            else
            {
                Debug.LogError("No valid adaptive tonemapper type found!");
                Graphics.Blit(source, destination); // at least we get the TransformToLDR effect
            }

            // cleanup for adaptive

            for (int i = 0; i < downsample; i++)
            {
                RenderTexture.ReleaseTemporary(rts[i]);
            }
            RenderTexture.ReleaseTemporary(rtSquared);
        }

19 View Source File : ScreenSpaceAmbientObscurance.cs
License : Apache License 2.0
Project Creator : activey

[ImageEffectOpaque]
        void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources () == false) {
                Graphics.Blit (source, destination);
                return;
            }
			Camera camera = GetComponent<Camera>();

            Matrix4x4 P = camera.projectionMatrix;
            var invP= P.inverse;
            Vector4 projInfo = new Vector4
                ((-2.0f / P[0,0]),
                 (-2.0f / P[1,1]),
                 ((1.0f - P[0,2]) / P[0,0]),
                 ((1.0f + P[1,2]) / P[1,1]));

			if (camera.stereoEnabled)
			{
				Matrix4x4 P0 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left);
				Matrix4x4 P1 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right);

				Vector4 projInfo0 = new Vector4
					((-2.0f / (P0[0, 0])),
					 (-2.0f / (P0[1, 1])),
					 ((1.0f - P0[0, 2]) / P0[0, 0]),
					 ((1.0f + P0[1, 2]) / P0[1, 1]));

				Vector4 projInfo1 = new Vector4
					((-2.0f / (P1[0, 0])),
					 (-2.0f / (P1[1, 1])),
					 ((1.0f - P1[0, 2]) / P1[0, 0]),
					 ((1.0f + P1[1, 2]) / P1[1, 1]));

				aoMaterial.SetVector("_ProjInfoLeft", projInfo0); // used for unprojection
				aoMaterial.SetVector("_ProjInfoRight", projInfo1); // used for unprojection
			}

			aoMaterial.SetVector ("_ProjInfo", projInfo); // used for unprojection
            aoMaterial.SetMatrix ("_ProjectionInv", invP); // only used for reference
            aoMaterial.SetTexture ("_Rand", rand); // not needed for DX11 :)
            aoMaterial.SetFloat ("_Radius", radius);
            aoMaterial.SetFloat ("_Radius2", radius*radius);
            aoMaterial.SetFloat ("_Intensity", intensity);
            aoMaterial.SetFloat ("_BlurFilterDistance", blurFilterDistance);

            int rtW = source.width;
            int rtH = source.height;

            RenderTexture tmpRt  = RenderTexture.GetTemporary (rtW>>downsample, rtH>>downsample);
            RenderTexture tmpRt2;

            Graphics.Blit (source, tmpRt, aoMaterial, 0);

            if (downsample > 0) {
                tmpRt2 = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit(tmpRt, tmpRt2, aoMaterial, 4);
                RenderTexture.ReleaseTemporary (tmpRt);
                tmpRt = tmpRt2;

                // @NOTE: it's probably worth a shot to blur in low resolution
                //  instead with a bilat-upsample afterwards ...
            }

            for (int i = 0; i < blurIterations; i++) {
                aoMaterial.SetVector("_Axis", new Vector2(1.0f,0.0f));
                tmpRt2 = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit (tmpRt, tmpRt2, aoMaterial, 1);
                RenderTexture.ReleaseTemporary (tmpRt);

                aoMaterial.SetVector("_Axis", new Vector2(0.0f,1.0f));
                tmpRt = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit (tmpRt2, tmpRt, aoMaterial, 1);
                RenderTexture.ReleaseTemporary (tmpRt2);
            }

            aoMaterial.SetTexture ("_AOTex", tmpRt);
            Graphics.Blit (source, destination, aoMaterial, 2);

            RenderTexture.ReleaseTemporary (tmpRt);
        }

19 View Source File : ScreenSpaceAmbientObscurance.cs
License : MIT License
Project Creator : GlaireDaggers

[ImageEffectOpaque]
        void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources () == false) {
                Graphics.Blit (source, destination);
                return;
            }

            Matrix4x4 P = GetComponent<Camera>().projectionMatrix;
            var invP= P.inverse;
            Vector4 projInfo = new Vector4
                ((-2.0f / (Screen.width * P[0])),
                 (-2.0f / (Screen.height * P[5])),
                 ((1.0f - P[2]) / P[0]),
                 ((1.0f + P[6]) / P[5]));

            aoMaterial.SetVector ("_ProjInfo", projInfo); // used for unprojection
            aoMaterial.SetMatrix ("_ProjectionInv", invP); // only used for reference
            aoMaterial.SetTexture ("_Rand", rand); // not needed for DX11 :)
            aoMaterial.SetFloat ("_Radius", radius);
            aoMaterial.SetFloat ("_Radius2", radius*radius);
            aoMaterial.SetFloat ("_Intensity", intensity);
            aoMaterial.SetFloat ("_BlurFilterDistance", blurFilterDistance);

            int rtW = source.width;
            int rtH = source.height;

            RenderTexture tmpRt  = RenderTexture.GetTemporary (rtW>>downsample, rtH>>downsample);
            RenderTexture tmpRt2;

            Graphics.Blit (source, tmpRt, aoMaterial, 0);

            if (downsample > 0) {
                tmpRt2 = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit(tmpRt, tmpRt2, aoMaterial, 4);
                RenderTexture.ReleaseTemporary (tmpRt);
                tmpRt = tmpRt2;

                // @NOTE: it's probably worth a shot to blur in low resolution
                //  instead with a bilat-upsample afterwards ...
            }

            for (int i = 0; i < blurIterations; i++) {
                aoMaterial.SetVector("_Axis", new Vector2(1.0f,0.0f));
                tmpRt2 = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit (tmpRt, tmpRt2, aoMaterial, 1);
                RenderTexture.ReleaseTemporary (tmpRt);

                aoMaterial.SetVector("_Axis", new Vector2(0.0f,1.0f));
                tmpRt = RenderTexture.GetTemporary (rtW, rtH);
                Graphics.Blit (tmpRt2, tmpRt, aoMaterial, 1);
                RenderTexture.ReleaseTemporary (tmpRt2);
            }

            aoMaterial.SetTexture ("_AOTex", tmpRt);
            Graphics.Blit (source, destination, aoMaterial, 2);

            RenderTexture.ReleaseTemporary (tmpRt);
        }

19 View Source File : BloomAndFlares.cs
License : Apache License 2.0
Project Creator : activey

private void Vignette(float amount, RenderTexture from, RenderTexture to)
        {
            if (lensFlareVignetteMask)
            {
                screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask);
                Graphics.Blit(from, to, screenBlend, 3);
            }
            else
            {
                vignetteMaterial.SetFloat("vignetteIntensity", amount);
                Graphics.Blit(from, to, vignetteMaterial);
            }
        }

19 View Source File : NoiseAndGrain.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false || (null == noiseTexture))
            {
                Graphics.Blit(source, destination);
                if (null == noiseTexture)
                {
                    Debug.LogWarning("Noise & Grain effect failing as noise texture is not replacedigned. please replacedign.", transform);
                }
                return;
            }

            softness = Mathf.Clamp(softness, 0.0f, 0.99f);

            if (dx11Grain && supportDX11)
            {
                // We have a fancy, procedural noise pattern in this version, so no texture needed

                dx11NoiseMaterial.SetFloat("_DX11NoiseTime", Time.frameCount);
                dx11NoiseMaterial.SetTexture("_NoiseTex", noiseTexture);
                dx11NoiseMaterial.SetVector("_NoisePerChannel", monochrome ? Vector3.one : intensities);
                dx11NoiseMaterial.SetVector("_MidGrey", new Vector3(midGrey, 1.0f / (1.0f - midGrey), -1.0f / midGrey));
                dx11NoiseMaterial.SetVector("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier);

                if (softness > Mathf.Epsilon)
                {
                    RenderTexture rt = RenderTexture.GetTemporary((int)(source.width * (1.0f - softness)), (int)(source.height * (1.0f - softness)));
                    DrawNoiseQuadGrid(source, rt, dx11NoiseMaterial, noiseTexture, mesh, monochrome ? 3 : 2);
                    dx11NoiseMaterial.SetTexture("_NoiseTex", rt);
                    Graphics.Blit(source, destination, dx11NoiseMaterial, 4);
                    RenderTexture.ReleaseTemporary(rt);
                }
                else
                    DrawNoiseQuadGrid(source, destination, dx11NoiseMaterial, noiseTexture, mesh, (monochrome ? 1 : 0));
            }
            else
            {
                // normal noise (DX9 style)

                if (noiseTexture)
                {
                    noiseTexture.wrapMode = TextureWrapMode.Repeat;
                    noiseTexture.filterMode = filterMode;
                }

                noiseMaterial.SetTexture("_NoiseTex", noiseTexture);
                noiseMaterial.SetVector("_NoisePerChannel", monochrome ? Vector3.one : intensities);
                noiseMaterial.SetVector("_NoiseTilingPerChannel", monochrome ? Vector3.one * monochromeTiling : tiling);
                noiseMaterial.SetVector("_MidGrey", new Vector3(midGrey, 1.0f / (1.0f - midGrey), -1.0f / midGrey));
                noiseMaterial.SetVector("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier);

                if (softness > Mathf.Epsilon)
                {
                    RenderTexture rt2 = RenderTexture.GetTemporary((int)(source.width * (1.0f - softness)), (int)(source.height * (1.0f - softness)));
                    DrawNoiseQuadGrid(source, rt2, noiseMaterial, noiseTexture, mesh, 2);
                    noiseMaterial.SetTexture("_NoiseTex", rt2);
                    Graphics.Blit(source, destination, noiseMaterial, 1);
                    RenderTexture.ReleaseTemporary(rt2);
                }
                else
                    DrawNoiseQuadGrid(source, destination, noiseMaterial, noiseTexture, mesh, 0);
            }
        }

19 View Source File : ColorCorrectionLookup.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources () == false || !SystemInfo.supports3DTextures) {
                Graphics.Blit (source, destination);
                return;
            }

            if (converted3DLut == null) {
                SetIdenreplacedyLut ();
            }

            int lutSize = converted3DLut.width;
            converted3DLut.wrapMode = TextureWrapMode.Clamp;
            material.SetFloat("_Scale", (lutSize - 1) / (1.0f*lutSize));
            material.SetFloat("_Offset", 1.0f / (2.0f * lutSize));
            material.SetTexture("_ClutTex", converted3DLut);

            Graphics.Blit (source, destination, material, QualitySettings.activeColorSpace == ColorSpace.Linear ? 1 : 0);
        }

19 View Source File : ColorGradingModelEditor.cs
License : MIT License
Project Creator : liangxiegame

void DrawBackgroundTexture(Rect rect, int preplaced)
        {
            float scale = EditorGUIUtility.pixelsPerPoint;

            var oldRt = RenderTexture.active;
            var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            s_MaterialSpline.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
            s_MaterialSpline.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);

            Graphics.Blit(null, rt, s_MaterialSpline, preplaced);
            RenderTexture.active = oldRt;

            GUI.DrawTexture(rect, rt);
            RenderTexture.ReleaseTemporary(rt);
        }

19 View Source File : Bloom.cs
License : Apache License 2.0
Project Creator : activey

private void BrightFilter (float thresh, RenderTexture from, RenderTexture to)
        {
            brightPreplacedFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh));
            Graphics.Blit (from, to, brightPreplacedFilterMaterial, 0);
        }

19 View Source File : ParadeMonitor.cs
License : MIT License
Project Creator : liangxiegame

public override void OnMonitorGUI(Rect r)
        {
            if (Event.current.type == EventType.Repaint)
            {
                // If m_MonitorAreaRect isn't set the preview was just opened so refresh the render to get the waveform data
                if (Mathf.Approximately(m_MonitorAreaRect.width, 0) && Mathf.Approximately(m_MonitorAreaRect.height, 0))
                    InternalEditorUtility.RepaintAllViews();

                // Sizing
                float width = m_WaveformTexture != null
                    ? Mathf.Min(m_WaveformTexture.width, r.width - 65f)
                    : r.width;
                float height = m_WaveformTexture != null
                    ? Mathf.Min(m_WaveformTexture.height, r.height - 45f)
                    : r.height;

                m_MonitorAreaRect = new Rect(
                        Mathf.Floor(r.x + r.width / 2f - width / 2f),
                        Mathf.Floor(r.y + r.height / 2f - height / 2f - 5f),
                        width, height
                        );

                if (m_WaveformTexture != null)
                {
                    m_Material.SetFloat("_Exposure", m_MonitorSettings.paradeExposure);

                    var oldActive = RenderTexture.active;
                    Graphics.Blit(null, m_WaveformTexture, m_Material, 0);
                    RenderTexture.active = oldActive;

                    Graphics.DrawTexture(m_MonitorAreaRect, m_WaveformTexture);

                    var color = Color.white;
                    const float kTickSize = 5f;

                    // Rect, lines & ticks points
                    //  A O B P C Q D
                    //  N           E
                    //  M           F
                    //  L           G
                    //  K T J S I R H

                    var A = new Vector3(m_MonitorAreaRect.x, m_MonitorAreaRect.y);
                    var D = new Vector3(A.x + m_MonitorAreaRect.width + 1f, m_MonitorAreaRect.y);
                    var H = new Vector3(D.x, D.y + m_MonitorAreaRect.height + 1f);
                    var K = new Vector3(A.x, H.y);

                    var F = new Vector3(D.x, D.y + (H.y - D.y) / 2f);
                    var M = new Vector3(A.x, A.y + (K.y - A.y) / 2f);

                    var B = new Vector3(A.x + (D.x - A.x) / 3f, A.y);
                    var C = new Vector3(A.x + (D.x - A.x) * 2f / 3f, A.y);
                    var I = new Vector3(K.x + (H.x - K.x) * 2f / 3f, K.y);
                    var J = new Vector3(K.x + (H.x - K.x) / 3f, K.y);

                    var N = new Vector3(A.x, A.y + (M.y - A.y) / 2f);
                    var L = new Vector3(A.x, M.y + (K.y - M.y) / 2f);
                    var E = new Vector3(D.x, D.y + (F.y - D.y) / 2f);
                    var G = new Vector3(D.x, F.y + (H.y - F.y) / 2f);

                    var O = new Vector3(A.x + (B.x - A.x) / 2f, A.y);
                    var P = new Vector3(B.x + (C.x - B.x) / 2f, B.y);
                    var Q = new Vector3(C.x + (D.x - C.x) / 2f, C.y);

                    var R = new Vector3(I.x + (H.x - I.x) / 2f, I.y);
                    var S = new Vector3(J.x + (I.x - J.x) / 2f, J.y);
                    var T = new Vector3(K.x + (J.x - K.x) / 2f, K.y);

                    // Borders
                    Handles.color = color;
                    Handles.DrawLine(A, D);
                    Handles.DrawLine(D, H);
                    Handles.DrawLine(H, K);
                    Handles.DrawLine(K, new Vector3(A.x, A.y - 1f));

                    Handles.DrawLine(B, J);
                    Handles.DrawLine(C, I);

                    // Vertical ticks
                    Handles.DrawLine(A, new Vector3(A.x - kTickSize, A.y));
                    Handles.DrawLine(N, new Vector3(N.x - kTickSize, N.y));
                    Handles.DrawLine(M, new Vector3(M.x - kTickSize, M.y));
                    Handles.DrawLine(L, new Vector3(L.x - kTickSize, L.y));
                    Handles.DrawLine(K, new Vector3(K.x - kTickSize, K.y));

                    Handles.DrawLine(D, new Vector3(D.x + kTickSize, D.y));
                    Handles.DrawLine(E, new Vector3(E.x + kTickSize, E.y));
                    Handles.DrawLine(F, new Vector3(F.x + kTickSize, F.y));
                    Handles.DrawLine(G, new Vector3(G.x + kTickSize, G.y));
                    Handles.DrawLine(H, new Vector3(H.x + kTickSize, H.y));

                    // Horizontal ticks
                    Handles.DrawLine(A, new Vector3(A.x, A.y - kTickSize));
                    Handles.DrawLine(B, new Vector3(B.x, B.y - kTickSize));
                    Handles.DrawLine(C, new Vector3(C.x, C.y - kTickSize));
                    Handles.DrawLine(D, new Vector3(D.x, D.y - kTickSize));
                    Handles.DrawLine(O, new Vector3(O.x, O.y - kTickSize));
                    Handles.DrawLine(P, new Vector3(P.x, P.y - kTickSize));
                    Handles.DrawLine(Q, new Vector3(Q.x, Q.y - kTickSize));

                    Handles.DrawLine(H, new Vector3(H.x, H.y + kTickSize));
                    Handles.DrawLine(I, new Vector3(I.x, I.y + kTickSize));
                    Handles.DrawLine(J, new Vector3(J.x, J.y + kTickSize));
                    Handles.DrawLine(K, new Vector3(K.x, K.y + kTickSize));
                    Handles.DrawLine(R, new Vector3(R.x, R.y + kTickSize));
                    Handles.DrawLine(S, new Vector3(S.x, S.y + kTickSize));
                    Handles.DrawLine(T, new Vector3(T.x, T.y + kTickSize));

                    // Labels
                    GUI.color = color;
                    GUI.Label(new Rect(A.x - kTickSize - 34f, A.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleRight);
                    GUI.Label(new Rect(M.x - kTickSize - 34f, M.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleRight);
                    GUI.Label(new Rect(K.x - kTickSize - 34f, K.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleRight);

                    GUI.Label(new Rect(D.x + kTickSize + 4f, D.y - 15f, 30f, 30f), "1.0", FxStyles.tickStyleLeft);
                    GUI.Label(new Rect(F.x + kTickSize + 4f, F.y - 15f, 30f, 30f), "0.5", FxStyles.tickStyleLeft);
                    GUI.Label(new Rect(H.x + kTickSize + 4f, H.y - 15f, 30f, 30f), "0.0", FxStyles.tickStyleLeft);
                }
            }
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void Blur ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPreplaced, float spread) {
            RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height);
            if ((int)iterations > 1) {
                BlurHex (from, to, blurPreplaced, spread, tmp);
                if ((int)iterations > 2) {
                    dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f));
                    Graphics.Blit (to, tmp, dofBlurMaterial, blurPreplaced);
                    dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  0.0f, 0.0f, 0.0f));
                    Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
                }
            }
            else {
                dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f));
                Graphics.Blit (from, tmp, dofBlurMaterial, blurPreplaced);
                dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize,  0.0f, 0.0f, 0.0f));
                Graphics.Blit (tmp, to, dofBlurMaterial, blurPreplaced);
            }
            RenderTexture.ReleaseTemporary (tmp);
        }

19 View Source File : TrackballGroupDrawer.cs
License : MIT License
Project Creator : liangxiegame

void OnWheelGUI(Rect position, int size, SerializedProperty property)
        {
            if (Event.current.type == EventType.Layout)
                return;

            var value = property.colorValue;
            float offset = value.a;

            var wheelDrawArea = position;
            wheelDrawArea.height = size;

            if (wheelDrawArea.width > wheelDrawArea.height)
            {
                wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f;
                wheelDrawArea.width = position.height;
            }

            wheelDrawArea.width = wheelDrawArea.height;

            float hsize = size / 2f;
            float radius = 0.38f * size;
            Vector3 hsv;
            Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z);

            if (Event.current.type == EventType.Repaint)
            {
                float scale = EditorGUIUtility.pixelsPerPoint;

                // Wheel texture
                var oldRT = RenderTexture.active;
                var rt = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
                s_Material.SetFloat("_Offset", offset);
                s_Material.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
                s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f));
                Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1);
                RenderTexture.active = oldRT;

                GUI.DrawTexture(wheelDrawArea, rt);
                RenderTexture.ReleaseTemporary(rt);

                // Thumb
                var thumbPos = Vector2.zero;
                float theta = hsv.x * (Mathf.PI * 2f);
                float len = hsv.y * radius;
                thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f));
                thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f));
                thumbPos *= len;
                var thumbSize = FxStyles.wheelThumbSize;
                var thumbSizeH = thumbSize / 2f;
                FxStyles.wheelThumb.Draw(new Rect(wheelDrawArea.x + hsize + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
            }

            var bounds = wheelDrawArea;
            bounds.x += hsize - radius;
            bounds.y += hsize - radius;
            bounds.width = bounds.height = radius * 2f;
            hsv = GetInput(bounds, hsv, radius);
            value = Color.HSVToRGB(hsv.x, hsv.y, 1f);
            value.a = offset;

            // Luminosity booster
            position = wheelDrawArea;
            float oldX = position.x;
            float oldW = position.width;
            position.y += position.height + 4f;
            position.x += (position.width - (position.width * 0.75f)) / 2f;
            position.width = position.width * 0.75f;
            position.height = EditorGUIUtility.singleLineHeight;
            value.a = GUI.HorizontalSlider(position, value.a, -1f, 1f);

            // Advanced controls
            var data = Vector3.zero;

            if (TryGetDisplayValue(value, property, out data))
            {
                position.x = oldX;
                position.y += position.height;
                position.width = oldW / 3f;

                using (new EditorGUI.DisabledGroupScope(true))
                {
                    GUI.Label(position, data.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                    position.x += position.width;
                    GUI.Label(position, data.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                    position.x += position.width;
                    GUI.Label(position, data.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
                    position.x += position.width;
                }
            }

            // replacedle
            position.x = oldX;
            position.y += position.height;
            position.width = oldW;
            GUI.Label(position, property.displayName, EditorStyles.centeredGreyMiniLabel);

            if (m_ResetState)
            {
                value = Color.clear;
                m_ResetState = false;
            }

            property.colorValue = value;
        }

19 View Source File : BlurOptimized.cs
License : Apache License 2.0
Project Creator : activey

public void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources() == false) {
                Graphics.Blit (source, destination);
                return;
            }

            float widthMod = 1.0f / (1.0f * (1<<downsample));

            blurMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod, -blurSize * widthMod, 0.0f, 0.0f));
            source.filterMode = FilterMode.Bilinear;

            int rtW = source.width >> downsample;
            int rtH = source.height >> downsample;

            // downsample
            RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);

            rt.filterMode = FilterMode.Bilinear;
            Graphics.Blit (source, rt, blurMaterial, 0);

            var preplacedOffs= blurType == BlurType.StandardGauss ? 0 : 2;

            for(int i = 0; i < blurIterations; i++) {
                float iterationOffs = (i*1.0f);
                blurMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + iterationOffs, -blurSize * widthMod - iterationOffs, 0.0f, 0.0f));

                // vertical blur
                RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, blurMaterial, 1 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;

                // horizontal blur
                rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format);
                rt2.filterMode = FilterMode.Bilinear;
                Graphics.Blit (rt, rt2, blurMaterial, 2 + preplacedOffs);
                RenderTexture.ReleaseTemporary (rt);
                rt = rt2;
            }

            Graphics.Blit (rt, destination);

            RenderTexture.ReleaseTemporary (rt);
        }

19 View Source File : SSAOEffect.cs
License : MIT License
Project Creator : PacktPublishing

[ImageEffectOpaque]
	void OnRenderImage (RenderTexture source, RenderTexture destination)
	{
		if (!m_Supported || !m_SSAOShader.isSupported) {
			enabled = false;
			return;
		}
		CreateMaterials ();

		m_Downsampling = Mathf.Clamp (m_Downsampling, 1, 6);
		m_Radius = Mathf.Clamp (m_Radius, 0.05f, 1.0f);
		m_MinZ = Mathf.Clamp (m_MinZ, 0.00001f, 0.5f);
		m_OcclusionIntensity = Mathf.Clamp (m_OcclusionIntensity, 0.5f, 4.0f);
		m_OcclusionAttenuation = Mathf.Clamp (m_OcclusionAttenuation, 0.2f, 2.0f);
		m_Blur = Mathf.Clamp (m_Blur, 0, 4);

		// Render SSAO term into a smaller texture
		RenderTexture rtAO = RenderTexture.GetTemporary (source.width / m_Downsampling, source.height / m_Downsampling, 0);
		float fovY = GetComponent<Camera>().fieldOfView;
		float far = GetComponent<Camera>().farClipPlane;
		float y = Mathf.Tan (fovY * Mathf.Deg2Rad * 0.5f) * far;
		float x = y * GetComponent<Camera>().aspect;
		m_SSAOMaterial.SetVector ("_FarCorner", new Vector3(x,y,far));
		int noiseWidth, noiseHeight;
		if (m_RandomTexture) {
			noiseWidth = m_RandomTexture.width;
			noiseHeight = m_RandomTexture.height;
		} else {
			noiseWidth = 1; noiseHeight = 1;
		}
		m_SSAOMaterial.SetVector ("_NoiseScale", new Vector3 ((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f));
		m_SSAOMaterial.SetVector ("_Params", new Vector4(
			m_Radius,
			m_MinZ,
			1.0f / m_OcclusionAttenuation,
			m_OcclusionIntensity));
			
		bool doBlur = m_Blur > 0;
		Graphics.Blit (doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount);

		if (doBlur)
		{
			// Blur SSAO horizontally
			RenderTexture rtBlurX = RenderTexture.GetTemporary (source.width, source.height, 0);
			m_SSAOMaterial.SetVector ("_TexelOffsetScale",
				new Vector4 ((float)m_Blur / source.width, 0,0,0));
			m_SSAOMaterial.SetTexture ("_SSAO", rtAO);
			Graphics.Blit (null, rtBlurX, m_SSAOMaterial, 3);
			RenderTexture.ReleaseTemporary (rtAO); // original rtAO not needed anymore

			// Blur SSAO vertically
			RenderTexture rtBlurY = RenderTexture.GetTemporary (source.width, source.height, 0);
			m_SSAOMaterial.SetVector ("_TexelOffsetScale",
				new Vector4 (0, (float)m_Blur/source.height, 0,0));
			m_SSAOMaterial.SetTexture ("_SSAO", rtBlurX);
			Graphics.Blit (source, rtBlurY, m_SSAOMaterial, 3);
			RenderTexture.ReleaseTemporary (rtBlurX); // blurX RT not needed anymore

			rtAO = rtBlurY; // AO is the blurred one now
		}

		// Modulate scene rendering with SSAO
		m_SSAOMaterial.SetTexture ("_SSAO", rtAO);
		Graphics.Blit (source, destination, m_SSAOMaterial, 4);

		RenderTexture.ReleaseTemporary (rtAO);
	}

19 View Source File : EdgeDetection.cs
License : Apache License 2.0
Project Creator : activey

[ImageEffectOpaque]
        void OnRenderImage (RenderTexture source, RenderTexture destination)
		{
            if (CheckResources () == false)
			{
                Graphics.Blit (source, destination);
                return;
            }

            Vector2 sensitivity = new Vector2 (sensitivityDepth, sensitivityNormals);
            edgeDetectMaterial.SetVector ("_Sensitivity", new Vector4 (sensitivity.x, sensitivity.y, 1.0f, sensitivity.y));
            edgeDetectMaterial.SetFloat ("_BgFade", edgesOnly);
            edgeDetectMaterial.SetFloat ("_SampleDistance", sampleDist);
            edgeDetectMaterial.SetVector ("_BgColor", edgesOnlyBgColor);
            edgeDetectMaterial.SetFloat ("_Exponent", edgeExp);
            edgeDetectMaterial.SetFloat ("_Threshold", lumThreshold);

            Graphics.Blit (source, destination, edgeDetectMaterial, (int) mode);
        }

19 View Source File : Lutify.cs
License : MIT License
Project Creator : XINCGer

void RenderLut2D(RenderTexture source, RenderTexture destination, int preplaced)
	{
		LookupTexture.filterMode = LutFiltering;

		// Uniforms
		float tileSize = Mathf.Sqrt((float)LookupTexture.width);
		Material.SetTexture("_LookupTex2D", LookupTexture);
		Material.SetVector("_Params", new Vector4(1f / (float)LookupTexture.width, 1f / (float)LookupTexture.height, tileSize - 1f, Blend));

		Graphics.Blit(source, destination, Material, preplaced + (LutFiltering == FilterMode.Point ? 6 : 0));
	}

19 View Source File : Bloom.cs
License : Apache License 2.0
Project Creator : activey

public void OnRenderImage (RenderTexture source, RenderTexture destination)
        {
            if (CheckResources()==false)
            {
                Graphics.Blit (source, destination);
                return;
            }

            // screen blend is not supported when HDR is enabled (will cap values)

            doHdr = false;
            if (hdr == HDRBloomMode.Auto)
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
            else {
                doHdr = hdr == HDRBloomMode.On;
            }

            doHdr = doHdr && supportHDRTextures;

            BloomScreenBlendMode realBlendMode = screenBlendMode;
            if (doHdr)
                realBlendMode = BloomScreenBlendMode.Add;

            var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
            var rtW2= source.width/2;
            var rtH2= source.height/2;
            var rtW4= source.width/4;
            var rtH4= source.height/4;

            float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
            float oneOverBaseSize = 1.0f / 512.0f;

            // downsample
            RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
            RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
            if (quality > BloomQuality.Cheap) {
                Graphics.Blit (source, halfRezColorDown, screenBlend, 2);
                RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2);
                Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6);
                RenderTexture.ReleaseTemporary(rtDown4);
            }
            else {
                Graphics.Blit (source, halfRezColorDown);
                Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6);
            }
            RenderTexture.ReleaseTemporary (halfRezColorDown);

            // cut colors (thresholding)
            RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
            BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor);

            // blurring

            if (bloomBlurIterations < 1) bloomBlurIterations = 1;
            else if (bloomBlurIterations > 10) bloomBlurIterations = 10;

            for (int iter = 0; iter < bloomBlurIterations; iter++)
			{
                float spreadForPreplaced = (1.0f + (iter * 0.25f)) * sepBlurSpread;

                // vertical blur
                RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPreplaced * oneOverBaseSize, 0.0f, 0.0f));
                Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
                RenderTexture.ReleaseTemporary(secondQuarterRezColor);
                secondQuarterRezColor = blur4;

                // horizontal blur
                blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPreplaced / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
                RenderTexture.ReleaseTemporary (secondQuarterRezColor);
                secondQuarterRezColor = blur4;

                if (quality > BloomQuality.Cheap)
				{
                    if (iter == 0)
                    {
                        Graphics.SetRenderTarget(quarterRezColor);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (secondQuarterRezColor, quarterRezColor);
                    }
                    else
                    {
                        quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected
                        Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10);
                    }
                }
            }

            if (quality > BloomQuality.Cheap)
            {
                Graphics.SetRenderTarget(secondQuarterRezColor);
                GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6);
            }

            // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares)

            if (lensflareIntensity > Mathf.Epsilon)
			{

                RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);

                if (lensflareMode == 0)
				{
                    // ghosting only

                    BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4);

                    if (quality > BloomQuality.Cheap)
					{
                        // smooth a little
                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
                        Graphics.SetRenderTarget(quarterRezColor);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
                        Graphics.SetRenderTarget(rtFlares4);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
                    }

                    // no ugly edges!
                    Vignette (0.975f, rtFlares4, rtFlares4);
                    BlendFlares (rtFlares4, secondQuarterRezColor);
                }
                else
				{

                    //Vignette (0.975ff, rtFlares4, rtFlares4);
                    //DrawBorder(rtFlares4, screenBlend, 8);

                    float flareXRot = 1.0f * Mathf.Cos(flareRotation);
                    float flareyRot = 1.0f * Mathf.Sin(flareRotation);

                    float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize;

                    blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f));
                    blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f));
                    blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
                    blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation);

                    // "pre and cut"
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2);
                    // "post"
                    rtFlares4.DiscardContents();
                    Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3);

                    blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f));
                    // stretch 1st
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth);
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
                    // stretch 2nd
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f);
                    rtFlares4.DiscardContents();
                    Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1);
                    // stretch 3rd
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f);
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);

                    // additional blur preplacedes
                    for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++)
					{
                        stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize;

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
                        rtFlares4.DiscardContents();
                        Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
                        quarterRezColor.DiscardContents();
                        Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
                    }

                    if (lensflareMode == (LensFlareStyle) 1)
                        // anamorphic lens flares
                        AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
                    else
					{
                        // "combined" lens flares

                        Vignette (1.0f, quarterRezColor, rtFlares4);
                        BlendFlares (rtFlares4, quarterRezColor);
                        AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
                    }
                }
                RenderTexture.ReleaseTemporary (rtFlares4);
            }

            int blendPreplaced = (int) realBlendMode;
            //if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon)
            //	blendPreplaced += 4;

            screenBlend.SetFloat ("_Intensity", bloomIntensity);
            screenBlend.SetTexture ("_ColorBuffer", source);

            if (quality > BloomQuality.Cheap)
			{
                RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
                Graphics.Blit (secondQuarterRezColor, halfRezColorUp);
                Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPreplaced);
                RenderTexture.ReleaseTemporary (halfRezColorUp);
            }
            else
                Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPreplaced);

            RenderTexture.ReleaseTemporary (quarterRezColor);
            RenderTexture.ReleaseTemporary (secondQuarterRezColor);
        }

19 View Source File : Bloom.cs
License : MIT License
Project Creator : XINCGer

public void OnRenderImage (RenderTexture source, RenderTexture destination)
        {
            if (CheckResources()==false)
            {
                Graphics.Blit (source, destination);
                return;
            }

            // screen blend is not supported when HDR is enabled (will cap values)

            doHdr = false;
            if (hdr == HDRBloomMode.Auto)
#if UNITY_5_6_OR_NEWER
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().allowHDR;
#else
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
#endif
            else {
                doHdr = hdr == HDRBloomMode.On;
            }

            doHdr = doHdr && supportHDRTextures;

            BloomScreenBlendMode realBlendMode = screenBlendMode;
            if (doHdr)
                realBlendMode = BloomScreenBlendMode.Add;

            var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
            var rtW2= source.width/2;
            var rtH2= source.height/2;
            var rtW4= source.width/4;
            var rtH4= source.height/4;

            float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
            float oneOverBaseSize = 1.0f / 512.0f;

            // downsample
            RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
            RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
            if (quality > BloomQuality.Cheap) {
                Graphics.Blit (source, halfRezColorDown, screenBlend, 2);
                RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2);
                Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6);
                RenderTexture.ReleaseTemporary(rtDown4);
            }
            else {
                Graphics.Blit (source, halfRezColorDown);
                Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6);
            }
            RenderTexture.ReleaseTemporary (halfRezColorDown);

            // cut colors (thresholding)
            RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
            BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor);

            // blurring

            if (bloomBlurIterations < 1) bloomBlurIterations = 1;
            else if (bloomBlurIterations > 10) bloomBlurIterations = 10;

            for (int iter = 0; iter < bloomBlurIterations; iter++)
			{
                float spreadForPreplaced = (1.0f + (iter * 0.25f)) * sepBlurSpread;

                // vertical blur
                RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPreplaced * oneOverBaseSize, 0.0f, 0.0f));
                Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
                RenderTexture.ReleaseTemporary(secondQuarterRezColor);
                secondQuarterRezColor = blur4;

                // horizontal blur
                blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);
                blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPreplaced / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4);
                RenderTexture.ReleaseTemporary (secondQuarterRezColor);
                secondQuarterRezColor = blur4;

                if (quality > BloomQuality.Cheap)
				{
                    if (iter == 0)
                    {
                        Graphics.SetRenderTarget(quarterRezColor);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (secondQuarterRezColor, quarterRezColor);
                    }
                    else
                    {
                        quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected
                        Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10);
                    }
                }
            }

            if (quality > BloomQuality.Cheap)
            {
                Graphics.SetRenderTarget(secondQuarterRezColor);
                GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6);
            }

            // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares)

            if (lensflareIntensity > Mathf.Epsilon)
			{

                RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat);

                if (lensflareMode == 0)
				{
                    // ghosting only

                    BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4);

                    if (quality > BloomQuality.Cheap)
					{
                        // smooth a little
                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f));
                        Graphics.SetRenderTarget(quarterRezColor);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f));
                        Graphics.SetRenderTarget(rtFlares4);
                        GL.Clear(false, true, Color.black); // Clear to avoid RT restore
                        Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);
                    }

                    // no ugly edges!
                    Vignette (0.975f, rtFlares4, rtFlares4);
                    BlendFlares (rtFlares4, secondQuarterRezColor);
                }
                else
				{

                    //Vignette (0.975ff, rtFlares4, rtFlares4);
                    //DrawBorder(rtFlares4, screenBlend, 8);

                    float flareXRot = 1.0f * Mathf.Cos(flareRotation);
                    float flareyRot = 1.0f * Mathf.Sin(flareRotation);

                    float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize;

                    blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f));
                    blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f));
                    blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
                    blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation);

                    // "pre and cut"
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2);
                    // "post"
                    rtFlares4.DiscardContents();
                    Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3);

                    blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f));
                    // stretch 1st
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth);
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);
                    // stretch 2nd
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f);
                    rtFlares4.DiscardContents();
                    Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1);
                    // stretch 3rd
                    blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f);
                    quarterRezColor.DiscardContents();
                    Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1);

                    // additional blur preplacedes
                    for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++)
					{
                        stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize;

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
                        rtFlares4.DiscardContents();
                        Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4);

                        blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f));
                        quarterRezColor.DiscardContents();
                        Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4);
                    }

                    if (lensflareMode == (LensFlareStyle) 1)
                        // anamorphic lens flares
                        AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
                    else
					{
                        // "combined" lens flares

                        Vignette (1.0f, quarterRezColor, rtFlares4);
                        BlendFlares (rtFlares4, quarterRezColor);
                        AddTo (1.0f, quarterRezColor, secondQuarterRezColor);
                    }
                }
                RenderTexture.ReleaseTemporary (rtFlares4);
            }

            int blendPreplaced = (int) realBlendMode;
            //if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon)
            //	blendPreplaced += 4;

            screenBlend.SetFloat ("_Intensity", bloomIntensity);
            screenBlend.SetTexture ("_ColorBuffer", source);

            if (quality > BloomQuality.Cheap)
			{
                RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat);
                Graphics.Blit (secondQuarterRezColor, halfRezColorUp);
                Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPreplaced);
                RenderTexture.ReleaseTemporary (halfRezColorUp);
            }
            else
                Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPreplaced);

            RenderTexture.ReleaseTemporary (quarterRezColor);
            RenderTexture.ReleaseTemporary (secondQuarterRezColor);
        }

19 View Source File : TiltShift.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (CheckResources() == false) {
                Graphics.Blit (source, destination);
                return;
            }

            tiltShiftMaterial.SetFloat("_BlurSize", maxBlurSize < 0.0f ? 0.0f : maxBlurSize);
            tiltShiftMaterial.SetFloat("_BlurArea", blurArea);
            source.filterMode = FilterMode.Bilinear;

            RenderTexture rt = destination;
            if (downsample > 0f) {
                rt = RenderTexture.GetTemporary (source.width>>downsample, source.height>>downsample, 0, source.format);
                rt.filterMode = FilterMode.Bilinear;
            }

            int basePreplacedNr = (int) quality; basePreplacedNr *= 2;
            Graphics.Blit (source, rt, tiltShiftMaterial, mode == TiltShiftMode.TiltShiftMode ? basePreplacedNr : basePreplacedNr + 1);

            if (downsample > 0) {
                tiltShiftMaterial.SetTexture ("_Blurred", rt);
                Graphics.Blit (source, destination, tiltShiftMaterial, 8);
            }

            if (rt != destination)
                RenderTexture.ReleaseTemporary (rt);
        }

19 View Source File : DepthOfField.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (!CheckResources ()) {
                Graphics.Blit (source, destination);
                return;
            }

            // clamp & prepare values so they make sense

            if (aperture < 0.0f) aperture = 0.0f;
            if (maxBlurSize < 0.1f) maxBlurSize = 0.1f;
            focalSize = Mathf.Clamp(focalSize, 0.0f, 2.0f);
            internalBlurWidth = Mathf.Max(maxBlurSize, 0.0f);

            // focal & coc calculations

            focalDistance01 = (focalTransform) ? (cachedCamera.WorldToViewportPoint (focalTransform.position)).z / (cachedCamera.farClipPlane) : FocalDistance01 (focalLength);
            dofHdrMaterial.SetVector("_CurveParams", new Vector4(1.0f, focalSize, (1.0f / (1.0f - aperture) - 1.0f), focalDistance01));

            // possible render texture helpers

            RenderTexture rtLow = null;
            RenderTexture rtLow2 = null;
            RenderTexture rtSuperLow1 = null;
            RenderTexture rtSuperLow2 = null;
            float fgBlurDist = internalBlurWidth * foregroundOverlap;

            if (visualizeFocus)
            {

                //
                // 2.
                // visualize coc
                //
                //

                WriteCoc (source, true);
                Graphics.Blit (source, destination, dofHdrMaterial, 16);
            }
            else if ((blurType == BlurType.DX11) && dx11bokehMaterial)
            {

                //
                // 1.
                // optimized dx11 bokeh scatter
                //
                //


                if (highResolution) {

                    internalBlurWidth = internalBlurWidth < 0.1f ? 0.1f : internalBlurWidth;
                    fgBlurDist = internalBlurWidth * foregroundOverlap;

                    rtLow = RenderTexture.GetTemporary (source.width, source.height, 0, source.format);

                    var dest2= RenderTexture.GetTemporary (source.width, source.height, 0, source.format);

                    // capture COC
                    WriteCoc (source, false);

                    // blur a bit so we can do a frequency check
                    rtSuperLow1 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format);
                    rtSuperLow2 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format);

                    Graphics.Blit(source, rtSuperLow1, dofHdrMaterial, 15);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f));
                    Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f));
                    Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);

                    // capture fg coc
                    if (nearBlur)
                        Graphics.Blit (source, rtSuperLow2, dofHdrMaterial, 4);

                    dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1);
                    dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic);
                    dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
                    dx11bokehMaterial.SetTexture ("_FgCocMask", nearBlur ? rtSuperLow2 : null);

                    // collect bokeh candidates and replace with a darker pixel
                    Graphics.SetRandomWriteTarget (1, cbPoints);
                    Graphics.Blit (source, rtLow, dx11bokehMaterial, 0);
                    Graphics.ClearRandomWriteTargets ();

                    // fg coc blur happens here (after collect!)
                    if (nearBlur) {
                        dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist));
                        Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 2);
                        dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist));
                        Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 2);

                        // merge fg coc with bg coc
                        Graphics.Blit (rtSuperLow2, rtLow, dofHdrMaterial, 3);
                    }

                    // NEW: LAY OUT ALPHA on destination target so we get nicer outlines for the high rez version
                    Graphics.Blit (rtLow, dest2, dofHdrMaterial, 20);

                    // box blur (easier to merge with bokeh buffer)
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth));
                    Graphics.Blit (rtLow, source, dofHdrMaterial, 5);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
                    Graphics.Blit (source, dest2, dofHdrMaterial, 21);

                    // apply bokeh candidates
                    Graphics.SetRenderTarget (dest2);
                    ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0);
                    dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints);
                    dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture);
                    dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*source.width), 1.0f/(1.0f*source.height), internalBlurWidth));
                    dx11bokehMaterial.SetPreplaced (2);

                    Graphics.DrawProceduralIndirect (MeshTopology.Points, cbDrawArgs, 0);

                    Graphics.Blit (dest2, destination);	// hackaround for DX11 high resolution flipfun (OPTIMIZEME)

                    RenderTexture.ReleaseTemporary(dest2);
                    RenderTexture.ReleaseTemporary(rtSuperLow1);
                    RenderTexture.ReleaseTemporary(rtSuperLow2);
                }
                else {
                    rtLow = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);
                    rtLow2 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);

                    fgBlurDist = internalBlurWidth * foregroundOverlap;

                    // capture COC & color in low resolution
                    WriteCoc (source, false);
                    source.filterMode = FilterMode.Bilinear;
                    Graphics.Blit (source, rtLow, dofHdrMaterial, 6);

                    // blur a bit so we can do a frequency check
                    rtSuperLow1 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format);
                    rtSuperLow2 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format);

                    Graphics.Blit(rtLow, rtSuperLow1, dofHdrMaterial, 15);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f));
                    Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f));
                    Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19);

                    RenderTexture rtLow3 = null;

                    if (nearBlur) {
                        // capture fg coc
                        rtLow3 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format);
                        Graphics.Blit (source, rtLow3, dofHdrMaterial, 4);
                    }

                    dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1);
                    dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic);
                    dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth));
                    dx11bokehMaterial.SetTexture ("_FgCocMask", rtLow3);

                    // collect bokeh candidates and replace with a darker pixel
                    Graphics.SetRandomWriteTarget (1, cbPoints);
                    Graphics.Blit (rtLow, rtLow2, dx11bokehMaterial, 0);
                    Graphics.ClearRandomWriteTargets ();

                    RenderTexture.ReleaseTemporary(rtSuperLow1);
                    RenderTexture.ReleaseTemporary(rtSuperLow2);

                    // fg coc blur happens here (after collect!)
                    if (nearBlur) {
                        dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist));
                        Graphics.Blit (rtLow3, rtLow, dofHdrMaterial, 2);
                        dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist));
                        Graphics.Blit (rtLow, rtLow3, dofHdrMaterial, 2);

                        // merge fg coc with bg coc
                        Graphics.Blit (rtLow3, rtLow2, dofHdrMaterial, 3);
                    }

                    // box blur (easier to merge with bokeh buffer)
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth));
                    Graphics.Blit (rtLow2, rtLow, dofHdrMaterial, 5);
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth));
                    Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, 5);

                    // apply bokeh candidates
                    Graphics.SetRenderTarget (rtLow2);
                    ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0);
                    dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints);
                    dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture);
                    dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*rtLow2.width), 1.0f/(1.0f*rtLow2.height), internalBlurWidth));
                    dx11bokehMaterial.SetPreplaced (1);
                    Graphics.DrawProceduralIndirect (MeshTopology.Points, cbDrawArgs, 0);

                    // upsample & combine
                    dofHdrMaterial.SetTexture ("_LowRez", rtLow2);
                    dofHdrMaterial.SetTexture ("_FgOverlap", rtLow3);
                    dofHdrMaterial.SetVector ("_Offsets",  ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth * Vector4.one);
                    Graphics.Blit (source, destination, dofHdrMaterial, 9);

                    if (rtLow3) RenderTexture.ReleaseTemporary(rtLow3);
                }
            }
            else
            {

                //
                // 2.
                // poisson disc style blur in low resolution
                //
                //

                source.filterMode = FilterMode.Bilinear;

                if (highResolution) internalBlurWidth *= 2.0f;

                WriteCoc (source, true);

                rtLow = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format);
                rtLow2 = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format);

                int blurPreplaced = (blurSampleCount == BlurSampleCount.High || blurSampleCount == BlurSampleCount.Medium) ? 17 : 11;

                if (highResolution) {
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.025f, internalBlurWidth));
                    Graphics.Blit (source, destination, dofHdrMaterial, blurPreplaced);
                }
                else {
                    dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.1f, internalBlurWidth));

                    // blur
                    Graphics.Blit (source, rtLow, dofHdrMaterial, 6);
                    Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, blurPreplaced);

                    // cheaper blur in high resolution, upsample and combine
                    dofHdrMaterial.SetTexture("_LowRez", rtLow2);
                    dofHdrMaterial.SetTexture("_FgOverlap", null);
                    dofHdrMaterial.SetVector ("_Offsets",  Vector4.one * ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth);
                    Graphics.Blit (source, destination, dofHdrMaterial, blurSampleCount == BlurSampleCount.High ? 18 : 12);
                }
            }

            if (rtLow) RenderTexture.ReleaseTemporary(rtLow);
            if (rtLow2) RenderTexture.ReleaseTemporary(rtLow2);
        }

19 View Source File : Antialiasing.cs
License : Apache License 2.0
Project Creator : activey

public void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false)
            {
                Graphics.Blit(source, destination);
                return;
            }

			// ----------------------------------------------------------------
            // FXAA antialiasing modes

            if (mode == AAMode.FXAA3Console && (materialFXAAIII != null))
            {
                materialFXAAIII.SetFloat("_EdgeThresholdMin", edgeThresholdMin);
                materialFXAAIII.SetFloat("_EdgeThreshold", edgeThreshold);
                materialFXAAIII.SetFloat("_EdgeSharpness", edgeSharpness);

                Graphics.Blit(source, destination, materialFXAAIII);
            }
            else if (mode == AAMode.FXAA1PresetB && (materialFXAAPreset3 != null))
            {
                Graphics.Blit(source, destination, materialFXAAPreset3);
            }
            else if (mode == AAMode.FXAA1PresetA && materialFXAAPreset2 != null)
            {
                source.anisoLevel = 4;
                Graphics.Blit(source, destination, materialFXAAPreset2);
                source.anisoLevel = 0;
            }
            else if (mode == AAMode.FXAA2 && materialFXAAII != null)
            {
                Graphics.Blit(source, destination, materialFXAAII);
            }
            else if (mode == AAMode.SSAA && ssaa != null)
            {
				// ----------------------------------------------------------------
                // SSAA antialiasing
                Graphics.Blit(source, destination, ssaa);
            }
            else if (mode == AAMode.DLAA && dlaa != null)
            {
				// ----------------------------------------------------------------
				// DLAA antialiasing

                source.anisoLevel = 0;
                RenderTexture interim = RenderTexture.GetTemporary(source.width, source.height);
                Graphics.Blit(source, interim, dlaa, 0);
                Graphics.Blit(interim, destination, dlaa, dlaaSharp ? 2 : 1);
                RenderTexture.ReleaseTemporary(interim);
            }
            else if (mode == AAMode.NFAA && nfaa != null)
            {
                // ----------------------------------------------------------------
                // nfaa antialiasing

                source.anisoLevel = 0;

                nfaa.SetFloat("_OffsetScale", offsetScale);
                nfaa.SetFloat("_BlurRadius", blurRadius);

                Graphics.Blit(source, destination, nfaa, showGeneratedNormals ? 1 : 0);
            }
            else
            {
                // none of the AA is supported, fallback to a simple blit
                Graphics.Blit(source, destination);
            }
        }

19 View Source File : Bloom.cs
License : Apache License 2.0
Project Creator : activey

private void AddTo (float intensity_, RenderTexture from, RenderTexture to)
        {
            screenBlend.SetFloat ("_Intensity", intensity_);
            to.MarkRestoreExpected(); // additive blending, RT restore expected
            Graphics.Blit (from, to, screenBlend, 9);
        }

19 View Source File : BloomAndFlares.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false)
            {
                Graphics.Blit(source, destination);
                return;
            }

            // screen blend is not supported when HDR is enabled (will cap values)

            doHdr = false;
            if (hdr == HDRBloomMode.Auto)
                doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
            else
            {
                doHdr = hdr == HDRBloomMode.On;
            }

            doHdr = doHdr && supportHDRTextures;

            BloomScreenBlendMode realBlendMode = screenBlendMode;
            if (doHdr)
                realBlendMode = BloomScreenBlendMode.Add;

            var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
            RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat);
            RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
            RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
            RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);

            float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
            float oneOverBaseSize = 1.0f / 512.0f;

            // downsample

            Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
            Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample

            RenderTexture.ReleaseTemporary(halfRezColor);

            // cut colors (thresholding)

            BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
            quarterRezColor.DiscardContents();

            // blurring

            if (bloomBlurIterations < 1) bloomBlurIterations = 1;

            for (int iter = 0; iter < bloomBlurIterations; iter++)
            {
                float spreadForPreplaced = (1.0f + (iter * 0.5f)) * sepBlurSpread;
                separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPreplaced * oneOverBaseSize, 0.0f, 0.0f));

                RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
                Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial);
                src.DiscardContents();

                separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPreplaced / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
                thirdQuarterRezColor.DiscardContents();
            }

            // lens flares: ghosting, anamorphic or a combination

            if (lensflares)
            {

                if (lensflareMode == 0)
                {

                    BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor);
                    quarterRezColor.DiscardContents();

                    // smooth a little, this needs to be resolution dependent
                    /*
                    separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff));
                    Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                    separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff));
                    Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                    */
                    // no ugly edges!

                    Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor);
                    thirdQuarterRezColor.DiscardContents();

                    BlendFlares(secondQuarterRezColor, quarterRezColor);
                    secondQuarterRezColor.DiscardContents();
                }

                // (b) hollywood/anamorphic flares?

                else
                {

                    // thirdQuarter has the brightcut unblurred colors
                    // quarterRezColor is the blurred, brightcut buffer that will end up as bloom

                    hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f));
                    hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
                    thirdQuarterRezColor.DiscardContents();

                    Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
                    secondQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
                    thirdQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f);
                    Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
                    secondQuarterRezColor.DiscardContents();

                    hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f);
                    Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
                    thirdQuarterRezColor.DiscardContents();

                    if (lensflareMode == (LensflareStyle34)1)
                    {
                        for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++)
                        {
                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                            secondQuarterRezColor.DiscardContents();

                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                            thirdQuarterRezColor.DiscardContents();
                        }

                        AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
                        secondQuarterRezColor.DiscardContents();
                    }
                    else
                    {

                        // (c) combined

                        for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++)
                        {
                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
                            secondQuarterRezColor.DiscardContents();

                            separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
                            Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
                            thirdQuarterRezColor.DiscardContents();
                        }

                        Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor);
                        secondQuarterRezColor.DiscardContents();

                        BlendFlares(thirdQuarterRezColor, secondQuarterRezColor);
                        thirdQuarterRezColor.DiscardContents();

                        AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
                        secondQuarterRezColor.DiscardContents();
                    }
                }
            }

            // screen blend bloom results to color buffer

            screenBlend.SetFloat("_Intensity", bloomIntensity);
            screenBlend.SetTexture("_ColorBuffer", source);
            Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode);

            RenderTexture.ReleaseTemporary(quarterRezColor);
            RenderTexture.ReleaseTemporary(secondQuarterRezColor);
            RenderTexture.ReleaseTemporary(thirdQuarterRezColor);
        }

19 View Source File : DepthOfFieldDeprecated.cs
License : Apache License 2.0
Project Creator : activey

void Downsample ( RenderTexture from, RenderTexture to) {
            dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * to.width), 1.0f / (1.0f * to.height), 0.0f, 0.0f));
            Graphics.Blit (from, to, dofMaterial, SMOOTH_DOWNSAMPLE_Preplaced);
        }

19 View Source File : CRTEffect.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage(RenderTexture src, RenderTexture dest)
        {
            ensureResources();

            setKeyword("ANTI_FLICKER", this.AntiFlicker, ref this.antiFlickerEnabled);
            setKeyword("ROLLING_FLICKER", this.EnableRollingFlicker, ref this.rollingFlickerEnabled);
            setKeyword("PIXEL_MASK", this.EnablePixelMask, ref this.pixelMaskEnabled);
            setKeyword("USE_TV_CURVATURE", this.EnableTVCurvature, ref this.tvCurvatureEnabled);
            setKeyword("QUANTIZE_RGB", this.QuantizeRGB, ref this.quantizeRGBEnabled);
            setKeyword("RF_SIGNAL", this.VideoMode == VideoType.RF, ref this.rfEnabled);

            if (compositeTemp == null || compositeTemp.width != DisplaySizeX || compositeTemp.height != DisplaySizeY)
            {
                if (compositeTemp != null)
                    RenderTexture.ReleaseTemporary(compositeTemp);

                compositeTemp = RenderTexture.GetTemporary(DisplaySizeX, DisplaySizeY, src.depth, RenderTextureFormat.ARGBHalf);
            }

            if (QuantizeRGB)
            {
                Vector4 quantize = new Vector4(Mathf.Pow(2f, RBits), Mathf.Pow(2f, GBits), Mathf.Pow(2f, BBits), 1f);
                Vector4 oneOverQuantize = new Vector4(1f / quantize.x, 1f / quantize.y, 1f / quantize.z, 1f);

                material.SetVector("_QuantizeRGB", quantize);
                material.SetVector("_OneOverQuantizeRGB", oneOverQuantize);
            }

			material.SetFloat("_Realtime", Time.realtimeSinceStartup);

            material.SetVector("_IQOffset", new Vector4(IQScale.x, IQScale.y, IQOffset.x, IQOffset.y));
            material.SetMatrix("_RGB2YIQ_MAT", this.rgb2yiq_mat);
            material.SetMatrix("_YIQ2RGB_MAT", this.yiq2rgb_mat);

            material.SetFloat("_RFNoise", this.RFNoise);
			material.SetFloat("_LumaSharpen", this.LumaSharpen);

            material.SetInt("_Framecount", -this.frameCount);
            material.SetVector("_ScreenSize", new Vector4(DisplaySizeX, DisplaySizeY, 1f / DisplaySizeX, 1f / DisplaySizeY));

            material.SetFloat("_RollingFlickerAmount", this.RollingFlickerFactor);
            material.SetVector("_FlickerOffs", new Vector4(this.flickerOffset, this.flickerOffset + RollingVSyncTime, 0f, 0f));

            material.SetVector("_PixelMaskScale", new Vector4(MaskRepeatX, MaskRepeatY));
            material.SetTexture("_PixelMask", PixelMaskTexture);
            material.SetFloat("_Brightness", PixelMaskBrightness);

            material.SetFloat("_TVCurvature", Curvature);
            

            RenderTexture preplaced1 = RenderTexture.GetTemporary(DisplaySizeX, DisplaySizeY, src.depth, RenderTextureFormat.ARGBHalf);
			//preplaced1.filterMode = FilterMode.Point;
			RenderTexture preplaced2 = RenderTexture.GetTemporary(DisplaySizeX, DisplaySizeY, src.depth, RenderTextureFormat.ARGBHalf);
			//preplaced2.filterMode = FilterMode.Point;

            RenderTexture lastComposite = RenderTexture.GetTemporary(DisplaySizeX, DisplaySizeY, src.depth, RenderTextureFormat.ARGBHalf);

            RenderTexture final = preplaced1;

            if (this.VideoMode == VideoType.Composite || this.VideoMode == VideoType.RF)
            {
                Graphics.Blit(src, preplaced1);

				Graphics.Blit(preplaced1, preplaced2, material, Preplaced_COMPOSITE_ENCODE);

				// preplaced last frame's signal and save current frame's signal
				Graphics.Blit(compositeTemp, lastComposite);
				Graphics.Blit(preplaced2, compositeTemp);
				material.SetTexture("_LastCompositeTex", lastComposite);
				
				Graphics.Blit(preplaced2, preplaced1, material, Preplaced_COMPOSITE_DECODE);
				Graphics.Blit(preplaced1, preplaced2, material, Preplaced_COMPOSITE_FINAL);

				final = preplaced2;
			}
            else if (this.VideoMode == VideoType.SVideo)
            {
                Graphics.Blit(src, preplaced1);

                Graphics.Blit(preplaced1, preplaced2, material, Preplaced_SVIDEO_ENCODE);

                // preplaced last frame's signal and save current frame's signal
                Graphics.Blit(compositeTemp, lastComposite);
                Graphics.Blit(preplaced2, compositeTemp);
                material.SetTexture("_LastCompositeTex", lastComposite);

                Graphics.Blit(preplaced2, preplaced1, material, Preplaced_SVIDEO_DECODE);
            }
            else if (this.VideoMode == VideoType.VGA)
            {
                Graphics.Blit(src, preplaced1, material, Preplaced_VGA);
            }
            else if (this.VideoMode == VideoType.VGAFast)
            {
                final = src;
            }
            else if (this.VideoMode == VideoType.Component)
            {
                Graphics.Blit(src, preplaced1, material, Preplaced_COMPONENT);
            }

            //Graphics.Blit(final, dest, material, Preplaced_TV_OVERLAY);
            if (StretchToDisplay)
                blitQuad(final, dest, material, Preplaced_TV_OVERLAY);
            else
            {
                float screenAspect = (float)Screen.width / (float)Screen.height;

                if (screenAspect < AspectRatio)
                {
                    // fit to screen width
                    float width = 1f;
                    float height = screenAspect / AspectRatio;
                    float heightDiff = 1f - height;

                    blitQuad(new Rect(0f, heightDiff * 0.5f, width, height), final, dest, material, Preplaced_TV_OVERLAY);
                }
                else
                {
                    // fit to screen height
                    float height = 1f;
                    float width = (1f / screenAspect) * AspectRatio;
                    float widthDiff = 1f - width;

                    blitQuad(new Rect(widthDiff * 0.5f, 0f, width, height), final, dest, material, Preplaced_TV_OVERLAY);
                }
            }

            RenderTexture.ReleaseTemporary(preplaced1);
            RenderTexture.ReleaseTemporary(preplaced2);
            RenderTexture.ReleaseTemporary(lastComposite);
        }