Frage

Using a shader I'm trying to color a plane so it replicates the pixels on a texture. The texture is 32x32 pixels and the plane is also sized 32x32 in space coordinates.

Does anyone know how I would inspect the first pixel on the texture, then use it to color the first square (1x1) on the plane?

Generated texture example: (First pixel is red on purpose)
enter image description here

This code using a vec2 with coordinates (0,0) doesn't work as I expected. I assumed the color at (0,0) would be red but it's not, it's green:

vec4 color = texture2D(texture, vec2(0, 0));

I guess there's something that I'm missing, or not understanding about texture2D as (0,0) doesn't appear to be the ending pixel either.

If anyone could help me out, it would be greatly appriciated. Thanks.


EDIT:
Thanks for the comments and answers! Using this code, it's working now:

// Flip the texture vertically
vec3 verpos2 = verpos.xyz * vec3(1.0, 1.0, -1.0);

// Calculate the pixel coordinates the fragment belongs to
float pixX = floor(verpos2.x - floor(verpos2.x / 32.0) * 32.0);
float pixZ = floor(verpos2.z - floor(verpos2.z / 32.0) * 32.0);

float texX = (pixX + 0.5) / 32.0;
float texZ = (pixZ + 0.5) / 32.0;

gl_FragColor = texture2D(texture, vec2(texX, texZ));

That said, I'm having an issue with jagged lines on the edges of each "block". Looks to me like my math is off and it's confused about what color the sides should be, because I didn't have this problem when using only vertex colors. Can anyone see where I've gone wrong or how it could be done better?
Thanks again!

enter image description here

War es hilfreich?

Lösung

Yes... as Ben Pious mentioned in a comment, remember that WebGL displays 0,0 in lower left.

Also, for indexing into your textures, try to sample from the "middle" of each pixel. On a 32x32 source texture, to get pixel (0,0) you'd want:

texture2D(theSampler, vec2(0.5/32.0, 0.5/32.0));

Or more generally,

texture2D(theSampler, vec2((xPixelIndex + 0.5) / width, (yPixelIndex + 0.5) / height);

This is only if you're explicitly accessing texture pixels; if you're getting values interpolated and passed through from the vertex shader (say a (-1,-1) to (1,1) square, and pass varying vec2((x+1)/2,(y+1)/2) to the fragment shader), this "middle of each pixel" is reflected in your varying value.

But it's probably just the Y-up like Ben says. :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top