所以我试图将一堆 vector 传递给片段着色器,显然我应该使用1d纹理。但是,如果我尝试访问传递的 vector ,则值不是我期望的。
我应该如何索引texture()函数?
传递纹理:
std::vector<vec3> triangles;
//triangles is already filled by this point
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, texture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB16F, Object::triangles.size(), 0, GL_RGB, GL_FLOAT, &Object::triangles[0]);
GLint textureLoc = glGetUniformLocation( getId(), "triangles" );
glUniform1f(textureLoc, 0);
setUniform((int)Object::triangles.size(), "triCount");
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//draw a rectangle from -1,-1 to 1,1
片段着色器代码:uniform sampler1D triangles;
uniform int triCount;
struct Triangle{
vec3 a,b,c;
vec3 normal;
};
void main(){
for(int i = 0;i < triCount;i++){//for each triangle
Triangle triangle;
//set the points of the triangle
triangle.a = vec3(texture(triangles,i));
triangle.b = vec3(texture(triangles,i++));
triangle.c = vec3(texture(triangles,i++));
//set the normal vector of the triangle
triangle.normal = vec3(texture(triangles,i++));
//then i do stuff with the current triangle and return a color
}
}
该数组包含3个点和一堆三角形的法线 vector ,这就是为什么我以这种方式从纹理读取的原因。编辑:
glGetTexImage确认传递的纹理正确。
最佳答案
当使用 texture
时,纹理坐标是[0.0,1.0]范围内的浮点值。使用 texelFetch
从整体纹理坐标范围为[0,width)的纹理中查找单个Texel:
triangle.a = texelFetch(triangles, i*4, 0).xyz;
triangle.b = texelFetch(triangles, i*4+1, 0).xyz;
triangle.c = texelFetch(triangles, i*4+2, 0).xyz;
triangle.normal = texelFetch(triangles, i*4+3, 0).xyz;
请注意,着色器代码中Texel索引的计算不正确。或者,您可以通过将索引除以纹理的宽度来计算纹理坐标。纹理的大小可以通过
textureSize
获得:float width = float(textureSize(triangles, 0));
triangle.a = texture(triangles, (float(i*4)+0.5) / width).xyz;
triangle.b = texture(triangles, (float(i*4)+1.5) / width).xyz;
triangle.c = texture(triangles, (float(i*4)+2.5) / width).xyz;
triangle.normal = texture(triangles, (float(i*4)+3.5) / width).xyz;
关于c++ - 通过OpenGL中的纹理传递数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64742487/