Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flat array from an array of structs?

Tags:

c++

c

opengl

Hey guys. Thanks for clicking.

This is a problem that I'm encountering while coding OpenGL, but it's a pretty general problem overall - so nothing graphics specific.

I have a struct (not a class, just a simply struct), Particle.

typedef struct
{
    float x;
    float y;
    float z;
}float3;

typedef struct
{
   float3 position;
   float3 velocity;
   //...other stuff
}Particle;

And I am working with a bunch of particles (Particle* particles[]), but I have a function that requires a float* of positions packed in an x, y, z order.

Thus a summary of my problem:

My data:

//I have this in a bunch of encapsulated structs
[... {1.0f, 2.0f, 3.0f,} ... {4.0f, 5.0f, 6.0f} ...]

//I want...
[1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f]

My problem is...I have all the data there already! I don't want to have to malloc/memcpy around again. Is there a way to use the data that is already there? Any C pointer acrobatics? I am also worrying about things like alignment/padding.

(float3 is a struct defined in CUDA, if anyone is curious).

like image 289
SharkCop Avatar asked Jun 09 '26 14:06

SharkCop


1 Answers

glVertexAttribPointer has a stride parameter that is designed for just this situation.

Typically you will load an array of Particle objects into a VBO, and then, with the VBO bound:

glVertexAttribPointer(shader_arg_position, 3, GL_FLOAT, GL_FALSE, sizeof (Particle), offsetof(Particle, position));
like image 167
Ben Voigt Avatar answered Jun 11 '26 06:06

Ben Voigt