internal representation of struct

Simon Buerger krox at gmx.net
Fri Mar 18 10:10:35 PDT 2011


On 18.03.2011 17:34, lenochware wrote:
> Hello, I have array of type vertex_t vertices[] where vertex_t is:
>
> struct vertex_t {
>    float[3] xyz;
>    ubyte[4] color;
>    ...
> }
>
> Now, I would like use instead of array "float[3] xyz" "vec3f xyz", where vec3f is:
>
> struct vec3f {
>    float x, y, z;
>
> ...some functions...
> }
>
> where I have defined some operators for adding and multipliing vectors etc.
>
> Is it possible? "xyz" must be exactly 3 floats in memory because I am sending
> vertices array pointer into OpenGL rendering pipeline.
> Will be struct vec3f represented just like 3 floats - aren't here some
> additional metadata - because structure contains also some functions?

There is no metadata in structs. The only thing there is padding in 
order to align the fields. But floats have a size of 4 and alignment 
the same, so your vec3f will be exactly 12 bytes without any problem 
(done it myself for OpenGL)

> My additional question: What about effectivity? I would like keep struct
> vertex_t as simple as possible, because I need do calculations fast. Will have
> replacing float array to structure some impact on speed?

depends: When you want to to a component-wise vector multiplication, 
you want the compiler to use SSE and alike. With
float[3] a,b,c;
c[] = a[]*b[];
That will probably work (that is one reason the []-notion exists in 
the first place). But with
vec3f a,b,c;
c.x = a.x*b.x; c.y=a.y*b.y; c.z=a.z*b.z;
it really depends on the quality of the compiler if it sees the 
opportunity for optimisation.

If you want to be sure, I suggest the following:
struct vec3
{
	float[3] data;
	vec3 opMul(vec3 other) {
		vec3 tmp = this;
		tmp.data[] *= other.data[];
	}
}

As a last note: When you do OpenGL, the biggest part of calculations 
should be done on the GPU, so the few on the CPU might not be 
performance critical at all. But that depends of course on the exact 
thing you want to do.

- Krox



More information about the Digitalmars-d mailing list