Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

How can I access the nth element in a texture2d from a pixel shader? For example if I wanted to get the 5th vector4 from 10 x 10 texture2d

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

2D textures usually aren't addressed in terms like the "nth element". The whole point of a 2D texture is that you want to access it using 2D coordinates. If you want to send a 1D array to the shader I'd use a 1D texture.

That being said, you can compute it by something like this:

int x = n % textureWidth;
int y = n / textureWidth;                            // integer division
float u = (float(x) + 0.5) / float(textureWidth);    // map into 0-1 range
float v = (float(y) + 0.5) / float(textureHeight);
float4 result = tex2D(sampler, float2(u, v));

(This assumes you already know how to set up a sampler parameter in the shader and bind a texture to it from the application side.)

share|improve this answer
    
A 1d texture sounds perfect for my situation. How does use them in XNA? –  Mr Bell Nov 16 '11 at 23:16
    
Shouldn't you add 0.5 to float(x) and float(y) before dividing? Otherwise you will get off-by-one errors, especially on a 10×10 texture. –  Sam Hocevar Nov 17 '11 at 7:25
    
@SamHocevar, good catch! I'll edit to add that. –  Nathan Reed Nov 17 '11 at 18:19
    
+1 now that the code works :-) –  Sam Hocevar Nov 17 '11 at 19:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.