TweetFollow Us on Twitter

Dec 98 Getting Started

Volume Number: 14 (1998)
Issue Number: 12
Column Tag: Getting Started

Color Animation

by Dave Mark and Dan Parks Sydow

How a Mac program generates smooth, flicker-free color animation

A couple of articles back we covered the bitmap and its use in offscreen drawing to create smooth black and white animation. Last month's article introduced Color QuickDraw and drawing in color. In this month's article we combine all these recently learned techniques to tackle smooth, fast, color animation.

Bitmaps and Offscreen

Drawing Review

A bitmap is a representation of a monochrome (blacK-and-white) image. The map is composed of a grid of pixels, with each pixel considered either on or off. An image is defined by specifying the state of each pixel in the map. A single bit is used to keep track of whether a single pixel is on or off.

An offscreen bitmap is a bitmap that is drawn in memory alone - it doesn't have an onscreen representation. That is, a data structure holds the bit information that defines an image, but the contents of this data structure aren't translated to a window's graphics port. Animation is accomplished using a total of three offscreen bitmaps. One bitmap holds a background image, a second bitmap holds the foreground image, and the third bitmap is a mixer, or master, that is a combination of the other two bitmaps. The image that is the foreground bitmap and the image that is the background bitmap combine in the master bitmap offscreen (in memory), after which the image in the master (and only the master) bitmap appears onscreen. Repeating this process via a loop, with a slight shift of the position of the foreground image relative to the background image, is the basis for animation. Because each pass through the loop creates a master bitmap behind the scene in memory rather than in view of the user onscreen, flicker is kept to a minimum.

Pixmaps and Offscreen Drawing

For monochrome animation, the BitMap data structure is used to define the state of the pixels that make up a bitmap image. Here's the BitMap data structure:

struct BitMap
{
   Ptr        baseAddr;
   Short      rowBytes;
   Rect       bounds;
};

A color image necessitates the use of a different data structure. The PixMap data structure includes the same three fields as the BitMap data structure - but it also holds more information as well. Among the extra information stored in the more complex PixMap is the number of bits used to define the color of each pixel. Here's a look at the PixMap data structure:

struct PixMap {
   Ptr               baseAddr;      /*pointer to pixels*/   
   short             rowBytes;      /*offset to next line*/
   Rect              bounds;        /*encloses bitmap*/
   short             pmVersion;     /*pixMap vers number*/
   short             packType;      /*defines packing */
   long              packSize;      /*length of data*/
   Fixed             hRes;          /*horiz. Res. (ppi)*/
   Fixed             vRes;          /*vert. Res. (ppi)*/
   short             pixelType;     /*defines pixel type*/
   short             pixelSize;     /*bits in pixel*/
   short             cmpCount;      /*components in pixel*/
   short             cmpSize;       /*bits per component*/
#if OLDPIXMAPSTRUCT
   long              planeBytes;    /*plane*/
   CTabHandle        pmTable;       /*color map*/
   long              pmReserved;
#else
   OSType            pixelFormat;   /*fourCharCode rep.*/
   CTabHandle        pmTable;       /*color map*/
   PixMapExtHandle   pmExt;         /*pixMap handle ext.*/
#endif
};

With monochrome bitmap animation, all you had to do was fill out the relatively simple BitMap structure, create a GrafPort, then connect the two via a call to SetPortBits(). Once that's done, you are ready to copy the BitMap from port to port via a call to CopyBits().

A PixMap is more complex than a BitMap, so color pixel map animation requires extra effort. Fortunately, the Toolbox offers a high-level set of functions that simplify somewhat the creation of offscreen PixMaps. An offscreen PixMap is known as a graphics world, or GWorld. A GWorld is created in memory and typically drawn to a window via a call to CopyBits(), just as done with a BitMap.

The GWorld is a full-color, offscreen drawing environment. Just as you'd use an offscreen GrafPort and BitMap to prepare a black-and-white image for blitting to the screen (blitting comes from BLock Transfer, meaning copying a block of memory from one area to another, all at once), you'll use a GWorld to do the same for a color image.

PixMapper

Two issues ago, the Getting Started program BitMapper was developed to demonstrate offscreen animation using black-and-white bitmaps. Figure 1 shows the window displayed by BitMapper. The floating hand is the foreground image and the framed gray pattern is the background image. As you move the mouse, the hand appears to float over the gray background, just like a cursor. What the user is seeing is the mixer bitmap - the copied version of the offscreen bitmap that represents the combining of the foreground hand bitmap with the background gray bitmap.

Figure 1. The BitMapper window.

This month's program is called PixMapper. Like BitMapper, PixMapper moves a foreground image over a background image. As we did for BitMapper, in PixMapper we create a PICT resource to serve as the foreground image. To demonstrate a different technique, though, in PixMapper we create the background image in our code. Figure 2 shows the PICT resource (an image we copied from the Scrapbook) moving over the background (which is simply a checkerboard pattern drawn with few calls to QuickDraw routines).

Figure 2. PixMapper in action.

As soon as you run PixMapper the menu bar, featuring the Apple, File, Edit, and Help menus, appears. With the exception of the Quit item in the File menu, there's nothing of significance in these menus. Next, a window appears, filling the entire main screen (the screen with the menu bar). PixMapper fills the window with a checkerboard pattern of red and green colored squares (just in time for Christmas, of course!). PixMapper then loads a PICT resource, and uses a series of offscreen GWorlds to animate the PICT across the colored background. The animation begins in the upper left corner and moves towards the lower right. Every time the PICT hits the edge of the window, the PICT bounces off and continues in the opposite direction.

The speed of the foreground image depends on the speed of your machine and the size of the PICT. The important thing to notice is that the PICT animates smoothly with absolutely no flicker. If there is any hesitation, it is most likely due to the system taking time to do some housekeeping chore.

Creating the PixMapper Resources

To get started, open your CodeWarrior development folder and create a folder named PixMapper. Start up ResEdit and create a new resource file named PixMapper.rsrc inside the PixMapper folder. Figure 3 shows the five types of resources used by PixMapper. By now you should be experienced in creating and working with each of these resource types.

Figure 3. The PixMapper resources.

Figure 3 shows the three MENU resources the program needs. Only the Quit item in the File menu is of significance - the other items exist in preparation for turning PixMapper into a "real" program.

PixMapper uses the same ALRT and DITL resources that have been used in recent Getting Started examples. The one ALRT and one DITL are used to support the error-handling alert displayed by the program's DoError() routine (see the September 1998 Apple Events Getting Started column for more information on these resources and on the DoError() routine).

The one WIND resource will be used to display the color animation. The size of the WIND isn't at all important - we'll be resizing the window from within the source code. Since the window will be fixed on the screen, the type of WIND isn't too important either, though you'll want to choose a type that foregoes the drag bar (title bar) so the user doesn't get the impression that the window is movable.

You need a single PICT resource to serve as the foreground image. In the PixMapper source code we'll be referencing this resource by an ID of 128, so make sure to assign the PICT that value. For the foreground image you'll want something relatively small. Of course to witness the power of the PixMapper program you'll want to use a color image. You might also consider using a picture that is non-rectangular or that has a hole in it. In your paint program use the lasso tool to select only the pixels in the picture (and not the background). Though a rectangular picture will work just fine, a non-rectangular picture (like an X or an O shape) produces much more impressive results.

That's it for the PixMapper.rsrc file. Now quit ResEdit, making sure to first save your changes.

Creating the PixMapper Project

Launch CodeWarrior and create a new project based on the MacOS:C_C++:MacOS Toolbox:MacOS Toolbox Multi-Target stationary. You should have already created a project folder, so uncheck the Create Folder check box. Name the project PixMapper.mcp and designate the PixMapper folder as the project's destination. Remove the SillyBalls.c and SillyBalls.rsrc placeholder files from the new project window, then add the PixMapper.rsrc file. The PixMapper project doesn't use of any of the standard ANSI libraries, so feel free to remove the ANSI Libraries folder.

Now choose New from the File menu to create a new, empty source code window. Save it with the name PixMapper.c and then choose Add Window from the Project menu to add the file to the project. The full source code listing for the PixMapper program appears next in the source code walk-through. You can type it into the PixMapper.c file as you read the walk-through, or you can take a shortcut and download the entire PixMapper project from MacTech's ftp site at ftp://ftp.mactech.com/src/mactech/volume14_1998/14.12.sit.

Walking Through the Source Code

On to the code. As with other Getting Started projects, PixMapper starts off with some constant definitions.

/********************* constants *********************/

#define kMBARResID            128
#define kALRTResID            128
#define kWINDResID            128

#define kSleep                7
#define   kMoveToFront        (WindowPtr)-1L

#define kSquareSize           16

#define kForegroundPICT       128
#define kIgnored              nil
#define kUseMaxDepth          0

#define mApple                128
#define iAbout                1

#define mFile                 129
#define iQuit                 1

There is a bunch of globals used by PixMapper. The familiar gDone starts life as false and is set to true when Quit is selected from the File menu. The program's only window is kept track of using the WindowPtr variable gMainWindow. Variables gXBump and gYBump specify the number of pixels the PICT moves each new animation cycle. One way to speed up the animation is to raise the bump values, though the code was written to work with single pixel movements.

/****************** global variables *****************/

Boolean           gDone;
WindowPtr         gMainWindow;
short             gXBump = 1, gYBump = 1;

We'll use three GWorlds. The graphics world gPictWorld holds the PICT image. Graphics world gSaveWorld holds the background of the window for later restoration. Finally, gSaveMixWorld is used to combine the PICT and the background. The three PixMapHandles are handles to the PixMaps tied to their respective GWorld.

GWorldPtr         gPictWorld;
GWorldPtr         gSaveWorld;
GWorldPtr         gSaveMixWorld;
PixMapHandle      gPixMapSave;
PixMapHandle      gPixMapSaveMix;
PixMapHandle      gPixMapPict;

The rectangle gPictWorldRect is the exact size of the PICT and is the bounding rectangle for gPictWorld. Rectangle gWorldRect is the bounding Rect for the mixing GWorld. The mixing GWorld is one pixel bigger in all directions than the PICT. This was done so that when we save a region the size of gWorldRect from the PixMapper window, we'll have a one pixel border around the PICT. This way, when the PICT moves one pixel in any direction, we'll have the right pixels saved for later restoration. You'll see how this works later in the code. Rectangle gSavedFloaterRect contains the current position of the PICT in the PixMapper window.

Rect                  gPictWorldRect;
Rect                  gWorldRect;
Rect                  gSavedFloaterRect;

Next come the program's function prototypes:

/********************* functions *********************/
void            ToolBoxInit( void );
void            MenuBarInit( void );
Boolean      HasGWorlds( void );
void            CreateWindow( void );
void            PaintWindow( void );
void            GWorldInit( void );
GWorldPtr    MakeGWorld( Rect *boundsPtr );
void            DrawFirstFloater( void );
void            MoveFloater( void );
void            CalcNewFloaterPosition( void );
void            EventLoop( void );
void            DoEvent( EventRecord *eventPtr );
void            HandleMouseDoWn( EventRecord *eventPtr );
void            HandleMenuChoice( long menuChoice );
void            HandleAppleChoice( short item );
void            HandleFileChoice( short item );
void            DoError( Str255 errorString );

As always, main() begins by initializing the Toolbox.

/************************ main ***********************/

void   main( void )
{
   ToolBoxInit();

Next, HasGWorlds() is called to see if GWorlds are available on this machine. We'll look at HasGWorlds() just ahead.

   if ( ! HasGWorlds() )
      DoError( "\pDeep GWorlds not supported" );

If so, the menu bar is set up, the main window is created, and the three graphics worlds are created. Both CreateWindow() and GWorldInit() are discussed later in this walk-through.

   MenuBarInit();
   CreateWindow();
   GWorldInit();

Next, the initial position of the PICT is plotted and the main animation loop is entered. The word floater refers to the foreground PICT, which appears to float over the background.

   DrawFirstFloater();
   
   EventLoop();
}

ToolBoxInit() and MenuBarInit() are the same as prior versions.

/******************** ToolBoxInit ********************/

void   ToolBoxInit( void )
{
   InitGraf( &qd.thePort );
   InitFonts();
   InitWindows();
   InitMenus();
   TEInit();
   InitDialogs( NULL );
   InitCursor();
}

/******************** MenuBarInit ********************/

void   MenuBarInit( void )
{
   Handle         menuBar;
   MenuHandle      menu;
   
   menuBar = GetNewMBar( kMBARResID );
   SetMenuBar( menuBar );

   menu = GetMenuHandle( mApple );
   AppendResMenu( menu, 'DRVR' );
   
   DrawMenuBar();
}

HasGWorlds() calls Gestalt() using the selector gestaltQuickdrawFeatures. If Gestalt() returns an error we'll display an appropriate error message.

/********************* HasGWorlds ********************/

Boolean   HasGWorlds( void )
{
   long      response;
   long      mask;
   OSErr   err;
   
   err = Gestalt( gestaltQuickdrawFeatures, &response );
   
   if ( err != noErr )
      DoError( "\pError calling Gestalt()" );

Next, we'll set up a comparison mask so we can look at the appropriate bit in response. Since gestaltHasDeepGWorlds has a value of 1, we'll want to look at bit number 1, which is the second bit from the right. We'll use the << operator to set bit number 1 in mask, leaving mask with a value of 2.

   mask = 1 << gestaltHasDeepGWorlds;

Finally, we'll use mask to see if bit number 1 is set in response. If so, deep GWorlds are available and we'll return true. Otherwise, we'll return false.

   if ( response & mask )
      return true;
   else
      return false;
}

CreateWindow() creates a new color window a little shorter than the main screen. The top of the window starts just below the menu bar. After setting up the window's size, a call to GetNewCWindow() creates a new CWindowRecord (as opposed to the WindowRecord that would result from a call to GetNewWindow()).

/******************* CreateWindow ********************/

void   CreateWindow( void )
{
   Rect      wBound;
   long      wWidth, wHeight;
   
   wBound = qd.screenBits.bounds;
   wBound.top += GetMBarHeight();
         
   gMainWindow = GetNewCWindow(    kWINDResID, nil,
                                   kMoveToFront);

The window is based on a WIND resource. Recall that we chose an arbitrary size for the window when creating this resource. Now it's time to match the window size to the size of the user's screen. The window boundary calculations are based of the wBound rectangle, which holds the display area of the graphics device (less the menu bar height). Finally, a call to PaintWindow() fills the window with colored rectangles.

   wWidth = wBound.right - wBound.left;
   wHeight = wBound.bottom - wBound.top;
   
   SizeWindow( gMainWindow, wWidth, wHeight, true );
   MoveWindow( gMainWindow, wBound.left, wBound.top, true );
   
   ShowWindow( gMainWindow );
   SetPort( gMainWindow );

   PaintWindow();
}

PaintWindow() starts by declaring several variables and calculating the number of columns and rows in the PixMapper window.

/******************** PaintWindow ********************/

void   PaintWindow( void )
{
   RGBColor      redColor  = {65535, 0, 0};
   RGBColor      greenColor = {0, 40000, 15000};
   RGBColor      currentColor;
   Rect            r;
   short         row, col, numRows, numCols;
   
   SetPort( gMainWindow );
   
   r = gMainWindow->portRect;

Both numCols and numRows are based on kSquareSize. Each square on the window will be kSquareSize pixels on a side. If either numCols or numRows is not evenly divisible by kSquareSize, we'll add another row or column just so we don't leave any white space at the edge of the window.

   numCols = (r.right - r.left) / kSquareSize;
   if ( numCols != numCols/kSquareSize * kSquareSize )
      numCols++;
      
   numRows = (r.bottom - r.top) / kSquareSize;
   if ( numRows != numRows/kSquareSize * kSquareSize )
      numRows++;

Next, we'll step through all the squares, drawing each in the color appropriate to create a red and green checkerboard pattern. First, we set up the boundaries of a single square.

   for ( row = 0; row < numRows; row++ )
      for ( col = 0; col < numCols; col++ )
      {
         r.top = row * kSquareSize;
         r.bottom = r.top + kSquareSize;
         r.left = col * kSquareSize;
         r.right = r.left + kSquareSize;

Now, we determine whether the square should be red or green. Recall from your C background that the modulus operator (%) returns the remainder of an integral division. So, for example, if row is even and we divide by 2, the modulus result is 0 (no remainder). If row is odd when we divide by 2, the modulus is always 1. The following could be written a little more compact then it now appears, but the result would be even more confusing!

         if ( ( row % 2 == 1 ) && ( col % 2 == 1 ) )
            currentColor = redColor;
         else if ( ( row % 2 == 0 ) && ( col % 2 == 0 ))
            currentColor = redColor;
         else
            currentColor = greenColor;

A call to RGBForeColor() is made to set up subsequent drawing in the appropriate color. Recall from last month that RGBForeColor() is the QuickDraw routine that accepts an RGB color as its parameter. A call to the QuickDraw function PaintRect() actually draws the colored rectangle.

         RGBForeColor( &currentColor );
         
         PaintRect( &r );
      }

When we're done, we set the foreground and background colors to their normal values. QuickDraw defines eight global constants to represent eight very basic colors (including black and white - refer to the QuickDraw.h universal header file for the rest). The QuickDraw routines ForeColor() and BackColor() are used with any of these eight constants to set the foreground color (the color used for drawing) and the background color (the color used to repaint a window's content area). Note that we could have used RGBForeColor() and RGBBackColor() here, provided we set up and specified black and white as RGBColor variables.

   ForeColor( blackColor );
   BackColor( whiteColor );
}

Now it's time to look at some code that involves graphics worlds. The three GWorlds are created in GWorldInit(), a routine that was called from main(). GWorldInit() starts by loading the PICT resource.

/********************* GWorldInit ********************/

void   GWorldInit( void )
{
   PicHandle      pic;
   
   pic = GetPicture( kForegroundPICT );

   if ( pic == nil )
      DoError( "\pError loading PICT..." );

We'll grab the PICT's frame and normalize it (make its upper left corner (0,0)).

   gPictWorldRect = (**pic).picFrame;
   OffsetRect(    &gPictWorldRect, -gPictWorldRect.left, 
                     -gPictWorldRect.top );

gWorldRect is set to be 2 pixels taller and 2 pixels wider than the PICT. That leaves a one pixel border all the way around.

   gWorldRect = gPictWorldRect;
   gWorldRect.bottom += 2;
   gWorldRect.right += 2;

Next, we'll call our own MakeGWorld() routine to build one GWorld the size of the PICT and two the size of gWorldRect, storing the pointers in our three globals.

   gPictWorld = MakeGWorld( &gPictWorldRect );
   gSaveWorld = MakeGWorld( &gWorldRect );
   gSaveMixWorld = MakeGWorld( &gWorldRect );

When we create a GWorld, a PixMap is created for us. We'll call GetGWorldPixMap() to store the handle to each PixMap in its respective global.

   gPixMapPict = GetGWorldPixMap( gPictWorld );
   gPixMapSave = GetGWorldPixMap( gSaveWorld );
   gPixMapSaveMix = GetGWorldPixMap( gSaveMixWorld );

Next, we'll lock all three PixMaps in memory. Why? Just as you'd lock a handle before you singly dereferenced it to access its pointer, you lock your PixMap before you draw into it. Normally, you'd lock the pixels just before you draw, then unlock the pixels after the call to the drawing routine returns to prevent heap fragmentation. To keep things simple, we're just going to lock all three PixMaps for the duration of the program.

   if ( ! LockPixels( gPixMapPict ) )
      DoError( "\pLockPixels failed..." );

   if ( ! LockPixels( gPixMapSave ) )
      DoError( "\pLockPixels failed..." );

   if ( ! LockPixels( gPixMapSaveMix ) )
      DoError( "\pLockPixels failed..." );

Finally, we'll make the gPictWorld the current GWorld and draw the PICT in it. SetGWorld() makes the specified GWorld the current port, just as a call to SetPort() might make a window the current port.

   SetGWorld( gPictWorld, kIgnored );
      
   DrawPicture( pic, &gPictWorldRect );
}

MakeGWorld() calls NewGWorld() to create a new GWorld, returning a pointer to the new GWorld. The first parameter is the address of the GWorldPtr that will eventually point to the new GWorld. The second parameter specifies the pixel depth of the new GWorld. By passing in a value of 0, we're asking NewGWorld() to use the deepest device that intersects boundsPtr, the third parameter. The fourth and fifth parameters specify a color table and a GDevice, in case you want to roll your own. We'll pass nil in for each, asking NewGWorld() to take care of these parameters for us. The final parameter lets us set special GWorld flags. We'll pass in 0, ignoring the flags. You can read about these flags in the description of NewGWorld() in the Offscreen Graphics Worlds chapter of Inside Macintosh: Imaging With QuickDraw.

/********************* MakeGWorld ********************/

GWorldPtr MakeGWorld( Rect *boundsPtr )
{
   QDErr         err;
   GWorldPtr   newGWorld;

   err = NewGWorld( &newGWorld, kUseMaxDepth,
            boundsPtr, kIgnored, kIgnored, noNewDevice );
            
   if ( err != noErr )
      DoError( "\pMy call to NewGWorld died! Bye..." );
   
   return( newGWorld );
}

Here, in DrawFirstFloater(), comes the really important stuff. Just as it did in BitMapper, CopyBits() is used to copy a block of pixels from one offscreen to another. Though CopyBits() expects to work with pointers to BitMaps, it can handle either BitMaps or PixMaps. A bit of typecasting is necessary, however, if only to placate the compiler's typecasting mechanism.

/****************** DrawFirstFloater *****************/

void   DrawFirstFloater( void )
{

Each call to CopyBits() copies from the first parameter to the second, using the Rects in the third and fourth parameters. The srcCopy mode tells CopyBits() to replace all the destination bits with the appropriate source bits. The transparent mode, on the other hand, tells the compiler not to copy the white pixels. This comes in handy when we copy a non-rectangular or non-solid image from one GWorld to another. The last parameter to CopyBits() specifies an optional mask parameter which we won't use. Passing nil tells CopyBits() to ignore this parameter.

The first call to CopyBits() copies the background of the PixMapper window into the gPixMapSave PixMap. We're saving away the pixels we're about to obliterate with the PICT, with an extra one pixel border we'll need when the floater moves in one direction or the other.

   CopyBits(    &(gMainWindow->portBits), 
                  (BitMap *)(*gPixMapSave),
                  &gWorldRect, &gWorldRect, srcCopy, nil );

Next, we'll set up a Rect the size of the PICT that is 1 pixel down and 1 pixel to the right of the upper left corner of the window. This is where we'll plot the PICT.

   gSavedFloaterRect = gPictWorldRect;
   OffsetRect( &gSavedFloaterRect, 1, 1 );

This call to CopyBits() draws the PICT in the PixMapper window.

   CopyBits(    (BitMap *)(*gPixMapPict), 
                  &(gMainWindow->portBits),
                  &gPictWorldRect, &gSavedFloaterRect, 
                  transparent, nil );
}

MoveFloater() is responsible for moving the foreground image. Because the image is moved only slightly, MoveFloater() gets called repeatedly from the event loop. MoveFloater() starts off by calling CalcNewFloaterPosition() to update the values of gXBump and gYBump, in case the floater is hitting the edge of the window.

/******************** MoveFloater ********************/

void   MoveFloater( void )
{
   Rect      r;
   RgnHandle   newRgn, savedRgn, oldClip;

   CalcNewFloaterPosition();

This call to CopyBits() copies the saved pixels to the mixer GWorld.

   CopyBits(    (BitMap *)(*gPixMapSave), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gWorldRect, &gWorldRect, srcCopy, nil );

Next, we position a Rect the size of the PICT in the mix GWorld using gXBump and gYBump. This Rect is the new position of the floater in the mix GWorld. We'll then call CopyBits() to copy the floater on top of the saved pixels in the mixing GWorld. Remember, we used transparent mode so we'd only draw the non-background pixels. You might want to handle this differently if you need to draw white pixels.

   r = gPictWorldRect;
   OffsetRect( &r, gXBump + 1, gYBump + 1 );
   
   CopyBits(    (BitMap *)(*gPixMapPict), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gPictWorldRect, &r, transparent, nil );

Next, we construct a Rect at the floater's last position in the PixMapper window, then make it one pixel bigger in all directions (the size of the mixing GWorld). We're going to use this Rect to copy the contents of the mixing GWorld into the window.

   r = gSavedFloaterRect;
   InsetRect( &r, -1, -1 );

   CopyBits(    (BitMap *)(*gPixMapSaveMix), 
                  &(gMainWindow->portBits),
                  &gWorldRect, &r, srcCopy, nil );

Now we update the saved floater position stored in gSavedFloaterRect to reflect the new position.

   OffsetRect( &gSavedFloaterRect, gXBump, gYBump );

Following that, we create our one pixel bigger Rect again, this time at the floater's new position. We then copy the floater, with a one pixel border, into the mixing GWorld.

   r = gSavedFloaterRect;
   InsetRect( &r, -1, -1 );
   
   CopyBits(    &(gMainWindow->portBits), 
                  (BitMap *)(*gPixMapSaveMix),
                  &r, &gWorldRect, srcCopy, nil );

Next, copy the saved pixels into the appropriate position in the mixing GWorld. The idea here is that we are reconstructing the pixels that should be behind the floater.

   r = gWorldRect;
   OffsetRect( &r, -gXBump, -gYBump );
   
   CopyBits(    (BitMap *)(*gPixMapSave), 
                  (BitMap *)(*gPixMapSaveMix),
                  &gWorldRect, &r, srcCopy, nil );

Finally, we copy the reconstructed "behind the floater" pixels from the mix GWorld into the save GWorld. We are now ready to move the floater all over again.

   CopyBits(    (BitMap *)(*gPixMapSaveMix), 
                  (BitMap *)(*gPixMapSave),
                  &gWorldRect, &gWorldRect, srcCopy, nil );
}

This routine figures out if bumping the floater will move it off the edge of the window in any direction. If so, the direction of floater movement is changed, so the floater moves away from that edge, rather than towards it.

/*************** CalcNewFloaterPosition **************/

void   CalcNewFloaterPosition( void )
{
   Rect   r;
   
   r = gSavedFloaterRect;
   
   OffsetRect( &r, gXBump, gYBump );
   
   if (   (r.left < gMainWindow->portRect.left) ||
         ( r.right > gMainWindow->portRect.right ) )
      gXBump *= -1;
   
   if (   (r.top < gMainWindow->portRect.top) ||
         ( r.bottom > gMainWindow->portRect.bottom ) )
      gYBump *= -1;
}

At this point we're home free. The remaining code, with a single exception, is all "copy and paste" code from other Getting Started examples. The exception appears in EventLoop(). It's here that we repeatedly call MoveFloater() to keep the animation running. Only when the user quits does the animation loop end.

/********************** EventLoop ********************/

void   EventLoop( void )
{      
   EventRecord      event;
   
   gDone = false;
   while ( gDone == false )
   {
      if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
         DoEvent( &event );

      MoveFloater();
   }
}

/*********************** DoEvent *********************/

void   DoEvent( EventRecord *eventPtr )
{
   char   theChar;
   
   switch ( eventPtr->what )
   {
      case mouseDown: 
         HandleMouseDown( eventPtr );
         break;
      case keyDown:
      case autoKey:
         theChar = eventPtr->message & charCodeMask;
         if ( (eventPtr->modifiers & cmdKey) != 0 ) 
         HandleMenuChoice( MenuKey( theChar ) );
         break;
      case updateEvt:
         BeginUpdate( (WindowPtr)(eventPtr->message) );
         EndUpdate( (WindowPtr)(eventPtr->message) );
         break;
   }
}

/******************* HandleMouseDown *****************/

void   HandleMouseDown( EventRecord *eventPtr )
{
   WindowPtr      window;
   short          thePart;
   long           menuChoice;
   
   thePart = FindWindow( eventPtr->where, &window );
   
   switch ( thePart )
   {
      case inMenuBar:
         menuChoice = MenuSelect( eventPtr->where );
         HandleMenuChoice( menuChoice );
         break;
      case inSysWindow : 
         SystemClick( eventPtr, window );
         break;
   }
}

/******************* HandleMenuChoice ****************/

void   HandleMenuChoice( long menuChoice )
{
   short   menu;
   short   item;
   
   if ( menuChoice != 0 )
   {
      menu = HiWord( menuChoice );
      item = LoWord( menuChoice );
      
      switch ( menu )
      {
         case mApple:
            HandleAppleChoice( item );
            break;
         case mFile:
            HandleFileChoice( item );
            break;
      }
      HiliteMenu( 0 );
   }
}

/****************** HandleAppleChoice ****************/

void   HandleAppleChoice( short item )
{
   MenuHandle   appleMenu;
   Str255       accName;
   short        accNumber;
   
   switch ( item )
   {
      case iAbout:
         SysBeep( 10 );
         break;
      default:
         appleMenu = GetMenuHandle( mApple );
         GetMenuItemText( appleMenu, item, accName );
         accNumber = OpenDeskAcc( accName );
         break;
   }
}

/******************* HandleFileChoice ****************/

void   HandleFileChoice( short item )
{
   switch ( item )
   {
      case iQuit:
         gDone = true;
         break;
   }
}

/*********************** DoError *********************/

void   DoError( Str255 errorString )
{
   ParamText( errorString, "\p", "\p", "\p" );
   
   StopAlert( kALRTResID, nil );
   
   ExitToShell();
}

Running PixMapper

Run PixMapper by selecting Run from the Project menu. Once your code compiles, a window appears with a checkerboard pattern drawn in it. The window will be the exact size of your screen. The animation begins automatically. As the foreground image moves, notice that the background shows through the image openings. Choose Quit from the File menu to end the animation and the program.

Till Next Month...

PixMap data structures and graphics worlds can be tricky to work with, but the PixMapper code should give you a good base for creating your own animated effects. Don't worry too much about the specifics of the PixMapper algorithm. The important things to understand are how to construct a GWorld, how to use CopyBits() to copy PixMaps between GWorlds and windows, and the basics of working with color. You can get more information on the PixMap data structure in the Color QuickDraw chapter of Inside Macintosh: Imaging With QuickDraw. The QuickDraw Drawing chapter of that same volume discusses the all-important CopyBits() routine. For more on graphics worlds, read the Offscreen Graphics Worlds chapter of Imaging With QuickDraw.

If you want to turn PixMapper into a more useful program, provide the user with some control of the animation. PixMapper's MoveFloater() routine is responsible for creating one "frame" in an animated sequence, and is called repeatedly from EventLoop(). Be aware that while a routine like MoveFloater() needs to be called from within a loop to achieve an animated effect, that loop doesn't have to be the event loop. Try adding an Animation menu and then moving the call to a routine that handles a selection from that menu.

If PixMapper seems somewhat slow to you, there's a reason for that. CopyBits() is a general purpose routine designed to handle all color environments and both BitMaps and PixMaps. There are also many ways you can improve the performance of the basic PixMapper algorithm, though that tends to make the code even more confusing. One simple way to speed things up a bit is to increase the value of both the gXBump and gYBump global variables. To maintain smooth animation, you'll also have to alter a little bit of the code. Hint: It's no coincidence that as written, gXBump and gYBump both have a value of 1, and the global variable gWorldRect is set up to be one pixel larger in each direction then the foreground image.

These suggestions should provide you with plenty to do until next month's column. See you then...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance 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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.