What I am doing is screenshotting a quad whose attached material creates a texture. That texture has Perlin noise values stored in the red channel. To test how accurate the values are, I am setting the blue value outputting from the fragment shader to 0.65.
In my ShaderLab code…
mainColor.b = 0.65;
In script, I am getting 0.6509804 in my Debug.Log. Here is my script:
using UnityEngine;
using UnityEngine.Experimental.Rendering;
public class PixelReader : MonoBehaviour
{
Material material;
Camera perlinCamera;
RenderTexture renderTexture;
Texture2D blankTexture, texture;
public Color[] GetNoise(int chunkX, int chunkY, int chunkSize)
{
if (perlinCamera == null)
{
perlinCamera = GetComponent<Camera>();
material = GetComponentInChildren<MeshRenderer>().materials[0];
renderTexture = new RenderTexture(chunkSize, chunkSize, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
blankTexture = new Texture2D(chunkSize, chunkSize, TextureFormat.RGBA32, false, false);
texture = new Texture2D(chunkSize, chunkSize, TextureFormat.RGBA32, false, false);
}
RenderTexture.active = renderTexture;
perlinCamera.targetTexture = renderTexture;
// Set up shader variables
material.SetTexture("_MainTex", blankTexture);
material.SetFloat("_ChunkX", chunkX);
material.SetFloat("_ChunkY", chunkY);
material.SetFloat("_ChunkSize", chunkSize);
perlinCamera.Render();
texture.ReadPixels(new Rect(0, 0, chunkSize, chunkSize), 0, 0);
texture.Apply();
byte[] bytes = texture.EncodeToPNG();
System.IO.File.WriteAllBytes("C:/Users/vmc4/Downloads/TextureExport.png", bytes);
RenderTexture.active = null;
perlinCamera.targetTexture = null;
//chunkQuad.SetActive(false);
return texture.GetPixels();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
Debug.Log(GetNoise(8, 1, 16)[0].b);
}
}
}
How can I get the output to be exact?
I have tried using different color space settings. It seems that setting the RenderTexture to linear color space made the output more exact. The value was way off before because it was in gamma-corrected color space.
I have read online it could be a post-processing setting but that didn’t seem to do the trick when I changed them. Perhaps I missed one or some other graphics setting. Any help would be appreciated.