Fixed Point Math
 Volume Number: 10 Issue Number: 3 Column Tag: Under The Hood

Fixed Point Math For Speed Freaks

Fast fixed math and derived graphics utility routines

By Alexei Lebedev

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

Several of the author’s free programs, Kubik, Fractal Artist, Tower of Hanoi, as well as some other programs and patches can be downloaded from CompuServe. Author’s e-mail address is 70534,404@compuserve.com. Kubik simulates Rubik’s cube, and Fractal Artist draws some fractals like Mandelbrot Set and Julia Sets. Both Kubik and Fractal Artist (which were built for speed) make use of fixed point arithmetic techniques described here.

In this article we will explore several aspects of Mac programming: fixed point arithmetic in assembly, 3-d transformations, perspective and parallel projections, backplane elimination, offscreen bitmaps, and animation. We’ll discuss details of a set of utility routines, the complete source of which is available in the source files on disk or the online services (see page 2 for details about the online services).

Fixed Point Format

Let’s first build a small library of functions to do fixed point arithmetic. There are several reasons to do this instead of using built-in functions like FixMul and FixDiv. The first and most important is speed - Toolbox functions are slow. Just for comparison, our function for multiplying two Fixed numbers is 3 instructions long and computations are done in registers, whereas FixMul in my LC’s ROM has 47 instructions, and accesses memory many times. [This reasoning changes when it comes to math and the PowerPC. See the Powering Up series to learn more about the new common wisdom. - Ed. stb] The second reason is that we get to choose the precision of the numbers, because we can distribute bit usage between fractional and integer parts of a Fixed number in any way we like. Thus, if we were calculating a Mandelbrot set, we would probably choose 4 bits for the integer part, and 28 for the fraction. For graphics, on the other hand, it makes more sense to split the bits evenly between integer and fractional parts. This lets us use numbers as large as 32767+65535/65536, and fractions as small as 1/65536.

A Fixed number is simply a real number (float) multiplied by a scale in order to get rid of the fractional part. We will use 32-bit fixed point numbers, with the integer part in the higher word, and the fractional part in the lower word. So in our case (f) is scaled by 216 = 65536.

Fixed Point Arithmetic

Fixed numbers can be added (and subtracted) just like long integers. Why? Let n and m be the two numbers we want to add. Then their Fixed equivalents are nf and mf, where is f is, of course, 65536. Adding nf and mf we get (n+m)f, which is n+m expressed in Fixed notation. Let’s apply the same logic to other operations. With multiplication it’s a bit different (no pun intended), because nf*mf = (n*m)f2 has the wrong units. The correct result is (n*m)f. To get it, we simply divide the expression above by f. Note that this is not necessary when a Fixed number is being multiplied by an integer, because nf*m = (n*m)f. This important fact has been omitted in Inside Mac Volume I. As a result, some programmers write lines like fixnum = FixMul(fixnum, FixRatio(5, 1)), when all that is needed is fixnum *= 5 or something similar.

We will now implement multiplication in assembly. We will be using the 68020’s signed multiply instruction muls.l, which has syntax muls.l dx, dy:dz. This multiplies a long word in dx by a long word in dz, splitting the 64-bit result between dy and dz. Note that the registers can overlap, which means that to square a number, you would write muls.l dx,dy:dx.

```/* 1 */
asm {
muls.l d0, d1:d2
move.w d1, d2 ; join high and low words of the result
swap   d2; reorder words for correct result
}
```

The last two instructions divide d1:d2 by 65536, effectively shifting them down 16 bits. Figure 1 illustrates how this is done.

Fig. 1 Multiplying Fixed numbers

Division is slightly less trivial, but still very straight-forward. It uses the signed divide instruction divs.l.

```/* 2 */
asm {
move.l num1, d2 ; num1 = numerator
move.l num2, d1 ; num2 = denominator
move.w d2, d0   ; split d2 between d2 and d0
swap   d0
clr.w  d0
swap   d2
ext.l  d2
divs.l d1, d2:d0
bra.s  @end
moveq  #-2, d0
ror.l  #1, d0
tst.l  d2
bgt    @end; is num1 > 0, return 0x7FFFFFFF
not.l  d0; return 0x80000000
end:
}
```

The code first loads the numbers and checks if denominator is 0. If this is the case, it tries to return a number closest to infinity of the same sign as the numerator.

Rotating -2 (0xFFFFFFFE) one bit to the right gives 0x7FFFFFFF. If numerator > 0, there is nothing to do, because 0x7FFFFFFF is the largest positive Fixed number. If numerator is negative, we return NOT(0xFFFFFFFE), or 0x80000000. Even though this IS the smallest Fixed number, it is not very usable, because -0x80000000 = 0x7FFFFFFF + 1 = 0x80000000! That’s why FixDiv() returns 0x80000001. Naturally, our code can be modified to return 0x80000001. All we have to is change not.l to neg.l. Actually, it not important at all which value is returned. Division by zero should not occur under any circumstances. The compiler, for example, doesn’t include any run time checking for this kind of thing in the code. The macro Divide() (in the file FixedPointMath.h) doesn’t either, because it takes up space. Function DivideCh() in FixedPointMath.c is safer to use, but it takes up more space, and handicaps you with function call overhead.

Let’s look at the mechanism of division. Multiply() and Divide() are two basic operations, using which you can implement many other functions, so it’s important to understand how they work.

```/* 3 */
move.w d2, d0
swap   d0
clr.w  d0
swap   d2
ext.l  d2
```

The idea here is to split d2 between d2 and d0, and divide this 64-bit quantity by d1 (it is basically the reverse of Multiply()). The first three instructions put d2.w into the d0.hw. The last two instructions put d2.hw into d2.w. After all of this is done, we can use divs.l d1,d2:d0 to divide the numbers.

Now that we know how division and multiplication work, we can build many more useful functions. For example, a square root function.

```/* 4 */
Fixed FixSqrt(register Fixed num)  // uses Newton’s method to find  num
{
register Fixed s;
register short i;

s = (num + 65536) >> 1;  //divide by 2
for (i = 0; i < 6; i++)  //converge six times
s = (s + Divide(num, s)) >> 1;
return s;
}
```

It is the implementation of a well-known formula for finding square roots. It is based on Newton's method. S, (= num), can be calculated to any precision, but since (s+num/s)/2 converges very quickly, I decided that six iterations would be enough (For showing me the algorithm for this function, I would like to thank Alexander Migdal). Adescription of Newton’s method can be found in any high-school level book on mathematics.

As another example, we will consider a function for rounding Fixed to integers. After that we will move on to graphics-related topics. You will find more useful macros in FixedPointMath.h. Since they are all derived from Multiply(), Divide(), or FixRnd(), we will not discuss them here.

```/* 5 */
asm {
swap   d0
bpl.s  @end
bvc.s  @end
subq   #1, d0
end:
}
```

This code rounds integers upwards. Note that when n > 0 and n - trunc(n) >= .5, bit 15 is set. After swap, this bit raises the N flag. In this case, we round up by adding 1 to the truncated result. If an overflow occurs, we subtract one

(d0.w (=0x8000) - 1 = 0x7FFF)

Note that this also works when n < 0, because for negative numbers bit 15 means that n - trunc(n) <= -.5. This code can be easily extended to round negative numbers correctly (away from 0), but since it is implemented as a macro, it would be nicer to keep it small (it returns the same result as Toolbox’s FixRound()).

3D Transformations

Possibly to your regret, I will not derive formulas for rotating points here. Instead, I will refer you to a book by Leendert Ammeraal, Programming Principles in Computer Graphics, second edition (published by John Wiley & Sons; its price is high, but think of it as the K&R of graphics programming). It is an excellent book, take my word for it. Using elegant C++ code, it implements vector classes, explains matrices, polygon triangulation, Bresenham’s algorithms, and includes a 3d graphics program utilizing z-buffer and other nice things. Here is a function for rotating a point about z-axis:

```/* 6 */
void RollPoint(Vector3D *p, short angle)
{
Fixed sin, cos, xPrime, yPrime;

GetTrigValues(angle, &sin, &cos);
xPrime = Multiply(p->x, cos) - Multiply(p->y, sin);
yPrime = Multiply(p->x, sin) + Multiply(p->y, cos);
p->x = xPrime;
p->y = yPrime;
}
```

To demonstrate its correctness, let y be 0. Then after rotation p will have coordinates (x*cos(angle), x*sin(angle)). If on the other hand, we let x be 0, p will be (-y*sin(angle), y*cos(angle)). It’s always nice to have a piece of paper and pencil, because visualizing things is not always easy. Also, in case you didn’t know, a positive angle rotates a point counter-clockwise.

In RollPoint(), GetTrigValues() is used to calculate sine and cosine of an angle. Yes, it appeared previously in MacTutor (“Real-Time 3D Animation”, April/May 1992, Volume 8, No. 1, pp. 12-13). I borrowed it when I was building my 3D library, because I found it useful. You will find its implementation of GetTrigValues() in SineTable.h. The sine table used for look-up is initialized by InitSineTable(). InitSineTable() only builds the table once, storing it in a resource ‘sint’ with id 128.

You will find three other routines in file Transformations.c. They are ScalePoint(), PitchPoint(), and YawPoint(). ScalePoint() multiplies each coordinate of a point by the number you specify. The other two rotate points around x- and y- axes respectively (Yaw is for y, and Pitch is like a pitch modulation wheel in synthesizers: it spins up and down). Note that usually matrices are used for rotating and translating points. The advantage of using matrices is that they “remember” transformations applied to them, so if you teach a matrix three hundred transformations, you could quickly apply it to any other point, and this would be equivalent to doing all these transformations by hand.

Projection

We will now take a quick look at projection. Examine Fig. 2 to get an idea of what’s going on.

Figure 2.

SpaceSize specifies width and height of a rectangle in XY plane which is mapped to the screen. This rectangle (call it spaceR) has 3D coordinates of ((-spaceSize.x, spaceSize.y, 0), (spaceSize.x, spaceSize.y, 0), (spaceSize.x, -spaceSize.y, 0), (-spaceSize.x, -spaceSize.y, 0)). screenCenter is the origin of the 2D coordinate system. It maps to a 3D point (0,0,0), and vice versa. A screen rectangle (viewR) can be specified with ViewPort(). spaceR will be mapped to viewR and vice versa. screenCenter is set to the center of viewR.

Fig. 2 shows the viewing pyramid from the side. The camera is located on the Z axis, and is facing the XY plane. The distance from camera to the screen (eyez) can be changed using a routine SetViewAngle(theta). We calulate distance to the projection screen so that every point (lying in the xy plane) inside the spaceR rectangle is visible. The smaller the angle, the greater its cotangent, the greater eyez, and less noticeable the perspective. Specifying a viewing angle of 0 will result in a divide by zero. Instead, D3toD2par() should be used for parallel projection. A large value of theta will result in distortions and very strong perspective.

```/* 7 */
eyez = spaceSize * cot(theta)
we have

P’ =   P * eyez   screenCenter  =  P * cot(theta) * screenCenter
(eyez - P.z)  spaceSize                eyez - P.z

void D3toD2(Vector3D *p3D, Point *p2D)
{
Fixed d = eyez - p3D->z;
p2D->v = center.y
- FixRnd(Divide(Multiply(p3D->y, ratio.y),d));
p2D->h = center.x
+ FixRnd(Divide(Multiply(p3D->x, ratio.x),d));
}
```

This function implements perspective projection (in Mac’s coordinate system the origin is in the upper-left corner, and y increases downward). Let’s see how parallel projection can be implemented. Since the camera is assumed to be infinitely far away, we take the limit of P’ as eyez approaches . We have

```/* 8 */
P’  =    P *  screenCenter
spaceSize
```

Another way to see this is note that P’.z no longer contributes (since there is no perspective), so eyez’s cancel.

Fig. 2 shows P’’, P’s image on the screen when using parallel projection. The following piece of code shows its implementation.

```/* 9 */
void D3toD2par(Vector3D *p3D, Point *p2D)
{
p2D->v = center.y - FixRnd(p3D->y * center.y/spaceSize.y);
p2D->h = center.x + FixRnd(p3D->x * center.x/spaceSize.x);
}
```

Back plane elimination

Suppose we have a triangle ABC. The orientation of points ABC is said to be positive if we turn counter-clockwise when visiting points ABC in the specified order. It is zero if A, B, and C lie on the same line, and is negative, if we turn clockwise. As long as we’re talking about convex, closed objects where all of the polygons use the same point ordering, the concept of orientation turns out to be very useful when determining whether a triangle (or some other polygon, provided all of its lie in the same plane) is visible. We say that points with positive (counter-clockwise) orientation lie on a visible plane, otherwise they line on the backplane, and the triangle is not drawn. The following function computes orientation of three points.

```/* 10 */
static short visi(Point p1, Point p2, Point p3)
{
return (long)((p2.v - p1.v) * (p3.h - p1.h)) -
(long)((p2.h - p1.h) * (p3.v - p1.v));
}
```

The result of this function is > 0 if the orientation is positive, < 0 if it negative, and 0 if all three points lie on the same line.

Figure 3

From this figure you see that A x B is a vector which points out of the page if (P1 P2 P3) have positive orientation, and into the page otherwise. The function visi() returns the opposite of (ad - bc) to account for mac’s coordinate system, where y increases downward. In that sense, mac has left-handed coordinate system.

Offscreen Bitmaps

We now come to the easiest part of the discussion.

```/* 11 */
Boolean NewBitMap(BitMap *theBitMap, Rect *theRect)
{
theBitMap->rowBytes = (((theRect->right
- theRect->left)+15)/16)*2;
- theRect->top)
* theBitMap->rowBytes);
theBitMap->bounds = *theRect;
return (!MemErr);
}
```

This function is straight-forward. rowBytes is calculated so it is even (as required by QuickDraw). Then NewBitMap allocates a block to hold the bit image. It returns true if everything is OK, otherwise it returns false.

Here is a piece of code from the OffscreenPort function, which allocates an offscreen port, and associates it with a bitmap, pointer to which is passed as a parameter:

```/* 12 */
OpenPort(newPort);
newPort->portBits = *theBitMap;
newPort->portRect = theBitMap->bounds;
RectRgn(newPort->visRgn, &newPort->portRect);
ClipRect(&newPort->portRect);
EraseRect(&newPort->portRect);
```

We use RectRgn() to set new port’s visRgn to its portRect in case it happens to be larger than the screen. As to animation, it is all done by the CopyBits() call in the main() function.

Community Search:
MacTech Search:

Parallels Desktop 10.2.0 - Run Windows a...
Parallels Desktop is simply the world's bestselling, top-rated, and most trusted solution for running Windows applications on your Mac. With Parallels Desktop for Mac, you can seamlessly run both... Read more
LaunchBar 6.2 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Firefox 37.0 - Fast, safe Web browser. (...
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
Arq 4.11 - Online backup to Google Drive...
Arq is super-easy online backup for the Mac. Back up to your own Google Drive storage (15GB free storage), your own Amazon Glacier (\$.01/GB per month storage) or S3, or any SFTP server. Arq backs up... Read more
MacFamilyTree 7.3.4 - Create and explore...
MacFamilyTree gives genealogy a facelift: it's modern, interactive, incredibly fast, and easy to use. We're convinced that generations of chroniclers would have loved to trade in their genealogy... Read more
Yummy FTP 1.10.2 - FTP/SFTP/FTPS client...
Yummy FTP is an FTP + SFTP + FTPS file transfer client which focuses on speed, reliability and productivity. Whether you need to transfer a few files or a few thousand, schedule automatic backups, or... Read more
VueScan 9.5.08 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Iridient Developer 3.0.1 - Powerful imag...
Iridient Developer (was RAW Developer) is a powerful image conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more
Monodraw 0.8.4.1 - Powerful ASCII art ed...
Monodraw allows you to easily create text-based art (like diagrams, layouts, flow charts) and visually represent algorithms, data structures, binary formats and more. Because it's all just text, it... Read more
Air Video Server HD 2.1.0 - Stream video...
Air Video Server HD streams videos instantly from your computer on your iPhone, iPad, iPod touch or Apple TV. No need to worry about converting or transferring files. We took everything that was... Read more

Latest Forum Discussions

Marvel Mighty Heroes, the Ultimate Marve...
DeNA and Marvel Entertainment have brought us a new action-packed brawler: Marvel Mighty Heroes. You can play with up to four of your friends as you favorite marvel heroes like Iron Man, Thor, Spider-Man, Captain America, Star-Lord, Hulk, and... | Read more »
Take Note - The Jot Script 2 Evernote Ed...
Adonit's Jot Script 2 sylus has an all-new edition that's meant to be Evernote's BFF. The sylus has been redesigned to work better with iPads and give you faster stroke tracking, smoother line rendering, and better tip-to-line accuracy. | Read more »
INFINIT Lets Mobile Users Send Files of...
Infinit  is a file sharing app that ignores file size limits. It maintains the original quality of your photos and videos so you can be sure they look awesome after sending. You can move entire albums of photos or full HD films from your iPhone to... | Read more »
Serious Sam Double D Developer is Making...
There's nothing like the thrill of watching a horse race, especially when the horses are drunk.  | Read more »
2K Announces WWE 2K, Mobile's First...
It seems like this month has been pretty big for wrestling. First Wrestlemania, then 2K has announces that they're releasing  WWE 2K for iOS. It's a simulation-based WWE game where you'll get to play with several WWE superstars such as John Cena, ... | Read more »
How the Apple Watch Could Change the Fac...
The Apple Watch is still a ways out, but my previous musings on the wearable’s various features got me thinking: what might it be like a year after launch? Two years? Five years? What if it becomes a symbiotic part of the iOS framework to the point... | Read more »
You Can Start Challenging Your Friends t...
Last year we reported that Sebastian Gosztyla's new game, Dual, was theorized to be released sometime during the summer of 2014. Sadly that did not become a reality, but the good news it there is now an official release date. | Read more »
Forgotten Memories : Alternate Realities...
Forgotten Memories : Alternate Realities, from Psychoz Interactive, is planned for release on April 23. The Resident Evil, Silent Hill, and Alone in the Dark inspired horror game puts you in the shoes of Rose Hawkins as she searches for a missing... | Read more »
Pie In The Sky: A Pizza Odyssey (Games)
Pie In The Sky: A Pizza Odyssey 1.0 Device: iOS Universal Category: Games Price: \$2.99, Version: 1.0 (iTunes) Description: A game about delivering pizza. In space. | Read more »
Chosen Gives Hopeful Singers, Songwriter...
If YouTube videos and reality TV shows like The Voice have taught us one thing, it’s that there are a lot of people out there who are anxious to show the world their talents. And if they’ve taught us a second thing, it’s that there’s an almost... | Read more »

Price Scanner via MacPrices.net

Will Microsoft’s Surface 3 Give The 12-inch M...
The more I ruminate over the new 12-inch MacBook, the more it occurs that it’s probably going to be more of a cannibalization threat to high-end iPads (including a new 12-inch ‘Pad when/if that... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
MacMall has the 2013 13″ 2.4GHz/128GB Retina MacBook Pro available for \$949.99 for a limited time. Shipping is free. Their price is \$350 off original MSRP, and it’s the only sub-\$1000 new Retina... Read more
Adobe today announced the availability of Adobe Comp CC, a free iPad app that enables rapid creation of layout concepts for mobile, Web and print projects. With Comp CC, designers can rough out and... Read more
13-inch 2.6GHz/256GB Retina MacBook Pro avail...
Best Buy has clearance 2014 13″ 2.6GHz/256GB Retina MacBook Pros available for \$1199.99 including free shipping. Their price is \$300 off original MSRP, and it’s the lowest price for this model.... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
21-inch 1.4GHz iMac on sale for \$999, save \$1...
Best Buy has the 21″ 1.4GHz iMac on sale for \$999.99 on their online store. Choose free shipping or free local store pick up. Price is for online orders only, in-store prices may vary. Their price is... Read more
2.6GHz Mac mini on sale for \$649, save \$50
Amazon has the 2.6GHz Mac mini on sale for \$649.99 including free shipping. Their price is \$50 off MSRP, and it’s the lowest price available for this model. Read more
Textkraft Professional 3.2 Powerful iPad Text...
Finally it’s springtime, at least theoretically in my neck of the woods, where we’re still navigating canyons between towering snowbanks with temperatures well below freezing in winter weather that... Read more
Apple offering refurbished 27-inch 5K iMacs f...
The Apple Store is offering Apple Certified Refurbished 27″ 3.5GHz 5K iMacs for \$2119 including free shipping. Their price is \$380 off the price of new models, and it’s the lowest price available for... Read more
16GB iPad mini on sale for \$199, save \$50
Walmart has 16GB iPad minis (1st generation) available for \$199.99 on their online store, including free shipping. Their price is \$50 off MSRP. Online orders only. Read more

Jobs Board

DevOps Software Engineer - *Apple* Pay, iOS...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Sr. Technical Services Consultant, *Apple*...
**Job Summary** Apple Professional Services (APS) has an opening for a senior technical position that contributes to Apple 's efforts for strategic and transactional Read more
Lead *Apple* Solutions Consultant - Retail...
**Job Summary** Job Summary The Lead ASC is an Apple employee who serves as the Apple business manager and influencer in a hyper-business critical Reseller's store Read more
*Apple* Pay - Site Reliability Engineer - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more