- Home /
Texture coordinate sampling in cg surface shader
Hi, I'm trying to sample the color from a procedurally generated texture in a surface shader. This is a self-contained, simplified version that demonstrates the issue.
Brief: I have a texture that looks like this.
I'd like the texture to be 2x2 pixels, but I have tried various sizes to make sure it wasn't a size issue.
What I want to do: I'm trying to sample each pixel and get the exact rgba value in order to do some fancy stuff in the shader with.
Problem: If I turn OFF both the FilterMode.Point and the TextureWrapMode.Clamp, every texture coordinate retrieves a blend of all of the colors, but as long as either or both are ON, it only retrieves GREEN or WHITE.
How I'm doing it:
I create the texture in code like so.
opsTex = new Texture2D(size, size, TextureFormat.RGBA32, false, false);
opsTex.filterMode = FilterMode.Point;
opsTex.wrapMode = TextureWrapMode.Clamp;
I apply the texture using SetPixels and Apply on the texture itself, then assign the texture to the material.
opsTex.SetPixels(opsTexColors);
opsTex.Apply(false);
renderer.material.SetTexture("_CoolTex", opsTex);
Inside the shader I retrieve the value via a simple tex2D lookup. Here it's being applied to the Emission just so it's easily visible as to what color value it's retrieving.
float2 coord = (0,0);
o.Emission = tex2D(_ProceduralTex, coord).rgb;
I change the value of coord around to get the color I want.
These are the values I SHOULD get:
coord = (0.25,0.25) :: GREEN
coord = (0.25,0.75) :: BLUE
coord = (0.75,0.25) :: RED
coord = (0.75,0.75) :: WHITE
These are the values I ACTUALLY get:
coord = (0.25,0.25) :: GREEN
coord = (0.25,0.75) :: GREEN
coord = (0.75,0.25) :: WHITE
coord = (0.75,0.75) :: WHITE
Conclusion: What am I missing? My mind is sufficiently boggled. Seems to me like the texture coordinate should give me exactly what it is displaying at that point, but it's not.
Thanks for any help.
Answer by nSwarm · May 01, 2012 at 05:31 PM
Solution found!
It's one of these fun facepalm moments though, so hopefully this experience will help someone or at least give a chuckle.
float2 coord = (0.25, 0.75);
The error lies in this line. The answer?
float coord = float2(0.25, 0.75);
Yep. The issue is, CG supports comma operators. (http://http.developer.nvidia.com/Cg/Cg_language.html) Which means this code is valid, it just fills the float2 with 0.75, so we have to typecast to get what we want.
So that was fun. :)
Thanks for posting that, I'm about to try to implement the same technique and this seems like a very confusing issue, I don't think I would have figured it out!
Your answer
Follow this Question
Related Questions
ZBuffer and Object Depth 1 Answer
How to add Bump/Normal Map to surface shader? (CG) 0 Answers
GetPixelBilinear returning different value between unity versions for Compressed texture 1 Answer
Shader that renders fragment behind 0 Answers
Prevent ColorMask obscuring parts of an object's mesh 0 Answers