Chaining Transformations

As you’ve seen, you can create transformation matrices to translate, scale, rotate, and skew. But what if you want to do more than one at a time?

It’s a completely reasonable expectation. Let’s say that you are (eventually) going to render a teapot. The model you’re rendering is at the origin and is small relative to the rest of the scene. The model is also tipped on its side. You’d like to rotate it so it’s right-side up, scale it to a reasonable size, and then translate it so it’s sitting on a table, instead of the floor.

You could apply each transformation in sequence, like this:

 # rotate the teapot to be right-side up
 A ← rotation_x(​π​ / 2)
 teapot ← A * teapot
 
 # next, make the teapot 5x larger
 B ← scaling(5, 5, 5)
 teapot ← B * teapot
 
 # finally, move the teapot onto a table
 C ← translation(10, 5, 7)
 teapot ← C * teapot

But that’s just the same as this:

 A ← rotation_x(​π​ / 2)
 B ← scaling(5, 5, 5)
 C ← translation(10, 5, 7)
 
 teapot ← C * (B * (A * teapot))

Or, since matrix multiplication is associative:

 teapot ← (C * B * A) * teapot

Note that the order of the multiplications is important! Matrix multiplication is associative, but not commutative. When it comes to matrices, A × B is not guaranteed to be the same as B × A.

So, if you want a single matrix that rotates, and then scales, and then translates, you can multiply the translation matrix by the scaling matrix, and then by the rotation matrix. That is to say, you must concatenate the transformations in reverse order to have them applied in the order you want! Add the following tests to demonstrate this (particularly counterintuitive) result.

 Scenario​: Individual transformations are applied in sequence
 Given​ p ← point(1, 0, 1)
 And​ A ← rotation_x(π / 2)
 And​ B ← scaling(5, 5, 5)
 And​ C ← translation(10, 5, 7)
 # apply rotation first
 When​ p2 ← A * p
 Then​ p2 = point(1, -1, 0)
 # then apply scaling
 When​ p3 ← B * p2
 Then​ p3 = point(5, -5, 0)
 # then apply translation
 When​ p4 ← C * p3
 Then​ p4 = point(15, 0, 7)
 
 Scenario​: Chained transformations must be applied in reverse order
 Given​ p ← point(1, 0, 1)
 And​ A ← rotation_x(π / 2)
 And​ B ← scaling(5, 5, 5)
 And​ C ← translation(10, 5, 7)
 When​ T ← C * B * A
 Then​ T * p = point(15, 0, 7)

Awesome! You now have vectors and points, and matrix transformations. This is a fantastic foundation for the rest of your ray tracer! Let’s find something to do with those pieces before moving on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.90.44