TweetFollow Us on Twitter

Line Art Rotation
Volume Number:6
Issue Number:5
Column Tag:C Forum

Related Info: Quickdraw

Line Art Rotation

By Jeffrey J. Martin, College Station, TX

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

[ Jeff Martin is a student at Texas A&M University working on his bachelors in computer science. He has been a personal computer technician at the campus computer center, a system operator on the campus mainframes, and now freelances graphic work for various professors. He hopes that one day a motion picture computer animation company will take him away from all of this.]

This being my first stab at an article, I will try to keep it short while leaving in all of the essential vitamins and nutrients. In that spirit my user interface will bring back nostalgic thoughts to those past Apple II and TRS-80 users, and any PC people will feel right at home.

The essence of this program is to show how a seemingly complicated transformation and rotation can be applied to an array of points that form any arbitrary line art.

Of course to form a transformation on the array of points (e.g. offset the points to the left) we simply add some delta x(dx) and/or delta y(dy) to every point:

/* 1 */


Now rotation is a little harder, but to spare you the heartache, it can be shown that for rotation about the origin(fig 1):

So the trick of rotating about some arbitrary point is to first transform that pivot point to be the origin(transforming every other point by the save amount). Second, perform the rotation of all points by the angle theta. Third, transform the pivot back(once again transforming all other points as well).

Now all of this may seem to be a costly maneuver, but the fact is that we can roll all of these into a single matrix multiplication, using homogeneous coordinates:


form one matrix.

Fig. 2 shows the multiplication of a homogeneous coordinate and a translation matrix. Please verify that this results in (X+dx,Y+dy) (if unfamiliar with matrix multiplication see mult procedure in program).

Similarly figure 3 shows multiplication with a rotation matrix - an exact translation of our rotation equations in matix form.

So the translation, rotation, and inverse translation matrices are as shown in figure 4. Which forms one matrix to be multiplied times the vertices.

The following program allows the user to enter in points with the mouse until a key is pressed. At that time the user then uses the mouse to enter a pivot point. The program uses the pivot point to form the translation and inverse translation matrices(from the x and y coordinates). The program then forms a rotation matrix of a constant rotation angle(Π/20) and calculates the new vertices based on the values of the old ones. The program undraws the old lines and redraws the new and calculates again until the object has rotated through a shift of 4Π(2 rotations). press the mouse button again to exit program.

Once again, I point out that the code does not follow the user guidelines, but then it is not exactly meant to be an application in itself. Build your own program around it and see what you can do. One suggestion is to cancel the erasing of the object to achieve spirograph patterns. I think too many of the submissions to MacTutor contain an interface that we all know too well, and for those just interested in the algorithms it can mean a lot of extra work. Have Fun.

/* 2 */

int errno;

void mult();  /*out matrix mult proc*/
/*floating value of points to avoid roundoff*/
typedef struct rec {float h,v;} points;
  int buttondown=0, /*flagg for mouse       */
      n=-1,         /*number of vertices    */
      keypressed=0, /*flagg for key         */
      flip=0,       /*to allow alternating  */
      flop=1,       /*vertices to be drawn  */
      i;            /*array counter         */
  float x,          /*angle counter         */
      T[3][3],      /*translation matrix    */
      Tinv[3][3],   /*translate back        */
      Rz[3][3],     /*rotate matrix         */
      c[3][3],      /*result of T&R         */
      d[3][3];      /*result of c&Tinv      */
  long curtick,     /*for delay loop        */
       lastick;     /*for delay loop        */
  EventRecord nextevent;/*to get mouse&key  */
  Point origin,dummy;   /*pivot and locator */
  points points[2][30];/*vertices(don’t draw Eiffel tower)  */
  WindowPtr scnwdw;    /*window pointer     */
  Rect      scnrect;   /*window rect        */
*  Set things up                     *
scnwdw=NewWindow(0,&scnrect,”\p”,TRUE,dBoxProc, -1,FALSE,0);
*  Get points                        *
      if(nextevent.what==mouseDown) buttondown=1;
      else if(nextevent.what==keyDown) keypressed=1;
    if(buttondown) /*get a point and draw it*/ 
    } /*end of get point*/
  }  /*end of get points*/
*  Get origin                        *
      if(nextevent.what==mouseDown) buttondown=1;
*  Make translation matrix           *
*  Rotate                            *
  x=0.157;  /*rotation angle - about 9 degrees*/
    }  /*end update points*/
    ForeColor(whiteColor);  /*undraw flop*/
    lastick=TickCount(); /*time delay for retace to improve animation*/
    do{curtick=TickCount();} while(lastick+1>curtick);
    for(i=1;i<=n;i++) LineTo((int)points[flop][i].h,(int)points[flop][i].v);
    ForeColor(blackColor);  /*draw flip*/
    do{curtick=TickCount();} while(lastick+1>curtick);
    for(i=1;i<=n;i++) LineTo((int)points[flip][i].h,(int)points[flip][i].v);
  }  /*end rotate*/
*  End everything                    *
      if(nextevent.what==mouseDown) buttondown=1;
}  /*program end*/

void mult(A,B,C)
  float A[][3],B[][3],C[][3];
  int i,j,k;
}  /*end mult*/

3D Modeling & Rotation

The main thrust of this exercise is to extend the line art rotation into 3D object rotation using the same techniques as the 2D, while also implementing parallel projection as our means of 3D modeling.

The first part of the exercise requires that we define an object in a structure that we can easily manipulate. Using a cube for simplicity, we will start by defining the center of the cube and an array of vertices, vertex[2][# of pts] (see GetPoints in program). Referring to fig. 1, each vertex corresponds to a corner of the cube. The second dimension of the array is to provide a destination for transformed vertices. Having both sets will allow us to undraw and immediately redraw the shape - minimizing the hangtime between redrawing allows for smoother animation.

Figure 1.

Next let us construct an array of lines connecting these vertices. Each element of the line array refers to the index of the beginning and ending vertex of that particular line. This array will never change. Think of when you roll a die - the edges still go between the same corners, but the position of the corners has changed.

The next construct is the translation and inverse translation matrixes. As in 2D rotation, we must transform our local center of rotation to the origin, rotate, then translate back.

The idea of homogeneous coordinates was introduced in the last article and is now extended into 3D by adding a fourth term. Fig. 2 shows our homogeneous coordinate as a 1x4 matrix times our translation matrix(4x4). The purpose of this multiplication is to add a dx, dy and dz to every point, in order to center our vertices about the origin. Please verify that the matrix multiplication results in X+dx,Y+dy,Z+dz (if unfamiliar with matrix multiplication see matmult in program).

Figure 2.

Now we once again reach the challenging concept of rotation. Although similar to 2D, we now have the option of rotating around the X and Y as well as the Z-axis.

The simplest, rotation about the z-axis, is just as in our 2D rotations, because none of the z-values change. If this is hard to understand, think about this: if you look straight down a pencil with the point a foot away from you and spin it a half turn, the point is still a foot away, but the writing is now on the other side. The equations for the changes in the X and Y are as follows:

  Xnew=XoldCos(Ø) + YoldSin(Ø)
  Ynew=-XoldSin(Ø) + YoldCos(Ø)

The 3D representation in matrix form with a vertex multiplication is in fig. 3. And the proof of all this is in that dusty old trigonometry book up on your shelf. (once again direct multiplication of fig. 3 will yield the preceding equations).

Figure 3.

Similarly rotation about the X axis changes none of the x-values, and rotation about Y changes none of the y-values. The transformation equations are given as follows:

Rotation about the X:

 Ynew=YoldCos(Ø) + ZoldSin(Ø)

Rotation about the Y:

   Xnew=XoldCos(Ø) - ZoldSin(Ø)
 Znew=XoldSin(Ø) + ZoldCos(Ø)

The corresponding matrices are shown in figures 4 and 5.

Figure 4.

Figure 5.

Once again we will construct a new array of vertices from a single transformation matrix formed from the translation to the origin, rotation about an axis, and translation back. Therefore creating the new vertices:


or after combining T*Rz*Tinv into a single Master Transformation(MT):


Finally the trick of parallel projection when viewing an object from down the Z axis is that all you have to do is draw lines between the x,y components of the points (ignore the z). For those mathematically inclined, you will realize that this is just the projection of those 3D lines on the X-Y plane (see fig. 6).

Figure 6.

The particular stretch of code I’ve included implements this transformation on the cube for rotation along the X and Y axes of the center of the cube using the arrow keys. The successive transformations of the vertices are loaded into the flip of the array (vertex[flip][pnt.#]). Then the flop is undrawn while the flip is drawn as mentioned previously and flip and flop are changed to their corresponding 0 or 1.

After launching, the application immediately draws the cube and then rotates it in response to the arrows. The program exits after a single mouse click.

Once again the code is not intended to match up to the guidelines - but is intended for use with other code or simple instructional purposes. It is concise as possible and should be easy to type in. A quick change to numofpts and numoflines as well as your own vertex and and line definitions would allow you to spin your favorite initial into its most flattering orientation.

The inspiration for this program came from the floating couch problem presented in Dirk Gently’s Holistic Detective Agency, by Douglas Adams. If enough interest is shown, perhaps a future article would include hidden line removal and color rendering techniques. After all, it was a red couch.

One last suggestion for those truly interested is to pull your shape definition in from a 3D cad program that will export in text format, such as Super 3D or AutoCad.

Anyway, on with the show

/* 3 */

/* Following is inline macro for drawing lines */
#define viewpts(s) {for(i=0;i<numoflns;i++)  \
                     { MoveTo((int)vertex[s][line[i].v1].x,  \
                       (int)vertex[s][line[i].v1].y); \
                       LineTo((int)vertex[s][line[i].v2].x, \
                       (int)vertex[s][line[i].v2].y); }}  
#define numofpts 8 /* A cube has eight vertices */
#define numoflns 12    /* lines for every face. */

/* the following are the data structs for vertices and lines*/ typedef 
struct rec1 {float x,y,z;} point3d;
typedef struct rec2 {int v1,v2;} edge;
void mult();/* Matrices multiplication */

  point3d vertex[2][8], /* array of 3D pts   */
          center;/* centroid of cube */
  edge    line[12];/* array of lines */
  int     buttondown=0, /* mousedwn flag(for prog end)*/
          keypressed=0,       /* keydwn flg(for arrows)     */
          flip=0,             /* This is index for vertex so*/
          flop=1,             /* can undraw flip & draw flop*/
          i,                  /* counter           */
          rot=0; /* Flag for direction of rotat*/
  long    low;   /* low word of keydwn message */
  float   a,/* Particular angle of rotat     */
          R[4][4], /* Rotation matrix*/
          c[4][4], /* Product of trans & rot mats*/
          d[4][4], /* Product of c and inv trans */
          T[4][4],Tinv[4][4], /* Translation & inv trans    */
          x=0.087266;/* Algle of rot in rad  */
  EventRecord nextevent;
  KeyMap    thekeys;
  WindowPtr scnwdw;
  Rect      scnrect;
*  Set things up *
*  Get points. Arbitrary cube.*

*  Rotate *
viewpts(flip);   /* This draws first set of pts*/
  while(!buttondown) /* Mini event loop*/
      if(nextevent.what==mouseDown) buttondown=1;
      else if(nextevent.what==keyDown) keypressed=1;
      else if(nextevent.what==autoKey) keypressed=1;
    if(keypressed) /* Find out which one     */
      if(low==126) {rot=1;a=-x;} /* Set dir flag and-*/
      if(low==124) {rot=2;a=-x;} /* angle(pos or neg */
      if(low==125) {rot=3;a=x;}
      if(low==123) {rot=4;a=x;}
        case 1:/* Both of these are rot about the X axis */
        case 3: R[0][0]=1;R[0][1]=0;R[0][2]=0;R[0][3]=0;
        case 2:/* Both of these are rot about the Y axis */
        case 4: 
      }  /*end switch*/
      mult(T,R,c); /* Combine trans & rotation */
      mult(c,Tinv,d);/* Combine that and inv trans */
      flip++;flip=flip%2;flop++;flop=flop%2; /* flip flop   */
      /* The following actually calculates new vert of rotat*/
       viewpts(flop);/* Undraw*/
       viewpts(flip);/* Draw*/
    }  /*end update points*/

*  End everything*
}  /*program end*/

void mult(A,B,C)
  float A[][4],B[][4],C[][4];
  int i,j,k;
}  /*end mult*/

Apple Inc.
Microsoft Corpora
Google Inc.

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty
Download the patch by launching the Starcraft II game and downloading it through the connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »
Evernote Business Notebook by Moleskin I...
Evernote Business Notebook by Moleskin Introduced – Support Available in Evernote for iOS Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »

Price Scanner via

Deal Alert! 13-inch MacBook Pro on sale for $...
Best Buy has the 13″ 2.5GHz MacBook Pro on sale for $999.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $200 off MSRP. Price is valid... Read more
Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more

Jobs Board

*Apple* Inc. Research Data Specialist - Appl...
…of Worldwide Market Research & Intelligence. The team is responsible for conducting Apple branded consumer market research. It is also responsible for analyzing data Read more
*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.