示例#1
2
 public Terrain(Device device, String texture, int pitch, Renderer renderer)
 {
     HeightMap = new System.Drawing.Bitmap(@"Data/Textures/"+texture);
     WaterShader = new WaterShader(device);
     TerrainShader = new TerrainShader(device);
     _width = HeightMap.Width-1;
     _height = HeightMap.Height-1;
     _pitch = pitch;
     _terrainTextures = new ShaderResourceView[4];
     _terrainTextures[0] = new Texture(device, "Sand.png").TextureResource;
     _terrainTextures[1] = new Texture(device, "Grass.png").TextureResource;
     _terrainTextures[2] = new Texture(device, "Ground.png").TextureResource;
     _terrainTextures[3] = new Texture(device, "Rock.png").TextureResource;
     _reflectionClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
     _refractionClippingPlane = new Vector4(0.0f, -1.0f, 0.0f, 0.0f);
     _noClippingPlane = new Vector4(0.0f, 1.0f, 0.0f, 10000);
     _reflectionTexture = new RenderTexture(device, renderer.ScreenSize);
     _refractionTexture = new RenderTexture(device, renderer.ScreenSize);
     _renderer = renderer;
     _bitmap = new Bitmap(device,_refractionTexture.ShaderResourceView,renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap.Position = new Vector2I(renderer.ScreenSize.X - 100, 0);
     _bitmap2 = new Bitmap(device, _reflectionTexture.ShaderResourceView, renderer.ScreenSize, new Vector2I(100, 100), 0);
     _bitmap2.Position = new Vector2I(renderer.ScreenSize.X - 100, 120);
     _bumpMap = _renderer.TextureManager.Create("OceanWater.png");
     _skydome = new ObjModel(device, "skydome.obj", renderer.TextureManager.Create("Sky.png"));
     BuildBuffers(device);
     WaveTranslation = new Vector2(0,0);
 }
示例#2
0
	protected virtual void OnRenderImage(RenderTexture source, RenderTexture destination)
	{
		material.SetVector("_RedClamp", red);
		material.SetVector("_GreenClamp", green);
		material.SetVector("_BlueClamp", blue);
		Graphics.Blit(source, destination, material);
	}
示例#3
0
    Texture2D Capture(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
	static void CustomGraphicsBlit(RenderTexture src, RenderTexture dst, Material mat, int pass) {
		RenderTexture.active = dst;
		
		mat.SetTexture("_MainTex", src);
		
		GL.PushMatrix();
		GL.LoadOrtho();
		
		mat.SetPass(pass);
		
		GL.Begin(GL.QUADS);
		
		GL.MultiTexCoord2(0, 0.0f, 0.0f);
		GL.Vertex3(0.0f, 0.0f, 3.0f); // BL
		
		GL.MultiTexCoord2(0, 1.0f, 0.0f);
		GL.Vertex3(1.0f, 0.0f, 2.0f); // BR
		
		GL.MultiTexCoord2(0, 1.0f, 1.0f);
		GL.Vertex3(1.0f, 1.0f, 1.0f); // TR
		
		GL.MultiTexCoord2(0, 0.0f, 1.0f);
		GL.Vertex3(0.0f, 1.0f, 0.0f); // TL
		
		GL.End();
		GL.PopMatrix();
	}
示例#5
0
    /// <summary>
    /// 对相机截图。 
    /// </summary>
    /// <returns>The screenshot2.</returns>
    /// <param name="camera">Camera.要被截屏的相机</param>
    /// <param name="rect">Rect.截屏的区域</param>
    Texture2D CaptureCamera(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        Debug.Log(rect.width + " " + rect.height);
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //--- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //camera2.targetTexture = rt;
        //camera2.Render();
        //-------------------------------------------------------------------
        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        CacheFactory.SaveToPicture(screenShot, "/ScreenShot.png",CacheFactory.PictureType.JPG);
        return screenShot;
    }
示例#6
0
    void OnRenderImage( RenderTexture source ,   RenderTexture destination  )
    {
        #if UNITY_EDITOR
        FindShaders ();
        CheckSupport ();
        CreateMaterials ();
        #endif

        agonyTint = Mathf.Clamp01 (agonyTint - Time.deltaTime * 2.75f);

        RenderTexture tempRtLowA = RenderTexture.GetTemporary (source.width / 4, source.height / 4,0, rtFormat);
        RenderTexture tempRtLowB = RenderTexture.GetTemporary (source.width / 4, source.height / 4, 0,rtFormat);

        // prepare data

        apply.SetColor ("_ColorMix", colorMix);
        apply.SetVector ("_Parameter",new Vector4 (colorMixBlend * 0.25f,  0.0f, 0.0f, 1.0f - intensity - agonyTint));

        // downsample & blur

        Graphics.Blit (source, tempRtLowA, apply, agonyTint < 0.5f ? 1 : 5);
        Graphics.Blit (tempRtLowA, tempRtLowB, apply, 2);
        Graphics.Blit (tempRtLowB, tempRtLowA, apply, 3);

        // apply

        apply.SetTexture ("_Bloom", tempRtLowA);
        Graphics.Blit (source, destination, apply, QualityManager.quality > Quality.Medium ? 4 : 0);

        RenderTexture.ReleaseTemporary (tempRtLowA);
        RenderTexture.ReleaseTemporary (tempRtLowB);
    }
    // Use this for initialization
    void Awake()
    {
        GameObject go = new GameObject("depthCamera");
        depthCamera = go.AddComponent<Camera>();
        depthCamera.transform.position = Vector3.zero;
        depthCamera.transform.rotation = transform.rotation;
        depthCamera.transform.localPosition += transform.forward * Near;
        depthCamera.transform.parent = transform;
        depthCamera.isOrthoGraphic = true;

        depthCamera.clearFlags = CameraClearFlags.SolidColor;
        depthCamera.backgroundColor = Color.white;
        depthTexture = new RenderTexture(TextureSize,TextureSize, 16, RenderTextureFormat.ARGB32);
        depthTexture.filterMode = FilterMode.Point;
        depthCamera.targetTexture = depthTexture;
        depthCamera.SetReplacementShader(shader, null);
        depthCamera.enabled = false;
        biasMatrix = Matrix4x4.identity;
        biasMatrix[ 0, 0 ] = 0.5f;
        biasMatrix[ 1, 1 ] = 0.5f;
        biasMatrix[ 2, 2 ] = 0.5f;
        biasMatrix[ 0, 3 ] = 0.5f;
        biasMatrix[ 1, 3 ] = 0.5f;
        biasMatrix[ 2, 3 ] = 0.5f;
    }
 void LateUpdate()
 {
     if(_isActive != isActive)
     {
         _isActive = isActive;
         if(isActive)
         {
             depthTexture = new RenderTexture(TextureSize,TextureSize, 16, RenderTextureFormat.ARGB32);
             depthTexture.filterMode = FilterMode.Point;
         }else
         {
             RenderTexture.DestroyImmediate(depthTexture);
         }
     }
     if(isActive)
     {
         depthCamera.cullingMask = casterLayer;
         depthCamera.orthographicSize = Size;
         depthCamera.farClipPlane = Far;
         depthCamera.Render();
         Matrix4x4 depthProjectionMatrix = depthCamera.projectionMatrix;
         Matrix4x4 depthViewMatrix = depthCamera.worldToCameraMatrix;
         Matrix4x4 depthVP = depthProjectionMatrix * depthViewMatrix ;
         Matrix4x4 depthVPBias = biasMatrix * depthVP;
         Shader.SetGlobalMatrix("_depthVPBias", depthVPBias);
         Shader.SetGlobalMatrix("_depthV", depthViewMatrix);
         Shader.SetGlobalTexture("_kkShadowMap", depthCamera.targetTexture);
         Shader.SetGlobalFloat("_bias", Bias);
         Shader.SetGlobalFloat("_strength", 1 - Strength);
         Shader.SetGlobalFloat("_texmapScale", 1f/TextureSize);
         Shader.SetGlobalFloat("_farplaneScale", 1/Far);
     }
 }
示例#9
0
    // Called by camera to apply image effect
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Create the accumulation texture
        if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height)
        {
            DestroyImmediate(accumTexture);
            accumTexture = new RenderTexture(source.width, source.height, 0);
            accumTexture.hideFlags = HideFlags.HideAndDontSave;
            Graphics.Blit( source, accumTexture );
        }

        // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution.
        if (extraBlur)
        {
            RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
            Graphics.Blit(accumTexture, blurbuffer);
            Graphics.Blit(blurbuffer,accumTexture);
            RenderTexture.ReleaseTemporary(blurbuffer);
        }

        // Clamp the motion blur variable, so it can never leave permanent trails in the image
        blurAmount = Mathf.Clamp( blurAmount, 0.0f, 0.92f );

        // Setup the texture and floating point values in the shader
        material.SetTexture("_MainTex", accumTexture);
        material.SetFloat("_AccumOrig", 1.0F-blurAmount);

        // Render the image using the motion blur shader
        Graphics.Blit (source, accumTexture, material);
        Graphics.Blit (accumTexture, destination);
    }
 // Make a material that points to the target texture.  Texture scale
 // and offset will be controlled by rect.
 public void Create(RenderTexture target) {
   meshRenderer.material = new Material(Shader.Find("Cardboard/GUIScreen")) {
     mainTexture = target,
     mainTextureOffset = rect.position,
     mainTextureScale = rect.size
   };
 }
示例#11
0
    void OnRenderImage(RenderTexture src,RenderTexture dst)
    {
        RenderTexture blurTex = RenderTexture.GetTemporary(Screen.width /1, Screen.height / 1);
        //
        Graphics.Blit(src, blurTex, mat,0);
        //Graphics.Blit(blurTex, dst);
        RenderTexture buffer = RenderTexture.GetTemporary(src.width / 4, src.height / 4, 0);
        RenderTexture buffer2 = RenderTexture.GetTemporary(src.width / 4, src.height / 4, 0);

        DownSample4x(blurTex, buffer);//
        // Graphics.Blit(buffer, dst);
        bool oddEven = true;
        for (int i = 0; i < times; i++)
        {
            if (oddEven)
                FourTapCone(buffer, buffer2, i);
            else
                FourTapCone(buffer2, buffer, i);
            oddEven = !oddEven;
        }
        if (oddEven)
        {
            mat.SetTexture("_Energy", buffer);
            Graphics.Blit(src, dst,mat,1);
        }
        else
        {
            mat.SetTexture("_Energy", buffer2);
            Graphics.Blit(src, dst,mat,1);
        }
        RenderTexture.ReleaseTemporary(buffer);
        RenderTexture.ReleaseTemporary(buffer2);

        RenderTexture.ReleaseTemporary(blurTex);
    }
示例#12
0
文件: ShaderToy.cs 项目: rbrt/GGJ16
    void OnRenderImage (RenderTexture source, RenderTexture destination)
	{
		if (CheckResources()==false)
		{
            Graphics.Blit (source, destination);
            return;
        }

		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, material, 0);

		Debug.Log("MSKFNAN");

		if (!winner) {
			material.SetVector("iResolution",new Vector4(Screen.width,Screen.height,0,0));
			material.SetFloat("distFromOrigin", DistFromOrigin );
			material.SetVector("buddyPos",BuddyBoy.transform.position);
			material.SetFloat("distFromPath", DistFromPath );
			material.SetVector("camForward",BuddyBoy.transform.forward);
			material.SetVector("camRight",BuddyBoy.transform.right);
			material.SetVector("camUp",BuddyBoy.transform.up);
		}

		Graphics.Blit (rt, destination);
		RenderTexture.ReleaseTemporary (rt);
    }
示例#13
0
	public void OnDestroy() {
		GameObject.Destroy(_characterCamera.gameObject);

		GameObject.Destroy(_rTex);
		GameObject.Destroy(_canvasOverlay.gameObject);
		_rTex = null;
	}
	void OnRenderImage (RenderTexture source, RenderTexture destination){

		Graphics.Blit(source,destination,mat);
		//mat is the material which contains the shader
		//we are passing the destination RenderTexture to


		int width = Screen.width;
		int height = Screen.height;

		Debug.Log (width.ToString ());
		Debug.Log (height.ToString ());

		Texture2D tex = new Texture2D(width, height);
		tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);


		if (flag == true) {
			string[] blue = new string[width * height];

			for (int i = 0; i < height; i++) {
				for (int j=0; j < width; j++) {
					blue[(i * width) + j]  = tex.GetPixel (j, i).b.ToString ();
				}
			}
			string output = string.Join(",", blue);
			File.WriteAllText ("/Users/mettinger/Desktop/temp/output.txt", output);
			flag = false;
		}
		Debug.Log (tex.GetPixel(x,y).b.ToString());
	
	}
示例#15
0
    public Material Bake()
    {
        Camera camera = transform.FindChild("Camera").camera;
        RenderTexture render_texture = new RenderTexture(256, 256, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
        render_texture.useMipMap = true;
        render_texture.filterMode = FilterMode.Trilinear;
        render_texture.mipMapBias = -0.5f;
        camera.targetTexture = render_texture;

        transform.FindChild("Title").gameObject.layer = LayerMask.NameToLayer("Active Card Render Texture");
        transform.FindChild("Rules").gameObject.layer = LayerMask.NameToLayer("Active Card Render Texture");

        Transform tile_mesh = transform.FindChild("Tile_base").FindChild("default");
        Material material = new Material(tile_mesh.renderer.material);
        material.mainTexture = render_texture;

        camera.Render();

        transform.FindChild("Title").gameObject.layer = LayerMask.NameToLayer("Card Render Texture");
        transform.FindChild("Rules").gameObject.layer = LayerMask.NameToLayer("Card Render Texture");

        Material return_material = new Material(multiply);
        return_material.mainTexture = render_texture;

        return return_material;
    }
示例#16
0
 // Called by camera to apply image effect
 void OnRenderImage(RenderTexture source, RenderTexture destination)
 {
     base.material.SetFloat("_Intense1", intense1);
     base.material.SetFloat("_Intense2", intense2);
     base.material.SetFloat("_Count", count);
     Graphics.Blit (source, destination, material);
 }
	// Use this for initialization
	void Start ()
	{		
//		storedScreenWidth = Screen.width;
//		storedScreenHeight = Screen.height;
//		myRT = new RenderTexture(Screen.width, Screen.height, 24);
		
		storedScreenWidth = 1024;
		storedScreenHeight = 1024;
		myRT = new RenderTexture(1024, 1024, 24);
		
		myRT.format = RenderTextureFormat.ARGB32;
		myRT.filterMode = FilterMode.Point;
		myRT.isPowerOfTwo = false;
		myRT.isCubemap = false;
		myRT.Create();
		
		mat = new Material (
		"Shader \"Hidden/Invert\" {" +
		"SubShader {" +
		" Pass {" +
		" ZTest Always Cull Off ZWrite Off" +
		" SetTexture [_RenderTexy] { combine texture }" +
		" }" +
		"}" +
		"}"
		);
	}
示例#18
0
    // =============================================================================
    // =============================================================================
    // METHODS STATIC --------------------------------------------------------------
    private static void Render4TapQuad( RenderTexture dest, float offsetX, float offsetY )
    {
        GL.Begin( GL.QUADS );

        // Direct3D needs interesting texel offsets!
        Vector2 off = Vector2.zero;
        if( dest != null )
        {
            off = dest.GetTexelOffset()*0.75f;
        }

        Set4TexCoords( off.x, off.y, offsetX, offsetY );
        GL.Vertex3( 0f, 0f, 0.1f );

        Set4TexCoords( 1.0f + off.x, off.y, offsetX, offsetY );
        GL.Vertex3( 1f, 0f, 0.1f );

        Set4TexCoords( 1.0f + off.x, 1.0f + off.y, offsetX, offsetY );
        GL.Vertex3( 1f, 1f, 0.1f );

        Set4TexCoords( off.x, 1.0f + off.y, offsetX, offsetY );
        GL.Vertex3( 0f, 1f, 0.1f );

        GL.End();
    }
示例#19
0
    void Start()
    {

        child = GetComponentInChildren<MeshRenderer>();

        Vector3 parentScale = transform.parent.localScale;

        //make render texture that fits the object
        if(parentScale.x <= parentScale.y)
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * scaleFactor, Mathf.CeilToInt(parentScale.y) * scaleFactor, 0);
        else
            tex = new RenderTexture(Mathf.CeilToInt(parentScale.x) * scaleFactor, Mathf.CeilToInt(parentScale.y) * scaleFactor/2, 0);

        //tex.Create();

        tex.filterMode = FilterMode.Point;
        tex.anisoLevel = 0;

        tex.depth = (int)Depth;

        tex.filterMode = textureFilterMode;

        //tex.Create();

        //get camera
        cam = GetComponent<Camera>();
        cam.orthographicSize = parentScale.y/2;

        cam.targetTexture = tex;

        //cam.clearFlags = CameraClearFlags.Depth;

        child.material.mainTexture = tex;
    }
示例#20
0
 // Called by camera to apply image effect
 void OnRenderImage(RenderTexture source, RenderTexture destination)
 {
     //If you dont want to animate exposure and gamma, move them to Awake method
     base.material.SetFloat("_Exposure", exposure);
     base.material.SetFloat("_Gamma", gamma);
     Graphics.Blit (source, destination, material);
 }
示例#21
0
    void OnRenderImage(RenderTexture source, RenderTexture dest) 
    {
        if (m_Shader != null) 
        {
            Material.SetColor("_SephiaColor", m_Sephia);
            Material.SetFloat("_VignetteAmount", m_VignetteAmount);
            Material.SetFloat("_OldEffectAmount", m_OldEffectAmount);

            if (m_Vignette)
                Material.SetTexture("_Vignette", m_Vignette);

            if (m_Scratches)
            {
                Material.SetTexture("_Scratches", m_Scratches);
                Material.SetFloat("_ScratchesXSpeed", m_ScratchesXSpeed);
                Material.SetFloat("_ScratchesYSpeed", m_ScratchesYSpeed);
            }

            if (m_Dust)
            {
                Material.SetTexture("_Dust", m_Dust);
                Material.SetFloat("_DustXSpeed", m_DustXSpeed);
                Material.SetFloat("_DustYSpeed", m_DustYSpeed);
                Material.SetFloat("_RandomValue", m_RandomValue);
            }

            Graphics.Blit(source, dest, Material);
        }
        else
            Graphics.Blit(source, dest, null);

    }
示例#22
0
文件: BlurEffect.cs 项目: adenlb/FTJ
	// Called by the camera to apply the image effect
	void OnRenderImage (RenderTexture source, RenderTexture destination) {		
		RenderTexture buffer = RenderTexture.GetTemporary(source.width, source.height, 0);
		RenderTexture buffer2 = RenderTexture.GetTemporary(source.width, source.height, 0);
		
		// Copy source to the 4x4 smaller texture.
		DownSample4x (source, buffer);
		
		// Blur the small texture
		bool oddEven = true;
		for(int i = 0; i < iterations; i++)
		{
			if( oddEven )
				FourTapCone (buffer, buffer2, i);
			else
				FourTapCone (buffer2, buffer, i);
			oddEven = !oddEven;
		}
		if( oddEven )
			Graphics.Blit(buffer, destination);
		else
			Graphics.Blit(buffer2, destination);
		
		RenderTexture.ReleaseTemporary(buffer);
		RenderTexture.ReleaseTemporary(buffer2);
	}	
    public void CreateTextures()
    {
        if (texW == 0) texW = 1;//TODO rm
        if (texH == 0) texH = 1;
        if (texW == 0) throw new System.Exception("texW must be > 0");
        if (texH == 0) throw new System.Exception("texH must be > 0");
        texelSize = new Vector2(1f / texW, 1f / texH);
        maxTexelDistance = texelSize.magnitude;

        //Create textures
        texCur = new RenderTexture(texW, texH, 0, RenderTextureFormat.RFloat);
        texCur.enableRandomWrite = true;
        texCur.generateMips = false;
        texCur.Create();
        texDest = new RenderTexture(texW, texH, 0, RenderTextureFormat.RFloat);
        texDest.enableRandomWrite = true;
        texDest.generateMips = false;
        texCur.filterMode = FilterMode.Point;
        texDest.Create();

        //Clear textures
        Graphics.SetRenderTarget(texCur);
        GL.Clear(true, true, Color.white);
        Graphics.SetRenderTarget(texDest);
        GL.Clear(true, true, Color.white);
        Graphics.SetRenderTarget(null);

        //Instantiate material
        renderMaterial = new Material(visibilityOverlayMaterial);
        renderMaterial.SetTexture("_Mask", texCur);
    }
    void OnDisable()
    {
        if (volume!= null)
        {
            volume.Release();
            volume= null;
        }

        if (volumeBuffer != null)
        {
            volumeBuffer.Release();
            volumeBuffer = null;
        }

        if (targetBuffer != null)
        {
            targetBuffer.Release();
            targetBuffer = null;
        }
        /*
        if (particleColorBuffer != null)
        {
            particleColorBuffer.Release();
            particleColorBuffer = null;
        }
         */

        if (particleBuffer != null)
        {
            particleBuffer.Release();
            particleBuffer = null;
        }
    }
示例#25
0
    /// <summary>
    /// 对相机截图。 
    /// </summary>
    /// <returns>The screenshot2.</returns>
    /// <param name="camera">Camera.要被截屏的相机</param>
    /// <param name="rect">Rect.截屏的区域</param>
    public static Texture2D CaptureCamera(string _fileParentPath, string _fileName)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)Screen.width, (int)Screen.height, 24);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        Camera.main.targetTexture = rt;
        Camera.main.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        screenShot = new Texture2D((int)Screen.width * 3 / 4, (int)Screen.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(new Rect(Screen.width * 1 / 8, 0, Screen.width * 3 / 4, Screen.height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        Camera.main.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件
        //byte[] bytes = screenShot.EncodeToPNG();
        byte[] bytes = screenShot.EncodeToJPG();
        string filename = _fileParentPath + _fileName;
        System.IO.File.WriteAllBytes(filename, bytes);

        return screenShot;
    }
    public static void ComputeFocusScores(RenderTexture instanceIdBuffer, RenderTexture depthBuffer)
    {
        //ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(3, "_ClearBuffer", GPUBuffers.Get.ProteinFocusScore);
        //ComputeShaderManager.Get.ComputeColorInfo.Dispatch(3, Mathf.CeilToInt(SceneManager.Get.NumLipidInstances / 64.0f), 1, 1);

        ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(3, "_ClearBuffer", GPUBuffers.Get.ProteinFocusScore);
        ComputeShaderManager.Get.ComputeColorInfo.Dispatch(3, Mathf.CeilToInt(SceneManager.Get.NumProteinInstances / 64.0f), 1, 1);
        

        //*************************************************//

        GPUBuffers.Get.IngredientsColorInfo.SetData(CPUBuffers.Get.IngredientsDisplayInfo.ToArray());
        GPUBuffers.Get.IngredientGroupsColorInfo.SetData(CPUBuffers.Get.IngredientGroupsDisplayInfo.ToArray());

        ComputeShaderManager.Get.ComputeColorInfo.SetInt("_Width", instanceIdBuffer.width);
        ComputeShaderManager.Get.ComputeColorInfo.SetInt("_Height", instanceIdBuffer.height);


        ComputeShaderManager.Get.ComputeColorInfo.SetTexture(4, "_DepthBuffer", depthBuffer);
        ComputeShaderManager.Get.ComputeColorInfo.SetTexture(4, "_InstanceIdBuffer", instanceIdBuffer);

        //ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(4, "_IngredientsInfo", GPUBuffers.Get.IngredientsInfo);
        //ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(4, "_LipidInstancesInfo", GPUBuffers.Get.LipidInstancesInfo);
        ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(4, "_ProteinInstancesInfo", GPUBuffers.Get.ProteinInstancesInfo);
        ComputeShaderManager.Get.ComputeColorInfo.SetBuffer(4, "_RWProteinFocusScore", GPUBuffers.Get.IngredientsColorInfo);

        ComputeShaderManager.Get.ComputeColorInfo.Dispatch(4, Mathf.CeilToInt(instanceIdBuffer.width / 8.0f), Mathf.CeilToInt(instanceIdBuffer.height / 8.0f), 1);
    }
示例#27
0
    // Use this for initialization
    void Start()
    {
        //eyeDistance_s = S3DVM.eyeDistance;
        //focalDistance_s = S3DVM.focalDistance;

        camera = GetComponent<Camera>();

        //leftEye = new GameObject ("leftEye");
        //rightEye = new GameObject ("rightEye");

        //leftEye.AddComponent<Camera>();
        //rightEye.AddComponent<Camera>();

        //leftEye.GetComponent<Camera>().CopyFrom (camera);
        //rightEye.GetComponent<Camera>().CopyFrom (camera);

        FrontRT = new RenderTexture ((int)(Screen.width*textureResolution), (int)(Screen.height*textureResolution), 24);
        BackRT = new RenderTexture ((int)(Screen.width*textureResolution), (int)(Screen.height*textureResolution), 24);

        FrontCam.GetComponent<Camera>().targetTexture = FrontRT;
        BackCam.GetComponent<Camera>().targetTexture = BackRT;

        MergedCameras.SetTexture ("_FrontTex", FrontRT);
        MergedCameras.SetTexture ("_BackTex", BackRT);
    }
示例#28
0
    // Called by camera to apply image effect
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        material.SetFloat("_PixelWidth", pixelWidth);
        material.SetFloat("_PixelHeight", pixelHeight);

        Graphics.Blit (source, destination, material, 0);
    }
示例#29
0
 IEnumerator Screenshot()
 {
     if (!Directory.Exists(outPath))
     {
         Directory.CreateDirectory(outPath);
     }
     while (record)
     {
         /*counter++;
         Application.CaptureScreenshot(outPath + counter.ToString("D8") + ".png", 0);
         UnityEngine.Debug.Log("PNG Created " + counter);
         yield return new WaitForSeconds(recordStep);*/
         counter++;
         RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
         camera.targetTexture = rt;
         Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
         camera.Render();
         RenderTexture.active = rt;
         screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
         camera.targetTexture = null;
         RenderTexture.active = null; // JC: added to avoid errors
         Destroy(rt);
         byte[] bytes = screenShot.EncodeToPNG();
         string filename = outPath + counter.ToString("D8") + ".png";//8 didget naming scheme limits us to videos roughly 28.9 days long
         System.IO.File.WriteAllBytes(filename, bytes);
         UnityEngine.Debug.Log(string.Format("Took screenshot to: {0}", filename));
         yield return new WaitForSeconds(recordStep);
         }
     yield break;
 }
示例#30
0
文件: VJ04Vfx.cs 项目: Garridus/VJ04
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (_material == null) {
            _material = new Material(_shader);
            _material.hideFlags = HideFlags.DontSave;
        }

        if (_noise > 0.01f || _invert > 0.01f || _whiteout > 0.01f)
        {
            if (_noise > 0.01f)
            {
                _material.EnableKeyword("NOISE_ON");
                _material.SetFloat("_NoiseThreshold", Mathf.Clamp01(1.0f - _noise * 1.2f));
                _material.SetFloat("_NoiseDisplace", 0.01f + Mathf.Pow(_noise, 3) * 0.1f);
            }
            else
            {
                _material.DisableKeyword("NOISE_ON");
            }

            _material.SetFloat("_Invert", _invert);
            _material.SetFloat("_Whiteout", _whiteout);

            Graphics.Blit(source, destination, _material);
        }
        else
        {
            Graphics.Blit(source, destination);
        }
    }
示例#31
0
    public void PostProcess(RenderTexture source, RenderTexture destination)
    {
        Vector4 blurStep = Vector4.zero;

        blurStep.x = MaxVelocity / 1000.0f;
        blurStep.y = MaxVelocity / 1000.0f;

        RenderTexture dilatedRT = null;

        if (QualitySettings.antiAliasing > 1)
        {
            dilatedRT            = RenderTexture.GetTemporary(m_width, m_height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            dilatedRT.name       = "AM-DilatedTemp";
            dilatedRT.filterMode = FilterMode.Point;

            m_dilationMaterial.SetTexture("_MotionTex", m_motionRT);
            Graphics.Blit(m_motionRT, dilatedRT, m_dilationMaterial, 0);
            m_dilationMaterial.SetTexture("_MotionTex", dilatedRT);
            Graphics.Blit(dilatedRT, m_motionRT, m_dilationMaterial, 1);
        }

        if (DebugMode)
        {
            m_debugMaterial.SetTexture("_MotionTex", m_motionRT);
            Graphics.Blit(source, destination, m_debugMaterial);
        }
        else
        {
            ApplyMotionBlur(source, destination, blurStep);
        }

        if (dilatedRT != null)
        {
            RenderTexture.ReleaseTemporary(dilatedRT);
        }
    }
示例#32
0
    // Called by camera to apply image effect
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Create the accumulation texture
        if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height)
        {
            DestroyImmediate(accumTexture);
            accumTexture           = new RenderTexture(source.width, source.height, 0);
            accumTexture.hideFlags = HideFlags.HideAndDontSave;
            Graphics.Blit(source, accumTexture);
        }

        // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution.
        if (extraBlur)
        {
            RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
            accumTexture.MarkRestoreExpected();
            Graphics.Blit(accumTexture, blurbuffer);
            Graphics.Blit(blurbuffer, accumTexture);
            RenderTexture.ReleaseTemporary(blurbuffer);
        }

        // Clamp the motion blur variable, so it can never leave permanent trails in the image
        blurAmount = Mathf.Clamp(blurAmount, 0.0f, 0.92f);

        // Setup the texture and floating point values in the shader
        material.SetTexture("_MainTex", accumTexture);
        material.SetFloat("_AccumOrig", 1.0F - blurAmount);

        // We are accumulating motion over frames without clear/discard
        // by design, so silence any performance warnings from Unity
        accumTexture.MarkRestoreExpected();

        // Render the image using the motion blur shader
        Graphics.Blit(source, accumTexture, material);
        Graphics.Blit(accumTexture, destination);
    }
        private void OnRenderImage(RenderTexture sourceTexture, RenderTexture destTexture)
        {
            if (m_Material == null)
            {
                m_Material  = new Material(m_Shader);
                m_Supported = m_Shader.isSupported;
            }

            if (m_Material != null && m_Supported)
            {
#if UNITY_EDITOR
                if (!UnityEditor.EditorApplication.isPlaying && !m_PreviewCorrection)
                {
                    Graphics.Blit(sourceTexture, destTexture);
                    return;
                }
#endif
                Graphics.Blit(sourceTexture, destTexture, m_Material);
            }
            else
            {
                Graphics.Blit(sourceTexture, destTexture);
            }
        }
示例#34
0
        public void Blur(RenderTexture src, int nIterations)
        {
            var tmp0  = RenderTexture.GetTemporary(src.width, src.height, 0, src.format);
            var tmp1  = RenderTexture.GetTemporary(src.width, src.height, 0, src.format);
            var iters = Mathf.Clamp(nIterations, 0, 10);

            Graphics.Blit(src, tmp0);
            for (var i = 0; i < iters; i++)
            {
                for (var pass = 2; pass < 4; pass++)
                {
                    tmp1.DiscardContents();
                    tmp0.filterMode = FilterMode.Bilinear;
                    Graphics.Blit(tmp0, tmp1, material, pass);
                    var tmpSwap = tmp0;
                    tmp0 = tmp1;
                    tmp1 = tmpSwap;
                }
            }
            Graphics.Blit(tmp0, src);

            RenderTexture.ReleaseTemporary(tmp0);
            RenderTexture.ReleaseTemporary(tmp1);
        }
示例#35
0
    public static Texture2D Scale(Texture sourceTex, int targetWidth, int targetHeight, TextureFormat format = TextureFormat.RGBA32, Options options = new Options())
    {
        if (sourceTex == null)
        {
            throw new ArgumentException("Parameter 'sourceTex' is null!");
        }

        Texture2D result = null;

        RenderTexture rt       = RenderTexture.GetTemporary(targetWidth, targetHeight);
        RenderTexture activeRT = RenderTexture.active;

        try
        {
            Graphics.Blit(sourceTex, rt);
            RenderTexture.active = rt;

            result = new Texture2D(targetWidth, targetHeight, format, options.generateMipmaps, options.linearColorSpace);
            result.ReadPixels(new Rect(0, 0, targetWidth, targetHeight), 0, 0, false);
            result.Apply(options.generateMipmaps, options.markNonReadable);
        }
        catch (Exception e)
        {
            Debug.LogException(e);

            Object.Destroy(result);
            result = null;
        }
        finally
        {
            RenderTexture.active = activeRT;
            RenderTexture.ReleaseTemporary(rt);
        }

        return(result);
    }
示例#36
0
        private void Start()
        {
            activeRT = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
            {
                dimension       = UnityEngine.Rendering.TextureDimension.Tex2D,
                antiAliasing    = 1,
                useMipMap       = false,
                useDynamicScale = false,
                wrapMode        = TextureWrapMode.Clamp,
                filterMode      = FilterMode.Bilinear
            };

            activeRT.Create();

            Camera = GetComponentInChildren <Camera>();
            Camera.targetTexture = activeRT;
            Camera.fieldOfView   = FieldOfView;
            Camera.nearClipPlane = MinDistance;
            Camera.farClipPlane  = MaxDistance;

            AAWireBoxes        = gameObject.AddComponent <AAWireBox>();
            AAWireBoxes.Camera = Camera;

            nextSend = Time.time + 1.0f / Frequency;

            var radHFOV = 2 * Mathf.Atan(Mathf.Tan(Camera.fieldOfView * Mathf.Deg2Rad / 2) * Camera.aspect);

            degHFOV = Mathf.Rad2Deg * radHFOV;

            BoxCollider camBoxCollider = cameraRangeTrigger.GetComponent <BoxCollider>();

            camBoxCollider.center = new Vector3(0, 0, DetectionRange / 2f);
            camBoxCollider.size   = new Vector3(2 * Mathf.Tan(radHFOV / 2) * DetectionRange, 3f, DetectionRange);

            cameraRangeTrigger.SetCallbacks(OnCollider);
        }
示例#37
0
    static void creat()
    {
        try
        {
            GameObject g = GameObject.Instantiate(Resources.Load<GameObject>("A"));
            g.name = "CameraRender";
            var tex = new RenderTexture(1, 1, 1);
            if (!Directory.Exists(Path.Combine(Application.dataPath, "renderTexture"))) Directory.CreateDirectory((Path.Combine(Application.dataPath, "renderTexture")));

            AssetDatabase.CreateAsset(tex, "Assets/renderTexture/" + g.name + ".renderTexture");
            g.GetComponent<Camera>().targetTexture = tex;
        }
        catch (Exception)
        {
            Debug.LogWarning("此功能需要在代码中定制");
          
        }


        // Add an animation clip to it
        //添加一个动画剪辑到材质上
        //var animationClip = new AnimationClip();
        //animationClip.name = "My Clip";
        //AssetDatabase.AddObjectToAsset(animationClip, material);

        //// Reimport the asset after adding an object.
        ////在新建一个对象后重新导入资源
        //// Otherwise the change only shows up when saving the project
        ////否则这个更改只会在保存工程时才显示
        //AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(animationClip));

        //// Print the path of the created asset
        ////打印新建的资源
        //Debug.Log(AssetDatabase.GetAssetPath(material));

    }
	void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
	{
		if(SCShader != null)
		{
			TimeX+=Time.deltaTime;
			if (TimeX>100)  TimeX=0;
			material.SetFloat("_TimeX", TimeX);
			material.SetFloat("_Value",  Mathf.Clamp(Blood_On_Screen,0.02f,1.6f));
			material.SetFloat("_Value2", Mathf.Clamp(Blood_Intensify,0,2f));
			material.SetFloat("_Value3", Mathf.Clamp(Blood_Darkness,0,2f));
			material.SetFloat("_Value4", Mathf.Clamp(Blood_Fade,0,1f));
            material.SetFloat("_Value5", Mathf.Clamp(Blood_Distortion_Speed,0,2f));
			material.SetColor("_Color2", Blood_Color);
			material.SetTexture("_MainTex2", Texture2);

			Graphics.Blit(sourceTexture, destTexture, material);
		}
		else
		{
			Graphics.Blit(sourceTexture, destTexture);	
		}
		
		
	}
示例#39
0
        public static Texture CreateDataTexture(int width, int height, int depth, GraphicsFormat format, string name, bool allocateRendertexture, ref int allocatedBytes)
        {
            int elementSize = format == GraphicsFormat.R16G16B16A16_SFloat ? 8 :
                              format == GraphicsFormat.R8G8B8A8_UNorm ? 4 : 1;

            Texture texture;

            allocatedBytes += (width * height * depth) * elementSize;
            if (allocateRendertexture)
            {
                texture = new RenderTexture(new RenderTextureDescriptor()
                {
                    width             = width,
                    height            = height,
                    volumeDepth       = depth,
                    graphicsFormat    = format,
                    mipCount          = 1,
                    enableRandomWrite = true,
                    dimension         = TextureDimension.Tex3D,
                    msaaSamples       = 1,
                });
            }
            else
            {
                texture = new Texture3D(width, height, depth, format, TextureCreationFlags.None, 1);
            }

            texture.hideFlags = HideFlags.HideAndDontSave;
            texture.name      = name;

            if (allocateRendertexture)
            {
                (texture as RenderTexture).Create();
            }
            return(texture);
        }
示例#40
0
        //-------------------------------------------------------------------//
        // Main entry point                                                  //
        //-------------------------------------------------------------------//
        public void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
            {
                Graphics.Blit(source, destination);
                return;
            }

            if (visualizeBluriness)
            {
                Vector4 blurrinessParam;
                Vector4 blurrinessCoe;
                ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
                filmicDepthOfFieldMaterial.SetVector("_BlurParams", blurrinessParam);
                filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
                Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (uiMode == UIMode.Explicit) ? (int)Passes.VisualizeCocExplicit : (int)Passes.VisualizeCoc);
            }
            else
            {
                DoDepthOfField(source, destination);
            }

            m_RTU.ReleaseAllTemporyRenderTexutres();
        }
示例#41
0
    void LateUpdate()
    {
        transform.position = drone.transform.position + offset;
        Camera camera = GameObject.Find("Main Camera").GetComponent <Camera>();

        takeHiResShot |= Input.GetKeyDown("k");
        if (takeHiResShot)
        {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camera.targetTexture = null;
            RenderTexture.active = null; // JC: added to avoid errors
            Destroy(rt);
            byte[] bytes    = screenShot.EncodeToPNG();
            string filename = ScreenShotName(resWidth, resHeight);
            System.IO.File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            takeHiResShot = false;
        }
    }
示例#42
0
        //-------------------------------------------------------------------//
        // Blurs                                                             //
        //-------------------------------------------------------------------//
        private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
        {
            ComputeBlurDirections(false);

            int blurPass;
            int blurPassMerge;

            GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
            filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
            RenderTexture tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);


            filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection1);
            Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);

            filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection2);
            Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);

            filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection3);
            filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", src);
            Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
            m_RTU.ReleaseTemporaryRenderTexture(tmp);
            SwapRenderTexture(ref src, ref dst);
        }
示例#43
0
        void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (State != RecorderState.Recording)
            {
                Graphics.Blit(source, destination);
                return;
            }

            m_Time += Time.unscaledDeltaTime;

            if (m_Time >= m_TimePerFrame)
            {
                // Limit the amount of frames stored in memory
                if (m_Frames.Count >= m_MaxFrameCount)
                    m_RecycledRenderTexture = m_Frames.Dequeue();

                m_Time -= m_TimePerFrame;

                // Frame data
                RenderTexture rt = m_RecycledRenderTexture;
                m_RecycledRenderTexture = null;

                if (rt == null)
                {
                    rt = new RenderTexture(m_Width, m_Height, 0, RenderTextureFormat.ARGB32);
                    rt.wrapMode = TextureWrapMode.Clamp;
                    rt.filterMode = FilterMode.Bilinear;
                    rt.anisoLevel = 0;
                }

                Graphics.Blit(source, rt);
                m_Frames.Enqueue(rt);
            }

            Graphics.Blit(source, destination);
        }
示例#44
0
        void CheckInternalLogLut()
        {
            // Check internal lut state, (re)create it if needed
            if (m_InternalLogLut == null || !m_InternalLogLut.IsCreated())
            {
                RuntimeUtilities.Destroy(m_InternalLogLut);

                var format = GetLutFormat();
                m_InternalLogLut = new RenderTexture(k_Lut3DSize, k_Lut3DSize, 0, format, RenderTextureReadWrite.Linear)
                {
                    name              = "Color Grading Log Lut",
                    hideFlags         = HideFlags.DontSave,
                    filterMode        = FilterMode.Bilinear,
                    wrapMode          = TextureWrapMode.Clamp,
                    anisoLevel        = 0,
                    enableRandomWrite = true,
                    volumeDepth       = k_Lut3DSize,
                    dimension         = TextureDimension.Tex3D,
                    autoGenerateMips  = false,
                    useMipMap         = false
                };
                m_InternalLogLut.Create();
            }
        }
示例#45
0
        private static void DrawLowLevelQuad(float x1, float x2, float y1, float y2, RenderTexture source, RenderTexture dest, Material material)
        {
            RenderTexture.active = dest;
            material.SetTexture("_MainTex", source);
            bool flag = true;

            GL.PushMatrix();
            GL.LoadOrtho();
            for (int i = 0; i < material.passCount; i++)
            {
                float num2;
                float num3;
                material.SetPass(i);
                GL.Begin(7);
                if (flag)
                {
                    num2 = 1f;
                    num3 = 0f;
                }
                else
                {
                    num2 = 0f;
                    num3 = 1f;
                }
                GL.TexCoord2(0f, num2);
                GL.Vertex3(x1, y1, 0.1f);
                GL.TexCoord2(1f, num2);
                GL.Vertex3(x2, y1, 0.1f);
                GL.TexCoord2(1f, num3);
                GL.Vertex3(x2, y2, 0.1f);
                GL.TexCoord2(0f, num3);
                GL.Vertex3(x1, y2, 0.1f);
                GL.End();
            }
            GL.PopMatrix();
        }
 void OnRenderImage(RenderTexture sourceTexture, RenderTexture destTexture)
 {
     if (SCShader != null)
     {
         TimeX += Time.deltaTime;
         if (TimeX > 100)
         {
             TimeX = 0;
         }
         if (Camera2 != null)
         {
             material.SetTexture("_MainTex2", Camera2tex);
         }
         material.SetFloat("_TimeX", TimeX);
         material.SetFloat("_Value", BlendFX);
         material.SetFloat("_Value2", SwitchCameraToCamera2);
         material.SetVector("_ScreenResolution", new Vector4(sourceTexture.width, sourceTexture.height, 0.0f, 0.0f));
         Graphics.Blit(sourceTexture, destTexture, material);
     }
     else
     {
         Graphics.Blit(sourceTexture, destTexture);
     }
 }
 static void RemoveCommandBuffer(Camera cam)
 {
     if (sm_cameraCommands.ContainsKey(cam))
     {
         var cameraCommands = sm_cameraCommands[cam];
         if (cameraCommands.fluidDepths.Count > 0)
         {
             foreach (var cb in cameraCommands.fluidDepths)
             {
                 RenderTexture.ReleaseTemporary(cb);
             }
             cameraCommands.fluidDepths.Clear();
         }
         else
         {
             cam.RemoveCommandBuffer(CAMERA_EVENT, cameraCommands.copyBackground);
             sm_cameraCommands.Remove(cam);
             if (sm_cameraCommands.Count == 0)
             {
                 Camera.onPostRender -= RemoveCommandBuffer;
             }
         }
     }
 }
示例#48
0
        /// <summary>
        /// Conversion video format to stereo.
        /// </summary>
        protected void SetStereoVideoFormat(RenderTexture frameRenderTexture)
        {
            Vector3 cameraPosition = captureCamera.transform.position;

            // Left eye
            captureCamera.transform.Translate(new Vector3(-interPupillaryDistance, 0, 0), Space.Self);
            RenderCameraToRenderTexture(captureCamera, frameRenderTexture, stereoTargetTexture);
            if (stereoFormat == StereoType.TOP_BOTTOM)
            {
                stereoPackMaterial.DisableKeyword("STEREOPACK_BOTTOM");
                stereoPackMaterial.EnableKeyword("STEREOPACK_TOP");
            }
            else if (stereoFormat == StereoType.LEFT_RIGHT)
            {
                stereoPackMaterial.DisableKeyword("STEREOPACK_RIGHT");
                stereoPackMaterial.EnableKeyword("STEREOPACK_LEFT");
            }
            Graphics.Blit(stereoTargetTexture, finalTargetTexture, stereoPackMaterial);
            // Right eye
            captureCamera.transform.localPosition = cameraPosition;
            captureCamera.transform.Translate(new Vector3(interPupillaryDistance, 0f, 0f), Space.Self);
            RenderCameraToRenderTexture(captureCamera, frameRenderTexture, stereoTargetTexture);
            if (stereoFormat == StereoType.TOP_BOTTOM)
            {
                stereoPackMaterial.EnableKeyword("STEREOPACK_BOTTOM");
                stereoPackMaterial.DisableKeyword("STEREOPACK_TOP");
            }
            else if (stereoFormat == StereoType.LEFT_RIGHT)
            {
                stereoPackMaterial.EnableKeyword("STEREOPACK_RIGHT");
                stereoPackMaterial.DisableKeyword("STEREOPACK_LEFT");
            }
            Graphics.Blit(stereoTargetTexture, finalTargetTexture, stereoPackMaterial);
            // Restore camera state
            captureCamera.transform.localPosition = cameraPosition;
        }
 private void BlurFg(RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread)
 {
     this.dofBlurMaterial.SetTexture("_TapHigh", from);
     RenderTexture temporary = RenderTexture.GetTemporary(to.width, to.height);
     if (iterations <= DofBlurriness.Low)
     {
         this.dofBlurMaterial.SetVector("offsets", new Vector4(0f, spread * this.oneOverBaseSize, 0f, 0f));
         Graphics.Blit(from, temporary, this.dofBlurMaterial, blurPass);
         this.dofBlurMaterial.SetVector("offsets", new Vector4((spread / this.widthOverHeight) * this.oneOverBaseSize, 0f, 0f, 0f));
         Graphics.Blit(temporary, to, this.dofBlurMaterial, blurPass);
     }
     else
     {
         this.BlurHex(from, to, blurPass, spread, temporary);
         if (iterations > DofBlurriness.High)
         {
             this.dofBlurMaterial.SetVector("offsets", new Vector4(0f, spread * this.oneOverBaseSize, 0f, 0f));
             Graphics.Blit(to, temporary, this.dofBlurMaterial, blurPass);
             this.dofBlurMaterial.SetVector("offsets", new Vector4((spread / this.widthOverHeight) * this.oneOverBaseSize, 0f, 0f, 0f));
             Graphics.Blit(temporary, to, this.dofBlurMaterial, blurPass);
         }
     }
     RenderTexture.ReleaseTemporary(temporary);
 }
示例#50
0
        void StepKernel(float deltaTime)
        {
            // GPGPU buffer swap
            var pb = _positionBuffer1;
            var vb = _velocityBuffer1;

            _positionBuffer1 = _positionBuffer2;
            _velocityBuffer1 = _velocityBuffer2;
            _positionBuffer2 = pb;
            _velocityBuffer2 = vb;

            // private state update
            _noiseOffset += (_flow + Vector3.one * _noiseMotion) * deltaTime;

            // invoking velocity update kernel
            UpdateKernelShader(deltaTime);
            _kernelMaterial.SetTexture("_PositionTex", _positionBuffer1);
            _kernelMaterial.SetTexture("_VelocityTex", _velocityBuffer1);
            Graphics.Blit(null, _velocityBuffer2, _kernelMaterial, 3);

            // invoking position update kernel
            _kernelMaterial.SetTexture("_VelocityTex", _velocityBuffer2);
            Graphics.Blit(null, _positionBuffer2, _kernelMaterial, 2);
        }
        void Initialize()
        {
            if (m_TempRenderTexture == null)
            {
                // Temporary RT used for convolution and compression
                m_TempRenderTexture                  = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);
                m_TempRenderTexture.hideFlags        = HideFlags.HideAndDontSave;
                m_TempRenderTexture.dimension        = TextureDimension.Tex2D;
                m_TempRenderTexture.useMipMap        = true;
                m_TempRenderTexture.autoGenerateMips = false;
                m_TempRenderTexture.name             = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflectionTemp", mips: true);
                m_TempRenderTexture.Create();

                m_ConvolutionTargetTexture                  = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);
                m_ConvolutionTargetTexture.hideFlags        = HideFlags.HideAndDontSave;
                m_ConvolutionTargetTexture.dimension        = TextureDimension.Tex2D;
                m_ConvolutionTargetTexture.useMipMap        = true;
                m_ConvolutionTargetTexture.autoGenerateMips = false;
                m_ConvolutionTargetTexture.name             = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
                m_ConvolutionTargetTexture.Create();

                InitializeProbeBakingStates();
            }
        }
    void OnRenderImage(RenderTexture sourceTexture, RenderTexture destTexture)
    {
        if (SCShader != null)
        {
            TimeX += Time.deltaTime;
            if (TimeX > 100)
            {
                TimeX = 0;
            }
            material.SetFloat("_TimeX", TimeX);
            material.SetFloat("_Value", Fade);
            material.SetFloat("_Value2", Intensity);

            material.SetFloat("_Value4", Speed * 6);
            material.SetFloat("_Value5", Size);


            material.SetFloat("_FixDistance", _FixDistance);

            material.SetFloat("Drop_Near", Snow_Near);
            material.SetFloat("Drop_Far", Snow_Far);
            material.SetFloat("Drop_With_Obj", SnowWithoutObject);
            material.SetFloat("Myst", Myst);
            material.SetColor("Myst_Color", Myst_Color);

            material.SetVector("_ScreenResolution", new Vector4(sourceTexture.width, sourceTexture.height, 0.0f, 0.0f));
            material.SetTexture("Texture2", Texture2);
            GetComponent <Camera>().depthTextureMode = DepthTextureMode.Depth;

            Graphics.Blit(sourceTexture, destTexture, material);
        }
        else
        {
            Graphics.Blit(sourceTexture, destTexture);
        }
    }
示例#53
0
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        SetUpObjects();

        // Update old frame buffers with the constant interval.
        if ((frameCount % 13) == 0)
        {
            Graphics.Blit(source, oldFrame1);
        }
        if ((frameCount % 73) == 0)
        {
            Graphics.Blit(source, oldFrame2);
        }

        // Set up the material.
        material.SetFloat("_Intensity", _intensity);
        material.SetTexture("_GlitchTex", noiseTexture);
        material.SetTexture("_BufferTex", Random.value > 0.5f ? oldFrame1 : oldFrame2);

        // Glitch it!
        Graphics.Blit(source, destination, material);

        frameCount++;
    }
示例#54
0
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (material != null)
        {
            if (accumulationTexture == null || accumulationTexture.width != src.width || accumulationTexture.height != src.height)
            {
                DestroyImmediate(accumulationTexture);
                accumulationTexture           = new RenderTexture(src.width, src.height, 0);
                accumulationTexture.hideFlags = HideFlags.HideAndDontSave;
                Graphics.Blit(src, accumulationTexture);
            }

            accumulationTexture.MarkRestoreExpected();

            material.SetFloat("_BlurAmount", 1.0f - blurAmount);

            Graphics.Blit(src, accumulationTexture, material);
            Graphics.Blit(accumulationTexture, dest);
        }
        else
        {
            Graphics.Blit(src, dest);
        }
    }
示例#55
0
    void CreateTexture(ref RenderTexture texture, int resolution, string name)
    {
        var format = UnityEngine.Experimental.Rendering.GraphicsFormat.R16G16B16A16_UNorm;

        if (texture == null || !texture.IsCreated() || texture.width != resolution || texture.height != resolution || texture.volumeDepth != resolution || texture.graphicsFormat != format)
        {
            //Debug.Log ("Create tex: update noise: " + updateNoise);
            if (texture != null)
            {
                texture.Release();
            }
            texture = new RenderTexture(resolution, resolution, 0);
            texture.graphicsFormat    = format;
            texture.volumeDepth       = resolution;
            texture.enableRandomWrite = true;
            texture.dimension         = UnityEngine.Rendering.TextureDimension.Tex3D;
            texture.name = name;

            texture.Create();
            Load(name, texture);
        }
        texture.wrapMode   = TextureWrapMode.Repeat;
        texture.filterMode = FilterMode.Bilinear;
    }
示例#56
0
文件: Bloom.cs 项目: K07H/The-Forest
        public RenderTexture CreateBloomTexture(RenderTexture halfResSource, BloomParameters bloomParams)
        {
            if (this.numDownsamples != bloomParams.downsamples)
            {
                this.numDownsamples  = bloomParams.downsamples;
                this.m_bloomTextures = new RenderTexture[this.numDownsamples];
            }
            halfResSource.filterMode = FilterMode.Bilinear;
            RenderTextureFormat format = halfResSource.format;
            int num  = halfResSource.width;
            int num2 = halfResSource.height;

            for (int i = 0; i < this.numDownsamples; i++)
            {
                this.m_bloomTextures[i]            = RenderTexture.GetTemporary(num, num2, 0, format);
                this.m_bloomTextures[i].filterMode = FilterMode.Bilinear;
                this.m_bloomTextures[i].wrapMode   = TextureWrapMode.Clamp;
                num  /= 2;
                num2 /= 2;
            }
            halfResSource.filterMode = FilterMode.Bilinear;
            RenderTexture source = halfResSource;

            for (int j = 1; j < this.numDownsamples; j++)
            {
                Graphics.Blit(source, this.m_bloomTextures[j], this.m_bloomMat, 0);
                source = this.m_bloomTextures[j];
            }
            for (int k = this.numDownsamples - 1; k > 1; k--)
            {
                Graphics.Blit(this.m_bloomTextures[k], this.m_bloomTextures[k - 1], this.m_bloomMat, 1);
            }
            this.m_bloomMat.SetFloat("_EnergyNormalizer", 1f / (float)this.numDownsamples);
            Graphics.Blit(this.m_bloomTextures[1], this.m_bloomTextures[0], this.m_bloomMat, 2);
            return(this.m_bloomTextures[0]);
        }
示例#57
0
        private void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
            {
                Graphics.Blit(source, destination);
                return;
            }

            if (settings.visualizeFocus)
            {
                Vector4 blurrinessParam;
                Vector4 blurrinessCoe;
                ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
                filmicDepthOfFieldMaterial.SetVector(m_BlurParams, blurrinessParam);
                filmicDepthOfFieldMaterial.SetVector(m_BlurCoe, blurrinessCoe);
                Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (int)Passes.VisualizeCocExplicit);
            }
            else
            {
                DoDepthOfField(source, destination);
            }

            m_RTU.ReleaseAllTemporaryRenderTextures();
        }
示例#58
0
 private void OnRenderImage(RenderTexture source, RenderTexture destination)
 {
     if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height)
     {
         DestroyImmediate(accumTexture);
         accumTexture           = new RenderTexture(source.width, source.height, 0);
         accumTexture.hideFlags = HideFlags.HideAndDontSave;
         Graphics.Blit(source, accumTexture);
     }
     if (extraBlur)
     {
         RenderTexture temporary = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
         accumTexture.MarkRestoreExpected();
         Graphics.Blit(accumTexture, temporary);
         Graphics.Blit(temporary, accumTexture);
         RenderTexture.ReleaseTemporary(temporary);
     }
     blurAmount = Mathf.Clamp(blurAmount, 0f, 0.92f);
     material.SetTexture("_MainTex", accumTexture);
     material.SetFloat("_AccumOrig", 1f - blurAmount);
     accumTexture.MarkRestoreExpected();
     Graphics.Blit(source, accumTexture, material);
     Graphics.Blit(accumTexture, destination);
 }
示例#59
0
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        blurMat    = new Material(Shader.Find("Casey-Screen/CannyEdgeDetect-GBlur"));
        sobelMat   = new Material(Shader.Find("Casey-Screen/CannyEdgeDetect-Sobel"));
        supressMat = new Material(Shader.Find("Casey-Screen/CannyEdgeDetect-NonMaxSupression"));


        blurTex    = RenderTexture.GetTemporary(source.width, source.height);
        sobelTex   = RenderTexture.GetTemporary(source.width, source.height);
        supressTex = RenderTexture.GetTemporary(source.width, source.height);

        blurMat.SetFloat("_Res", blurResolution);
        //Graphics.Blit(source, blurTex, blurMat);

        sobelMat.SetFloat("_Res", sobelResolution);
        //Graphics.Blit(blurTex, sobelTex, sobelMat);

        supressMat.SetFloat("_Res", supressResolution);
        supressMat.SetFloat("_UpperThreshold", upperThreshold);
        supressMat.SetTexture("_SourceTex", source);
        //Graphics.Blit(sobelTex, supressTex, supressMat);

        Graphics.Blit(source, destination, sobelMat);
    }
        static void CopySRGBWrite(bool isSRGB)
        {
            var src         = Selection.activeObject as Texture;
            var texturePath = UnityPath.FromAsset(src);

            var path = EditorUtility.SaveFilePanel("save prefab", "Assets",
                                                   Path.GetFileNameWithoutExtension(AddPath(texturePath.FullPath, ".sRGB")), "prefab");
            var assetPath = UnityPath.FromFullpath(path);

            if (!assetPath.IsUnderAssetsFolder)
            {
                return;
            }
            Debug.LogFormat("[CopySRGBWrite] {0} => {1}", texturePath, assetPath);

            var renderTexture = new RenderTexture(src.width, src.height, 0,
                                                  RenderTextureFormat.ARGB32,
                                                  RenderTextureReadWrite.sRGB);

            using (var scope = new ColorSpaceScope(isSRGB))
            {
                Graphics.Blit(src, renderTexture);
            }

            var dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false,
                                    RenderTextureReadWrite.sRGB == RenderTextureReadWrite.Linear);

            dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
            dst.Apply();

            RenderTexture.active = null;

            assetPath.CreateAsset(dst);

            GameObject.DestroyImmediate(renderTexture);
        }