TweetFollow Us on Twitter

From Algorithm to Animation: the Sequel

Volume Number: 19 (2003)
Issue Number: 7
Column Tag: QuickTime

From Algorithm to Animation: the Sequel

Making QuickTime movies which illustrate abstract processes

by Jay Martin Anderson

THE ORIGINAL

In the November 1993 issue of MacTech (volume 9, number 11), I described how I made a QuickTime movie of an algorithm from computational mathematics. In the intervening ten years, QuickTime has grown and matured, the Mac OS has crossed the divide between Classic and OS X, and several generations of IDEs have come and gone.

My interest in making QuickTime movies to illustrate algorithms from computer science and mathematics has not. Consequently, I wish to present an update of the technique used to make animations of algorithms, and apply it to a theorem from beginning calculus which my colleagues challenged me to illustrate this year.

THE PROBLEM

The Department of Mathematics at Franklin and Marshall College includes both mathematics and computer science and frequently enjoys sharing problems in one area with the other. In the spring of 2003, my mathematician colleagues challenged me to construct a way to depict the Mean Value Theorem (MVT) which states that, for a suitably "nice" function f(x) on a range a <= x <= b, somewhere (some x = c, a <= c <= b) the slope of the function, f'(c) is equal to the "rise over run" of the function, (f(b)-f(a))/(b-a).

I chose to take a particular function f(x) = x3 on the range -1 <= x <= 1, trace along the function showing a line tangent to the curve at each point, and stop when the tangent line had the same slope as the "rise over run," which is 1.

THE PARADIGM

At F&M we have developed a paradigm for constructing algorithm animations. We divide the moviemaking application into three parts: the model, the view, and the controller.

The model contains the algorithm to be visualized. In this example, it is the function and its derivative. The state of the model is the value of x, along with the value of f(x) and f'(x).

The view contains the graphical elements necessary to illustrate the model. It is in the view that a single picture of a single state of the model is developed. In our work beginning in 2003, the view is developed with OpenGL. In the view we will draw the graph of the function, the tangent line at every value of x, the line which represents the "rise over run," and any tangent line with the same slope as "rise over run."

The controller does all the initialization and cleanup necessary for the moviemaking application. In particular, it does all the work necessary to pass individual views to QuickTime for the formation of a movie. Most importantly, the controller contains the timing, which signals the model to change its state and the view to generate a new picture. The controller will continue to ask the model to change its state until the value of x has spanned the entire range of interest.

Many movies are divided into "acts" and "scenes," much like a real theater piece. This provides a simple way to modularize the model and the view, and is particularly useful if the animated view of the model is more complex than simply moving an object along a path. For this simple example, acts and scenes are not necessary.

Our movies are also annotated. A view of a state of the model is also accompanied by a few sentences of text which explain what the view shows. The resulting QuickTime movie has one video track, and one text track for each (natural) language necessary. The natural language feature of QuickTime makes it particularly easy to construct movies in English, German, Italian, etc. The text annotation in this movie gives numerical values for x and f'(x).

Beginning in 2003, our development platform for algorithm animation is Apple's Developer Tools, including Project Builder and Interface Builder. The application is developed in Objective-C, using Cocoa classes. The model is a subclass of NSObject; the view is a subclass of NSOpenGLView; and the controller is also a subclass of NSObject. Since the movie, and not the application which creates it, is the object of this exercise, the graphical user interface is kept as simple as possible, often including only a button "Make Movie" and perhaps some widgets to select among choices for the movie.

The connection between the strictly object-oriented Objective-C and Cocoa classes, and the older QuickTime API is not always elegant. Nonetheless, it is that connection which is perhaps the most significant contribution of this article. Almost every time the controller has to move information between the model or the view and QuickTime, some conversion is necessary.

Using Interface Builder

We begin with Project Builder and construct a new project, a Cocoa application. Interface Builder allows us easily to construct a window and view of appropriate size, place whatever GUI widgets we need in the window, construct the model and controller objects, and generate some source code for the model-view-controller system.

Launch Interface Builder by double-clicking the MainMenu.nib icon, which is found inside the Resources folder of the Files pane of the project. Make the window an appropriate size, and drag a Custom View onto the window. Make the Custom View be an appropriate size as well. Create a subclass of NSOpenGLView, such as MyOpenGLView, and make the Custom View be an instance of MyOpenGLView.

Drop whatever widgets you need into the window. In this example, we use only a button, labeled Make Movie.

Create a subclass of NSObject called MyController and a subclass of NSObject called MyModel. Within MyController, create an Action method, for example, createMovie. Also within MyController, create Outlets, which are instances of the classes MyModel and MyOpenGLView, respectively. Likewise, in the class MyOpenGLView, create an Outlet, which is an instance of the class MyModel.

Make instances of these classes, and generate code for these classes.

Build connections as follows: from any widgets, such as the Make Movie button to the instance of MyController, with the target of the createMovie method; from the instance of MyController to the instance of MyModel; from the instance of MyController to MyOpenGLView; and finally from the instance of MyOpenGLView to the instance of MyModel. The connection from the button to the method means that the button sends the createMovie message to the controller. The connection from the controller to the model means that the controller can send messages (usually inquiries) to the model, and likewise to the view. The connection from the view to the model means that the view can send messages (again, usually inquiries) to the model.


Figure 1. Using Interface Builder. The window contains the view, a subclass of NSOpenGLView, and one button. The view is connected to the class MyModel, so that the view may inquire the state of the model.

This completes the work with interface builder; save the nib and continue with Project Builder.

The Code

The work of managing QuickTime is done with the createMovie method of the controller object. This also includes code to provide an interface, albeit awkward, between the Objective-C classes of Cocoa and the "legacy" code of QuickTime. Three points bear special mention.

First, OpenGL draws into a context, which is described by a pixel format. QuickTime accepts images from a pixMap, which is part of the GWorld data structure. The function CopyNSBitmapImageRepToGWorld accomplishes the task of copying pixels from the first to the second environment. It is based on the assumption of 32-bit pixels in each structure. Curiously, the copying of pixels requires an NSBitmapImageRep, which is four bytes wider than the context.

Second, QuickTime constructs a movie file using an FSSpec. The FSSpec must be derived from a path or file name in the "classic" Macintosh format, and it must appear as a Pascal string. The function QTUtils_ConvertCToPascalString serves to convert a C-string to a Pascal string.

Finally, the image drawn by OpenGL is inverted when it is copied to QuickTime. Given that the QuickTime movie is the object of this exercise, it seems simplest to construct the OpenGL drawings upside-down, and let the pixel copying to QuickTime invert them to the proper orientation.

The code for the class MyController, as well as for portions of the classes MyModel and MyOpenGLView, along with all header files, can be found on the website

http://eDisk.fandm.edu/~jay.anderson/mactech/example.html

The model is the simplest unit in this example. The methods f and ff serve to calculate the function and its derivative. The method changeState advances a point along the curve by equal increments in the x-direction, and computes the corresponding value of the function and its derivative. The method changeState also looks for matches between the slope of the curve and the "rise over run," and records the matches.

Listing 1: MyModel.m

MyModel

A portion of the class MyModel, which encapsulates the algorithm to be illustrated and its data 
structures.  Shown here are the method changeState, and the methods that evaluate the function and 
its derivative.  The remainder of the class, and the header file MyModel.h are found on the website.

@implementation MyModel
- (void)changeState:(int)frNo
{
   if (frNo == 0)
   {
      // beginning frame is blank, with only an annotation
      strcpy(annotation, "MEAN VALUE THEOREM.  Compare
 rise/run to slope of graph.");
   }
   else
   {
      // as frame number goes from 0 to 200, x goes from -1.0 to 1.0 in 200 steps
      x = -1.0 + frNo/100.0;
      y = [self f:x];
      slope = [self ff:x];
      sprintf(annotation, "x = %5.2f, y = %5.2f, slope =
 %5.2f", x, y, slope);
      if (fabs(slope - ror) < 0.01) 
      {
         // slope matches rise/run; record this position, append extra annotation
         match = 1;
         xMatch[nMatches++] = x;
         strcat(annotation, "\rSlope matches rise/run: mean
 value theorem!");  
      }
      else                          
         match = 0;
   }
}
- (float)f:(float)z
{ return z*z*z; }
- (float)ff:(float)z
{ return 3*z*z; }
@end

The view is responsible for drawing the curve, the "rise over run" line, a point and tangent line which moves along the curve as the state of the model changes, and any matches between the slope of the curve and the rise-over-run line. These are simple OpenGL primitives: point, line and line-strip. Colors, the point size and the line width are chosen for viewing ease.

Listing 2: MyOpenGLView.m

MyOpenGLView

The method drawRect from the class MyOpenGLView; the remainder of the class and the header file 
MyOpenGLView.h are found on the website.  This method is invoked when the display message is sent 
to the view.  It draws each frame of the movie.  

@implementation MyOpenGLView
- (void)drawRect:(NSRect)rect
{
   float x, y, slope;
   short match;
    
   glClear(GL_COLOR_BUFFER_BIT);   // clear the screen
   x = model->x;
   y = model->y;
   slope = model->slope;
   match = model->match;
   
   /* Draw the components of the frame:  the graph of the function, the rise/run line,
      the point at (x, y), and the slope of the graph at that point.
   */
   [self drawGraph];                  
   [self drawRR];
   [self drawPoint:x:y];
   [self drawSlope:x:y:slope];
 
   /* Draw a tangent line at each place where the slope of the function matches the
      rise/run line.
   */   
   if (model->nMatches > 0)
   {
      int i;
      for (i = 0; i < model->nMatches; i++)
         [self drawMatch:i];
   }
   // show it!
   glFlush();
}
@end

The text annotations are developed within the model, and left in a string. In the controller, this string is copied to the text handler, just as the image is copied to an image compressor. Color, font, and size of text can be chosen when the text handler is constructed.

Lights! CAMERA!  ACTION!

The controller runs a simple loop to construct successive frames of the movie. In particular, the controller sends the changeState message to the model, and then the display message to the view. This image is then copied to QuickTime and compressed. In addition, the controller sends a getText message to the model to acquire the annotation to be placed into the text track.

Results

The model-view-controller paradigm has been implemented for making QuickTime movies that illustrate algorithms in Java and in Cocoa/Objective-C. The Cocoa/Objective-C implementation allows the use of OpenGL with QuickTime in a workable, if awkward, marriage of Objective-C classes with "legacy" QuickTime APIs. This opens up abstract moviemaking to the standard of OpenGL, including three-dimensional graphics. The Java implementation, which is not described here, does not require the awkward connection between software components, but does not provide easy access to OpenGL.


Figure 2. One frame of the Mean Value Theorem movie. The test point has moved from x = -1.00 to x = -0.32, and has found one spot where the slope of the curve matches the rise/run line. The text track is shown in white on blue beneath the video track.

Besides the sample movie described here, our work in 2003 and beyond includes constructing animations of algorithms from computational geometry, such as the triangulation of a polygon, constructing and searching in kd-trees and range trees, and more. Our recent work includes animations of algorithms for computing the convex hull, for the intersection of many line segments and for recognizing the polygon in which a point lies. Sample movies are posted on our web site (begin at http://eDisk.fandm.edu/~jay.anderson) as they become available.

ACKNOWLEDGMENTS

Significant assistance has come from Apple Computer, from whom code to construct QuickTime movies, media, and tracks has been borrowed; and from Big Nerd Ranch and Aaron Hillegass, whose Cocoa programming book, course and advice were enormously useful.


Jay Martin Anderson is the Richard S. and Ann B. Barshinger Professor of Computer Science at Franklin and Marshall College in Lancaster, Pennsylvania. Once a physical chemist, he has been teaching computer science since 1978 and making QuickTime movies since 1992. His interests include many aspects of computer graphics, including cartography and computational geometry; opera, theatre, and bicycling. He can be reached at jay.anderson@fandm.edu.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.