# Working with quaternions

hi!
i’m using quaternions to simulate rotations. now i need to multiply a vector by a quaternion in a vertex shader:

``````vec3 MultiplyVectorByQuaternion( vec3 vector, vec4 quaternion )
{
vec3 kVector1 = vec3( quaternion.x, quaternion.y, quaternion.z );
vec3 kVector2 = cross( kVector1, vector );

kVector2 += vector*quaternion.w;

vec3 kVector3 = cross( kVector2, kVector1 );

kVector1 *= vector*kVector1;

kVector1 += kVector2*quaternion.w;

return vec3( kVector1-kVector3 );
}
``````

this works fine but i guess there are better ways to do it - is there a chance that i can take advantage of glsl’s built-in functions to do such calculations?

There is some trick that allows you to transform (not multiply) a vector by a quaternion in 2 operations. It requires some clever use of swizzling, but it can be done (note to ARB: why isn’t quaternion/vector transform a built-in function?).

Unfortunately I don’t know it. But I know it exists. Try Google.

Well, a quaternion product can be viewed as the product of a 4x4 matrix with a 4x1 vector, so I might start with that ``````vec3 quat_transform( vec4 q, vec3 v )
{
return v + 2.*cross( q.xyz, cross( q.xyz, v ) + q.w*v );
}
``````

Could it be that the component of both crossproducts are swapped?
With swapped components

`````` vec3 qtransform( vec4 q, vec3 v ){