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. :wink:

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 :slight_smile:

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

quad_transform(Q,vec3(0.0,0.0,1.0));

will be equal to

vec3(2*(Q.xQ.z-Q.wQ.y),2*(Q.yQ.z+Q.wQ.x),1-2*(Q.xQ.x+Q.yQ.y));

that is the part from a quaternion to matrix convertion code (the 3rd vector). Imho it should be:

 vec3 qtransform( vec4 q, vec3 v ){ 
	return v + 2.0*cross(cross(v, q.xyz ) + q.w*v, q.xyz);
	} 

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.