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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.