我正在开发一款使用OpenGL ES 2进行绘图的iPhone应用程序.我知道通常纹理坐标是在0-1范围内定义的,但理想情况下我想将它们从0-1023(我的TextureAtlas的大小)映射出来以便于阅读.我已经看到了以这种方式定义坐标的示例代码,但是无法确定以前允许这样做的调用.glMatrixMode(GL_TEXTURE)好像它可能涉及,但我不太确定如何实现它.
我的最终目标是完成这样的事情,我在地图册中使用的纹理位于左上角48px的正方形中:
GLshort texcoords[]={
48,48,
0,48,
48,0,
0,0,
};
glVertexAttribPointer(ATTRIB_TEXTUREPOSITON, 2, GL_SHORT, 0, 0, texcoords);
glEnableVertexAttribArray(ATTRIB_TEXTUREPOSITON);
Run Code Online (Sandbox Code Playgroud) 我试图通过指定我想要的坐标在OpenGL中绘制一个纹理的子区域.然而,正在发生的是,根据图像的大小,它似乎在选择纹理坐标的位置有一个轻微的偏移.偏移量似乎小于像素的大小,并且输出是相邻像素的模糊组合.
这是我所描述的想法.在这种情况下,我想要选择6x5绿色/白色区域,但OpenGL渲染的内容包括顶部和左侧像素的浅粉色调.

输出结果如下:

我可以通过在将它们传递给glTexCoordPointer之前向纹理坐标添加偏移来修复它,但问题是我无法计算偏移量是什么,并且对于不同的纹理看起来不同.
伪代码:
float uFactor = regionWidth / textureWidth; // For the example: 0.6f
float vFactor = regionHeight / textureHeight; // For the example: 0.5f
data[0].t[0] = 0.0f * uFactor;
data[0].t[1] = 0.0f * vFactor;
data[1].t[0] = 1.0f * uFactor;
data[1].t[1] = 0.0f * vFactor;
data[2].t[0] = 0.0f * uFactor;
data[2].t[1] = 1.0f * vFactor;
data[3].t[0] = 1.0f * uFactor;
data[3].t[1] = 1.0f * vFactor;
glPushMatrix();
// translate/scale/bind operations
glTexCoordPointer(2, GL_FLOAT, 0, data[0].t);
Run Code Online (Sandbox Code Playgroud) 所以我有一个三角形:
我有一个顶点着色器:
uniform mat4 uViewProjection;
attribute vec3 aVertexPosition;
attribute vec2 aTextureCoords;
varying vec2 vTextureCoords;
void main(void) {
vTextureCoords = aTextureCoords;
gl_Position = uViewProjection * vec4(aVertexPosition, 1.0);
}
Run Code Online (Sandbox Code Playgroud)
我有一个片段着色器:
precision mediump float;
uniform sampler2D uMyTexture;
varying vec2 vTextureCoords;
void main(void) {
gl_FragColor = texture2D(uMyTexture, vTextureCoords);
}
Run Code Online (Sandbox Code Playgroud)
我提供了三组顶点和UV,交错:
# x, y, z, s, t
0.0, 1.0, 0.0, 0.5, 1.0
-1.0, -1.0, 0.0, 0.0, 0.0
1.0, -1.0, 0.0, 1.0, 0.0
Run Code Online (Sandbox Code Playgroud)
片段着色器如何知道以不同于像素B的方式绘制像素A?有什么变化?