Next: , Previous: Special objects, Up: Introduction by example



2.5 Transforms

Now let's add a second copy of the pierced tetrahedron. We'll rotate the copy 90 degrees about the x-axis with the origin as center of rotation so we can see the back, then translate it to the right—in the positive x-direction—so it doesn't collide with the original. To help us see what's going on, make the back side gray.

  def pierced_tetrahedron {
    def p1 (0,0,1) def p2 (1,0,0)
    def p3 (0,1,0) def p4 (-.3,-.5,-.8)
    polygon(p1)(p2)(p3)                      % original
    polygon(p1)(p4)(p2)                      % bottom
    polygon(p1)(p3)(p4)                      % left
    polygon[fillcolor=lightgray](p3)(p2)(p4) % rear
    line[linecolor=red](-1,-1,-1)(2,2,2)
  }
  {pierced_tetrahedron}  % tetrahedron in original position
  put { rotate(90, (0,0,0), [1,0,0]) % copy in new position
        then translate([2.5,0,0]) } {pierced_tetrahedron}
Here the entire code of the previous example has been wrapped in a definition by forming a block with braces (a single item would not need them). The point definitions nested inside the braces are lexically scoped. Their meaning extends only to the end of the block. The outer def is called a drawable definition because it describes something that can be drawn.

A drawable definition by itself causes nothing to happen until its name is referenced. Drawable references must be enclosed in curly braces, e.g. {foo}, with no intervening white space. In the code above, the first reference {pierced_tetrahedron} is a plain one. Its effect is merely to duplicate the earlier drawing. Almost any series of sketch commands stuff may be replaced with def foo { stuff } {foo} without changing its meaning.

The put command supplies a second reference, this time with a transform applied first. The rotate transform turns the tetrahedron 90 degrees about the origin. The axis of rotation is the vector [1,0,0]. By the right hand rule, this causes the top of the tetrahedron to rotate toward the viewer and the bottom away. The rule receives its name from the following definition:

Right hand rule. If the right hand is wrapped around any axis with the thumb pointing in the axis direction, then the fingers curl in the direction of positive rotation about that axis.
The translate transform moves the pyramid laterally to the right by adding the vector [2.5,0,0] to each vertex coordinate. The result is shown here.
ex050.png