Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

Your Answer


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.