Sign in to follow this  
avocados

macro that adds vectors?

Recommended Posts

struct v3d { float x; float y; float z; };

void func() {
v3d point_a = { 1,1,1 };
v3d point_b = { 2,2,2 };

point_a * point_b; //point_a now contains the product of the two vectors

Is it possible a macro can make the last line functional? Would prefer that aesthetically to add() and multiply() etc;

+

Share this post


Link to post
Share on other sites
__declspec(align(16)) union
{
struct{ f32 x, y, z, w; };
f32 v[4]; //floats
f128 v128; //_m128 type
};

then you can just use the SSE intrinsics and do the entire thing in one shot.

Something like:
inline Vector Vector::operator+(f32 x) const { return Vector(_mm_add_ps(this->v128, _mm_load1_ps(&x))); }


Share this post


Link to post
Share on other sites
clashie is on the right track, but I'm going to vote against the union. Unions like that can cause the compiler to output some atrocious code because a XMM register that the _m128 will fit in is different from the float registers that the f32 x will fit in. This causes the compiler to do a lot of unneeded loads and stores to keep both parts of the union in sync.

Share this post


Link to post
Share on other sites
Quote:
Original post by avocados
point_a * point_b; //point_a now contains the product of the two vectors

Is it possible a macro can make the last line functional? Would prefer that aesthetically to add() and multiply() etc;


This is a perfect example of a situation where giving the function a name is actually much better than overloading an operator. If you are going to overload an operator for this, use operator *= instead of operator *.

It's not immediately clear to me which product of the two vectors you are talking about. I can count up to five possible interpretations of that product: Dot product, cross product, tensor product, external product and component-by-component product. The last one is not very mathematically meaningful, but some people use it anyway.

If your code says cross_product(point_a, point_b), it's a lot more clear.

It's also pretty bad that you are calling the variables point_a and point_b if they are vectors. I understand that points can be identified with vectors if you decide on an origin, but then none of the products make much sense.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this