- Home /
Bake a texture from shader
Hi, I am trying to bake a final result from shader to texture. the only thing a shader does is apply second uv set on texture.
Here is the shader code :
Shader "Custom/uv2Tex" {
Properties {
_MainTex ("Diffuse", 2D) = "white" { }
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D _MainTex;
struct a2v {
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct v2f {
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
v2f vert (a2v v)
{
v2f o;
o.vertex = mul( UNITY_MATRIX_MVP, v.vertex);
o.texcoord1 = v.texcoord1;
return o;
}
half4 frag (v2f i) : COLOR
{
half4 color = tex2D(_MainTex, i.texcoord1);
return color;
}
ENDCG
}
}
}
and here is the script that bakes the texture:
using UnityEngine;
using System.Collections;
using System.IO;
public class BakeVideo : MonoBehaviour {
public Texture2D Maintexture;
public RenderTexture RT;
public Material bakeMat;
public MeshRenderer Go;
// Use this for initialization
IEnumerator Start () {
yield return UploadPNG();
}
IEnumerator UploadPNG()
{
yield return new WaitForEndOfFrame();
bakeMat = Go.sharedMaterial;
Maintexture = Go.sharedMaterial.GetTexture ("_MainTex") as Texture2D;
Graphics.Blit (Maintexture, RT, bakeMat);
// Create a texture the size of the screen, RGB24 format
RenderTexture.active = RT;
Texture2D tex = new Texture2D(512,512);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, 512, 512), 0, 0);
tex.Apply();
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);
// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
}
}
The problem is that my result is always looking the same as the original texture, as if the Graphics.Blit is not taking into account the uv alteration in shader? Is there a way to solve this? Thanks
Answer by SunnyChow · Dec 26, 2016 at 10:23 AM
I think you are using a mesh with customised second uv data. and i believe Graphics.Blit doesn't have similar uv data.
To achieve what you want, the easiest way it's to set a camera and render it to render texture, or you can use GL.LoadOrtho() and Graphics.DrawMeshNow() to do the similar rendering manually
yes, i'am using a mesh with customised second uv data; thnx, I will look into GL.LoadOrtho() and Graphics.Draw$$anonymous$$eshNow() ;