如何将每个顶点属性传递给GLSL着色器

问题描述:

如果可能的话,如何将自定义顶点属性发送给着色器并访问它?请注意,该模型将与VBO一起呈现。例如,假设我有一个顶点结构如下:如何将每个顶点属性传递给GLSL着色器

struct myVertStruct{ 
    double x, y, z; // for spacial coords 
    double nx, ny, nz; // for normals 
    double u, v; // for texture coords 
    double a, b; // just a couple of custom properties 

要访问,比方说,法线,人们可以在着色器调用:

varying vec3 normal; 

这将如何自定义属性来实现?

+4

第1步:*停止使用双打*。第2步:以与其他属性相同的方式执行此操作。 '正常'没什么特别的。另外,'vec3 normal'是一个顶点着色器*输出*,而不是一个属性。所以你的问题很困惑。 – 2013-02-27 01:52:40

+0

您正在使用哪种OpenGL版本? OpenGL 2和OpenGL 3+的代码略有不同。另外,正如@NicolBolas已经提到的,“变化”不是顶点着色器输入的选项。 – 2013-02-27 08:09:57

首先,你不能使用双精度浮点数,因为这些不被几乎所有的GPU.So支持,只是改变你的结构的成员飘起然后......

定义在GLSL相同结构。

struct myVertStruct 
{ 
    float x, y, z; // for spacial coords 
    float nx, ny, nz; // for normals 
    float u, v; // for texture coords 
    float a, b; // just a couple of custom properties 
} myStructName; 

然后,实例化在c结构阵列/ C++,创建VBO,分配的内存,然后将其绑定到着色器:当绑定属性

struct myVertStruct 
{ 
    float x, y, z; // for spacial coords 
    float nx, ny, nz; // for normals 
    float u, v; // for texture coords 
    float a, b; // just a couple of custom properties 
}; 

GLuint vboID; 
myVertStruct myStructs[100]; // just using 100 verts for the sake of the example 
// .... fill struct array; 

glGenBuffers(1,&vboID); 

然后:

glBindBuffer(GL_ARRAY_BUFFER, vboID); 
glVertexAttribPointer(0, sizeof(myVertStruct) * 100, GL_FLOAT, GL_FALSE, 0, &struct); 
glBindBuffer(GL_ARRAY_BUFFER, 0); 

...然后将您的vbo绑定到您使用上面使用的glsl段创建的着色器程序。

+1

你确定这可以吗? 'myStructName'不能使用'in'限定符,因为它是一个'struct'。因此,您不能使用它将值传递给着色器。 – 2013-11-23 04:15:21