c++ - std::vector<MyClass*> 的 VBO 和正确的步幅

标签 c++ opengl stl vbo

我想知道如何在没有数据复制的情况下为以下问题获得最大的数据局部性和性能。

我有一个 std::vector< MyClass* >,其中 MyClass 类似于

class MyClass
{
public:
    MyClass(int n,double px,double py,double pz)
    {
        someField=n;
        x=px;
        y=py;
        z=pz;
        anotherField=100;
        anotherUnusefulField=-10.0;
    }

    int someField;
    int anotherField;


    double x;
    double y;
    double z;
    double anotherUnusefulField;
};

std::vector<MyClass*> myClassVector;
// add some values and set x,y,z

for (std::vector<MyClass*>::iterator iter = myClassVector.begin(); iter!=myClassVector.end();++iter)
{
    MyClass *tmp = *iter;
    tmp->x+=1.0;
    tmp->y+=2.0;
    tmp->z+=3.0;
}

我经常对这些数据进行迭代,我也想强制执行数据局部性。指向 MyClass 的指针中包含的数据应发送到 OpenGL 顶点数组,其中顶点x,y,z 变量确定。正如您可能想象的那样很难正确设置步幅,所以我在这里询问是否有其他(可移植)解决方案来解决这个问题。

(p.s. 我已经阅读了帖子 VBOs with std::vector 但我的情况基本上不同,因为我有指针并且我在类中还有其他变量。)

最佳答案

I have pointers

这些指针对 OpenGL 毫无用处,因为它们位于客户端地址空间中。此外,OpenGL 不会取消引用二级指针。

and I also have other variables inside the class.

好吧,那就不要这样做了。如果将这些类实例传递给 OpenGL,就会复制大量无用数据。我建议您只将索引存储到类成员中紧密打包的 std::vector 或数组中,以及对 vector/数组本身的引用。您可以使用 getter/setter/referencer 成员函数来抽象出对 vector 的访问,即

class …
{

    // …
    std::vector<v_t> *v;
    size_t index_v;
    x_t getX() const { return (*v)[index_v]; }
    x_t setX(x_t x) { return (*v)[index_v] = x;}
    x_t &x() { return (*v)[index_v]; }

};

关于c++ - std::vector<MyClass*> 的 VBO 和正确的步幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636720/

相关文章:

c++ - 使用 pthread_create() 创建超过 1000 个线程

opengl - 什么是 channel 和多个着色器 channel 及其私有(private)变量

c++ - 4x4 矩阵重置缩放?

c++ - std::stringstream 十六进制转换错误

c++ - 如何在 C++ 中生成 overflow_error 或 underflow_error 异常?

c++ - 每次调用 C++ 函数时,如何防止变量被重新初始化?

c++ - GLSL OpenGL 多边形不渲染

c++ - 在空容器上调用时 std::partition 的行为?

C++ 装饰器模式

c++ - 在模板推导中使用boost变量