Calculating a rotation matrix from one vector to another

Aligning one plane to another is a common task in 3D modeling. The easiest way to align planes is by using their normal vectors – we need to rotate the original plane so that its normal vector coincides with the normal vector of the plane for which the alignment is performed. Therefore, the task of rotating one plane to another can be reduced to the problem of rotating the normal vector of the first place to the normal vector of the second plane.

One of the ways for rotating a vector is to use transformation matrices.

Let’s consider an example of finding a matrix for rotating one vector to another.

We can start from a source object – the first plane

We can get the normal to it by finding the cross product for two vectors from its origin to any pair of its vertices.

Since the matrices work relative to the zero point, we need to get the global coordinates of the normal vector by multiplying it by the world matrix of the plane.

The same for the second plane, to which we need to rotate the first plane

Get its normal vector in the global coordinate system.

Now we have two vectors. Let’s calculate the transformation matrix for the rotation from the first vector to the second.

We can use some Blender Python API functions for this.

Define a function that will take two vectors as parameters and return the rotation matrix from one vector to the other.

Here we first find the angle between the two vectors.

Then we determine the axis around which we will rotate the first vector so that it comes to the second. This is very easy to do because these two vectors form the plane in which the rotation will be performed. The rotation axis is the normal to this plane. And as we did before, we can get it through the cross product of two vectors.

And finally, we get the matrix we need by calling the Matrix.Rotation function.

Or we can use an optimized trigonometry function (by Inigo Quilez) to get the rotation matrix.

Although it looks more complicated, it performs fewer operations and takes into account the special case when the vectors from the input parameters can be collinear.

To use it in Blender, we need to modify it a bit: since the calculations result in a 3×3 matrix, we need to transform it into the standard Blender transformation matrix – 4×4. Also, all calculations in it are made for the left-hand orientation of the axes, but Blender uses the right-hand one. Therefore, before using the resulting matrix, we need to transpose it.

By calling the first or second function with the previously calculated normal vectors, we will get the transformation matrix we need.

Now we can add the resulting matrix to the world transformation matrix of our first plane.

And we will see that our first plane will be aligned by the second plane.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments