简体   繁体   English

C ++结构内存布局和OpenGL glVertexPointer?

[英]C++ struct memory layout and OpenGL glVertexPointer?

I have following struct to store my vertex data. 我有以下结构来存储我的顶点数据。

struct Rz3DContourNode {
  float x; //pos x
  float y;   //pos y
  float z;  //pos z
  float nx;  //normal x
  float ny;  //normal y
  float nz;  //normal z
};

I store list of vertices in STL vector as follows : 我将顶点列表存储在STL向量中,如下所示:

std::vector < Rz3DContourNode >  nodes;

When I try to use this as as vertex-array in OPEGL ,in does not render incorrectly. 当我尝试将其用作OPEGL中的顶点数组时,in不会正确渲染。

glVertexPointer(3, GL_FLOAT, 12, &nodes[0]);
glDrawArrays(GL_POINTS,0,nodes.size());

So, I tried to confirm the values using pointer arithmetic (assuming thats the way OPENGL handle data) as follows: 因此,我尝试使用指针算法(假设这就是OPENGL处理数据的方式)来确认值,如下所示:

float *ptr=(float*) &nodes[0];

for(int i=0;i<nodes.size();i++)
{

   Rz3DContourNode confirmNode=nodes[i];  

  float x=*ptr;
    ptr++;

  float y=*ptr;
    ptr++;

  float z=*ptr;
     ptr++;


  //Confirm values !!! Do not equal ??
  qDebug("x=%4.2f  y=%4.2f z=%4.2f  | nx=%4.2f ny=%4.2f nz=%4.2f
        ",confirmNode.x,confirmNode.y,confirmNode.z,x,y,z);



  //Skip normal positions
  ptr++;
  ptr++;
  ptr++;

}

The values does not equal if I directly access values from the struct. 如果我直接从结构访问值,则值不相等。

Does this means struct does not save the values contiguously ? 这是否意味着struct不连续保存值?

[EDIT] I Just noticed that using sizeof() instead of 12 fix the problem as follows: [编辑]我只是注意到使用sizeof()而不是12可以解决以下问题:

glVertexPointer(3, GL_FLOAT, sizeof(Rz3DContourNode), &nodes[0]);

But still I am confused why my hack didnt traverse correctly in memory?(why qDebug doesnt print identical values ?) 但是仍然令我感到困惑的是,为什么我的黑客无法在内存中正确遍历?(为什么qDebug不打印相同的值?)

sizeof(Rz3DContourNode) == 6*4 = 24 bytes ... not 12!

The stride is the # of bytes between the start of each vertex, not the padding. 跨度是每个顶点开始之间的字节数,而不是填充。 Although 0 is a special value that indicates tightly packed data. 尽管0是一个特殊值,它表示数据紧密压缩。

So, if you're using 3 floats as vertex data, there's no difference between a stride of 0 and 12 (because 3 floats are 12 bytes). 因此,如果将3个浮点数用作顶点数据,则步幅0和12之间没有区别(因为3个浮点数是12个字节)。 In your case, your struct is 24 bytes, so you should put that. 在您的情况下,您的结构是24字节,因此您应该输入。

This convention (stride = step size, not padding) allows the simple use of sizeof, so you ended up doing the the right thing intuitively. 这种约定(步长=步长,而不是填充)允许简单地使用sizeof,因此您最终会直观地执行正确的操作。 That's good API design for you. 这对您来说是一个很好的API设计。 :) :)

See glVertexPointer docs : 请参阅glVertexPointer docs

stride

Specifies the byte offset between consecutive vertices. 指定连续顶点之间的字节偏移量。 If stride is 0, the vertices are understood to be tightly packed in the array. 如果stride为0,则将顶点理解为紧密排列在数组中。 The initial value is 0. 初始值为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM