diff --git a/01-01.html b/01-01.html index 2136c6e..15a5105 100644 --- a/01-01.html +++ b/01-01.html @@ -24,7 +24,7 @@ - +
@@ -36,18 +36,16 @@


-

Part I -

-

Chapter 1
The Best Optimizer Is between Your Ears -

-

The Human Element of Code Optimization

+

Part I

+

Chapter 1
The Best Optimizer Is between Your Ears

+

The Human Element of Code Optimization

This book is devoted to a topic near and dear to my heart: writing software that pushes PCs to the limit. Given run-of-the-mill software, PCs run like the 97-pound-weakling minicomputers they are. Give them the proper care, however, and those ugly boxes are capable of miracles. The key is this: Only on microcomputers do you have the run of the whole machine, without layers of operating systems, drivers, and the like getting in the way. You can do anything you want, and you can understand everything that’s going on, if you so wish.

As we’ll see shortly, you should indeed so wish.

Is performance still an issue in this era of cheap 486 computers and super-fast Pentium computers? You bet. How many programs that you use really run so fast that you wouldn’t be happier if they ran faster? We’re so used to slow software that when a compile-and-link sequence that took two minutes on a PC takes just ten seconds on a 486 computer, we’re ecstatic—when in truth we should be settling for nothing less than instantaneous response.

Impossible, you say? Not with the proper design, including incremental compilation and linking, use of extended and/or expanded memory, and well-crafted code. PCs can do just about anything you can imagine (with a few obvious exceptions, such as applications involving super-computer-class number-crunching) if you believe that it can be done, if you understand the computer inside and out, and if you’re willing to think past the obvious solution to unconventional but potentially more fruitful approaches.

My point is simply this: PCs can work wonders. It’s not easy coaxing them into doing that, but it’s rewarding—and it’s sure as heck fun. In this book, we’re going to work some of those wonders, starting...

...now.

-

Understanding High Performance

+

Understanding High Performance

Before we can create high-performance code, we must understand what high performance is. The objective (not always attained) in creating high-performance software is to make the software able to carry out its appointed tasks so rapidly that it responds instantaneously, as far as the user is concerned. In other words, high-performance code should ideally run so fast that any further improvement in the code would be pointless.

Notice that the above definition most emphatically does not say anything about making the software as fast as possible. It also does not say anything about using assembly language, or an optimizing compiler, or, for that matter, a compiler at all. It also doesn’t say anything about how the code was designed and written. What it does say is that high-performance code shouldn’t get in the user’s way—and that’s all.

@@ -57,7 +55,7 @@

“What’s a fast slow program?” you ask. That’s a good question, and a brief (true) story is perhaps the best answer.

-

When Fast Isn’t Fast

+

When Fast Isn’t Fast

In the early 1970s, as the first hand-held calculators were hitting the market, I knew a fellow named Irwin. He was a good student, and was planning to be an engineer. Being an engineer back then meant knowing how to use a slide rule, and Irwin could jockey a slipstick with the best of them. In fact, he was so good that he challenged a fellow with a calculator to a duel—and won, becoming a local legend in the process.

When you get right down to it, though, Irwin was spitting into the wind. In a few short years his hard-earned slipstick skills would be worthless, and the entire discipline would be essentially wiped from the face of the earth. What’s more, anyone with half a brain could see that changeover coming. Irwin had basically wasted the considerable effort and time he had spent optimizing his soon-to-be-obsolete skills.

@@ -74,7 +72,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/01-02.html b/01-02.html index 5c96b87..7f1d2cc 100644 --- a/01-02.html +++ b/01-02.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

Rules for Building High-Performance Code

+

Rules for Building High-Performance Code

We’ve got the following rules for creating high-performance software:

Making rules is easy; the hard part is figuring out how to apply them in the real world. For my money, examining some actual working code is always a good way to get a handle on programming concepts, so let’s look at some of the performance rules in action.

-

Know Where You’re Going

+

Know Where You’re Going

If we’re going to create high-performance code, first we have to know what that code is going to do. As an example, let’s write a program that generates a 16-bit checksum of the bytes in a file. In other words, the program will add each byte in a specified file in turn into a 16-bit value. This checksum value might be used to make sure that a file hasn’t been corrupted, as might occur during transmission over a modem or if a Trojan horse virus rears its ugly head. We’re not going to do anything with the checksum value other than print it out, however; right now we’re only interested in generating that checksum value as rapidly as possible.

-

Make a Big Map

+

Make a Big Map

How are we going to generate a checksum value for a specified file? The logical approach is to get the file name, open the file, read the bytes out of the file, add them together, and print the result. Most of those actions are straightforward; the only tricky part lies in reading the bytes and adding them together.

-

Make Lots of Little Maps

+

Make Lots of Little Maps

Actually, we’re only going to make one little map, because we only have one program section that requires much thought—the section that reads the bytes and adds them up. What’s the best way to do this?

It would be convenient to load the entire file into memory and then sum the bytes in one loop. Unfortunately, there’s no guarantee that any particular file will fit in the available memory; in fact, it’s a sure thing that many files won’t fit into memory, so that approach is out.

@@ -125,7 +125,7 @@ main(int argc, char *argv[]) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/01-03.html b/01-03.html index d829eb8..10cba32 100644 --- a/01-03.html +++ b/01-03.html @@ -24,7 +24,7 @@ - +
@@ -205,7 +205,7 @@ _ChecksumFileendp

The lesson is clear: Optimization makes code faster, but without proper design, optimization just creates fast slow code.

Well, then, how are we going to improve our design? Before we can do that, we have to understand what’s wrong with the current design.

-

Know the Territory

+

Know the Territory

Just why is Listing 1.1 so slow? In a word: overhead. The C library implements the read() function by calling DOS to read the desired number of bytes. (I figured this out by watching the code execute with a debugger, but you can buy library source code from both Microsoft and Borland.) That means that Listing 1.1 (and Listing 1.3 as well) executes one DOS function per byte processed—and DOS functions, especially this one, come with a lot of overhead.

For starters, DOS functions are invoked with interrupts, and interrupts are among the slowest instructions of the x86 family CPUs. Then, DOS has to set up internally and branch to the desired function, expending more cycles in the process. Finally, DOS has to search its own buffers to see if the desired byte has already been read, read it from the disk if not, store the byte in the specified location, and return. All of that takes a long time—far, far longer than the rest of the main loop in Listing 1.1. In short, Listing 1.1 spends virtually all of its time executing read(), and most of that time is spent somewhere down in DOS.

You can verify this for yourself by watching the code with a debugger or using a code profiler, but take my word for it: There’s a great deal of overhead to DOS calls, and that’s what’s draining the life out of Listing 1.1.

@@ -223,7 +223,7 @@ _ChecksumFileendp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/01-04.html b/01-04.html index b0550ac..aaa8f04 100644 --- a/01-04.html +++ b/01-04.html @@ -24,7 +24,7 @@ - +
@@ -78,14 +78,14 @@ main(int argc, char *argv[]) { } -

Know When It Matters

+

Know When It Matters

The last section contained a particularly interesting phrase: the time-critical portions of your code. Time-critical portions of your code are those portions in which the speed of the code makes a significant difference in the overall performance of your program—and by “significant,” I don’t mean that it makes the code 100 percent faster, or 200 percent, or any particular amount at all, but rather that it makes the program more responsive and/or usable from the user’s perspective.

Don’t waste time optimizing non-time-critical code: set-up code, initialization code, and the like. Spend your time improving the performance of the code inside heavily-used loops and in the portions of your programs that directly affect response time. Notice, for example, that I haven’t bothered to implement a version of the checksum program entirely in assembly; Listings 1.2 and 1.6 call assembly subroutines that handle the time-critical operations, but C is still used for checking command-line parameters, operning files, printing, and the like.

If you were to implement any of the listings in this chapter entirely in hand-optimized assembly, I suppose you might get a performance improvement of a few percent—but I rather doubt you’d get even that much, and you’d sure as heck spend an awful lot of time for whatever meager improvement does result. Let C do what it does well, and use assembly only when it makes a perceptible difference.

Besides, we don’t want to optimize until the design is refined to our satisfaction, and that won’t be the case until we’ve thought about other approaches.

-

Always Consider the Alternatives

+

Always Consider the Alternatives

Listing 1.4 is good, but let’s see if there are other—perhaps less obvious—ways to get the same results faster. Let’s start by considering why Listing 1.4 is so much better than Listing 1.1. Like read(), getc() calls DOS to read from the file; the speed improvement of Listing 1.4 over Listing 1.1 occurs because getc() eads many bytes at once via DOS, then manages those bytes for us. That’s faster than reading them one at a time using read()—but there’s no reason to think that it’s faster than having our program read and manage blocks itself. Easier, yes, but not faster.

Consider this: Every invocation of getc() involves pushing a parameter, executing a call to the C library function, getting the parameter (in the C library code), looking up information about the desired stream, unbuffering the next byte from the stream, and returning to the calling code. That takes a considerable amount of time, especially by contrast with simply maintaining a pointer to a buffer and whizzing through the data in the buffer inside a single loop.

There are four reasons that many programmers would give for not trying to improve on Listing 1.4:

@@ -109,7 +109,7 @@ main(int argc, char *argv[]) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/01-05.html b/01-05.html index ddaa7e3..e1210eb 100644 --- a/01-05.html +++ b/01-05.html @@ -24,7 +24,7 @@ - +
@@ -103,7 +103,7 @@ main(int argc, char *argv[]) {

That brings us to the fourth reason: avoiding an internal-buffered implementation like Listing 1.5 because of the difficulty of coding such an approach. True, it is easier to let a C library function do the work, but it’s not all that hard to do the buffering internally. The key is the concept of handling data in restartable blocks; that is, reading a chunk of data, operating on the data until it runs out, suspending the operation while more data is read in, and then continuing as though nothing had happened.

In Listing 1.5 the restartable block implementation is pretty simple because checksumming works with one byte at a time, forgetting about each byte immediately after adding it into the total. Listing 1.5 reads in a block of bytes from the file, checksums the bytes in the block, and gets another block, repeating the process until the entire file has been processed. In Chapter 5, we’ll see a more complex restartable block implementation, involving searching for text strings.

At any rate, Listing 1.5 isn’t much more complicated than Listing 1.4—and it’s a lot faster. Always consider the alternatives; a bit of clever thinking and program redesign can go a long way.

-

Know How to Turn On the Juice

+

Know How to Turn On the Juice

I have said time and again that optimization is pointless until the design is settled. When that time comes, however, optimization can indeed make a significant difference. Table 1.1 indicates that the optimized version of Listing 1.5 produced by Microsoft C outperforms an unoptimized version of the same code by more than 60 percent. What’s more, a mostly-assembly version of Listing 1.5, shown in Listings 1.6 and 1.7, outperforms even the best-optimized C version of List1.5 by 26 percent. These are considerable improvements, well worth pursuing—once the design has been maxed out.

LISTING 1.6 L1-6.C

@@ -177,7 +177,7 @@ main(int argc, char *argv[]) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/01-06.html b/01-06.html index 20321d1..feba09d 100644 --- a/01-06.html +++ b/01-06.html @@ -24,7 +24,7 @@ - +
@@ -97,11 +97,11 @@ _ChecksumChunkendp

All this is basically a way of saying: Know where you’re going, know the territory, and know when it matters.

-

Where We’ve Been, What We’ve Seen

+

Where We’ve Been, What We’ve Seen

What have we learned? Don’t let other people’s code—even DOS—do the work for you when speed matters, at least not without knowing what that code does and how well it performs.

Optimization only matters after you’ve done your part on the program design end. Consider the ratios on the vertical axis of Table 1.1, which show that optimization is almost totally wasted in the checksumming application without an efficient design. Optimization is no panacea. Table 1.1 shows a two-times improvement from optimization—and a 50-times-plus improvement from redesign. The longstanding debate about which C compiler optimizes code best doesn’t matter quite so much in light of Table 1.1, does it? Your organic optimizer matters much more than your compiler’s optimizer, and there’s always assembly for those usually small sections of code where performance really matters.

-

Where We’re Going

+

Where We’re Going

This chapter has presented a quick step-by-step overview of the design process. I’m not claiming that this is the only way to create high-performance code; it’s just an approach that works for me. Create code however you want, but never forget that design matters more than detailed optimization. Never stop looking for inventive ways to boost performance—and never waste time speeding up code that doesn’t need to be sped up.

I’m going to focus on specific ways to create high-performance code from now on. In Chapter 5, we’ll continue to look at restartable blocks and internal buffering, in the form of a program that searches files for text strings.


@@ -117,7 +117,7 @@ _ChecksumChunkendp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/02-01.html b/02-01.html index 3f92989..b8c8981 100644 --- a/02-01.html +++ b/02-01.html @@ -24,7 +24,7 @@ - +
@@ -36,13 +36,12 @@


-

Chapter 2
A World Apart -

-

The Unique Nature of Assembly Language Optimization

+

Chapter 2
A World Apart

+

The Unique Nature of Assembly Language Optimization

As I showed in the previous chapter, optimization is by no means always a matter of “dropping into assembly.” In fact, in performance tuning high-level language code, assembly should be used rarely, and then only after you’ve made sure a badly chosen or clumsily implemented algorithm isn’t eating you alive. Certainly if you use assembly at all, make absolutely sure you use it right. The potential of assembly code to run slowly is poorly understood by a lot of people, but that potential is great, especially in the hands of the ignorant.

Truly great optimization, however, happens only at the assembly level, and it happens in response to a set of dynamics that is totally different from that governing C/C++ or Pascal optimization. I’ll be speaking of assembly-level optimization time and again in this book, but when I do, I think it will be helpful if you have a grasp of those assembly specific dynamics.

As usual, the best way to wade in is to present a real-world example.

-

Instructions: The Individual versus the Collective

+

Instructions: The Individual versus the Collective

Some time ago, I was asked to work over a critical assembly subroutine in order to make it run as fast as possible. The task of the subroutine was to construct a nibble out of four bits read from different bytes, rotating and combining the bits so that they ultimately ended up neatly aligned in bits 3-0 of a single byte. (In case you’re curious, the object was to construct a 16-color pixel from bits scattered over 4 bytes.) I examined the subroutine line by line, saving a cycle here and a cycle there, until the code truly seemed to be optimized. When I was done, the key part of the code looked something like this:

@@ -78,7 +77,7 @@ LoopTop:

This moved the costly multibit rotation out of the loop so that it was performed just once, rather than four times. While the code may not look much different from the original, and in fact still contains exactly the same number of instructions, the performance of the entire subroutine improved by about 10 percent from just this one change. (Incidentally, that wasn’t the end of the optimization; I eliminated the DEC and JNJ instructions by expanding the four iterations of the loop—but that’s a tale for another chapter.)

The point is this: To write truly superior assembly programs, you need to know what the various instructions do and which instructions execute fastest...and more. You must also learn to look at your programming problems from a variety of perspectives so that you can put those fast instructions to work in the most effective ways.

-

Assembly Is Fundamentally Different

+

Assembly Is Fundamentally Different

Is it really so hard as all that to write good assembly code for the PC? Yes! Thanks to the decidedly quirky nature of the x86 family CPUs, assembly language differs fundamentally from other languages, and is undeniably harder to work with. On the other hand, the potential of assembly code is much greater than that of other languages, as well.

To understand why this is so, consider how a program gets written. A programmer examines the requirements of an application, designs a solution at some level of abstraction, and then makes that design come alive in a code implementation. If not handled properly, the transformation that takes place between conception and implementation can reduce performance tremendously; for example, a programmer who implements a routine to search a list of 100,000 sorted items with a linear rather than binary search will end up with a disappointingly slow program.


@@ -94,7 +93,7 @@ LoopTop:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/02-02.html b/02-02.html index e3ce907..8c3b125 100644 --- a/02-02.html +++ b/02-02.html @@ -24,7 +24,7 @@ - +
@@ -36,23 +36,23 @@


-

Transformation Inefficiencies

+

Transformation Inefficiencies

No matter how well an implementation is derived from the corresponding design, however, high-level languages like C/C++ and Pascal inevitably introduce additional transformation inefficiencies, as shown in Figure 2.1.

The process of turning a design into executable code by way of a high-level language involves two transformations: one performed by the programmer to generate source code, and another performed by the compiler to turn source code into machine language instructions. Consequently, the machine language code generated by compilers is usually less than optimal given the requirements of the original design.

High-level languages provide artificial environments that lend themselves relatively well to human programming skills, in order to ease the transition from design to implementation. The price for this ease of implementation is a considerable loss of efficiency in transforming source code into machine language. This is particularly true given that the x86 family in real and 16-bit protected mode, with its specialized memory-addressing instructions and segmented memory architecture, does not lend itself particularly well to compiler design. Even the 32-bit mode of the 386 and its successors, with their more powerful addressing modes, offer fewer registers than compilers would like.


Figure 2.1
  The high-level language transformation inefficiencies. +
-->Figure 2.1  The high-level language transformation inefficiencies.

Assembly, on the other hand, is simply a human-oriented representation of machine language. As a result, assembly provides a difficult programming environment—the bare hardware and systems software of the computer—but properly constructed assembly programs suffer no transformation loss, as shown in Figure 2.2.

Only one transformation is required when creating an assembler program, and that single transformation is completely under the programmer’s control. Assemblers perform no transformation from source code to machine language; instead, they merely map assembler instructions to machine language instructions on a one-to-one basis. As a result, the programmer is able to produce machine language code that’s precisely tailored to the needs of each task a given application requires.


Figure 2.2
  Properly constructed assembly programs suffer no transformation loss. +
-->Figure 2.2  Properly constructed assembly programs suffer no transformation loss.

The key, of course, is the programmer, since in assembly the programmer must essentially perform the transformation from the application specification to machine language entirely on his or her own. (The assembler merely handles the direct translation from assembly to machine language.)

-

Self-Reliance

+

Self-Reliance

The first part of assembly language optimization, then, is self. An assembler is nothing more than a tool to let you design machine-language programs without having to think in hexadecimal codes. So assembly language programmers—unlike all other programmers—must take full responsibility for the quality of their code. Since assemblers provide little help at any level higher than the generation of machine language, the assembly programmer must be capable both of coding any programming construct directly and of controlling the PC at the lowest practical level—the operating system, the BIOS, even the hardware where necessary. High-level languages handle most of this transparently to the programmer, but in assembly everything is fair—and necessary—game, which brings us to another aspect of assembly optimization: knowledge.

-

Knowledge

+

Knowledge

In the PC world, you can never have enough knowledge, and every item you add to your store will make your programs better. Thorough familiarity with both the operating system APIs and BIOS interfaces is important; since those interfaces are well-documented and reasonably straightforward, my advice is to get a good book or two and bring yourself up to speed. Similarly, familiarity with the PC hardware is required. While that topic covers a lot of ground—display adapters, keyboards, serial ports, printer ports, timer and DMA channels, memory organization, and more—most of the hardware is well-documented, and articles about programming major hardware components appear frequently in the literature, so this sort of knowledge can be acquired readily enough.

The single most critical aspect of the hardware, and the one about which it is hardest to learn, is the CPU. The x86 family CPUs have a complex, irregular instruction set, and, unlike most processors, they are neither straightforward nor wellregarding true code performance. What’s more, assembly is so difficult to learn that most articles and books that present assembly code settle for code that just works, rather than code that pushes the CPU to its limits. In fact, since most articles and books are written for inexperienced assembly programmers, there is very little information of any sort available about how to generate high-quality assembly code for the x86 family CPUs. As a result, knowledge about programming them effectively is by far the hardest knowledge to gather. A good portion of this book is devoted to seeking out such knowledge.

@@ -71,7 +71,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/02-03.html b/02-03.html index bab8c8c..c9810c0 100644 --- a/02-03.html +++ b/02-03.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

The Flexible Mind

+

The Flexible Mind

Is the never-ending collection of information all there is to the assembly optimization, then? Hardly. Knowledge is simply a necessary base on which to build. Let’s take a moment to examine the objectives of good assembly programming, and the remainder of the forces that act on assembly optimization will fall into place.

Basically, there are only two possible objectives to high-performance assembly programming: Given the requirements of the application, keep to a minimum either the number of processor cycles the program takes to run, or the number of bytes in the program, or some combination of both. We’ll look at ways to achieve both objectives, but we’ll more often be concerned with saving cycles than saving bytes, for the PC generally offers relatively more memory than it does processing horsepower. In fact, we’ll find that two-to-three times performance improvements over already tight assembly code are often possible if we’re willing to spend additional bytes in order to save cycles. It’s not always desirable to use such techniques to speed up code, due to the heavy memory requirements—but it is almost always possible.

@@ -50,7 +50,7 @@

Simple logic dictates that no compiler can know as much about what a piece of code needs to do or adapt as well to those needs as the person who wrote the code. Given that superior information and adaptability, an assembly language programmer can generate better code than a compiler, all the more so given that compilers are constrained by the limitations of high-level languages and by the process of transformation from high-level to machine language. Consequently, carefully optimized assembly is not just the language of choice but the only choice for the 1percent to 10 percent of code—usually consisting of small, well-defined subroutines—that determines overall program performance, and it is the only choice for code that must be as compact as possible, as well. In the run-of-the-mill, non-time-critical portions of your programs, it makes no sense to waste time and effort on writing optimized assembly code—concentrate your efforts on loops and the like instead; but in those areas where you need the finest code quality, accept no substitutes.

Note that I said that an assembly programmer can generate better code than a compiler, not will generate better code. While it is true that good assembly code is better than good compiled code, it is also true that bad assembly code is often much worse than bad compiled code; since the assembly programmer has so much control over the program, he or she has virtually unlimited opportunities to waste cycles and bytes. The sword cuts both ways, and good assembly code requires more, not less, forethought and planning than good code written in a high-level language.

The gist of all this is simply that good assembly programming is done in the context of a solid overall framework unique to each program, and the flexible mind is the key to creating that framework and holding it together.

-

Where to Begin?

+

Where to Begin?

To summarize, the skill of assembly language optimization is a combination of knowledge, perspective, and a way of thought that makes possible the genesis of absolutely the fastest or the smallest code. With that in mind, what should the first step be? Development of the flexible mind is an obvious step. Still, the flexible mind is no better than the knowledge at its disposal. The first step in the journey toward mastering optimization at that exalted level, then, would seem to be learning how to learn.


@@ -65,7 +65,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-01.html b/03-01.html index cc8b72e..e689264 100644 --- a/03-01.html +++ b/03-01.html @@ -24,7 +24,7 @@ - +
@@ -36,14 +36,13 @@


-

Chapter 3
Assume Nothing -

-

Understanding and Using the Zen Timer

+

Chapter 3
Assume Nothing

+

Understanding and Using the Zen Timer

When you’re pushing the envelope in writing optimized PC code, you’re likely to become more than a little compulsive about finding approaches that let you wring more speed from your computer. In the process, you’re bound to make mistakes, which is fine—as long as you watch for those mistakes and learn from them.

A case in point: A few years back, I came across an article about 8088 assembly language called “Optimizing for Speed.” Now, “optimize” is not a word to be used lightly; Webster’s Ninth New Collegiate Dictionary defines optimize as “to make as perfect, effective, or functional as possible,” which certainly leaves little room for error. The author had, however, chosen a small, well-defined 8088 assembly language routine to refine, consisting of about 30 instructions that did nothing more than expand 8 bits to 16 bits by duplicating each bit.

The author of “Optimizing” had clearly fine-tuned the code with care, examining alternative instruction sequences and adding up cycles until he arrived at an implementation he calculated to be nearly 50 percent faster than the original routine. In short, he had used all the information at his disposal to improve his code, and had, as a result, saved cycles by the bushel. There was, in fact, only one slight problem with the optimized version of the routine....

It ran slower than the original version!

-

The Costs of Ignorance

+

The Costs of Ignorance

As diligent as the author had been, he had nonetheless committed a cardinal sin of x86 assembly language programming: He had assumed that the information available to him was both correct and complete. While the execution times provided by Intel for its processors are indeed correct, they are incomplete; the other—and often more important—part of code performance is instruction fetch time, a topic to which I will return in later chapters.

Had the author taken the time to measure the true performance of his code, he wouldn’t have put his reputation on the line with relatively low-performance code. What’s more, had he actually measured the performance of his code and found it to be unexpectedly slow, curiosity might well have led him to experiment further and thereby add to his store of reliable information about the CPU.

There you have an important tenet of assembly language optimization: After crafting the best code possible, check it in action to see if it’s really doing what you think it is. If it’s not behaving as expected, that’s all to the good, since solving mysteries is the path to knowledge. You’ll learn more in this way, I assure you, than from any manual or book on assembly language. @@ -51,7 +50,7 @@

Assume nothing. I cannot emphasize this strongly enough—when you care about performance, do your best to improve the code and then measure the improvement. If you don’t measure performance, you’re just guessing, and if you’re guessing, you’re not very likely to write top-notch code.

Ignorance about true performance can be costly. When I wrote video games for a living, I spent days at a time trying to wring more performance from my graphics drivers. I rewrote whole sections of code just to save a few cycles, juggled registers, and relied heavily on blurry-fast register-to-register shifts and adds. As I was writing my last game, I discovered that the program ran perceptibly faster if I used look-up tables instead of shifts and adds for my calculations. It shouldn’t have run faster, according to my cycle counting, but it did. In truth, instruction fetching was rearing its head again, as it often does, and the fetching of the shifts and adds was taking as much as four times the nominal execution time of those instructions.

Ignorance can also be responsible for considerable wasted effort. I recall a debate in the letters column of one computer magazine about exactly how quickly text can be drawn on a Color/Graphics Adapter (CGA) screen without causing snow. The letter-writers counted every cycle in their timing loops, just as the author in the story that started this chapter had. Like that author, the letter-writers had failed to take the prefetch queue into account. In fact, they had neglected the effects of video wait states as well, so the code they discussed was actually much slower than their estimates. The proper test would, of course, have been to run the code to see if snow resulted, since the only true measure of code performance is observing it in action.

-

The Zen Timer

+

The Zen Timer

Clearly, one key to mastering Zen-class optimization is a tool with which to measure code performance. The most accurate way to measure performance is with expensive hardware, but reasonable measurements at no cost can be made with the PC’s 8253 timer chip, which counts at a rate of slightly over 1,000,000 times per second. The 8253 can be started at the beginning of a block of code of interest and stopped at the end of that code, with the resulting count indicating how long the code took to execute with an accuracy of about 1 microsecond. (A microsecond is one millionth of a second, and is abbreviated µs). To be precise, the 8253 counts once every 838.1 nanoseconds. (A nanosecond is one billionth of a second, and is abbreviated ns.)

Listing 3.1 shows 8253-based timer software, consisting of three subroutines: ZTimerOn, ZTimerOff, and ZTimerReport. For the remainder of this book, I’ll refer to these routines collectively as the “Zen timer.” C-callable versions of the two precision Zen timers are presented in Chapter K on the companion CD-ROM.


@@ -67,7 +66,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-02.html b/03-02.html index 4d4cf47..649993c 100644 --- a/03-02.html +++ b/03-02.html @@ -24,7 +24,7 @@ - +
@@ -493,7 +493,7 @@ Code ends
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-03.html b/03-03.html index fe8d0af..ad1cafa 100644 --- a/03-03.html +++ b/03-03.html @@ -24,7 +24,7 @@ - +
@@ -36,20 +36,20 @@


-

The Zen Timer Is a Means, Not an End

+

The Zen Timer Is a Means, Not an End

We’re going to spend the rest of this chapter seeing what the Zen timer can do, examining how it works, and learning how to use it. I’ll be using the Zen timer again and again over the course of this book, so it’s essential that you learn what the Zen timer can do and how to use it. On the other hand, it is by no means essential that you understand exactly how the Zen timer works. (Interesting, yes; essential, no.)

In other words, the Zen timer isn’t really part of the knowledge we seek; rather, it’s one tool with which we’ll acquire that knowledge. Consequently, you shouldn’t worry if you don’t fully grasp the inner workings of the Zen timer. Instead, focus on learning how to use it, and you’ll be on the right road.

-

Starting the Zen Timer

+

Starting the Zen Timer

ZTimerOn is called at the start of a segment of code to be timed. ZTimerOn saves the context of the calling code, disables interrupts, sets timer 0 of the 8253 to mode 2 (divide-by-N mode), sets the initial timer count to 0, restores the context of the calling code, and returns. (I’d like to note that while Intel’s documentation for the 8253 seems to indicate that a timer won’t reset to 0 until it finishes counting down, in actual practice, timers seem to reset to 0 as soon as they’re loaded.)

Two aspects of ZTimerOn are worth discussing further. One point of interest is that ZTimerOn disables interrupts. (ZTimerOff later restores interrupts to the state they were in when ZTimerOn was called.) Were interrupts not disabled by ZTimerOn, keyboard, mouse, timer, and other interrupts could occur during the timing interval, and the time required to service those interrupts would incorrectly and erratically appear to be part of the execution time of the code being measured. As a result, code timed with the Zen timer should not expect any hardware interrupts to occur during the interval between any call to ZTimerOn and the corresponding call to ZTimerOff, and should not enable interrupts during that time.

-

Time and the PC

+

Time and the PC

A second interesting point about ZTimerOn is that it may introduce some small inaccuracy into the system clock time whenever it is called. To understand why this is so, we need to examine the way in which both the 8253 and the PC’s system clock (which keeps the current time) work.

The 8253 actually contains three timers, as shown in Figure 3.1. All three timers are driven by the system board’s 14.31818 MHz crystal, divided by 12 to yield a 1.19318 MHz clock to the timers, so the timers count once every 838.1 ns. Each of the three timers counts down in a programmable way, generating a signal on its output pin when it counts down to 0. Each timer is capable of being halted at any time via a 0 level on its gate input; when a timer’s gate input is 1, that timer counts constantly. All in all, the 8253’s timers are inherently very flexible timing devices; unfortunately, much of that flexibility depends on how the timers are connected to external circuitry, and in the PC the timers are connected with specific purposes in mind.

Timer 2 drives the speaker, although it can be used for other timing purposes when the speaker is not in use. As shown in Figure 3.1, timer 2 is the only timer with a programmable gate input in the PC; that is, timer 2 is the only timer that can be started and stopped under program control in the manner specified by Intel. On the other hand, the output of timer 2 is connected to nothing other than the speaker. In particular, timer 2 cannot generate an interrupt to get the 8088’s attention.

Timer 1 is dedicated to providing dynamic RAM refresh, and should not be tampered with lest system crashes result.


Figure 3.1
  The configuration of the 8253 timer chip in the PC. +
-->Figure 3.1  The configuration of the 8253 timer chip in the PC.

Finally, timer 0 is used to drive the system clock. As programmed by the BIOS at power-up, every 65,536 (64K) counts, or 54.925 milliseconds, timer 0 generates a rising edge on its output line. (A millisecond is one-thousandth of a second, and is abbreviated ms.) This line is connected to the hardware interrupt 0 (IRQ0) line on the system board, so every 54.925 ms, timer 0 causes hardware interrupt 0 to occur.

@@ -70,7 +70,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-04.html b/03-04.html index 7cdd90e..fc6f850 100644 --- a/03-04.html +++ b/03-04.html @@ -24,7 +24,7 @@ - +
@@ -43,12 +43,12 @@

Potentially far greater inaccuracy can be incurred by timing code that takes longer than about 110 ms to execute. Recall that all interrupts, including the timer interrupt, are disabled while timing code with the Zen timer. The 8259 interrupt controller is capable of remembering at most one pending timer interrupt, so all timer interrupts after the first one during any given Zen timing interval are ignored. Consequently, if a timing interval exceeds 54.9 ms, the system clock effectively stops 54.9 ms after the timing interval starts and doesn’t restart until the timing interval ends, losing time all the while.

The effects on the system time of the Zen timer aren’t a matter for great concern, as they are temporary, lasting only until the next warm or cold boot. System that have batteryclocks, (AT-style machines; that is, virtually all machines in common use) automatically reset the correct time whenever the computer is booted, and systems without battery-clocks prompt for the correct date and time when booted. Also,repeated use of the Zen timer usually makes the system clock slow by at most a total of a few seconds, unless code that takes much longer than 54 ms to run is timed (in which case the Zen timer will notify you that the code is too long to time).

Nonetheless, it’s a good idea to reboot your computer at the end of each session with the Zen timer in order to make sure that the system clock is correct.

-

Stopping the Zen Timer

+

Stopping the Zen Timer

At some point after ZTimerOn is called, ZTimerOff must always be called to mark the end of the timing interval. ZTimerOff saves the context of the calling program, latches and reads the timer 0 count, converts that count from the countdown value that the timer maintains to the number of counts elapsed since ZTimerOn was called, and stores the result. Immediately after latching the timer 0 count—and before enabling interrupts—ZTimerOff checks the 8259 interrupt controller to see if there is a pending timer interrupt, setting a flag to mark that the timer overflowed if there is indeed a pending timer interrupt.

After that, ZTimerOff executes just the overhead code of ZTimerOn and ZTimerOff 16 times, and averages and saves the results in order to determine how many of the counts in the timing result just obtained were incurred by the overhead of the Zen timer rather than by the code being timed.

Finally, ZTimerOff restores the context of the calling program, including the state of the interrupt flag that was in effect when ZTimerOn was called to start timing, and returns.

One interesting aspect of ZTimerOff is the manner in which timer 0 is stopped in order to read the timer count. We don’t actually have to stop timer 0 to read the count; the 8253 provides a special latched read feature for the specific purpose of reading the count while a time is running. (That’s a good thing, too; we’ve no documented way to stop timer 0 if we wanted to, since its gate input isn’t connected. Later in this chapter, though, we’ll see that timer 0 can be stopped after all.) We simply tell the 8253 to latch the current count, and the 8253 does so without breaking stride.

-

Reporting Timing Results

+

Reporting Timing Results

ZTimerReport may be called to display timing results at any time after both ZTimerOn and ZTimerOff have been called. ZTimerReport first checks to see whether the timer overflowed (counted down to 0 and turned over) before ZTimerOff was called; if overflow did occur, ZTimerOff prints a message to that effect and returns. Otherwise, ZTimerReport subtracts the reference count (representing the overhead of the Zen timer) from the count measured between the calls to ZTimerOn and ZTimerOff, converts the result from timer counts to microseconds, and prints the resulting time in microseconds to the standard output.

Note that ZTimerReport need not be called immediately after ZTimerOff. In fact, after a given call to ZTimerOff, ZTimerReport can be called at any time right up until the next call to ZTimerOn.

You may want to use the Zen timer to measure several portions of a program while it executes normally, in which case it may not be desirable to have the text printed by ZTimerReport interfere with the program’s normal display. There are many ways to deal with this. One approach is removal of the invocations of the DOS print string function (INT 21H with AH equal to 9) from ZTimerReport, instead running the program under a debugger that supports screen flipping (such as Turbo Debugger or CodeView), placing a breakpoint at the start of ZTimerReport, and directly observing the count in microseconds as ZTimerReport calculates it.

@@ -69,7 +69,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-05.html b/03-05.html index b40fb36..f1a96c1 100644 --- a/03-05.html +++ b/03-05.html @@ -24,7 +24,7 @@ - +
@@ -36,14 +36,14 @@


-

Notes on the Zen Timer

+

Notes on the Zen Timer

The Zen timer subroutines are designed to be near-called from assembly language code running in the public segment Code. The Zen timer subroutines can, however, be called from any assembly or high-level language code that generates OBJ files that are compatible with the Microsoft linker, simply by modifying the segment that the timer code runs in to match the segment used by the code being timed, or by changing the Zen timer routines to far procedures and making far calls to the Zen timer code from the code being timed, as discussed at the end of this chapter. All three subroutines preserve all registers and all flags except the interrupt flag, so calls to these routines are transparent to the calling code.

If you do change the Zen timer routines to far procedures in order to call them from code running in another segment, be sure to make all the Zen timer routines far, including ReferenceZTimerOn and ReferenceZTimerOff. (You’ll have to put FAR PTR overrides on the calls from ZTimerOff to the latter two routines if you do make them far.) If the reference routines aren’t the same type—near or far—as the other routines, they won’t reflect the true overhead incurred by starting and stopping the Zen timer.

Please be aware that the inaccuracy that the Zen timer can introduce into the system clock time does not affect the accuracy of the performance measurements reported by the Zen timer itself. The 8253 counts once every 838 ns, giving us a count resolution of about 1µs, although factors such as the prefetch queue (as discussed below), dynamic RAM refresh, and internal timing variations in the 8253 make it perhaps more accurate to describe the Zen timer as measuring code performance with an accuracy of better than 10µs. In fact, the Zen timer is actually most accurate in assessing code performance when timing intervals longer than about 100 µs. At any rate, we’re most interested in using the Zen timer to assess the relative performance of various code sequences—that is, using it to compare and tweak code—and the timer is more than accurate enough for that purpose.

The Zen timer works on all PC-compatible computers I’ve tested it on, including XTs, ATs, PS/2 computers, and 386, 486, and Pentium-based machines. Of course, I haven’t been able to test it on all PC-compatibles, but I don’t expect any problems; computers on which the Zen timer doesn’t run can’t truly be called “PC-compatible.”

On the other hand, there is certainly no guarantee that code performance as measured by the Zen timer will be the same on compatible computers as on genuine IBM machines, or that either absolute or relative code performance will be similar even on different IBM models; in fact, quite the opposite is true. For example, every PS/2 computer, even the relatively slow Model 30, executes code much faster than does a PC or XT. As another example, I set out to do the timings for my earlier book Zen of Assembly Language on an XTcomputer, only to find that the computer wasn’t quite IBM-compatible regarding code performance. The differences were minor, mind you, but my experience illustrates the risk of assuming that a specific make of computer will perform in a certain way without actually checking.

Not that this variation between models makes the Zen timer one whit less useful—quite the contrary. The Zen timer is an excellent tool for evaluating code performance over the entire spectrum of PC-compatible computers.

-

A Sample Use of the Zen Timer

+

A Sample Use of the Zen Timer

Listing 3.2 shows a test-bed program for measuring code performance with the Zen timer. This program sets DS equal to CS (for reasons we’ll discuss shortly), includes the code to be measured from the file TESTCODE, and calls ZTimerReport to display the timing results. Consequently, the code being measured should be in the file TESTCODE, and should contain calls to ZTimerOn and ZTimerOff .

LISTING 3.2 PZTEST.ASM

@@ -130,7 +130,7 @@ Skip:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-06.html b/03-06.html index 91ebaa2..5e93556 100644 --- a/03-06.html +++ b/03-06.html @@ -24,7 +24,7 @@ - +
@@ -121,7 +121,7 @@ pztime <filename>

In fact, that’s exactly how I timed each of the listings in this book. Code fragments you write yourself can be timed in just the same way. If you wish to time code directly in place in your programs, rather than in the test-bed program of Listing 3.2, simply insert calls to ZTimerOn, ZTimerOff, and ZTimerReport in the appropriate places and link PZTIMER to your program.

-

The Long-Period Zen Timer

+

The Long-Period Zen Timer

With a few exceptions, the Zen timer presented above will serve us well for the remainder of this book since we’ll be focusing on relatively short code sequences that generally take much less than 54 ms to execute. Occasionally, however, we will need to time longer intervals. What’s more, it is very likely that you will want to time code sequences longer than 54 ms at some point in your programming career. Accordingly, I’ve also developed a Zen timer for periods longer than 54 ms. The long-period Zen timer (so named by contrast with the precision Zen timer just presented) shown in Listing 3.5 can measure periods up to one hour in length.

The key difference between the long-period Zen timer and the precision Zen timer is that the long-period timer leaves interrupts enabled during the timing period. As a result, timer interrupts are recognized by the PC, allowing the BIOS to maintain an accurate system clock time over the timing period. Theoretically, this enables measurement of arbitrarily long periods. Practically speaking, however, there is no need for a timer that can measure more than a few minutes, since the DOS time of day and date functions (or, indeed, the DATE and TIME commands in a batch file) serve perfectly well for longer intervals. Since very long timing intervals aren’t needed, the long-period Zen timer uses a simplified means of calculating elapsed time that is limited to measuring intervals of an hour or less. If a period longer than an hour is timed, the long-period Zen timer prints a message to the effect that it is unable to time an interval of that length.

@@ -139,7 +139,7 @@ pztime <filename>
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-07.html b/03-07.html index 4858f15..ffa5ce5 100644 --- a/03-07.html +++ b/03-07.html @@ -24,7 +24,7 @@ - +
@@ -39,7 +39,7 @@

While permitting the timer interrupt to occur allows long intervals to be timed, that same interrupt makes the long-period Zen timer less accurate than the precision Zen timer, since the time the BIOS spends handling timer interrupts during the timing interval is included in the time measured by the long-period timer. Likewise, any other interrupts that occur during the timing interval, most notably keyboard and mouse interrupts, will increase the measured time.

The long-period Zen timer has some of the same effects on the system time as does the precision Zen timer, so it’s a good idea to reboot the system after a session with the long-period Zen timer. The long-period Zen timer does not, however, have the same potential for introducing major inaccuracy into the system clock time during a single timing run since it leaves interrupts enabled and therefore allows the system clock to update normally.

-

Stopping the Clock

+

Stopping the Clock

There’s a potential problem with the long-period Zen timer. The problem is this: In order to measure times longer than 54 ms, we must maintain not one but two timing components, the timer 0 count and the BIOS time-of-day count. The time-of-day count measures the passage of 54.9 ms intervals, while the timer 0 count measures time within those 54.9 ms intervals. We need to read the two time components simultaneously in order to get a clean reading. Otherwise, we may read the timer count just before it turns over and generates an interrupt, then read the BIOS time-of-day count just after the interrupt has occurred and caused the time-of-day count to turn over, with a resulting 54 ms measurement inaccuracy. (The opposite sequence—reading the time-of-day count and then the timer count—can result in a 54 ms inaccuracy in the other direction.)

The only way to avoid this problem is to stop timer 0, read both the timer and time-of-day counts while the timer is stopped, and then restart the timer. Alas, the gate input to timer 0 isn’t program-controllable in the PC, so there’s no documented way to stop the timer. (The latched read feature we used in Listing 3.1 doesn’t stop the timer; it latches a count, but the timer keeps running.) What should we do?

@@ -698,7 +698,7 @@ Code ends
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-08.html b/03-08.html index 7eaa25a..cf570df 100644 --- a/03-08.html +++ b/03-08.html @@ -24,7 +24,7 @@ - +
@@ -41,7 +41,7 @@

While the the non-PS/2 version is more dangerous than the PS/2 version, it also produces more accurate results when it does work. If you have a non-PS/2 PC-compatible computer, the choice between the two timing approaches is yours.

If you do leave the PS2 equate at 1 in Listing 3.5, you should repeat each code-timing run several times before relying on the results to be accurate to more than 54 ms, since variations may result from the possible lack of synchronization between the timer 0 count and the BIOS time-of-day count. In fact, it’s a good idea to time code more than once no matter which version of the long-period Zen timer you’re using, since interrupts, which must be enabled in order for the long-period timer to work properly, may occur at any time and can alter execution time substantially.

Finally, please note that the precision Zen timer works perfectly well on both PS/2 and non-PS/2 computers. The PS/2 and 8253 considerations we’ve just discussed apply only to the longZen timer.

-

Example Use of the Long-Period Zen Timer

+

Example Use of the Long-Period Zen Timer

The long-period Zen timer has exactly the same calling interface as the precision Zen timer, and can be used in place of the precision Zen timer simply by linking it to the code to be timed in place of linking the precision timer code. Whenever the precision Zen timer informs you that the code being timed takes too long for the precision timer to handle, all you have to do is link in the long-period timer instead.

Listing 3.6 shows a test-bed program for the long-period Zen timer. While this program is similar to Listing 3.2, it’s worth noting that Listing 3.6 waits for a few seconds before calling ZTimerOn, thereby allowing any pending keyboard interrupts to be processed. Since interrupts must be left on in order to time periods longer than 54 ms, the interrupts generated by keystrokes (including the upstroke of the Enter key press that starts the program)—or any other interrupts, for that matter—could incorrectly inflate the time recorded by the long-period Zen timer. In light of this, resist the temptation to type ahead, move the mouse, or the like while the long-period Zen timer is timing.

@@ -122,7 +122,7 @@ Code ends
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-09.html b/03-09.html index 685e556..85ba6f5 100644 --- a/03-09.html +++ b/03-09.html @@ -24,7 +24,7 @@ - +
@@ -145,7 +145,7 @@ lztime lst3-8.asm

the result is 72,544 µs, or about 3.63 µs per load of AL from memory. This is just slightly longer than the time per load of AL measured by the precision Zen timer, as we would expect given that interrupts are left enabled by the long-period Zen timer. The extra fraction of a microsecond measured per MOV reflects the time required to execute the BIOS code that handles the 18.2 timer interrupts that occur each second.

Note that the command can take as much as 10 minutes to finish on a slow PC if you are using MASM, with most of that time spent assembling Listing 3.8. Why? Because MASM is notoriously slow at assembling REPT blocks, and the block in Listing 3.8 is repeated 20,000 times.

-

Using the Zen Timer from C

+

Using the Zen Timer from C

The Zen timer can be used to measure code performance when programming in C—but not right out of the box. As presented earlier, the timer is designed to be called from assembly language; some relatively minor modifications are required before the ZTimerOn (start timer), ZTimerOff (stop timer), and ZTimerReport (display timing results) routines can be called from C. There are two separate cases to be dealt with here: small code model and large; I’ll tackle the simpler one, the small code model, first.

Altering the Zen timer for linking to a small code model C program involves the following steps: C hange ZTimerOn to _ZTimerOn, change ZTimerOff to _ZTimerOff, change ZTimerReport to _ZTimerReport, and change Code to _TEXT . Figure 3.2 shows the line numbers and new states of all lines from Listing 3.1 that must be changed. These changes convert the code to use C-style external label names and the small model C code segment. (In C++, use the “C” specifier, as in

@@ -166,7 +166,7 @@ extern “C” ZTimerOn(void);
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/03-10.html b/03-10.html index f076be5..74bd04b 100644 --- a/03-10.html +++ b/03-10.html @@ -24,7 +24,7 @@ - +
@@ -50,12 +50,12 @@ ZTimerReport();

(I’m talking about the precision timer here. The long-period timer—Listing 3.5—requires the same modifications, but to different lines.)


Figure 3.2
  Changes for use with small code model C. +
-->Figure 3.2  Changes for use with small code model C.

Altering the Zen timer for use in C’s large code model is a tad more complex, because in addition to the above changes, all functions, including the internal reference timing routines that are used to calculate overhead so it can be subtracted out, must be converted to far. Figure 3.3 shows the line numbers and new states of all lines from Listing 3.1 that must be changed in order to call the Zen timer from large code model C. Again, the line numbers are specific to the precision timer, but the long-period timer is very similar.

The full listings for the C-callable Zen timers are presented in Chapter K on the companion CD-ROM.

-

Watch Out for Optimizing Assemblers!

+

Watch Out for Optimizing Assemblers!

One important safety tip when modifying the Zen timer for use with large code model C code: Watch out for optimizing assemblers! TASM actually replaces

@@ -73,16 +73,16 @@ call near ptr ReferenceZTimerOn

(and likewise for ReferenceZTimerOff ), which works because ReferenceZTimerOn is in the same segment as the calling code. This is normally a great optimization, being both smaller and faster than a far call. However, it’s not so great for the Zen


Figure 3.3
  Changes for use with large code model C. +
-->Figure 3.3  Changes for use with large code model C.

timer, because our purpose in calling the reference timing code is to determine exactly how much time is taken by overhead code—including the far calls to ZTimerOn and ZTimerOff! By converting the far calls to push/near call pairs within the Zen timer module, TASM makes it impossible to emulate exactly the overhead of the Zen timer, and makes timings slightly (about 16 cycles on a 386) less accurate.

What’s the solution? Put the NOSMART directive at the start of the Zen timer code. This directive instructs TASM to turn off all optimizations, including converting far calls to push/near call pairs. By the way, there is, to the best of my knowledge, no such problem with MASM up through version 5.10A.

In my mind, the whole business of optimizing assemblers is a mixed blessing. In general, it’s nice to have the assembler shortening jumps and selecting sign-extended forms of instructions for you. On the other hand, the benefits of tricks like substituting push/near call pairs for far calls are relatively small, and those tricks can get in the way when complete control is needed. Sure, complete control is needed very rarely, but when it is, optimizing assemblers can cause subtle problems; I discovered TASM’s alteration of far calls only because I happened to view the code in the debugger, and you might want to do the same if you’re using a recent version of MASM.

I’ve tested the changes shown in Figures 3.2 and 3.3 with TASM and Borland C++ 4.0, and also with the latest MASM and Microsoft C/C++ compiler.

-

Further Reading

+

Further Reading

For those of you who wish to pursue the mechanics of code measurement further, one good article about measuring code performance with the 8253 timer is “Programming Insight: High-Performance Software Analysis on the IBM PC,” by Byron Sheppard, which appeared in the January, 1987 issue of Byte. For complete if somewhat cryptic information on the 8253 timer itself, I refer you to Intel’s Microsystem Components Handbook, which is also a useful reference for a number of other PC components, including the 8259 Programmable Interrupt Controller and the 8237 DMA Controller. For details about the way the 8253 is used in the PC, as well as a great deal of additional information about the PC’s hardware and BIOS resources, I suggest you consult IBM’s series of technical reference manuals for the PC, XT, AT, Model 30, and microchannel computers, such as the Models 50, 60, and 80.

For our purposes, however, it’s not critical that you understand exactly how the Zen timer works. All you really need to know is what the Zen timer can do and how to use it, and we’ve accomplished that in this chapter.

-

Armed with the Zen Timer, Onward and Upward

+

Armed with the Zen Timer, Onward and Upward

The Zen timer is not perfect. For one thing, the finest resolution to which it can measure an interval is at best about 1µs, a period of time in which a 66 MHz Pentium computer can execute as many as 132 instructions (although an 8088-based PC would be hard-pressed to manage two instructions in a microsecond). Another problem is that the timing code itself interferes with the state of the prefetch queue and processor cache at the start of the code being timed, because the timing code is not necessarily fetched and does not necessarily access memory in exactly the same time sequence as the code immediately preceding the code under measurement normally does. This prefetch effect can introduce as much as 3 to 4 µ of inaccuracy. Similarly, the state of the prefetch queue at the end of the code being timed affects how long the code that stops the timer takes to execute. Consequently, the Zen timer tends to be more accurate for longer code sequences, since the relative magnitude of the inaccuracy introduced by the Zen timer becomes less over longer periods.

Imperfections notwithstanding, the Zen timer is a good tool for exploring C code and x86 family assembly language, and it’s a tool we’ll use frequently for the remainder of this book.


@@ -98,7 +98,7 @@ call near ptr ReferenceZTimerOn
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-01.html b/04-01.html index 944b852..90bf416 100644 --- a/04-01.html +++ b/04-01.html @@ -24,7 +24,7 @@ - +
@@ -36,21 +36,20 @@


-

Chapter 4
In the Lair of the Cycle-Eaters -

-

How the PC Hardware Devours Code Performance

+

Chapter 4
In the Lair of the Cycle-Eaters

+

How the PC Hardware Devours Code Performance

This chapter, adapted from my earlier book, Zen of Assembly Language located on the companion CD-ROM, goes right to the heart of my philosophy of optimization: Understand where the time really goes when your code runs. That may sound ridiculously simple, but, as this chapter makes clear, it turns out to be a challenging task indeed, one that at times verges on black magic. This chapter is a long-time favorite of mine because it was the first—and to a large extent only—work that I know of that discussed this material, thereby introducing a generation of PC programmers to pedal-to-the-metal optimization.

This chapter focuses almost entirely on the first popular x86-family processor, the 8088. Some of the specific features and results that I cite in this chapter are no longer applicable to modern x86-family processors such as the 486 and Pentium, as I’ll point out later on when we discuss those processors. Nonetheless, the overall theme of this chapter—that understanding dimly-seen and poorly-documented code gremlins called cycle-eaters that lurk in your system is essential to performance programming—is every bit as valid today. Also, later chapters often refer back to the basic cycle-eaters described in this chapter, so this chapter is the foundation for the discussions of x86-family optimization to come. What’s more, the Zen timer remains an excellent tool with which to flush out and examine cycle-eaters, as we’ll see in later chapters, and this chapter is as good an illustration of how to use the Zen timer as you’re likely to find.

So, don’t take either the absolute or the relative execution times presented in this chapter as gospel for newer processors, and read on to later chapters to see how the cycle-eaters and optimization rules have changed over time, but do take the time to at least skim through this chapter to give yourself a good start on the material in the rest of this book.

-

Cycle-Eaters

+

Cycle-Eaters

Programming has many levels, ranging from the familiar (high-level languages, DOS calls, and the like) down to the esoteric things that lie on the shadowy edge of hardware-land. I call these cycle-eaters because, like the monsters in a bad 50s horror movie, they lurk in those shadows, taking their share of your program’s performance without regard to the forces of goodness or the U.S. Army. In this chapter, we’re going to jump right in at the lowest level by examining the cycle-eaters that live beneath the programming interface; that is, beneath your application, DOS, and BIOS—in fact, beneath the instruction set itself.

Why start at the lowest level? Simply because cycle-eaters affect the performance of all assembler code, and yet are almost unknown to most programmers. A full understanding of code optimization requires an understanding of cycle-eaters and their implications. That’s no simple task, and in fact it is in precisely that area that most books and articles about assembly programming fall short.

Nearly all literature on assembly programming discusses only the programming interface: the instruction set, the registers, the flags, and the BIOS and DOS calls. Those topics cover the functionality of assembly programs most thoroughly—but it’s performance above all else that we’re after. No one ever tells you about the raw stuff of performance, which lies beneath the programming interface, in the dimly-seen realm—populated by instruction prefetching, dynamic RAM refresh, and wait states—where software meets hardware. This area is the domain of hardware engineers, and is almost never discussed as it relates to code performance. And yet it is only by understanding the mechanisms operating at this level that we can fully understand and properly improve the performance of our code.

Which brings us to cycle-eaters.

-

The Nature of Cycle-Eaters

+

The Nature of Cycle-Eaters

Cycle-eaters are gremlins that live on the bus or in peripherals (and sometimes within the CPU itself), slowing the performance of PC code so that it doesn’t execute at full speed. Most cycle-eaters (and all of those haunting the older Intel processors) live outside the CPU’s Execution Unit, where they can only affect the CPU when the CPU performs a bus access (a memory or I/O read or write). Once your code and data are already inside the CPU, those cycle-eaters can no longer be a problem. Only on the 486 and Pentium CPUs will you find cycle-eaters inside the chip, as we’ll see in later chapters.

The nature and severity of the cycle-eaters vary enormously from processor to processor, and (especially) from memory architecture to memory architecture. In order to understand them all, we need first to understand the simplest among them, those that haunted the original 8088-based IBM PC. Later on in this book, I’ll be better able to explain the newer generation of cycle-eaters in terms of those ancestral cycle-eaters—but we have to get the groundwork down first.

-

The 8088’s Ancestral Cycle-Eaters

+

The 8088’s Ancestral Cycle-Eaters

Internally, the 8088 is a 16-bit processor, capable of running at full speed at all times—unless external data is required. External data must traverse the 8088’s external data bus and the PC’s data bus one byte at a time to and from peripherals, with cycle-eaters lurking along every step of the way. What’s more, external data includes not only memory operands but also instruction bytes, so even instructions with no memory operands can suffer from cycle-eaters. Since some of the 8088’s fastest instructions are register-only instructions, that’s important indeed.

The major cycle-eaters are:

    @@ -61,7 +60,7 @@

The locations of these cycle-eaters in the primordial 8088-based PC are shown in Figure 4.1. We’ll cover each of the cycle-eaters in turn in this chapter. The material won’t be easy since cycle-eaters are among the most subtle aspects of assembly programming. By the same token, however, this will be one of the most important and rewarding chapters in this book. Don’t worry if you don’t catch everything in this chapter, but do read it all even if the going gets a bit tough. Cycle-eaters play a key role in later chapters, so some familiarity with them is highly desirable.

-

The 8-Bit Bus Cycle-Eater

+

The 8-Bit Bus Cycle-Eater

Look! Down on the motherboard! It’s a 16-bit processor! It’s an 8-bit processor! It’s...

...an 8088!

Fans of the 8088 call it a 16-bit processor. Fans of other 16-bit processors call the 8088 an 8-bit processor. The truth of the matter is that the 8088 is a 16-bit processor that often performs like an 8-bit processor.

@@ -78,7 +77,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-02.html b/04-02.html index eaceae5..d12e0b7 100644 --- a/04-02.html +++ b/04-02.html @@ -24,7 +24,7 @@ - +
@@ -37,16 +37,16 @@



Figure 4.1
  The location of the major cycle-eaters in the IBM PC. +
-->Figure 4.1  The location of the major cycle-eaters in the IBM PC.


Figure 4.2
  Internal data bus widths of the 8088. +
-->Figure 4.2  Internal data bus widths of the 8088.

As shown in Figure 4.1, the 8-bit bus cycle-eater lies squarely on the 8088’s external data bus. Technically, it might be more accurate to place this cycle-eater in the Bus Interface Unit, which breaks 16-bit memory accesses into paired 8-bit accesses, but it is really the limited width of the external data bus that constricts data flow into and out of the 8088. True, the original PC’s bus is also only 8 bits wide, but that’s just to match the 8088’s 8-bit bus; even if the PC’s bus were 16 bits wide, data could still pass into and out of the 8088 chip itself only 1 byte at a time.

Each bus access by the 8088 takes 4 clock cycles, or 0.838 µs in the 4.77 MHz PC, and transfers 1 byte. That means that the maximum rate at which data can be transferred into and out of the 8088 is 1 byte every 0.838 µs. While 8086 bus accesses also take 4 clock cycles, each 8086 bus access can transfer either 1 byte or 1 word, for a maximum transfer rate of 1 word every 0.838 µs. Consequently, for word-sized memory accesses, the 8086 has an effective transfer rate of 1 byte every 0.419 µs. By contrast, every word-sized access on the 8088 requires two 4-cycle-long bus accesses, one for the high byte of the word and one for the low byte of the word. As a result, the 8088 has an effective transfer rate for word-sized memory accesses of just 1 word every 1.676 µs—and that, in a nutshell, is the 8-bit bus cycle-eater.

A related cycle-eater lurks beneath the 386SX chip, which is a 32-bit processor internally with only a 16-bit path to system memory. The numbers are different, but the way the cycle-eater operates is exactly the same. AT-compatible systems have 16-bit data buses, which can access a full 16-bit word at a time. The 386SX can process 32 bits (a doubleword) at a time, however, and loses a lot of time fetching that doubleword from memory in two halves.

-

The Impact of the 8-Bit Bus Cycle-Eater

+

The Impact of the 8-Bit Bus Cycle-Eater

One obvious effect of the 8-bit bus cycle-eater is that word-sized accesses to memory operands on the 8088 take 4 cycles longer than byte-sized accesses. That’s why the official instruction timings indicate that for code running on an 8088 an additional 4 cycles are required for every word-sized access to a memory operand. For instance,

@@ -76,7 +76,7 @@ add byte ptr [MemVar],al

String instructions can suffer from the 8-bit bus cycle-eater to a greater extent than other instructions. Believe it or not, a single REP MOVSW instruction can lose as much as 131,070 word-sized memory accesses x 4 cycles, or 524,280 cycles to the 8-bit bus cycle-eater! In other words, one 8088 instruction (admittedly, an instruction that does a great deal) can take over one-tenth of a second longer on an 8088 than on an 8086, simply because of the 8-bit bus. One-tenth of a second! That’s a phenomenally long time in computer terms; in one-tenth of a second, the 8088 can perform more than 50,000 additions and subtractions.

The upshot of all this is simply that the 8088 can transfer word-sized data to and from memory at only half the speed of the 8086, which inevitably causes performance problems when coupled with an Execution Unit that can process word-sized data every bit as quickly as an 8086. These problems show up with any code that uses word-sized memory operands. More ominously, as we will see shortly, the 8-bit bus cycle-eater can cause performance problems with other sorts of code as well.

-

What to Do about the 8-Bit Bus Cycle-Eater?

+

What to Do about the 8-Bit Bus Cycle-Eater?

The obvious implication of the 8-bit bus cycle-eater is that byte-sized memory variables should be used whenever possible. After all, the 8088 performs byte-sized memory accesses just as quickly as the 8086. For instance, Listing 4.1, which uses a byte-sized memory variable as a loop counter, runs in 10.03 s per loop. That’s 20 percent faster than the 12.05 µs per loop execution time of Listing 4.2, which uses a word-sized counter. Why the difference in execution times? Simply because each word-sized DEC performs 4 byte-sized memory accesses (two to read the word-sized operand and two to write the result back to memory), while each byte-sized DEC performs only 2 byte-sized memory accesses in all.

LISTING 4.1 LST4-1.ASM

@@ -127,7 +127,7 @@ LoopTop:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-03.html b/04-03.html index 7f76659..da2f7f9 100644 --- a/04-03.html +++ b/04-03.html @@ -24,7 +24,7 @@ - +
@@ -85,7 +85,7 @@ mov dx,word ptr [MemVar]

There is yet another reason why register operands are preferable to memory operands, and it’s an unexpected effect of the 8-bit bus cycle-eater. Instructions with only register operands tend to be shorter (in terms of bytes) than instructions with memory operands, and when it comes to performance, shorter is usually better. In order to explain why that is true and how it relates to the 8-bit bus cycle-eater, I must diverge for a moment.

For the last few pages, you may well have been thinking that the 8-bit bus cycle-eater, while a nuisance, doesn’t seem particularly subtle or difficult to quantify. After all, any instruction reference tells us exactly how many cycles each instruction loses to the 8-bit bus cycle-eater, doesn’t it?

Yes and no. It’s true that in general we know approximately how much longer a given instruction will take to execute with a word-sized memory operand than with a byte-sized operand, although the dynamic RAM refresh and wait state cycle-eaters (which I’ll cover a little later) can raise the cost of the 8-bit bus cycle-eater considerably. However, all word-sized memory accesses lose 4 cycles to the 8-bit bus cycle-eater, and there’s one sort of word-sized memory access we haven’t discussed yet: instruction fetching. The ugliest manifestation of the 8-bit bus cycle-eater is in fact the prefetch queue cycle-eater.

-

The Prefetch Queue Cycle-Eater

+

The Prefetch Queue Cycle-Eater

In an 8088 context, here’s the prefetch queue cycle-eater in a nutshell: The 8088’s 8-bit external data bus keeps the Bus Interface Unit from fetching instruction bytes as fast as the 16-bit Execution Unit can execute them, so the Execution Unit often lies idle while waiting for the next instruction byte to be fetched.

Exactly why does this happen? Recall that the 8088 is an 8086 internally, but accesses word-sized memory data at only one-half the maximum rate of the 8086 due to the 8088’s 8-bit external data bus. Unfortunately, instructions are among the word-sized data the 8086 fetches, meaning that the 8088 can fetch instructions at only one-half the speed of the 8086. On the other hand, the 8086-equivalent Execution Unit of the 8088 can execute instructions every bit as fast as the 8086. The net result is that the Execution Unit burns up instruction bytes much faster than the Bus Interface Unit can fetch them, and ends up idling while waiting for instructions bytes to arrive.

@@ -121,7 +121,7 @@ shr ax,1
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-04.html b/04-04.html index 5a5606f..3ddf076 100644 --- a/04-04.html +++ b/04-04.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

Official Execution Times Are Only Part of the Story

+

Official Execution Times Are Only Part of the Story

The sequence of 5 SHR instructions in the last example is 10 bytes long. That means that it can never execute in less than 24 cycles even if the 4-byte prefetch queue is full when it starts, since 6 instruction bytes would still remain to be fetched, at 4 cycles per fetch. If the prefetch queue is empty at the start, the sequence could take 40 cycles. In short, thanks to instruction fetching, the code won’t run at its documented speed, and could take up to four times longer than it is supposed to.

Why does Intel document Execution Unit execution time rather than overall instruction execution time, which includes both instruction fetch time and Execution Unit (EU) execution time? Well, instruction fetching isn’t performed as part of instruction execution by the Execution Unit, but instead is carried on in parallel by the Bus Interface Unit (BIU) whenever the external data bus isn’t in use or whenever the EU runs out of instruction bytes to execute. Sometimes the BIU is able to use spare bus cycles to prefetch instruction bytes before the EU needs them, so in those cases instruction fetching takes no time at all, practically speaking. At other times the EU executes instructions faster than the BIU can fetch them, and instruction fetching then becomes a significant part of overall execution time. As a result, the effective fetch time for a given instruction varies greatly depending on the code mix preceding that instruction. Similarly, the state in which a given instruction leaves the prefetch queue affects the overall execution time of the following instructions.

In other words, while the execution time for a given instruction is constant, the fetch time for that instruction depends heavily on the context in which the instruction is executing—the amount of prefetching the preceding instructions allowed—and can vary from a full 4 cycles per instruction byte to no time at all. @@ -44,7 +44,7 @@

As we’ll see later, other cycle-eaters, such as DRAM refresh and display memory wait states, can cause prefetching variations even during different executions of the same code sequence. Given that, it’s meaningless to talk about the prefetch time of a given instruction except in the context of a specific code sequence.

So now you know why the official instruction execution times are often wrong, and why Intel can’t provide better specifications. You also know now why it is that you must time your code if you want to know how fast it really is.

-

There Is No Such Beast as a True Instruction Execution Time

+

There Is No Such Beast as a True Instruction Execution Time

The effect of the code preceding an instruction on the execution time of that instruction makes the Zen timer trickier to use than you might expect, and complicates the interpretation of the results reported by the Zen timer. For one thing, the Zen timer is best used to time code sequences that are more than a few instructions long; below 10µs or so, prefetch queue effects and the limited resolution of the clock driving the timer can cause problems.

Some slight prefetch queue-induced inaccuracy usually exists even when the Zen timer is used to time longer code sequences, since the calls to the Zen timer usually alter the code’s prefetch queue from its normal state. (Branches—jumps, calls, returns and the like—empty the prefetch queue.) Ideally, the Zen timer is used to measure the performance of an entire subroutine, so the prefetch queue effects of the branches at the start and end of the subroutine are similar to the effects of the calls to the Zen timer when you’re measuring the subroutine’s performance.

@@ -84,7 +84,7 @@


Figure 4.3
  Execution and instruction prefetching sequence for Listing 4.5. +
-->Figure 4.3  Execution and instruction prefetching sequence for Listing 4.5.

Now let’s examine Listing 4.6. Here each SHR follows a MUL instruction. Since MUL instructions take so long to execute that the prefetch queue is always full when they finish, each SHR should be ready and waiting in the prefetch queue when the preceding MUL ends. As a result, we’d expect that each SHR would execute in 2 cycles; together with the 118-cycle execution time of multiplying 0 times 0, the total execution time should come to 120 cycles per SHR/MUL pair, as shown in Figure 4.4. And, by God, when we run Listing 4.6 we get an execution time of 25.14 µs per SHR/MUL pair, or exactly 120 cycles! According to these results, the “true” execution time of SHR would seem to be 2 cycles, quite a change from the conclusion we drew from Listing 4.5.

The key point is this: We’ve seen one code sequence in which SHR took 8-plus cycles to execute, and another in which it took only 2 cycles. Are we talking about two different forms of SHR here? Of course not—the difference is purely a reflection of the differing states in which the preceding code left the prefetch queue. In Listing 4.5, each SHR after the first few follows a slew of other SHR instructions which have sucked the prefetch queue dry, so overall performance reflects instruction fetch time. By contrast, each SHR in Listing 4.6 follows a MUL instruction which leaves the prefetch queue full, so overall performance reflects Execution Unit execution time.


@@ -100,7 +100,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-05.html b/04-05.html index 04b1e44..830dc2f 100644 --- a/04-05.html +++ b/04-05.html @@ -24,7 +24,7 @@ - +
@@ -39,7 +39,7 @@

Clearly, either instruction fetch time or Execution Unit execution time—or even a mix of the two, if an instruction is partially prefetched—can determine code performance. Some people operate under a rule of thumb by which they assume that the execution time of each instruction is 4 cycles times the number of bytes in the instruction. While that’s often true for register-only code, it frequently doesn’t hold for code that accesses memory. For one thing, the rule should be 4 cycles times the number of memory accesses, not instruction bytes, since all accesses take 4 cycles on the 8088-based PC. For another, memory-accessing instructions often have slower Execution Unit execution times than the 4 cycles per memory access rule would dictate, because the 8088 isn’t very fast at calculating memory addresses. Also, the 4 cycles per instruction byte rule isn’t true for register-only instructions that are already in the prefetch queue when the preceding instruction ends.

The truth is that it never hurts performance to reduce either the cycle count or the byte count of a given bit of code, but there’s no guarantee that one or the other will improve performance either. For example, consider Listing 4.7, which consists of a series of 4-cycle, 2-byte MOV AL,0 instructions, and which executes at the rate of 1.81 µs per instruction. Now consider Listing 4.8, which replaces the 4-cycle MOV AL,0 with the 3-cycle (but still 2-byte) SUB AL,AL, Despite its 1-cycle-per-instruction advantage, Listing 4.8 runs at exactly the same speed as Listing 4.7. The reason: Both instructions are 2 bytes long, and in both cases it is the 8-cycle instruction fetch time, not the 3 or 4-cycle Execution Unit execution time, that limits performance.


Figure 4.4
  Execution and instruction prefetching sequence for Listing 4.6. +
-->Figure 4.4  Execution and instruction prefetching sequence for Listing 4.6.

LISTING 4.7 LST4-7.ASM

@@ -77,11 +77,11 @@
The only true execution time for an instruction is a time measured in a certain context, and that time is meaningful only in that context.

What we really want is to know how long useful working code takes to run, not how long a single instruction takes, and the Zen timer gives us the tool we need to gather that information. Granted, it would be easier if we could just add up neatly documented instruction execution times—but that’s not going to happen. Without actually measuring the performance of a given code sequence, you simply don’t know how fast it is. For crying out loud, even the people who designed the 8088 at Intel couldn’t tell you exactly how quickly a given 8088 code sequence executes on the PC just by looking at it! Get used to the idea that execution times are only meaningful in context, learn the rules of thumb in this book, and use the Zen timer to measure your code.

-

Approximating Overall Execution Times

+

Approximating Overall Execution Times

Don’t think that because overall instruction execution time is determined by both instruction fetch time and Execution Unit execution time, the two times should be added together when estimating performance. For example, practically speaking, each SHR in Listing 4.5 does not take 8 cycles of instruction fetch time plus 2 cycles of Execution Unit execution time to execute. Figure 4.3 shows that while a given SHR is executing, the fetch of the next SHR is starting, and since the two operations are overlapped for 2 cycles, there’s no sense in charging the time to both instructions. You could think of the extra instruction fetch time for SHR in Listing 4.5 as being 6 cycles, which yields an overall execution time of 8 cycles when added to the 2 cycles of Execution Unit execution time.

Alternatively, you could think of each SHR in Listing 4.5 as taking 8 cycles to fetch, and then executing in effectively 0 cycles while the next SHR is being fetched. Whichever perspective you prefer is fine. The important point is that the time during which the execution of one instruction and the fetching of the next instruction overlap should only be counted toward the overall execution time of one of the instructions. For all intents and purposes, one of the two instructions runs at no performance cost whatsoever while the overlap exists.

As a working definition, we’ll consider the execution time of a given instruction in a particular context to start when the first byte of the instruction is sent to the Execution Unit and end when the first byte of the next instruction is sent to the EU.

-

What to Do about the Prefetch Queue Cycle-Eater?

+

What to Do about the Prefetch Queue Cycle-Eater?

Reducing the impact of the prefetch queue cycle-eater is one of the overriding principles of high-performance assembly code. How can you do this? One effective technique is to minimize access to memory operands, since such accesses compete with instruction fetching for precious memory accesses. You can also greatly reduce instruction fetch time simply by your choice of instructions: Keep your instructions short. Less time is required to fetch instructions that are 1 or 2 bytes long than instructions that are 5 or 6 bytes long. Reduced instruction fetching lowers minimum execution time (minimum execution time is 4 cycles times the number of instruction bytes) and often leads to faster overall execution.

While short instructions minimize overall prefetch time, ironically they actually often suffer more from the prefetch queue bottleneck than do long instructions. Short instructions generally have such fast execution times that they drain the prefetch queue despite their small size. For example, consider the SHR of Listing 4.5, which runs at only 25 percent of its Execution Unit execution time even though it’s only 2 bytes long, thanks to the prefetch queue bottleneck. Short instructions are nonetheless generally faster than long instructions, thanks to the combination of fewer instruction bytes and faster Execution Unit execution times, and should be used as much as possible—just don’t expect them to run at their “official” documented speeds.


@@ -96,7 +96,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-06.html b/04-06.html index 6058f81..7f868ed 100644 --- a/04-06.html +++ b/04-06.html @@ -24,7 +24,7 @@ - +
@@ -38,23 +38,23 @@


More than anything, the above rules mean using the registers as heavily as possible, both because register-only instructions are short and because they don’t perform memory accesses to read or write operands. However, using the registers is a rule of thumb, not a commandment. In some circumstances, it may actually be faster to access memory. (The look-up table technique is one such case.) What’s more, the performance of the prefetch queue (and hence the performance of each instruction) differs from one code sequence to the next, and can even differ during different executions of the same code sequence.

All in all, writing good assembler code is as much an art as a science. As a result, you should follow the rules of thumb described here—and then time your code to see how fast it really is. You should experiment freely, but always remember that actual, measured performance is the bottom line.

-

Holding Up the 8088

+

Holding Up the 8088

In this chapter I’ve taken you further and further into the depths of the PC, telling you again and again that you must understand the computer at the lowest possible level in order to write good code. At this point, you may well wonder, “Have we gotten low enough?”

Not quite yet. The 8-bit bus and prefetch queue cycle-eaters are low-level indeed, but we’ve one level yet to go. Dynamic RAM refresh and wait states—our next topics—together form the lowest level at which the hardware of the PC affects code performance. Below this level, the PC is of interest only to hardware engineers.

Before we begin our discussion of dynamic RAM refresh, let’s step back for a moment to take an overall look at this lowest level of cycle-eaters. In truth, the distinctions between wait states and dynamic RAM refresh don’t much matter to a programmer. What is important is that you understand this: Under certain circumstances, devices on the PC bus can stop the CPU for 1 or more cycles, making your code run more slowly than it seemingly should.

Unlike all the cycle-eaters we’ve encountered so far, wait states and dynamic RAM refresh are strictly external to the CPU, as was shown in Figure 4.1. Adapters on the PC’s bus, such as video and memory cards, can insert wait states on any bus access, the idea being that they won’t be able to complete the access properly unless the access is stretched out. Likewise, the channel of the DMA controller dedicated to dynamic RAM refresh can request control of the bus at any time, although the CPU must relinquish the bus before the DMA controller can take over. This means that your code can’t directly control wait states or dynamic RAM refresh. However, code can sometimes be designed to minimize the effects of these cycle-eaters, and even when the cycle-eaters slow your code without there being a thing in the world you can do about it, you’re still better off understanding that you’re losing performance and knowing why your code doesn’t run as fast as it’s supposed to than you were programming in ignorance.

Let’s start with DRAM refresh, which affects the performance of every program that runs on the PC.

-

Dynamic RAM Refresh: The Invisible Hand

+

Dynamic RAM Refresh: The Invisible Hand

Dynamic RAM (DRAM) refresh is sort of an act of God. By that I mean that DRAM refresh invisibly and inexorably steals a certain fraction of all available memory access time from your programs, when they are accessing memory for code and data. (When they are accessing cache on more recent processors, theoretically the DRAM refresh cycle-eater doesn’t come into play, but there are other cycle-eaters waiting to prey on cache-bound programs.) While you could stop DRAM refresh, you wouldn’t want to since that would be a sure prescription for crashing your computer. In the end, thanks to DRAM refresh, almost all code runs a bit slower on the PC than it otherwise would, and that’s that.

A bit of background: A static RAM (SRAM) chip is a memory chip that retains its contents indefinitely so long as power is maintained. By contrast, each of several blocks of bits in a dynamic RAM (DRAM) chip retains its contents for only a short time after it’s accessed for a read or write. In order to get a DRAM chip to store data for an extended period, each of the blocks of bits in that chip must be accessed regularly, so that the chip’s stored data is kept refreshed and valid. So long as this is done often enough, a DRAM chip will retain its contents indefinitely.

All of the PC’s system memory consists of DRAM chips. Each DRAM chip in the PC must be completely refreshed about once every four milliseconds in order to ensure the integrity of the data it stores. Obviously, it’s highly desirable that the memory in the PC retain the correct data indefinitely, so each DRAM chip in the PC must always be refreshed within 4 µs of the last refresh. Since there’s no guarantee that a given program will access each and every DRAM block once every 4 µs, the PC contains special circuitry and programming for providing DRAM refresh.

-

How DRAM Refresh Works in the PC

+

How DRAM Refresh Works in the PC

On the original 8088-based IBM PC, timer 1 of the 8253 timer chip is programmed at power-up to generate a signal once every 72 cycles, or once every 15.08µs. That signal goes to channel 0 of the 8237 DMA controller, which requests the bus from the 8088 upon receiving the signal. (DMA stands for direct memory access, the ability of a device other than the 8088 to control the bus and access memory directly, without any help from the 8088.) As soon as the 8088 is between memory accesses, it gives control of the bus to the 8237, which in conjunction with special circuitry on the PC’s motherboard then performs a single 4-cycle read access to 1 of 256 possible addresses, advancing to the next address on each successive access. (The read access is only for the purpose of refreshing the DRAM; the data that is read isn’t used.)

The 256 addresses accessed by the refresh DMA accesses are arranged so that taken together they properly refresh all the memory in the PC. By accessing one of the 256 addresses every 15.08 µs, all of the PC’s DRAM is refreshed in 256 x 15.08 µs, or 3.86 µs, which is just about the desired 4 µs time I mentioned earlier. (Only the first 640K of memory is refreshed in the PC; video adapters and other adapters above 640K containing memory that requires refreshing must provide their own DRAM refresh in pre-AT systems.)

Don’t sweat the details here. The important point is this: For at least 4 out of every 72 cycles, the original PC’s bus is given over to DRAM refresh and is not available to the 8088, as shown in Figure 4.5. That means that as much as 5.56 percent of the PC’s already inadequate bus capacity is lost. However, DRAM refresh doesn’t necessarily stop the 8088 in its tracks for 4 cycles. The Execution Unit of the 8088 can keep processing while DRAM refresh is occurring, unless the EU needs to access memory. Consequently, DRAM refresh can slow code performance anywhere from 0 percent to 5.56 percent (and actually a bit more, as we'll see shortly), depending on the extent to which DRAM refresh occupies cycles during which the 8088 would otherwise be accessing memory.


Figure 4.5
  The PC bus dynamic RAM (DRAM) refresh. +
-->Figure 4.5  The PC bus dynamic RAM (DRAM) refresh.


@@ -68,7 +68,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-07.html b/04-07.html index d84dc27..3493d49 100644 --- a/04-07.html +++ b/04-07.html @@ -24,7 +24,7 @@ - +
@@ -37,7 +37,7 @@


-

The Impact of DRAM Refresh

+

The Impact of DRAM Refresh

Let’s look at examples from opposite ends of the spectrum in terms of the impact of DRAM refresh on code performance. First, consider the series of MUL instructions in Listing 4.9. Since a 16-bit MUL on the 8088 executes in between 118 and 133 cycles and is only 2 bytes long, there should be plenty of time for the prefetch queue to fill after each instruction, even after DRAM refresh has taken its slice of memory access time. Consequently, the prefetch queue should be able to keep the Execution Unit well-supplied with instruction bytes at all times. Since Listing 4.9 uses no memory operands, the Execution Unit should never have to wait for data from memory, and DRAM refresh should have no impact on performance. (Remember that the Execution Unit can operate normally during DRAM refreshes so long as it doesn’t need to request a memory access from the Bus Interface Unit.)

LISTING 4.9 LST4-9.ASM

@@ -74,13 +74,13 @@

Since 4 cycles are required to read each instruction byte, we’d expect each SHR to execute in 8 cycles, or 1.676 µs, if there were no DRAM refresh. In fact, each SHR in Listing 4.10 executes in 1.81 µs, indicating that DRAM refresh is taking 7.4 percent of the program’s execution time. That’s nearly 2 percent more than our worst-case estimate of the loss to DRAM refresh overhead! In fact, the result indicates that DRAM refresh is stealing not 4, but 5.33 cycles out of every 72 cycles. How can this be?

The answer is that a given DRAM refresh can actually hold up CPU memory accesses for as many as 6 cycles, depending on the timing of the DRAM refresh’s DMA request relative to the 8088’s internal instruction execution state. When the code in Listing 4.10 runs, each DRAM refresh holds up the CPU for either 5 or 6 cycles, depending on where the 8088 is in executing the current SHR instruction when the refresh request occurs. Now we see that things can get even worse than we thought: DRAM refresh can steal as much as 8.33 percent of available memory access time—6 out of every 72 cycles—from the 8088.

Which of the two cases we’ve examined reflects reality? While either case can happen, the latter case—significant performance reduction, ranging as high as 8.33 percent—is far more likely to occur. This is especially true for high-performance assembly code, which uses fast instructions that tend to cause non-stop instruction fetching.

-

What to Do About the DRAM Refresh Cycle-Eater?

+

What to Do About the DRAM Refresh Cycle-Eater?

Hmmm. When we discovered the prefetch queue cycle-eater, we learned to use short instructions. When we discovered the 8-bit bus cycle-eater, we learned to use byte-sized memory operands whenever possible, and to keep word-sized variables in registers. What can we do to work around the DRAM refresh cycle-eater?

Nothing.

As I’ve said before, DRAM refresh is an act of God. DRAM refresh is a fundamental, unchanging part of the PC’s operation, and there’s nothing you or I can do about it. If refresh were any less frequent, the reliability of the PC would be compromised, so tinkering with either timer 1 or DMA channel 0 to reduce DRAM refresh overhead is out. Nor is there any way to structure code to minimize the impact of DRAM refresh. Sure, some instructions are affected less by DRAM refresh than others, but how many multiplies and divides in a row can you really use? I suppose that code could conceivably be structured to leave a free memory access every 72 cycles, so DRAM refresh wouldn’t have any effect. In the old days when code size was measured in bytes, not K bytes, and processors were less powerful—and complex—programmers did in fact use similar tricks to eke every last bit of performance from their code. When programming the PC, however, the prefetch queue cycle-eater would make such careful code synchronization a difficult task indeed, and any modest performance improvement that did result could never justify the increase in programming complexity and the limits on creative programming that such an approach would entail. Besides, all that effort goes to waste on faster 8088s, 286s, and other computers with different execution speeds and refresh characteristics. There’s no way around it: Useful code accesses memory frequently and at irregular intervals, and over the long haul DRAM refresh always exacts its price.

If you’re still harboring thoughts of reducing the overhead of DRAM refresh, consider this. Instructions that tend not to suffer very much from DRAM refresh are those that have a high ratio of execution time to instruction fetch time, and those aren’t the fastest instructions of the PC. It certainly wouldn’t make sense to use slower instructions just to reduce DRAM refresh overhead, for it’s total execution time—DRAM refresh, instruction fetching, and all—that matters.

The important thing to understand about DRAM refresh is that it generally slows your code down, and that the extent of that performance reduction can vary considerably and unpredictably, depending on how the DRAM refreshes interact with your code’s pattern of memory accesses. When you use the Zen timer and get a fractional cycle count for the execution time of an instruction, that’s often the DRAM refresh cycle-eater at work. (The display adapter cycleis another possible culprit, and, on 386s and later processors, cache misses and pipeline execution hazards produce this sort of effect as well.) Whenever you get two timing results that differ less or more than they seemingly should, that’s usually DRAM refresh too. Thanks to DRAM refresh, variations of up to 8.33 percent in PC code performance are par for the course.

-

Wait States

+

Wait States

Wait states are cycles during which a bus access by the CPU to a device on the PC’s bus is temporarily halted by that device while the device gets ready to complete the read or write. Wait states are well and truly the lowest level of code performance. Everything we have discussed (and will discuss)—even DMA accesses—can be affected by wait states.


@@ -95,7 +95,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-08.html b/04-08.html index 34d3cc1..3b2b18f 100644 --- a/04-08.html +++ b/04-08.html @@ -24,7 +24,7 @@ - +
@@ -42,23 +42,23 @@

By understanding the circumstances in which wait states can occur, you can avoid them when possible. Even when it’s not possible to work around wait states, it’s still to your advantage to understand how they can cause your code to run more slowly.

First, let’s learn a bit more about wait states by contrast with DRAM refresh. Unlike DRAM refresh, wait states do not occur on any regularly scheduled basis, and are of no particular duration. Wait states can only occur when an instruction performs a memory or I/O read or write. Both the presence of wait states and the number of wait states inserted on any given bus access are entirely controlled by the device being accessed. When it comes to wait states, the CPU is passive, merely accepting whatever wait states the accessed device chooses to insert during the course of the access. All of this makes perfect sense given that the whole point of the wait state mechanism is to allow a device to stretch out any access to itself for however much time it needs to perform the access.


Figure 4.6
  Video wait states inserted by the display adapter. +
-->Figure 4.6  Video wait states inserted by the display adapter.

As with DRAM refresh, wait states don’t stop the 8088 completely. The Execution Unit can continue processing while wait states are inserted, so long as the EU doesn’t need to perform a bus access. However, in the PC, wait states most often occur when an instruction accesses a memory operand, so in fact the Execution Unit usually is stopped by wait states. (Instruction fetches rarely wait in an 8088-based PC because system memory is zero-wait-state. AT-class memory systems routinely insert 1 or more wait states, however.)

As it turns out, wait states pose a serious problem in just one area in the PC. While any adapter can insert wait states, in the PC only display adapters do so to the extent that performance is seriously affected.

-

The Display Adapter Cycle-Eater

+

The Display Adapter Cycle-Eater

Display adapters must serve two masters, and that creates a fundamental performance problem. Master #1 is the circuitry that drives the display screen. This circuitry must constantly read display memory in order to obtain the information used to draw the characters or dots displayed on the screen. Since the screen must be redrawn between 50 and 70 times per second, and since each redraw of the screen can require as many as 36,000 reads of display memory (more in Super VGA modes), master #1 is a demanding master indeed. No matter how demanding master #1 gets, however, its needs must always be met—otherwise the quality of the picture on the screen would suffer.

Master #2 is the CPU, which reads from and writes to display memory in order to manipulate the bytes that the video circuitry reads to form the picture on the screen. Master #2 is less important than master #1, since the CPU affects display quality only indirectly. In other words, if the video circuitry has to wait for display memory accesses, the picture will develop holes, snow, and the like, but if the CPU has to wait for display memory accesses, the program will just run a bit slower—no big deal.

It matters a great deal which master is more important, for while both the CPU and the video circuitry must gain access to display memory, only one of the two masters can read or write display memory at any one time. Potential conflicts are resolved by flat-out guaranteeing the video circuitry however many accesses to display memory it needs, with the CPU waiting for whatever display memory accesses are left over.

It turns out that the 8088 CPU has to do a lot of waiting, for three reasons. First, the video circuitry can take as much as about 90 percent of the available display memory access time, as shown in Figure 4.7, leaving as little as about 10 percent of all display memory accesses for the 8088. (These percentages vary considerably among the many EGA and VGA clones.)


Figure 4.7
  Allocation of display memory access. +
-->Figure 4.7  Allocation of display memory access.

Second, because the displayed dots (or pixels, short for “picture elements”) must be drawn on the screen at a constant speed, many display adapters provide memory accesses only at fixed intervals. As a result, time can be lost while the 8088 synchronizes with the start of the next display adapter memory access, even if the video circuitry isn’t accessing display memory at that time, as shown in Figure 4.8.

Finally, the time it takes a display adapter to complete a memory access is related to the speed of the clock which generates pixels on the screen rather than to the memory access speed of the 8088. Consequently, the time taken for display memory to complete an 8088 read or write access is often longer than the time taken for system memory to complete an access, even if the 8088 lucks into hitting a free display memory access just as it becomes available, again as shown in Figure 4.8. Any or all of the three factors I’ve described can result in wait states, slowing the 8088 and creating the display adapter cycle.


Figure 4.8
  Display memory access slots. +
-->Figure 4.8  Display memory access slots.

If some of this is Greek to you, don’t worry. The important point is that display memory is not very fast compared to normal system memory. How slow is it? Incredibly slow. Remember how slow IBM’s ill-fated PCjrwas? In case you’ve forgotten, I’ll refresh your memory: The PCjrwas at best only half as fast as the PC. The PCjr had an 8088 running at 4.77 MHz, just like the PC—why do you suppose it was so much slower? I’ll tell you why: All the memory in the PCjr was display memory.

Enough said. All the memory in the PC is not display memory, however, and unless you’re thickheaded enough to put code in display memory, the PC isn’t going to run as slowly as a PCjr. (Putting code or other non-video data in unused areas of display memory sounds like a neat idea—until you consider the effect on instruction prefetching of cutting the 8088’s already-poor memory access performance in half. Running your code from display memory is sort of like running on a hypothetical 8084—an 8086 with a 4-bit bus. Not recommended!) Given that your code and data reside in normal system memory below the 640K mark, how great an impact does the display adapter cycle-eater have on performance?


@@ -74,7 +74,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-09.html b/04-09.html index b6a64d7..903342f 100644 --- a/04-09.html +++ b/04-09.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


The answer varies considerably depending on what display adapter and what display mode we’re talking about. The display adapter cycle-eater is worst with the Enhanced Graphics Adapter (EGA) and the original Video Graphics Array (VGA). (Many VGAs, especially newer ones, insert many fewer wait states than IBM’s original VGA. On the other hand, Super VGAs have more bytes of display memory to be accessed in high-resolution mode.) While the Color/Graphics Adapter (CGA), Monochrome Display Adapter (MDA), and Hercules Graphics Card (HGC) all suffer from the display adapter cycle-eater as well, they suffer to a lesser degree. Since the VGA represents the base standard for PC graphics now and for the foreseeable future, and since it is the hardest graphics adapter to wring performance from, we’ll restrict our discussion to the VGA (and its close relative, the EGA) for the remainder of this chapter.

-

The Impact of the Display Adapter Cycle-Eater

+

The Impact of the Display Adapter Cycle-Eater

Even on the EGA and VGA, the effect of the display adapter cycle-eater depends on the display mode selected. In text mode, the display adapter cycle-eater is rarely a major factor. It’s not that the cycle-eater isn’t present; however, a mere 4,000 bytes control the entire text mode display, and even with the display adapter cycle-eater it just doesn’t take that long to manipulate 4,000 bytes. Even if the display adapter cycle-eater were to cause the 8088 to take as much as 5µs per display memory access—more than five times normal—it would still take only 4,000x 2x 5µs, or 40 µs, to read and write every byte of display memory. That’s a lot of time as measured in 8088 cycles, but it’s less than the blink of an eye in human time, and video performance only matters in human time. After all, the whole point of drawing graphics is to convey visual information, and if that information can be presented faster than the eye can see, that is by definition fast enough.

That’s not to say that the display adapter cycle-eater can’t matter in text mode. In Chapter 3, I recounted the story of a debate among letter-writers to a magazine about exactly how quickly characters could be written to display memory without causing snow. The writers carefully added up Intel’s instruction cycle times to see how many writes to display memory they could squeeze into a single horizontal retrace interval. (On a CGA, it’s only during the short horizontal retrace interval and the longer vertical retrace interval that display memory can be accessed in 80-column text mode without causing snow.) Of course, now we know that their cardinal sin was to ignore the prefetch queue; even if there were no wait states, their calculations would have been overly optimistic. There are display memory wait states as well, however, so the calculations were not just optimistic but wildly optimistic.

@@ -116,7 +116,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/04-10.html b/04-10.html index 334d321..8287cf6 100644 --- a/04-10.html +++ b/04-10.html @@ -24,7 +24,7 @@ - +
@@ -42,7 +42,7 @@

In addition, code that accesses display memory infrequently tends to suffer only about half of the maximum display memory wait states, because on average such code will access display memory halfway between one available display memory access slot and the next. As a result, code that accesses display memory less intensively than the code in Listing 4.11 will on average lose 4 or 5 rather than 8-plus cycles to the display adapter cycle-eater on each memory access.

Nonetheless, the display adapter cycle-eater always takes its toll on graphics code. Interestingly, that toll becomes much higher on ATs and 80386 machines because while those computers can execute many more instructions per microsecond than can the 8088-based PC, it takes just as long to access display memory on those computers as on the 8088-based PC. Remember, the limited speed of access to a graphics adapter is an inherent characteristic of the adapter, so the fastest computer around can’t access display memory one iota faster than the adapter will allow.

-

What to Do about the Display Adapter Cycle-Eater?

+

What to Do about the Display Adapter Cycle-Eater?

What can we do about the display adapter cycle-eater? Well, we can minimize display memory accesses whenever possible. In particular, we can try to avoid read/modify/write display memory operations of the sort used to mask individual pixels and clip images. Why? Because read/modify/write operations require two display memory accesses (one read and one write) each time display memory is manipulated. Instead, we should try to use writes of the sort that set all the pixels in a given byte of display memory at once, since such writes don’t require accompanying read accesses. The key here is that only half as many display memory accesses are required to write a byte to display memory as are required to read a byte from display memory, mask part of it off and alter the rest, and write the byte back to display memory. Half as many display memory accesses means half as many display memory wait states.

Moreover, 486s and Pentiums, as well as recent Super VGAs, employ write-caching schemes that make display memory writes considerably faster than display memory reads. @@ -51,7 +51,7 @@

Another principle for display adapter programming on the 8088 is to perform multiple accesses to display memory very rapidly, in order to make use of as many of the scarce accesses to display memory as possible. This is especially important when many large images need to be drawn quickly, since only by using virtually every available display memory access can many bytes be written to display memory in a short period of time. Repeated string instructions are ideal for making maximum use of display memory accesses; of course, repeated string instructions can only be used on whole bytes, so this is another point in favor of modifying display memory a byte at a time. (On faster processors, however, display memory is so slow that it often pays to do several instructions worth of work between display memory accesses, to take advantage of cycles that would otherwise be wasted on the wait states.)

It would be handy to explore the display adapter cycle-eater issue in depth, with lots of example code and execution timings, but alas, I don’t have the space for that right now. For the time being, all you really need to know about the display adapter cycle-eater is that on the 8088 you can lose more than 8 cycles of execution time on each access to display memory. For intensive access to display memory, the loss really can be as high as 8cycles (and up to 50, 100, or even more on 486s and Pentiums paired with slow VGAs), while for average graphics code the loss is closer to 4 cycles; in either case, the impact on performance is significant. There is only one way to discover just how significant the impact of the display adapter cycle-eater is for any particular graphics code, and that is of course to measure the performance of that code.

-

Cycle-Eaters: A Summary

+

Cycle-Eaters: A Summary

We’ve covered a great deal of sophisticated material in this chapter, so don’t feel bad if you haven’t understood everything you’ve read; it will all become clear from further reading, especially once you study, time, and tune code that you have written yourself. What’s really important is that you come away from this chapter understanding that on the 8088:

    @@ -62,7 +62,7 @@

This basic knowledge about cycle-eaters puts you in a good position to understand the results reported by the Zen timer, and that means that you’re well on your way to writing high-performance assembler code.

-

What Does It All Mean?

+

What Does It All Mean?

There you have it: life under the programming interface. It’s not a particularly pretty picture for the inhabitants of that strange realm where hardware and software meet are little-known cycle-eaters that sap the speed from your unsuspecting code. Still, some of those cycle-eaters can be minimized by keeping instructions short, using the registers, using byte-sized memory operands, and accessing display memory as little as possible. None of the cycle-eaters can be eliminated, and dynamic RAM refresh can scarcely be addressed at all; still, aren’t you better off knowing how fast your code really runs—and why—than you were reading the official execution times and guessing? And while specific cycle-eaters vary in importance on later x86-family processors, with some cycle-eaters vanishing altogether and new ones appearing, the concept that understanding these obscure gremlins is a key to performance remains unchanged, as we’ll see again and again in later chapters.


@@ -76,7 +76,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/05-01.html b/05-01.html index 03f003e..3784a97 100644 --- a/05-01.html +++ b/05-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 5
Crossing the Border -

-

Searching Files with Restartable Blocks

+

Chapter 5
Crossing the Border

+

Searching Files with Restartable Blocks

We just moved. Those three little words should strike terror into the heart of anyone who owns more than a sleeping bag and a toothbrush. Our last move was the usual zoo—and then some. Because the distance from the old house to the new was only five miles, we used cars to move everything smaller than a washing machine. We have a sizable household—cats, dogs, kids, com, you name it—so the moving process took a number of car trips. A large number—33, to be exact. I personally spent about 15 hours just driving back and forth between the two houses. The move took days to complete.

Never again.

You’re probably wondering two things: What does this have to do with high-performance programming, and why on earth didn’t I rent a truck and get the move over in one or two trips, saving hours of driving? As it happens, the second question answers the first. I didn’t rent a truck because it seemed easier and cheaper to use cars—no big truck to drive, no rentals, spread the work out more manageably, and so on.

@@ -50,13 +49,13 @@

And with that, let’s look at a fairly complex application of restartable blocks.

-

Searching for Text

+

Searching for Text

The application we’re going to examine searches a file for a specified string. We’ll develop a program that will search the file specified on the command line for a string (also specified on the comline), then report whether the string was found or not. (Because the searched-for string is obtained via argv, it can’t contain any whitespace characters.)

This is a very limited subset of what search utilities such as grep can do, and isn’t really intended to be a generally useful application; the purpose is to provide insight into restartable blocks in particular and optimization in general in the course of developing a search engine. That search engine will, however, be easy to plug into any program, and there’s nothing preventing you from using it in a more fruitful context, like searching through a user-selectable file set.

The first point to address in designing our program involves the appropriate text-search approach to use. Literally dozens of workable ways exist to search a file. We can immediately discard all approaches that involve reading any byte of the file more than once, because disk access time is orders of magnitude slower than any data handling performed by our own code. Based on our experience in Chapter 1, we can also discard all approaches that get bytes either one at a time or in small sets from DOS. We want to read big “buffers-full” of bytes at a pop from the searched file, and the bigger the buffer the better—in order to minimize DOS’s overhead. A good rough cut is a buffer that will be between 16K and 64K, depending on the exact search approach, 64K being the maximum size because near pointers make for superior performance.

So we know we want to work with a large buffer, filling it as infrequently as possible. Now we have to figure out how to search through a file by loading it into that large buffer in chunks. To accomplish this, we have to know how we want to do our searching, and that’s not immediately obvious. Where do we begin?

Well, it might be instructive to consider how we would search if our search involved only one buffer, already resident in memory. In other words, suppose we don’t have to bother with file handling at all, and further suppose that we don’t have to deal with searching through multiple blocks. After all, that’s a good description of the all-important inner loop of our searching program, where the program will spend virtually all of its time (aside from the unavoidable disk access overhead).

-

Avoiding the String Trap

+

Avoiding the String Trap

The easiest approach would be to use a C/C++ library function. The closest match to what we need is strstr(), which searches one string for the first occurrence of a second string. However, while strstr() would work, it isn’t ideal for our purposes. The problem is this: Where we want to search a fixed-length buffer for the first occurrence of a string, strstr() searches a string for the first occurrence of another string.


@@ -70,7 +69,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/05-02.html b/05-02.html index 668f126..ca01a6e 100644 --- a/05-02.html +++ b/05-02.html @@ -24,7 +24,7 @@ - +
@@ -39,23 +39,23 @@

We could put a zero byte at the end of our buffer to allow strstr() to work, but why bother? The strstr() function must spend time either checking for the end of the string being searched or determining the length of that string—wasted effort given that we already know exactly how long our search buffer is. Even if a given strstr() implementation is well-written, its performance will suffer, at least for our application, from unnecessary overhead.

This illustrates why you shouldn’t think of C/C++ library functions as black boxes; understand what they do and try to figure out how they do it, and relate that to their performance in the context you’re interested in.
-

Brute-Force Techniques

+

Brute-Force Techniques

Given that no C/C++ library function meets our needs precisely, an obvious alternative approach is the brute-force technique that uses memcmp() to compare every potential matching location in the buffer to the string we’re searching for, as illustrated in Figure 5.1.

By the way, we could, of course, use our own code, working with pointers in a loop, to perform the comparison in place of memcmp(). But memcmp() will almost certainly use the very fast REPZ CMPS instruction. However, never assume! It wouldn’t hurt to use a debugger to check out the actual machine-code implementation of memcmp() from your compiler. If necessary, you could always write your own assembly language implementation of memcmp().


Figure 5.1
  The brute-force searching technique. +
-->Figure 5.1  The brute-force searching technique.

Invoking memcmp() for each potential match location works, but entails considerable overhead. Each comparison requires that parameters be pushed and that a call to and return from memcmp() be performed, along with a pass through the comparison loop. Surely there’s a better way!

Indeed there is. We can eliminate most calls to memcmp() by performing a simple test on each potential match location that will reject most such locations right off the bat. We’ll just check whether the first character of the potentially matching buffer location matches the first character of the string we’re searching for. We could make this check by using a pointer in a loop to scan the buffer for the next match for the first character, stopping to check for a match with the rest of the string only when the first character matches, as shown in Figure 5.2.

-

Using memchr()

+

Using memchr()

There’s yet a better way to implement this approach, however. Use the memchr() function, which does nothing more or less than find the next occurrence of a specified character in a fixed-length buffer (presumably by using the extremely efficient REPNZ SCASB instruction, although again it wouldn’t hurt to check). By using memchr() to scan for potential matches that can then be fully tested with memcmp(), we can build a highly efficient search engine that takes good advantage of the information we have about the buffer being searched and the string we’re searching for. Our engine also relies heavily on repeated string instructions, assuming that the memchr() and memcmp() library functions are properly coded.


Figure 5.2
  The faster string-searching technique. +
-->Figure 5.2  The faster string-searching technique.

We’re going to go with the this approach in our file-searching program; the only trick lies in deciding how to integrate this approach with restartable blocks in order to search through files larger than our buffer. This certainly isn’t the fastest-possible searching algorithm; as one example, the Boyer-Moore algorithm, which cleverly eliminates many buffer locations as potential matches in the process of checking preceding locations, can be considerably faster. However, the Boyer-Moore algorithm is quite complex to understand and implement, and would distract us from our main focus, restartable blocks, so we’ll save it for a later chapter (Chapter 14, to be precise). Besides, I suspect you’ll find the approach we’ll use to be fast enough for most purposes.

Now that we’ve selected a searching approach, let’s integrate it with file handling and searching through multiple blocks. In other words, let’s make it restartable.

-

Making a Search Restartable

+

Making a Search Restartable

As it happens, there’s no great trick to putting the pieces of this search program together. Basically, we’ll read in a buffer of data (we’ll work with 16K at a time to avoid signed overflow problems with integers), search it for a match with the memchr()/memcmp() engine described, and exit with a “string found” response if the desired string is found.

Otherwise, we’ll load in another buffer full of data from the file, search it, and so on. The only trick lies in handling potentially matching sequences in the file that start in one buffer and end in the next—that is, sequences that span buffers. We’ll handle this by copying the unchecked bytes at the end of one buffer to the start of the next and reading that many fewer bytes the next time we fill the buffer.

The exact number of bytes to be copied from the end of one buffer to the start of the next is the length of the searched-for string minus 1, since that’s how many bytes at the end of the buffer can’t be checked as possible matches (because the check would run off the end of the buffer).

@@ -73,7 +73,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/05-03.html b/05-03.html index 54252ec..fb8de99 100644 --- a/05-03.html +++ b/05-03.html @@ -24,7 +24,7 @@ - +
@@ -219,7 +219,7 @@ main(int argc, char *argv[]) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/05-04.html b/05-04.html index bf9c7cc..31af143 100644 --- a/05-04.html +++ b/05-04.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

Interpreting Where the Cycles Go

+

Interpreting Where the Cycles Go

To boost the overall performance of Listing 5.1, I would normally convert SearchForString() to assembly language at this point. However, I’m not going to do that, and the reason is as important a lesson as any discussion of optimized assembly code is likely to be. Take a moment to examine some interesting performance aspects of the C implementation, and all should become much clearer.

As you’ll recall from Chapter 1, one of the important rules for optimization involves knowing when optimization is worth bothering with at all. Another rule involves understanding where most of a program’s execution time is going. That’s more true for Listing 5.1 than you might think.

When Listing 5.1 is run on a 1 MB assembly source file, it takes about three seconds to find the string “xxxend” (which is at the end of the file) on a 20 MHz 386 machine, with the entire file in a disk cache. If BLOCK_SIZE is trimmed from 16K to 4K, execution time does not increase perceptibly! At 2K, the program slows slightly; it’s not until the block size shrinks to 64 bytes that execution time becomes approximately double that of the 16K buffer.

@@ -44,7 +44,7 @@

When I replaced the read() function call in Listing 5.1 with code that simply fools the program into thinking that a 1 MB file is being read, the program ran almost instantaneously—in less than 1/2 second, even when the searched-for string wasn’t anywhere to be found. By contrast, Listing 5.1 requires three seconds to run even when searching for a single character that isn’t found anywhere in the file, the case in which a single call to memchr() (and thus a single REPNZ SCASB) can eliminate an entire block at a time.

All in all, the time required for DOS disk access calls is taking up at least 80 percent of execution time, and search time is less than 20 percent of overall execution time. In fact, search time is probably a good deal less than 20 percent of the total, given that the overhead of loading the program, running through the C startup code, opening the file, executing printf(), and exiting the program and returning to the DOS shell are also included in my timings. Given which, it should be apparent why converting to assembly language isn’t worth the trouble—the best we could do by speeding up the search is a 10 percent or so improvement, and that would require more than doubling the performance of code that already uses repeated string instructions to do most of the work.

Not likely.

-

Knowing When Assembly Is Pointless

+

Knowing When Assembly Is Pointless

So that’s why we’re not going to go to assembly language in this example—which is not to say it would never be worth converting the search engine in Listing 5.1 to assembly.

If, for example, your application will typically search buffers in which the first character of the search string occurs frequently as might be the case when searching a text buffer for a string starting with the space character an assembly implementation might be several times faster. Why? Because assembly code can switch from REPNZ SCASB to match the first character to REPZ CMPS to check the remaining characters in just a few instructions.

@@ -61,7 +61,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/05-05.html b/05-05.html index 5f16157..84924b2 100644 --- a/05-05.html +++ b/05-05.html @@ -24,7 +24,7 @@ - +
@@ -44,7 +44,7 @@

By the way, don’t think that just because very large block sizes don’t much improve performance, it wasn’t worth using restartable blocks in Listing 5.1. Listing 5.1 runs more than three times more slowly with a block size of 32 bytes than with a block size of 4K, and any byte-by-byte approach would surely be slower still, due to the overhead of repeated calls to DOS and/or the C stream I/O library.

Restartable blocks do minimize the overhead of DOS file-access calls in Listing 5.1; it’s just that there’s no way to reduce that overhead to the point where it becomes worth attempting to further improve the performance of our relatively efficient search engine. Although the search engine is by no means fully optimized, it’s nonetheless as fast as there’s any reason for it to be, given the balance of performance among the components of this program.

-

Always Look Where Execution Is Going

+

Always Look Where Execution Is Going

I’ve explained two important lessons: Know when it’s worth optimizing further, and use restartable blocks to process large data sets as a series of blocks, with each block handled at high speed. The first lesson is less obvious than it seems.

When I set out to write this chapter, I fully intended to write an assembly language version of Listing 5.1, and I expected the assembly version to be much faster. When I actually looked at where execution time was going (which I did by modifying the program to remove the calls to the read() function, but a code profiler could be used to do the same thing much more easily), I found that the best code in the world wouldn’t make much difference.

@@ -66,7 +66,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/06-01.html b/06-01.html index 3518604..d5d8dc1 100644 --- a/06-01.html +++ b/06-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 6
Looking Past Face Value -

-

How Machine Instructions May Do More Than You Think

+

Chapter 6
Looking Past Face Value

+

How Machine Instructions May Do More Than You Think

I first met Jeff Duntemann at an authors’ dinner hosted by PC Tech Journal at Fall Comdex, back in 1985. Jeff was already reasonably well-known as a computer editor and writer, although not as famous as Complete Turbo Pascal, editions 1 through 672 (or thereabouts), TURBO TECHNIX, and PC TECHNIQUES would soon make him. I was fortunate enough to be seated next to Jeff at the dinner table, and, not surprisingly, our often animated conversation revolved around computers, computer writing, and more computers (not necessarily in that order).

Although I was making a living at computer work and enjoying it at the time, I nonetheless harbored vague ambitions of being a science-fiction writer when I grew up. (I have since realized that this hardly puts me in elite company, especially in the computer world, where it seems that every other person has told me they plan to write science fiction “someday.” Given that probably fewer than 500—I’m guessing here—original science fiction and fantasy short stories, and perhaps a few more novels than that, are published each year in this country, I see a few mid-life crises coming.)

At any rate, I had accumulated a small collection of rejection slips, and fancied myself something of an old hand in the field. At the end of the dinner, as the other writers complained half-seriously about how little they were paid for writing for Tech Journal, I leaned over to Jeff and whispered, “You know, the pay isn’t so bad here. You should see what they pay for science fiction—even to the guys who win awards!”

@@ -51,7 +50,7 @@

To produce the best code, you must decide precisely what you need to accomplish, then put together the sequence of instructions that accomplishes that end most efficiently, regardless of what the instructions are usually used for. That’s why optimization for the PC is an art, and it’s why the best assembly language for the x86 family will almost always handily outperform compiled code. With that in mind, let’s look past face value—and while we’re at it, I’ll toss in a few examples of not judging a book by its cover.

The point to all this: You must come to regard the x86 family instructions for what they do, not what you’re used to thinking they do. Yes, SHL shifts a pattern left—but a look-up table can do the same thing, and can often do it faster. ADD can indeed add two operands, but it can’t put the result in a third register; LEA can. The instruction set is your raw material for writing high-performance code. By limiting yourself to thinking only in certain well-established ways about the various instructions, you’re putting yourself at a substantial disadvantage every time you sit down to program.

In short, the x86 family can do much more than you think—if you’ll use everything it has to offer. Give it a shot!

-

Memory Addressing and Arithmetic

+

Memory Addressing and Arithmetic

Years ago, I saw a clip on the David Letterman show in which Letterman walked into a store by the name of “Just Lamps” and asked, “So what do you sell here?”

“Lamps,” he was told. “Just lamps. Can’t you read?”

@@ -87,7 +86,7 @@ mov al,[bx+si]
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/06-02.html b/06-02.html index cc490b2..ffc18b4 100644 --- a/06-02.html +++ b/06-02.html @@ -24,7 +24,7 @@ - +
@@ -49,7 +49,7 @@ LoopTop:

Here, MOV AL,[BX] is two cycles faster than MOV AL,[BX+SI].

On a 286 or 386, however, the balance shifts. MOV AL,[BX+SI] takes no longer than MOV AL,[BX] on these processors because effective address calculations generally take no extra time at all. (According to the MASM manual, one extra clock is required if three memory addressing components, as in MOV AL,[BX+SI+1], are used. I have not been able to confirm this from Intel publications, but then I haven’t looked all that hard.) If you’re optimizing for the 286 or 386, then, you can take advantage of the processor’s ability to perform arithmetic as part of memory address calculations without taking a performance hit.

The 486 is an odd case, in which the use of an index register or the use of a base register that’s the destination of the previous instruction may slow things down, so it is generally but not always better to perform the addition outside the loop on the 486. All memory addressing calculations are free on the Pentium, however. I’ll discuss 486 performance issues in Chapters 12 and 13, and the Pentium in Chapters 19 through 21.

-

Math via Memory Addressing

+

Math via Memory Addressing

You’re probably not particularly wowed to hear that you can use addressing modes to perform memory addressing arithmetic that would otherwise have to be performed with separate arithmetic instructions. You may, however, be a tad more interested to hear that you can also use addressing modes to perform arithmetic that has nothing to do with memory addressing, and with a couple of advantages over arithmetic instructions, at that.

How?

@@ -87,13 +87,13 @@ lea di,[si+2]

Mind you, the only components LEA can add are BX or BP, SI or DI, and a constant displacement, so it’s not going to replace ADD most of the time. Also, LEA is considerably slower than ADD on an 8088, although it is just as fast as ADD on a 286 or 386 when fewer than three memory addressing components are used. LEA is 1 cycle slower than ADD on a 486 if the sum of two registers is used to point to memory, but no slower than ADD on a Pentium. On both a 486 and Pentium, LEA can also be slowed down by addressing interlocks.


Figure 6.1
  Operation of ADD Reg,Reg vs. LEA Reg,{Addr}. +
-->Figure 6.1  Operation of ADD Reg,Reg vs. LEA Reg,{Addr}.

-

The Wonders of LEA on the 386

+

The Wonders of LEA on the 386

LEA really comes into its own as a “super-ADD” instruction on the 386, 486, and Pentium, where it can take advantage of the enhanced memory addressing modes of those processors. (The 486 and Pentium offer the same modes as the 386, so I’ll refer only to the 386 from now on.) The 386 can do two very interesting things: It can use any 32-bit register (EAX, EBX, and so on) as the memory addressing base register and/or the memory addressing index register, and it can multiply any 32-bit register used as an index by two, four, or eight in the process of calculating a memory address, as shown in Figure 6.2. Let’s see what that’s good for.

Well, the obvious advantage is that any two 32-bit registers, or any 32-bit register and any constant, or any two 32-bit registers and any constant, can be added together, with the result stored in any register. This makes the 32-bit LEA much more generally useful than the standard 16-bit LEA in the role of an ADD with an independent destination.


Figure 6.2
  Operation of the 32-bit LEA reg,[Addr]. +
-->Figure 6.2  Operation of the 32-bit LEA reg,[Addr].

But what else can LEA do on a 386, besides add?

It can multiply any register used as an index. LEA can multiply only by the power-of-two values 2, 4, or 8, but that’s useful more often than you might imagine, especially when dealing with pointers into tables. Besides, multiplying by 2, 4, or 8 amounts to a left shift of 1, 2, or 3 bits, so we can now add up to two 32-bit registers and a constant, and shift (or multiply) one of the registers to some extent—all with a single instruction. For example,

@@ -114,7 +114,7 @@ add edi,offset TableBase

when pointing to an entry in a doubly indexed table.

-

Multiplication with LEA Using Non-Powers of Two

+

Multiplication with LEA Using Non-Powers of Two

Are you impressed yet with all that LEA can do on the 386? Believe it or not, one more feature still awaits us. LEA can actually perform a fast multiply of a 32-bit register by some values other than powers of two. You see, the same 32-bit register can be both base and index on the 386, and can be scaled as the index while being used unchanged as the base. That means that you can, for example, multiply EBX by 5 with:

@@ -147,7 +147,7 @@ add  ebx,edx
 
 
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/07-01.html b/07-01.html index 5c7cd3a..e921c46 100644 --- a/07-01.html +++ b/07-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 7
Local Optimization -

-

Optimizing Halfway between Algorithms and Cycle Counting

+

Chapter 7
Local Optimization

+

Optimizing Halfway between Algorithms and Cycle Counting

You might not think it, but there’s much to learn about performance programming from the Great Buffalo Sauna Fiasco. To wit:

The scene is Buffalo, New York, in the dead of winter, with the snow piled several feet deep. Four college students, living in typical student housing, are frozen to the bone. The third floor of their house, uninsulated and so cold that it’s uninhabitable, has an ancient bathroom. One fabulously cold day, inspiration strikes:

@@ -54,7 +53,7 @@

So, drawing fortitude from the knowledge that our quest is a pure and worthy one, let’s resume our exploration of assembly language instructions with hidden talents and instructions with well-known talents that are less than they appear to be. In the process, we’ll come to see that there is another, very important optimization level between the algorithm/design level and the cycle-counting/individual instruction level. I’ll call this middle level local optimization; it involves focusing on optimizing sequences of instructions rather than individual instructions, all with an eye to implementing designs as efficiently as possible given the capabilities of the x86 family instruction set.

And yes, in case you’re wondering, the above story is indeed true. Was I there? Let me put it this way: If I were, I’d never admit it!

-

When LOOP Is a Bad Idea

+

When LOOP Is a Bad Idea

Let’s examine first an instruction that is less than it appears to be: LOOP. There’s no mystery about what LOOP does; it decrements CX and branches if CX doesn’t decrement to zero. It’s so beautifully suited to the task of counting down loops that any experienced x86 programmer instinctively stuffs the loop count in CX and reaches for LOOP when setting up a loop. That’s fine—LOOP does, of course, work as advertised—but there is one problem:

On half of the processors in the x86 family, LOOP is slower than DEC CX followed by JNZ. (Granted, DEC CX/JNZ isn’t precisely equivalent to LOOP, because DEC alters the flags and LOOP doesn’t, but in most situations they’re comparable.)
@@ -74,7 +73,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/07-02.html b/07-02.html index 235ce63..d406dbe 100644 --- a/07-02.html +++ b/07-02.html @@ -24,7 +24,7 @@ - +
@@ -51,12 +51,12 @@ jz SkipLoop ;If field is 0, don’t bother

will do just fine and is faster on all processors. Use JCXZ only when the Zero flag isn’t already set to reflect the status of CX.

-

The Lessons of LOOP and JCXZ

+

The Lessons of LOOP and JCXZ

What can we learn from LOOP and JCXZ? First, that a single instruction that is intended to do a complex task is not necessarily faster than several instructions that together do the same thing. Second, that the relative merits of instructions and optimization rules vary to a surprisingly large degree across the x86 family.

In particular, if you’re going to write 386 protected mode code, which will run only on the 386, 486, and Pentium, you’d be well advised to rethink your use of the more esoteric members of the x86 instruction set. LOOP, JCXZ, the various accumulator-specific instructions, and even the string instructions in many circumstances no longer offer the advantages they did on the 8088. Sometimes they’re just not any faster than more general instructions, so they’re not worth going out of your way to use; sometimes, as with LOOP, they’re actually slower, and you’d do well to avoid them altogether in the 386/486 world. Reviewing the instruction cycle times in the MASM or TASM manuals, or looking over the cycle times in Intel’s literature, is a good place to start; published cycle times are closer to actual execution times on the 386 and 486 than on the 8088, and are reasonably reliable indicators of the relative performance levels of x86 instructions.

-

Avoiding LOOPS of Any Stripe

+

Avoiding LOOPS of Any Stripe

Cycle counting and directly substituting instructions (DEC CX/JNZ for LOOP, for example) are techniques that belong at the lowest level of optimization. It’s an important level, but it’s fairly mechanical; once you’ve learned the capabilities and relative performance levels of the various instructions, you should be able to select the best instructions fairly easily. What’s more, this is a task at which compilers excel. What I’m saying is that you shouldn’t get too caught up in counting cycles because that’s a small (albeit important) part of the optimization picture, and not the area in which your greatest advantage lies.

-

Local Optimization

+

Local Optimization

One level at which assembly language programming pays off handsomely is that of local optimization; that is, selecting the best sequence of instructions for a task. The key to local optimization is viewing the 80x86 instruction set as a set of building blocks, each with unique characteristics. Your job is to sequence those blocks so that they perform well. It doesn’t matter what the instructions are intended to do or what their names are; all that matters is what they do.

Our discussion of LOOP versus DEC/JNZ is an excellent example of optimization by cycle counting. It’s worth knowing, but once you’ve learned it, you just routinely use DEC/JNZ at the bottom of loops in 386/486-specific code, and that’s that. Besides, you’ll save at most a few cycles each time, and while that helps a little, it’s not going to make all that much difference.

Now let’s step back for a moment, and with no preconceptions consider what the x86 instruction set can do for us. The bulk of the time with both LOOP and DEC/JNZ is taken up by branching, which just happens to be one of the slowest aspects of every processor in the x86 family, and the rest is taken up by decrementing the count register and checking whether it’s zero. There may be ways to perform those tasks a little faster by selecting different instructions, but they can get only so fast, and branching can’t even get all that fast.

@@ -76,7 +76,7 @@ jz SkipLoop ;If field is 0, don’t bother
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/07-03.html b/07-03.html index 05ae0b3..2124763 100644 --- a/07-03.html +++ b/07-03.html @@ -24,7 +24,7 @@ - +
@@ -131,7 +131,7 @@ SearchMaxLengthendp end Start -

Unrolling Loops

+

Unrolling Loops

Listing 7.2 takes a different tack, unrolling the loop so that four bytes are checked for each LOOP performed. The same instructions are used inside the loop in each listing, but Listing 7.2 is arranged so that three-quarters of the LOOPs are eliminated. Listings 7.1 and 7.2 perform exactly the same task, and they use the same instructions in the loop—the searching algorithm hasn’t changed in any way—but we have sequenced the instructions differently in Listing 7.2, and that makes all the difference.


@@ -145,7 +145,7 @@ SearchMaxLengthendp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/07-04.html b/07-04.html index b42bf1a..6b81b36 100644 --- a/07-04.html +++ b/07-04.html @@ -24,7 +24,7 @@ - +
@@ -185,7 +185,7 @@ SearchMaxLengthendp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/07-05.html b/07-05.html index 2ab203d..dedb998 100644 --- a/07-05.html +++ b/07-05.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

Rotating and Shifting with Tables

+

Rotating and Shifting with Tables

As another example of local optimization, consider the matter of rotating or shifting a mask into position. First, let’s look at the simple task of setting bit N of AX to 1.

The obvious way to do this is to place N in CL, rotate the bit into position, and OR it with AX, as follows:

@@ -81,13 +81,13 @@ BIT_PATTERN=BIT_PATTERN SHL 1
Besides illustrating the advantages of local optimization, this example also shows that it generally pays to precalculate results; this is often done at or before assembly time, but precalculated tables can also be built at run time. This is merely one aspect of a fundamental optimization rule: Move as much work as possible out of your critical code by whatever means necessary.
-

NOT Flips Bits—Not Flags

+

NOT Flips Bits—Not Flags

The NOT instruction flips all the bits in the operand, from 0 to 1 or from 1 to 0. That’s as simple as could be, but NOT nonetheless has a minor but interesting talent: It doesn’t affect the flags. That can be irritating; I once spent a good hour tracking down a bug caused by my unconscious assumption that NOT does set the flags. After all, every other arithmetic and logical instruction sets the flags; why not NOT? Probably because NOT isn’t considered to be an arithmetic or logical instruction at all; rather, it’s a data manipulation instruction, like MOV and the various rotates. (These are RCR, RCL, ROR, and ROL, which affect only the Carry and Overflow flags.) NOT is often used for tasks, such as flipping masks, where there’s no reason to test the state of the result, and in that context it can be handy to keep the flags unmodified for later testing.

Besides, if you want to NOT an operand and set the flags in the process, you can just XOR it with -1. Put another way, the only functional difference between NOT AX and XOR AX,0FFFFH is that XOR modifies the flags and NOT doesn’t.

The x86 instruction set offers many ways to accomplish almost any task. Understanding the subtle distinctions between the instructions—whether and which flags are set, for example—can be critical when you’re trying to optimize a code sequence and you’re running out of registers, or when you’re trying to minimize branching.

-

Incrementing with and without Carry

+

Incrementing with and without Carry

Another case in which there are two slightly different ways to perform a task involves adding 1 to an operand. You can do this with INC, as in INC AX, or you can do it with ADD, as in ADD AX,1. What’s the difference? The obvious difference is that INC is usually a byte or two shorter (the exception being ADD AL,1, which at two bytes is the same length as INC AL), and is faster on some processors. Less obvious, but no less important, is that ADD sets the Carry flag while INC leaves the Carry flag untouched.

Why is that important? Because it allows INC to function as a data pointer manipulation instruction for multi-word arithmetic. You can use INC to advance the pointers in code like that shown in Listing 7.5 without having to do any work to preserve the Carry status from one addition to the next.

LISTING 7.5 L7-5.ASM

@@ -153,7 +153,7 @@ ADC DX,0
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/08-01.html b/08-01.html index 3ea9414..7c7fcb3 100644 --- a/08-01.html +++ b/08-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 8
Speeding Up C with Assembly Language -

-

Jumping Languages When You Know It’ll Help

+

Chapter 8
Speeding Up C with Assembly Language

+

Jumping Languages When You Know It’ll Help

When I was a senior in high school, a pop song called “Seasons in the Sun,” sung by one Terry Jacks, soared up the pop charts and spent, as best I can recall, two straight weeks atop Kasey Kasem’s American Top 40. “Seasons in the Sun” wasn’t a particularly good song, primarily because the lyrics were silly. I’ve never understood why the song was a hit, but, as so often happens with undistinguished but popular music by forgotten one- or two-shot groups (“Don’t Pull Your Love Out on Me Baby,” “Billy Don’t Be a Hero,” et al.), I heard it everywhere for a month or so, then gave it not another thought for 15 years.

Recently, though, I came across a review of a Rhino Records collection of obscure 1970s pop hits. Knowing that Jeff Duntemann is an aficionado of such esoterica (who do you know who owns an album by The Peppermint Trolley Company?), I sent the review to him. He was amused by it and, as we kicked the names of old songs around, “Seasons in the Sun” came up. I expressed my wonderment that a song that really wasn’t very good was such a big hit.

“Well,” said Jeff, “I think it suffered in the translation from the French.”

@@ -48,14 +47,14 @@

Apropos of which, when was the last time you heard of Terry Jacks?

-

Billy, Don’t Be a Compiler

+

Billy, Don’t Be a Compiler

The key to optimizing C programs with assembly language is, as always, writing good assembly language code, but with an added twist. Rule 1 when converting C code to assembly is this: Don’t think like a compiler. That’s more easily said than done, especially when the C code you’re converting is readily available as a model and the assembly code that the compiler generates is available as well. Nevertheless, the principle of not thinking like a compiler is essential, and is, in one form or another, the basis for all that I’ll discuss below.

Before I discuss Rule 1 further, let me mention rule number 0: Only optimize where it matters. The bulk of execution time in any program is spent in a very small portion of the code, and most code beyond that small portion doesn’t have any perceptible impact on performance. Unless you’re supremely concerned with code size (an area in which assembly-only programs can excel), I’d suggest that you write most of your code in C and reserve assembly for the truly critical sections of your code; that’s the formula that I find gives the most bang for the buck.

This is not to say that complete programs shouldn’t be designed with optimized assembly language in mind. As you’ll see shortly, orienting your data structures towards assembly language can be a salubrious endeavor indeed, even if most of your code is in C. When it comes to actually optimizing code and/or converting it to assembly, though, do it only where it matters. Get a profiler—and use it!

Also make it a point to concentrate on refining your program design and algorithmic approach at the conceptual and/or C levels before doing any assembly language optimization.

Assembly language optimization is the final and far from the only step in the optimization chain, and as such should be performed last; converting to assembly too soon can lock in your code before the design is optimal. At the very least, conversion to assembly tends to make future changes and debugging more difficult, slowing you down and limiting your options.
-

Don’t Call Your Functions on Me, Baby

+

Don’t Call Your Functions on Me, Baby

In order to think differently from a compiler, you must understand both what compilers and C programmers tend to do and how that differs from what assembly language does well. In this pursuit, it can be useful to examine the code your compiler generates, either by viewing the code in a debugger or by having the compiler generate an assembly language output file. (The latter is done with /Fa or /Fc in Microsoft C/C++ and -S in Borland C++.)

C programmers tend to modularize their code with lots of function calls. That’s good for readable, reliable, reusable code, and it allows the compiler to optimize better because it can deal with fewer variables and statements in each optimization arena—but it’s not so good when viewed from the assembly language level. Calls and returns are slow, especially in the large code model, and the pushes required to put parameters on the stack are expensive as well.

What this means is that when you want to speed up a portion of a C program, you should identify the entire critical portion and move all of that critical portion into an assembly language function. You don’t want to move a part of the inner loop into assembly language and then call it from C every time through the loop; the function call and return overhead would be unacceptable. Carve out the critical code en masse and move it into assembly, and try to avoid calls and returns even in your assembly code. True, in assembly you can pass parameters in registers, but the calls and returns themselves are still slow; if the extra cycles they take don’t affect performance, then the code they’re in probably isn’t critical, and perhaps you’ve chosen to convert too much code to assembly, eh?


@@ -71,7 +70,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/08-02.html b/08-02.html index da2b218..b108dd7 100644 --- a/08-02.html +++ b/08-02.html @@ -24,7 +24,7 @@ - +
@@ -36,18 +36,18 @@


-

Stack Frames Slow So Much

+

Stack Frames Slow So Much

C compilers work within the stack frame model, whereby variables reside in a block of stack memory and are accessed via offsets from BP. Compilers may store a couple of variables in registers and may briefly keep other variables in registers when they’re used repeatedly, but the stack frame is the underlying architecture. It’s a nice architecture; it’s flexible, convenient, easy to program, and makes for fairly compact code. However, stack frames have a few drawbacks. They must be constructed and destroyed, which takes both time and code. They are so easy to use that they tend to bias the assembly language programmer in favor of accessing memory variables more often than might be necessary. Finally, you cannot use BP as a general-purpose register if you intend to access a stack frame, and having that seventh register available is sometimes useful indeed.

That doesn’t mean you shouldn’t use stack frames, which are useful and often necessary. Just don’t fall victim to their undeniable charms.

-

Torn Between Two Segments

+

Torn Between Two Segments

C compilers are not terrific at handling segments. Some compilers can efficiently handle a single far pointer used in a loop by leaving ES set for the duration of the loop. But two far pointers used in the same loop confuse every compiler I’ve seen, causing the full segment:offset address to be reloaded each time either pointer is used.

This particularly affects performance in 286 protected mode (under OS/2 1.X or the Rational DOS Extender, for example) because segment loads in protected mode take a minimum of 17 cycles, versus a mere 2 cycles in real mode.

In assembly language you have full control over segments. Use it, and, if necessary, reorganize your code to minimize segment loading.

-

Why Speeding Up Is Hard to Do

+

Why Speeding Up Is Hard to Do

You might think that the most obvious advantage assembly language has over C is that it allows the use of all forms of instructions and all registers in all ways, whereas C compilers tend to use a subset of registers and instructions in a limited number of ways. Yes and no. It’s true that C compilers typically don’t generate instructions such as XLAT, rotates, or the string instructions. On the other hand, XLAT and rotates are useful in a limited set of circumstances, and string instructions are used in the C library functions. In fact, C library code is likely to be carefully optimized by experts, and may be much better than equivalent code you’d produce yourself.

Am I saying that C compilers produce better code than you do? No, I’m saying that they can, unless you use assembly language properly. Writing code in assembly language rather than C guarantees nothing.

You can write good assembly, bad assembly, or assembly that is virtually indistinguishable from compiled code; you are more likely than not to write the latter if you think that optimization consists of tweaking compiled C code. @@ -56,7 +56,7 @@

True optimization requires rethinking your code to take advantage of assembly language. A C loop that searches through an integer array for matches might compile


Figure 8.1
  Tweaked compiler output for a loop. +
-->Figure 8.1  Tweaked compiler output for a loop.

to something like Figure 8.1A. You might look at that and tweak it to the code shown in Figure 8.1B.

@@ -69,7 +69,7 @@ jz Match

It’s a simple example—but, I hope, a convincing one. Stretch your brain when you optimize.

-

Taking It to the Limit

+

Taking It to the Limit

The ultimate in assembly language optimization comes when you change the rules; that is, when you reorganize the entire program to allow the use of better assembly language code in the small section of code that most affects overall performance. For example, consider that the data searched in the last example is stored in an array of structures, with each structure in the array containing other information as well. In this situation, REP SCASW couldn’t be used because the data searched through wouldn’t be contiguous.

However, if the need for performance in searching the array is urgent enough, there’s no reason why you can’t reorganize the data. This might mean removing the array elements from the structures and storing them in their own array so that REP SCASW could be used.

Organizing a program’s data so that the performance of the critical sections can be optimized is a key part of design, and one that’s easily shortchanged unless, during the design stage, you thoroughly understand and work to bring together your data needs, the critical sections of your program, and potential assembly language optimizations. @@ -86,7 +86,7 @@ jz Match

That said, let me show some of these precepts in action.

-

A C-to-Assembly Case Study

+

A C-to-Assembly Case Study

Listing 8.1 is the sample C application I’m going to use to examine optimization in action. Listing 8.1 isn’t really complete—it doesn’t handle the “no-matches” case well, and it assumes that the sum of all matches will fit into an int—but it will do just fine as an optimization example.


@@ -100,7 +100,7 @@ jz Match
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/08-03.html b/08-03.html index 7972d5a..4281857 100644 --- a/08-03.html +++ b/08-03.html @@ -24,7 +24,7 @@ - +
@@ -162,7 +162,7 @@ unsigned int FindIDAverage(unsigned int SearchedForID,

The main body of Listing 8.1 constructs a linked list of memory blocks of various sizes and stores an array of structures across those blocks, as shown in Figure 8.2. The function FindIDAverage in Listing 8.1 searches through that array for all matches to a specified ID number and returns the average value of all such matches. FindIDAverage contains two nested loops, the outer one repeating once for each linked block and the inner one repeating once for each array element in each block. The inner loop—the critical one—is compact, containing only four statements, and should lend itself rather well to compiler optimization.


Figure 8.2
  Linked array storage format (version 1). +
-->Figure 8.2  Linked array storage format (version 1).

As it happens, Microsoft C/C++ does optimize the inner loop of FindIDAverage nicely. Listing 8.2 shows the code Microsoft C/C++ generates for the inner loop, consisting of a mere seven assembly language instructions inside the loop. The compiler is smart enough to convert the loop index variable, which counts up but is used for nothing but counting loops, into a count-down variable so that the LOOP instruction can be used.

LISTING 8.2 L8-2.COD

@@ -212,7 +212,7 @@ $FB264:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/08-04.html b/08-04.html index 6558eae..319b522 100644 --- a/08-04.html +++ b/08-04.html @@ -24,7 +24,7 @@ - +
@@ -258,7 +258,7 @@ _FindIDAverage ENDP
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/08-05.html b/08-05.html index 7de8ad4..03a44b2 100644 --- a/08-05.html +++ b/08-05.html @@ -24,7 +24,7 @@ - +
@@ -61,7 +61,7 @@ extern unsigned int FindIDAverage2(unsigned int,


Figure 8.3
  Linked array storage format (version 2). +
-->Figure 8.3  Linked array storage format (version 2).

@@ -205,7 +205,7 @@ _FindIDAverage2 ENDP
 
 
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-01.html b/09-01.html index ec165d6..c350707 100644 --- a/09-01.html +++ b/09-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 9
Hints My Readers Gave Me -

-

Optimization Odds and Ends from the Field

+

Chapter 9
Hints My Readers Gave Me

+

Optimization Odds and Ends from the Field

Back in high school, I took a pre-calculus class from Mr. Bourgeis, whose most notable characteristics were incessant pacing and truly enormous feet. My friend Barry, who sat in the back row, right behind me, claimed that it was because of his large feet that Mr. Bourgeis was so restless. Those feet were so heavy, Barry hypothesized, that if Mr. Bourgeis remained in any one place for too long, the floor would give way under the strain, plunging the unfortunate teacher deep into the mantle of the Earth and possibly all the way through to China. Many amusing cartoons were drawn to this effect.

Unfortunately, Barry was too busy drawing cartoons, or, alternatively, sleeping, to actually learn any math. In the long run, that didn’t turn out to be a handicap for Barry, who went on to become vice-president of sales for a ham-packing company, where presumably he was rarely called upon to derive the quadratic equation. Barry’s lack of scholarship caused some problems back then, though. On one memorable occasion, Barry was half-asleep, with his eyes open but unfocused and his chin balanced on his hand in the classic “if I fall asleep my head will fall off my hand and I’ll wake up” posture, when Mr. Bourgeis popped a killer problem:

“Barry, solve this for X, please.” On the blackboard lay the equation:

@@ -58,7 +57,7 @@ X - 1 = 0

“Well, I could hear the answer all the way up here. Surely you could hear it just one row away?”

The class went wild. They might as well have sent us home early for all we accomplished the rest of the day.

I like to think I know more about performance programming than Barry knew about math. Nonetheless, I always welcome good ideas and comments, and many readers have sent me a slew of those over the years. So in this chapter, I think I’ll return the favor by devoting a chapter to reader feedback.

-

Another Look at LEA

+

Another Look at LEA

Several people have pointed out that while LEA is great for performing certain additions (see Chapter 6), it isn’t a perfect replacement for ADD. What’s the difference? LEA, an addressing instruction by trade, doesn’t affect the flags, while the arithmetic ADD instruction most certainly does. This is no problem when performing additions that involve only quantities that fit in one machine word (32 bits in 386 protected mode, 16 bits otherwise), but it renders LEA useless for multiword operations, which use the Carry flag to tie together partial results. For example, these instructions

@@ -92,7 +91,7 @@ ADDLOOP:
 

(Yes, I could use LODSD instead of MOV/LEA; I’m just illustrating a point here. Besides, LODS is only 1 cycle faster than MOV/LEA on the 386, and is actually more than twice as slow on the 486.) If we used ADD rather than LEA to advance the pointers, the carry from one ADC to the next would have to be preserved with either PUSHF/POPF or LAHF/SAHF. (Alternatively, we could use multiple INCs, since INC doesn’t affect the Carry flag.)

In short, LEA is indeed different from ADD. Sometimes it’s better. Sometimes not; that’s the nature of the various instruction substitutions and optimizations that will occur to you over time. There’s no such thing as “best” instructions on the x86; it all depends on what you’re trying to do.

But there sure are a lot of interesting options, aren’t there?

-

The Kennedy Portfolio

+

The Kennedy Portfolio

Reader John Kennedy regularly passes along intriguing assembly programming tricks, many of which I’ve never seen mentioned anywhere else. John likes to optimize for size, whereas I lean more toward speed, but many of his optimizations are good for both purposes. Here are a few of my favorites:

John’s code for setting AX to its absolute value is:

@@ -149,7 +148,7 @@ CopyDone:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-02.html b/09-02.html index 5bf9dbf..520df65 100644 --- a/09-02.html +++ b/09-02.html @@ -24,7 +24,7 @@ - +
@@ -76,7 +76,7 @@ SHL AX,2 ;*64 ADD AX,BX ;*80 -

Speeding Up Multiplication

+

Speeding Up Multiplication

That brings us to multiplication, one of the slowest of x86 operations and one that allows for considerable optimization. One way to speed up multiplication is to use shift and add, LEA, or a lookup table to hard-code a multiplication operation for a fixed multiplier, as shown above. Another is to take advantage of the early-out feature of the 386 (and the 486, but in the interests of brevity I’ll just say “386” from now on) by arranging your operands so that the multiplier (always the rightmost operand following MUL or IMUL) is no larger than the other operand.

Why? Because the 386 processes one multiplier bit per cycle and immediately ends a multiplication when all significant bits of the multiplier have been processed, so fewer cycles are required to multiply a large multiplicand times a small multiplier than a small multiplicand times a large multiplier, by a factor of about 1 cycle for each significant multiplier bit eliminated.
@@ -88,10 +88,10 @@ ADD AX,BX ;*80

All in all, MUL and IMUL are reasonable performers on the 386, no longer to be avoided in most cases—and you can help that along by arranging your code to make the smaller operand the multiplier whenever you know which operand is smaller.

That doesn’t mean that your code should test and swap operands to make sure the smaller one is the multiplier; that rarely pays off. I’m speaking more of the case where you’re scaling an array up by a value that’s always in the range of, say, 2 to 10; because the scale value will always be small and the array elements may have any value, the scale value is the logical choice for the multiplier.

-

Optimizing Optimized Searching

+

Optimizing Optimized Searching

Rob Williams writes with a wonderful optimization to the REPNZ SCASB-based optimized searching routine I discussed in Chapter 5. As a quick refresher, I described searching a buffer for a text string as follows: Scan for the first byte of the text string with REPNZ SCASB, then use REPZ CMPS to check for a full match whenever REPNZ SCASB finds a match for the first character, as shown in Figure 9.1. The principle is that most buffer characters won’t match the first character of any given string, so REPNZ SCASB, by far the fastest way to search on the PC, can be used to eliminate most potential matches; each remaining potential match can then be checked in its entirety with REPZ CMPS.


Figure 9.1
  Simple searching method for locating a text string. +
-->Figure 9.1  Simple searching method for locating a text string.

Rob’s revelation, which he credits without explanation to Edgar Allen Poe (search nevermore?), was that by far the slowest part of the whole deal is handling REPNZ SCASB matches, which require checking the remainder of the string with REPZ CMPS and restarting REPNZ SCASB if no match is found.

Rob points out that the number of REPNZ SCASB matches can easily be reduced simply by scanning for the character in the searched-for string that appears least often in the buffer being searched. @@ -109,7 +109,7 @@ ADD AX,BX ;*80
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-03.html b/09-03.html index 34f85e6..5a9fb33 100644 --- a/09-03.html +++ b/09-03.html @@ -24,7 +24,7 @@ - +
@@ -41,7 +41,7 @@
The difference between Listings 9.1 and 9.2 (which gives you more than a doubling of performance) is due entirely to understanding the nature of the data being handled, and biasing the code to reflect that knowledge.


Figure 9.2
  Faster searching method for locating a text string. +
-->Figure 9.2  Faster searching method for locating a text string.

LISTING 9.1 L9-1.ASM

@@ -152,7 +152,7 @@ _FindStringendp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-04.html b/09-04.html index b303f89..6f09be9 100644 --- a/09-04.html +++ b/09-04.html @@ -24,7 +24,7 @@ - +
@@ -187,7 +187,7 @@ void main() {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-05.html b/09-05.html index 51b16b0..dbacdc9 100644 --- a/09-05.html +++ b/09-05.html @@ -24,7 +24,7 @@ - +
@@ -39,7 +39,7 @@

You’ll notice that in Listing 9.2 I didn’t use a table of character frequencies in English text to determine the character for which to scan, but rather let the caller make that choice. Each buffer of bytes has unique characteristics, and English-letter frequency could well be inappropriate. What if the buffer is filled with French text? Cyrillic? What if it isn’t text that’s being searched? It might be worthwhile for an application to build a dynamic frequency table for each buffer so that the best scan character could be chosen for each search. Or perhaps not, if the search isn’t time-critical or the buffer is small.

The point is that you can improve performance dramatically by understanding the nature of the data with which you work. (This is equally true for high-level language programming, by the way.) Listing 9.2 is very similar to and only slightly more complex than Listing 9.1; the difference lies not in elbow grease or cycle counting but in the organic integrating optimizer technology we all carry around in our heads.

-

Short Sorts

+

Short Sorts

David Stafford (recently of Borland and Borland Japan) who happens to be one of the best assembly language programmers I’ve ever met, has written a C-callable routine that sorts an array of integers in ascending order. That wouldn’t be particularly noteworthy, except that David’s routine, shown in Listing 9.4, is exactly 25 bytes long. Look at the code; you’ll keep saying to yourself, “But this doesn’t work...oh, yes, I guess it does.” As they say in the Prego spaghetti sauce ads, it’s in there—and what a job of packing. Anyway, David says that a 24-byte sort routine eludes him, and he’d like to know if anyone can come up with one.

LISTING 9.4 L9-4.ASM

@@ -78,12 +78,12 @@ _sort: pop dx ;get return address (entry point) end -

Full 32-Bit Division

+

Full 32-Bit Division

One of the most annoying limitations of the x86 is that while the dividend operand to the DIV instruction can be 32 bits in size, both the divisor and the result must be 16 bits. That’s particularly annoying in regards to the result because sometimes you just don’t know whether the ratio of the dividend to the divisor is greater than 64K-1 or not—and if you guess wrong, you get that godawful Divide By Zero interrupt. So, what is one to do when the result might not fit in 16 bits, or when the dividend is larger than 32 bits? Fall back to a software division approach? That will work—but oh so slowly.

There’s another technique that’s much faster than a pure software approach, albeit not so flexible. This technique allows arbitrarily large dividends and results, but the divisor is still limited to16 bits. That’s not perfect, but it does solve a number of problems, in particular eliminating the possibility of a Divide By Zero interrupt from a too-large result.

This technique involves nothing more complicated than breaking up the division into word-sized chunks, starting with the most significant word of the dividend. The most significant word is divided by the divisor (with no chance of overflow because there are only 16 bits in each); then the remainder is prepended to the next 16 bits of dividend, and the process is repeated, as shown in Figure 9.3. This process is equivalent to dividing by hand, except that here we stop to carry the remainder manually only after each word of the dividend; the hardware divide takes care of the rest. Listing 9.5 shows a function to divide an arbitrarily large dividend by a 16-bit divisor, and Listing 9.6 shows a sample division of a large dividend. Note that the same principle can be applied to handling arbitrarily large dividends in 386 native mode code, but in that case the operation can proceed a dword, rather than a word, at a time.


Figure 9.3
  Fast multiword division on the 386. +
-->Figure 9.3  Fast multiword division on the 386.

As for handling signed division with arbitrarily large dividends, that can be done easily enough by remembering the signs of the dividend and divisor, dividing the absolute value of the dividend by the absolute value of the divisor, and applying the stored signs to set the proper signs for the quotient and remainder. There may be more clever ways to produce the same result, by using IDIV, for example; if you know of one, drop me a line c/o Coriolis Group Books.


@@ -98,7 +98,7 @@ _sort: pop dx ;get return address (entry point)
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-06.html b/09-06.html index b7e3527..88a8171 100644 --- a/09-06.html +++ b/09-06.html @@ -24,7 +24,7 @@ - +
@@ -128,7 +128,7 @@ main() { } -

Sweet Spot Revisited

+

Sweet Spot Revisited

Way back in Volume 1, Number 1 of PC TECHNIQUES, (April/May 1990) I wrote the very first of that magazine’s HAX (#1), which extolled the virtues of placing your most commonly-used automatic (stack-based) variables within the stack’s “sweet spot,” the area between +127 to -128 bytes away from BP, the stack frame pointer. The reason was that the 8088 can store addressing displacements that fall within that range in a single byte; larger displacements require a full word of storage, increasing code size by a byte per instruction, and thereby slowing down performance due to increased instruction fetching time.

This takes on new prominence in 386 native mode, where straying from the sweet spot costs not one, but two or three bytes. Where the 8088 had two possible displacement sizes, either byte or word, on the 386 there are three possible sizes: byte, word, or dword. In native mode (32-bit protected mode), however, a prefix byte is needed in order to use a word-sized displacement, so a variable located outside the sweet spot requires either two extra bytes (an extra displacement byte plus a prefix byte) or three extra bytes (a dword displacement rather than a byte displacement). Either way, instructions grow alarmingly.

Performance may or may not suffer from missing the sweet spot, depending on the processor, the memory architecture, and the code mix. On a 486, prefix bytes often cost a cycle; on a 386SX, increased code size often slows performance because instructions must be fetched through the half-pint 16-bit bus; on a 386, the effect depends on the instruction mix and whether there’s a cache.

@@ -148,7 +148,7 @@ main() {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/09-07.html b/09-07.html index 8a48ffa..387a15b 100644 --- a/09-07.html +++ b/09-07.html @@ -24,7 +24,7 @@ - +
@@ -36,15 +36,15 @@


-

Hard-Core Cycle Counting

+

Hard-Core Cycle Counting

Next, we come to an item that cycle counters will love, especially since it involves apparently incorrect documentation on Intel’s part. According to Intel’s documents, all RCR and RCL instructions, which perform rotations through the Carry flag, as shown in Figure 9.4, take 9 cycles on the 386 when working with a register operand. My measurements indicate that the 9-cycle execution time almost holds true for multibit rotate-through-carries, which I’ve timed at 8 cycles apiece; for example, RCR AX,CL takes 8 cycles on my 386, as does RCL DX,2. Contrast that with ROR and ROL, which can rotate the contents of a register any number of bits in just 3 cycles.

However, rotating by one bit through the Carry flag does not take 9 cycles, contrary to Intel’s 80386 Programmer’s Reference Manual, or even 8 cycles. In fact, RCR reg,1 and RCL reg,1 take 3 cycles, just like ROR, ROL, SHR, and SHL. At least, that’s how fast they run on my 386, and I very much doubt that you’ll find different execution times on other 386s. (Please let me know if you do, though!)


Figure 9.4
  Performing rotate instructions using the Carry flag. +
-->Figure 9.4  Performing rotate instructions using the Carry flag.

Interestingly, according to Intel’s i486 Microprocessor Programmer’s Reference Manual, the 486 can RCR or RCL a register by one bit in 3 cycles, but takes between 8 and 30 cycles to perform a multibit register RCR or RCL!

No great lesson here, just a caution to be leery of multibit RCR and RCL when performance matters—and to take cycle-time documentation with a grain of salt.

-

Hardwired Far Jumps

+

Hardwired Far Jumps

Did you ever wonder how to code a far jump to an absolute address in assembly language? Probably not, but if you ever do, you’re going to be glad for this next item, because the obvious solution doesn’t work. You might think all it would take to jump to, say, 1000:5 would be JMP FAR PTR 1000:5, but you’d be wrong. That won’t even assemble. You might then think to construct in memory a far pointer containing 1000:5, as in the following:

@@ -82,7 +82,7 @@ start:
 

By the way, if you’re wondering how I figured this out, I merely applied my good friend Dan Illowsky’s long-standing rule for dealing with MASM:

If the obvious doesn’t work (and it usually doesn’t), just try everything you can think of, no matter how ridiculous, until you find something that does—a rule with plenty of history on its side.

-

Setting 32-Bit Registers: Time versus Space

+

Setting 32-Bit Registers: Time versus Space

To finish up this chapter, consider these two items. First, in 32-bit protected mode,

@@ -125,7 +125,7 @@ move bx,-1
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/10-01.html b/10-01.html index 5e7acce..02fc345 100644 --- a/10-01.html +++ b/10-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 10
Patient Coding, Faster Code -

-

How Working Quickly Can Bring Execution to a Crawl

+

Chapter 10
Patient Coding, Faster Code

+

How Working Quickly Can Bring Execution to a Crawl

My grandfather does The New York Times crossword puzzle every Sunday. In ink. With nary a blemish.

The relevance of which will become apparent in a trice.

What my grandfather is, is a pattern matcher par excellence. You’re a pattern matcher, too. So am I. We can’t help it; it comes with the territory. Try focusing on text and not reading it. Can’t do it. Can you hear the voice of someone you know and not recognize it? I can’t. And how in the Nine Billion Names of God is it that we’re capable of instantly recognizing one face out of the thousands we’ve seen in our lifetimes—even years later, from a different angle and in different light? Although we take them for granted, our pattern-matching capabilities are surely a miracle on the order of loaves and fishes.

@@ -50,11 +49,11 @@

In this chapter, I’m going to walk you through a simple but illustrative case history that nicely points up the wisdom of delaying gratification when faced with programming problems, so that your mind has time to chew on the problems from other angles. The alternative solutions you find by doing this may seem obvious, once you’ve come up with them. They may not even differ greatly from your initial solutions. Often, however, they will be much better—and you’ll never even have the chance to decide whether they’re better or not if you take the first thing that comes into your head and run with it.

-

The Case for Delayed Gratification

+

The Case for Delayed Gratification

Once upon a time, I set out to read Algorithms, by Robert Sedgewick (Addison-Wesley), which turned out to be a wonderful, stimulating, and most useful book, one that I recommend highly. My story, however, involves only what happened in the first 12 pages, for it was in those pages that Sedgewick discussed Euclid’s algorithm.

Euclid’s algorithm (discovered by Euclid, of Euclidean geometry fame, a very long time ago, way back when computers still used core memory) is a straightforward algorithm that solves one of the simplest problems imaginable: finding the greatest common integer divisor (GCD) of two positive integers. Sedgewick points out that this is useful for reducing a fraction to its lowest terms. I’m sure it’s useful for other things, as well, although none spring to mind. (A long time ago, I wrote an article about optimizing a bit of code that wasn’t even vaguely time-critical, and got swamped with letters telling me so. I knew it wasn’t time-critical; it was just a good example. So for now, close your eyes and imagine that finding the GCD is not only necessary but must also be done as quickly as possible, because it’s perfect for the point I want to make here and now. Okay?)

The problem at hand, then, is simply this: Find the largest integer value that evenly divides two arbitrary positive integers. That’s all there is to it. So warm up your pattern matchers...and go!

-

The Brute-Force Syndrome

+

The Brute-Force Syndrome

I have a funny feeling that you’d already figured out how to find the GCD before I even said “go.” That’s what I did when reading Algorithms; before I read another word, I had to figure it out for myself. Programmers are like that; give them a problem and their eyes immediately glaze over as they try to solve it before you’ve even shut your mouth. That sort of instant response can certainly be impressive, but it can backfire, too, as it did in my case.

You see, I fell victim to a common programming pitfall, the “brute-force” syndrome. The basis of this syndrome is that there are many problems that have obvious, brute-force solutions—with one small drawback. The drawback is that if you were to try to apply a brute-force solution by hand—that is, work a single problem out with pencil and paper or a calculator—it would generally require that you have the patience and discipline to work on the problem for approximately seven hundred years, not counting eating and sleeping, in order to get an answer. Finding all the prime numbers less than 1,000,000 is a good example; just divide each number up to 1,000,000 by every lesser number, and see what’s left standing. For most of the history of humankind, people were forced to think of cleverer solutions, such as the Sieve of Eratosthenes (we’d have been in big trouble if the ancient Greeks had had computers), mainly because after about five minutes of brute force-type work, people’s attention gets diverted to other important matters, such as how far a paper airplane will fly from a second-story window.


@@ -69,7 +68,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/10-02.html b/10-02.html index ae2842e..9617f1b 100644 --- a/10-02.html +++ b/10-02.html @@ -24,7 +24,7 @@ - +
@@ -41,7 +41,7 @@

The solution that I instantly came up with to finding the GCD is about as brute- force as you can get: Divide both the larger integer (iL) and the smaller integer (iS) by every integer equal to or less than the smaller integer, until a number is found that divides both evenly, as shown in Figure 10.1. This works, but it’s a lousy solution, requiring as many as iS*2 divisions; very expensive, especially for large values of iS. For example, finding the GCD of 30,001 and 30,002 would require 60,002 divisions, which alone, disregarding tests and branches, would take about 2 seconds on an 8088, and more than 50 milliseconds even on a 25 MHz 486—a very long time in computer years, and not insignificant in human years either.

Listing 10.1 is an implementation of the brute-force approach to GCD calculation. Table 10.1 shows how long it takes this approach to find the GCD for several integer pairs. As expected, performance is extremely poor when iS is large.


Figure 10.1
  Using a brute-force algorithm to find a GCD. +
-->Figure 10.1  Using a brute-force algorithm to find a GCD.

@@ -136,7 +136,7 @@ unsigned int gcd(unsigned int int1, unsigned int int2) { } -

Wasted Breakthroughs

+

Wasted Breakthroughs

Sedgewick’s first solution to the GCD problem was pretty much the one I came up with. He then pointed out that the GCD of iL and iS is the same as the GCD of iL-iS and iS. This was obvious (once Sedgewick pointed it out); by the very nature of division, any number that divides iL evenly nL times and iS evenly nS times must divide iL-iS evenly nL-nS times. Given that insight, I immediately designed a new, faster approach, shown in Listing 10.2.

LISTING 10.2 L10-2.C

@@ -186,7 +186,7 @@ unsigned int gcd(unsigned int int1, unsigned int int2) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/10-03.html b/10-03.html index 035e6ac..567eaa1 100644 --- a/10-03.html +++ b/10-03.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


Listing 10.2 repeatedly subtracts iS from iL until iL becomes less than or equal to iS. If iL becomes equal to iS, then that’s the GCD; alternatively, if iL becomes less than iS, iL and iS switch values, and the process is repeated, as shown in Figure 10.2. The number of iterations this approach requires relative to Listing 10.1 depends heavily on the values of iL and iS, so it’s not always faster, but, as Table 10.1 indicates, Listing 10.2 is generally much better code.


Figure 10.2
  Using repeated subtraction algorithm to find a GCD. +
-->Figure 10.2  Using repeated subtraction algorithm to find a GCD.

Listing 10.2 is a far graver misstep than Listing 10.1, for all that it’s faster. Listing 10.1 is obviously a hacked-up, brute-force approach; no one could mistake it for anything else. It could be speeded up in any of a number of ways with a little thought. (Simply skipping testing all the divisors between iS and iS/2, not inclusive, would cut the worst-case time in half, for example; that’s not a particularly good optimization, but it illustrates how easily Listing 10.1 can be improved.) Listing 10.1 is a hack job, crying out for inspiration.

Listing 10.2, on the other hand, has gotten the inspiration—and largely wasted it through haste. Had Sedgewick not told me otherwise, I might well have assumed that Listing 10.2 was optimized, a mistake I would never have made with Listing 10.1. I experienced a conceptual breakthrough when I understood Sedgewick’s point: A smaller number can be subtracted from a larger number without affecting their GCD, thereby inexpensively reducing the scale of the problem. And, in my hurry to make this breakthrough reality, I missed its full scope. As Sedgewick says on the very next page, the number that one gets by subtracting iS from iL until iL is less than iS is precisely the same as the remainder that one gets by dividing iL by iS—again, this is inherent in the nature of division—and that is the basis for Euclid’s algorithm, shown in Figure 10.3. Listing 10.3 is an implementation of Euclid’s algorithm.

@@ -94,11 +94,11 @@ static unsigned int gcd_recurs(unsigned int larger_int,
Had I been implementing GCD determination without Sedgewick’s help, I would surely not have settled for Listing 10.1—but I might well have ended up with Listing 10.2 in my enthusiasm over the “brilliant” discovery of subtracting the lesser Using Euclid’s algorithm to find a GCD number from the greater. In a commercial product, my lack of patience and discipline could have been costly indeed.


Figure 10.3
  Using Euclid’s algorithm to find a GCD. +
-->Figure 10.3  Using Euclid’s algorithm to find a GCD.

Give your mind time and space to wander around the edges of important programming problems before you settle on any one approach. I titled this book’s first chapter “The Best Optimizer Is between Your Ears,” and that’s still true; what’s even more true is that the optimizer between your ears does its best work not at the implementation stage, but at the very beginning, when you try to imagine how what you want to do and what a computer is capable of doing can best be brought together.

-

Recursion

+

Recursion

Euclid’s algorithm lends itself to recursion beautifully, so much so that an implementation like Listing 10.3 comes almost without thought. Again, though, take a moment to stop and consider what’s really going on, at the assembly language level, in Listing 10.3. There’s recursion and then there’s recursion; code recursion and data recursion, to be exact. Listing 10.3 is code recursion—recursion through calls—the sort most often used because it is conceptually simplest. However, code recursion tends to be slow because it pushes parameters and calls a subroutine for every iteration. Listing 10.4, which uses data recursion, is much faster and no more complicated than Listing 10.3. Actually, you could just say that Listing 10.4 uses a loop and ignore any mention of recursion; conceptually, though, Listing 10.4 performs the same recursive operations that Listing 10.3 does.

LISTING 10.4 L10-4.C

@@ -138,7 +138,7 @@ unsigned int gcd(unsigned int int1, unsigned int int2) { } -

Patient Optimization

+

Patient Optimization

At long last, we’re ready to optimize GCD determination in the classic sense. Table 10.1 shows the performance of Listing 10.4 with and without Microsoft C/C++’s maximum optimization, and also shows the performance of Listing 10.5, an assembly language version of Listing 10.4. Sure, the optimized versions are faster than the unoptimized version of Listing 10.4—but the gains are small compared to those realized from the higher-level optimizations in Listings 10.2 through 10.4.


@@ -152,7 +152,7 @@ unsigned int gcd(unsigned int int1, unsigned int int2) {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/10-04.html b/10-04.html index 282fe6f..e9b17e5 100644 --- a/10-04.html +++ b/10-04.html @@ -24,7 +24,7 @@ - +
@@ -147,7 +147,7 @@ _gcd endp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-01.html b/11-01.html index 0c8cf6a..e54a21c 100644 --- a/11-01.html +++ b/11-01.html @@ -24,7 +24,7 @@ - +
@@ -36,12 +36,11 @@


-

Chapter 11
Pushing the 286 and 386 -

-

New Registers, New Instructions, New Timings, New Complications

+

Chapter 11
Pushing the 286 and 386

+

New Registers, New Instructions, New Timings, New Complications

This chapter, adapted from my earlier book Zen of Assembly Language (1989; now out of print), provides an overview of the 286 and 386, often contrasting those processors with the 8088. At the time I originally wrote this, the 8088 was the king of processors, and the 286 and 386 were the new kids on the block. Today, of course, all three processors are past their primes, but many millions of each are still in use, and the 386 in particular is still well worth considering when optimizing software.

This chapter provides an interesting look at the evolution of the x86 architecture, to a greater degree than you might expect, for the x86 family came into full maturity with the 386; the 486 and the Pentium are really nothing more than faster 386s, with very little in the way of new functionality. In contrast, the 286 added a number of instructions, respectable performance, and protected mode to the 8088’s capabilities, and the 386 added more instructions and a whole new set of addressing modes, and brought the x86 family into the 32-bit world that represents the future (and, increasingly, the present) of personal computing. This chapter also provides insight into the effects on optimization of the variations in processors and memory architectures that are common in the PC world. So, although the 286 and 386 no longer represent the mainstream of computing, this chapter is a useful mix of history lesson, x86 overview, and details on two workhorse processors that are still in wide use.

-

Family Matters

+

Family Matters

While the x86 family is a large one, only a few members of the family—which includes the 8088, 8086, 80188, 80186, 286, 386SX, 386DX, numerous permutations of the 486, and now the Pentium—really matter.

The 8088 is now all but extinct in the PC arena. The 8086 was used fairly widely for a while, but has now all but disappeared. The 80186 and 80188 never really caught on for use in PC and don’t require further discussion.

@@ -49,7 +48,7 @@

I’m not going to discuss the 386SX in detail. If you do find yourself programming for the 386SX, follow the same general rules you should follow for the 8088: use short instructions, use the registers as heavily as possible, and don’t branch. In other words, avoid memory, since the 386SX is by definition better at processing data internally than it is at accessing memory.

The 486 is a world unto itself for the purposes of optimization, and the Pentium is a universe unto itself. We’ll treat them separately in later chapters.

This leaves us with just two processors: the 286 and the 386. Each was the PC standard in its day. The 286 is no longer used in new systems, but there are millions of 286-based systems still in daily use. The 386 is still being used in new systems, although it’s on the downhill leg of its lifespan, and it is in even wider use than the 286. The future clearly belongs to the 486 and Pentium, but the 286 and 386 are still very much a part of the present-day landscape.

-

Crossing the Gulf to the 286 and the 386

+

Crossing the Gulf to the 286 and the 386

Apart from vastly improved performance, the biggest difference between the 8088 and the 286 and 386 (as well as the later Intel CPUs) is that the 286 introduced protected mode, and the 386 greatly expanded the capabilities of protected mode. We’re only going to talk about real-mode operation of the 286 and 386 in this book, however. Protected mode offers a whole new memory management scheme, one that isn’t supported by the 8088. Only code specifically written for protected mode can run in that mode; it’s an alien and hostile environment for MS-DOS programs.

In particular, segments are different creatures in protected mode. They’re selectors—indexes into a table of segment descriptors—rather than plain old registers, and can’t be set to arbitrary values. That means that segments can’t be used for temporary storage or as part of a fast indivisible 32-bit load from memory, as in

@@ -69,7 +68,7 @@ mov dx,word ptr [LongVar+2]

Protected mode uses those altered segment registers to offer access to a great deal more memory than real mode: The 286 supports 16 megabytes of memory, while the 386 supports 4 gigabytes (4K megabytes) of physical memory and 64 terabytes (64K gigabytes!) of virtual memory.

In protected mode, your programs generally run under an operating system (OS/2, Unix, Windows NT or the like) that exerts much more control over the computer than does MS-DOS. Protected mode operating systems can generally run multiple programs simultaneously, and the performance of any one program may depend far less on code quality than on how efficiently the program uses operating system services and how often and under what circumstances the operating system preempts the program. Protected mode programs are often mostly collections of operating system calls, and the performance of whatever code isn’t operating-system oriented may depend primarily on how large a time slice the operating system gives that code to run in.

In short, taken as a whole, protected mode programming is a different kettle of fish altogether from what I’ve been describing in this book. There’s certainly a knack to optimizing specifically for protected mode under a given operating system...but it’s not what we’ve been learning, and now is not the time to pursue it further. In general, though, the optimization strategies discussed in this book still hold true in protected mode; it’s just issues specific to protected mode or a particular operating system that we won’t discuss.

-

In the Lair of the Cycle-Eaters, Part II

+

In the Lair of the Cycle-Eaters, Part II

Under the programming interface, the 286 and 386 differ considerably from the 8088. Nonetheless, with one exception and one addition, the cycle-eaters remain much the same on computers built around the 286 and 386. Next, we’ll review each of the familiar cycle-eaters I covered in Chapter 4 as they apply to the 286 and 386, and we’ll look at the new member of the gang, the data alignment cycle-eater.

The one cycle-eater that vanishes on the 286 and 386 is the 8-bit bus cycle-eater. The 286 is a 16-bit processor both internally and externally, and the 386 is a 32-bit processor both internally and externally, so the Execution Unit/Bus Interface Unit size mismatch that plagues the 8088 is eliminated. Consequently, there’s no longer any need to use byte-sized memory variables in preference to word-sized variables, at least so long as word-sized variables start at even addresses, as we’ll see shortly. On the other hand, access to byte-sized variables still isn’t any slower than access to word-sized variables, so you can use whichever size suits a given task best.


@@ -85,7 +84,7 @@ mov dx,word ptr [LongVar+2]
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-02.html b/11-02.html index 454d86b..8973d1d 100644 --- a/11-02.html +++ b/11-02.html @@ -24,7 +24,7 @@ - +
@@ -42,7 +42,7 @@

After a branch it does matter how fast the queue can refill, and there we come to the second reason the prefetch queue cycle-eater lives on: The 286 and 386 are so fast that sometimes the Execution Unit can execute instructions faster than they can be fetched, even though instruction fetching is much faster on the 286 and 386 than on the 8088.

(All other things being equal, too-slow instruction fetching is more of a problem on the 286 than on the 386, since the 386 fetches 4 instruction bytes at a time versus the 2 instruction bytes fetched per memory access by the 286. However, the 386 also typically runs at least twice as fast as the 286, meaning that the 386 can easily execute instructions faster than they can be fetched unless very high-speed memory is used.)

The most significant reason that the prefetch queue cycle-eater not only survives but prospers on the 286 and 386, however, lies in the various memory architectures used in computers built around the 286 and 386. Due to the memory architectures, the 8-bit bus cycle-eater is replaced by a new form of the wait state cycle-eater: wait states on accesses to normal system memory.

-

System Wait States

+

System Wait States

The 286 and 386 were designed to lose relatively little performance to the prefetch queue cycle-eater...when used with zero-wait-state memory: memory that can complete memory accesses so rapidly that no wait states are needed. However, true zero-wait-state memory is almost never used with those processors. Why? Because memory that can keep up with a 286 is fairly expensive, and memory that can keep up with a 386 is very expensive. Instead, computer designers use alternative memory architectures that offer more performance for the dollar—but less performance overall—than zero-wait-state memory. (It is possible to build zero-wait-state systems for the 286 and 386; it’s just so expensive that it’s rarely done.)

The IBM AT and true compatibles use one-wait-state memory (some AT clones use zero-wait-state memory, but such clones are less common than one-wait-state AT clones). The 386 systems use a wide variety of memory systems—including high-speed caches, interleaved memory, and static-column RAM—that insert anywhere from 0 to about 5 wait states (and many more if 8 or 16-bit memory expansion cards are used); the exact number of wait states inserted at any given time depends on the interaction between the code being executed and the memory system it’s running on.

The performance of most 386 memory systems can vary greatly from one memory access to another, depending on factors such as what data happens to be in the cache and which interleaved bank and/or RAM column was accessed last. @@ -90,7 +90,7 @@ Skip:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-03.html b/11-03.html index fc49fbc..980ac34 100644 --- a/11-03.html +++ b/11-03.html @@ -24,7 +24,7 @@ - +
@@ -55,7 +55,7 @@

Of course, those are exactly the rules that apply to 8088 optimization as well. Isn’t it convenient that the same general rules apply across the board?

-

Data Alignment

+

Data Alignment

Thanks to its 16-bit bus, the 286 can access word-sized memory variables just as fast as byte-sized variables. There’s a catch, however: That’s only true for word-sized variables that start at even addresses. When the 286 is asked to perform a word-sized access starting at an odd address, it actually performs two separate accesses, each of which fetches 1 byte, just as the 8088 does for all word-sized accesses.

Figure 11.1 illustrates this phenomenon. The conversion of word-sized accesses to odd addresses into double byte-sized accesses is transparent to memory-accessing instructions; all any instruction knows is that the requested word has been accessed, no matter whether 1 word-sized access or 2 byte-sized accesses were required to accomplish it.

@@ -65,7 +65,7 @@

That, in a nutshell, is the data alignment cycle-eater, the one new cycle-eater of the 286 and 386. (The data alignment cycle-eater is a close relative of the 8088’s 8-bit bus cycle-eater, but since it behaves differently—occurring only at odd addresses—and is avoided with a different workaround, we’ll consider it to be a new cycle-eater.)


Figure 11.1
  The data alignment cycle-eater. +
-->Figure 11.1  The data alignment cycle-eater.

The way to deal with the data alignment cycle-eater is straightforward: Don’t perform word-sized accesses to odd addresses on the 286 if you can help it. The easiest way to avoid the data alignment cycle-eater is to place the directive EVEN before each of your word-sized variables. EVEN forces the offset of the next byte assembled to be even by inserting a NOP if the current offset is odd; consequently, you can ensure that any word-sized variable can be accessed efficiently by the 286 simply by preceding it with EVEN.

Listing 11.2, which accesses memory a word at a time with each word starting at an odd address, runs on a 10 MHz AT clone in 1.27 ms per repetition of MOVSW, or 0.64 ms per word-sized memory access. That’s 6-plus cycles per word-sized access, which breaks down to two separate memory accesses—3 cycles to access the high byte of each word and 3 cycles to access the low byte of each word, the inevitable result of non-word-aligned word-sized memory accesses—plus a bit extra for DRAM refresh.

@@ -115,7 +115,7 @@ Skip:

The data alignment cycle-eater has intriguing implications for speeding up 286/386 code. The expenditure of a little care and a few bytes to make sure that word-sized variables and memory blocks are word-aligned can literally double the performance of certain code running on the 286. Even if it doesn’t double performance, word alignment usually helps and never hurts.

-

Code Alignment

+

Code Alignment

Lack of word alignment can also interfere with instruction fetching on the 286, although not to the extent that it interferes with access to word-sized memory variables. The 286 prefetches instructions a word at a time; even if a given instruction doesn’t begin at an even address, the 286 simply fetches the first byte of that instruction at the same time that it fetches the last byte of the previous instruction, as shown in Figure 11.2, then separates the bytes internally. That means that in most cases, instructions run just as fast whether they’re word-aligned or not.

There is, however, a non-word-alignment penalty on branches to odd addresses. On a branch to an odd address, the 286 is only able to fetch 1 useful byte with the first instruction fetch following the branch, as shown in Figure 11.3. In other words, lack of word alignment of the target instruction for any branch effectively cuts the instruction-fetching power of the 286 in half for the first instruction fetch after that branch. While that may not sound like much, you’d be surprised at what it can do to tight loops; in fact, a brief story is in order.


@@ -131,7 +131,7 @@ Skip:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-04.html b/11-04.html index ac8996f..1be4dd8 100644 --- a/11-04.html +++ b/11-04.html @@ -24,7 +24,7 @@ - +
@@ -49,10 +49,10 @@ LoopTop:


Figure 11.2
  Word-aligned prefetching on the 286. +
-->Figure 11.2  Word-aligned prefetching on the 286.


Figure 11.3
  How instruction bytes are fetched after a branch. +
-->Figure 11.3  How instruction bytes are fetched after a branch.

Now, this code should run in, say, about 12 cycles per loop at most. Instead, it took over 14 cycles per loop, an execution time that I could not explain in any way. After rolling it around in my head for a while, I took a look at the code under a debugger...and the answer leaped out at me. The loop began at an odd address! That meant that two instruction fetches were required each time through the loop; one to get the opcode byte of the LOOP instruction, which resided at the end of one word-aligned word, and another to get the displacement byte, which resided at the start of the next word-aligned word.

One simple change brought the execution time down to a reasonable 12.5 cycles per loop:

@@ -80,22 +80,22 @@ FindChar proc near

In my experience, this simple practice is the one form of code alignment that consistently provides a reasonable return for bytes and effort expended, although sometimes it also pays to word-align tight time-critical loops.

-

Alignment and the 386

+

Alignment and the 386

So far we’ve only discussed alignment as it pertains to the 286. What, you may well ask, of the 386?

The 386 adds the issue of doubleword alignment (that is, alignment to addresses that are multiples of four.) The rule for the 386 is: Word-sized memory accesses should be word-aligned (it’s impossible for word-aligned word-sized accesses to cross doubleword boundaries), and doubleword-sized memory accesses should be doubleword-aligned. However, in real (as opposed to 32-bit protected) mode, doubleword-sized memory accesses are rare, so the simple word-alignment rule we’ve developed for the 286 serves for the 386 in real mode as well.

As for code alignment...the subroutine-start word-alignment rule of the 286 serves reasonably well there too since it avoids the worst case, where just 1 byte is fetched on entry to a subroutine. While optimum performance would dictate doubleword alignment of subroutines, that takes 3 bytes, a high price to pay for an optimization that improves performance only on the post 286 processors.

-

Alignment and the Stack

+

Alignment and the Stack

One side-effect of the data alignment cycle-eater of the 286 and 386 is that you should never allow the stack pointer to become odd. (You can make the stack pointer odd by adding an odd value to it or subtracting an odd value from it, or by loading it with an odd value.) An odd stack pointer on the 286 or 386 (or a non-doubleword-aligned stack in 32-bit protected mode on the 386, 486, or Pentium) will significantly reduce the performance of PUSH, POP, CALL, and RET, as well as INT and IRET, which are executed to invoke DOS and BIOS functions, handle keystrokes and incoming serial characters, and manage the mouse. I know of a Forth programmer who vastly improved the performance of a complex application on the AT simply by forcing the Forth interpreter to maintain an even stack pointer at all times.

An interesting corollary to this rule is that you shouldn’t INC SP twice to add 2, even though that takes fewer bytes than ADD SP,2. The stack pointer is odd between the first and second INC, so any interrupt occurring between the two instructions will be serviced more slowly than it normally would. The same goes for decrementing twice; use SUB SP,2 instead.

Keep the stack pointer aligned at all times.
-

The DRAM Refresh Cycle-Eater: Still an Act of God

+

The DRAM Refresh Cycle-Eater: Still an Act of God

The DRAM refresh cycle-eater is the cycle-eater that’s least changed from its 8088 form on the 286 and 386. In the AT, DRAM refresh uses a little over five percent of all available memory accesses, slightly less than it uses in the PC, but in the same ballpark. While the DRAM refresh penalty varies somewhat on various AT clones and 386 computers (in fact, a few computers are built around static RAM, which requires no refresh at all; likewise, caches are made of static RAM so cached systems generally suffer less from DRAM refresh), the 5 percent figure is a good rule of thumb.

Basically, the effect of the DRAM refresh cycle-eater is pretty much the same throughout the PC-compatible world: fairly small, so it doesn’t greatly affect performance; unavoidable, so there’s no point in worrying about it anyway; and a nuisance since it results in fractional cycle counts when using the Zen timer. Just as with the PC, a given code sequence on the AT can execute at varying speeds at different times as a result of the interaction between the code and DRAM refresh.

There’s nothing much new with DRAM refresh on 286/386 computers, then. Be aware of it, but don’t overly concern yourself—DRAM refresh is still an act of God, and there’s not a blessed thing you can do about it. Happily, the internal caches of the 486 and Pentium make DRAM refresh largely a performance non-issue on those processors.

-

The Display Adapter Cycle-Eater

+

The Display Adapter Cycle-Eater

Finally we come to the last of the cycle-eaters, the display adapter cycle-eater. There are two ways of looking at this cycle-eater on 286/386 computers: (1) It’s much worse than it was on the PC, or (2) it’s just about the same as it was on the PC.

Either way, the display adapter cycle-eater is extremely bad news on 286/386 computers and on 486s and Pentiums as well. In fact, this cycle-eater on those systems is largely responsible for the popularity of VESA local bus (VLB).

@@ -112,7 +112,7 @@ FindChar proc near
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-05.html b/11-05.html index fd3005e..31683dd 100644 --- a/11-05.html +++ b/11-05.html @@ -24,7 +24,7 @@ - +
@@ -47,13 +47,13 @@

I know that’s hard to believe, but the display adapter cycle-eater gives out just so many display memory accesses in a given time, and no more, no matter how fast the processor is. In fact, the faster the processor, the more the display adapter cycle-eater hurts the performance of instructions that access display memory. The display adapter cycle-eater is not only still present in 286/386 computers, it’s worse than ever.

What can we do about this new, more virulent form of the display adapter cycle-eater? The workaround is the same as it was on the PC: Access display memory as little as you possibly can.

-

New Instructions and Features: The 286

+

New Instructions and Features: The 286

The 286 and 386 offer a number of new instructions. The 286 has a relatively small number of instructions that the 8088 lacks, while the 386 has those instructions and quite a few more, along with new addressing modes and data sizes. We’ll discuss the 286 and the 386 separately in this regard.

The 286 has a number of instructions designed for protected-mode operations. As I’ve said, we’re not going to discuss protected mode in this book; in any case, protected-mode instructions are generally used only by operating systems. (I should mention that the 286’s protected mode brings with it the ability to address 16 MB of memory, a considerable improvement over the 8088’s 1 MB. In real mode, however, programs are still limited to 1 MB of addressable memory on the 286. In either mode, each segment is still limited to 64K.)

There are also a handful of 286-specific real-mode instructions, and they can be quite useful. BOUND checks array bounds. ENTER and LEAVE support compact and speedy stack frame construction and removal, ideal for interfacing to high-level languages such as C and Pascal (although these instructions are actually relatively slow on the 386 and its successors, and should be used with caution when performance matters). INS and OUTS are new string instructions that support efficient data transfer between memory and I/O ports. Finally, PUSHA and POPA push and pop all eight general-purpose registers.

A couple of old instructions gain new features on the 286. For one, the 286 version of PUSH is capable of pushing a constant on the stack. For another, the 286 allows all shifts and rotates to be performed for not just 1 bit or the number of bits specified by CL, but for any constant number of bits.

-

New Instructions and Features: The 386

+

New Instructions and Features: The 386

The 386 is somewhat more complex than the 286 regarding new features. Once again, we won’t discuss protected mode, which on the 386 comes with the ability to address up to 4 gigabytes per segment and 64 terabytes in all. In real mode (and in virtual-86 mode, which allows the 386 to multitask MS-DOS applications, and which is identical to real mode so far as MS-DOS programs are concerned), programs running on the 386 are still limited to 1 MB of addressable memory and 64K per segment.

The 386 has many new instructions, as well as new registers, addressing modes and data sizes that have trickled down from protected mode. Let’s take a quick look at these new real-mode features.

@@ -71,7 +71,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-06.html b/11-06.html index c6e260b..0ae047c 100644 --- a/11-06.html +++ b/11-06.html @@ -24,7 +24,7 @@ - +
@@ -39,12 +39,12 @@

Finally, it’s possible in real mode to use the 386’s new addressing modes, in which any 32-bit general-purpose register or pair of registers can be used to address memory. What’s more, multiplication of memory-addressing registers by 2, 4, or 8 for look-ups in word, doubleword, or quadword tables can be built right into the memory addressing mode. (The 32-bit addressing modes are discussed further in later chapters.) In protected mode, these new addressing modes allow you to address a full 4 gigabytes per segment, but in real mode you’re still limited to 64K, even with 32-bit registers and the new addressing modes, unless you play some unorthodox tricks with the segment registers.

Note well: Those tricks don’t necessarily work with system software such as Windows, so I’d recommend against using them. If you want 4-gigabyte segments, use a 32-bit environment such as Win32.
-

Optimization Rules: The More Things Change...

+

Optimization Rules: The More Things Change...

Let’s see what we’ve learned about 286/386 optimization. Mostly what we’ve learned is that our familiar PC cycle-eaters still apply, although in somewhat different forms, and that the major optimization rules for the PC hold true on ATs and 386-based computers. You won’t go wrong on any of these computers if you keep your instructions short, use the registers heavily and avoid memory, don’t branch, and avoid accessing display memory like the plague.

Although we haven’t touched on them, repeated string instructions are still desirable on the 286 and 386 since they provide a great deal of functionality per instruction byte and eliminate both the prefetch queue cycle-eater and branching. However, string instructions are not quite so spectacularly superior on the 286 and 386 as they are on the 8088 since non-string memory-accessing instructions have been speeded up considerably on the newer processors.

There’s one cycle-eater with new implications on the 286 and 386, and that’s the data alignment cycle-eater. From the data alignment cycle-eater we get a new rule: Word-align your word-sized variables, and start your subroutines at even addresses.

-

Detailed Optimization

+

Detailed Optimization

While the major 8088 optimization rules hold true on computers built around the 286 and 386, many of the instruction-specific optimizations no longer hold, for the execution times of most instructions are quite different on the 286 and 386 than on the 8088. We have already seen one such example of the sometimes vast difference between 8088 and 286/386 instruction execution times: MOV [WordVar],0, which has an Execution Unit execution time of 20 cycles on the 8088, has an EU execution time of just 3 cycles on the 286 and 2 cycles on the 386.

In fact, the performance of virtually all memory-accessing instructions has been improved enormously on the 286 and 386. The key to this improvement is the near elimination of effective address (EA) calculation time. Where an 8088 takes from 5 to 12 cycles to calculate an EA, a 286 or 386 usually takes no time whatsoever to perform the calculation. If a base+index+displacement addressing mode, such as MOV AX,[WordArray+bx+si], is used on a 286 or 386, 1 cycle is taken to perform the EA calculation, but that’s both the worst case and the only case in which there’s any EA overhead at all.

The elimination of EA calculation time means that the EU execution time of memory-addressing instructions is much closer to the EU execution time of register-only instructions. For instance, on the 8088 ADD [WordVar],100H is a 31-cycle instruction, while ADD DX,100H is a 4-cycle instruction—a ratio of nearly 8 to 1. By contrast, on the 286 ADD [WordVar],100H is a 7-cycle instruction, while ADD DX,100H is a 3-cycle instruction—a ratio of just 2.3 to 1.

@@ -82,7 +82,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-07.html b/11-07.html index 6031c3a..2e6d702 100644 --- a/11-07.html +++ b/11-07.html @@ -24,7 +24,7 @@ - +
@@ -64,7 +64,7 @@ Skip:

Is this always the case? No. When the prefetch queue is full, memory-accessing instructions on the 286 and 386 are much faster (relative to register-only instructions) than they are on the 8088. Given the system wait states prevalent on 286 and 386 computers, however, the prefetch queue is likely to be empty quite a bit, especially when code consisting of instructions with short EU execution times is executed. Of course, that’s just the sort of code we’re likely to write when we’re optimizing, so the performance of high-speed code is more likely to be controlled by instruction size than by EU execution time on most 286 and 386 computers, just as it is on the PC.

All of which is just a way of saying that faster memory access and EA calculation notwithstanding, it’s just as desirable to keep instructions short and memory accesses to a minimum on the 286 and 386 as it is on the 8088. And the way to do that is to use the registers as heavily as possible, use string instructions, use short forms of instructions, and the like.

The more things change, the more they remain the same....

-

POPF and the 286

+

POPF and the 286

We’ve one final 286-related item to discuss: the hardware malfunction of POPF under certain circumstances on the 286.

The problem is this: Sometimes POPF permits interrupts to occur when interrupts are initially off and the setting popped into the Interrupt flag from the stack keeps interrupts off. In other words, an interrupt can happen even though the Interrupt flag is never set to 1. Now, I don’t want to blow this particular bug out of proportion. It only causes problems in code that cannot tolerate interrupts under any circumstances, and that’s a rare sort of code, especially in user programs. However, some code really does need to have interrupts absolutely disabled, with no chance of an interrupt sneaking through. For example, a critical portion of a disk BIOS might need to retrieve data from the disk controller the instant it becomes available; even a few hundred microseconds of delay could result in a sector’s worth of data misread. In this case, one misplaced interrupt during a POPF could result in a trashed hard disk if that interrupt occurs while the disk BIOS is reading a sector of the File Allocation Table.

There is a workaround for the POPF bug. While the workaround is easy to use, it’s considerably slower than POPF, and costs a few bytes as well, so you won’t want to use it in code that can tolerate interrupts. On the other hand, in code that truly cannot be interrupted, you should view those extra cycles and bytes as cheap insurance against mysterious and erratic program crashes.

@@ -82,7 +82,7 @@ Skip:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/11-08.html b/11-08.html index aaedd08..27aaf20 100644 --- a/11-08.html +++ b/11-08.html @@ -24,7 +24,7 @@ - +
@@ -39,7 +39,7 @@

Well, there’s only one instruction other than POPF that loads the FLAGS register directly from the stack, and that’s IRET, which loads the FLAGS register from the stack as it branches, as shown in Figure 11.5. iret has no known bugs of the sort that plague POPF, so it’s certainly a candidate to replace popf in non-interruptible applications. Unfortunately, IRET loads the FLAGS register with the third word down on the stack, not the word on top of the stack, as is the case with POPF; the far return address that IRET pops into CS:IP lies between the top of the stack and the word popped into the FLAGS register.

Obviously, the segment:offset that IRET expects to find on the stack above the pushed flags isn’t present when the stack is set up for POPF, so we’ll have to adjust the stack a bit before we can substitute IRET for POPF. What we’ll have to do is push the segment:offset of the instruction after our workaround code onto the stack right above the pushed flags. IRET will then branch to that address and pop the flags, ending up at the instruction after the workaround code with the flags popped. That’s just the result that would have occurred had we executed POPF—WITH the bonus that no interrupts can accidentally occur when the Interrupt flag is 0 both before and after the pop.


Figure 11.4
  The operation of POPF. +
-->Figure 11.4  The operation of POPF.

How can we push the segment:offset of the next instruction? Well, finding the offset of the next instruction by performing a near call to that instruction is a tried-and-true trick. We can do something similar here, but in this case we need a far call, since IRET requires both a segment and an offset. We’ll also branch backward so that the address pushed on the stack will point to the instruction we want to continue with. The code works out like this:

@@ -63,7 +63,7 @@ popfskip:


Figure 11.5
  The operation of IRET. +
-->Figure 11.5  The operation of IRET.

The operation of this code is illustrated in Figure 11.6.

@@ -105,7 +105,7 @@ EMULATE_POPFmacro


Figure 11.6
  Workaround code for the POPF bug. +
-->Figure 11.6  Workaround code for the POPF bug.

The standard version of EMULATE_POPF is 6 bytes longer than POPF and much slower, as you’d expect given that it involves three branches. Anyone in his/her right mind would prefer POPF to a larger, slower, three-branch macro—given a choice. In noncode, however, there’s no choice here; the safer—if slower—approach is the best. (Having people associate your programs with crashed computers is not a desirable situation, no matter how unfair the circumstances under which it occurs.)

And now you know the nature of and the workaround for the POPF bug. Whether you ever need the workaround or not, it’s a neatly packaged example of the tremendous flexibility of the x86 instruction set.


@@ -121,7 +121,7 @@ EMULATE_POPFmacro
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/12-01.html b/12-01.html index 58f7668..1e578fa 100644 --- a/12-01.html +++ b/12-01.html @@ -24,7 +24,7 @@ - +
@@ -36,25 +36,24 @@


-

Chapter 12
Pushing the 486 -

-

It’s Not Just a Bigger 386

+

Chapter 12
Pushing the 486

+

It’s Not Just a Bigger 386

So this traveling salesman is walking down a road, and he sees a group of men digging a ditch with their bare hands. “Whoa, there!” he says. “What you guys need is a Model 8088 ditch digger!” And he whips out a trowel and sells it to them.

A few days later, he stops back around. They’re happy with the trowel, but he sells them the latest ditch-digging technology, the Model 80286 spade. That keeps them content until he stops by again with a Model 80386 shovel (a full 32 inches wide, with a narrow point to emulate the trowel), and that holds them until he comes back around with what they really need: a Model 80486 bulldozer.

Having reached the top of the line, the salesman doesn’t pay them a call for a while. When he does, not only are they none too friendly, but they’re digging with the 80386 shovel; the bulldozer is sitting off to one side. “Why on earth are you using that shovel?” the salesman asks. “Why aren’t you digging with the bulldozer?”

“Well, Lord knows we tried,” says the foreman, “but it was all we could do just to lift the damn thing!”

Substitute “processor” for the various digging implements, and you get an idea of just how different the optimization rules for the 486 are from what you’re used to. Okay, it’s not quite that bad—but upon encountering a processor where string instructions are often to be avoided and memory-to-register MOVs are frequently as fast as register-to-register MOVs, Dorothy was heard to exclaim (before she sank out of sight in a swirl of hopelessly mixed metaphors), “I don’t think we’re in Kansas anymore, Toto.”

-

Enter the 486

+

Enter the 486

No chip that is a direct, fully compatible descendant of the 8088, 286, and 386 could ever be called a RISC chip, but the 486 certainly contains RISC elements, and it’s those elements that are most responsible for making 486 optimization unique. Simple, common instructions are executed in a single cycle by a RISC-like core processor, but other instructions are executed pretty much as they were on the 386, where every instruction takes at least 2 cycles. For example, MOV AL, [TestChar] takes only 1 cycle on the 486, assuming both instruction and data are in the cache—3 cycles faster than the 386—but STOSB takes 5 cycles, 1 cycle slower than on the 386. The floating-point execution unit inside the 486 is also much faster than the 387 math coprocessor, largely because, being in the same silicon as the CPU (the 486 has a math coprocessor built in), it is more tightly coupled. The results are sometimes startling: FMUL (floating point multiply) is usually faster on the 486 than IMUL (integer multiply)!

An encyclopedic approach to 486 optimization would take a book all by itself, so in this chapter I’m only going to hit the highlights of 486 optimization, touching on several optimization rules, some documented, some not. You might also want to check out the following sources of 486 information: i486 Microprocessor Programmer’s Reference Manual, from Intel; “8086 Optimization: Aim Down the Middle and Pray,” in the March, 1991 Dr. Dobb’s Journal; and “Peak Performance: On to the 486,” in the November, 1990 Programmer’s Journal.

-

Rules to Optimize By

+

Rules to Optimize By

In Appendix G of the i486 Microprocessor Programmers Reference Manual, Intel lists a number of optimization techniques for the 486. While neither exhaustive (we’ll look at two undocumented optimizations shortly) nor entirely accurate (we’ll correct two of the rules here), Intel’s list is certainly a good starting point. In particular, the list conveys the extent to which 486 optimization differs from optimization for earlier x86 processors. Generally, I’ll be discussing optimization for real mode (it being the most widely used mode at the moment), although many of the rules should apply to protected mode as well.

486 optimization is generally more precise and less frustrating than optimization for other x86 processors because every 486 has an identical internal cache. Whenever both the instructions being executed and the data the instructions access are in the cache, those instructions will run in a consistent and calculatable number of cycles on all 486s, with little chance of interference from the prefetch queue and without regard to the speed of external memory.

In other words, for cached code (which time-critical code almost always is), performance is predictable and can be calculated with good precision, and those calculations will apply on any 486. However, “predictable” doesn’t mean “trivial”; the cycle times printed for the various instructions are not the whole story. You must be aware of all the rules, documented and undocumented, that go into calculating actual execution times—and uncovering some of those rules is exactly what this chapter is about.

-

The Hazards of Indexed Addressing

+

The Hazards of Indexed Addressing

Rule #1: Avoid indexed addressing (that is, try not to use either two registers or scaled addressing to point to memory).

Intel cautions against using indexing to address memory because there’s a one-cycle penalty for indexed addressing. True enough—but “indexed addressing” might not mean what you expect.

@@ -98,7 +97,7 @@ LoopTop:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/12-02.html b/12-02.html index c934f06..d6ffb2d 100644 --- a/12-02.html +++ b/12-02.html @@ -24,7 +24,7 @@ - +
@@ -42,7 +42,7 @@

All this fuss over one cycle! You might well wonder how much difference one cycle could make. After all, on the 8088, effective address calculations take a minimum of 5 cycles. On the 486, however, 1 cycle is a big deal because many instructions, including most register-only instructions (MOV, ADD, CMP, and so on) execute in just 1 cycle. In particular, MOVs to and from memory execute in 1 cycle—if they’re not hampered by something like indexed addressing, in which case they slow to half speed (or worse, as we will see shortly).

For example, consider the summing example shown earlier. The version that uses base+index ([BX+SI]) addressing executes in eight cycles per loop. As expected, the version that uses base ([SI]) addressing runs one cycle faster, at seven cycles per loop. However, the loop code executes so fast on the 486 that the single cycle saved by using base addressing makes the whole loop more than 14 percent faster.

In a key loop on the 486, 1 cycle can indeed matter.

-

Calculate Memory Pointers Ahead of Time

+

Calculate Memory Pointers Ahead of Time

Rule #2: Don’t use a register as a memory pointer during the next two cycles after loading it.

Intel states that if the destination of one instruction is used as the base addressing component of the next instruction, then a one-cycle penalty is imposed. This rule, unlike anything ever before seen in the x86 family, reflects the heavily pipelined nature of the 486. Apparently, the 486 starts each effective address calculation before the start of the instruction that will need it, as shown in Figure 12.1; this effectively makes the address calculation time vanish, because it happens while the preceding instruction executes.

@@ -82,7 +82,7 @@ LoopTop:

Considering that MOV normally takes only one cycle total, that’s quite a loss. For example, the postdecrement loop shown above is 2 full cycles faster than the preincrement loop, resulting in a 29 percent improvement in the performance of the entire loop. But wait, there’s more. If a register is loaded 2 cycles (which generally means 2 instructions, but, because some 486 instructions take more than 1 cycle,


Figure 12.1
  One-cycle-ahead address pipelining. +
-->Figure 12.1  One-cycle-ahead address pipelining.

the 2 are not always equivalent) before it’s used to point to memory, 1 cycle is lost. Therefore, whereas this code

@@ -121,9 +121,9 @@ jnz LoopTop

Clearly, there’s considerable optimization potential in careful rearrangement of 486 code.


Figure 12.2
  Two-cycle-ahead address pipelining. +
-->Figure 12.2  Two-cycle-ahead address pipelining.

-

Caveat Programmor

+

Caveat Programmor

A caution: I’m quite certain that the 2-cycle-ahead addressing pipeline interruption penalty I’ve described exists in the two 486s I’ve tested. However, there’s no guarantee that Intel won’t change this aspect of the 486 in the future, especially given that the documentation indicates otherwise. Perhaps the 2-cycle penalty is the result of a bug in the initial steps of the 486, and will revert to the documented 1-cycle penalty someday; likewise for the undocumented optimizations I’ll describe below. Nonetheless, none of the optimizations I suggest would hurt performance even if the undocumented performance characteristics of the 486 were to vanish, and they certainly will help performance on at least some 486s right now, so I feel they’re well worth using.


@@ -138,7 +138,7 @@ jnz LoopTop
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/12-03.html b/12-03.html index 7c3cb3e..4c9d4fc 100644 --- a/12-03.html +++ b/12-03.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


There is, of course, no guarantee that I’m entirely correct about the optimizations discussed in this chapter. Without knowing the internals of the 486, all I can do is time code and make inferences from the results; I invite you to deduce your own rules and cross-check them against mine. Also, most likely there are other optimizations that I’m unaware of. If you have further information on these or any other undocumented optimizations, please write and let me know. And, of course, if anyone from Intel is reading this and wants to give us the gospel truth, please do!

-

Stack Addressing and Address Pipelining

+

Stack Addressing and Address Pipelining

Rule #2A: Rule #2 sometimes, but not always, applies to the stack pointer when it is implicitly used to point to memory.

Intel states that the stack pointer is an implied destination register for CALL, ENTER, LEAVE, RET, PUSH, and POP (which alter (E)SP), and that it is the implied base addressing register for PUSH, POP, and RET (which use (E)SP to address memory). Intel then implies that the aforementioned addressing pipeline penalty is incurred whenever the stack pointer is used as a destination by one of the first set of instructions and is then immediately used to address memory by one of the second set. This raises the specter of unpleasant programming contortions such as intermixing PUSHes and POPs with other instructions to avoid interrupting the addressing pipeline. Fortunately, matters are actually not so grim as Intel’s documentation would indicate; my tests indicate that the addressing pipeline penalty pops up only spottily when the stack pointer is involved.

@@ -82,7 +82,7 @@ pop ax

loses two cycles for the same reason.

I certainly haven’t tried all possible combinations, but the results so far indicate that the stack pointer incurs the addressing pipeline penalty only if (E)SP is the explicit destination of one instruction and is then used by one of the two following instructions to address memory. So, for instance, SP isn’t the explicit operand of POP AX—AX is—and no cycles are lost if POP AX is followed by POP or RET. Happily, then, we need not worry about the sequence in which we use PUSH and POP. However, adding to, moving to, or subtracting from the stack pointer should ideally be done at least two cycles before PUSH, POP, RET, or any other instruction that uses the stack pointer to address memory.

-

Problems with Byte Registers

+

Problems with Byte Registers

There are two ways to lose cycles by using byte registers, and neither of them is documented by Intel, so far as I know. Let’s start with the lesser and simpler of the two.

Rule #3: Do not load a byte portion of a register during one instruction, then use that register in its entirety as a source register during the next instruction.

@@ -133,7 +133,7 @@ xlat
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/12-04.html b/12-04.html index 465fb33..e4fc9a5 100644 --- a/12-04.html +++ b/12-04.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


You don’t need to understand every corner of the 486 universe unless you’re a diehard ASMhead who does this stuff for fun. Just learn enough to be able to speed up the key portions of your programs, and spend the rest of your time on a fast design and overall implementation.

-

More Fun with Byte Registers

+

More Fun with Byte Registers

Rule #4: Don’t load any byte register exactly 2 cycles before using any register to address memory.

This, the last of this chapter’s rules, is the strangest of the lot. If any byte register is loaded, and then two cycles later any register is used to point to memory, one cycle is lost. So, for example, this code

@@ -78,7 +78,7 @@ mov ax,[bx]

A more sophisticated programmer would expect to lose one cycle, because BX is loaded two cycles before being used to address memory. In fact, though, this code takes 5 cycles—2 cycles, or 67 percent, longer than normal. Why? Well, under normal conditions, loading a byte register—CL in this case—one cycle before using a register to address memory produces no penalty; loading 2 cycles ahead is the only case that normally incurs a penalty. However, think of Rule #4 as meaning that loading a byte register disrupts the memory addressing pipeline as it starts up. Viewed that way, we can see that MOV BX,OFFSET MemVar interrupts the addressing pipeline, forcing it to start again, and then, presumably, MOV CL,AL interrupts the pipeline again because the pipeline is now on its first cycle: the one that loading a byte register can affect.

I know—it seems awfully complicated. It isn’t, really. Generally, try not to use byte destinations exactly two cycles before using a register to address memory, and try not to load a register either one or two cycles before using it to address memory, and you’ll be fine.
-

Timing Your Own 486 Code

+

Timing Your Own 486 Code

In case you want to do some 486 performance analysis of your own, let me show you how I arrived at one of the above conclusions; at the same time, I can warn you of the timing hazards of the cache. Listings 12.1 and 12.2 show the code I ran through the Zen timer in order to establish the effects of loading a byte register before using a register to address memory. Listing 12.1 ran in 120 µs on a 33 MHz 486, or 4 cycles per repetition (120 µs/1000 repetitions = 120 ns per repetition; 120 ns per repetition/30 ns per cycle = 4 cycles per repetition); Listing 12.2 ran in 90 µs, or 3 cycles, establishing that loading a byte register costs a cycle only when it’s performed exactly 2 cycles before addressing memory.

LISTING 12.1 LST12-1.ASM

@@ -128,7 +128,7 @@ Done:

Note that Listings 12.1 and 12.2 each repeat the timing of the code under test a second time, to make sure that the instructions are in the cache on the second pass, the one for which results are displayed. Also note that the code is less than 8K in size, so that it can all fit in the 486’s 8K internal cache. If I double the REPT value in Listing 12.2 to 2,000, making the test code larger than 8K, the execution time more than doubles to 224 µs, or 3.7 cycles per repetition; the extra seven-tenths of a cycle comes from fetching non-cached instruction bytes.

Whenever you see non-integral timing results of this sort, it’s a good bet that the test code or data isn’t cached.
-

The Story Continues

+

The Story Continues

There’s certainly plenty more 486 lore to explore, including the 486’s unique prefetch queue, more optimization rules, branching optimizations, performance implications of the cache, the cost of cache misses for reads, and the implications of cache write-through for writes. Nonetheless, we’ve covered quite a bit of ground in this chapter, and I trust you’ve gotten a feel for the considerable extent to which 486 optimization differs from what you’re used to. Odd as 486 optimization is, though, it’s well worth mastering, for the 486 is, at its best, so staggeringly fast that carefully crafted 486 code can do more than twice as much per cycle as the best 386 code—which makes it perhaps 50 times as fast as optimized code for the original PC.

Sometimes it is hard to believe we’re still in Kansas!


@@ -144,7 +144,7 @@ Done:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/13-01.html b/13-01.html index d1bc4f0..1f9ad1b 100644 --- a/13-01.html +++ b/13-01.html @@ -24,7 +24,7 @@ - +
@@ -36,14 +36,13 @@


-

Chapter 13
Aiming the 486 -

-

Pipelines and Other Hazards of the High End

+

Chapter 13
Aiming the 486

+

Pipelines and Other Hazards of the High End

It’s a sad but true fact that 84 percent of American schoolchildren are ignorant of 92 percent of American history. Not my daughter, though. We recently visited historical Revolutionary-War-vintage Fort Ticonderoga, and she’s now 97 percent aware of a key element of our national heritage: that the basic uniform for soldiers in those days was what appears to be underwear, plus a hat so that no one could complain that they were undermining family values. Ha! Just kidding! Actually, what she learned was that in those days, it was pure coincidence if a cannonball actually hit anything it was aimed at, which isn’t surprising considering the lack of rifling, precision parts, and ballistics. The guides at the fort shot off three cannons; the closest they came to the target was about 50 feet, and that was only because the wind helped. I think the idea in early wars was just to put so much lead in the air that some of it was bound to hit something; preferably, but not necessarily, the enemy.

Nowadays, of course, we have automatic weapons that allow a teenager to singlehandedly defeat the entire U.S. Army, not to mention so-called “smart” bombs, which are smart in the sense that they can seek out and empty a taxpayer’s wallet without being detected by radar. There’s an obvious lesson here about progress, which I leave you to deduce for yourselves.

Here’s the same lesson, in another form. Ten years ago, we had a slow processor, the 8088, for which it was devilishly hard to optimize, and for which there was no good optimization documentation available. Now we have a processor, the 486, that’s 50 to 100 times faster than the 8088—and for which there is no good optimization documentation available. Sure, Intel provides a few tidbits on optimization in the back of the i486 Microprocessor Programmer’s Reference Manual, but, as I discussed in Chapter 12, that information is both incomplete and not entirely correct. Besides, most assembly language programmers don’t bother to read Intel’s manuals (which are extremely informative and well done, but only slightly more fun to read than the phone book), and go right on programming the 486 using outdated 8088 optimization techniques, blissfully unaware of a new and heavily mutated generation of cycle-eaters that interact with their code in ways undreamt of even on the 386.

For example, consider how Terje Mathisen doubled the speed of his word-counting program on a 486 simply by shuffling a couple of instructions.

-

486 Pipeline Optimization

+

486 Pipeline Optimization

I’ve mentioned Terje Mathisen in my writings before. Terje is an assembly language programmer extraordinaire, and author of the incredibly fast public-domain word-counting program WC (which comes complete with source code; well worth a look, if you want to see what really fast code looks like). Terje’s a regular participant in the ibm.pc/fast.code topic on Bix. In a thread titled “486 Pipeline Optimization, or TANSTATFC (There Ain’t No Such Thing As The Fastest Code),” he detailed the following optimization to WC, perhaps the best example of 486 pipeline optimization I’ve yet seen.

Terje’s inner loop originally looked something like the code in Listing 13.1. (I’ve taken a few liberties for illustrative purposes.) Of course, Terje unrolls this loop a few times (128 times, to be exact). By the way, in Listing 13.1 you’ll notice that Terje counts not only words but also lines, at a rate of three instructions for every two characters!

LISTING 13.1 L13-1.ASM

@@ -58,7 +57,7 @@ add dx,[bx+8000h] ;increment word and line count

Listing 13.1 looks as tight as it could be, with just two one-cycle instructions, one two-cycle instruction, and no branches. It is tight, but those three instructions actually take a minimum of 8 cycles to execute, as shown in Figure 13.1. The problem is that DI is loaded just before being used to address memory, and that costs 2 cycles because it interrupts the 486’s internal instruction pipeline. Likewise, BX is loaded just before being used to address memory, costing another two cycles. Thus, this loop takes twice as long as cycle counts would seem to indicate, simply because two registers are loaded immediately before being used, disrupting the 486’s pipeline.

Listing 13.2 shows Terje’s immediate response to these pipelining problems; he simply swapped the instructions that load DI and BL. This one change cut execution time per character pair from eight cycles to five cycles! The load of BL is now separated by one instruction from the use of BX to address memory, so the pipeline penalty is reduced from two cycles to one cycle. The load of DI is also separated by one instruction from the use of DI to address memory (remember, the loop is unrolled, so the last instruction is followed by the first instruction), but because the intervening instruction takes two cycles, there’s no penalty at all.


Figure 13.1
  Cycle-eaters in the original WC. +
-->Figure 13.1  Cycle-eaters in the original WC.

Remember, pipeline penalties diminish with increasing number of cycles, not instructions, between the pipeline disrupter and the potentially affected instruction. @@ -86,7 +85,7 @@ add dx,[bx+8000h] ;increment word and line count
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/13-02.html b/13-02.html index 08984c3..dca83af 100644 --- a/13-02.html +++ b/13-02.html @@ -24,7 +24,7 @@ - +
@@ -58,7 +58,7 @@ mov ax,[bx+8000h] ;get increments for next time

I’d like to point out two fairly remarkable things. First, the single cycle that Terje saved in Listing 13.4 sped up his entire word-counting engine by 25 percent or more; Listing 13.4 is fully twice as fast as Listing 13.1—all the result of nothing more than shifting an instruction and splitting another into two operations. Second, Terje’s word-counting engine can process more than 16 million characters per second on a 486/33.

Clever 486 optimization can pay off big. QED.

-

BSWAP: More Useful Than You Might Think

+

BSWAP: More Useful Than You Might Think

There are only 3 non-system instructions unique to the 486. None is earthshaking, but they have their uses. Consider BSWAP. BSWAP does just what its name implies, swapping the bytes (not bits) of a 32-bit register from one end of the register to the other, as shown in Figure 13.2. (BSWAP can only work with 32-bit registers; memory locations and 16-bit registers are not valid operands.) The obvious use of BSWAP is to convert data from Intel format (least significant byte first in memory, also called little endian) to Motorola format (most significant byte first in memory, or big endian), like so:

@@ -69,7 +69,7 @@ stosd
 
 

BSWAP can also be useful for reversing the order of pixel bits from a bitmap so that they can be rotated 32 bits at a time with an instruction such as ROR EAX,1. Intel’s byte ordering for multiword values (least-significant byte first) loads pixels in the wrong order, so far as word rotation is concerned, but BSWAP can take care of that.


Figure 13.2
  BSWAP in operation. +
-->Figure 13.2  BSWAP in operation.

As it turns out, though, BSWAP is also useful in an unexpected way, having to do with making efficient use of the upper half of 32-bit registers. As any assembly language programmer knows, the x86 register set is too small; or, to phrase that another way, it sure would be nice if the register set were bigger. As any 386/486 assembly language programmer knows, there are many cases in which 16 bits is plenty. For example, a 16-bit scan-line counter generally does the trick nicely in a video driver, because there are very few video devices with more than 65,535 addressable scan lines. Combining these two observations yields the obvious conclusion that it would be great if there were some way to use the upper and lower 16 bits of selected 386 registers as separate 16-bit registers, effectively increasing the available register space.

Unfortunately, the x86 instruction set doesn’t provide any way to work directly with only the upper half of a 32-bit register. The next best solution is to rotate the register to give you access in the lower 16 bits to the half you need at any particular time, with code along the lines of that in Listing 13.5. Having to rotate the 16-bit fields into position certainly isn’t as good as having direct access to the upper half, but surely it’s better than having to get the values out of memory, isn’t it?

@@ -102,7 +102,7 @@ looptop:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/13-03.html b/13-03.html index 637d99e..d2c95ae 100644 --- a/13-03.html +++ b/13-03.html @@ -24,7 +24,7 @@ - +
@@ -53,7 +53,7 @@ looptop: jnz looptop -

Pushing and Popping Memory

+

Pushing and Popping Memory

Pushing or popping a memory location, as in PUSH WORD PTR [BX] or POP [MemVar], is a compact, easy way to get a value onto or off of the stack, especially when pushing parameters for calling a C-compatible function. However, on a 486, these are unattractive instructions from a performance perspective. Pushing a memory location takes four cycles; by contrast, loading a memory location into a register takes only one cycle, and pushing a register takes just 1 more cycle, for a total of two cycles. Therefore,

@@ -74,7 +74,7 @@ push   word ptr [bx]
 

Why is it that such a convenient operation as pushing or popping memory is so slow? The rule on the 486 is that simple operations, which can be executed in a single cycle by the 486’s RISC core, are fast; whereas complex operations, which must be carried out in microcode just as they were on the 386, are almost all relatively slow. Slow, complex operations include all the string instructions except REP MOVS, as well as XLAT, LOOP, and, of course, PUSH mem and POP mem.

Whenever possible, try to use the 486’s 1-cycle instructions, including MOV, ADD, SUB, CMP, ADC, SBB, XOR, AND, OR, TEST, LEA, and PUSH reg and POP reg. These instructions have an added benefit in that it’s often possible to rearrange them for maximum pipeline efficiency, as is the case with Terje’s optimization described earlier in this chapter.
-

Optimal 1-Bit Shifts and Rotates

+

Optimal 1-Bit Shifts and Rotates

On a 486, the n-bit forms of the shift and rotate instructions—as in ROR AX,2 and SHL BX,9—are 2-cycle instructions, but the 1-bit forms—as in ROR AX,1 and SHL BX,1—are 3-cycle instructions. Go figure.

Assemblers default to the 1-bit instruction for 1-bit shifts and rotates. That’s not unreasonable since the 1-bit form is a byte shorter and is just as fast as the n-bit forms on a 386 and faster on a 286, and the n-bit form doesn’t even exist on an 8088. In a really critical loop, however, it might be worth hand-assembling the n-bit form of a single-bit shift or rotate in order to save that cycle. The easiest way to do this is to assemble a 2-bit form of the desired instruction, as in SHL AX,2, then look at the hex codes that the assembler generates and use DB to insert them in your program code, with the value two replaced with the value one. For example, you could determine that SHL AX,2 assembles to the bytes 0C1H 0E0H 002H, either by looking at the disassembly in a debugger or by having the assembler generate a listing file. You could then insert the n-bit version of SHL AX,1 in your code as follows:

@@ -98,7 +98,7 @@ mov dx,ax
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/13-04.html b/13-04.html index e57e3f3..2157c0f 100644 --- a/13-04.html +++ b/13-04.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

32-Bit Addressing Modes

+

32-Bit Addressing Modes

The 386 and 486 both support 32-bit addressing modes, in which any register may serve as the base memory addressing register, and almost any register may serve as the potentially scaled index register. For example,

@@ -89,7 +89,7 @@ LoopTop:
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-01.html b/14-01.html index ee4c1b1..1857e35 100644 --- a/14-01.html +++ b/14-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 14
Boyer-Moore String Searching -

-

Optimizing a Pretty Optimum Search Algorithm

+

Chapter 14
Boyer-Moore String Searching

+

Optimizing a Pretty Optimum Search Algorithm

When you seem to be stumped, stop for a minute and think. All the information you need may be right in front of your nose if you just look at things a little differently. Here’s a case in point:

When I was in college, I used to stay around campus for the summer. Oh, I’d take a course or two, but mostly it was an excuse to hang out and have fun. In that spirit, my girlfriend, Adrian (not my future wife, partly for reasons that will soon become apparent), bussed in to spend a week, sharing a less-than-elegant $150 per month apartment with me and, by necessity, my roommate.

Our apartment was pretty much standard issue for two male college students; maybe even a cut above. The dishes were usually washed, there was generally food in the refrigerator, and nothing larger than a small dog had taken up permanent residence in the bathroom. However, there was one sticking point (literally): the kitchen floor. This floor—standard tile, with a nice pattern of black lines on an off-white background (or so we thought)—had never been cleaned. By which I mean that I know for a certainty that we had never cleaned it, but I suspect that it had in fact not been cleaned since the Late Jurassic, or possibly earlier. Our feet tended to stick to it; had the apartment suddenly turned upside-down, I think we’d all have been hanging from the ceiling.

@@ -47,7 +46,7 @@

She stamped her foot (really; the only time I’ve ever seen it happen), and said, “No, you jerks! The kitchen floor! Look at the floor! I cleaned it!”

The floor really did look amazing. It was actually all white; the black lines had been grooves filled with dirt. We assured her that it looked terrific, it just wasn’t that obvious until you knew to look for it; anyone would tell you that it wasn’t the kind of thing that jumped out at you, but it really was great, no kidding. We had almost smoothed things over, when a friend walked in, looked around with a start, and said, “Hey! Did you guys put in a new floor?”

As I said, sometimes everything you need to know is right in front of your nose. Which brings us to Boyer-Moore string searching.

-

String Searching Refresher

+

String Searching Refresher

I’ve discussed string searching earlier in this book, in Chapters 5 and 9. You may want to refer back to these chapters for some background on string searching in general. I’m also going to use some of the code from that chapter as part of this chapter’s test suite. For further information, you may want to refer to the discussion of string searching in the excellent Algorithms in C, by Robert Sedgewick (Addison-Wesley), which served as the primary reference for this chapter. (If you look at Sedgewick, be aware that in the Boyer-Moore listing on page 288, there is a mistake: “j > 0” in the for loop should be “j >= 0,” unless I’m missing something.)

String searching is the simple matter of finding the first occurrence of a particular sequence of bytes (the pattern) within another sequence of bytes (the buffer). The obvious, brute-force approach is to try every possible match location, starting at the beginning of the buffer and advancing one position after each mismatch, until either a match is found or the buffer is exhausted. There’s even a nifty string instruction, REPZ CMPS, that’s perfect for comparing the pattern to the contents of the buffer at each location. What could be simpler?

We have some important information that we’re not yet using, though. Typically, the buffer will contain a wide variety of bytes. Let’s assume that the buffer contains text, in which case there will be dozens of different characters; and although the distribution of characters won’t usually be even, neither will any one character constitute half the buffer, or anything close. A reasonable conclusion is that the first character of the pattern will rarely match the first character of the buffer location currently being checked. This allows us to use the speedy REPNZ SCASB to whiz through the buffer, eliminating most potential match locations with single repetitions of SCASB. Only when that first character does (infrequently) match must we drop back to the slower REPZ CMPS approach.

@@ -70,7 +69,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-02.html b/14-02.html index ce15fff..1286a8e 100644 --- a/14-02.html +++ b/14-02.html @@ -24,7 +24,7 @@ - +
@@ -36,7 +36,7 @@


-

The Boyer-Moore Algorithm

+

The Boyer-Moore Algorithm

All our a priori knowledge of string searching is stated above, but there’s another sort of knowledge—knowledge that’s generated dynamically. As we search through the buffer, we acquire information each time we check for a match. One sort of information that we acquire is based on partial matches; we can often skip ahead after partial matches because (take a deep breath!) by partially matching, we have already implicitly done a comparison of the partially matched buffer characters with all possible pattern start locations that overlap those partially-matched bytes.

If that makes your head hurt, it should—and don’t worry. This line of thinking, which is the basis of the Knuth-Morris-Pratt algorithm and half the basis of the Boyer-Moore algorithm, is what gives Boyer-Moore its reputation for inscrutability. That reputation is well deserved for this aspect (which I will not discuss further in this book), but there’s another part of Boyer-Moore that’s easily understood, easily implemented, and highly effective.

Consider this: We’re searching for the pattern “ABC,” beginning the search at the start (offset 0) of a buffer containing “ABZABC.” We match on ‘A,’ we match on ‘B,’ and we mismatch on ‘C’; the buffer contains a ‘Z’ in this position. What have we learned? Why, we’ve learned not only that the pattern doesn’t match the buffer starting at offset 0, but also that it can’t possibly match starting at offset 1 or offset 2, either! After all, there’s a ‘Z’ in the buffer at offset 2; since the pattern doesn’t contain a single ‘Z,’ there’s no way that the pattern can match starting at any location from which it would span the ‘Z’ at offset 2. We can just skip straight from offset 0 to offset 3 and continue, saving ourselves two comparisons.

@@ -46,18 +46,18 @@

We learn nothing new from a mismatch on the leftmost character, except that the pattern can’t match starting at that location. A mismatch on the rightmost character, however, tells us about the possibilities of the pattern matching starting at every buffer location from which the pattern spans the mismatch location. If the mismatched character in the buffer doesn’t appear in the pattern, then we’ve just eliminated not one potential match, but as many potential matches as there are characters in the pattern; that’s how many locations there are in the buffer that might have matched, but have just been shown not to, because they overlap the mismatched character that doesn’t belong in the pattern. In this case, we can skip ahead by the full pattern length in the buffer! This is how we can outperform even REPNZ SCASB; REPNZ SCASB has to check every byte in the buffer, but Boyer-Moore doesn’t.

Figure 14.1 illustrates the operation of a Boyer-Moore search when the rightcharacter of the search pattern (which is the first character that’s compared at each location because we’re comparing backwards) mismatches with a buffer character that appears nowhere in the pattern. Figure 14.2 illustrates the operation of a partial match when the mismatch occurs with a character that’s not a pattern member. In this case, we can only skip ahead past the mismatch location, resulting in an advance of fewer bytes than the pattern length, and potentially as little as the same single byte distance by which the standard search approach advances.


Figure 14.1
  Mismatch on first character checked. +
-->Figure 14.1  Mismatch on first character checked.

What if the mismatch occurs with a buffer character that does occur in the pattern? Then we can’t skip past the mismatch location, but we can skip to whatever location aligns the rightmost occurrence of that character in the pattern with the mismatch location, as shown in Figure 14.3.

Basically, we exercise our right as members of a free society to compare strings in whichever direction we choose, and we choose to do so right to left, rather than the more intuitive left to right. Whenever we find a mismatch, we see what we can learn from the buffer character that failed to match the pattern. Imagine that we move the pattern to the right across the mismatch location until we find a start location that the mismatch does not eliminate as a possible match for the pattern. If the mismatch character doesn’t appear in the pattern, the pattern can move clear past the mismatch location. Otherwise, the pattern moves until a matching pattern byte lies atop the mismatch. That’s all there is to it!


Figure 14.2
  Mismatch on third character checked. +
-->Figure 14.2  Mismatch on third character checked.

-

Boyer-Moore: The Good and the Bad

+

Boyer-Moore: The Good and the Bad

The worst case for this version of Boyer-Moore is that the pattern mismatches on the leftmost character—the last character compared—every time. Again, not very likely, but it is true that this version of Boyer-Moore performs better as there are fewer and shorter partial matches; ideally, the rightmost character would never match until the full match location was reached. Longer patterns, which make for longer skips, help Boyer-Moore, as does a long distance to the match location, which helps diffuse the overhead of building the table of distances to skip ahead on all the possible mismatch values.


Figure 14.3
  Mismatch on character that appears in pattern. +
-->Figure 14.3  Mismatch on character that appears in pattern.

The best case for Boyer-Moore is good indeed: About N/M comparisons are required, where N is the buffer length and M is the pattern length. This reflects the ability of Boyer-Moore to skip ahead by a full pattern length on a complete mismatch.


@@ -73,7 +73,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-03.html b/14-03.html index 17b9743..3fd74f1 100644 --- a/14-03.html +++ b/14-03.html @@ -24,7 +24,7 @@ - +
@@ -127,7 +127,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-04.html b/14-04.html index 241583f..cacf79b 100644 --- a/14-04.html +++ b/14-04.html @@ -24,7 +24,7 @@ - +
@@ -198,7 +198,7 @@ void main() {
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-05.html b/14-05.html index 7a53f77..c6f02fc 100644 --- a/14-05.html +++ b/14-05.html @@ -24,7 +24,7 @@ - +
@@ -214,7 +214,7 @@ _FindString endp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/14-06.html b/14-06.html index 8afc34e..3c6bdfc 100644 --- a/14-06.html +++ b/14-06.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


Table 14.1 represents a limited and decidedly unscientific comparison of searching techniques. Nonetheless, the overall trend is clear: For all but the shortest patterns, well-implemented Boyer-Moore is generally as good as or better than—sometimes much better than—brute-force searching. (For short patterns, you might want to use REPNZ SCASB, thereby getting the best of both worlds.)

Know your data and use your smarts. Don’t stop thinking just because you’re implementing a big-name algorithm; you know more than it does.

-

Further Optimization of Boyer-Moore

+

Further Optimization of Boyer-Moore

We can do substantially better yet than Listing 14.3 if we’re willing to accept tighter limits on the data. Limiting the length of the searched-for pattern to a maximum of 255 bytes allows us to use the XLAT instruction and generally tighten the critical loop. (Be aware, however, that XLAT is a relatively expensive instruction on the 486 and Pentium.) Putting a copy of the searched-for string at the end of the search buffer as a sentinel, so that the search never fails, frees us from counting down the buffer length, and makes it easy to unroll the critical loop. Listing 14.4, which implements these optimizations, is about 60 percent faster than Listing 14.3.

LISTING 14.4 L14-4.ASM

@@ -192,7 +192,7 @@ _FindString endp

Note that Table 14.1 includes the time required to build the skip table each time FindString is called. This time could be eliminated for all but the first search when repeatedly searching for a particular pattern, by building the skip table externally and passing a pointer to it as a parameter.

-

Know What You Know

+

Know What You Know

Here we’ve turned up our nose at a repeated string instruction, we’ve gone against the grain by comparing backward, and yet we’ve speeded up our code quite a bit. All this without any restrictions or special requirements (excluding Listing 14.4)—and without any new information. Everything we needed was sitting there all along; we just needed to think to look at it.

As Yogi Berra might put it, “You don’t know what you know until you know it.”


@@ -208,7 +208,7 @@ _FindString endp
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/15-01.html b/15-01.html index 8d6db73..e408758 100644 --- a/15-01.html +++ b/15-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 15
Linked Lists and plain Unintended Challenges -

-

Unfamiliar Problems with Familiar Data Structures

+

Chapter 15
Linked Lists and plain Unintended Challenges

+

Unfamiliar Problems with Familiar Data Structures

After 21 years, this story still makes me wince. Oh, the humiliations I suffer for your enlightenment....

It wasn’t until ninth grade that I had my first real girlfriend. Okay, maybe I was a little socially challenged as a kid, but hey, show me a good programmer who wasn’t; it goes with the territory. Her name was Jeannie Schweigert, and she was about four feet tall, pretty enough, and female—and willing to go out with me, which made her approximately as attractive as Cheryl Tiegs, in my book.

@@ -48,7 +47,7 @@

I was a pretty mature teenager, so this was only slightly more traumatic than leading the Tournament of Roses parade in my underwear. On the next try, though, I did manage to get the hang of this kissing business, and eventually even went on to have a child. (Not with Jeannie, I might add; the mind boggles at the mess I could have made of that with her.) As it turns out, none of that stuff is particularly difficult; in fact, it’s kind of enjoyable, wink, wink, say no more.

When you’re dealing with something new, a little knowledge goes a long way. When it comes to kissing, we have to fumble along the learning curve on our own, but there are all sorts of resources to help speed up the learning process when it comes to programming. The basic mechanisms of programming—searches, sorts, parsing, and the like—are well-understood and superbly well-documented. Treat yourself to a book like Algorithms, by Robert Sedgewick (Addison Wesley), or Knuth’s The Art of Computer Programming series (also from Addison Wesley; and where was Knuth with The Art of Kissing when I needed him?), or practically anything by Jon Bentley, and when you tackle a new area, give yourself a head start. There’s still plenty of room for inventiveness and creativity on your part, but why not apply that energy on top of the knowledge that’s already been gained, instead of reinventing the wheel? I know, reinventing the wheel is just the kind of challenge programmers love—but can you really afford to waste the time? And do you honestly think that you’re so smart that you can out-think Knuth, who’s spent a lifetime at this stuff and happens to be a genius?

Maybe you can—but I sure can’t. For example, consider the evolution of my understanding of linked lists.

-

Linked Lists

+

Linked Lists

Linked lists are data structures composed of discrete elements, or nodes, joined together with links. In C, the links are typically pointers. Like all data structures, linked lists have their strengths and their weaknesses. Primary among the strengths are: simplicity; speedy sequential processing; ease and speed of insertion and deletion; the ability to mix nodes of various sizes and types; and the ability to handle variable amounts of data, especially when the total amount of data changes dynamically or is not always known beforehand. Weaknesses include: greater memory requirements than arrays (the pointers take up space); slow non-sequential processing, including finding arbitrary nodes; and an inability to backtrack, unless doubly-linked lists are used. Unfortunately, doubly linked lists need more memory, as well as processing time to maintain the backward links.

Linked lists aren’t very good for most types of sorts. Insertion and bubble sorts work fine, but more sophisticated sorts depend on efficient random access, which linked lists don’t provide. Likewise, you wouldn’t want to do a binary search on a linked list. On the other hand, linked lists are ideal for applications where nothing more than sequential access is needed to data that’s always sorted or nearly sorted.

@@ -58,7 +57,7 @@

The basic concept of a linked list—the one I came up with for that DDJ column—is straightforward, as shown in Figure 15.1. A head pointer points to the first node in the list, which points to the next node, which points to the next, and so on, until the last node in the list is reached (typically denoted by a NULL next-node pointer). Conceptually, nothing could be simpler. From an implementation perspective, however, there are serious flaws with this model.

The fundamental problem is that the model of Figure 15.1 unnecessarily complicates link manipulation. In order to delete a node, for example, you must change the preceding node’s NextNode pointer to point to the following node, as shown in Listing 15.1. (Listing 15.2 is the header file LLIST.H, which is #included by all the linked list listings in this chapter.) Easy enough—unless the preceding node happens to be the head pointer, which doesn’t have a NextNode field, because it’s not a node, so Listing 15.1 won’t work. Cumbersome special code and extra information (a pointer to the head of the list) are required to handle the head-pointer case, as shown in Listing 15.3. (I’ll grant you that if you make the next-node pointer the first field in the LinkNode structure, at offset 0, then you could successfully point to the head pointer and pretend it was a LinkNode structure—but that’s an ugly and potentially dangerous trick, and we’ll see a better approach next.)


Figure 15.1
  The basic concept of a linked list. +
-->Figure 15.1  The basic concept of a linked list.


@@ -72,7 +71,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/15-02.html b/15-02.html index 18f10b1..fcd6047 100644 --- a/15-02.html +++ b/15-02.html @@ -24,7 +24,7 @@ - +
@@ -100,10 +100,10 @@ struct LinkNode *DeleteNodeAfter(struct LinkNode **HeadOfListPtr,

However, it is true that if you’re going to store a variety of types of structures in your linked lists, you should start each node with the LinkNode field. That way, the link pointer is in the same place in every structure, and the same linked list code can handle all of the structure types by casting them to the base link-node structure type. This is a less than elegant approach, but it works. C++ can handle data mixing more cleanly than C, via derivation from a base link-node class.

Note that Listings 15.1 and 15.3 have to specify the linked-list delete operation as “delete the next node,” rather than “delete this node,” because in order to relink it’s necessary to access the NextNode field of the node preceding the node to be deleted, and it’s impossible to backtrack in a singly linked list. For this reason, singly-linked list operations tend to work with the structure preceding the one of interest—and that makes the problem of having to special-case the head pointer all the more acute.

Similar problems with the head pointer crop up when you’re inserting nodes, and in fact in all link manipulation code. It’s easy to end up working with either pointers to pointers or lots of special-case code, and while those approaches work, they’re inelegant and inefficient.

-

Dummies and Sentinels

+

Dummies and Sentinels

A far better approach is to use a dummy node for the head of the list, as shown in Figure 15.2. I invented this one for myself the next time I encountered linked lists, while designing a seed fill function for MetaWindows, back during my tenure at Metagraphics Corp. But I could have learned it by spending five minutes with Sedgewick’s book.


Figure 15.2
  Using a dummy head and tail node with a linked list. +
-->Figure 15.2  Using a dummy head and tail node with a linked list.

The next-node pointer of the head node, which points to the first real node, is the only part of the head node that’s actually used. This way the same code works on the head node as on the rest of the list, so there are no special cases. @@ -139,7 +139,7 @@ struct LinkNode *FindNodeBeforeValueNotLess(

Suppose, however, that we make the tail node a sentinel by giving it a value that is guaranteed to terminate the search, as shown in Figure 15.4. The list in Figure 15.4 has a sentinel with a value field of 32,767; since we’re working with integers, that’s the highest possible search value, and is guaranteed to satisfy any search that comes down the pike. The success or failure of the search can then be determined outside the loop, if necessary, by checking for the tail node’s special pointer—but the inside of the loop is streamlined to just one test, as shown in Listing 15.5. Not all linked lists lend themselves to sentinels, but the performance benefits are considerable for those lend themselves to sentinels, but the performance benefits are considerable for those that do.


Figure 15.3
  Representing an empty list. +
-->Figure 15.3  Representing an empty list.


@@ -153,7 +153,7 @@ struct LinkNode *FindNodeBeforeValueNotLess(
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/15-03.html b/15-03.html index 6e46150..8806c2f 100644 --- a/15-03.html +++ b/15-03.html @@ -24,7 +24,7 @@ - +
@@ -64,16 +64,16 @@ struct LinkNode *FindNodeBeforeValueNotLess(


Figure 15.4
  List terminated by a sentinel. +
-->Figure 15.4  List terminated by a sentinel.

-

Circular Lists

+

Circular Lists

One minor but elegant refinement yet remains: Use a single node as both the head and the tail of the list. We can do this by connecting the last node back to the first through the head/tail node in a circular fashion, as shown in Figure 15.5. This head/tail node can also, of course, be a sentinel; when it’s necessary to check for the end of the list explicitly, that can be done by comparing the current node pointer to the head pointer. If they’re equal, you’re at the head/tail node.

Why am I so fond of this circular list architecture? For one thing, it saves a node, and most of my linked list programming has been done in severely memory-constrained environments. Mostly, though, it’s just so neat; with this setup, there’s not a single node or inner-loop instruction wasted. Perfect economy of programming, if you ask me.

I must admit that I racked my brains for quite a while to come up with the circular list, simple as it may seem. Shortly after coming up with it, I happened to look in Sedgewick’s book, only to find my nifty optimization described plain as day; and a little while after that, I came across a thread in the algorithms/computer.sci topic on BIX that described it in considerable detail. Folks, the information is out there. Look it up before turning on your optimizer afterburners!

Listings 15.1 and 15.6 together form a suite of C functions for maintaining a circular linked list sorted by ascending value. (Listing 15.5 requires modification before it will work with circular lists.) Listing 15.7 is an assembly language version of InsertNodeSorted(); note the tremendous efficiency of the scanning loop in InsertNodeSorted()—four instructions per node!—thanks to the dummy head/tail/sentinel node. Listing 15.8 is a simple application that illustrates the use of the linked-list functions in Listings 15.1 and 15.6.

Contrast Figure 15.5 with Figure 15.1, and Listings 15.1, 15.5, 15.6, and 15.7 with Listings 15.3 and 15.4. Yes, linked lists are simple, but not so simple that a little knowledge doesn’t make a substantial difference. Make it a habit to read Knuth or Sedgewick or the like before you write a single line of code.


Figure 15.5
  Representing a circular list. +
-->Figure 15.5  Representing a circular list.

LISTING 15.6 L15-6.C

@@ -158,7 +158,7 @@ struct LinkNode *InsertNodeSorted(struct LinkNode *HeadOfListNode,
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/15-04.html b/15-04.html index 8fa9175..67f4c9c 100644 --- a/15-04.html +++ b/15-04.html @@ -24,7 +24,7 @@ - +
@@ -186,7 +186,7 @@ void main() } -

Hi/Lo in 24 Bytes

+

Hi/Lo in 24 Bytes

In one of my PC TECHNIQUES “Pushing the Envelope” columns, I passed along one of David Stafford’s fiendish programming puzzles: Write a C-callable function to find the greatest or smallest unsigned int. Not a big deal—except that David had already done it in 24 bytes, so the challenge was to do it in 24 bytes or less.

Such routines soon began coming at me from all angles. However (and I hate to say this because some of my correspondents were very pleased with the thought that they had bested David), no one has yet met the challenge—because most of you folks missed a key point. When David said, “Write a function to find the greatest or smallest unsigned int in 24 bytes or less,” he meant, “Write the hi and the lo functions in 24 bytes or less—combined.”

Oh.

@@ -237,7 +237,7 @@ around: ja save
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-01.html b/16-01.html index 615e69e..d6f8f76 100644 --- a/16-01.html +++ b/16-01.html @@ -24,7 +24,7 @@ - +
@@ -36,9 +36,8 @@


-

Chapter 16
There Ain’t No Such Thing as the Fastest Code -

-

Lessons Learned in the Pursuit of the Ultimate Word Counter

+

Chapter 16
There Ain’t No Such Thing as the Fastest Code

+

Lessons Learned in the Pursuit of the Ultimate Word Counter

I remember reading an overview of C++ development tools for Windows in a past issue of PC Week. In the lower left corner was the familiar box listing the 10 leading concerns of corporate buyers when it comes to C++. Boiled down, the list looked like this, in order of descending importance to buyers:

1.  Debugging @@ -53,7 +52,7 @@
10.  Windows development cycle automation

Is something missing here? You bet your maximum gluteus something’s missing—nowhere on that list is there so much as one word about how fast the compiled code runs! I’m not saying that performance is everything, but optimization isn’t even down there at number 10, below online help! Ye gods and little fishes! We are talking here about people who would take a bus from LA to New York instead of a plane because it had a cleaner bathroom; who would choose a painting from a Holiday Inn over a Matisse because it had a fancier frame; who would buy a Yugo instead of—well, hell, anything—because it had a nice owner’s manual and particularly attractive keys. We are talking about people who are focusing on means, and have forgotten about ends. We are talking about people with no programming souls.

-

Counting Words in a Hurry

+

Counting Words in a Hurry

What are we to make of this? At the very least, we can safely guess that very few corporate buyers ever enter optimization contests. Most of my readers do, however; in fact, far more than I thought ever would, but that gladdens me to no end. I issued my first optimization challenge in a “Pushing the Envelope” column in PC TECHNIQUES back in 1991, and was deluged by respondents who, one might also gather, do not live by PC Week.

That initial challenge was sparked by a column David Gerrold wrote (also in PC TECHNIQUES ) concerning the matter of counting the number of words in a document; David turned up some pretty interesting optimization issues along the way. David did all his coding in Pascal, pointing out that while an assembly language version would probably be faster, his Pascal utility worked properly and was fast enough for him.

It wasn’t, however, fast enough for me. The logical starting place for speeding up word counting would be David’s original Pascal code, but I’m much more comfortable with C, so Listing 16.1 is a loose approximation of David’s word count program, translated to C. I left out a few details, such as handling comment blocks, partly because I don’t use such blocks myself, and partly so we can focus on optimizing the core word-counting code. As Table 16.1 indicates, Listing 16.1 counts the words in a 104,448-word file in 4.6 seconds. The file was stored on a RAM disk, and Listing 16.1 was compiled with Borland C++ with all optimization enabled. A RAM disk was used partly because it returns consistent times—no seek times, rotational latency, or cache to muddy the waters—and partly to highlight word-counting speed rather than disk access speed.

@@ -171,7 +170,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-02.html b/16-02.html index e11a95a..47b549d 100644 --- a/16-02.html +++ b/16-02.html @@ -24,7 +24,7 @@ - +
@@ -186,7 +186,7 @@ end -

Which Way to Go from Here?

+

Which Way to Go from Here?

We could rearrange the tests in light of the nature of the data being scanned; for example, we could perform the tests more efficiently by taking advantage of the knowledge that if a byte is less than ‘0,’ it’s either an apostrophe or not a character at all. However, that sort of fine-tuning is typically good for speedups of only 10 to 20 percent, and I’ve intentionally refrained from implementing this in Listing 16.3 to avoid pointing you down the wrong path; what we need is a different tack altogether. Ponder this. What we really want to know is nothing more than whether a byte is a character, not what sort of character it is. For each byte value, we want a yes/no status, and nothing else—and that description practically begs for a lookup table. Listing 16.4 uses a lookup table approach to boost performance another 50 percent, to three times the performance of the original C code. On a 20 MHz 386, this represents a change from 4.6 to 1.6 seconds, which could be significant—who likes to wait? On an 8088, the improvement in word-counting a large file could easily be 10 or 20 seconds, which is definitely significant.


@@ -200,7 +200,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-03.html b/16-03.html index 2e19b31..ecdaf2c 100644 --- a/16-03.html +++ b/16-03.html @@ -24,7 +24,7 @@ - +
@@ -137,7 +137,7 @@

So, gosh, Listing 16.4 is the best word-counting code in the universe, right? Not hardly. If there’s one thing my years of toil in this vale of silicon have taught me, it’s that there’s never a lack of potential for further optimization. Never! Off the top of my head, I can think of at least three ways to speed up Listing 16.4; and, since Turbo Profiler reports that even in Listing 16.4, 88 percent of the time is spent scanning the buffer (as opposed to reading the file), there’s potential for those further optimizations to improve performance significantly. (However, it is true that when access is performed to a hard rather than RAM disk, disk access jumps to about half of overall execution time.) One possible optimization is unrolling the loop, although that is truly a last resort because it tends to make further changes extremely difficult.

Exhaust all other optimizations before unrolling loops.
-

Challenges and Hazards

+

Challenges and Hazards

The challenge I put to the readers of PC TECHNIQUES was to write a faster module to replace Listing 16.4. The author of the code that counted the words in my secret test file fastest on my 20 MHz cached 386 would be the winner and receive Numerous Valuable Prizes.

No listings were to be longer than 200 lines. No complete programs were to be accepted; submissions had to be plug-compatible with Listing 16.4. (This was to encourage people not to waste time optimizing outside the inner loop.) Finally, the code had to produce the same results as Listing 16.4; I didn’t want to see functions that approximated the word count by dividing the number of characters by six instead of counting actual words!

So how did the entrants in this particular challenge stack up? More than one claimed a speed-up over my assembly word-counting code of more than three times. On top of the three-times speedup over the original C code that I had already realized, we’re almost up to an order of magnitude faster. You are, of course, entitled to your own opinion, but I consider an order of magnitude to be significant.


@@ -153,7 +153,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-04.html b/16-04.html index b996d65..baa4b1e 100644 --- a/16-04.html +++ b/16-04.html @@ -24,7 +24,7 @@ - +
@@ -38,7 +38,7 @@


Truth to tell, I didn’t expect a three-times speedup; around two times was what I had in mind. Which just goes to show that any code can be made faster than you’d expect, if you think about it long enough and from many different perspectives. (The most potent word-counting technique seems to be a 64K lookup table that allows handling two bytes simultaneously. This is not the sort of technique one comes up with by brute-force optimization.) Thinking (or, worse yet, boasting) that your code is the fastest possible is rollescating on a tightrope in a hurricane; you’re due for a fall, if you catch my drift. Case in point: Terje Mathisen’s word-counting program.

-

Blinding Yourself to a Better Approach

+

Blinding Yourself to a Better Approach

Not so long ago, Terje Mathisen, who I introduced earlier in this book, wrote a very fast word-counting program, and posted it on Bix. When I say it was fast, I mean fast; this code was optimized like nobody’s business. We’re talking top-quality code here.

When the topic of optimizing came up in one of the Bix conferences, Terje’s program was mentioned, and he posted the following message: “I challenge BIXens (and especially mabrash!) to speed it up significantly. I would consider 5 percent a good result.” The clear implication was, “That code is as fast as it can possibly be.”

Naturally, it wasn’t; there ain’t no such thing as the fastest code (TANSTATFC? I agree, it doesn’t have the ring of TANSTAAFL). I pored over Terje’s 386 native-mode code, and found the critical inner loop, which was indeed as tight as one could imagine, consisting of just a few 386 native-mode instructions. However, one of the instructions was this:

@@ -53,14 +53,14 @@
CMP reg,[mem] takes 6 cycles on the 386, but CMP [ mem ],reg takes only 5 cycles; you should always performCMP with the memory operand on the left on the 386.

(Granted, CMP [mem],reg is 1 cycle slower than CMP reg,[mem] on the 286, and they’re both the same on the 8088; in this case, though, the code was specific to the 386. In case you’re curious, both forms take 2 cycles on the 486; quite a lot faster, eh?)

-

Watch Out for Luggable Assumptions!

+

Watch Out for Luggable Assumptions!

The first lesson to be learned here is not to lug assumptions that may no longer be valid from the 8088/286 world into the wonderful new world of 386 native-mode programming. The second lesson is that after you’ve slaved over your code for a while, you’re in no shape to see its flaws, or to be able to get the new perspectives needed to speed it up. I’ll bet Terje looked at that [EBX+EAX] addressing a hundred times while trying to speed up his code, but he didn’t really see what it did; instead, he saw what it was supposed to do. Mental shortcuts like this are what enable us to deal with the complexities of assembly language without overloading after about 20 instructions, but they can be a major problem when looking over familiar code.

The third, and most interesting, lesson is that a far more fruitful optimization came of all this, one that nicely illustrates that cycle counting is not the key to happiness, riches, and wondrous performance. After getting my 5 percent speedup, I mentioned to Terje the possibility of using a 64K lookup table. (This predated the arrival of entries for the optimization contest.) He said that he had considered it, but it didn’t seem to him to be worthwhile. He couldn’t shake the thought, though, and started to poke around, and one day, voila, he posted a new version of his word count program, WC50, that was much faster than the old version. I don’t have exact numbers, but Terje’s preliminary estimate was 80 percent faster, and word counting—including disk cache access time—proceeds at more than 3 MB per second on a 33 MHz 486. Even allowing for the speed of the 486, those are very impressive numbers indeed.

The point I want to make, though, is that the biggest optimization barrier that Terje faced was that he thought he had the fastest code possible. Once he opened up the possibility that there were faster approaches, and looked beyond the specific approach that he had so carefully optimized, he was able to come up with code that was a lot faster. Consider the incongruity of Terje’s willingness to consider a 5 percent speedup significant in light of his later near-doubling of performance.

Don’t get stuck in the rut of instruction-by-instruction optimization. It’s useful in key loops, but very often, a change in approach will work far greater wonders than any amount of cycle counting can.

By the way, Terje’s WC50 program is a full-fledged counting program; it counts characters, words, and lines, can handle multiple files, and lets you specify the characters that separate words, should you so desire. Source code is provided as part of the archive WC50 comes in. All in all, it’s a nice piece of work, and you might want to take a look at it if you’re interested in really fast assembly code. I wouldn’t call it the fastest word-counting code, though, because I would of course never be so foolish as to call anything the fastest.

-

The Astonishment of Right-Brain Optimization

+

The Astonishment of Right-Brain Optimization

As it happened, the challenge I issued to my PC TECHNIQUES readers was a smashing success, with dozens of good entries. I certainly enjoyed it, even though I did have to look at a lot of tricky assembly code that I didn’t write—hard work under the best of circumstances. It was worth the trouble, though. The winning entry was an astonishing example of what assembly language can do in the right hands; on my 386, it was four times faster at word counting than the nice, tight assembly code I provided as a starting point—and about 13 times faster than the original C implementation. Attention, high-level language chauvinists: Is the speedup getting significant yet? Okay, maybe word counting isn’t the most critical application, but how would you like to have that kind of improvement in your compression software, or in your real-time games—or in Windows graphics?

The winner was David Stafford, who at the time was working for Borland International; his entry is shown in Listing 16.5. Dave Methvin, whom some of you may recall as a tech editor of the late, lamented PC Tech Journal, was a close second, and Mick Brown, about whom I know nothing more than that he is obviously an extremely good assembly language programmer, was a close third, as shown in Table 16.2, which precedes Listing 16.5. Those three were out ahead of the pack; the fourth-place entry, good as it was (twice as fast as my original code), was twice as slow as David’s winning entry, so you can see that David, Dave, and Mick attained a rarefied level of optimization indeed.


@@ -75,7 +75,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-05.html b/16-05.html index 813a02c..dc5f853 100644 --- a/16-05.html +++ b/16-05.html @@ -24,7 +24,7 @@ - +
@@ -292,7 +292,7 @@ jumping.
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-06.html b/16-06.html index 96c205d..5860b96 100644 --- a/16-06.html +++ b/16-06.html @@ -24,7 +24,7 @@ - +
@@ -36,12 +36,12 @@


-

Levels of Optimization

+

Levels of Optimization

Three levels of optimization were evident in the word-counting entries I received in response to my challenge. I’d briefly describe them as “fine-tuning,” “new perspective,” and “table-driven state machine.” The latter categories produce faster code, but, by the same token, they are harder to design, harder to implement, and more difficult to understand, so they’re suitable for only the most demanding applications. (Heck, I don’t even guarantee that David Stafford’s entry works perfectly, although, knowing him, it probably does; the more complex and cryptic the code, the greater the chance for obscure bugs.)

Remember, optimize only when needed, and stop when further optimization will not be noticed. Optimization that’s not perceptible to the user is like buying Telly Savalas a comb; it’s not going to do any harm, but it’s nonetheless a waste of time.
-

Optimization Level 1: Good Code

+

Optimization Level 1: Good Code

The first level of optimization involves fine-tuning and clever use of the instruction set. The basic framework is still the same as my code (which in turn is basically the same as that of the original C code), but that framework is implemented more efficiently.

One obvious level 1 optimization is using a word rather than dword counter. ScanBuffer can never be called upon to handle more than 64K bytes at a time, so no more than 32K words can ever be found. Given that, it’s a logical step to use INC rather than ADD/ADC to keep count, adding the tally into the full 32-bit count only upon exiting the function. Another useful optimization is aligning loop tops and other branch destinations to word , or better yet dword , boundaries.

@@ -61,7 +61,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-07.html b/16-07.html index 740ddcd..62abc9a 100644 --- a/16-07.html +++ b/16-07.html @@ -24,7 +24,7 @@ - +
@@ -145,7 +145,7 @@ end -

Level 2: A New Perspective

+

Level 2: A New Perspective

The second level of optimization is one of breaking out of the mode of thinking established by my original code. Some entrants clearly did exactly that. They stepped back, thought about what the code actually needed to do, rather than just improving how it already worked, and implemented code that sprang from that new perspective.

You can see one example of this in Listing 16.6, where Willem uses CMP AX,0101H to check two bytes at once. While you might think of this as nothing more than a doubling up of tests, it’s a little more than that, especially when taken together with the use of two loops. This is a break with the serial nature of the C code, a recognition that word counting is really nothing more than a state machine that transitions from the “in word” state to the “not in word” state and back, counting a word on one but not both of those transitions. Willem says, in effect, “We’re in a word; if the next two bytes are non-separators, then we’re still in a word, else we’re not in a word, so count and change to the appropriate state.” That’s really quite different from saying, as I originally did, “If the last byte was a non-separator, then if the current byte is a separator, then count a word.” Willem has moved away from the all-in-one approach, splitting the code up into state-specific chunks that are more efficient because each does only the work required in a particular state.

@@ -165,7 +165,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/16-08.html b/16-08.html index 24ffff6..bb446f8 100644 --- a/16-08.html +++ b/16-08.html @@ -24,7 +24,7 @@ - +
@@ -57,7 +57,7 @@

John later divides the transition count by two to get the word count. (Food for thought: It’s also possible to use CMP and ADC to detect words without branching.)

John’s approach makes it clear that word-counting is nothing more than a fairly simple state machine. The interesting part, of course, is building the fastest state machine.

-

Level 3: Breakthrough

+

Level 3: Breakthrough

The boundaries between the levels of optimization are not sharply defined. In a sense, level 3 optimization is just like levels 1 and 2, but more so. At level 3, one takes whatever level 2 perspective seems most promising, and implements it as efficiently as possible on the x86. Even more than at level 2, at level 3 this means breaking out of familiar patterns of thinking.

In the case of word counting, level 3 means building a table-driven state machine dedicated to processing a buffer of bytes into a count of words with a minimum of branching. This level of optimization strips away many of the abstractions we usually use in coding, such as loops, tests, and named variables—look back to Listing 16.5, and you’ll see what I mean. Only a few people reached this level, and I don’t think any of them did it without long, hard thinking; David Stafford’s final entry (that is, the one I present as Listing 16.5) was at least the fifth entry he sent me.

@@ -104,17 +104,17 @@

The trick, then, is to identify the separator/not statuses of each set of three bytes and turn them into a 1 (count word) or 0 (don’t count word), as quickly as possible. Assuming that the separator/not status for the first byte is in the Carry flag, this is easily accomplished by a lookup in a 64K table, based on the Carry flag and the other two bytes, as shown in Figure 16.2. (Remember that we’re counting 7-bit ASCII here, so the high bit is ignored.) Thus, David is able to add the word/not status for each pair of bytes to the main word count simply by getting the two bytes, working in the carry status from the last byte, and using the resulting value to index into the 64K table, adding in the 1 or 0 value found in that table. A sequence of MOV/ADC/ADD suffices to perform all word-counting tasks for a pair of bytes. Three instructions, no branches—pretty nearly perfect code.


Figure 16.1
  The two potential word count locations. +
-->Figure 16.1  The two potential word count locations.

One detail remains to be attended to: setting the Carry flag for next time if the last byte was a non-separator. David does this in a bizarre and incredibly effective way: He presets the high bit of the count, and sets the high bit in the lookup table for those entries looked up by non-separators. When a non-separator’s lookup entry is added to the count, it will produce a carry, as desired. The high bit of the count is masked off before being added to the total count, so David is essentially using different parts of the count variables for different purposes (counting, and setting the Carry flag).


Figure 16.2
  Looking up a word count status. +
-->Figure 16.2  Looking up a word count status.

There are a number of other interesting details in David’s code, including the unrolling of the loop 64 times, so that 256 bytes in a row are processed without a single branch. Unfortunately, I lack the space to discuss Listing 16.5 any further. Perhaps that’s not so unfortunate, after all; I’d hate to deny you the pleasure of discovering the wonders of this rather remarkable code yourself. I will say one more thing, though. The cycle count for David’s inner loop is 6.5 cycles per byte processed, and the actual measured time for his routine, overhead and all, is 7.9 cycles/byte. The original C code clocked in at around 100 cycles/byte.

Enough said, I trust.

-

Enough Word Counting Already!

+

Enough Word Counting Already!

Before I finish up this chapter, I’d like to mention that Terje Mathisen’s WC word-counting program, which I’ve mentioned previously and which is available, with source, on Bix, is in the ballpark with David’s code for performance. What’s more, Terje’s program handles 8-bit ASCII, counts lines as well as words, and supports user-definable separator sets. It’s wonderful code, well worth a look; it also happens to be a great word-counting utility. By the way, Terje builds his 64K table on the fly, at program initialization; this allows for customized tables, shrinks the size of the EXE, and, according to Terje’s calculations, takes less time than loading the table off disk as part of the EXE.

So, has David written the fastest possible word-counting code? Well, maybe—but I have a letter from Terry Holmes, of San Rafael, California, that calculates the theoretical maximum performance of native 386 word-counting code at 5.5 cycles/byte, which would be significantly faster than David’s code. Terry, alas, didn’t bother to implement his design, but maybe I’ll take a shot at it someday. It’d be fun, for sure—but jeez, I’ve got real work to do!


@@ -130,7 +130,7 @@
-Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
diff --git a/17-01.html b/17-01.html index 4b04f8d..544e1cb 100644 --- a/17-01.html +++ b/17-01.html @@ -24,7 +24,7 @@ - +
@@ -36,16 +36,15 @@


-

Chapter 17
The Game of Life -

-

The Triumph of Algorithmic Optimization in a Cellular Automata Game

+

Chapter 17
The Game of Life

+

The Triumph of Algorithmic Optimization in a Cellular Automata Game

I’ve spent a lot of my life discussing assembly language optimization, which I consider to be an important and underappreciated topic. However, I’d like to take this opportunity to point out that there is much, much more to optimization than assembly language. Assembly is essential for absolute maximum performance, but it’s not the only ingredient; necessary but not sufficient, if you catch my drift—and not even necessary, if you’re looking for improved but not maximum performance. You’ve heard it a thousand times: Optimize your algorithm first. Devise new approaches. Or, as Knuth said, Premature optimization is the root of all evil.

This is, of course, old hat, stuff you know like the back of your hand. Or is it? As Jeff Duntemann pointed out to me the other day, performance programmers are made, not born. While I’m merrily gallivanting around in this book optimizing 486 pipelining and turning simple tasks into horribly complicated and terrifyingly fast state machines, many of you are still developing your basic optimization skills. I don’t want to shortchange those of you in the latter category, so in this chapter, we’ll discuss some high-level language optimizations that can be applied by mere mortals within a reasonable period of time. We’re going to examine a complete optimization process, from start to finish, and what we will find is that it’s possible to get a 50-times speed-up without using one byte of assembly! It’s all a matter of perspective—how you look at your code and data.

-

Conway’s Game

+

Conway’s Game

The program that we’re going to optimize is Conway’s famous Game of Life, long-ago favorite of the hackers at MIT’s AI Lab. If you’ve never seen it, let me assure you: Life is neat, and more than a little hypnotic. Fractals have been the hot graphics topic in recent years, but for eye-catching dazzle, Life is hard to beat.

Of course, eye-catching dazzle requires real-time performance—lots of pixels help too—and there’s the rub. When there are, say, 40,000 cells to process and display, a simple, straightforward implementation just doesn’t cut it, even on a 33 MHz 486. Happily, though, there are many, many ways to speed up Life, and they illustrate a variety of important optimization principles, as this chapter will show.

First, I’ll describe the ground rules of Life, implement a very straightforward version in C++, and then speed that version up by about eight times without using any drastically different approaches or any assembly. This may be a little tame for some of you, but be patient; for after that, we’ll haul out the big guns and move into the 30 to 40 times speed-up range. Then in the next chapter, I’ll show you how several programmers really floored it in taking me up on my second Optimization Challenge, which involved the Game of Life.

-

The Rules of the Game

+

The Rules of the Game

The Game of Life is ridiculously simple. There is a cellmap, consisting of a rectangular matrix of cells, each of which may initially be either on or off. Each cell has eight neighbors: two horizontally, two vertically, and four diagonally. For each succeeding generation of cells, the game logic determines whether each cell will be on or off according to the following rules:

    @@ -66,7 +65,7 @@
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-02.html b/17-02.html index fed2621..9744d6d 100644 --- a/17-02.html +++ b/17-02.html @@ -24,7 +24,7 @@ - +
    @@ -309,7 +309,7 @@ void show_text(int x, int y, char *text)
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-03.html b/17-03.html index 77dae2b..14bee63 100644 --- a/17-03.html +++ b/17-03.html @@ -24,7 +24,7 @@ - +
    @@ -36,7 +36,7 @@


    -

    Where Does the Time Go?

    +

    Where Does the Time Go?

    How slow is Listing 17.1? Table 17.1 shows that even on a 486, Listing 17.1 does fewer than three 96x96 generations per second. (The times in Table 17.1 are for 1,000 generations of a 96x96 cell map with seed=1, LIMIT_18_HZ=0, WRAP_EDGES=1, and magnifier=2, running on a 33 MHz 486.) Since my target is 18 generations per second with a 200x200 cellmap on a 20 MHz 386, Listing 17.1 is too slow by a rather wide margin—75 times too slow, in fact. You might say we have a little optimizing to do.

    The first rule of optimization is: Only optimize where it matters. Use a profiler, or risk making a fool of yourself. Consider Listings 17.1 and 17.2. Where do you think the potential for significant speed-up lies? I’ll tell you one place where I thought there was considerable potential—in draw_pixel(). As a programmer of high-speed graphics, I figured any drawing function that was not only written in C/C++ but also recalculated the target address from scratch for each pixel would be among the first optimization targets. I also expected to get major gains out of going to a Ping-Pong arrangement so that I didn’t have to copy the new cellmap back to current_map after calculating the next generation.

    @@ -98,7 +98,7 @@

    I was wrong. Wrong, wrong, wrong. (But at least I was smart enough to use a profiler before actually writing any new code.) Table 17.1 shows where the time actually goes in Listings 17.1 and 17.2. As you can see, the time taken by draw_pixel(), copy_cells(), and everything other than calculating the next generation is nothing more than noise. We could optimize these routines right down to executing instantaneously, and you know what? It wouldn’t make the slightest perceptible difference in how fast the program runs. Given the present state of our Game of Life implementation, the only areas worth looking at for possible optimizations are cell_state() and next_generation().

    It’s worth noting, though, that one reason draw_pixel() doesn’t much affect performance is that in Listing 17.1, we’re smart enough to redraw pixels only when their states change, rather than during every generation. Detecting and eliminating redundant operations is part of knowing the nature of your data, and is a potent optimization technique that will be extremely useful a little later in this chapter.
    -

    The Hazards and Advantages of Abstraction

    +

    The Hazards and Advantages of Abstraction

    How can we speed up cell_state() and next_generation()? I’ll tell you how not to do it: By writing those member functions in assembly. It’s tempting to say that cell_state() is taking all the time, so we need to speed it up with assembly, but what we really need to do is figure out why cell_state() is taking all the time, then address that aspect of the program directly.

    Once you know where you need to optimize, the one word to keep in mind isn’t assembly, it’s...plastics. No, actually, it’s abstraction. Well-written C and especially C++ programs are highly abstract models. For example, Listing 17.1 essentially creates a new programming language in which cells are tangible things, with built-in manipulation instructions. Given the cellmap member functions, you don’t even need to know the cell storage format! This is a wonderful thing, in general; it saves programming time and bugs, and frees you to work on the application’s needs, rather than implementation details.

    However, if you never look beneath the surface of the abstract model at the implementation details, you have no idea of what the true performance cost of various operations is, and, without that, you have largely surrendered control over performance. @@ -116,7 +116,7 @@
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-04.html b/17-04.html index 068f3cf..09e482a 100644 --- a/17-04.html +++ b/17-04.html @@ -24,7 +24,7 @@ - +
    @@ -39,13 +39,13 @@

    There’s a kicker here, though, and that’s the counting of neighbors for cells at the edge of the cellmap. When cellmap wrapping is enabled (so that the cellmap becomes essentially a toroid, with each edge joined seamlessly to the opposite edge, as opposed to having a border of off-cells), neighbors that reside on the other edge of the cellmap can’t be accessed by the standard fixed offset, as shown in Figure 17.1. So, in general, we could improve performance by hard-wiring our neighbor-counting for the bit-per-cell cellmap format, but it seems we’d need a lot of conditional code to handle wrapping, and that would slow things back down again.


    Figure 17.1
      Edge-wrapping complications. +
    -->Figure 17.1  Edge-wrapping complications.

    When a problem doesn’t lend itself well to optimization, make it a practice to see if you can change the problem definition to one that allows for greater efficiency. In this case, we’ll change the problem by putting padding bytes around the edge of the cellmap, and duplicating each edge of the cellmap in the padding bytes at the opposite side, as shown in Figure 17.2. That way, a hard-wired neighbor count will find exactly what it should—the opposite edge—without any special code at all.

    But doesn’t that extra copying of the edges take time? Sure, but only a little; we can build it into the cellmap copying function, and then frankly we won’t even notice it. Avoiding tens or hundreds of thousands of calls to cell_state(), on the other hand, will be very noticeable. Listing 17.3 shows the alterations to Listing 17.1 required to implement a hard-wired neighbor-counting function. This is a minor change, in truth, implemented in about half an hour and not making the code significantly larger—but Listing 17.3 is 3.6 times faster than Listing 17.1, as shown in Table 17.1. We’re up to about 10 generations per second on a 486; not where we want to be, but it is a vast improvement.


    Figure 17.2
      The “padding cells” solution. +
    -->Figure 17.2  The “padding cells” solution.

    LISTING 17.3 L17-3.CPP

    @@ -226,7 +226,7 @@ void cellmap::next_generation(cellmap& next_map)
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-05.html b/17-05.html index 276cded..ed5c7c0 100644 --- a/17-05.html +++ b/17-05.html @@ -24,7 +24,7 @@ - +
    @@ -39,7 +39,7 @@

    In Listing 17.3, note the padded cellmap edges, and the alteration of the member functions to compensate for the padding. Also note that the width now has to be a multiple of eight, to facilitate the process of copying the edges to the opposite padding bytes. We have decreased the generality of our Game of Life implementation in exchange for better performance. That’s a very common trade-off, as common as trading memory for performance. As a rule, the more general a program is, the slower it is. A corollary is that often (not always, but often), the more heavily optimized a program is, the more complex and the more difficult to implement it is. You can often improve performance a good deal by implementing only the level of generality you need, but at the same time decreased generality makes it more difficult to change or port the program at some later date. A Game of Life implementation, such as Listing 17.1, that’s built on set_cell(), clear_cell(), and get_cell() is completely general; you can change the cell storage format simply by changing the constructor and those three functions. Listing 17.3 is harder to change because count_neighbors() would also have to be altered, and it’s more complex than any of the other functions.

    So, in Listing 17.3, we’ve gotten under the hood and changed the cellmap format a little, and gotten impressive results. But now count_neighbors() is hard-wired for optimized counting, and it’s still taking up more than half the time. Maybe now it’s time to go to assembly?

    Not hardly.

    -

    Heavy-Duty C++ Optimization

    +

    Heavy-Duty C++ Optimization

    Before we get to assembly, we still have to perform C++ optimization, then see if we can find an alternative approach that better fits the application. It would actually have made much more sense if we had looked for a new approach as our first optimization step, but I decided it would be better to cover straightforward C++ optimizations at this point, and the mind-bending stuff a little later. Right now, let’s look at some C++ optimizations; Listing 17.4 is a C++-optimized version of Listing 17.3.

    LISTING 17.4 L17-4.CPP

    @@ -145,7 +145,7 @@ neighbor_count++;
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-06.html b/17-06.html index a0ac10d..597fafe 100644 --- a/17-06.html +++ b/17-06.html @@ -24,7 +24,7 @@ - +
    @@ -43,11 +43,11 @@
  • There are many possible cellmap representations other than one bit-per-pixel.
  • Cells change state relatively infrequently.
  • -

    Bringing In the Right Brain

    +

    Bringing In the Right Brain

    In the previous section, we saw how a C++ program could be sped up about eight times simply by rearranging the data and code in straightforward ways. Now we’re going to see how right-brain non-linear optimization can speed things up by another four times—and make the code simpler.

    Now that’s Zen code optimization.

    I have two objectives to achieve in the remainder of this chapter. First, I want to show that optimization consists of many levels, from assembly language up to conceptual design, and that assembly language kicks in pretty late in the optimization process. Second, I want to encourage you to saturate your brain with everything you know about any particular optimization problem, then make space for your right brain to solve the problem.

    -

    Re-Examining the Task

    +

    Re-Examining the Task

    Earlier in this chapter, we looked at a straightforward Game of Life implementation, then increased performance considerably by making the implementation a little less abstract and a little less general. We made a small change to the cellmap format, adding padding bytes off the edges so that pointer arithmetic would always work, but the major optimizations were moving the critical code into a single loop and using pointers rather than member functions whenever possible. In other words, we took what we already knew and made it more efficient.

    Now it’s time to re-examine the nature of this programming task from the ground up, looking for things that we don’t yet know. Let’s take a moment to review what the Game of Life consists of. The basic task is evolving a new generation, and that’s done by looking at the number of “on” neighbors a cell has and the cell’s own state. If a cell is on, and two or three neighbors are on, then the cell stays on; otherwise, an on-cell is turned off. If a cell is off and exactly three neighbors are on, then the cell is turned on; otherwise, an off-cell stays off. That’s all there is to it. As any fool can see, the trick is to arrange things so that we can count neighbors and check the cell state as quickly as possible. Large lookup tables, oddly encoded cellmaps, and lots of bit-twiddling assembly code spring to mind as possible approaches. Can’t you just feel your adrenaline start to pump?

    @@ -59,9 +59,9 @@

    But what about the overhead needed to maintain the neighbor counts? Well, each time a cell changes state, eight operations would be needed to update the counts in the eight neighboring cells. But this happens only once every ten cells, on average—so the cost of this approach is only one-tenth that of the original approach!

    Know your data.


    Figure 17.3
      New cell format. +
    -->Figure 17.3  New cell format.

    -

    Acting on What We Know

    +

    Acting on What We Know

    Once we’ve changed the cellmap format to store neighbor counts as well as states, with a byte for each cell, we can get another performance boost by again examining what we know about our data. I said earlier that most cells are off during any given generation. This means that most cells have no neighbors that are on. Since the cell map representation for an off-cell that has no neighbors is a zero byte, we can skip over scads of unchanged cells at a pop simply by scanning for non-zero bytes. This is much faster than explicitly testing cell states and neighbor counts, and lends itself beautifully to assembly language implementation as REPZ SCASB or (with a little cleverness) REPZ SCASW. (Unfortunately, there’s no C library function that can scan memory for the next byte that’s non-zero.)

    Listing 17.5 is a Game of Life implementation that uses the neighbor-count cell map format and scans for non-zero bytes. On a 20 MHz 386, Listing 17.5 is about 4.5 times faster at calculating generations (that is, the generation engine is 4.5 times faster; I’m ignoring the time consumed by drawing and text display) than Listing 17.4, which is no slouch. On a 33 MHz 486, Listing 17.5 is about 3.5 times faster than Listing 17.4. This is true even though Listing 17.5 must be compiled using the large model. Imagine that—getting a four times speed-up while switching from the small model to the large model!


    @@ -76,7 +76,7 @@
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-07.html b/17-07.html index 6fb2d51..3ec67f7 100644 --- a/17-07.html +++ b/17-07.html @@ -24,7 +24,7 @@ - +
    @@ -327,7 +327,7 @@ void cellmap::init()
    -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
    diff --git a/17-08.html b/17-08.html index a07036d..5aa3414 100644 --- a/17-08.html +++ b/17-08.html @@ -24,7 +24,7 @@ - +
    @@ -44,7 +44,7 @@
    We’ve gotten more than a 30-times speedup simply by removing a little of the abstraction that C++ encourages, and by storing and processing the data in a manner appropriate for the typical nature of the data itself. In other words, we’ve done some linear, left-brained optimization (using pointers and reducing calls) and some non-linear, right-brained optimization (understanding the real problem and listening for the creative whisper of non-obvious solutions).

    No doubt we could get another two to five times improvement with good assembly code—but that’s dwarfed by a 30-times improvement, so optimization at a conceptual level must come first.

    -

    The Challenge That Ate My Life

    +

    The Challenge That Ate My Life

    The most recent optimization challenge I laid my community of readers was to write the fastest possible Game of Life generation engine. By “engine” I meant that I didn’t care about time spent in input or output, only time consumed by the call to next-generation. The time spent updating the cellmap was what I wanted people to concentrate on.

    Here are the rules I laid down for the challenge:

      @@ -69,7 +69,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/18-01.html b/18-01.html index 762dd7b..3ffb279 100644 --- a/18-01.html +++ b/18-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,15 @@


      -

      Chapter 18
      It’s a plain Wonderful Life -

      -

      Optimization beyond the Pale

      +

      Chapter 18
      It’s a plain Wonderful Life

      +

      Optimization beyond the Pale

      When I was in high school, my gym teacher had us run a race around the soccer field, or rather, around a course marked with cones that roughly outlined the shape of the field. I quickly settled into second place behind Dwight Chamberlin. We cruised around the field, and when we came to the far corner, Dwight cut across the corner, inside a cone placed awkwardly far out from the others. I followed, and everyone else cut inside the cone too—except the pear-shaped kid bringing up the rear, who plodded his way around every single cone on his way to finishing about half a lap behind. When the laggard finally crossed the finish line, the coach named him the winner, to my considerable irritation. After all, the object was to see who could run the fastest, wasn’t it?

      Actually, it wasn’t. The object was to see who could run the fastest according to the limitations placed upon the contest. This is a crucial distinction, although usually taken for granted. Would it have been legitimate if I had cut across the middle of the field? If I had ridden a bike? If I had broken the world record for the 100 meters by dropping 100 meters from a plane? Competition has meaning only within a carefully circumscribed arena.

      Why am I telling you this? First, because it is a useful lesson for programming.

      All programming is performed within limitations, some of which can be bent or changed, but many of which cannot. You cannot change the maximum memory bandwidth of a VGA, or the maximum instruction execution rate of a 486. That is why the stunning 3D demos you see at SIGGRAPH have only passing relevance to everyday life on the desktop. A rule that Intel’s chip designers cannot break is 8086 compatibility, much as I’m sure they’d like to, but of course the flip side is that although RISC chips are technically superior, they command but a small fraction of the market; raw performance is not the arena of competition. Similarly, you will often be unable to change the specifications for the software you implement.
      -

      Breaking the Rules

      +

      Breaking the Rules

      The other reason for the anecdote has to do with the way my second Optimization Challenge worked itself out. If you’ll recall from the last chapter, the challenge I made to the readers of PC TECHNIQUES was to devise the fastest possible version of the Game of Life cellular automata simulation game. I gave an example, laid out the rules, and stood aside. Good thing, too. Apres moi, le deluge....

      And when the dust had settled, I was left with the uneasy realization that every submitted entry broke the rules. Every single entry. The rules clearly stated that submitted code must produce exactly the same output as my example implementation under all circumstances in order to be eligible to win. I do not think that there can be any question about what “exactly the same output” means. It means the same pixels, in the same colors, at the same places on the screen at the same points in all the Life simulations that the original code was capable of running. Period. And not one of the entries met that standard. Some submitted listings were more than 400 lines long. Some didn’t display the generation number at the right side of the screen, didn’t draw the same pixel colors, or didn’t bother with magnification. Some had bugs. Some didn’t support all possible cellmap widths and heights up to 200x200, requiring widths and heights that were specific multiples of a number of cells that lent itself to a particular implementation.

      This last mission is, in a way, a brilliant approach, as evidenced by the fact that it yielded the two fastest submissions, but it is not within the rules of the contest. Some of the rule-breaking was major, some very minor, and some had nothing to do with the Life engine itself, but the rules were clear; where was I to draw the line if not with exact compliance? And I was fully prepared to draw that line rigorously, disqualifying some mind-bending submissions in order to let lesser but fully compliant entries win—until I realized that there were no fully compliant entries.

      @@ -64,7 +63,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/18-02.html b/18-02.html index d70bc19..a6a68e3 100644 --- a/18-02.html +++ b/18-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Table-Driven Magic

      +

      Table-Driven Magic

      David Stafford won my first Optimization Challenge by means of a huge look-up table and an incredible state machine driven by that table. The table didn’t cause David’s entry to exceed the line limit because David’s submission included code to generate the table on the fly as part of the build process. David has done himself one better this time with his QLIFE program; not only does his build process generate a 64K table, but it also generates virtually all his code, consisting of 17,000-plus lines of assembly language spanning another 64K. What David has done is write the equivalent of a bitblt compiler for the Game of Life; one might in fact call it a Life compiler. What David’s code generates is still a general-purpose program; it takes arbitrary seed values, and can run for an arbitrary number of generations, so it’s not as if David simply hardwired the instructions to draw each successive screen. However, it’s a general-purpose program that is exquisitely tailored to the task it needs to perform.

      All the pieces of QLIFE are shown in Listings 18.1 through 18.5, as follows: Listing 18.1 is BUILD.BAT, the batch file used to build QLIFE; Listing 18.2 is LCOMP.C, the program used to generate the assembler code and data file QLIFE.ASM; Listing 18.3 is MAIN.C, the main program for QLIFE; Listing 18.4 is VIDEO.C, the video-related functions, and Listing 18.5 is LIFE.H, the header file. The following sidebar contains David’s build instructions, exactly as he wrote them. I certainly won’t have room to discuss all the marvelous intricacies of David’s code; I suggest you look over these listings until you understand them thoroughly (it took me a day to pick them apart) because there’s a lot of neat stuff in there, and it’s an approach to performance programming that operates at a more efficient, tightly integrated level than you may ever see again. One hint: It helps a lot to build and run LCOMP.C, redirect its output to QLIFE.ASM, and look at the assembly code in that file. This code is the entirety of David’s generation engine, and it’s almost impossible to visualize its operation without actually seeing it.

      @@ -83,7 +83,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/18-03.html b/18-03.html index 6d7b780..d0de77d 100644 --- a/18-03.html +++ b/18-03.html @@ -24,7 +24,7 @@ - +
      @@ -556,7 +556,7 @@ void main( void )
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/18-04.html b/18-04.html index cbff164..385bca0 100644 --- a/18-04.html +++ b/18-04.html @@ -24,7 +24,7 @@ - +
      @@ -194,13 +194,13 @@ extern unsigned short far ChangeList1[]; #define WRAPDOWN (UP * (HEIGHT - 1)) -

      Keeping Track of Change with a Change List

      +

      Keeping Track of Change with a Change List

      In my earlier optimizations to the Game of Life, described in the last chapter, I noted that most cells in a Life cellmap are dead, and in most cases all the neighbors are dead as well. This observation enabled me to get a major speed-up by scanning the cellmap for the few non-zero bytes (cells that were either alive or have neighbors that are alive). Although that was a big improvement, it still required my code to touch every cell to check its state. David has improved on this by maintaining a change list; that is, a list of pointers to cells that change in the current generation. Only those cells and their neighbors need to be checked or touched in any way in order to create the next generation, saving a great many instructions and also a great many cache misses due to the fact that cellmaps are too big to fit into the 486’s internal cache. During a given generation, David runs down the list of cells that changed from the previous generation to make the changes for this generation, and in the process generates the change list for the next generation.

      That’s the overall approach, but this being David Stafford, it’s not that simple, of course. I’ll let him tell you how his implementation works in his own words. (I’ve edited David’s text a bit, and added my own comments in square brackets, so blame me for any errors.)

      “Each three cells in the life grid are packed into two bytes, as shown in Figure 18.1. So, it is convenient if the width of the cell array is an even multiple of three. There’s nothing in the algorithm that prevents it from supporting any arbitrary size, but the code is a bit simpler this way. So if you want a 200x200 grid, I recommend just using a 201x200 grid, and be happy with the extra free column. Otherwise the edge wrapping code gets more complex.

      “Since every cell has from zero to eight neighbors, you may be wondering how I can manage to keep track of them with only three bits. Each cell really has only a maximum of seven neighbors since we only need to keep track of neighbors outside of the current cell word. That is, if cell ‘B’ changes state then we don’t need to reflect this in the neighbor counts of cells ‘A’ and ‘C.’ Updating is made a little faster. [In other words, when David picks up a word representing three cells, each of the three cells has at least one of the other cells in that word as a neighbor, and the state of that neighbor is stored right in that word, as shown in Figure 18.1. Therefore, the neighbor count for a given cell never needs to reflect more than seven neighbors, because at least one of the eight neighbors’ states is already encoded in the word.]


      Figure 18.1
        Cell triplet storage. +
      -->Figure 18.1  Cell triplet storage.


      @@ -214,7 +214,7 @@ extern unsigned short far ChangeList1[];
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/18-05.html b/18-05.html index 7a0cb38..2736a2f 100644 --- a/18-05.html +++ b/18-05.html @@ -24,7 +24,7 @@ - +
      @@ -53,7 +53,7 @@ FS : Video segment GS : Unused -

      A Layperson’s Overview of QLIFE

      +

      A Layperson’s Overview of QLIFE

      Most likely, you’re scratching your head right now in bemusement. I don’t blame you; I felt the same way myself at first. It’s actually pretty simple, though, once you have the hang of it. Basically, David runs down the change list, visiting every cell that’s due to change in this generation, setting it to the new state, drawing it in the new state, and adjusting the counts of all its neighbors. David has a separate assembly routine for every possible change of state for a cell triplet, and he jumps to the proper routine by taking the cell triplet word, masking off the lower 9 bits, and jumping to the address where the appropriate code to perform that particular change of state resides. He does this for every entry in the change list. When this is completed, the current generation has been drawn and updated.

      Now David runs down the change list again to generate the change list for the next generation. In this case, for every changed cell triplet, David looks at that triplet and all affected neighbors to see which will change in the next generation. He tests for this condition by using each potentially changed cell triplet word as an index into the aforementioned lookup table of new states. If the current state matches the appropriate state for the next generation, then there’s nothing to do and the cell is not added to the change list. If the states don’t match, then the cell is added to the change list, and the appropriate state for the next generation is set in the cell triplet. David checks the minimum possible number of cells for change by branching to code that checks only the relevant cells around each cell triplet in the current change list; that branching is accomplished by taking the cell triplet word, masking off the lower 9 bits, setting bit 8 to a 1-bit, and branching to the routine at that address. As with everything in this amazing program, this represents the least possible work to accomplish the desired result—just three instructions:

      @@ -80,7 +80,7 @@ jmp dx
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/19-01.html b/19-01.html index c9703da..6c58f07 100644 --- a/19-01.html +++ b/19-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,21 +36,20 @@


      -

      Chapter 19
      Pentium: Not the Same Old Song -

      -

      Learning a Whole Different Set of Optimization Rules

      +

      Chapter 19
      Pentium: Not the Same Old Song

      +

      Learning a Whole Different Set of Optimization Rules

      I can still remember the day I did my first 8088 programming. I had just moved over from the distantly related Z80, so the 8088 wasn’t totally alien, but it was nonetheless an incredibly exciting processor. The 8088’s instruction set was vastly more powerful and varied than the Z80’s, and as someone who thrives on puzzles of all sorts, from crosswords to Freecell to jigsaws to assembly language optimization, I was delighted to find that the 8088 made the optimization universe an order of magnitude more complicated—and correspondingly more interesting.

      Well, the years went by and the Z80 just died, and 8088 optimization got ever more complex and intriguing as I discovered the hazards of the 8088’s cycle-eaters. By the time 1989 rolled around, I had written Zen of Assembly Language, in which I described all that I had learned about the 8088 and concluded that 8088 optimization was a black art of infinite subtlety. Unfortunately, by that time the 286 was the standard, with the 386 coming on strong, and if the 286 was less amenable to hand optimization than the 8088 (and it surely was), then the 386 was downright unfriendly. Sure, assembly optimization could buy some performance on the 386, but only 20, 30, 40 percent or so—a far cry from the 100 to 400 percent of the 8088. At the same time, compiler technology was improving quickly, and the days of hand tuning seemed numbered.

      Happily, the 486 traveled to the beat of a different drum. The 486 had some interesting internal pipeline hazards, as well as an internal cache that made cycle counting more meaningful than ever before, and careful code massaging sometimes yielded startling results. Nonetheless, the 486 was still too simple to mark a return to the golden age of optimization.

      -

      The Return of Optimization as Art

      +

      The Return of Optimization as Art

      Then the Pentium came around, and filled our code with optimization hazards, and life was good again. The Pentium has two execution pipelines and enough rules and exceptions to those rules to bring joy to the heart of the hardest-core assembly junkie. For a change, Intel documented most of the Pentium optimization rules and spread the word about them, so we don’t have to go through as much spelunking of the Pentium as with its predecessors. They’ve done this, I suspect, largely because more than any previous x86 processor, the Pentium’s performance is highly dependent on properly optimized code.

      In the worst case, where the second execution pipe is dormant most of the time, the Pentium won’t perform all that much better than a 486 at the same clock speed. In the best case, where the second pipe is heavily used and the Pentium’s other advantages (such as branch prediction, write-back cache, 64-bit full speed external bus, and dual 8K caches) can kick in, the Pentium can be more than twice as fast as a 486. In a critical inner loop, hand optimization can double or even triple performance over 486-optimized code—and that’s on top of the sorts of algorithmic and design optimizations that are routinely performed on any processor. Good compilers can make a big difference on the Pentium, too, but there are some gotchas there, to which I’ll return later.

      It’s been a long time coming, but hard-core, big-payoff assembly language optimization is back in style, and for the rest of this book I’ll be delving into the Byzantine wonders of the Pentium. In this chapter, I’ll do a quick overview, then cover a variety of smaller Pentium optimization topics. In the next chapter, I’ll tackle the 900-pound gorilla of Pentium optimization: superscalar (dual execution pipe) programming. Trust me, this’ll be fun.

      Listen, do you want to know a secret? This lead-in has been brought to you with the help of “classic rock”—another way of saying “music Baby Boomers listened to back when they cared more about music than 401Ks and regular flossing.” There are so many of us Boomers that our music, even the worst of it, will never go away. When we’re 90 years old, propped up in our Kraftmatic adjustable beds and surfing the 5,000-channel information superhighway from one infomercial to the next, the sound system in the retirement community will be piping in a Muzak version of “Louie, Louie,” while on the holovid Country Joe McDonald and the Fish pitch Preparation H. I can hardly wait.

      Gimme a “P”....

      -

      The Pentium: An Overview

      +

      The Pentium: An Overview

      Architecturally, the Pentium is vastly different in many ways from the 486, but most of those differences are transparent to programmers. After all, the whole idea behind the Pentium is that it runs the same code as previous x86 processors, but faster; otherwise, Intel could have made a faster, cheaper RISC processor. Still, knowledge of the Pentium’s architecture is useful for understanding exactly how code will perform, and a few of the architectural differences are most decidedly not transparent to performance programmers.

      The Pentium is essentially one full 486 execution unit (EU), plus a second stripped-down 486 EU, on a single chip. The first EU is referred to as the U execution pipe, or U-pipe; the second, more limited one is called the V-pipe. The two pipes are capable of executing instructions simultaneously, have separate write buffers, and can even access the data cache simultaneously (although with certain limitations that I’ll discuss in the next chapter), so on the Pentium it is possible to execute two instructions, even instructions that access memory, in a single clock. The cycle times for instruction execution in a given pipe (both pipes process instructions at the same speed) are comparable to those for the 486, although some instructions—notably MUL, the repeated string instructions, and some of the shifts and rotates—have gotten faster.

      My first thought upon hearing of the Pentium’s dual pipes was to wonder how often the prefetch queue stalls for lack of instruction bytes, given that the demand for instruction bytes can be twice that of the 486. The answer is: rarely indeed, and then only because the code is not in the internal cache. The 486 has a single 8K cache that stores both code and data, and prefetching can stall if data fetching doesn’t allow time for prefetching to occur (although this rarely happens in practice).


      @@ -66,7 +65,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/19-02.html b/19-02.html index 8dc1172..5815024 100644 --- a/19-02.html +++ b/19-02.html @@ -24,7 +24,7 @@ - +
      @@ -41,14 +41,14 @@

      (And yes, self-modifying code still works; as with all Pentium changes, the dual caches introduce no incompatibilities with 386/486 code.) Also, because the code and data caches are separate, code can’t be driven out of the cache in a tight loop that accesses a lot of data, unlike the 486. In addition, the Pentium expands the 486’s 32-byte prefetch queue to 128 bytes. In conjunction with the branch prediction feature (described next), which allows the Pentium to prefetch properly at most branches, this larger prefetch queue means that the Pentium’s two pipes should be better fed than those of any previous x86 processor.

      -

      Crossing Cache Lines

      +

      Crossing Cache Lines

      There are three other characteristics of the Pentium that make for a healthy supply of instruction bytes. One is that the Pentium can prefetch instructions across cache lines. Unlike the 486, where there is a 3-cycle penalty for branching to an instruction that spans a cache line, there’s no such penalty on the Pentium. The second is that the cache line size (the number of bytes fetched from the external cache or main memory on a cache miss) on the Pentium is 32 bytes, twice the size of the 486’s cache line, so a cache miss causes a longer run of instructions to be placed in the cache than on the 486. The third is that the Pentium’s external bus is twice as wide as the 486’s, at 64 bits, and runs twice as fast, at 66 MHz, so the Pentium can fetch both instruction and data bytes from the external cache four times as fast as the 486.

      Even when the Pentium is running flat-out with both pipes in use, it can generally consume only about twice as many bytes as the 486; so the ratio of external memory bandwidth to processing power is much improved, although real-world performance is heavily dependent on the size and speed of the external cache.

      The upshot of all this is that at the same clock speed, with code and data that are mostly in the internal caches, the Pentium maxes out somewhere around twice as fast as a 486. (When the caches are missed a lot, the Pentium can get as much as three to four times faster, due to the superior external bus and bigger caches.) Most of this won’t affect how you program, but it is useful to know that you don’t have to worry about instruction fetching. It’s also useful to know the sizes of the caches because a high cache hit rate is crucial to Pentium performance. Cache misses are vastly slower than cache hits (anywhere from two to 50 or more times as slow, depending on the speed of the external cache and whether the external cache misses as well), and the Pentium can’t use the V-pipe on code that hasn’t already been executed out of the cache at least once. This means that it is very important to get the working sets of critical loops to fit in the internal caches.

      One change in the Pentium that you definitely do have to worry about is superscalar execution. Utilization of the V-pipe can range from near zero percent to 100 percent, depending on the code being executed, and careful rearrangement of code can have amazing effects. Maxing out V-pipe use is not a trivial task; I’ll spend all of the next chapter discussing it so as to have time to cover it properly. In the meantime, two good references for superscalar programming and other Pentium information are Intel’s Pentium Processor User’s Manual: Volume 3: Architecture and Programming Manual (ISBN 1-55512-195-0; Intel order number 241430-001), and the article “Optimizing Pentium Code” by Mike Schmidt, in Dr. Dobb’s Journal for January 1994.

      -

      Cache Organization

      +

      Cache Organization

      There are two other interesting changes in the Pentium’s cache organization. First, the cache is two-way set-associative, whereas the 486 is four-way set-associative. The details of this don’t matter, but simply put, this, combined with the 32-byte cache line size, means that the Pentium has somewhat coarser granularity in both space and time than the 486 in terms of packing bytes into the cache, although the total cache space is now bigger. There’s nothing you can do about this, but it may make it a little harder to get a loop’s working set into the cache. Second, the internal cache can now be configured (by the BIOS or OS; you won’t have to worry about it) for write-back rather than write-through operation. This means that writes to the internal data cache don’t necessarily get propagated to the external bus until other demands for cache space force the data out of the cache, making repeated writes to memory variables such as loop counters cheaper on average than on the 486, although not as cheap as registers.

      As a final note on Pentium architecture for this chapter, the pipeline stalls (what Intel calls AGIs, for Address Generation Interlocks) that I discussed earlier in this book (see Chapter 12) are still present in the Pentium. In fact, they’re there in spades on the Pentium; the two pipelines mean that an AGI can now slow down execution of an instruction that’s three instructions away from the AGI (because four instructions can execute in two cycles). So, for example, the code sequence

      @@ -88,7 +88,7 @@ add edx,4 ;V-pipe cycle 2
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/19-03.html b/19-03.html index f14bf40..7b63ace 100644 --- a/19-03.html +++ b/19-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Faster Addressing and More

      +

      Faster Addressing and More

      I’ll spend the rest of this chapter covering a variety of Pentium optimization tips. For starters, effective address calculations (that is, the addition and scaling required to calculate a memory operand’s address, as for example in MOV EAX,[EBX+ECX*2+4]) never take any extra cycles on the Pentium (other than possibly an AGI cycle), even for the use of base+index addressing (as in MOV [ESI+EDI],EAX) or scaling (*2, *4, or *8, as in INC ARRAY[ESI*4]). On the 486, both of the latter cases cause a 1-cycle penalty. The faster effective address calculations have the side effect of making LEA very attractive as an arithmetic instruction. LEA can add any two registers, one of which can be multiplied by one, two, four, or eight, plus a constant value, and can store the result in any register—all in one cycle, apart from AGIs. Not only that, but as we’ll see in the next chapter, LEA can go through either pipe, whereas SHL can only go through the U-pipe, so LEA is often a superior choice for multiplication by three, four, five, eight, or nine. (ADD is the best choice for multiplication by two.) If you use LEA for arithmetic, do remember that unlike ADD and SHL, it doesn’t modify any flags.

      As on the 486, memory operands should not cross any more alignment boundaries than absolutely necessary. Word operands should be word-aligned, dword operands should be dword-aligned, and qword operands (double-precision variables) should be qword-aligned. Spanning a dword boundary, as in

      @@ -67,7 +67,7 @@ mov eax,[ebx]
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/19-04.html b/19-04.html index 022ece4..10e6287 100644 --- a/19-04.html +++ b/19-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Branch Prediction

      +

      Branch Prediction

      One brand-spanking-new feature of the Pentium is branch prediction, whereby the Pentium tries to guess, based on past history, which way (or, for conditional jumps, whether or not), your code will jump at each branch, and prefetches along the likelier path. If the guess is correct, the branch or fall-through takes only 1 cycle—2 cycles less than a branch and the same as a fall-through on the 486; if the guess is wrong, the branch or fall-through takes 4 or 5 cycles (if it executes in the U- or V-pipe, respectively)—1 or 2 cycles more than a branch and 3 or 4 cycles more than a fall-through on the 486.

      Branch prediction is unprecedented in the x86, and fundamentally alters the nature of pedal-to-the-metal optimization, for the simple reason that it renders unrolled loops largely obsolete. Rare indeed is the loop that can’t afford to spare even 1 or 0 (yes, zero!) cycles per iteration for loop counting, and that’s how low the cost can go for maintaining a loop on the Pentium.
      @@ -46,12 +46,12 @@

      It’s an equally safe bet that it’s a bad move to have in a loop a conditional branch that goes both ways on a random basis; it’s hard to see how the Pentium could consistently predict such branches correctly, and mispredicted branches are more expensive than they might appear to be. Not only does a mispredicted branch take 4 or 5 cycles, but the Pentium can potentially execute as many as 8 or 10 instructions in that time—3 times as many as the 486 can execute during its branch time—so correct branch prediction (or eliminating branch instructions, if possible) is very important in inner loops. Note that on the 486 you can count on a branch to take 1 cycle when it falls through, but on the Pentium you can’t be sure whether it will take 1 or either 4 or 5 cycles on any given iteration.

      As things currently stand, branch prediction is an annoyance for assembly language optimization because it’s impossible to be certain exactly how code will perform until you measure it, and even then it’s difficult to be sure exactly where the cycles went. All I can say is try to fall through branches if possible, and try to be consistent in your branching if not.
      -

      Miscellaneous Pentium Topics

      +

      Miscellaneous Pentium Topics

      The Pentium has all the instructions of the 486, plus a few new ones. One much-needed instruction that has finally made it into the instruction set is CPUID, which allows your code to determine what processor it’s running on. CPUID is 15 years late, but at least it’s finally here. Another new instruction is CMPXCHG8B, which does a compare and conditional exchange on a qword. CMPXCHG8B doesn’t seem to me to be a particularly useful instruction, but I’m sure Intel wouldn’t have added it without a reason; if you know of a use for it, please pass it along to me.

      -

      486 versus Pentium Optimization

      +

      486 versus Pentium Optimization

      Many Pentium optimizations help, or at least don’t hurt, on the 486. Many, but not all—and many do hurt on the 386. As I discuss various Pentium optimizations, I will attempt to note the effects on the 486 as well, but doing this in complete detail would double the sizes of these discussions and make them hard to follow. In general, I’d recommend reserving Pentium optimization for your most critical code, and even there, it’s a good idea to have at least two code paths, one for the 386 and one for the 486/Pentium. It’s also a good idea to time your code on a 486 before and after Pentium-optimizing it, to make sure you haven’t hurt performance on what will be, after all, by far the most important processor over the next couple of years.

      With that in mind, is optimizing for the Pentium even worthwhile today? That depends on your application and its market—but if you want absolutely the best possible performance for your DOS and Windows apps on the fastest hardware, Pentium optimization can make your code scream.

      -

      Going Superscalar

      +

      Going Superscalar

      In the next chapter, we’ll look into the single biggest element of Pentium performance, cranking up the Pentium’s second execution pipe. This is the area in which compiler technology is most touted for the Pentium, the two thoughts apparently being that (1) most existing code is in C, so recompiling to use the second pipe better is an automatic win, and (2) it’s so complicated to optimize Pentium code that only a compiler can do it well. The first point is a reasonable one, but it does suffer from one flaw for large programs, in that Pentium-optimized code is larger than 486- or 386-optimized code, for reasons that will become apparent in the next chapter. Larger code means more cache misses and more page faults; and while most of the code in any program is not critical to performance, compilers optimize code indiscriminately.

      The result is that Pentium compiler optimization not only expands code, but can be less beneficial than expected or even slower in some cases. What makes more sense is enabling Pentium optimization only for key code. Better yet, you could hand-tune the most important code—and yes, you can absolutely do a better job with a small, critical loop than any PC compiler I’ve ever seen, or expect to see. Sure, you keep hearing how great each new compiler generation is, and compilers certainly have improved; but they play by the same rules we do, and we’re more flexible and know more about what we’re doing—and now we have the wonderfully complex and powerful Pentium upon which to loose our carbon-based optimizers.

      @@ -68,7 +68,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/20-01.html b/20-01.html index e307993..72cf833 100644 --- a/20-01.html +++ b/20-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,21 +36,20 @@


      -

      Chapter 20
      Pentium Rules -

      -

      How Your Carbon-Based Optimizer Can Put the “Super” in Superscalar

      +

      Chapter 20
      Pentium Rules

      +

      How Your Carbon-Based Optimizer Can Put the “Super” in Superscalar

      At the 1983 West Coast Computer Faire, my friend Dan Illowsky, Andy Greenberg (co-author of Wizardry, at that time the best-selling computer game ever), and I had an animated discussion about starting a company in the then-budding world of microcomputer software. One hot new software category at the time was educational software, and one of the hottest new educational software companies was Spinnaker Software. Andy used Spinnaker as an example of a company that had been aimed at a good market and started up properly, and was succeeding as a result. Dan didn’t buy this; his point was that Spinnaker had been given a bundle of money to get off the ground, and was growing only by spending a lot of that money in order to move its products. “Heck,” said Dan, “I could get that kind of market share too if I gave away a fifty-dollar bill with each of my games.”

      Remember, this was a time when a program, two diskette drives (for duplicating disks), and a couple of ads were enough to start a company, and, in fact, Dan built a very successful game company out of not much more than that. (I’ll never forget coming to visit one day and finding his apartment stuffed literally to the walls and ceiling with boxes of diskettes and game packages; he had left a narrow path to the computer so his wife and his mother could get in there to duplicate disks.) Back then, the field was wide open, with just about every competent programmer thinking of striking out on his or her own to try to make their fortune, and Dan and Andy and I were no exceptions. In short, we were having a perfectly normal conversation, and Dan’s comment was both appropriate, and, in retrospect, accurate.

      Appropriate, save for one thing: We were having this conversation while walking through a low-rent section of Market Street in San Francisco at night. A bum sitting against a nearby building overheard Dan, and rose up, shouting in a quavering voice loud enough to wake the dead, “Fifty-dollar bill! Fifty-dollar bill! He’s giving away fifty-dollar bills!” We ignored him; undaunted, he followed us for a good half mile, stopping every few feet to bellow “fifty-dollar bill!” No one else seemed to notice, and no one hassled us, but I was mighty happy to get to the sanctuary of the Fairmont Hotel and slip inside.

      The point is, most actions aren’t inherently good or bad; it’s all a matter of context. If Dan had uttered the words “fifty-dollar bill” on the West Coast Faire’s show floor, no one would have batted an eye. If he had said it in a slightly worse part of town than he did, we might have learned just how fast the three of us could run.

      Similarly, there’s no such thing as inherently fast code, only fast code in context. At the moment, the context is the Pentium, and the truth is that a sizable number of the x86 optimization tricks that you and I have learned over the past ten years are obsolete on the Pentium. True, the Pentium contains what amounts to about one-and-a-half 486s, but, as we’ll see shortly, that doesn’t mean that optimized Pentium code looks much like optimized 486 code, or that fast 486 code runs particularly well on a Pentium. (Fast Pentium code, on the other hand, does tend to run well on the 486; the only major downsides are that it’s larger, and that the FXCH instruction, which is largely free on the Pentium, is expensive on the 486.) So discard your x86 preconceptions as we delve into superscalar optimization for this one-of-a-kind processor.

      -

      An Instruction in Every Pipe

      +

      An Instruction in Every Pipe

      In the last chapter, we took a quick tour of the Pentium’s architecture, and started to look into the Pentium’s optimization rules. Now we’re ready to get to the key rules, those having to do with the Pentium’s most unique and powerful feature, the ability to execute more than one instruction per cycle. This is known as superscalar execution, and has heretofore been the sole province of fast RISC CPUs. The Pentium has two integer execution units, called the U-pipe and the V-pipe, which can execute two separate instructions simultaneously, potentially doubling performance—but only under the proper conditions. (There is also a separate floating-point execution unit that I won’t have the space to cover in this book.) Your job, as a performance programmer, is to understand the conditions needed for superscalar performance and make sure they’re met, and that’s what this and the next chapters are all about.

      The two pipes are not independent processors housed in a single chip; that is, the Pentium is not like having two 486s in a single computer. Rather, the two pipes are integral, parallel parts of the same processor. They operate on the same instruction stream, with the V-pipe simply executing the next instruction that the U-pipe would have handled, as shown in Figure 20.1. What the Pentium does, pure and simple, is execute a single instruction stream and, whenever possible, take the next two waiting instructions and execute both at once, rather than one after the other.

      The U-pipe is the more capable of the two pipes, able to execute any instruction in the Pentium’s instruction set. (A number of instructions actually use both pipes at once. Logically, though, you can think of such instructions as U-pipe instructions, and of the Pentium optimization model as one in which the U-pipe is able to execute all instructions and is always active, with the objective being to keep the V-pipe also working as much of the time as possible.) The U-pipe is generally similar to a full 486 in terms of both capabilities and instruction cycle counts. The V-pipe is a 486 subset, able to execute simple instructions such as MOV and ADD, but unable to handle MUL, DIV, string instructions, any sort of rotation or shift, or even ADC or SBB.


      Figure 20.1
        The Pentium’s two pipes. +
      -->Figure 20.1  The Pentium’s two pipes.

      Getting two instructions executing simultaneously in the two pipes is trickier than it sounds, not only because the V-pipe can handle only a relatively small subset of the Pentium’s instruction set, but also because those instructions that the V-pipe can handle are able to pair only with certain U-pipe instructions. For example, MOVSD uses both pipes, so no instruction can be executed in parallel with MOVSD.

      The use of both pipes does make MOVSD nearly twice as fast on the Pentium as on the 486, but it’s nonetheless slower than using equivalent simpler instructions that allow for superscalar execution. Stick to the Pentium’s RISC-like instructions—the pairable instructions I’ll discuss next—when you’re seeking maximum performance, with just a few exceptions such as REP MOVS and REP STOS. @@ -70,7 +69,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/20-02.html b/20-02.html index 6ff7923..376e873 100644 --- a/20-02.html +++ b/20-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      V-Pipe-Capable Instructions

      +

      V-Pipe-Capable Instructions

      Any instruction can go through the U-pipe, and, for practical purposes, the U-pipe is always executing instructions. (The exceptions are when the U-pipe execution unit is waiting for instruction or data bytes after a cache miss, and when a U-pipe instruction finishes before a paired V-pipe instruction, as I’ll discuss below.) Only the instructions shown in Table 20.1 can go through the V-pipe. In addition, the V-pipe can execute a separate instruction only when one of the instructions listed in Table 20.2 is executing in the U-pipe; superscalar execution is not possible while any instruction not listed in Table 20.2 is executing in the U-pipe. So, for example, if you use SHR EDX,CL, which takes 4 cycles to execute, no other instructions can execute during those 4 cycles; if, on the other hand, you use SHR EDX,10, it will take 1 cycle to execute in the U-pipe, and another instruction can potentially execute concurrently in the V-pipe. (As you can see, similar instruction sequences can have vastly different performance characteristics on the Pentium.)

      Basically, after the current instruction or pair of instructions is finished (that is, once neither the U- nor V-pipe is executing anything), the Pentium sends the next instruction through the U-pipe. If the instruction after the one in the U-pipe is an instruction the V-pipe can handle, if the instruction in the U-pipe is pairable, and if register contention doesn’t occur, then the V-pipe starts executing that instruction, as shown in Figure 20.2. Otherwise, the second instruction waits until the first instruction is done, then executes in the U-pipe, possibly pairing with the next instruction in line if all pairing conditions are met.


      @@ -126,7 +126,7 @@ ROL/ROR/RCL/RCR reg,1 (1 cycle)
      A fundamental rule of Pentium optimization is that it pays to break complex instructions into equivalent simple instructions, then shuffle the simple instructions for maximum use of the V-pipe. This is true partly because most of the pairable instructions are simple instructions, and partly because breaking instructions into pieces allows more freedom to rearrange code to avoid the AGIs and register contention I’ll discuss in the next chapter.


      Figure 20.2
        Instruction flow through the two pipes. +
      -->Figure 20.2  Instruction flow through the two pipes.

      One downside of this “RISCification” (turning complex instructions into simple, RISC-like ones) of Pentium-optimized code is that it makes for substantially larger code. For example,

      @@ -144,7 +144,7 @@ push eax


      Figure 20.3
        Pushing a value from memory effectively in one cycle. +
      -->Figure 20.3  Pushing a value from memory effectively in one cycle.

      A more telling example is the following

      @@ -178,7 +178,7 @@ mov [MemVar],edx
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/20-03.html b/20-03.html index d1087e5..633330d 100644 --- a/20-03.html +++ b/20-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,20 +36,20 @@


      -

      Lockstep Execution

      +

      Lockstep Execution

      You may wonder why anyone would bother breaking ADD [MemVar],EAX into three instructions, given that this instruction can go through either pipe with equal ease. The answer is that while the memory-accessing instructions other than MOV, PUSH, and POP listed in Table 20.1 (that is, INC/DEC [mem], ADD/SUB/XOR/AND/OR/CMP/ADC/SBB reg,[mem], and ADD/SUB/XOR/AND/OR/CMP/ADC/SBB [mem],reg/immed) can be paired, they do not provide the 100 percent overlap that we seek. If you look at Tables 20.1 and 20.2, you will see that instructions taking from 1 to 3 cycles can pair. However, any pair of instructions goes through the two pipes in lockstep. This means, for example, that if ADD [EBX],EDX is going through the U-pipe, and INC EAX is going through the V-pipe, the V-pipe will be idle for 2 of the 3 cycles that the U-pipe takes to execute its instruction, as shown in Figure 20.4. Out of the theoretical 6 cycles of work that can be done during this time, we actually get only 4 cycles of work, or 67 percent utilization. Even though these instructions pair, then, this sequence fails to make maximum use of the Pentium’s horsepower.

      The key here is that when two instructions pair, both execution units are tied up until both instructions have finished (which means at least for the amount of time required for the longer of the two to execute, plus possibly some extra cycles for pairable instructions that can’t fully overlap, as described below). The logical conclusion would seem to be that we should strive to pair instructions of the same lengths, but that is often not correct.

      The actual rule is that we should strive to pair one-cycle instructions (or, at most, two-cycle instructions, but not three-cycle instructions), which in turn leads to the corollary that we should, in general, use mostly one-cycle instructions when optimizing.


      Figure 20.4
        Lockstep execution and idle time in the V-pipe. +
      -->Figure 20.4  Lockstep execution and idle time in the V-pipe.

      Here’s why. The Pentium is fully capable of handling instructions that use memory operands in either pipe, or, if necessary, in both pipes at once. Each pipe has its own write FIFO, which buffers the last few writes and takes care of writing the data out while the Pentium continues processing. The Pentium also has a write-back internal data cache, so data that is frequently changed doesn’t have to be written to external memory (which is much slower than the cache) very often. This combination means that unless you write large blocks of data at a high speed, the Pentium should be able to keep up with both pipes’ memory writes without stalling execution.

      The Pentium is also designed to satisfy both pipes’ needs for reading memory operands with little waiting. The data cache is constructed so that both pipes can read from the cache on the same cycle. This feat is accomplished by organizing the data cache as eight-banked memory, as shown in Figure 20.5, with each 32-byte cache line consisting of 8 dwords, 1 in each bank. The banks are independent of one another, so as long as the desired data is in the cache and the U- and V-pipes don’t try to read from the same bank on the same cycle, both pipes can read memory operands on the same cycle. (If there is a cache bank collision, the V-pipe instruction stalls for one cycle.)

      Normally, you won’t pay close attention to which of the eight dword banks your paired memory accesses fall in—that’s just too much work—but you might want to watch out for simultaneously read addresses that have the same values for address


      Figure 20.5
        The Pentium’s eight bank data cache. +
      -->Figure 20.5  The Pentium’s eight bank data cache.

      bits 2, 3, and 4 (fall in the same bank) in tight loops, and you should also avoid sequences like

      @@ -97,7 +97,7 @@ add edi,[DestinationSkip] ;V-pipe cycles 1 and 2
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/20-04.html b/20-04.html index 091accf..999bdb1 100644 --- a/20-04.html +++ b/20-04.html @@ -24,7 +24,7 @@ - +
      @@ -38,14 +38,14 @@


      However, this beneficial pairing does not extend to non-MOV instructions with explicit memory destination operands, such as ADD [EBX],EAX. The Pentium executes only one such memory instruction at a time; if two memory-destination complex instructions get paired, first the U-pipe instruction is executed, and then the V-pipe instruction, with only one cycle of overlap, as shown in Figure 20.6. I don’t know for sure, but I’d guess that this is to guarantee that the two pipes will never perform out-of-order access to any given memory location. Thus, even though AND [EBX],AL pairs with AND [ECX],DL, the two instructions take 5 cycles in all to execute, and 4 cycles of idle time—2 in the U-pipe and 2 in the V-pipe, out of 10 cycles in all—are incurred in the process.


      Figure 20.6
        Non-overlapped lockstep execution. +
      -->Figure 20.6  Non-overlapped lockstep execution.


      Figure 20.7
        Interleaving simple instructions for maximum performance. +
      -->Figure 20.7  Interleaving simple instructions for maximum performance.

      The solution is to break the instructions into simple instructions and interleave them, as shown in Figure 20.7, which accomplishes the same task in 3 cycles, with no idle cycles whatsoever. Figure 20.7 is a good example of what optimized Pentium code generally looks like: mostly one-cycle instructions, mixed together so that at least two operations are in progress at once. It’s not the easiest code to read or write, but it’s the only way to get both pipes running at capacity.

      -

      Superscalar Notes

      +

      Superscalar Notes

      You may well ask why it’s necessary to interleave operations, as is done in Figure 20.7. It seems simpler just to turn

      @@ -64,7 +64,7 @@ mov [ebx],dl

      and be done with it. The problem here is one of dependency. Before the Pentium can execute AND DL,AL,, it must first know what is in DL, and it can’t know that until it loads DL from the address pointed to by EBX. Therefore, AND DL,AL can’t happen until the cycle after MOV DL,[EBX] executes. Likewise, the result can’t be stored until the cycle after AND DL,AL has finished. This means that these instructions, as written, can’t possibly pair, so the sequence takes the same three cycles as AND [EBX],AL. (Now it should be clear why AND [EBX], AL takes 3 cycles.) Consequently, it’s necessary to interleave these instructions with instructions that use other registers, so this set of operations can execute in one pipe while the other, unrelated set executes in the other pipe, as is done in Figure 20.7.

      What we’ve just seen is the read-after-write form of the superscalar hazard known as register contention. I’ll return to the subject of register contention in the next chapter; in the remainder of this chapter I’d like to cover a few short items about superscalar execution.

      -

      Register Starvation

      +

      Register Starvation

      The above examples should make it pretty clear that effective superscalar programming puts a lot of strain on the Pentium’s relatively small register set. There are only seven general-purpose registers (I strongly suggest using EBP in critical loops), and it does not help to have to sacrifice one of those registers for temporary storage on each complex memory operation; in pre-superscalar days, we used to employ those handy CISC memory instructions to do all that stuff without using any extra registers.

      More problematic still is that for maximum pairing, you’ll typically have two operations proceeding at once, one in each pipe, and trying to keep two operations in registers at once is difficult indeed. There’s not much to be done about this, other than clever and Spartan register usage, but be aware that it’s a major element of Pentium performance programming. @@ -74,7 +74,7 @@ mov [ebx],dl

      Finally, bear in mind that if the instructions being executed have not already been executed at least once since they were loaded into the internal cache, they can pair only if the first (U-pipe) instruction is not only pairable but also exactly 1 byte long, a category that includes only INC reg, DEC reg, PUSH reg, and POP reg. Knowing this can help you understand why sometimes, timing reveals that your code runs slower than it seems it should, although this will generally occur only when the cache working set for the code you’re timing is on the order of 8K or more—an awful lot of code to try to optimize.

      It should be excruciatingly clear by this point that you must time your Pentium-optimized code if you’re to have any hope of knowing if your optimizations are working as well as you think they are; there are just too many details involved for you to be sure your optimizations are working properly without checking. My most basic optimization rule has always been to grab the Zen timer and measure actual performance—and nowhere is this more true than on the Pentium. Don’t believe it until you measure it!


      Figure 20.8
        Prefix delays. +
      -->Figure 20.8  Prefix delays.


      @@ -88,7 +88,7 @@ mov [ebx],dl
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/21-01.html b/21-01.html index a120c7c..f58a9e3 100644 --- a/21-01.html +++ b/21-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,13 +36,12 @@


      -

      Chapter 21
      Unleashing the Pentium’s V-Pipe -

      -

      Focusing on Keeping Both Pentium Pipes Full

      +

      Chapter 21
      Unleashing the Pentium’s V-Pipe

      +

      Focusing on Keeping Both Pentium Pipes Full

      The other day, my daughter suggested that we each draw the prettiest picture we could, then see whose was prettier. I won’t comment on who won, except to note that apparently a bolt of lightning zipping toward a moose with antlers that bear an unfortunate resemblance to a propeller beanie isn’t going to win me any scholarships to art school, if you catch my drift. Anyway, my drawing happened to feature the word “chartreuse” (because it rhymed with “moose” and “Zeus”—hence the lightning; more than that I am not at liberty to divulge), and she wanted to know if the moose was actually chartreuse. I had to admit that I didn’t know, so we went to the dictionary, whereupon we learned that chartreuse is a pale apple-green color. Then she brought up the Windows Control Panel, pointed to the selection of predefined colors, and asked, “Which of those is chartreuse?”—and I realized that I still didn’t know.

      Some things can be described perfectly with words, but others just have to be experienced. Color is one such category, and Pentium optimization is another. I’ve spent the last two chapters detailing the rules for Pentium optimization, and I’ll spend half of this one doing so, as well. That’s good; without understanding the fundamentals, we have no chance of optimizing well. It’s not enough, though. We also need to look at a real-world example of Pentium optimization in action, and we’ll do that later in this chapter; after which, you should go out and do some Pentium optimization on your own. Optimization is one of those things that you can learn a lot about from reading, but ultimately it has to sink into your pores as you do it—especially Pentium optimization because the Pentium is perhaps the most complex (and rewarding) chip to optimize for that I’ve ever seen.

      In the last chapter, we explored the dual-execution-pipe nature of the Pentium, and learned which instructions could pair (execute simultaneously) in which pipes. Now we’re ready to look at AGIs and register contention—two hazards that can prevent otherwise properly written code from taking full advantage of the Pentium’s two pipes, and can thereby keep your code from pushing the Pentium to maximum performance.

      -

      Address Generation Interlocks

      +

      Address Generation Interlocks

      The Pentium is advertised as having a five-stage pipeline for each of its execution units. All this means is that at any given time, up to five instructions are in various stages of execution in each pipe; this overlapping of execution is done for speed, so each instruction doesn’t have to wait until the previous one has finished. The only way that the Pentium’s pipelining directly affects the way you program is in the areas of AGIs and register dependencies.

      AGIs are Address Generation Interlocks, a fancy way of saying that if a register is used to address memory, as is EBX in this instruction

      @@ -55,7 +54,7 @@ mov [ebx],eax

      The rule for AGIs is simple: If you modify any part of a register during a cycle, you cannot use that register to address memory during either that cycle or the next cycle. If you try to do this, the Pentium will simply stall the instruction that tries to use that register to address memory until two cycles after the register was modified. This was true on the 486 as well, but the Pentium’s new twist is that since more than one instruction can execute in a single cycle, an AGI can stall an instruction that’s as many as three instructions away from the changing of the addressing register, as shown in Figure 21.1, and an AGI can also cause a stall that costs as many as three instructions, as shown in Figure 21.2. This means that AGIs are both much easier to cause and potentially more expensive than on the 486, and you must keep a sharp eye out for them. It also means that it’s often worth calculating a memory pointer several instructions ahead of its actual use. Unfortunately, this tends to extend the lifetimes of pointer registers to span a greater number of instructions, making the Pentium’s relatively small register set seem even smaller.


      Figure 21.1
        An AGI can stall up to three instructions later. +
      -->Figure 21.1  An AGI can stall up to three instructions later.

      As an example of a sort of AGI that’s new to the Pentium, consider the following test for a NULL pointer, followed by the use of the pointer if it’s not NULL:

      @@ -73,7 +72,7 @@ mov edx,[ebp-8] ;V-pipe cycle 3 lockstep idle

      This commonplace code loses a U-pipe cycle to the AGI caused by AND EBX,EBX, followed by the attempt two instructions later to use EBX to point to memory. The code loses a V-pipe cycle as well, because lockstep execution won’t let the next V-pipe instruction execute until the paired U-pipe instruction that suffered the AGI finishes. The solution is to use TEST EBX,EBX instead of AND; TEST can’t modify EBX, so no AGI occurs. Sure, AND EBX,EBX doesn’t modify EBX either, but the Pentium doesn’t know that, so it has to insert the AGI.


      Figure 21.2
        An AGI can cost as many as 3 cycles. +
      -->Figure 21.2  An AGI can cost as many as 3 cycles.


      @@ -87,7 +86,7 @@ mov edx,[ebp-8] ;V-pipe cycle 3 lockstep idle
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/21-02.html b/21-02.html index 6f3de90..f705a22 100644 --- a/21-02.html +++ b/21-02.html @@ -24,7 +24,7 @@ - +
      @@ -84,7 +84,7 @@ mov [MemVar2],0 ;U-pipe 2

      Note, however, that my experiments thus far indicate that the two writes in the first case don’t actually pair (possibly because the memory variables have never been read into the internal cache), so you might want to insert an instruction between the two MOVs—and, of course, this is yet another reason why you should always measure your code’s actual performance.

      -

      Register Contention

      +

      Register Contention

      Finally, we come to the last major component of superscalar optimization: register contention. The basic premise here is simple: You can’t use the same register in two inherently sequential ways in a single cycle. For example, you can’t execute

      @@ -106,7 +106,7 @@ mov al,[Var] ;U-pipe cycle 2

      where an attempt is made to set both EAX and its AL subregister on the same cycle. Write-after-write contention implies that the two instructions comprising the above substitute for MOVZX should have at least one unrelated instruction between them when SUB EAX,EAX executes in the V-pipe.

      -

      Exceptions to Register Contention

      +

      Exceptions to Register Contention

      Intel has special-cased some very useful exceptions to register contention. Happily, write-after-read operations do not cause contention. Such operations, as in

      @@ -140,7 +140,7 @@ LoopTop:
       

      Branches can’t pair in the U-pipe; a branch that executes in the U-pipe runs alone, with the V-pipe idle. If a call or jump is correctly predicted by the Pentium’s branch prediction circuitry (as discussed in the last chapter), it executes in a single cycle, pairing if it runs in the V-pipe; if mispredicted, conditional jumps take 4 cycles in the U-pipe and 5 cycles in the V-pipe, and mispredicted calls and unconditional jumps take 3 cycles in either pipe. Note that RET can’t pair.

      -

      Who’s in First?

      +

      Who’s in First?

      One of the trickiest things about superscalar optimization is that a given instruction stream can execute at a different speed depending on the pipe where it starts execution, because which instruction goes through the U-pipe first determines which of the following instructions will be able to pair. If we take the last example and add one more instruction, the other instructions will go through different pipes than previously, and cause the loop as a whole to take 50 percent longer, even though we only added 25 percent more cycles:

      @@ -169,7 +169,7 @@ LoopTop:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/21-03.html b/21-03.html index 1c3e736..369e343 100644 --- a/21-03.html +++ b/21-03.html @@ -24,7 +24,7 @@ - +
      @@ -37,7 +37,7 @@


      It’s actually not hard to figure out which instructions go through which pipes; just back up until you find an instruction that can’t pair or can only go through the U-pipe, and work forward from there, given the knowledge that that instruction executes in the U-pipe. The easiest thing to look for is branches. All branch target instructions execute in the U-pipe, as do all instructions after conditional branches that fall through. Instructions with prefix bytes are generally good U-pipe markers, although they’re expensive instructions that should be avoided whenever possible, and have at least one aberration with regard to pipe usage, as discussed below. Shifts, rotates, ADC, SBB, and all other instructions not listed in Table 20.1 in the last chapter are likewise U-pipe markers.

      -

      Pentium Optimization in Action

      +

      Pentium Optimization in Action

      Now, let’s take a look at one of the simplest, tightest pieces of code imaginable, and see what our new Pentium perspective reveals. Listing 21.1 shows a loop implementing the TCP/IP checksum, a 16-bit checksum that wraps carries around to the low bit so that the result is endian-independent. This makes it easy to perform checksums on blocks of data regardless of the endian characteristics of the machines on which those blocks are generated and received. (Thanks to fellow performance enthusiast Terje Mathisen for suggesting this checksum as fertile ground for Pentium optimization, in the ibm.pc/fast.code forum on Bix.) The loop in Listing 21.1 consists of exactly five instructions; it’s hard to imagine that there’s a lot of performance to be wrung from this snippet, right?

      LISTING 21.1 L21-1.ASM

      @@ -87,7 +87,7 @@ ckloop:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/21-04.html b/21-04.html index 49f65ee..db54861 100644 --- a/21-04.html +++ b/21-04.html @@ -24,7 +24,7 @@ - +
      @@ -136,7 +136,7 @@ ckloopdone:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/21-05.html b/21-05.html index ba08c02..e0d6004 100644 --- a/21-05.html +++ b/21-05.html @@ -24,7 +24,7 @@ - +
      @@ -121,7 +121,7 @@ ckloopdone:

      Listing 21.5 is undeniably intricate code, and not the sort of thing one would choose to write as a matter of course. On the other hand, it’s five times as fast as the tight, seemingly-speedy loop in Listing 21.1 (and six times as fast as Listing 21.1 would have been if the prefix byte had behaved as expected). That’s an awful lot of speed to wring out of a five-instruction loop, and the TCP/IP checksum is, in fact, used by network software, an area in which a five-times speedup might make a significant difference in overall system performance.

      I don’t claim that Listing 21.5 is the fastest possible way to do a TCP/IP checksum on a Pentium; in fact, it isn’t. Unrolling the loop one more time, together with a trick of Terje’s that uses LEA to advance ESI (neither LEA nor DEC affects the carry flag, allowing Terje to add the carry from the previous loop iteration into the next iteration’s checksum via ADC), produces a version that’s a full 33 percent faster. Nonetheless, Listings 21.1 through 21.5 illustrate many of the techniques and considerations in Pentium optimization. Hand-optimization for the Pentium isn’t simple, and requires careful measurement to check the efficacy of your optimizations, so reserve it for when you really, really need it—but when you need it, you need it bad.

      -

      A Quick Note on the 386 and 486

      +

      A Quick Note on the 386 and 486

      I’ve mentioned that Pentium-optimized code does fine on the 486, but not always so well on the 386. On a 486, Listing 21.1 runs at 9 cycles per checksummed word, and Listing 21.5 runs at 2.5 cycles per checksummed word, a healthy 3.6-times speedup. On a 386, Listing 21.1 runs at 22 cycles per word; Listing 21.5 runs at 7 cycles per word, a 3.1-times speedup. As is often the case, Pentium optimization helped the other processors, but not as much as it helped the Pentium, and less on the 386 than on the 486.


      @@ -136,7 +136,7 @@ ckloopdone:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/22-01.html b/22-01.html index 2519e0c..967f57a 100644 --- a/22-01.html +++ b/22-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,11 @@


      -

      Chapter 22
      Zenning and the Flexible Mind -

      -

      Taking a Spin through What You’ve Learned

      +

      Chapter 22
      Zenning and the Flexible Mind

      +

      Taking a Spin through What You’ve Learned

      And so we come to the end of our journey; for now, at least. What follows is a modest bit of optimization, one which originally served to show readers of Zen of Assembly Language that they had learned more than just bits and pieces of knowledge; that they had also begun to learn how to apply the flexible mind—unconventional, broadly integrative thinking—to approaching high-level optimization at the algorithmic and program design levels. You, of course, need no such reassurance, having just spent 21 chapters learning about the flexible mind in many guises, but I think you’ll find this example instructive nonetheless. Try to stay ahead as the level of optimization rises from instruction elimination to instruction substitution to more creative solutions that involve broader understanding and redesign. We’ll start out by compacting individual instructions and bits of code, but by the end we’ll come up with a solution that involves the very structure of the subroutine, with each instruction carefully integrated into a remarkably compact whole. It’s a neat example of how optimization operates at many levels, some much less determininstic than others—and besides, it’s just plain fun.

      Enjoy!

      -

      Zenning

      +

      Zenning

      In Jeff Duntemann’s excellent book Borland Pascal From Square One (Random House, 1993), there’s a small assembly subroutine that’s designed to be called from a Turbo Pascal program in order to fill the screen or a systemscreen buffer with a specified character/attribute pair in text mode. This subroutine involves only 21 instructions and works perfectly well; however, with what we know, we can compact the subroutine tremendously and speed it up a bit as well. To coin a verb, we can “Zen” this already-tight assembly code to an astonishing degree. In the process, I hope you’ll get a feel for how advanced your assembly skills have become.

      Jeff’s original code follows as Listing 22.1 (with some text converted to lowercase in order to match the style of this book), but the comments are mine.

      LISTING 22.1 L22-1.ASM

      @@ -99,7 +98,7 @@ ClearS endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/22-02.html b/22-02.html index 85e8c2f..3694c03 100644 --- a/22-02.html +++ b/22-02.html @@ -24,7 +24,7 @@ - +
      @@ -136,7 +136,7 @@ ClearS endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/22-03.html b/22-03.html index f381045..ab7194c 100644 --- a/22-03.html +++ b/22-03.html @@ -24,7 +24,7 @@ - +
      @@ -125,7 +125,7 @@ ClearS endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-01.html b/23-01.html index b2148bd..8b8853c 100644 --- a/23-01.html +++ b/23-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,23 +36,21 @@


      -

      Part II -

      -

      Chapter 23
      Bones and Sinew -

      -

      At the Very Heart of Standard PC Graphics

      +

      Part II

      +

      Chapter 23
      Bones and Sinew

      +

      At the Very Heart of Standard PC Graphics

      The VGA is unparalleled in the history of computer graphics, for it is by far the most widely-used graphics standard ever, the closest we may ever come to a lingua franca of computer graphics. No other graphics standard has even come close to the 50,000,000 or so VGAs in use today, and virtually every PC compatible sold today has full VGA compatibility built in. There are, of course, a variety of graphics accelerators that outperform the standard VGA, and indeed, it is becoming hard to find a plain vanilla VGA anymore—but there is no standard for accelerators, and every accelerator contains a true-blue VGA at its core.

      What that means is that if you write your programs for the VGA, you’ll have the largest possible market for your software. In order for graphics-based software to succeed, however, it must perform well. Wringing the best performance from the VGA is no simple task, and it’s impossible unless you really understand how the VGA works—unless you have the internals down cold. This book is about PC graphics at many levels, but high performance is the foundation for all that is to come, so it is with the inner workings of the VGA that we will begin our exploration of PC graphics.

      The first eight chapters of Part II is a guided tour of the heart of the VGA; after you’ve absorbed what we’ll cover in this and the next seven chapters, you’ll have the foundation for understanding just about everything the VGA can do, including the fabled Mode X and more. As you read through these first chapters, please keep in mind that the really exciting stuff—animation, 3-D, blurry-fast lines and circles and polygons—has to wait until we have the fundamentals out of the way. So hold on and follow along, and before you know it the fireworks will be well underway.

      We’ll start our exploration with a quick overview of the VGA, and then we’ll dive right in and get a taste of what the VGA can do.

      -

      The VGA

      +

      The VGA

      The VGA is the baseline adapter for modern IBM PC compatibles, present in virtually every PC sold today or in the last several years. (Note that the VGA is often nothing more than a chip on a motherboard, with some memory, a DAC, and maybe a couple of glue chips; nonetheless, I’ll refer to it as an adapter from now on for simplicity.) It guarantees that every PC is capable of documented resolutions up to 640x480 (with 16 possible colors per pixel) and 320x200 (with 256 colors per pixel), as well as undocumented—but nonetheless thoroughly standard—resolutions up to 360x480 in 256-color mode, as we’ll see in Chapters 31-34 and 47-49. In order for a video adapter to claim VGA compatibility, it must support all the features and code discussed in this book (with a very few minor exceptions that I’ll note)—and my experience is that just about 100 percent of the video hardware currently shipping or shipped since 1990 is in fact VGA compatible. Therefore, VGA code will run on nearly all of the 50,000,000 or so PC compatibles out there, with the exceptions being almost entirely obsolete machines from the 1980s. This makes good VGA code and VGA programming expertise valuable commodities indeed.

      Right off the bat, I’d like to make one thing perfectly clear: The VGA is hard—sometimes very hard—to program for good performance. Hard, but not impossible—and that’s why I like this odd board. It’s a throwback to an earlier generation of micros, when inventive coding and a solid understanding of the hardware were the best tools for improving performance. Increasingly, faster processors and powerful coprocessors are seen as the solution to the sluggish software produced by high-level languages and layers of interface and driver code, and that’s surely a valid approach. However, there are tens of millions of VGAs installed right now, in machines ranging from 6-MHz 286s to 90-MHz Pentiums. What’s more, because the VGAs are generally 8- or at best 16-bit devices, and because of display memory wait states, a faster processor isn’t as much of a help as you’d expect. The upshot is that only a seasoned performance programmer who understands the VGA through and through can drive the board to its fullest potential.

      Throughout this book, I’ll explore the VGA by selecting a specific algorithm or feature and implementing code to support it on the VGA, examining aspects of the VGA architecture as they become relevant. You’ll get to see VGA features in context, where they are more comprehensible than in IBM’s somewhat arcane documentation, and you’ll get working code to use or to modify to meet your needs.

      The prime directive of VGA programming is that there’s rarely just one way to program the VGA for a given purpose. Once you understand the tools the VGA provides, you’ll be able to combine them to generate the particular synergy your application needs. My VGA routines are not intended to be taken as gospel, or to show “best” implementations, but rather to start you down the road to understanding the VGA.

      Let’s begin.

      -

      An Introduction to VGA Programming

      +

      An Introduction to VGA Programming

      Most discussions of the VGA start out with a traditional “Here’s a block diagram of the VGA” approach, with lists of registers and statistics. I’ll get to that eventually, but you can find it in IBM’s VGA documentation and several other books. Besides, it’s numbing to read specifications and explanations, and the VGA is an exciting adapter, the kind that makes you want to get your hands dirty probing under the hood, to write some nifty code just to see what the board can do. What’s more, the best way to understand the VGA is to see it work, so let’s jump right into a sample of the VGA in action, getting a feel for the VGA’s architecture in the process.

      Listing 23.1 is a sample VGA program that pans around an animated 16-color medium-resolution (640x350) playfield. There’s a lot packed into this code; I’m going to focus on the VGA-specific aspects so we don’t get sidetracked. I’m not going to explain how the ball is animated, for example; we’ll get to animation starting in Chapter 42. What I will do is cover each of the VGA features used in this program—the virtual screen, vertical and horizontal panning, color plane manipulation, multi-plane block copying, and page flipping—at a conceptual level, letting the code itself demonstrate the implementation details. We’ll return to many of these concepts in more depth later in this book.


      @@ -68,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-02.html b/23-02.html index a32d2f3..62fc638 100644 --- a/23-02.html +++ b/23-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      At the Core

      +

      At the Core

      A little background is necessary before we’re ready to examine Listing 23.1. The VGA is built around four functional blocks, named the CRT Controller (CRTC), the Sequence Controller (SC), the Attribute Controller (AC), and the Graphics Controller (GC). The single-chip VGA could have been designed to treat the registers for all the blocks as one large set, addressed at one pair of I/O ports, but in the EGA, each of these blocks was a separate chip, and the legacy of EGA compatibility is why each of these blocks has a separate set of registers and is addressed at different I/O ports in the VGA.

      Each of these blocks has a sizable complement of registers. It is not particularly important that you understand why a given block has a given register; all the registers together make up the programming interface, and it is the entire interface that is of interest to the VGA programmer. However, the means by which most VGA registers are addressed makes it necessary for you to remember which registers are in which blocks.

      @@ -153,7 +153,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-03.html b/23-03.html index e1eae83..7888079 100644 --- a/23-03.html +++ b/23-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Linear Planes and True VGA Modes

      +

      Linear Planes and True VGA Modes

      The VGA’s memory is organized as four 64K planes. Each of these planes is a linear bitmap; that is, each byte from a given plane controls eight adjacent pixels on the screen, the next byte controls the next eight pixels, and so on to the end of the scan line. The next byte then controls the first eight pixels of the next scan line, and so on to the end of the screen.

      The VGA adds a powerful twist to linear addressing; the logical width of the screen in VGA memory need not be the same as the physical width of the display. The programmer is free to define all or part of the VGA’s large memory map as a logical screen of up to 4,080 pixels in width, and then use the physical screen as a window onto any part of the logical screen. What’s more, a virtual screen can have any logical height up to the capacity of VGA memory. Such a virtual screen could be used to store a spreadsheet or a CAD/CAM drawing, for instance. As we will see shortly, the VGA provides excellent hardware for moving around the virtual screen; taken together, the virtual screen and the VGA’s smooth panning capabilities can generate very impressive effects.

      @@ -44,7 +44,7 @@

      Each memory plane provides one bit of data for each pixel. The bits for a given pixel from each of the four planes are combined into a nibble that serves as an address into the VGA’s palette RAM, which maps the one of 16 colors selected by display memory into any one of 64 colors, as shown in Figure 23.1. All sixty-four mappings for all 16 colors are independently programmable. (We’ll discuss the VGA’s color capabilities in detail starting in Chapter 33.)

      The VGA BIOS supports several graphics modes (modes 4, 5, and 6) in which VGA memory appears not to be organized as four linear planes. These modes exist for CGA compatibility only, and are not true VGA graphics modes; use them when you need CGA-type operation and ignore them the rest of the time. The VGA’s special features are most powerful in true VGA modes, and it is on the 16-color true-VGA modes (modes 0DH (320x200), 0EH (640x200), 10H (640x350), and 12H (640x480)) that I will concentrate in this part of the book. There is also a 256-color mode, mode 13H, that appears to be a single linear plane, but, as we will see in Chapters 31-34 and 47-49 of this book, that’s a polite fiction—and discarding that fiction gives us an opportunity to unleash the power of the VGA’s hardware for vastly better performance. VGA text modes, which feature soft fonts, are another matter entirely, upon which we’ll touch from time to time.


      Figure 23.1
        Video data from memory to pixel. +
      -->Figure 23.1  Video data from memory to pixel.

      With that background out of the way, we can get on to the sample VGA program shown in Listing 23.1. I suggest you run the program before continuing, since the explanations will mean far more to you if you’ve seen the features in action.

      @@ -621,7 +621,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-04.html b/23-04.html index 2ed404a..dddd096 100644 --- a/23-04.html +++ b/23-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,11 +36,11 @@


      -

      Smooth Panning

      +

      Smooth Panning

      The first thing you’ll notice upon running the sample program is the remarkable smoothness with which the display pans from side-to-side and up-and-down. That the display can pan at all is made possible by two VGA features: 256K of display memory and the virtual screen capability. Even the most memory-hungry of the VGA modes, mode 12H (640x480), uses only 37.5K per plane, for a total of 150K out of the total 256K of VGA memory. The medium-resolution mode, mode 10H (640x350), requires only 28K per plane, for a total of 112K. Consequently, there is room in VGA memory to store more than two full screens of video data in mode 10H (which the sample program uses), and there is room in all modes to store a larger virtual screen than is actually displayed. In the sample program, memory is organized as two virtual screens, each with a resolution of 672x384, as shown in Figure 23.2. The area of the virtual screen actually displayed at any given time is selected by setting the display memory address at which to begin fetching video data; this is set by way of the start address registers (Start Address High, CRTC register 0CH, and Start Address Low, CRTC register 0DH). Together these registers make up a 16-bit display memory address at which the CRTC begins fetching data at the beginning of each video frame. Increasing the start address causes higher-memory areas of the virtual screen to be displayed. For example, the Start Address High register could be set to 80H and the Start Address Low register could be set to 00H in order to cause the display screen to reflect memory starting at offset 8000H in each plane, rather than at the default offset of 0.


      Figure 23.2
        Video memory organization for Listing 23.1. +
      -->Figure 23.2  Video memory organization for Listing 23.1.

      The logical height of the virtual screen is defined by the amount of VGA memory available. As the VGA scans display memory for video data, it progresses from the start address toward higher memory one scan line at a time, until the frame is completed. Consequently, if the start address is increased, lines farther toward the bottom of the virtual screen are displayed; in effect, the virtual screen appears to scroll up on the physical screen.

      @@ -64,7 +64,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-05.html b/23-05.html index bbbadf8..e82a05a 100644 --- a/23-05.html +++ b/23-05.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Color Plane Manipulation

      +

      Color Plane Manipulation

      The VGA provides a considerable amount of hardware assistance for manipulating the four display memory planes. Two features illustrated by the sample program are the ability to control which planes are written to by a CPU write and the ability to copy four bytes—one from each plane—with a single CPU read and a single CPU write.

      The Map Mask register (SC register 2) selects which planes are written to by CPU writes. If bit 0 of the Map Mask register is 1, then each byte written by the CPU will be written to VGA memory plane 0, the plane that provides the video data for the least significant bit of the palette RAM address. If bit 0 of the Map Mask register is 0, then CPU writes will not affect plane 0. Bits 1, 2, and 3 of the Map Mask register similarly control CPU access to planes 1, 2, and 3, respectively. Any of the 16 possible combinations of enabled and disabled planes can be selected. Beware, however, of writing to an area of memory that is not zeroed. Planes that are disabled by the Map Mask register are not altered by CPU writes, so old and new images can mix on the screen, producing unwanted color effects as, say, three planes from the old image mix with one plane from the new image. The sample program solves this by ensuring that the memory written to is zeroed. A better way to set all planes at once is provided by the set/reset capabilities of the VGA, which I’ll cover in Chapter 25.

      @@ -47,7 +47,7 @@

      The Map Mask register can still mask out planes in write mode 1. All four planes are copied in the sample program because the Map Mask register is still 0Fh from when the blank image was created.

      The animated images appear to move a bit jerkily because they are byte-aligned and so must move a minimum of 8 pixels horizontally. This is easily solved by storing rotated versions of all images in VGA memory, and then in each instance drawing the correct rotation for the pixel alignment at which the image is to be drawn; we’ll see this technique in action in Chapter 49.

      Don’t worry if you’re not catching everything in this chapter on the first pass; the VGA is a complicated beast, and learning about it is an iterative process. We’ll be going over these features again, in different contexts, over the course of the rest of this book.

      -

      Page Flipping

      +

      Page Flipping

      When animated graphics are drawn directly on the screen, with no intermediate frame-composition stage, the image typically flickers and/or ripples, an unavoidable result of modifying display memory at the same time that it is being scanned for video data. The display memory of the VGA makes it possible to perform page flipping, which eliminates such problems. The basic premise of page flipping is that one area of display memory is displayed while another is being modified. The modifications never affect an area of memory as it is providing video data, so no undesirable side effects occur. Once the modification is complete, the modified buffer is selected for display, causing the screen to change to the new image in a single frame’s time, typically 1/60th or 1/70th of a second. The other buffer is then available for modification.

      As described above, the VGA has 64K per plane, enough to hold two pages and more in 640x350 mode 10H, but not enough for two pages in 640x480 mode 12H. For page flipping, two non-overlapping areas of display memory are needed. The sample program uses two 672x384 virtual pages, each 32,256 bytes long, one starting at A000:0000 and the other starting at A000:7E00. Flipping between the pages is as simple as setting the start address registers to point to one display area or the other—but, as it turns out, that’s not as simple as it sounds.

      @@ -66,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/23-06.html b/23-06.html index e1d6fc1..e8b44dd 100644 --- a/23-06.html +++ b/23-06.html @@ -24,7 +24,7 @@ - +
      @@ -44,13 +44,13 @@

      An important point illustrated by the sample program is that while the VGA’s display memory is far larger and more versatile than is the case with earlier adapters, it is nonetheless a limited resource and must be used judiciously. The sample program uses VGA memory to store two 672x384 virtual pages, leaving only 1024 bytes free to store images. In this case, the only images needed are a colored ball and a blank block with which to erase it, so there is no problem, but many applications require dozens or hundreds of images. The tradeoffs between virtual page size, page flipping, and image storage must always be kept in mind when designing programs for the VGA.

      To see the program run in 640x200 16-color mode, comment out the EQU line for MEDRES_VIDEO_MODE.

      -

      The Hazards of VGA Clones

      +

      The Hazards of VGA Clones

      Earlier, I said that any VGA that doesn’t support the features and functionality covered in this book can’t properly be called VGA compatible. I also noted that there are some exceptions, however, and we’ve just come to the most prominent one. You see, all VGAs really are compatible with the IBM VGA’s functionality when it comes to drawing pixels into display memory; all the write modes and read modes and set/reset capabilities and everything else involved with manipulating display memory really does work in the same way on all VGAs and VGA clones. That compatibility isn’t as airtight when it comes to scanning pixels out of display memory and onto the screen in certain infrequently-used ways, however.

      The areas of incompatibility of which I’m aware are illustrated by the sample program, and may in fact have caused you to see some glitches when you ran Listing 23.1. The problem, which arises only on certain VGAs, is that some settings of the Row Offset register cause some pixels to be dropped or displaced to the wrong place on the screen; often, this happens only in conjunction with certain start address settings. (In my experience, only VRAM (Video RAM)-based VGAs exhibit this problem, no doubt due to the way that pixel data is fetched from VRAM in large blocks.) Panning and large virtual bitmaps can be made to work reliably, by careful selection of virtual bitmap sizes and start addresses, but it’s difficult; that’s one of the reasons that most commercial software does not use these features, although a number of games do. The upshot is that if you’re going to use oversized virtual bitmaps and pan around them, you should take great care to test your software on a wide variety of VRAM- and DRAM-based VGAs.

      -

      Just the Beginning

      +

      Just the Beginning

      That pretty well covers the important points of the sample VGA program in Listing 23.1. There are many VGA features we didn’t even touch on, but the object was to give you a feel for the variety of features available on the VGA, to convey the flexibility and complexity of the VGA’s resources, and in general to give you an initial sense of what VGA programming is like. Starting with the next chapter, we’ll begin to explore the VGA systematically, on a more detailed basis.

      -

      The Macro Assembler

      +

      The Macro Assembler

      The code in this book is written in both C and assembly. I think C is a good development environment, but I believe that often the best code (although not necessarily the easiest to write or the most reliable) is written in assembly. This is especially true of graphics code for the x86 family, given segments, the string instructions, and the asymmetric and limited register set, and for real-time programming of a complex board like the VGA, there’s really no other choice for the lowest-level code.

      Before I’m deluged with protests from C devotees, let me add that the majority of my productive work is done in C; no programmer is immune to the laws of time, and C is simply a more time-efficient environment in which to develop, particularly when working in a programming team. In this book, however, we’re after the sine qua non of PC graphics—performance—and we can’t get there from here without a fair amount of assembly language.

      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/24-01.html b/24-01.html index 195e657..0d32062 100644 --- a/24-01.html +++ b/24-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,19 +36,18 @@


      -

      Chapter 24
      Parallel Processing with the VGA -

      -

      Taking on Graphics Memory Four Bytes at a Time

      +

      Chapter 24
      Parallel Processing with the VGA

      +

      Taking on Graphics Memory Four Bytes at a Time

      This heading refers to the ability of the VGA chip to manipulate up to four bytes of display memory at once. In particular, the VGA provides four ALUs (Arithmetic Logic Units) to assist the CPU during display memory writes, and this hardware is a tremendous resource in the task of manipulating the VGA’s sizable frame buffer. The ALUs are actually only one part of the surprisingly complex data flow architecture of the VGA, but since they’re involved in almost all memory access operations, they’re a good place to begin.

      -

      VGA Programming: ALUs and Latches

      +

      VGA Programming: ALUs and Latches

      I’m going to begin our detailed tour of the VGA at the heart of the flow of data through the VGA: the four ALUs built into the VGA’s Graphics Controller (GC) circuitry. The ALUs (one for each display memory plane) are capable of ORing, ANDing, and XORing CPU data and display memory data together, as well as masking off some or all of the bits in the data from affecting the final result. All the ALUs perform the same logical operation at any given time, but each ALU operates on a different display memory byte.

      Recall that the VGA has four display memory planes, with one byte in each plane at any given display memory address. All four display memory bytes operated on are read from and written to the same address, but each ALU operates on a byte that was read from a different plane and writes the result to that plane. This arrangement allows four display memory bytes to be modified by a single CPU write (which must often be preceded by a single CPU read, as we will see). The benefit is vastly improved performance; if the CPU had to select each of the four planes in turn via OUTs and perform the four logical operations itself, VGA performance would slow to a crawl.

      Figure 24.1 is a simplified depiction of data flow around the ALUs. Each ALU has a matching latch, which holds the byte read from the corresponding plane during the last CPU read from display memory, even if that particular plane wasn’t the plane that the CPU actually read on the last read access. (Only one byte can be read by the CPU with a single display memory read; the plane supplying the byte is selected by the Read Map register. However, the bytes at the specified address in all four planes are always read when the CPU reads display memory, and those four bytes are stored in their respective latches.)

      Each ALU logically combines the byte written by the CPU and the byte stored in the matching latch, according to the settings of bits 3 and 4 of the Data Rotate register (and the Bit Mask register as well, which I’ll cover next time), and then writes the result to display memory. It is most important to understand that neither ALU operand comes directly from display memory. The temptation is to think of the ALUs as combining CPU data and the contents of the display memory address being written to, but they actually combine CPU data and the contents of the last display memory location read, which need not be the location being modified. The most common application of the ALUs is indeed to modify a given display memory location, but doing so requires a read from that location to load the latches before the write that modifies it. Omission of the read results in a write operation that logically combines CPU data n with whatever data happens to be in the latches from the last read, which is normally undesirable.


      Figure 24.1
        VGA ALU data flow. +
      -->Figure 24.1  VGA ALU data flow.

      Occasionally, however, the independence of the latches from the display memory location being written to can be used to great advantage. The latches can be used to perform 4-byte-at-a-time (one byte from each plane) block copying; in this application, the latches are loaded with a read from the source area and written unmodified to the destination area. The latches can be written unmodified in one of two ways: By selecting write mode 1 (for an example of this, see the last chapter), or by setting the Bit Mask register to 0 so only the latched bits are written.

      @@ -67,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/24-02.html b/24-02.html index ee53fa4..ba53de8 100644 --- a/24-02.html +++ b/24-02.html @@ -24,7 +24,7 @@ - +
      @@ -306,7 +306,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/24-03.html b/24-03.html index e900ca4..1cb751c 100644 --- a/24-03.html +++ b/24-03.html @@ -24,7 +24,7 @@ - +
      @@ -39,7 +39,7 @@

      Logical function 0, which writes the CPU data unmodified, is the standard mode of operation of the ALUs. In this mode, the CPU data is combined with the latched data by ignoring the latched data entirely. Expressed as a logical function, this could be considered CPU data ANDed with 1 (or ORed with 0). This is the mode to use whenever you want to place CPU data into display memory, replacing the previous contents entirely. It may occur to you that there is no need to latch display memory at all when the data unmodified function is selected. In the sample program, that is true, but if the bit mask is being used, the latches must be loaded even for the data unmodified function, as I’ll discuss in the next chapter.

      Logical functions 1 through 3 cause the CPU data to be ANDed, ORed, and XORed with the latched data, respectively. Of these, XOR is the most useful, since exclusive-ORing is a traditional way to perform animation. The uses of the AND and OR logical functions are less obvious. AND can be used to mask a blank area into display memory, or to mask off those portions of a drawing operation that don’t overlap an existing display memory image. OR could conceivably be used to force an image into display memory over an existing image. To be honest, I haven’t encountered any particularly valuable applications for AND and OR, but they’re the sort of building-block features that could come in handy in just the right context, so keep them in mind.

      -

      Notes on the ALU/Latch Demo Program

      +

      Notes on the ALU/Latch Demo Program

      VGA settings such as the logical function select should be restored to their default condition before the BIOS is called to output text or draw pixels. The VGA BIOS does not guarantee that it will set most VGA registers except on mode sets, and there are so many compatible BIOSes around that the code of the IBM BIOS is not a reliable guide. For instance, when the BIOS is called to draw text, it’s likely that the result will be illegible if the Bit Mask register is not in its default state. Similarly, a mode set should generally be performed before exiting a program that tinkers with VGA settings.

      Along the same lines, the sample program does not explicitly set the Map Mask register to ensure that all planes are enabled for writing. The mode set for mode 10H leaves all planes enabled, so I did not bother to program the Map Mask register, or any other register besides the Data Rotate register, for that matter. However, the profusion of compatible BIOSes means there is some small risk in relying on the BIOS to leave registers set properly. For the highly safety-conscious, the best course would be to program data control registers such as the Map Mask and Read Mask explicitly before relying on their contents.

      @@ -75,7 +75,7 @@ MOV DX,(VALUE2 SHL 8) OR VALUE1
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-01.html b/25-01.html index 1c6eca4..1d23d1e 100644 --- a/25-01.html +++ b/25-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,24 +36,23 @@


      -

      Chapter 25
      VGA Data Machinery -

      -

      The Barrel Shifter, Bit Mask, and Set/Reset Mechanisms

      +

      Chapter 25
      VGA Data Machinery

      +

      The Barrel Shifter, Bit Mask, and Set/Reset Mechanisms

      In the last chapter, we examined a simplified model of data flow within the GC portion of the VGA, featuring the latches and ALUs. Now we’re ready to expand that model to include the barrel shifter, bit mask, and the set/reset capabilities, leaving only the write modes to be explored over the next few chapters.

      -

      VGA Data Rotation

      +

      VGA Data Rotation

      Figure 25.1 shows an expanded model of GC data flow, featuring the barrel shifter and bit mask circuitry. Let’s look at the barrel shifter first. A barrel shifter is circuitry capable of shifting—or rotating, in the VGA’s case—data an arbitrary number of bits in a single operation, as opposed to being able to shift only one bit position at a time. The barrel shifter in the VGA can rotate incoming CPU data up to seven bits to the right (toward the least significant bit), with bit 0 wrapping back to bit 7, after which the VGA continues processing the rotated byte just as it normally processes unrotated CPU data. Thanks to the nature of barrel shifters, this rotation requires no extra processing time over unrotated VGA operations. The number of bits by which CPU data is shifted is controlled by bits 2-0 of GC register 3, the Data Rotate register, which also contains the ALU function select bits (data unmodified, AND, OR, and XOR) that we looked at in the last chapter.


      Figure 25.1
        Data flow through the Graphics Controller. +
      -->Figure 25.1  Data flow through the Graphics Controller.

      The barrel shifter is powerful, but (as sometimes happens in this business) it sounds more useful than it really is. This is because the GC can only rotate CPU data, a task that the CPU itself is perfectly capable of performing. Two OUTs are needed to select a given rotation: one to set the GC Index register, and one to set the Data Rotate register. However, with careful programming it’s sometimes possible to leave the GC Index always pointing to the Data Rotate register, so only one OUT is needed. Even so, it’s often easier and/or faster to simply have the CPU rotate the data of interest CL times than to set the Data Rotate register. (Bear in mind that a single OUT takes from 11 to 31 cycles on a 486—and longer if the VGA is sluggish at responding to OUTs, as many VGAs are.) If only the VGA could rotate latched data, then there would be all sorts of useful applications for rotation, but, sadly, only CPU data can be rotated.

      The drawing of bit-mapped text is one use for the barrel shifter, and I’ll demonstrate that application below. In general, though, don’t knock yourself out trying to figure out how to work data rotation into your programs—it just isn’t all that useful in most cases.

      -

      The Bit Mask

      +

      The Bit Mask

      The VGA has bit mask circuitry for each of the four memory planes. The four bit masks operate in parallel and are all driven by the same mask data for each operation, so they’re generally referred to in the singular, as “the bit mask.” Figure 25.2 illustrates the operation of one bit of the bit mask for one plane. This circuitry occurs eight times in the bit mask for a given plane, once for each bit of the byte written to display memory. Briefly, the bit mask determines on a bit-by-bit basis whether the source for each byte written to display memory is the ALU for that plane or the latch for that plane.


      Figure 25.2
        Bit mask operation. +
      -->Figure 25.2  Bit mask operation.

      The bit mask is controlled by GC register 8, the Bit Mask register. If a given bit of the Bit Mask register is 1, then the corresponding bit of data from the ALUs is written to display memory for all four planes, while if that bit is 0, then the corresponding bit of data from the latches for the four planes is written to display memory unchanged. (In write mode 3, the actual bit mask that’s applied to data written to display memory is the logical AND of the contents of the Bit Mask register and the data written by the CPU, as we’ll see in Chapter 26.)

      @@ -71,7 +70,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-02.html b/25-02.html index d929bde..cbeb73a 100644 --- a/25-02.html +++ b/25-02.html @@ -24,7 +24,7 @@ - +
      @@ -286,7 +286,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-03.html b/25-03.html index e44d788..4b8f077 100644 --- a/25-03.html +++ b/25-03.html @@ -24,7 +24,7 @@ - +
      @@ -42,12 +42,12 @@

      The example code in Listing 25.1 is designed to illustrate the use of the Data Rotate and Bit Mask registers, and is not as fast or as complete as it might be. The case where text is byte-aligned could be detected and performed much faster, without the use of the Bit Mask or Data Rotate registers and with only one display memory access per font byte (to write the font byte), rather than four (to read display memory and write the font byte to each of the two bytes the character spans). Likewise, non-aligned text drawing could be streamlined to one display memory access per byte by having the CPU rotate and combine the font data directly, rather than setting up the VGA’s hardware to do it. (Listing 25.1 was designed to illustrate VGA data rotation and bit masking rather than the fastest way to draw text. We’ll see faster text-drawing code soon.) One excellent rule of thumb is to minimize display memory accesses of all types, especially reads, which tend to be considerably slower than writes. Also, in Listing 25.1 it would be faster to use a table lookup to calculate the bit masks for the two halves of each character rather than the shifts used in the example.

      For another (and more complex) example of drawing bit-mapped text on the VGA, see John Cockerham’s article, “Pixel Alignment of EGA Fonts,” PC Tech Journal, January, 1987. Parenthetically, I’d like to pass along John’s comment about the VGA: “When programming the VGA, everything is complex.”

      He’s got a point there.

      -

      The VGA’s Set/Reset Circuitry

      +

      The VGA’s Set/Reset Circuitry

      At last we come to the final aspect of data flow through the GC on write mode 0 writes: the set/reset circuitry. Figure 25.3 shows data flow on a write mode 0 write. The only difference between this figure and Figure 25.1 is that on its way to each plane potentially the rotated CPU data passes through the set/reset circuitry, which may or may not replace the CPU data with set/reset data. Briefly put, the set/reset circuitry enables the programmer to elect to independently replace the CPU data for each plane with either 00 or 0FFH.

      What is the use of such a feature? Well, the standard way to control color is to set the Map Mask register to enable writes to only those planes that need to be set to produce the desired color. For example, the Map Mask register would be set to 09H to draw in high-intensity blue; here, bits 0 and 3 are set to 1, so only the blue plane (plane 0) and the intensity plane (plane 3) are written to.


      Figure 25.3
        Data flow during a write mode 0 write operation. +
      -->Figure 25.3  Data flow during a write mode 0 write operation.

      Remember, though, that planes that are disabled by the Map Mask register are not written to or modified in any way. This means that the above approach works only if the memory being written to is zeroed; if, however, the memory already contains non-zero data, that data will remain in the planes disabled by the Map Mask, and the end result will be that some planes contain the data just written and other planes contain old data. In short, color control using the Map Mask does not force all planes to contain the desired color. In particular, it is not possible to force some planes to zero and other planes to one in a single write with the Map Mask register.

      @@ -64,7 +64,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-04.html b/25-04.html index 4fa12c0..c5cc247 100644 --- a/25-04.html +++ b/25-04.html @@ -24,7 +24,7 @@ - +
      @@ -122,7 +122,7 @@ cseg ends end start -

      Setting All Planes to a Single Color

      +

      Setting All Planes to a Single Color

      The set/reset circuitry can be used to force some planes to 0-bits and others to 1-bits during a single write, while letting CPU data go to still other planes, and so provides an efficient way to set all planes to a desired color. The set/reset circuitry works as follows:

      For each of the bits 0-3 in the Enable Set/Reset register (Graphics Controller register 1) that is 1, the corresponding bit in the Set/Reset register (GC register 0) is extended to a byte (0 or 0FFH) and replaces the CPU data for the corresponding plane. For each of the bits in the Enable Set/Reset register that is 0, the CPU data is used unchanged for that plane (normal operation). For example, if the Enable Set/Reset register is set to 01H and the Set/Reset register is set to 05H, then the CPU data is replaced for plane 0 only (the blue plane), and the value it is replaced with is 0FFH (bit 0 of the Set/Reset register extended to a byte). Note that in this case, bits 1-3 of the Set/Reset register have no effect.

      @@ -140,7 +140,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-05.html b/25-05.html index 5be6b24..b5a8e67 100644 --- a/25-05.html +++ b/25-05.html @@ -24,7 +24,7 @@ - +
      @@ -149,7 +149,7 @@ cseg ends end start -

      Manipulating Planes Individually

      +

      Manipulating Planes Individually

      Listing 25.4 illustrates the use of set/reset to control only some, rather than all, planes. Here, the set/reset circuitry forces plane 2 to 1 and planes 0 and 3 to 0. Because bit 1 of the Enable Set/Reset register is 0, however, set/reset does not affect plane 1; the CPU data goes unchanged to the plane 1 ALU. Consequently, the CPU data can be used to control the value written to plane 1. Given the settings of the other three planes, this means that each bit of CPU data that is 1 generates a brown pixel, and each bit that is 0 generates a red pixel. Writing alternating bytes of 07H and 0E0H, then, creates a vertically striped pattern of brown and red.

      In Listing 25.4, note that the vertical bars are 10 and 6 bytes wide, and do not start on byte boundaries. Although set/reset replaces an entire byte of CPU data for a plane, the combination of set/reset for some planes and CPU data for other planes, as in the example above, can be used to control individual pixels.

      @@ -279,7 +279,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/25-06.html b/25-06.html index 00ab4d4..1efa277 100644 --- a/25-06.html +++ b/25-06.html @@ -24,7 +24,7 @@ - +
      @@ -38,12 +38,12 @@


      There is no clearly defined role for the set/reset circuitry, as there is for, say, the bit mask. In many cases, set/reset is largely interchangeable with CPU data, particularly with CPU data written in write mode 2 (write mode 2 operates similarly to the set/reset circuitry, as we’ll see in Chapter 27). The most powerful use of set/reset, in my experience, is in applications such as the example of Listing 25.4, where it is used to force the value written to certain planes while the CPU data is written to other planes. In general, though, think of set/reset as one more tool you have at your disposal in getting the VGA to do what you need done, in this case a tool that lets you force all bits in each plane to either zero or one, or pass CPU data through unchanged, on each write to display memory. As tools go, set/reset is a handy one, and it’ll pop up often in this book.

      -

      Notes on Set/Reset

      +

      Notes on Set/Reset

      The set/reset circuitry is not active in write modes 1 or 2. The Enable Set/Reset register is inactive in write mode 3, but the Set/Reset register provides the primary drawing color in write mode 3, as discussed in the next chapter.

      Be aware that because set/reset directly replaces CPU data, it does not necessarily have to force an entire display memory byte to 0 or 0FFH, even when set/reset is replacing CPU data for all planes. For example, if the Bit Mask register is set to 80H, the set/reset circuitry can only modify bit 7 of the destination byte in each plane, since the other seven bits will come from the latches for each plane. Similarly, the set/reset value for each plane can be modified by that plane’s ALU. Once again, this illustrates that set/reset merely replaces the CPU data for selected planes; the set/reset value is then processed in exactly the same way that CPU data normally is.
      -

      A Brief Note on Word OUTs

      +

      A Brief Note on Word OUTs

      In the early days of the EGA and VGA, there was considerable debate about whether it was safe to do word OUTs (OUT DX,AX) to set Index/Data register pairs in a single instruction. Long ago, there were a few computers with buses that weren’t quite PC-compatatible, in that the two bytes in each word OUT went to the VGA in the wrong order: Data register first, then Index register, with predictably disastrous results. Consequently, I generally wrote my code in those days to use two 8-bit OUTs to set indexed registers. Later on, I made it a habit to use macros that could do either one 16-bit OUT or two 8-bit OUTs, depending on how I chose to assemble the code, and in fact you’ll find both ways of dealing with OUTs sprinkled through the code in this part of the book. Using macros for word OUTs is still not a bad idea in that it does no harm, but in my opinion it’s no longer necessary. Word OUTs are standard now, and it’s been a long time since I’ve heard of them causing any problems.


      @@ -57,7 +57,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/26-01.html b/26-01.html index e4ca3f5..d52f0e1 100644 --- a/26-01.html +++ b/26-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,13 +36,12 @@


      -

      Chapter 26
      VGA Write Mode 3 -

      -

      The Write Mode That Grows on You

      +

      Chapter 26
      VGA Write Mode 3

      +

      The Write Mode That Grows on You

      Over the last three chapters, we’ve covered the VGA’s write path from stem to stern—with one exception. Thus far, we’ve only looked at how writes work in write mode 0, the straightforward, workhorse mode in which each byte that the CPU writes to display memory fans out across the four planes. (Actually, we also took a quick look at write mode 1, in which the latches are always copied unmodified, but since exactly the same result can be achieved by setting the Bit Mask register to 0 in write mode 0, write mode 1 is of little real significance.)

      Write mode 0 is a very useful mode, but some of VGA’s most interesting capabilities involve the two write modes that we have yet to examine: write mode 1, and, especially, write mode 3. We’ll get to write mode 1 in the next chapter, but right now I want to focus on write mode 3, which can be confusing at first, but turns out to be quite a bit more powerful than one might initially think.

      -

      A Mode Born in Strangeness

      +

      A Mode Born in Strangeness

      Write mode 3 is strange indeed, and its use is not immediately obvious. The first time I encountered write mode 3, I understood immediately how it functioned, but could think of very few useful applications for it. As time passed, and as I came to understand the atrocious performance characteristics of OUT instructions, and the importance of text and pattern drawing as well, write mode 3 grew considerably in my estimation. In fact, my esteem for this mode ultimately reached the point where in the last major chunk of 16-color graphics code I wrote, write mode 3 was used more than write mode 0 overall, excluding simple pixel copying. So write mode 3 is well worth using, but to use it you must first understand it. Here’s how it works.

      In write mode 3, set/reset is automatically enabled for all four planes (the Enable Set/Reset register is ignored). The CPU data byte is rotated and then ANDed with the contents of the Bit Mask register, and the result of this operation is used as the contents of the Bit Mask register alone would normally be used. (If this is Greek to you, have a look back at Chapters 23 through 25. There’s no way to understand write mode 3 without understanding the rest of the VGA’s write data path first.)

      That’s what write mode 3 does—but what is it for? It turns out that write mode 3 is excellent for a surprisingly large number of purposes, because it makes it possible to avoid the bane of VGA performance, OUTs. Some uses for write mode 3 include lines, circles, and solid and two-color pattern fills. Most importantly, write mode 3 is ideal for transparent text; that is, it makes it possible to draw text in 16-color graphics mode quickly without wiping out the background in the process. (As we’ll see at the end of this chapter, write mode 3 is potentially terrific for opaque text—text drawn with the character box filled in with a solid color—as well.)

      @@ -59,7 +58,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/26-02.html b/26-02.html index 003aa5b..96aa386 100644 --- a/26-02.html +++ b/26-02.html @@ -24,7 +24,7 @@ - +
      @@ -347,7 +347,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/26-03.html b/26-03.html index 77818c9..b5207d0 100644 --- a/26-03.html +++ b/26-03.html @@ -24,7 +24,7 @@ - +
      @@ -372,7 +372,7 @@ cseg ends

      Similarly, Listing 26.1 is designed to illustrate write mode 3 and its interaction with the rest of the VGA as a contrast to Listing 25.1 in Chapter 25, rather than for maximum speed, and it could be made considerably more efficient. If we were going for performance, we’d have the CPU not only rotate the bytes into position, but also do the masking by ANDing in software. Even more significantly, we would have the CPU combine adjacent characters into complete, rotated bytes whenever possible, so that only one drawing operation would be required per byte of display memory modified. By doing this, we would eliminate all per-character OUTs, and would minimize display memory accesses, approximately doubling text-drawing speed.

      As a final note, consider that non-transparent text could also be accelerated with write mode 3. The latches could be filled with the background (text box) color, set/reset could be set to the foreground (text) color, and write mode 3 could then be used to turn monochrome text bytes written by the CPU into characters on the screen with just one write per byte. There are complications, such as drawing partial bytes, and rotating the bytes to align the characters, which we’ll revisit later on in Chapter 55, while we’re working through the details of the X-Sharp library. Nonetheless, the performance benefit of this approach can be a speedup of as much as four times—all thanks to the decidedly quirky but surprisingly powerful and flexible write mode 3.

      -

      A Note on Preserving Register Bits

      +

      A Note on Preserving Register Bits

      If you take a quick look, you’ll see that the code in Listing 26.1 uses the readable register feature of the VGA to preserve reserved bits and bits other than those being modified. Older adapters such as the CGA and EGA had few readable registers, so it was necessary to set all bits in a register whenever that register was modified. Happily, all VGA registers are readable, which makes it possible to change only those bits of immediate interest, and, in general, I highly recommend doing exactly that, since IBM (or clone manufacturers) may well someday use some of those reserved bits or change the meanings of some of the bits that are currently in use.


      @@ -387,7 +387,7 @@ cseg ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/27-01.html b/27-01.html index dd4dfb4..7b867d6 100644 --- a/27-01.html +++ b/27-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,23 +36,22 @@


      -

      Chapter 27
      Yet Another VGA Write Mode -

      -

      Write Mode 2, Chunky Bitmaps,and Text-Graphics Coexistence

      +

      Chapter 27
      Yet Another VGA Write Mode

      +

      Write Mode 2, Chunky Bitmaps,and Text-Graphics Coexistence

      In the last chapter, we learned about the markedly peculiar write mode 3 of the VGA, after having spent three chapters learning the ins and outs of the VGA’s data path in write mode 0, touching on write mode 1 as well in Chapter 23. In all, the VGA supports four write modes—write modes 0, 1, 2, and 3—and read modes 0 and 1 as well. Which leaves two burning questions: What is write mode 2, and how the heck do you read VGA memory?

      Write mode 2 is a bit unusual but not really hard to understand, particularly if you followed the description of set/reset in Chapter 25. Reading VGA memory, on the other hand, can be stranger than you could ever imagine.

      Let’s start with the easy stuff, write mode 2, and save the read modes for the next chapter.

      -

      Write Mode 2 and Set/Reset

      +

      Write Mode 2 and Set/Reset

      Remember how set/reset works? Good, because that’s pretty much how write mode 2 works. (You don’t remember? Well, I’ll provide a brief refresher, but I suggest that you go back through Chapters 23 through 25 and come up to speed on the VGA.)

      Recall that the set/reset circuitry for each of the four planes affects the byte written by the CPU in one of three ways: By replacing the CPU byte with 0, by replacing it with 0FFH, or by leaving it unchanged. The nature of the transformation for each plane is controlled by two bits. The enable set/reset bit for a given plane selects whether the CPU byte is replaced or not, and the set/reset bit for that plane selects the value with which the CPU byte is replaced if the enable set/reset bit is 1. The net effect of set/reset is to independently force any, none, or all planes to either of all ones or all zeros on CPU writes. As we discussed in Chapter 25, this is a convenient way to force a specific color to appear no matter what color the pixels being overwritten are. Set/reset also allows the CPU to control the contents of some planes while the set/reset circuitry controls the contents of other planes.

      Write mode 2 is basically a set/reset-type mode with enable set/reset always on for all planes and the set/reset data coming directly from the byte written by the CPU. Put another way, the lower four bits written by the CPU are written across the four planes, thereby becoming a color value. Put yet another way, bit 0 of the CPU byte is expanded to a byte and sent to the plane 0 ALU (if bit 0 is 0, a 0 byte is the CPU-side input to the plane 0 ALU, while if bit 0 is 1, a 0FFH byte is the CPU-side input); likewise, bit 1 of the CPU byte is expanded to a byte for plane 1, bit 2 is expanded for plane 2, and bit 3 is expanded for plane 3.

      It’s possible that you understand write mode 2 thoroughly at this point; nonetheless, I suspect that some additional explanation of an admittedly non-obvious mode wouldn’t hurt. Let’s follow the CPU byte through the VGA in write mode 2, step by step.

      -

      A Byte’s Progress in Write Mode 2

      +

      A Byte’s Progress in Write Mode 2

      Figure 27.1 shows the write mode 2 data path. The CPU byte comes into the VGA and is split into four separate bits, one for each plane. Bits 7-4 of the CPU byte vanish into the bit bucket, never to be heard from again. Speculation long held that those 4 unused bits indicated that IBM would someday come out with an 8-plane adapter that supported 256 colors. When IBM did finally come out with a 256-color mode (mode 13H of the VGA), it turned out not to be planar at all, and the upper nibble of the CPU byte remains unused in write mode 2 to this day.

      The bit of the CPU byte sent to each plane is expanded to a 0 or 0FFH byte, depending on whether the bit is 0 or 1, respectively. The byte for each plane then becomes the CPU-side input to the respective plane’s ALU. From this point on, the write mode 2 data path is identical to the write mode 0 data path. As discussed in earlier articles, the latch byte for each plane is the other ALU input, and the ALU either ANDs, ORs, or XORs the two bytes together or simply passes the CPU-side byte through. The byte generated by each plane’s ALU then goes through the bit mask circuitry, which selects on a bit-by-bit basis between the ALU byte and the latch byte. Finally, the byte from the bit mask circuitry for each plane is written to that plane if the corresponding bit in the Map Mask register is set to 1.


      Figure 27.1
        VGA data flow in write mode 2. +
      -->Figure 27.1  VGA data flow in write mode 2.

      It’s worth noting two differences between write mode 2 and write mode 0, the standard write mode of the VGA. First, rotation of the CPU data byte does not take place in write mode 2. Second, the Set/Reset and Enable Set/Reset registers have no effect in write mode 2. @@ -73,7 +72,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/27-02.html b/27-02.html index 8d60131..7f30ff1 100644 --- a/27-02.html +++ b/27-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Copying Chunky Bitmaps to VGA Memory Using Write Mode 2

      +

      Copying Chunky Bitmaps to VGA Memory Using Write Mode 2

      Let’s take a look at two examples of write mode 2 in action. Listing 27.1 presents a program that uses write mode 2 to copy a graphics image in chunky format to the VGA. In chunky format adjacent bits in a single byte make up each pixel: mode 4 of the CGA, EGA, and VGA is a 2-bit-per-pixel chunky mode, and mode 13H of the VGA is an 8-bit-per-pixel chunky mode. Chunky format is convenient, since all the information about each pixel is contained in a single byte; consequently chunky format is often used to store bitmaps in system memory.

      Unfortunately, VGA memory is organized as a planar rather than chunky bitmap in modes 0DH through 12H, with the bits that make up each pixel spread across four planes. The conversion from chunky to planar format in write mode 0 is quite a nuisance, requiring a good deal of bit manipulation. In write mode 2, however, the conversion becomes a snap, as shown in Listing 27.1. Once the VGA is placed in write mode 2, the lower four bits (the lower nibble) of the CPU byte (a single 4-bit chunky pixel) become eight planar pixels, all the same color. As discussed in Chapter 25, the bit mask makes it possible to narrow the effect of the CPU write down to a single pixel.

      @@ -277,7 +277,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/27-03.html b/27-03.html index 6320dd2..f9b4873 100644 --- a/27-03.html +++ b/27-03.html @@ -24,7 +24,7 @@ - +
      @@ -40,7 +40,7 @@

      For performance, it’s best to store 16-color bitmaps in pre-separated four-plane format in system memory, and copy one plane at a time to the screen. Ideally, such bitmaps should be copied one scan line at a time, with all four planes completed for one scan line before moving on to the next. I say this because when entire images are copied one plane at a time, nasty transient color effects can occur as one plane becomes visibly changed before other planes have been modified.
      -

      Drawing Color-Patterned Lines Using Write Mode 2

      +

      Drawing Color-Patterned Lines Using Write Mode 2

      A more serviceable use of write mode 2 is shown in the program presented in Listing 27.2. The program draws multicolored horizontal, vertical, and diagonal lines, basing the color patterns on passed color tables. Write mode 2 is ideal because in this application color can vary from one pixel to the next, and in write mode 2 all that’s required to set pixel color is a change of the lower nibble of the byte written by the CPU. Set/reset could be used to achieve the same result, but an index/data pair of OUTs would be required to set the Set/Reset register to each new color. Similarly, the Map Mask register could be used in write mode 0 to set pixel color, but in this case not only would an index/data pair of OUTs be required but there would also be no guarantee that data already in display memory wouldn’t interfere with the color of the pixel being drawn, since the Map Mask register allows only selected planes to be drawn to.

      Listing 27.2 is hardly a comprehensive line drawing program. It draws only a few special line cases, and although it is reasonably fast, it is far from the fastest possible code to handle those cases, because it goes through a dot-plot routine and because it draws horizontal lines a pixel rather than a byte at a time. Write mode 2 would, however, serve just as well in a full-blown line drawing routine. For any type of patterned line drawing on the VGA, the basic approach remains the same: Use the bit mask to select the pixel (or pixels) to be altered and use the CPU byte in write mode 2 to select the color in which to draw.

      LISTING 27.2 L27-2.ASM

      @@ -387,7 +387,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/27-04.html b/27-04.html index 31e2bd5..2b66829 100644 --- a/27-04.html +++ b/27-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,15 +36,15 @@


      -

      When to Use Write Mode 2 and When to Use Set/Reset

      +

      When to Use Write Mode 2 and When to Use Set/Reset

      As indicated earlier, write mode 2 and set/reset are functionally interchangeable. Write mode 2 lends itself to more efficient implementations when the drawing color changes frequently, as in Listing 27.2.

      Set/reset tends to be superior when many pixels in succession are drawn in the same color, since with set/reset enabled for all planes the Set/Reset register provides the color data and as a result the CPU is free to draw whatever byte value it wishes. For example, the CPU can execute an OR instruction to display memory when set/reset is enabled for all planes, thus both loading the latches and writing the color value with a single instruction, secure in the knowledge that the value it writes is ignored in favor of the set/reset color.

      Set/reset is also the mode of choice whenever it is necessary to force the value written to some planes to a fixed value while allowing the CPU byte to modify other planes. This is the mode of operation when set/reset is enabled for some but not all planes.

      -

      Mode 13H—320x200 with 256 Colors

      +

      Mode 13H—320x200 with 256 Colors

      I’m going to take a minute—and I do mean a minute—to discuss the programming model for mode 13H, the VGA’s 320x200 256-color mode. Frankly, there’s just not much to it, especially compared to the convoluted 16-color model that we’ve explored over the last five chapters. Mode 13H offers the simplest programming model in the history of PC graphics: A linear bitmap starting at A000:0000, consisting of 64,000 bytes, each controlling one pixel. The byte at offset 0 controls the upper left pixel on the screen, the byte at offset 319 controls the upper right pixel on the screen, the byte at offset 320 controls the second pixel down at the left of the screen, and the byte at offset 63,999 controls the lower right pixel on the screen. That’s all there is to it; it’s so simple that I’m not going to spend any time on a demo program, especially given that some of the listings later in this book, such as the antialiasing code in Chapter F on the companion CD-ROM, use mode 13H.

      -

      Flipping Pages from Text to Graphics and Back

      +

      Flipping Pages from Text to Graphics and Back

      A while back, I got an interesting letter from Phil Coleman, of La Jolla, who wrote:

      “Suppose I have the EGA in mode 10H (640x350 16-color graphics). I would like to preserve some or all of the image while I temporarily switch to text mode 3 to give my user a ‘Help’ screen. Naturally memory is scarce so I’d rather not make a copy of the video buffer at A000H to ‘remember’ the image while I digress to the Help text. The EGA BIOS says that the screen memory will not be cleared on a mode set if bit 7 of AL is set. Yet if I try that, it is clear that writing text into the B800H buffer trashes much more than the 4K bytes of a text page; when I switch back to mode 10H, “ghosts” appear in the form of bands of colored dots. (When in text mode, I do make a copy of the 4K buffer at B800H before showing the help; and I restore the 4K before switching back to mode 10H.) Is there a way to preserve the graphics image while I switch to text mode?’’

      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/27-05.html b/27-05.html index 0d27106..c6399e3 100644 --- a/27-05.html +++ b/27-05.html @@ -24,7 +24,7 @@ - +
      @@ -249,7 +249,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/28-01.html b/28-01.html index c855652..013efad 100644 --- a/28-01.html +++ b/28-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,13 +36,12 @@


      -

      Chapter 28
      Reading VGA Memory -

      -

      Read Modes 0 and 1, and the Color Don’t Care Register

      +

      Chapter 28
      Reading VGA Memory

      +

      Read Modes 0 and 1, and the Color Don’t Care Register

      Well, it’s taken five chapters, but we’ve finally covered the data write path and all four write modes of the VGA. Now it’s time to tackle the VGA’s two read modes. While the read modes aren’t as complex as the write modes, they’re nothing to sneeze at. In particular, read mode 1 (also known as color compare mode) is rather unusual and not at all intuitive.

      You may well ask, isn’t anything about programming the VGA straightforward? Well...no. But then, clearing up the mysteries of VGA programming is what this part of the book is all about, so let’s get started.

      -

      Read Mode 0

      +

      Read Mode 0

      Read mode 0 is actually relatively uncomplicated, given that you understand the four-plane nature of the VGA. (If you don’t understand the four-plane nature of the VGA, I strongly urge you to read Chapters 23-27 before continuing with this chapter.) Read mode 0, the read mode counterpart of write mode 0, lets you read from one (and only one) plane of VGA memory at any one time.

      Read mode 0 is selected by setting bit 3 of the Graphics Mode register (Graphics Controller register 5) to 0. When read mode 0 is active, the plane that supplies the data when the CPU reads VGA memory is the plane selected by bits 1 and 0 of the Read Map register (Graphics Controller register 4). When the Read Map register is set to 0, CPU reads come from plane 0 (the plane that normally contains blue pixel data). When the Read Map register is set to 1, CPU reads come from plane 1; when the Read Map register is 2, CPU reads come from plane 2; and when the Read Map register is 3, CPU reads come from plane 3.

      @@ -61,7 +60,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/28-02.html b/28-02.html index 77892ac..d87dc02 100644 --- a/28-02.html +++ b/28-02.html @@ -24,7 +24,7 @@ - +
      @@ -289,7 +289,7 @@ code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/28-03.html b/28-03.html index 61578e9..deb7280 100644 --- a/28-03.html +++ b/28-03.html @@ -24,7 +24,7 @@ - +
      @@ -41,7 +41,7 @@

      As you’d expect, neither the read mode nor the setting of the Read Map register affects CPU writes to VGA memory in any way.

      An important point regarding reading VGA memory involves the VGA’s latches. (Remember that each of the four latches stores a byte for one plane; on CPU writes, the latches can provide some or all of the data written to display memory, allowing fast copying and efficient pixel masking.) Whenever the CPU reads a given address in VGA memory, each of the four latches is loaded with the contents of the byte at that address in its respective plane. Even though the CPU only receives data from one plane in read mode 0, all four planes are always read, and the values read are stored in the latches. This is true in read mode 1 as well. In short, whenever the CPU reads VGA memory in any read mode, all four planes are read and all four latches are always loaded.
      -

      Read Mode 1

      +

      Read Mode 1

      Read mode 0 is the workhorse read mode, but it’s got an annoying limitation: Whenever you want to determine the color of a given pixel in read mode 0, you have to perform four VGA memory reads, one for each plane, and then interpret the four bytes you’ve read as eight 16-color pixels. That’s a lot of programming. The code is also likely to run slowly, all the more so because a standard IBM VGA takes an average of 1.1 microseconds to complete each memory read, and read mode 0 requires four reads in order to read the four planes, not to mention the even greater amount of time taken by the OUTs required to switch between the planes. (1.1 microseconds may not sound like much, but on a 66-MHz 486, it’s 73 clock cycles! Local-bus VGAs can be a good deal faster, but a read from the fastest local-bus adapter I’ve yet seen would still cost in the neighborhood of 10 486/66 cycles.)

      Read mode 1, also known as color compare mode, provides special hardware assistance for determining whether a pixel is a given color. With a single read mode 1 read, you can determine whether each of up to eight pixels is a specific color, and you can even specify any or all planes as “don’t care” planes in the pixel color comparison.

      Read mode 1 is selected by setting bit 3 of the Graphics Mode register (Graphics Controller register 5) to 1. In its simplest form, read mode 1 compares the cross-plane value of each of the eight pixels at a given address to the color value in bits 3-0 of the Color Compare register (Graphics Controller register 2), and returns a 1 to the CPU in the bit position of each pixel that matches the color in the Color Compare register and a 0 for each pixel that does not match.

      @@ -58,7 +58,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/28-04.html b/28-04.html index 44f35c7..41b81d9 100644 --- a/28-04.html +++ b/28-04.html @@ -24,7 +24,7 @@ - +
      @@ -202,7 +202,7 @@ code ends end Start -

      When all Planes “Don’t Care”

      +

      When all Planes “Don’t Care”

      Still and all, there aren’t all that many uses for basic color compare operations. There is, however, a genuinely odd application of read mode 1 that’s worth knowing about; but in order to understand that, we must first look at the “don’t care” aspect of color compare operation.

      As described earlier, during read mode 1 reads the color stored in the Color Compare register is compared to each of the 8 pixels at a given address in VGA memory. But—and it’s a big but—any plane for which the corresponding bit in the Color Don’t Care register is a 0 is always considered a color compare match, regardless of the values of that plane’s bits in the pixels and in the Color Compare register.

      @@ -222,7 +222,7 @@ end Start
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/28-05.html b/28-05.html index 50e8b17..067167d 100644 --- a/28-05.html +++ b/28-05.html @@ -24,7 +24,7 @@ - +
      @@ -162,7 +162,7 @@ code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-01.html b/29-01.html index c313ffe..be5b452 100644 --- a/29-01.html +++ b/29-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,19 +36,18 @@


      -

      Chapter 29
      Saving Screens and Other VGA Mysteries -

      -

      Useful Nuggets from the VGA Zen File

      +

      Chapter 29
      Saving Screens and Other VGA Mysteries

      +

      Useful Nuggets from the VGA Zen File

      There are a number of VGA graphics topics that aren’t quite involved enough to warrant their own chapters, yet still cause a fair amount of programmer headscratching—and thus deserve treatment somewhere in this book. This is the place, and during the course of this chapter we’ll touch on saving and restoring 16-color EGA and VGA screens, the 16-out-of-64 colors issue, and techniques involved in reading and writing VGA control registers.

      That’s a lot of ground to cover, so let’s get started!

      -

      Saving and Restoring EGA and VGA Screens

      +

      Saving and Restoring EGA and VGA Screens

      The memory architectures of EGAs and VGAs are similar enough to treat both together in this regard. The basic principle for saving EGA and VGA 16-color graphics screens is astonishingly simple: Write each plane to disk separately. Let’s take a look at how this works in the EGA’s hi-res mode 10H, which provides 16 colors at 640x350.

      All we need do is enable reads from plane 0 and write the 28,000 bytes of plane 0 that are displayed in mode 10H to disk, then enable reads from plane 1 and write the displayed portion of that plane to disk, and so on for planes 2 and 3. The result is a file that’s 112,000 (28,000 * 4) bytes long, with the planes stored as four distinct 28,000-byte blocks, as shown in Figure 29.1.

      The program shown later on in Listing 29.1 does just what I’ve described here, putting the screen into mode 10H, putting up some bittext so there is something to save, and creating the 112K file SNAPSHOT.SCR, which contains the visible portion of the mode 10H frame buffer.


      Figure 29.1
        Saving EGA/VGA display memory. +
      -->Figure 29.1  Saving EGA/VGA display memory.

      The only part of Listing 29.1 that’s even remotely tricky is the use of the Read Map register (Graphics Controller register 4) to make each of the four planes of display memory readable in turn. The same code is used to write 28,000 bytes of display memory to disk four times, and 28,000 bytes of memory starting at A000:0000 are written to disk each time; however, a different plane is read each time, thanks to the changing setting of the Read Map register. (If this is unclear, refer back to Figure 29.1; you may also want to reread Chapter 28 to brush up on the operation of the Read Map register in particular and reading EGA and VGA memory in general.)

      @@ -199,7 +198,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-02.html b/29-02.html index 8daf799..c054ae1 100644 --- a/29-02.html +++ b/29-02.html @@ -24,7 +24,7 @@ - +
      @@ -169,7 +169,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-03.html b/29-03.html index b0e0ac4..0ace50d 100644 --- a/29-03.html +++ b/29-03.html @@ -24,7 +24,7 @@ - +
      @@ -53,7 +53,7 @@ DISPLAYED_SCREEN_SIZEequ(640/8)*480

      While Listings 29.1 and 29.2 are written in assembly, the principles they illustrate apply equally well to high-level languages. In fact, there’s no need for any assembly at all when saving an EGA/VGA screen, as long as the high-level language you’re using can perform direct port I/O to set up the adapter and can read and write display memory directly.

      One tip if you’re saving and restoring the screen from a high-level language on an EGA, though: After you’ve completed the save or restore operation, be sure to put any registers that you’ve changed back to their default settings. Some high-level languages (and the BIOS as well) assume that various registers are left in a certain state, so on the EGA it’s safest to leave the registers in their most likely state. On the VGA, of course, you can just read the registers out before you change them, then put them back the way you found them when you’re done.
      -

      16 Colors out of 64

      +

      16 Colors out of 64

      How does one produce the 64 colors from which the 16 colors displayed by the EGA can be chosen? The answer is simple enough: There’s a BIOS function that lets you select the mapping of the 16 possible pixel values to the 64 possible colors. Let’s lay out a bit of background before proceeding, however.

      The EGA sends pixel information to the monitor on 6 pins. This means that there are 2 to the 6th, or 64 possible colors that an EGA can generate. However, for compatibility with premonitors, in 200-scan-line modes Enhanced Color Displaymonitors ignore two of the signals. As a result, in CGA-compatible modes (modes 4, 5, 6, and the 200-scan-line versions of modes 0, 1, 2, and 3) you can select from only 16 colors (although the colors can still be remapped, as described below). If you’re not hooked up to a monitor capable of displaying 350 scan lines (such as the old IBM Color Display), you can never select from more than 16 colors, since those monitors only accept four input signals. For now, we’ll assume we’re in one of the 350-scan line color modes, a group which includes mode 10H and the 350-scan-line versions of modes 0, 1, 2, and 3.

      @@ -61,7 +61,7 @@ DISPLAYED_SCREEN_SIZEequ(640/8)*480

      Actually, though, the correspondence of pixel values to color is absolutely arbitrary, depending solely on how the colorportion of the EGA containing the palette registers is programmed. If you cared to have color 0 be bright red and color 1 be black, that could easily be arranged, as could a mapping in which all 16 colors were yellow. What’s more, these mappings affect text-mode characters as readily as they do graphics-mode pixels, so you could map text attribute 0 to white and text attribute 15 to black to produce a black on white display, if you wished.

      Each of the 16 palette registers stores the mapping of one of the 16 possible 4-bit pixel values from memory to one of 64 possible 6-bit pixel values to be sent to the monitor as video data, as shown in Figure 29.2. A 4-bit pixel value of 0 causes the 6-bit value stored in palette register 0 to be sent to the display as the color of that pixel, a pixel value of 1 causes the contents of palette register 1 to be sent to the display, and so on. Since there are only four input bits, it stands to reason that only 16 colors are available at any one time; since there are six output bits, however, those 16 colors can be mapped to any of 64 colors. The mapping for each of the 16 pixel values is controlled by the lower six bits of the corresponding palette register, as shown in Figure 29.3. Secondary red, green, and blue are less-intense versions of red, green, and blue, although their exact effects vary from monitor to monitor. The best way to figure out what the 64 colors look like on your monitor is to see them, and that’s just what the program in Listing 29.3, which we’ll discuss shortly, lets you do.


      Figure 29.2
        Color translation via the palette registers. +
      -->Figure 29.2  Color translation via the palette registers.


      @@ -75,7 +75,7 @@ DISPLAYED_SCREEN_SIZEequ(640/8)*480
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-04.html b/29-04.html index 6df531a..e4ddff1 100644 --- a/29-04.html +++ b/29-04.html @@ -24,7 +24,7 @@ - +
      @@ -41,7 +41,7 @@

      Video function 10H is invoked by performing an INT 10H with AH set to 10H. If AL is 0 (subfunction 0), then BL contains the number of the palette register to set, and BH contains the value to set that register to. If AL is 1 (subfunction 1), then BH contains the value to set the overscan (border) color to. Finally, if AL is 2 (subfunction 2), then ES:DX points to a 17-byte array containing the values to set palette registers 0-15 and the overscan register to. (For completeness, although it’s unrelated to the palette registers, there is one more subfunction of video function 10H. If AL = 3 (subfunction 3), bit 0 of BL is set to 1 to cause bit 7 of text attributes to select blinking, or set to 0 to cause bit 7 of text attributes to select highreverse video.)


      Figure 29.3
        Bit organization within a palette register. +
      -->Figure 29.3  Bit organization within a palette register.

      Listing 29.3 uses video function 10H, subfunction 2 to step through all 64 possible colors. This is accomplished by putting up 16 color bars, one for each of the 16 possible 4-bit pixel values, then changing the mapping provided by the palette registers to select a different group of 16 colors from the set of 64 each time a key is pressed. Initially, colors 0-15 are displayed, then 1-16, then 2-17, and so on up to color 3FH wrapping around to colors 0-14, and finally back to colors 0-15. (By the way, at mode set time the 16 palette registers are not set to colors 0-15, but rather to 0H, 1H, 2H, H, 4H, 5H, 14H, 7H, 38H, 39H, 3AH, 3BH, 3CH, 3DH, 3EH, and 3FH, respectively. Bits 6, 5, and 4—secondary red, green, and blue—are all set to 1 in palette registers 8-15 in order to produce high-intensity colors. Palette register 6 is set to 14H to produce brown, rather than the yellow that the expected value of 6H would produce.)

      @@ -315,7 +315,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-05.html b/29-05.html index 2d4f325..8e5a200 100644 --- a/29-05.html +++ b/29-05.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,12 @@


      -

      Overscan

      +

      Overscan

      While we’re at it, I’m going to touch on overscan. Overscan is the color of the border of the display, the rectangular area around the edge of the monitor that’s outside the region displaying active video data but inside the blanking area. The overscan (or border) color can be programmed to any of the 64 possible colors by either setting Attribute Controller register 11H directly or calling video function 10H, subfunction 1.

      On ECD-compatible monitors, however, there’s too little scan time to display a proper border when the EGA is in 350-scan-line mode, so overscan should always be 0 (black) unless you’re in 200-scanmode. Note, though, that a VGA can easily display a border on a VGA-compatible monitor, and VGAs are in fact programmed at mode set for an 8-pixel-wide border in all modes; all you need do is set the overscan color on any VGA to see the border.
      -

      A Bonus Blanker

      +

      A Bonus Blanker

      An interesting bonus: The Attribute Controller provides a very convenient way to blank the screen, in the form of the aforementioned bit 5 of the Attribute Controller Index register (at address 3C0H after the Input Status 1 register—3DAH in color, 3BAH in monochrome—has been read and on every other write to 3C0H thereafter). Whenever bit 5 of the AC Index register is 0, video data is cut off, effectively blanking the screen. Setting bit 5 of the AC Index back to 1 restores video data immediately. Listing 29.4 illustrates this simple but effective form of screen blanking.

      LISTING 29.4 L29-4.ASM

      @@ -143,7 +143,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/29-06.html b/29-06.html index 9d6a143..00ffb65 100644 --- a/29-06.html +++ b/29-06.html @@ -24,7 +24,7 @@ - +
      @@ -38,7 +38,7 @@


      Does that do it for color selection? Yes and no. For the EGA, we’ve covered the whole of color selection—but not so for the VGA. The VGA can emulate everything we’ve discussed, but actually performs one 4-bit to 8-bit translation (except in 256-color modes, where all 256 colors are simultaneously available), followed by yet another translation, this one 8-bit to 18-bit. What’s more, the VGA has the ability to flip instantly through as many as 16 16-color sets. The VGA’s color selection capabilities, which are supported by another set of BIOS functions, can be used to produce stunning color effects, as we’ll see when we cover them starting in Chapter 33.

      -

      Modifying VGA Registers

      +

      Modifying VGA Registers

      EGA registers are not readable. VGA registers are readable. This revelation will not come as news to most of you, but many programmers still insist on setting entire VGA registers even when they’re modifying only selected bits, as if they were programming the EGA. This comes to mind because I recently received a query inquiring why write mode 1 (in which the contents of the latches are copied directly to display memory) didn’t work in Mode X. (I’ll go into Mode X in detail later in this book.) Actually, write mode 1 does work in Mode X; it didn’t work when this particular correspondent enabled it because he did so by writing the value 01H to the Graphics Mode register. As it happens, the write mode field is only one of several fields in that register, as shown in Figure 29.4. In 256-color modes, one of the other fields—bit 6, which enables 256-color pixel formatting—is not 0, and setting it to 0 messes up the screen quite thoroughly.

      The correct way to set a field within a VGA register is, of course, to read the register, mask off the desired field, insert the desired setting, and write the result back to the register. In the case of setting the VGA to write mode 1, do this:

      @@ -57,7 +57,7 @@ out dx,al ;set write mode 1

      This approach is more of a nuisance than simply setting the whole register, but it’s safer. It’s also slower; for cases where you must set a field repeatedly, it might be worthwhile to read and mask the register once at the start, and save it in a variable, so that the value is readily available in memory and need not be repeatedly read from the port. This approach is especially attractive because INs are much slower than memory accesses on 386 and 486 machines.

      Astute readers may wonder why I didn’t put a delay sequence, such as JMP $+2, between the IN and OUT involving the same register. There are, after all, guidelines from IBM, specifying that a certain period should be allowed to elapse before a second access to an I/O port is attempted, because not all devices can respond as rapidly as a 286 or faster CPU can access a port. My answer is that while I can’t guarantee that a delay isn’t needed, I’ve never found a VGA that required one; I suspect that the delay specification has more to do with motherboard chips such as the timer, the interrupt controller, and the like, and I sure hate to waste the delay time if it’s not necessary. However, I’ve never been able to find anyone with the definitive word on whether delays might ever be needed when accessing VGAs, so if you know the gospel truth, or if you know of a VGA/processor combo that does require delays, please let me know by contacting me through the publisher. You’d be doing a favor for a whole generation of graphics programmers who aren’t sure whether they’re skating on thin ice without those legendary delays.


      Figure 29.4
        Graphics mode register fields. +
      -->Figure 29.4  Graphics mode register fields.


      @@ -71,7 +71,7 @@ out dx,al ;set write mode 1
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-01.html b/30-01.html index 188b3aa..66783d7 100644 --- a/30-01.html +++ b/30-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,25 +36,24 @@


      -

      Chapter 30
      Video Est Omnis Divisa -

      -

      The Joys and Galling Problems of Using Split Screens on the EGA and VGA

      +

      Chapter 30
      Video Est Omnis Divisa

      +

      The Joys and Galling Problems of Using Split Screens on the EGA and VGA

      The ability to split the screen into two largely independent portions one—displayed above the other on the screen—is one of the more intriguing capabilities of the VGA and EGA. The split screen feature can be used for popups (including popups that slide smoothly onto the screen), or simply to display two separate portions of display memory on a single screen. While it’s possible to accomplish the same effects purely in software without using the split screen, software solutions tend to be slow and hard to implement.

      By contrast, the basic operation of the split screen is fairly simple, once you grasp the various coding tricks required to pull it off, and understand the limitations and pitfalls—like the fact that the EGA’s split screen implementation is a little buggy. Furthermore, panning with the split screen enabled is not as simple as it might seem. All in all, we do have some ground to cover.

      Let’s start with the basic operation of the split screen.

      -

      How the Split Screen Works

      +

      How the Split Screen Works

      The operation of the split screen is simplicity itself. A split screen start scan line value is programmed into two EGA registers or three VGA registers. (More on exactly which registers in a moment.) At the beginning of each frame, the video circuitry begins to scan display memory for video data starting at the address specified by the start address registers, just as it normally would. When the video circuitry encounters the specified split screen start scan line in the course of scanning video data onto the screen, it completes that scan line normally, then resets the internal pointer which addresses the next byte of display memory to be read for video data to zero. Display memory from address zero onward is then scanned for video data in the usual way, progressing toward the high end of memory. At the end of the frame, the pointer to the next byte of display memory to scan is reloaded from the start address registers, and the whole process starts over.

      The net effect: The contents of display memory starting at offset zero are displayed starting at the scan line following the specified split screen start scan line, as shown in Figure 30.1. It’s important to understand that the scan line that matches the split screen scan line is not part of the split screen; the split screen starts on the following scan line. So, for example, if the split screen scan line is set to zero, the split screen actually starts at scan line 1, the second scan line from the top of the screen.

      If both the start address and the split screen start scan line are set to 0, the data at offset zero in display memory is displayed as both the first scan line on the screen and the second scan line. There is no way to make the split screen cover the entire screen—it always comes up at least one scan line short.


      Figure 30.1
        Display memory and the split screen. +
      -->Figure 30.1  Display memory and the split screen.

      So, where is the split screen start scan line stored? The answer varies a bit, depending on whether you’re talking about the EGA or the VGA. On the EGA, the split screen start scan line is a 9-bit value, with bits 7-0 stored in the Line Compare register (CRTC register 18H) and bit 8 stored in bit 4 of the Overflow register (CRTC register 7). Other bits in the Overflow register serve as the high bits of other values, such as the vertical total and the vertical blanking start. Since EGA registers are—alas!—not readable, you must know the correct settings for the other bits in the Overflow registers to use the split screen on an EGA. Fortunately, there are only two standard Overflow register settings on the EGA: 11H for 200-scan-line modes and 1FH for 350-scan-line modes.

      The VGA, of course, presents no such problem in setting the split screen start scan line, for it has readable registers. However, the VGA supports a 10-bit split screen start scan line value, with bits 8-0 stored just as with the EGA, and bit 9 stored in bit 6 of the Maximum Scan Line register (CRTC register 9).

      Turning the split screen on involves nothing more than setting all bits of the split screen start scan line to the scan line after which you want the split screen to start appearing. (Of course, you’ll probably want to change the start address before using the split screen; otherwise, you’ll just end up displaying the memory at offset zero twice: once in the normal screen and once in the split screen.) Turning off the split screen is a simple matter of setting the split screen start scan line to a value equal to or greater than the last scan line displayed; the safest such approach is to set all bits of the split screen start scan line to 1. (That is, in fact, the split screen start scan line value programmed by the BIOS during a mode set.)

      -

      The Split Screen in Action

      +

      The Split Screen in Action

      All of these points are illustrated by Listing 30.1. Listing 30.1 fills display memory starting at offset zero (the split screen area of memory) with text identifying the split screen, fills display memory starting at offset 8000H with a graphics pattern, and sets the start address to 8000H. At this point, the normal screen is being displayed (the split screen start scan line is still set to the BIOS default setting, with all bits equal to 1, so the split screen is off), with the pixels based on the contents of display memory at offset 8000H. The contents of display memory between offset 0 and offset 7FFFH are not visible at all.

      Listing 30.1 then slides the split screen up from the bottom of the screen, one scan line at a time. The split screen slides halfway up the screen, bounces down a quarter of the screen, advances another half-screen, drops another quarter-screen, and finally slides all the way up to the top. If you’ve never seen the split screen in action, you should run Listing 30.1; the smooth overlapping of the split screen on top of the normal display is a striking effect.

      @@ -71,7 +70,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-02.html b/30-02.html index 9ad06bf..bfdf425 100644 --- a/30-02.html +++ b/30-02.html @@ -24,7 +24,7 @@ - +
      @@ -428,7 +428,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-03.html b/30-03.html index 172445e..c41bbe3 100644 --- a/30-03.html +++ b/30-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,11 +36,11 @@


      -

      VGA and EGA Split-Screen Operation Don’t Mix

      +

      VGA and EGA Split-Screen Operation Don’t Mix

      You must set the IS_VGA equate at the start of Listing 30.1 correctly for the adapter the code will run on in order for the program to perform properly. This equate determines how the upper bits of the split screen start scan line are set by SetSplitScreenRow. If IS_VGA is 0 (specifying an EGA target), then bit 8 of the split screen start scan line is set by programming the entire Overflow register to 1FH; this is hard-wired for the 350-scan-line modes of the EGA. If IS_VGA is 1 (specifying a VGA target), then bits 8 and 9 of the split screen start scan line are set by reading the registers they reside in, changing only the split-screen-related bits, and writing the modified settings back to their respective registers.

      The VGA version of Listing 30.1 won’t work on an EGA, because EGA registers aren’t readable. The EGA version of Listing 30.1 won’t work on a VGA, both because VGA monitors require different vertical settings than EGA monitors and because the EGA version doesn’t set bit 9 of the split screen start scan line. In short, there is no way that I know of to support both VGA and EGA split screens with common code; separate drivers are required. This is one of the reasons that split screens are so rarely used in PC programming.

      By the way, Listing 30.1 operates in mode 10H because that’s the highest-resolution mode the VGA and EGA share. That’s not the only mode the split screen works in, however. In fact, it works in all modes, as we’ll see later.

      -

      Setting the Split-Screen-Related Registers

      +

      Setting the Split-Screen-Related Registers

      Setting the split-screen-related registers is not as simple a matter as merely outputting the right values to the right registers; timing is also important. The split screen start scan line value is checked against the number of each scan line as that scan line is displayed, which means that the split screen start scan line potentially takes effect the moment it is set. In other words, if the screen is displaying scan line 15 and you set the split screen start to 16, that change will be picked up immediately and the split screen will start after the next scan line. This is markedly different from changes to the start address, which take effect only at the start of the next frame.

      The instantly-effective nature of the split screen is a bit of a problem, not because the changed screen appears as soon as the new split screen start scan line is set—that seems to me to be an advantage—but because the changed screen can appear before the new split screen start scan line is set.

      @@ -49,7 +49,7 @@

      The solution is simple: Set the split screen start scan line at a time when it can’t possibly match the currently displayed scan line. The easy way to do that is to set it when there isn’t any currently displayed scan line—during vertical non-display time. One safe time that’s easy to find is the start of the vertical sync pulse, which is typically pretty near the middle of vertical non-display time, and that’s the approach I’ve followed in Listing 30.1. I’ve also disabled interrupts during the period when the split screen registers are being set. This isn’t absolutely necessary, but if it’s not done, there’s the possibility that an interrupt will occur between register sets and delay the later register sets until display time, again causing flicker.

      One interesting effect of setting the split screen registers at the start of vertical sync is that it has the effect of synchronizing the program to the display adapter’s frame rate. No matter how fast the computer running Listing 30.1 may be, the split screen will move at a maximum rate of once per frame. This is handy for regulating execution speed over a wide variety of hardware performance ranges; however, be aware that the VGA supports 70 Hz frame rates in all non-480-scan-line modes, while the VGA in 480-scan-line-modes and the EGA in all color modes support 60 Hz frame rates.

      -

      The Problem with the EGA Split Screen

      +

      The Problem with the EGA Split Screen

      I mentioned earlier that the EGA’s split screen is a little buggy. How? you may well ask, particularly given that Listing 30.1 illustrates that the EGA split screen seems pretty functional.

      The bug is this: The first scan line of the EGA split screen—the scan line starting at offset zero in display memory—is displayed not once but twice. In other words, the first line of split screen display memory, and only the first line, is replicated one unnecessary time, pushing all the other lines down by one.

      @@ -70,7 +70,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-04.html b/30-04.html index 433ff89..1838700 100644 --- a/30-04.html +++ b/30-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Split Screen and Panning

      +

      Split Screen and Panning

      Back in Chapter 23, I presented a program that performed smooth horizontal panning. Smooth horizontal panning consists of two parts: byte-by-byte (8-pixel) panning by changing the start address and pixel-by-pixel intrabyte panning by setting the Pel Panning register (AC register 13H) to adjust alignment by 0 to 7 pixels. (IBM prefers its own jargon and uses the word “pel” instead of “pixel” in much of their documentation, hence “pel panning.” Then there’s DASD, a.k.a. Direct Access Storage Device—IBM-speak for hard disk.)

      Horizontal smooth panning works just fine, although I’ve always harbored some doubts that any one horizontal-smooth-panning approach works properly on all display board clones. (More on this later.) There’s a catch when using horizontal smooth panning with the split screen up, though, and it’s a serious catch: You can’t byte-pan the split screen (which always starts at offset zero, no matter what the setting of the start address registers)—but you can pel-pan the split screen.

      @@ -45,7 +45,7 @@

      On the VGA, there is recourse. A VGA-only bit, bit 5 of the AC Mode Control register (AC register 10H), turns off pel panning in the split screen. In other words, when this bit is set to 1, pel panning is reset to zero before the first line of the split screen, and remains zero until the end of the frame. This doesn’t allow you to pan the split screen horizontally, mind you—there’s no way to do that—but it does let you pan the normal screen while the split screen stays rock-solid. This can be used to produce an attractive “streaming tape” effect in the normal screen while the split screen is used to display non-moving information.

      -

      The Split Screen and Horizontal Panning: An Example

      +

      The Split Screen and Horizontal Panning: An Example

      Listing 30.2 illustrates the interaction of horizontal smooth panning with the split screen, as well as the suppression of pel panning in the split screen. Listing 30.2 creates a virtual screen 1024 pixels across by setting the Offset register (CRTC register 13H) to 64, sets the normal screen to scan video data beginning far enough up in display memory to leave room for the split screen starting at offset zero, turns on the split screen, and fills in the normal screen and split screen with distinctive patterns. Next, Listing 30.2 pans the normal screen horizontally without setting bit 5 of the AC Mode Control register to 1. As you’d expect, the split screen jerks about quite horribly. After a key press, Listing 30.2 sets bit 5 of the Mode Control register and pans the normal screen again. This time, the split screen doesn’t budge an inch—if the code is running on a VGA.

      By the way, if IS_VGA is set to 0 in Listing 30.2, the program will assemble in a form that will run on the EGA and only the EGA. Pel panning suppression in the split screen won’t work in this version, however, because the EGA lacks the capability to support that feature. When the EGA version runs, the split screen simply jerks back and forth during both panning sessions.


      @@ -60,7 +60,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-05.html b/30-05.html index a6fd3ae..ebd3af5 100644 --- a/30-05.html +++ b/30-05.html @@ -24,7 +24,7 @@ - +
      @@ -472,7 +472,7 @@ endStart
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-06.html b/30-06.html index 5e71b4e..c238e65 100644 --- a/30-06.html +++ b/30-06.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Notes on Setting and Reading Registers

      +

      Notes on Setting and Reading Registers

      There are a few interesting points regarding setting and reading registers to be made about Listing 30.2. First, bit 5 of the AC Index register should be set to 1 whenever palette RAM is not being set (which is to say, all the time in your code, because palette RAM should normally be set via the BIOS). When bit 5 is 0, video data from display memory is no longer sent to palette RAM, and the screen becomes a solid color—not normally a desirable state of affairs.

      Recall also that the AC Index and Data registers are both written to at I/O address 3C0H, with the toggle that determines which one is written to at any time switching state on every write to 3C0H; this toggle is reset to index mode by each read from the Input Status 0 register (3DAH in color modes, 3BAH in monochrome modes). The AC Index and Data registers can also be written to at 3C1H on the EGA, but not on the VGA, so steer clear of that practice.

      @@ -60,7 +60,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/30-07.html b/30-07.html index 98dfc37..b0b6010 100644 --- a/30-07.html +++ b/30-07.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,12 @@


      -

      Split Screens in Other Modes

      +

      Split Screens in Other Modes

      So far we’ve only discussed the split screen in mode 10H. What about other modes? Generally, the split screen works in any mode; the basic rule is that when a scan line on the screen matches the split screen scan line, the internal display memory pointer is reset to zero. I’ve found this to be true even in oddball modes, such as line-doubled CGA modes and the 320x200 256-color mode (which is really a 320x400 mode with each line repeated. For split-screen purposes, the VGA and EGA seem to count purely in scan lines, not in rows or doubled scan lines or the like. However, I have run into small anomalies in those modes on clones, and I haven’t tested all modes (nor, lord knows, all clones!) so be careful when using the split screen in modes other than modes 0DH-12H, and test your code on a variety of hardware.

      Come to think of it, I warn you about the hazards of running fancy VGA code on clones pretty often, don’t I? Ah, well—just one of the hazards of the diversity and competition of the PC market! It is a fact of life, though—if you’re a commercial developer and don’t test your video code on at least half a dozen VGAs, you’re living dangerously.

      What of the split screen in text mode? It works fine; in fact, it not only resets the internal memory pointer to zero, but also resets the text scan line counter—which marks which line within the font you’re on—to zero, so the split screen starts out with a full row of text. There’s only one trick with text mode: When split screen pel panning suppression is on, the pel panning setting is forced to 0 for the rest of the frame. Unfortunately, 0 is not the “no-panning” setting for 9-dot-wide text; 8 is. The result is that when you turn on split screen pel panning suppression, the text in the split screen won’t pan with the normal screen, as intended, but will also display the undesirable characteristic of moving one pixel to the left. Whether this causes any noticeable on-screen effects depends on the text displayed by a particular application; for example, there should be no problem if the split screen has a border of blanks on the left side.

      -

      How Safe?

      +

      How Safe?

      So, how safe is it to use the split screen? My opinion is that it’s perfectly safe, although I’d welcome input from people with extensive split screen experience—and the effects are striking enough that the split screen is well worth using in certain applications.

      I’m a little more leery of horizontal smooth scrolling, with or without the split screen. Still, the Wilton book doesn’t advise any particular caution, and I haven’t heard any horror stories from the field lately, so the clone manufacturers must finally have gotten it right. (I vividly remember some early clones years back that didn’t quite get it right.) So, on balance, I’d say to use horizontal smooth scrolling if you really need it; on the other hand, in fast animation you can often get away with byte scrolling, which is easier, faster, and safer. (I recently saw a game that scrolled as smoothly as you could ever want. It was only by stopping it with Ctrl-NumLock that I was able to be sure that it was, in fact, byte panning, not pel panning.)

      In short, use the fancy stuff—but only when you have


      @@ -57,7 +57,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/31-01.html b/31-01.html index e0435a0..0e6ce9a 100644 --- a/31-01.html +++ b/31-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,26 +36,25 @@


      -

      Chapter 31
      Higher 256-Color Resolution on the VGA -

      -

      When Is 320x200 Really 320x400?

      +

      Chapter 31
      Higher 256-Color Resolution on the VGA

      +

      When Is 320x200 Really 320x400?

      One of the more appealing features of the VGA is its ability to display 256 simultaneous colors. Unfortunately, one of the less appealing features of the VGA is the limited resolution (320x200) of the one 256-color mode the IBM-standard BIOS supports. (There are, of course, higher resolution 256-color modes in the legion of SuperVGAs, but they are by no means a standard, and differences between seemingly identical modes from different manufacturers can be vexing.) More colors can often compensate for less resolution, but the resolution difference between the 640x480 16-color mode and the 320x200 256-color mode is so great that many programmers must regretfully decide that they simply can’t afford to use the 256-color mode.

      If there’s one thing we’ve learned about the VGA, however, it’s that there’s never just one way to do things. With the VGA, alternatives always exist for the clever programmer, and that’s more true than you might imagine with 256-color mode. Not only is there a high 256-color resolution, there are lots of higher 256-color resolutions, going all the way up to 360x480—and that’s with the vanilla IBM VGA!

      In this chapter, I’m going to focus on one of my favorite 256-color modes, which provides 320x400 resolution and two graphics pages and can be set up with very little reof the VGA. In the next chapter, I’ll discuss higher-resolution 256-color modes, and starting in Chapter 47, I’ll cover the high-performance “Mode X” 256-color programming that many games use.

      So. Let’s get started.

      -

      Why 320x200? Only IBM Knows for Sure

      +

      Why 320x200? Only IBM Knows for Sure

      The first question, of course, is, “How can it be possible to get higher 256-color resolutions out of the VGA?” After all, there were no unused higher resolutions to be found in the CGA, Hercules card, or EGA.

      The answer is another question: “Why did IBM not use the higher-resolution 256-color modes of the VGA?” The VGA is easily capable of twice the 200-scan-line vertical resolution of mode 13H, the 256-color mode, and IBM clearly made a decision not to support a higher-resolution 256-color mode. In fact, mode 13H does display 400 scan lines, but each row of pixels is displayed on two successive scan lines, resulting in an effective resolution of 320x200. This is the same scan-doubling approach used by the VGA to convert the CGA’s 200-scan-line modes to 400 scan lines; however, the resolution of the CGA has long been fixed at 200 scan lines, so IBM had no choice with the CGA modes but to scan-double the lines. Mode 13H has no such historical limitation—it’s the first 256-color mode ever offered by IBM, if you don’t count the late and unlamented Professional Graphics Controller (PGC). Why, then, would IBM choose to limit the resolution of mode 13H?

      There’s no way to know, but one good guess is that IBM wanted a standard 256-color mode across all PS/2 computers (for which the VGA was originally created), and mode 13H is the highest-resolution 256-color mode that could fill the bill. You see, each 256-color pixel requires one byte of display memory, so a 320x200 256-color mode requires 64,000 bytes of display memory. That’s no problem for the VGA, which has 256K of display memory, but it’s a stretch for the MCGA of the Model 30, since the MCGA comes with only 64K.

      On the other hand, the smaller display memory size of the MCGA also limits the number of colors supported in 640x480 mode to 2, rather than the 16 supported by the VGA. In this case, though, IBM simply created two modes and made both available on the VGA: mode 11H for 640x480 2-color graphics and mode 12H for 640x480 16-color graphics. The same could have been done for 256-color graphics—but wasn’t. Why? I don’t know. Maybe IBM just didn’t like the odd aspect ratio of a 320x400 graphics mode. Maybe they didn’t want to have to worry about how to map in more than 64K of display memory. Heck, maybe they made a mistake in designing the chip. Whatever the reason, mode 13H is really a 400-scan-line mode masquerading as a 200-scan-line mode, and we can readily end that masquerade.

      -

      320x400 256-Color Mode

      +

      320x400 256-Color Mode

      Okay, what’s so great about 320x400 256-color mode? Two things: easy, safe mode sets and page flipping.

      As I said above, mode 13H is really a 320x400 mode, albeit with each line doubled to produce an effective resolution of 320x200. That means that we don’t need to change any display timings, widths, or heights in order to tweak mode 13H into 320x400 mode—and that makes 320x400 a safe choice. Basically, 320x400 mode differs from mode 13H only in the settings of mode bits, which are sure to be consistent from one VGA clone to the next and which work equally well with all monitors. The other hi-res 256-color modes differ from mode 13H not only in the settings of the mode bits but also in the settings of timing and dimension registers, which may not be exactly the same on all VGA clones and particularly not on all multisync monitors. (Because multisyncs sometimes shrink the active area of the screen when used with standard VGA modes, some VGAs use alternate register settings for multisync monitors that adjust the CRT Controller timings to use as much of the screen area as possible for displaying pixels.)

      The other good thing about 320x400 256-color mode is that two pages are supported. Each 320x400 256-color mode requires 128,000 bytes of display memory, so we can just barely manage two pages in 320x400 mode, one starting at offset 0 in display memory and the other starting at offset 8000H. Those two pages are the largest pair of pages that can fit in the VGA’s 256K, though, and the higher-resolution 256-color modes, which use still larger bitmaps (areas of display memory that control pixels on the screen), can’t support two pages at all. As we’ve seen in earlier chapters and will see again in this book, paging is very useful for off-screen construction of images and fast, smooth animation.

      That’s why I like 320x400 256-color mode. The next step is to understand how display memory is organized in 320x400 mode, and that’s not so simple.

      -

      Display Memory Organization in 320x400 Mode

      +

      Display Memory Organization in 320x400 Mode

      First, let’s look at why display memory must be organized differently in 320x400 256-color mode than in mode 13H. The designers of the VGA intentionally limited the maximum size of the bitmap in mode 13H to 64K, thereby limiting resolution to 320x200. This was accomplished in hardware, so there is no way to extend the bitmap organization of mode 13H to 320x400 mode.


      @@ -69,7 +68,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/31-02.html b/31-02.html index fd3f222..8d0e9ba 100644 --- a/31-02.html +++ b/31-02.html @@ -24,7 +24,7 @@ - +
      @@ -41,7 +41,7 @@

      We’re talking about the VGA, so of course there are actually several bitmap organizations that let us use higher 256-color resolutions than mode 13H. The one I like best is shown in Figure 31.1. Each byte controls one 256-color pixel. Pixel 0 is at address 0 in plane 0, pixel 1 is at address 0 in plane 1, pixel 2 is at address 0 in plane 2, pixel 3 is at address 0 in plane 3, pixel 4 is at address 1 in plane 0, and so on.

      Let’s look at this another way. Ideally, we’d like one long bitmap, with each pixel at the address that’s just after the address of the pixel to the left. Well, that’s true in this case too, if you consider the number of the plane that the pixel is in to be part of the pixel’s address. View the pixel numbers on the screen as increasing from left to right and from the end of one scan line to the start of the next. Then the pixel number, n, of the pixel at display memory address address in plane plane is:


      Figure 31.1
        Bitmap organization in 320x400 256-color mode in 320x400 256-color mode. +
      -->Figure 31.1  Bitmap organization in 320x400 256-color mode in 320x400 256-color mode.

      n = (address * 4) + plane

      To turn that around, the display memory address of pixel number n is given by

      @@ -51,7 +51,7 @@

      Basically, the full address of the pixel, its pixel number, is broken into two components: the display memory address and the plane.

      By the way, because 320x400 mode has a significantly different memory organization from mode 13H, the BIOS text routines won’t work in 320x400 mode. If you want to draw text in 320x400 mode, you’ll have to look up a font in the BIOS ROM and draw the text yourself. Likewise, the BIOS read pixel and write pixel routines won’t work in 320x400 mode, but that’s no problem because I’ll provide equivalent routines in the next section.

      Our next task is to convert standard mode 13H into 320x400 mode. That’s accomplished by undoing some of the mode bits that are set up especially for mode 13H, so that from a programming perspective the VGA reverts to a straightforward planar model of memory. That means taking the VGA out of chain 4 mode and doubleword mode, turning off the double display of each scan line, making sure chain mode, odd/even mode, and word mode are turned off, and selecting byte mode for video data display. All that’s done in the Set320x400Mode subroutine in Listing 31.1, which we’ll discuss next.

      -

      Reading and Writing Pixels

      +

      Reading and Writing Pixels

      The basic graphics functions in any mode are functions to read and write single pixels. Any more complex function can be built on these primitives, although that’s rarely the speediest solution. What’s more, once you understand the operation of the read and write pixel functions, you’ve got all the knowledge you need to create functions that perform more complex graphics functions. Consequently, we’ll start our exploration of 320x400 mode with pixel-at-a-time line drawing.

      Listing 31.1 draws 8 multicolored octagons in turn, drawing a new one on top of the old one each time a key is pressed. The main-loop code of Listing 31.1 should be easily understood; a series of diagonal, horizontal, and vertical lines are drawn one pixel at a time based on a list of line descriptors, with the draw colors incremented for each successive time through the line list.


      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/31-03.html b/31-03.html index 3036e56..e1ad0ee 100644 --- a/31-03.html +++ b/31-03.html @@ -24,7 +24,7 @@ - +
      @@ -381,7 +381,7 @@ end Start
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/31-04.html b/31-04.html index 5843fb8..96ed448 100644 --- a/31-04.html +++ b/31-04.html @@ -24,7 +24,7 @@ - +
      @@ -51,7 +51,7 @@

      In 320x400 mode, the calculation of the memory address is not significantly slower than in mode 13H, and the calculation and selection of the target plane is quickly accomplished. As with mode 13H, 320x400 mode benefits tremendously from the byte-per-pixel organization of 256-color mode, which eliminates the need for the time-consuming pixel-masking of the 16-color modes. Most important, byte-per-pixel modes never require read-modify-write operations (which can be extremely slow due to display memory wait states) in order to clip and draw pixels. To draw a pixel, you just store its color in display memory—what could be simpler?

      More sophisticated operations than pixel drawing are less easy to accomplish in 320x400 mode, but with a little ingenuity it is possible to implement a reasonably efficient version of just about any useful graphics function. A fast line draw for 320x400 256-color mode would be simple (although not as fast as would be possible in mode 13H). Fast image copies could be implemented by copying one-quarter of the image to one plane, one-quarter to the next plane, and so on for all four planes, thereby eliminating the OUT per pixel that sequential processing requires. If you’re really into performance, you could store your images with all the bytes for plane 0 grouped together, followed by all the bytes for plane 1, and so on. That would allow a single REP MOVS instruction to copy all the bytes for a given plane, with just four REP MOVS instructions copying the whole image. In a number of cases, in fact, 320x400 256-color mode can actually be much faster than mode 13H, because the VGA’s hardware can be used to draw four or even eight pixels with a single access; I’ll return to the topic of high-performance programming in 256-color modes other than mode 13H (“non-chain 4” modes) in Chapter 47.

      It’s all a bit complicated, but as I say, you should be able to design an adequately fast—and often very fast—version for 320x400 mode of whatever graphics function you need. If you’re not all that concerned with speed, WritePixel and ReadPixel should meet your needs.

      -

      Two 256-Color Pages

      +

      Two 256-Color Pages

      Listing 31.2 demonstrates the two pages of 320x400 256-color mode by drawing slanting color bars in page 0, then drawing color bars slanting the other way in page 1 and flipping to page 1 on the next key press. (Note that page 1 is accessed starting at offset 8000H in display memory, and is—unsurprisingly—displayed by setting the start address to 8000H.) Finally, Listing 31.2 draws vertical color bars in page 0 and flips back to page 0 when another key is pressed.

      The color bar routines don’t use the WritePixel subroutine from Listing 31.1; they go straight to display memory instead for improved speed. As I mentioned above, better speed yet could be achieved by a color-bar algorithm that draws all the pixels in plane 0, then all the pixels in plane 1, and so on, thereby avoiding the overhead of constantly reprogramming the Map Mask register.


      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/31-05.html b/31-05.html index 1f8dfd0..06ca7b6 100644 --- a/31-05.html +++ b/31-05.html @@ -24,7 +24,7 @@ - +
      @@ -302,7 +302,7 @@ endStart

      When you run Listing 31.2, note the extremely smooth edges and fine gradations of color, especially in the screens with slanting color bars. The displays produced by Listing 31.2 make it clear that 320x400 256-color mode can produce effects that are simply not possible in any 16-color mode.

      -

      Something to Think About

      +

      Something to Think About

      You can, if you wish, use the display memory organization of 320x400 mode in 320x200 mode by modifying Set320x400Mode to leave the maximum scan line setting at 1 in the mode set. (The version of Set320x400Mode in Listings 31.1 and 31.2 forces the maximum scan line to 0, doubling the effective resolution of the screen.) Why would you want to do that? For one thing, you could then choose from not two but four 320x200 256-color display pages, starting at offsets 0, 4000H, 8000H, and 0C000H in display memory. For another, having only half as many pixels per screen can as much as double drawing speeds; that’s one reason that many games run at 320x200, and even then often limit the active display drawing area to only a portion of the screen.


      @@ -316,7 +316,7 @@ endStart
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/32-01.html b/32-01.html index 16ebfb8..ca7921d 100644 --- a/32-01.html +++ b/32-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,14 +36,13 @@


      -

      Chapter 32
      Be It Resolved: 360x480 -

      -

      Taking 256-Color Modes About as Far as the Standard VGA Can Take Them

      +

      Chapter 32
      Be It Resolved: 360x480

      +

      Taking 256-Color Modes About as Far as the Standard VGA Can Take Them

      In the last chapter, we learned how to coax 320x400 256-color resolution out of a standard VGA. At the time, I noted that the VGA was actually capable of supporting 256-color resolutions as high as 360x480, but didn’t pursue the topic further, preferring to concentrate on the versatile and easy-to-set 320x400 256-color mode instead.

      Some time back I was sent a particularly useful item from John Bridges, a longtime correspondent and an excellent programmer. It was a complete mode set routine for 360x480 256-color mode that he has placed into the public domain. In addition, John wrote, “I also have a couple of freeware (free, but not public domain) utilities out there, including PICEM, which displays PIC, PCX, and GIF images not only in 360x480x256 but also in 640x350x256, 640x400x256, 640x480x256, and 800x600x256 on SuperVGAs.”

      In this chapter, I’m going to combine John’s mode set code with appropriately modified versions of the dot-plot code from Chapter 31 and the line-drawing code that we’ll develop in Chapter 35. Together, those routines will make a pretty nifty demo of the capabilities of 360x480 256-color mode.

      -

      Extended 256-Color Modes: What’s Not to Like?

      +

      Extended 256-Color Modes: What’s Not to Like?

      When last we left 256-color programming, we had found that the standard 256-color mode, mode 13H, which officially offers 320x200 resolution, actually displays 400, not 200, scan lines, with line-doubling used to reduce the effective resolution to 320x200. By tweaking a few of the VGA’s mode registers, we converted mode 13H to a true 320x400 256-color mode. As an added bonus, that 320x400 mode supports two graphics pages, a distinct improvement over the single graphics page supported by mode 13H. (We also learned how to get four graphics pages at 320x200 resolution, should that be needed.)

      I particularly like 320x400 256-color mode for two reasons: It supports two-page graphics, which is very important for animation applications; and it doesn’t require changing any of the monitor timing characteristics of the VGA. The mode bits that we changed to produce 320x400 256-color mode are pretty much guaranteed to be the same from one VGA to another, but the monitor-oriented registers are less certain to be constant, especially for VGAs that provide special support for the extended capabilities of various multiscanning monitors.

      All in all, those are good arguments for 320x400 256-color mode. However, the counter-argument seems compelling as well—nothing beats higher resolution for producing striking graphics. Given that, and given that John Bridges was kind enough to make his mode set code available, I’m going to look at 360x480 256mode next. However, bear in mind that the drawbacks of this mode are the flip side of the strengths of 320x400 256-color mode: Only one graphics page, and direct setting of the monitorregisters. Also, this mode has a peculiar and unique aspect ratio, with 480 pixels (as many as high-resolution mode 12H) vertically and only 360 horizontally. That makes for fairly poor horizontal resolution and sometimes-jagged drawing; on the other hand, the resolution is better in both directions than in mode 13H, and mode 13H itself has an odd aspect ratio, so it seems a bit petty to complain.

      @@ -51,7 +50,7 @@

      I don’t know how likely this code is to produce problems with clone VGAs in general; however, I did find that I had to put an older Video Seven VRAM VGA into “pure” mode—where it treats the VRAMs as DRAMs and exactly emulates a plain-vanilla IBM VGA—before 360x480 256-color mode would work properly. Now, that particular problem was due to an inherent characteristic of VRAMs, and shouldn’t occur on Video Seven’s Fastwrite adapter or any other VGA clone. Nonetheless, 360x480 256-color mode is a good deal different from any standard VGA mode, and while the code in this chapter runs perfectly well on all other VGAs in my experience, I can’t guarantee its functionality on any particular VGA/monitor combination, unlike 320x400 256-color mode. Mind you, 360x480 256-color mode should work on all VGAs—there are just too many variables involved for me to be certain. Feedback from readers with broad 360x480 256-color experience is welcome.

      The above notwithstanding, 360x480 256-color mode offers 64 times as many colors and nearly three times as many pixels as IBM’s original CGA color graphics mode, making startlingly realistic effects possible. No mode of the VGA (at least no mode that I know of!), documented or undocumented, offers a better combination of resolution and color; even 320x400 256-color mode has 26 percent fewer pixels.

      In other words, 360x480 256-color mode is worth considering—so let’s have a look.

      -

      360x480 256-Color Mode

      +

      360x480 256-Color Mode

      I’m going to start by showing you 360x480 256-color mode in action, after which we’ll look at how it works. I suspect that once you see what this mode looks like, you’ll be more than eager to learn how to use it.

      Listing 32.1 contains three C-callable assembly functions. As you would expect, Set360x480Mode places the VGA into 360x480 256mode. Draw360x480Dot draws a pixel of the specified color at the specified location. Finally, Read360x480Dot returns the color of the pixel at the specified location. (This last function isn’t actually used in the example program in this chapter, but is included for completeness.)

      @@ -68,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/32-02.html b/32-02.html index f3a782a..e2fc6b6 100644 --- a/32-02.html +++ b/32-02.html @@ -24,7 +24,7 @@ - +
      @@ -265,7 +265,7 @@ _TEX Tends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/32-03.html b/32-03.html index 6c53209..a86bb7d 100644 --- a/32-03.html +++ b/32-03.html @@ -24,7 +24,7 @@ - +
      @@ -258,7 +258,7 @@ void main()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/32-04.html b/32-04.html index aba86d1..f9b7a62 100644 --- a/32-04.html +++ b/32-04.html @@ -24,7 +24,7 @@ - +
      @@ -40,15 +40,15 @@

      The one thing you may not notice right away is just how much detail is visible on the screen, because the blending of colors tends to obscure the superior resolution of this mode. Each of the four rectangles displayed measures 180 pixels horizontally by 240 vertically. Put another way, each one of those rectangles has two-thirds as many pixels as the entire mode 13H screen; in all, 360x480 256-color mode has 2.7 times as many pixels as mode 13H! As mentioned above, the resolution is unevenly distributed, with vertical resolution matching that of mode 12H but horizontal resolution barely exceeding that of mode 13H—but resolution is hot stuff, no matter how it’s laid out, and 360x480 256-color mode has the highest 256-color resolution you’re ever likely to see on a standard VGA. (SuperVGAs are quite another matter—but when you require a SuperVGA you’re automatically excluding what might be a significant chunk of the market for your code.)

      Now that we’ve seen the wonders of which our new mode is capable, let’s take the time to understand how it works.

      -

      How 360x480 256-Color Mode Works

      +

      How 360x480 256-Color Mode Works

      In describing 360x480 256-color mode, I’m going to assume that you’re familiar with the discussion of 320x400 256-color mode in the last chapter. If not, go back to that chapter and read it; the two modes have a great deal in common, and I’m not going to bore you by repeating myself when the goods are just a few page flips (the paper kind) away.

      360x480 256-color mode is essentially 320x400 256-color mode, but stretched in both dimensions. Let’s look at the vertical stretching first, since that’s the simpler of the two.

      -

      480 Scan Lines per Screen: A Little Slower, But No Big Deal

      +

      480 Scan Lines per Screen: A Little Slower, But No Big Deal

      There’s nothing unusual about 480 scan lines; standard modes 11H and 12H support that vertical resolution. The number of scan lines has nothing to do with either the number of colors or the horizontal resolution, so converting 320x400 256mode to 320x480 256-color mode is a simple matter of reprogramming the VGA’s vertical control registers—which control the scan lines displayed, the vertical sync pulse, vertical blanking, and the total number of scan lines—to the 480-scansettings, and setting the polarities of the horizontal and vertical sync pulses to tell the monitor to adjust to a 480-line screen.

      Switching to 480 scan lines has the effect of slowing the screen refresh rate. The VGA always displays at 70 Hz except in 480-scan-line modes; there, due to the time required to scan the extra lines, the refresh rate slows to 60 Hz. (VGA monitors always scan at the same rate horizontally; that is, the distance across the screen covered by the electron beam in a given period of time is the same in all modes. Consequently, adding extra lines per frame requires extra time.) 60 Hz isn’t bad—that’s the only refresh rate the EGA ever supported, and the EGA was the industry standard in its time—but it does tend to flicker a little more and so is a little harder on the eyes than 70 Hz.

      -

      360 Pixels per Scan Line: No Mean Feat

      +

      360 Pixels per Scan Line: No Mean Feat

      Converting from 320 to 360 pixels per scan line is more difficult than converting from 400 to 480 scan lines per screen. None of the VGA’s graphics modes supports 360 pixels across the screen, or anything like it; the standard choices are 320 and 640 pixels across. However, the VGA does support the horizontal resolution we seek—360 pixels—in 40-column text mode.

      Unfortunately, the register settings that select those horizontal resolutions aren’t directly transferable to graphics mode. Text modes display 9 dots (the width of one character) for each time information is fetched from display memory, while graphics modes display just 4 or 8 dots per display memory fetch. (Although it’s a bit confusing, it’s standard terminology to refer to the interval required for one display memory fetch as a “character,” and I’ll follow that terminology from now on.) Consequently, both modes display either 40 or 80 characters per scan line; the only difference is that text modes display more pixels per character. Given that graphics modes can’t display 9 dots per character (there’s only enough information for eight 16pixels or four 256-color pixels in each memory fetch, and that’s that), we’d seem to be at an impasse.


      @@ -63,7 +63,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/32-05.html b/32-05.html index 04c120d..d82d23f 100644 --- a/32-05.html +++ b/32-05.html @@ -24,7 +24,7 @@ - +
      @@ -41,7 +41,7 @@

      I’ll bet that you can see where I’m headed: We can switch from the 25 MHz clock to the 28 MHz clock in 320x480 256mode in order to get more pixels. It takes two clocks to produce one 256-color pixel, so we’ll get 40 rather than 80 extra pixels by doing this, bringing our horizontal resolution to the desired 360 pixels.

      Switching horizontal resolutions sounds easy, doesn’t it? Alas, it’s not. There’s no standard VGA mode that uses the 28 MHz clock to draw 8 rather than 9 dots per character, so the timing parameters have to be calculated from scratch. John Bridges has already done that for us, but I want you to appreciate that producing this mode took some work. The registers controlling the total number of characters per scan line, the number of characters displayed, the horizontal sync pulse, horizontal blanking, the offset from the start of one line to the start of the next, and the clock speed all have to be altered in order to set up 360x480 256-color mode. The function Set360x480Mode in Listing 32.1 does all that, and sets up the registers that control vertical resolution, as well.

      Once all that’s done, the VGA is in 360x480 mode, awaiting our every high-resolution 256-color graphics whim.

      -

      Accessing Display Memory in 360x480 256-Color Mode

      +

      Accessing Display Memory in 360x480 256-Color Mode

      Setting up for 360x480 256-color mode proved to be quite a task. Is drawing in this mode going to be as difficult?

      No. In fact, if you know how to draw in 320x400 256-color mode, you already know how to draw in 360x480 256-color mode; the conversion between the two is a simple matter of changing the working screen width from 320 pixels to 360 pixels. In fact, if you were to take the 320x400 256-color pixel reading and pixel writing code from Chapter 31 and change the SCREEN_WIDTH equate from 320 to 360, those routines would work perfectly in 360x480 256-color mode.

      @@ -53,7 +53,7 @@

      The other programming difference between the two modes is that the area of display memory mapped to the screen is longer in 360x480 256-color mode, which is only common sense given that there are more pixels in that mode. The exact amount of memory required in 360x480 256-color mode is 360 times 480 = 172,800 bytes. That’s more than half of the VGA’s 256 Kb memory complement, so page-flipping is out; however, there’s no reason you couldn’t use that extra memory to create a virtual screen larger than 360x480, around which you could then scroll, if you wish.

      That’s really all there is to drawing in 360x480 256-color mode. From a programming perspective, this mode is no more complicated than 320x400 256-color mode once the mode set is completed, and should be capable of good performance given some clever coding. It’s not particular straightforward to implement bitblt, block move, or fast line-drawing code for any of the extended 256-color modes, but it can be done—and it’s worth the trouble. Even the small taste we’ve gotten of the capabilities of these modes shows that they put the traditional CGA, EGA, and generally even VGA modes to shame.


      Figure 32.1
        Pixel organization in 360x480 256-color mode. +
      -->Figure 32.1  Pixel organization in 360x480 256-color mode.

      There’s more and better to come, though; in later chapters, we’ll return to high-resolution 256-color programming in a big way, by exploring the tremendous potential of these modes for real time 2-D and 3-D animation.


      @@ -69,7 +69,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/33-01.html b/33-01.html index 04404ca..669ee9d 100644 --- a/33-01.html +++ b/33-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,26 +36,25 @@


      -

      Chapter 33
      Yogi Bear and Eurythmics Confront VGA Colors -

      -

      The Basics of VGA Color Generation

      +

      Chapter 33
      Yogi Bear and Eurythmics Confront VGA Colors

      +

      The Basics of VGA Color Generation

      Kevin Mangis wants to know about the VGA’s 4-bit to 8-bit to 18-bit color translation. Mansur Loloyan would like to find out how to generate a look-up table containing 256 colors and how to change the default color palette. And surely they are only the tip of the iceberg; hordes of screaming programmers from every corner of the planet are no doubt tearing the place up looking for a discussion of VGA color, and venting their frustration at my mailbox. Let’s have it, they’ve said, clearly and in considerable numbers. As Eurythmics might say, who is this humble writer to disagree?

      On the other hand, I hope you all know what you’re getting into. To paraphrase Yogi, the VGA is smarter (and more confusing) than the average board. There’s the basic 8-bit to 18-bit translation, there’s the EGA-compatible 4-bit to 6-bit translation, there’s the 2- or 4-bit color paging register that’s used to pad 6- or 4-bit pixel values out to 8 bits, and then there’s 256-color mode. Fear not, it will all make sense in the end, but it may take us a couple of additional chapters to get there—so let’s get started.

      Before we begin, though, I must refer you to Michael Covington’s excellent article, “Color Vision and the VGA,” in the June/July 1990 issue of PC TECHNIQUES. Michael, one of the most brilliant people it has ever been my pleasure to meet, is an expert in many areas I know nothing about, including linguistics and artificial intelligence. Add to that list the topic of color perception, for his article superbly describes the mechanisms by which we perceive color and ties that information to the VGA’s capabilities. After reading Michael’s article, you’ll understand what colors the VGA is capable of generating, and why.

      Our topic in this chapter complements Michael’s article nicely. Where he focused on color perception, we’ll focus on color generation; that is, the ways in which the VGA can be programmed to generate those colors that lie within its capabilities. To find out why a VGA can’t generate as pure a red as an LED, read Michael’s article. If you want to find out how to flip between 16 different sets of 16 colors, though, don’t touch that dial!

      I would be remiss if I didn’t point you in the direction of two more articles, these in the July 1990 issue of Dr. Dobb’s Journal. “Super VGA Programming,” by Chris Howard, provides a good deal of useful information about SuperVGA chipsets, modes, and programming. “Circles and the Digital Differential Analyzer,” by Tim Paterson, is a good article about fast circle drawing, a topic we’ll tackle soon. All in all, the dog days of 1990 were good times for graphics.

      -

      VGA Color Basics

      +

      VGA Color Basics

      Briefly put, the VGA color translation circuitry takes in one 4- or 8-bit pixel value at a time and translates it into three 6-bit values, one each of red, green, and blue, that are converted to corresponding analog levels and sent to the monitor. Seems simple enough, doesn’t it? Unfortunately, nothing is ever that simple on the VGA, and color translation is no exception.

      -

      The Palette RAM

      +

      The Palette RAM

      The color path in the VGA involves two stages, as shown in Figure 33.1. The first stage fetches a 4-bit pixel from display memory and feeds it into the EGA-compatible palette RAM (so called because it is functionally equivalent to the palette RAM color translation circuitry of the EGA), which translates it into a 6-bit value and sends it on to the DAC. The translation involves nothing more complex than the 4-bit value of a pixel being used as the address of one of the 16 palette RAM registers; a pixel value of 0 selects the contents of palette RAM register 0, a pixel value of 1 selects register 1, and so on. Each palette RAM register stores 6 bits, so each time a palette RAM register is selected by an incoming 4-bit pixel value, 6 bits of information are sent out by the palette RAM. (The operation of the palette RAM was described back in Chapter 29.)

      The process is much the same in text mode, except that in text mode each 4-bit pixel value is generated based on the character’s font pattern and attribute. In 256-color mode, which we’ll get to eventually, the palette RAM is not a factor from the programmer’s perspective and should be left alone.

      -

      The DAC

      +

      The DAC

      Once the EGA-compatible palette RAM has fulfilled its karma and performed 4-bit to 6-bit translation on a pixel, the resulting value is sent to the DAC (Digital/Analog Converter). The DAC performs an 8-bit to 18-bit conversion in much the same manner as the palette RAM, converts the 18-bit result to analog red, green, and blue signals (6 bits for each signal), and sends the three analog signals to the monitor. The DAC is a separate chip, external to the VGA chip, but it’s an integral part of the VGA standard and is present on every VGA.


      Figure 33.1
        The VGA color generation path. +
      -->Figure 33.1  The VGA color generation path.

      (I’d like to take a moment to point out that you can’t speak of “color” at any point in the color translation process until the output stage of the DAC. The 4-bit pixel values in memory, 6-bit values in the palette RAM, and 8-bit values sent to the DAC are all attributes, not colors, because they’re subject to translation by a later stage. For example, a pixel with a 4-bit value of 0 isn’t black, it’s attribute 0. It will be translated to 3FH if palette RAM register 0 is set to 3FH, but that’s not the color white, just another attribute. The value 3FH coming into the DAC isn’t white either, and if the value stored in DAC register 63 is red=7, green=0, and blue=0, the actual color displayed for that pixel that was 0 in display memory will be dim red. It isn’t color until the DAC says it’s color.)

      The DAC contains 256 18-bit storage registers, used to translate one of 256 possible 8-bit values into one of 256K (262,144, to be precise) 18-bit values. The 18-bit values are actually composed of three 6-bit values, one each for red, green, and blue; for each color component, the higher the number, the brighter the color, with 0 turning that color off in the pixel and 63 (3FH) making that color maximum brightness. Got all that?


      @@ -71,7 +70,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/33-02.html b/33-02.html index 15e6240..629e8a1 100644 --- a/33-02.html +++ b/33-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,16 @@


      -

      Color Paging with the Color Select Register

      +

      Color Paging with the Color Select Register

      “Wait a minute,” you say bemusedly. “Aren’t you missing some bits between the palette RAM and the DAC?” Indeed I am. The palette RAM puts out 6 bits at a time, and the DAC takes in 8 bits at a time. The two missing bits—bits 6 and 7 going into the DAC—are supplied by bits 2 and 3 of the Color Select register (Attribute Controller register 14H). This has intriguing implications. In 16-color modes, pixel data can select only one of 16 attributes, which the EGA palette RAM translates into one of 64 attributes. Normally, those 64 attributes look up colors from registers 0 through 63 in the DAC, because bits 2 and 3 of the Color Select register are both zero. By changing the Color Select register, however, one of three other 64 color sets can be selected instantly. I’ll refer to the process of flipping through color sets in this manner as color paging.

      That’s interesting, but frankly it seems somewhat half-baked; why bother expanding 16 attributes to 64 attributes before looking up the colors in the DAC? What we’d really like is to map the 16 attributes straight through the palette RAM without changing them and supply the upper 4 bits going to the DAC from a register, giving us 16 color pages. As it happens, all we have to do to make that happen is set bit 7 of the Attribute Controller Mode register (register 10H) to 1. Once that’s done, bits 0 through 3 of the Color Select register go straight to bits 4 through 7 of the DAC, and only bits 3 through 0 coming out of the palette RAM are used; bits 4 and 5 from the palette RAM are ignored. In this mode, the palette RAM effectively contains 4-bit, rather than 6-bit, registers, but that’s no problem because the palette RAM will be programmed to pass pixel values through unchanged by having register 0 set to 0, register 1 set to 1, and so on, a configuration in which the upper two bits of all the palette RAM registers are the same (zero) and therefore irrelevant. As a matter of fact, you’ll generally want to set the palette RAM to this pass-through state when working with VGA color, whether you’re using color paging or not.

      Why is it a good idea to set the palette RAM to a pass-through state? It’s a good idea because the palette RAM is programmed by the BIOS to EGA-compatible settings and the first 64 DAC registers are programmed to emulate the 64 colors that an EGA can display during mode sets for 16-color modes. This is done for compatibility with EGA programs, and it’s useless if you’re going to tinker with the VGA’s colors. As a VGA programmer, you want to take a 4-bit pixel value and turn it into an 18-bit RGB value; you can do that without any help from the palette RAM, and setting the palette RAM to pass-through values effectively takes it out of the circuit and simplifies life something wonderful. The palette RAM exists solely for EGA compatibility, and serves no useful purpose that I know of for VGA-only color programming.

      -

      256-Color Mode

      +

      256-Color Mode

      So far I’ve spoken only of 16-color modes; what of 256-color modes?

      The rule in 256-color modes is: Don’t tinker with the VGA palette. Period. You can select any colors you want by reprogramming the DAC, and there’s no guarantee as to what will happen if you mess around with the palette RAM. There’s no benefit that I know of to changing the palette RAM in 256-color mode, and the effect may vary from VGA to VGA. So don’t do it unless you know something I don’t.

      On the other hand, feel free to alter the DAC settings to your heart’s content in 256-color mode, all the more so because this is the only mode in which all 256 DAC settings can be displayed simultaneously. By the way, the Color Select register and bit 7 of the Attribute Controller Mode register are ignored in 256-color mode; all 8 bits sent from the VGA chip to the DAC come from display memory. Therefore, there is no color paging in 256-color mode. Of course, that makes sense given that all 256 DAC registers are simultaneously in use in 256-color mode.

      -

      Setting the Palette RAM

      +

      Setting the Palette RAM

      The palette RAM can be programmed either directly or through BIOS interrupt 10H, function 10H. I strongly recommend using the BIOS interrupt; a clone BIOS may mask incompatibilities with genuine IBM silicon. Such incompatibilities could include anything from flicker to trashing the palette RAM; or they may not exist at all, but why find out the hard way? My policy is to use the BIOS unless there’s a clear reason not to do so, and there’s no such reason that I know of in this case.

      When programming specifically for the VGA, the palette RAM needs to be loaded only once, to store the pass-through values 0 through 15 in palette RAM registers 0 through 15. Setting the entire palette RAM is accomplished easily enough with subfunction 2 (AL=2) of function 10H (AH=10H) of interrupt 10H. A single call to this subfunction sets all 16 palette RAM registers (and the Overscan register) from a block of 17 bytes pointed to by ES:DX, with ES:DX pointing to the value for register 0, ES:DX+1 pointing to the value for register 1, and so on up to ES:DX+16, which points to the overscan value. The palette RAM registers store 6 bits each, so only the lower 6 bits of each of the first 16 bytes in the 17-byte block are significant. (The Overscan register, which specifies what’s displayed between the area of the screen that’s controlled by the values in display memory and the blanked region at the edges of the screen, is an 8-bit register, however.)

      @@ -63,7 +63,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/33-03.html b/33-03.html index 4abdb1c..50746f8 100644 --- a/33-03.html +++ b/33-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,13 +36,13 @@


      -

      Setting the DAC

      +

      Setting the DAC

      Like the palette RAM, the DAC registers can be set either directly or through the BIOS. Again, the BIOS should be used whenever possible, but there are a few complications here. My experience is that varying degrees of flicker and screen bounce occur on many VGAs when a large block of DAC registers is set through the BIOS. That’s not a problem when the DAC is loaded just once and then left that way, as is the case in Listing 33.1, which we’ll get to shortly, but it can be a serious problem when the color set is changed rapidly (“cycled”) to produce on-screen effects such as rippling colors. My (limited) experience is that it’s necessary to program the DAC directly in order to cycle colors cleanly, although input from readers who have worked extensively with VGA color is welcome.

      At any rate, the code in this chapter will use the BIOS to set the DAC, so I’ll describe the BIOS DAC-setting functions next. Later, I’ll briefly describe how to set both the palette RAM and DAC registers directly, and I’ll return to the topic in detail in an upcoming chapter when we discuss color cycling.

      An individual DAC register can be set by interrupt 10H, function 10H (AH=10), subfunction 10H (AL=10H), with BX indicating the register to be set and the color to which that register is to be set stored in DH (6-bit red component), CH (6-bit green component), and CL (6-bit blue component).

      A block of sequential DAC registers ranging in size from one register up to all 256 can be set via subfunction 12H (AL=12H) of interrupt 10H, function 10H (AH=10H). In this case, BX contains the number of the first register to set, CX contains the number of registers to set, and ES:DX contains the address of a table of color entries to which DAC registers BX through BX+CX-1 are to be set. The color entry for each DAC register consists of three bytes; the first byte is a 6-bit red component, the second byte is a 6-bit green component, and the third byte is a 6-bit blue component, as illustrated by Listing 33.1.

      -

      If You Can’t Call the BIOS, Who Ya Gonna Call?

      +

      If You Can’t Call the BIOS, Who Ya Gonna Call?

      Although the palette RAM and DAC registers should be set through the BIOS whenever possible, there are times when the BIOS is not the best choice or even a choice at all; for example, a protected-mode program may not have access to the BIOS. Also, as mentioned earlier, it may be necessary to program the DAC directly when performing color cycling. Therefore, I’ll briefly describe how to set the palette RAM and DAC registers directly; in Chapter A on the companion CD-ROM I’ll discuss programming the DAC directly in more detail.

      The palette RAM registers are Attribute Controller registers 0 through 15. They are set by first reading the Input Status 1 register (at 3DAH in color mode or 3BAH in monochrome mode) to reset the Attribute Controller toggle to index mode, then loading the Attribute Controller Index register (at 3C0H) with the number (0 through 15) of the register to be loaded. Do not set bit 5 of the Index register to 1, as you normally would, but rather set bit 5 to 0. Setting bit 5 to 0 allows values to be written to the palette RAM registers, but it also causes the screen to blank, so you should wait for the start of vertical retrace before loading palette RAM registers if you don’t want the screen to flicker. (Do you see why it’s easier to go through the BIOS?) Then, write the desired register value to 3C0H, which has now toggled to become the Attribute Controller Data register. Write any desired number of additional register number/register data pairs to 3C0H, then write 20H to 3C0H to unblank the screen.

      @@ -51,7 +51,7 @@

      Loading the DAC is just as sequence-dependent and potentially susceptible to interference as is loading the palette, so my personal inclination is to go through the whole process of disabling interrupts, loading the DAC Write Index, and writing a three-byte RGB value separately for each DAC register; although that doesn’t take advantage of the autoincrementing feature, it seems to me to be least susceptible to outside influences. (It would be even better to disable interrupts for the entire duration of DAC register loading, but that’s much too long a time to leave interrupts off.) However, I have no hard evidence to offer in support of my conservative approach to setting the DAC, just an uneasy feeling, so I’d be most interested in hearing from any readers.

      A final point is that the process of loading both the palette RAM and DAC registers involves performing multiple OUTs to the same register. Many people whose opinions I respect recommend delaying between I/O accesses to the same port by performing a JMP $+2 (jumping flushes the prefetch queue and forces a memory access—or at least a cache access—to fetch the next instruction byte). In fact, some people recommend two JMP $+2 instructions between I/O accesses to the same port, and three jumps between I/O accesses to the same port that go in opposite directions (OUT followed by IN or IN followed by OUT). This is clearly necessary when accessing some motherboard chips, but I don’t know how applicable it is when accessing VGAs, so make of it what you will. Input from knowledgeable readers is eagerly solicited.

      In the meantime, if you can use the BIOS to set the DAC, do so; then you won’t have to worry about the real and potential complications of setting the DAC directly.

      -

      An Example of Setting the DAC

      +

      An Example of Setting the DAC

      This chapter has gotten about as big as a chapter really ought to be; the VGA color saga will continue in the next few. Quickly, then, Listing 33.1 is a simple example of setting the DAC that gives you a taste of the spectacular effects that color translation makes possible. There’s nothing particularly complex about Listing 33.1; it just selects 256-color mode, fills the screen with one-pixel-wide concentric diamonds drawn with sequential attributes, and sets the DAC to produce a smooth gradient of each of the three primary colors and of a mix of red and blue. Run the program; I suspect you’ll be surprised at the stunning display this short program produces. Clever color manipulation is perhaps the easiest way to produce truly eye-catching effects on the PC.


      @@ -66,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/33-04.html b/33-04.html index 94c8486..fbff2f6 100644 --- a/33-04.html +++ b/33-04.html @@ -24,7 +24,7 @@ - +
      @@ -232,7 +232,7 @@ FillVertLoop:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/34-01.html b/34-01.html index c47ff87..d818a33 100644 --- a/34-01.html +++ b/34-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,19 +36,18 @@


      -

      Chapter 34
      Changing Colors without Writing Pixels -

      -

      Special Effects through Realtime Manipulation of DAC Colors

      +

      Chapter 34
      Changing Colors without Writing Pixels

      +

      Special Effects through Realtime Manipulation of DAC Colors

      Sometimes, strange as it may seem, the harder you try, the less you accomplish. Brute force is fine when it suffices, but it does not always suffice, and when it does not, finesse and alternative approaches are called for. Such is the case with rapidly cycling through colors by repeatedly loading the VGA’s Digital to Analog Converter (DAC). No matter how much you optimize your code, you just can’t reliably load the whole DAC cleanly in a single frame, so you had best find other ways to use the DAC to cycle colors. What’s more, BIOS support for DAC loading is so inconsistent that it’s unusable for color cycling; direct loading through the I/O ports is the only way to go. We’ll see why next, as we explore color cycling, and then finish up this chapter and this section by cleaning up some odds and ends about VGA color.

      There’s a lot to be said about loading the DAC, so let’s dive right in and see where the complications lie.

      -

      Color Cycling

      +

      Color Cycling

      As we’ve learned in past chapters, the VGA’s DAC contains 256 storage locations, each holding one 18-bit value representing an RGB color triplet organized as 6 bits per primary color. Each and every pixel generated by the VGA is fed into the DAC as an 8-bit value (refer to Chapter 33 and to Chapter A on the companion CD-ROM to see how pixels become 8-bit values in non-256 color modes) and each 8-bit value is used to look up one of the 256 values stored in the DAC. The looked-up value is then converted to analog red, green, and blue signals and sent to the monitor to form one pixel.

      That’s straightforward enough, and we’ve produced some pretty impressive color effects by loading the DAC once and then playing with the 8-bit path into the DAC. Now, however, we want to generate color effects by dynamically changing the values stored in the DAC in real time, a technique that I’ll call color cycling. The potential of color cycling should be obvious: Smooth motion can easily be simulated by altering the colors in an appropriate pattern, and all sorts of changing color effects can be produced without altering a single bit of display memory.

      For example, a sunset can be made to color and darken by altering the DAC locations containing the colors used to draw the sunset, or a river can be made to appear to flow by cycling through the colors used to draw the river. Another use for color cycling is in providing more realistic displays for applications like realtime 3-D games, where the VGA’s 256 simultaneous colors can be made to seem like many more by changing the DAC settings from frame to frame to match the changing color demands of the rendered scene. Which leaves only one question: How do we load the DAC smoothly in realtime?

      Actually, so far as I know, you can’t. At least you can’t load the entire DAC—all 256 locations—frame after frame without producing distressing on-screen effects on at least some computers. In non-256 color modes, it is indeed possible to load the DAC quickly enough to cycle all displayed colors (of which there are 16 or fewer), so color cycling could be used successfully to cycle all colors in such modes. On the other hand, color paging (which flips among a number of color sets stored within the DAC in all modes other than 256 color mode, as discussed in Chapter A on the companion CD-ROM) can be used in non-256 color modes to produce many of the same effects as color cycling and is considerably simpler and more reliable then color cycling, so color paging is generally superior to color cycling whenever it’s available. In short, color cycling is really the method of choice for dynamic color effects only in 256-color mode—but, regrettably, color cycling is at its least reliable and capable in that mode, as we’ll see next.

      -

      The Heart of the Problem

      +

      The Heart of the Problem

      Here’s the problem with loading the entire DAC repeatedly: The DAC contains 256 color storage locations, each loaded via either 3 or 4 OUT instructions (more on that next), so at least 768 OUTs are needed to load the entire DAC. That many OUTs take a considerable amount of time, all the more so because OUTs are painfully slow on 486s and Pentiums, and because the DAC is frequently on the ISA bus (although VLB and PCI are increasingly common), where wait states are inserted in fast computers. In an 8 MHz AT, 768 OUTs alone would take 288 microseconds, and the data loading and looping that are also required would take in the ballpark of 1,800 microseconds more, for a minimum of 2 milliseconds total.

      As it happens, the DAC should only be loaded during vertical blanking; that is, the time between the end of displaying the bottom border and the start of displaying the top border, when no video information at all is being sent to the screen by the DAC. Otherwise, small dots of snow appear on the screen, and while an occasional dot of this sort wouldn’t be a problem, the constant DAC loading required by color cycling would produce a veritable snowstorm on the screen. By the way, I do mean “border,” not “frame buffer”; the overscan pixels pass through the DAC just like the pixels controlled by the frame buffer, so you can’t even load the DAC while the border color is being displayed without getting snow.

      The start of vertical blanking itself is not easy to find, but the leading edge of the vertical sync pulse is easy to detect via bit 3 of the Input Status 1 register at 3DAH; when bit 3 is 1, the vertical sync pulse is active. Conveniently, the vertical sync pulse starts partway through but not too far into vertical blanking, so it serves as a handy way to tell when it’s safe to load the DAC without producing snow on the screen.

      @@ -65,7 +64,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/34-02.html b/34-02.html index d03c3a5..90b73d1 100644 --- a/34-02.html +++ b/34-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Loading the DAC via the BIOS

      +

      Loading the DAC via the BIOS

      The DAC can be loaded either directly or through subfunctions 10H (for a single DAC register) or 12H (for a block of DAC registers) of the BIOS video service interrupt 10H, function 10H, described in Chapter 33. For cycling the contents of the entire DAC, the block-load function (invoked by executing INT 10H with AH = 10H and AL = 12H to load a block of CX DAC locations, starting at location BX, from the block of RGB triplets—3 bytes per triplet—starting at ES:DX into the DAC) would be the better of the two, due to the considerably greater efficiency of calling the BIOS once rather than 256 times. At any rate, we’d like to use one or the other of the BIOS functions for color cycling, because we know that whenever possible, one should use a BIOS function in preference to accessing hardware directly, in the interests of avoiding compatibility problems. In the case of color cycling, however, it is emphatically not possible to use either of the BIOS functions, for they have problems. Serious problems.

      The difficulty is this: IBM’s BIOS specification describes exactly how the parameters passed to the BIOS control the loading of DAC locations, and all clone BIOSes meet that specification scrupulously, which is to say that if you invoke INT 10H, function 10H, subfunction 12H with a given set of parameters, you can be sure that you will end up with the same values loaded into the same DAC locations on all VGAs from all vendors. IBM’s spec does not, however, describe whether vertical retrace should be waited for before loading the DAC, nor does it mention whether video should be left enabled while loading the DAC, leaving cloners to choose whatever approach they desire—and, alas, every VGA cloner seems to have selected a different approach.

      I tested four clone VGAs from different manufacturers, some in a 20 MHz 386 machine and some in a 10 MHz 286 machine. Two of the four waited for vertical retrace before loading the DAC; two didn’t. Two of the four blanked the display while loading the DAC, resulting in flickering bars across the screen. One showed speckled pixels spattered across the top of the screen while the DAC was being loaded. Also, not one was able to load all 256 DAC locations without showing some sort of garbage on the screen for at least one frame, but that’s not the BIOS’s fault; it’s a problem endemic to the VGA.

      @@ -44,7 +44,7 @@

      As but one example of the unsuitability of the BIOS DAC-loading functions for color cycling, imagine that you want to cycle all 256 colors 70 times a second, which is once per frame. In order to accomplish that, you would normally wait for the start of the vertical sync signal (marking the end of the frame), then call the BIOS to load the DAC. On some boards—boards with BIOSes that don’t wait for vertical sync before loading the DAC—that will work pretty well; you will, in fact, load the DAC once a frame. On other boards, however, it will work very poorly indeed; your program will wait for the start of vertical sync, and then the BIOS will wait for the start of the next vertical sync, with the result being that the DAC gets loaded only once every two frames. Sadly, there’s no way, short of actually profiling the performance of BIOS DAC loads, for you to know which sort of BIOS is installed in a particular computer, so unless you can always control the brand of VGA your software will run on, you really can’t afford to color cycle by calling the BIOS.

      Which is not to say that loading the DAC directly is a picnic either, as we’ll see next.

      -

      Loading the DAC Directly

      +

      Loading the DAC Directly

      So we must load the DAC directly in order to perform color cycling. The DAC is loaded directly by sending (with an OUT instruction) the number of the DAC location to be loaded to the DAC Write Index register at 3C8H and then performing three OUTs to write an RGB triplet to the DAC Data register at 3C9H. This approach must be repeated 256 times to load the entire DAC, requiring over a thousand OUTs in all.

      There is another, somewhat faster approach, but one that has its risks. After an RGB triplet is written to the DAC Data register, the DAC Write Index register automatically increments to point to the next DAC location, and this repeats indefinitely as successive RGB triplets are written to the DAC. By taking advantage of this feature, the entire DAC can be loaded with just 769 OUTs: one OUT to the DAC Write Index register and 768 OUTs to the DAC Data register.

      So what’s the drawback? Well, imagine that as you’re loading the DAC, an interrupt-driven TSR (such as a program switcher or multitasker) activates and writes to the DAC; you could end up with quite a mess on the screen, especially when your program resumes and continues writing to the DAC—but in all likelihood to the wrong locations. No problem, you say; just disable interrupts for the duration. Good idea—but it takes much longer to load the DAC than interrupts should be disabled for. If, on the other hand, you set the index for each DAC location separately, you can disable interrupts 256 times, once as each DAC location is loaded, without problems.

      @@ -61,7 +61,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/34-03.html b/34-03.html index 5a2293c..e08e8f2 100644 --- a/34-03.html +++ b/34-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      A Test Program for Color Cycling

      +

      A Test Program for Color Cycling

      Anyway, the choice of how to load the DAC is yours. Given that I’m not providing you with any hard-and-fast rules (mainly because there don’t seem to be any), what you need is a tool so that you can experiment with various DAC-loading approaches for yourself, and that’s exactly what you’ll find in Listing 34.1.

      Listing 34.1 draws a band of vertical lines, each one pixel wide, across the screen. The attribute of each vertical line is one greater than that of the preceding line, so there’s a smooth gradient of attributes from left to right. Once everything is set up, the program starts cycling the colors stored in however many DAC locations are specified by the CYCLE_SIZE equate; as many as all 256 DAC locations can be cycled. (Actually, CYCLE_SIZE-1 locations are cycled, because location 0 is kept constant in order to keep the background and border colors from changing, but CYCLE_SIZE locations are loaded, and it’s the number of locations we can load without problems that we’re interested in.)

      @@ -307,7 +307,7 @@ endif;USE_BIOS
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/34-04.html b/34-04.html index 4535368..0f51ac4 100644 --- a/34-04.html +++ b/34-04.html @@ -24,7 +24,7 @@ - +
      @@ -47,7 +47,7 @@

      If, however, NOT_8088 is 1, indicating that the processor is a 286 or better (perhaps AT_LEAST_286 would have been a better name), then after the initial DAC Write Index value is set, all 768 DAC locations are loaded with a single REP OUTSB. This is clearly the fastest approach, but it runs the risk, albeit remote, that the loading sequence will be interrupted and the DAC registers will become garbled.

      My own experience with Listing 34.1 indicates that it is sometimes possible to load all 256 locations cleanly but sometimes it is not; it all depends on the processor, the bus speed, the VGA, and the DAC, as well as whether autoincrementation and REP OUTSB are used. I’m not going to bother to report how many DAC locations I could successfully load with each of the various approaches, for the simple reason that I don’t have enough data points to make reliable suggestions, and I don’t want you acting on my comments and running into trouble down the pike. You now have a versatile tool with which to probe the limitations of various DAC-loading approaches; use it to perform your own tests on a sampling of the slowest hardware configurations you expect your programs to run on, then leave a generous safety margin.

      One thing’s for sure, though—you’re not going to be able to cycle all 256 DAC locations cleanly once per frame on a reliable basis across the current generation of PCs. That’s why I said at the outset that brute force isn’t appropriate to the task of color cycling. That doesn’t mean that color cycling can’t be used, just that subtler approaches must be employed. Let’s look at some of those alternatives.

      -

      Color Cycling Approaches that Work

      +

      Color Cycling Approaches that Work

      First of all, I’d like to point out that when color cycling does work, it’s a thing of beauty. Assemble Listing 34.1 so that it doesn’t use the BIOS to load the DAC, doesn’t guard against interrupts, and uses 286-specific instructions if your computer supports them. Then tinker with CYCLE_SIZE until the color cycling is perfectly clean on your computer. Color cycling looks stunningly smooth, doesn’t it? And this is crude color cycling, working with the default color set; switch over to a color set that gradually works its way through various hues and saturations, and you could get something that looks for all the world like true-color animation (albeit working with a small subset of the full spectrum at any one time).

      Given that, how can we take advantage of color cycling within the limitations of loading the DAC? The simplest approach, and my personal favorite, is that of cycling a portion of the DAC while using the rest of the DAC locations for other, non-cycling purposes. For example, you might allocate 32 DAC locations to the aforementioned sunset, reserve 160 additional locations for use in drawing a static mountain scene, and employ the remaining 64 locations to draw images of planes, cars, and the like in the foreground. The 32 sunset colors could be cycled cleanly, and the other 224 colors would remain the same throughout the program, or would change only occasionally.

      That suggests a second possibility: If you have several different color sets to be cycled, interleave the loading so that only one color set is cycled per frame. Suppose you are animating a night scene, with stars twinkling in the background, meteors streaking across the sky, and a spaceship moving across the screen with its jets flaring. One way to produce most of the necessary effects with little effort would be to draw the stars in several attributes and then cycle the colors for those attributes, draw the meteor paths in successive attributes, one for each pixel, and then cycle the colors for those attributes, and do much the same for the jets. The only remaining task would be to animate the spaceship across the screen, which is not a particularly difficult task.

      @@ -66,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/34-05.html b/34-05.html index 780b006..c6b04e2 100644 --- a/34-05.html +++ b/34-05.html @@ -24,7 +24,7 @@ - +
      @@ -42,18 +42,18 @@

      Yet another approach to color cycling is that of loading a bit of the DAC during each horizontal blanking period. Combine that with counting scan lines, and you could vastly expand the number of simultaneous on-screen colors by cycling colors as a frame is displayed, so that the color set changes from scan line to scan line down the screen.

      The possibilities are endless. However, were I to be writing 256-color software that used color cycling, I’d find out how many colors could be cycled after the start of vertical sync on the slowest computer I expected the software to run on, I’d lop off at least 10 percent for a safety margin, and I’d structure my program so that no color cycling set exceeded that size, interleaving several color cycling sets if necessary.

      That’s what I’d do. Don’t let yourself be held back by my limited imagination, though! Color cycling may be the most complicated of all the color control techniques, but it’s also the most powerful.

      -

      Odds and Ends

      +

      Odds and Ends

      In my experience, when relying on the autoincrementing feature while loading the DAC, the Write Index register wraps back from 255 to 0, and likewise when you load a block of registers through the BIOS. So far as I know, this is a characteristic of the hardware, and should be consistent; also, Richard Wilton documents this behavior for the BIOS in the VGA bible, Programmer’s Guide to PC Video Systems, Second Edition (Microsoft Press), so you should be able to count on it. Not that I see that DAC index wrapping is especially useful, but it never hurts to understand exactly how your resources behave, and I never know when one of you might come up with a serviceable application for any particular quirk.

      -

      The DAC Mask

      +

      The DAC Mask

      There’s one register in the DAC that I haven’t mentioned yet, the DAC Mask register at 03C6H. The operation of this register is simple but powerful; it can mask off any or all of the 8 bits of pixel information coming into the DAC from the VGA. Whenever a bit of the DAC Mask register is 1, the corresponding bit of pixel information is passed along to the DAC to be used in looking up the RGB triplet to be sent to the screen. Whenever a bit of the DAC Mask register is 0, the corresponding pixel bit is ignored, and a 0 is used for that bit position in all look-ups of RGB triplets. At the extreme, a DAC Mask setting of 0 causes all 8 bits of pixel information to be ignored, so DAC location 0 is looked up for every pixel, and the entire screen displays the color stored in DAC location 0. This makes setting the DAC Mask register to 0 a quick and easy way to blank the screen.

      -

      Reading the DAC

      +

      Reading the DAC

      The DAC can be read directly, via the DAC Read Index register at 3C7H and the DAC Data register at 3C9H, in much the same way as it can be written directly by way of the DAC Write Index register—complete with autoincrementing the DAC Read Index register after every three reads. Everything I’ve said about writing to the DAC applies to reading from the DAC. In fact, reading from the DAC can even cause snow, just as loading the DAC does, so it should ideally be performed during vertical blanking.

      The DAC can also be read by way of the BIOS in either of two ways. INT 10H, function 10H (AH=10H), subfunction 15H (AL=15H) reads out a single DAC location, specified by BX; this function returns the RGB triplet stored in the specified location with the red component in the lower 6 bits of DH, the green component in the lower 6 bits of CH, and the blue component in the lower 6 bits of CL.

      INT 10H, function 10H (AH=10H), subfunction 17H (AL=17H) reads out a block of DAC locations of length CX, starting with the location specified by BX. ES:DX must point to the buffer in which the RGB values from the specified block of DAC locations are to be stored. The form of this buffer (RGB, RGB, RGB ..., with three bytes per RGB triple) is exactly the same as that of the buffer used when calling the BIOS to load a block of registers.

      Listing 34.1 illustrates reading the DAC both through the BIOS block-read function and directly, with the direct-read code capable of conditionally assembling to either guard against interrupts or not and to use REP INSB or not. As you can see, reading the DAC settings is very much symmetric with setting the DAC.

      -

      Cycling Down

      +

      Cycling Down

      And so, at long last, we come to the end of our discussion of color control on the VGA. If it has been more complex than anyone might have imagined, it has also been most rewarding. There’s as much obscure but very real potential in color control as there is anywhere on the VGA, which is to say that there’s a very great deal of potential indeed. Put color cycling or color paging together with the page flipping and image drawing techniques explored elsewhere in this book, and you’ll leave the audience gasping and wondering “How the heck did they do that?”


      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-01.html b/35-01.html index 5a17df3..b1b603e 100644 --- a/35-01.html +++ b/35-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 35
      Bresenham Is Fast, and Fast Is Good -

      -

      Implementing and Optimizing Bresenham’s Line-Drawing Algorithm

      +

      Chapter 35
      Bresenham Is Fast, and Fast Is Good

      +

      Implementing and Optimizing Bresenham’s Line-Drawing Algorithm

      For all the complexity of graphics design and programming, surprisingly few primitive functions lie at the heart of most graphics software. Heavily used primitives include routines that draw dots, circles, area fills, bit block logical transfers, and, of course, lines. For many years, computer graphics were created primarily with specialized line-drawing hardware, so lines are in a way the lingua franca of computer graphics. Lines are used in a wide variety of microcomputer graphics applications today, notably CAD/CAM and computer-aided engineering.

      Probably the best-known formula for drawing lines on a computer display is called Bresenham’s line-drawing algorithm. (We have to be specific here because there is also a less-well-known Bresenham’s circle-drawing algorithm.) In this chapter, I’ll present two implementations for the EGA and VGA of Bresenham’s line-drawing algorithm, which provides decent line quality and excellent drawing speed.

      The first implementation is in rather plain C, with the second in not-so-plain assembly, and they’re both pretty good code. The assembly implementation is damned good code, in fact, but if you want to know whether it’s the fastest Bresenham’s implementation possible, I must tell you that it isn’t. First of all, the code could be sped up a bit by shuffling and combining the various error-term manipulations, but that results in truly cryptic code. I wanted you to be able to relate the original algorithm to the final code, so I skipped those optimizations. Also, write mode 3, which is unique to the VGA, could be used for considerably faster drawing. I’ve described write mode 3 in earlier chapters, and I strongly recommend its use in VGA-only line drawing.

      @@ -47,16 +46,16 @@

      Finally, unrolled loops and/or duplicated code could be used to eliminate most of the branches in the final assembly implementation, and because x86 processors are notoriously slow at branching, that would make quite a difference in overall performance. If you’re interested in unrolled loops and similar assembly techniques, I refer you to the first part of this book.

      That brings us neatly to my final point: Even if I didn’t know that there were further optimizations to be made to my line-drawing implementation, I’d assume that there were. As I’m sure the experienced assembly programmers among you know, there are dozens of ways to tackle any problem in assembly, and someone else always seems to have come up with a trick that never occurred to you. I’ve incorporated a suggestion made by Jim Mackraz in the code in this chapter, and I’d be most interested in hearing of any other tricks or tips you may have.

      Notwithstanding, the line-drawing implementation in Listing 35.3 is plenty fast enough for most purposes, so let’s get the discussion underway.

      -

      The Task at Hand

      +

      The Task at Hand

      There are two important characteristics of any line-drawing function. First, it must draw a reasonable approximation of a line. A computer screen has limited resolution, and so a line-drawing function must actually approximate a straight line by drawing a series of pixels in what amounts to a jagged pattern that generally proceeds in the desired direction. That pattern of pixels must reliably suggest to the human eye the true line it represents. Second, to be usable, a line-drawing function must be fast. Minicomputers and mainframes generally have hardware that performs line drawing, but most microcomputers offer no such assistance. True, nowadays graphics accelerators such as the S3 and ATI chips have line drawing hardware, but some other accelerators don’t; when drawing lines on the latter sort of chip, when drawing on the CGA, EGA, and VGA, and when drawing sorts of lines not supported by line-drawing hardware as well, the PC’s CPU must draw lines on its own, and, as many users of graphics-oriented software know, that can be a slow process indeed.

      Line drawing quality and speed derive from two factors: The algorithm used to draw the line and the implementation of that algorithm. The first implementation (written in Borland C++) that I’ll be presenting in this chapter illustrates the workings of the algorithm and draws lines at a good rate. The second implementation, written in assembly language and callable directly from Borland C++, draws lines at extremely high speed, on the order of three to six times faster than the C version. Between them, the two implementations illuminate Bresenham’s line-drawing algorithm and provide high-performance line-drawing capability.

      The difficulty in drawing a line lies in generating a set of pixels that, taken together, are a reasonable facsimile of a true line. Only horizontal, vertical, and 1:1 diagonal lines can be drawn precisely along the true line being represented; all other lines must be approximated from the array of pixels that a given video mode supports, as shown in Figure 35.1.

      Considerable thought has gone into the design of line-drawing algorithms, and a number of techniques for drawing high-quality lines have been developed. Unfortunately, most of these techniques were developed for powerful, expensive graphics workstations and require very high resolution, a large color palette, and/or floating-point hardware. These techniques tend to perform poorly and produce less visually impressive results on all but the best-endowed PCs.

      Bresenham’s line-drawing algorithm, on the other hand, is uniquely suited to microcomputer implementation in that it requires no floating-point operations, no divides, and no multiplies inside the line-drawing loop. Moreover, it can be implemented with surprisingly little code.

      -

      Bresenham’s Line-Drawing Algorithm

      +

      Bresenham’s Line-Drawing Algorithm

      The key to grasping Bresenham’s algorithm is to understand that when drawing an approximation of a line on a finite-resolution display, each pixel drawn will lie either exactly on the true line or to one side or the other of the true line. The amount by which the pixel actually drawn deviates from the true line is the error of the line drawing at that point. As the drawing of the line progresses from one pixel to the next, the error can be used to tell when, given the resolution of the display, a more accurate approximation of the line can be drawn by placing a given pixel one unit of screen resolution away from its predecessor in either the horizontal or the vertical direction, or both.


      Figure 35.1
        Approximating a true line from a pixel array. +
      -->Figure 35.1  Approximating a true line from a pixel array.


      @@ -70,7 +69,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-02.html b/35-02.html index 0be02fe..664c2a5 100644 --- a/35-02.html +++ b/35-02.html @@ -24,7 +24,7 @@ - +
      @@ -42,7 +42,7 @@

      In Figure 35.2, the endpoints of the line fall exactly on displayed pixels. However, no other part of the line squarely intersects the center of a pixel, meaning that all other pixels will have to be plotted as approximations of the line. The approach to approximation that Bresenham’s algorithm takes is to move exactly 1 pixel along the major dimension of the line each time a new pixel is drawn, while moving 1 pixel along the minor dimension each time the line moves more than halfway between pixels along the minor dimension.

      In Figure 35.2, the X dimension is the major dimension. This means that 6 dots, one at each of X coordinates 0, 1, 2, 3, 4, and 5, will be drawn. The trick, then, is to decide on the correct Y coordinates to accompany those X coordinates.


      Figure 35.2
        Drawing between two pixel endpoints. +
      -->Figure 35.2  Drawing between two pixel endpoints.

      It’s easy enough to select the Y coordinates by eye in Figure 35.2. The appropriate Y coordinates are 0, 0, 1, 1, 2, 2, based on the Y coordinate closest to the line for each X coordinate. Bresenham’s algorithm makes the same selections, based on the same criterion. The manner in which it does this is by keeping a running record of the error of the line—that is, how far from the true line the current Y coordinate is—at each X coordinate, as shown in Figure 35.3. When the running error of the line indicates that the current Y coordinate deviates from the true line to the extent that the adjacent Y coordinate would be closer to the line, then the current Y coordinate is changed to that adjacent Y coordinate.

      @@ -50,7 +50,7 @@

      Since X is the major dimension, the next pixel has an X coordinate of 1. The Y coordinate of this pixel will be whichever of 0 (the last Y coordinate) or 1 (the adjacent Y coordinate in the direction of the end point of the line) the true line at this X coordinate is closer to. The running error at this point is B minus A, as shown in Figure 35.3. This amount is less than 1/2 (that is, less than halfway to the next Y coordinate), so the Y coordinate does not change at X equal to 1. Consequently, the second pixel is drawn at (1,0).

      The third pixel has an X coordinate of 2. The running error at this point is C minus A, which is greater than 1/2 and therefore closer to the next than to the current Y coordinate. The third pixel is drawn at (2,1), and 1 is subtracted from the running error to compensate for the adjustment of one pixel in the current Y coordinate. The running error of the pixel actually drawn at this point is C minus D.


      Figure 35.3
        The error term in Bresenham’s algorithm. +
      -->Figure 35.3  The error term in Bresenham’s algorithm.

      The fourth pixel has an X coordinate of 3. The running error at this point is E minus D; since this is less than 1/2, the current Y coordinate doesn’t change. The fourth pixel is drawn at (3,1).

      @@ -58,7 +58,7 @@

      Finally, the sixth pixel is the end point of the line. This pixel has an X coordinate of 5. The running error at this point is G minus G, or 0, indicating that this point is squarely on the true line, as of course it should be given that it’s the end point, so the current Y coordinate remains the same. The end point of the line is drawn at (5,2), and the line is complete.

      That’s really all there is to Bresenham’s algorithm. The algorithm is a process of drawing a pixel at each possible coordinate along the major dimension of the line, each with the closest possible coordinate along the minor dimension. The running error is used to keep track of when the coordinate along the minor dimension must change in order to remain as close as possible to the true line. The above description of the case where X is the major dimension, Y is the minor dimension, and both dimensions are greater than zero is readily generalized to all eight octants in which lines could be drawn, as we will see in the C implementation.

      The above discussion summarizes the nature rather than the exact mechanism of Bresenham’s line-drawing algorithm. I’ll provide a brief seat-of-the-pants discussion of the algorithm in action when we get to the C implementation of the algorithm; for a full mathematical treatment, I refer you to pages 433-436 of Foley and Van Dam’s Fundamentals of Interactive Computer Graphics (Addison-Wesley, 1982), or pages 72-78 of the second edition of that book, which was published under the name Computer Graphics: Principles and Practice (Addison-Wesley, 1990). These sources provide the derivation of the integer-only, divide-free version of the algorithm, as well as Pascal code for drawing lines in one of the eight possible octants.

      -

      Strengths and Weaknesses

      +

      Strengths and Weaknesses

      The overwhelming strength of Bresenham’s line-drawing algorithm is speed. With no divides, no floating-point operations, and no need for variables that won’t fit in 16 bits, it is perfectly suited for PCs.

      The weakness of Bresenham’s algorithm is that it produces relatively low-quality lines by comparison with most other line-drawing algorithms. In particular, lines generated with Bresenham’s algorithm can tend to look a little jagged. On the PC, however, jagged lines are an inevitable consequence of relatively low resolution and a small color set, so lines drawn with Bresenham’s algorithm don’t look all that much different from lines drawn in other ways. Besides, in most applications, users are far more interested in the overall picture than in the primitive elements from which that picture is built. As a general rule, any collection of pixels that trend from point A to point B in a straight fashion is accepted by the eye as a line. Bresenham’s algorithm is successfully used by many current PC programs, and by the standard of this wide acceptance the algorithm is certainly good enough.

      @@ -75,7 +75,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-03.html b/35-03.html index cd95666..74b6742 100644 --- a/35-03.html +++ b/35-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      An Implementation in C

      +

      An Implementation in C

      It’s time to get down and look at some actual working code. Listing 35.1 is a C implementation of Bresenham’s line-drawing algorithm for modes 0EH, 0FH, 10H, and 12H of the VGA, called as function EVGALine. Listing 35.2 is a sample program to demonstrate the use of EVGALine.

      LISTING 35.1 L35-1.C

      @@ -246,7 +246,7 @@ char Color; /* color to draw line in */
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-04.html b/35-04.html index 2a1d34f..d176434 100644 --- a/35-04.html +++ b/35-04.html @@ -24,7 +24,7 @@ - +
      @@ -124,7 +124,7 @@ void main() } -

      Looking at EVGALine

      +

      Looking at EVGALine

      The EVGALine function itself performs four operations. EVGALine first sets up the VGA’s hardware so that all pixels drawn will be in the desired color. This is accomplished by setting two of the VGA’s registers, the Enable Set/Reset register and the Set/Reset register. Setting the Enable Set/Reset to the value 0FH, as is done in EVGALine, causes all drawing to produce pixels in the color contained in the Set/Reset register. Setting the Set/Reset register to the passed color, in conjunction with the Enable Set/Reset setting of 0FH, causes all drawing done by EVGALine and the functions it calls to generate the passed color. In summary, setting up the Enable Set/Reset and Set/Reset registers in this way causes the remainder of EVGALine to draw a line in the specified color.

      EVGALine next performs a simple check to cut in half the number of line orientations that must be handled separately. Figure 35.4 shows the eight possible line orientations among which a Bresenham’s algorithm implementation must distinguish. (In interpreting Figure 35.4, assume that lines radiate outward from the center of the figure, falling into one of eight octants delineated by the horizontal and vertical axes and the two diagonals.) The need to categorize lines into these octants falls out of the major/minor axis nature of the algorithm; the orientations are distinguished by which coordinate forms the major axis and by whether each of X and Y increases or decreases from the line start to the line end.

      A moment of thought will show, however, that four of the line orientations are redundant. Each of the four orientations for which DeltaY, the Y component of the line, is less than 0 (that is, for which the line start Y coordinate is greater than the line end Y coordinate) can be transformed into one of the four orientations for which the line start Y coordinate is less than the line end Y coordinate simply by reversing the line start and end coordinates, so that the line is drawn in the other direction. EVGALine does this by swapping (X0,Y0) (the line start coordinates) with (X1,Y1) (the line end coordinates) whenever Y0 is greater than Y1. @@ -132,7 +132,7 @@ void main()

      This accomplished, EVGALine must still distinguish among the four remaining line orientations. Those four orientations form two major categories, orientations for which the X dimension is the major axis of the line and orientations for which the Y dimension is the major axis. As shown in Figure 35.4, octants 1 (where X increases from start to finish) and 2 (where X decreases from start to finish) fall into the latter category, and differ in only one respect, the direction in which the X coordinate moves when it changes. Handling of the running error of the line is exactly the same for both cases, as one would expect given the symmetry of lines differing only in the sign of DeltaX, the X coordinate of the line. Consequently, for those cases where DeltaX is less than zero, the direction of X movement is made negative, and the absolute value of DeltaX is used for error term calculations.

      Similarly, octants 0 (where X increases from start to finish) and 3 (where X decreases from start to finish) differ only in the direction in which the X coordinate moves when it changes. The difference between line drawing in octants 0 and 3 and line drawing in octants 1 and 2 is that in octants 0 and 3, since X is the major axis, the X coordinate changes on every pixel of the line and the Y coordinate changes only when the running error of the line dictates. In octants 1 and 2, the Y coordinate changes on every pixel and the X coordinate changes only when the running error dictates, since Y is the major axis.


      Figure 35.4
        Bresenham’s eight possible line orientations. +
      -->Figure 35.4  Bresenham’s eight possible line orientations.


      @@ -146,7 +146,7 @@ void main()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-05.html b/35-05.html index 040986a..730b803 100644 --- a/35-05.html +++ b/35-05.html @@ -24,7 +24,7 @@ - +
      @@ -41,13 +41,13 @@

      EVGALine determines which line-drawing function to call and with what value for the direction of change of the X coordinate based on two criteria: whether DeltaX is negative or not, and whether the absolute value of DeltaX (|DeltaX|) is less than DeltaY or not, as shown in Figure 35.5. Recall that the value of DeltaY, and hence the direction of change of the Y coordinate, is guaranteed to be non-negative as a result of the earlier elimination of four of the line orientations.

      After calling the appropriate function to draw the line (more on those functions shortly), EVGALine restores the state of the Enable Set/Reset register to its default of zero. In this state, the Set/Reset register has no effect, so it is not necessary to restore the state of the Set/Reset register as well. EVGALine also restores the state of the Bit Mask register (which, as we will see, is modified by EVGADot, the pixel-drawing routine actually used to draw each pixel of the lines produced by EVGALine) to its default of 0FFH. While it would be more modular to have EVGADot restore the state of the Bit Mask register after drawing each pixel, it would also be considerably slower to do so. The same could be said of having EVGADot set the Enable Set/Reset and Set/Reset registers for each pixel: While modularity would improve, speed would suffer markedly.


      Figure 35.5
        EVGALine’s decision logic. +
      -->Figure 35.5  EVGALine’s decision logic.

      -

      Drawing Each Line

      +

      Drawing Each Line

      The Octant0 and Octant1 functions draw lines for which |DeltaX| is greater than DeltaY and lines for which |DeltaX| is less than or equal to DeltaY, respectively. The parameters to Octant0 and Octant1 are the starting point of the line, the length of the line in each dimension, and XDirection, the amount by which the X coordinate should be changed when it moves. XDirection must be either 1 (to draw toward the right edge of the screen) or -1 (to draw toward the left edge of the screen). No value is required for the amount by which the Y coordinate should be changed; since DeltaY is guaranteed to be positive, the Y coordinate always changes by 1 pixel.

      Octant0 draws lines for which |DeltaX| is greater than DeltaY. For such lines, the X coordinate of each pixel drawn differs from the previous pixel by either 1 or -1, depending on the value of XDirection. (This makes it possible for Octant0 to draw lines in both octant 0 and octant 3.) Whenever ErrorTerm becomes non-negative, indicating that the next Y coordinate is a better approximation of the line being drawn, the Y coordinate is increased by 1.

      Octant1 draws lines for which |DeltaX| is less than or equal to DeltaY. For these lines, the Y coordinate of each pixel drawn is 1 greater than the Y coordinate of the previous pixel. Whenever ErrorTerm becomes non-negative, indicating that the next X coordinate is a better approximation of the line being drawn, the X coordinate is advanced by either 1 or -1, depending on the value of XDirection. (This makes it possible for Octant1 to draw lines in both octant 1 and octant 2.)

      -

      Drawing Each Pixel

      +

      Drawing Each Pixel

      At the core of Octant0 and Octant1 is a pixel-drawing function, EVGADot. EVGADot draws a pixel at the specified coordinates in whatever color the hardware of the VGA happens to be set up for. As described earlier, since the entire line drawn by EVGALine is of the same color, line-drawing performance is improved by setting the VGA’s hardware up once in EVGALine before the line is drawn, and then drawing all the pixels in the line in the same color via EVGADot.

      EVGADot makes certain assumptions about the screen. First, it assumes that the address of the byte controlling the pixels at the start of a given row on the screen is 80 bytes after the start of the row immediately above it. In other words, this implementation of EVGADot only works for screens configured to be 80 bytes wide. Since this is the standard configuration of all of the modes EVGALine is designed to work in, the assumption of 80 bytes per row should be no problem. If it is a problem, however, EVGADot could easily be modified to retrieve the BIOS integer variable at address 0040:004A, which contains the number of bytes per row for the current video mode.

      Second, EVGADot assumes that screen memory is organized as a linear bitmap starting at address A000:0000, with the pixel at the upper left of the screen controlled by bit 7 of the byte at offset 0, the next pixel to the right controlled by bit 6, the ninth pixel controlled by bit 7 of the byte at offset 1, and so on. Further, it assumes that the graphics adapter’s hardware is configured such that setting the Bit Mask register to allow modification of only the bit controlling the pixel of interest and then ORing a value of 0FEH with display memory will draw that pixel correctly without affecting any other dots. (Note that 0FEH is used rather than 0FFH or 0 because some optimizing compilers turn ORs with the latter values into simpler operations or optimize them away entirely. As explained later, however, it’s not the value that’s ORed that matters, given the way we’ve set up the VGA’s hardware; it’s the act of ORing itself, and the value 0FEH forces the compiler to perform the OR operation.) Again, this is the normal way in which modes 0EH, 0FH, 10H, and 12H operate. As described earlier, EVGADot also assumes that the VGA is set up so that each pixel drawn in the above-mentioned manner will be drawn in the correct color.

      @@ -65,7 +65,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-06.html b/35-06.html index 683eac9..901d051 100644 --- a/35-06.html +++ b/35-06.html @@ -24,7 +24,7 @@ - +
      @@ -38,12 +38,12 @@


      The result of all this is simply a single pixel drawn in the color set up in EVGALine. EVGADot may seem excessively complex for a function that does nothing more that draw one pixel, but programming the VGA isn’t trivial (as we’ve seen in the early chapters of this part). Besides, while the explanation of EVGADot is lengthy, the code itself is only five lines long.

      Line drawing would be somewhat faster if the code of EVGADot were made an inline part of Octant0 and Octant1, thereby saving the overhead of preparing parameters and calling the function. Feel free to do this if you wish; I maintained EVGADot as a separate function for clarity and for ease of inserting a pixel-drawing function for a different graphics adapter, should that be desired. If you do install a pixel-drawing function for a different adapter, or a fundamentally different mode such as a 256-color SuperVGA mode, remember to remove the hardware-dependent outportb lines in EVGALine itself.

      -

      Comments on the C Implementation

      +

      Comments on the C Implementation

      EVGALine does no error checking whatsoever. My assumption in writing EVGALine was that it would be ultimately used as the lowest-level primitive of a graphics software package, with operations such as error checking and clipping performed at a higher level. Similarly, EVGALine is tied to the VGA’s screen coordinate system of (0,0) to (639,199) (in mode 0EH), (0,0) to (639,349) (in modes 0FH and 10H), or (0,0) to (639,479) (in mode 12H), with the upper left corner considered to be (0,0). Again, transformation from any coordinate system to the coordinate system used by EVGALine can be performed at a higher level. EVGALine is specifically designed to do one thing: draw lines into the display memory of the VGA. Additional functionality can be supplied by the code that calls EVGALine.

      The version of EVGALine shown in Listing 35.1 is reasonably fast, but it is not as fast as it might be. Inclusion of EVGADot directly into Octant0 and Octant1, and, indeed, inclusion of Octant0 and Octant1 directly into EVGALine would speed execution by saving the overhead of calling and parameter passing. Handpicked register variables might speed performance as well, as would the use of word OUTs rather than byte OUTs. A more significant performance increase would come from eliminating separate calculation of the address and mask for each pixel. Since the location of each pixel relative to the previous pixel is known, the address and mask could simply be adjusted from one pixel to the next, rather than recalculated from scratch.

      These enhancements are not incorporated into the code in Listing 35.1 for a couple of reasons. One reason is that it’s important that the workings of the algorithm be clearly visible in the code, for learning purposes. Once the implementation is understood, rewriting it for improved performance would certainly be a worthwhile exercise. Another reason is that when flat-out speed is needed, assembly language is the best way to go. Why produce hard-to-understand C code to boost speed a bit when assembly-language code can perform the same task at two or more times the speed?

      Given which, a high-speed assembly language version of EVGALine would seem to be a logical next step.

      -

      Bresenham’s Algorithm in Assembly

      +

      Bresenham’s Algorithm in Assembly

      Listing 35.3 is a high-performance implementation of Bresenham’s algorithm, written entirely in assembly language. The code is callable from C just as is Listing 35.1, with the same name, EVGALine, and with the same parameters. Either of the two can be linked to any program that calls EVGALine, since they appear to be identical to the calling program. The only difference between the two versions is that the sample program in Listing 35.2 runs over three times as fast on a 486 with an ISA-bus VGA when calling the assembly-language version of EVGALine as when calling the C version, and the difference would be considerably greater yet on a local bus, or with the use of write mode 3. Link each version with Listing 35.2 and compare performance—the difference is startling.


      @@ -57,7 +57,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/35-07.html b/35-07.html index eb380df..27b1133 100644 --- a/35-07.html +++ b/35-07.html @@ -24,7 +24,7 @@ - +
      @@ -425,7 +425,7 @@ _EVGALine endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/36-01.html b/36-01.html index c9dbe1c..bb8e223 100644 --- a/36-01.html +++ b/36-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 36
      The Good, the Bad, and the Run-Sliced -

      -

      Faster Bresenham Lines with Run-Length Slice Line Drawing

      +

      Chapter 36
      The Good, the Bad, and the Run-Sliced

      +

      Faster Bresenham Lines with Run-Length Slice Line Drawing

      Years ago, I worked at a company that asked me to write blazingly fast line-drawing code for an AutoCAD driver. I implemented the basic Bresenham’s line-drawing algorithm; streamlined it as much as possible; special-cased horizontal, diagonal, and vertical lines; broke out separate, optimized routines for lines in each octant; and massively unrolled the loops. When I was done, I had line drawing down to a mere five or six instructions per pixel, and I handed the code over to the AutoCAD driver person, content in the knowledge that I had pushed the theoretical limits of the Bresenham’s algorithm on the 80x86 architecture, and that this was as fast as line drawing could get on a PC. That feeling lasted for about a week, until Dave Miller, who these days is a Windows display-driver whiz at Engenious Solutions, casually mentioned Bresenham’s faster run-length slice line-drawing algorithm.

      Remember Bill Murray’s safety tip in Ghostbusters? It goes something like this. Harold Ramis tells the Ghostbusters not to cross the beams of the antighost guns. “Why?” Murray asks.

      @@ -88,12 +87,12 @@ else

      Think of it this way: A program is a state machine. It takes a set of inputs and produces a corresponding set of outputs by passing through a set of states. Your primary job as a programmer is to implement the desired state machine. Your additional job as a performance programmer is to minimize the lengths of the paths through the state machine. This means performing as many tests and calculations as possible outside the loops, so that the loops themselves can do as little work—that is, pass through as few states—as possible.

      Which brings us full circle to Bresenham’s run-length slice line-drawing algorithm, which just happens to be an excellent example of a minimized state machine. In case you’re fuzzy on the good/bad performance thing, that’s “good”—as in fast.

      -

      Run-Length Slice Fundamentals

      +

      Run-Length Slice Fundamentals

      First off, I have a confession to make: I’m not sure that the algorithm I’ll discuss is actually, precisely Bresenham’s run-length slice algorithm. It’s been a long time since I read about this algorithm; in the intervening years, I’ve misplaced Bresenham’s article, and have been unable to unearth it. As a result, I had to derive the algorithm from scratch, which was admittedly more fun than reading about it, and also ensured that I understood it inside and out. The upshot is that what I discuss may or may not be Bresenham’s run-length slice algorithm—but it surely is fast.

      The place to begin understanding the run-length slice algorithm is the standard Bresenham’s line-drawing algorithm. (I discussed the standard Bresenham’s line-drawing algorithm at length in the previous chapter.) The basis of the standard approach is stepping one pixel at a time along the major axis (the longer dimension of the line), while maintaining an integer error term that indicates at each major-axis step how close the line is to advancing halfway to the next pixel along the minor axis. Figure 36.1 illustrates standard Bresenham’s line drawing. The key point here is that a calculation and a test are performed once for each step along the major axis.


      Figure 36.1
        Standard Bresenham’s line drawing. +
      -->Figure 36.1  Standard Bresenham’s line drawing.


      @@ -107,7 +106,7 @@ else
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/36-02.html b/36-02.html index fe7a829..c2f2c95 100644 --- a/36-02.html +++ b/36-02.html @@ -24,7 +24,7 @@ - +
      @@ -42,17 +42,17 @@

      Consider this: When you’re called upon to draw a line with an X-dimension of 35 and a Y-dimension of 10, you have a great deal of information available, some of which is ignored by standard Bresenham’s. In particular, because the slope is between 1/3 and 1/4, you know that every single run—a run being a set of pixels at the same minor-axis coordinate—must be either three or four pixels long. No other length is possible, as shown in Figure 36.3 (apart from the first and last runs, which are special cases that I’ll discuss shortly). Therefore, for this line, there’s no need to perform an error-term calculation and test for each pixel. Instead, we can just perform one test per run, to see whether the run is three or four pixels long, thereby eliminating about 70 percent of the calculations in drawing this line.

      Take a moment to let the idea behind run-length slice drawing soak in. Periodic decisions must be made to control pixel placement. The key to speed is to make those decisions as infrequently and as quickly as possible. Of course, it will work to make a decision at each pixel—that’s standard Bresenham’s. However, most of those per-pixel decisions are redundant, and in fact we have enough information before we begin drawing to know which are the redundant decisions. Run-length slice drawing is exactly equivalent to standard Bresenham’s, but it pares the decision-making process down to a minimum. It’s somewhat analogous to the difference between finding the greatest common divisor of two numbers using Euclid’s algorithm and finding it by trying every possible divisor. Both approaches produce the desired result, but that which takes maximum advantage of the available information and minimizes redundant work is preferable.


      Figure 36.2
        Run-length slice line drawing. +
      -->Figure 36.2  Run-length slice line drawing.


      Figure 36.3
        Runs in a slope 1/3.5 line. +
      -->Figure 36.3  Runs in a slope 1/3.5 line.

      -

      Run-Length Slice Implementation

      +

      Run-Length Slice Implementation

      We know that for any line, a given run will always be one of two possible lengths. How, though, do we know which length to select? Surprisingly, this is easy to determine. For the following discussion, assume that we have a slope of 1/3.5, so that X is the major axis; however, the discussion also applies to Y-major lines, with X and Y reversed.

      The minimum possible length for any run in an X-major line is int(XDelta/YDelta), where XDelta is the X-dimension of the line and YDelta is the Y-dimension. The maximum possible length is int(XDelta/YDelta)+ 1. The trick, then, is knowing which of these two lengths to select for each run. To see how we can make this selection, refer to Figure 36.4. For each one-pixel step along the minor axis (Y, in this case), we advance at least three pixels. The full advance distance along X (the major axis) is actually three-plus pixels, because there is also a fractional portion to the advance along X for a single-pixel Y step. This fractional advance is the key to deciding when to add an extra pixel to a run. The fraction indicates what portion of an extra pixel we advance along X (the major axis) during each run. If we keep a running sum of the fractional parts, we have a measure of how close we are to needing an extra pixel; when the fractional sum reaches 1, it’s time to add an extra pixel to the current run. Then, we can subtract 1 from the running sum (because we just advanced one pixel), and continue on.


      Figure 36.4
        How the error term determines run length. +
      -->Figure 36.4  How the error term determines run length.

      Practically speaking, however, we can’t work with fractions because floating-point arithmetic is slow and fixed-point arithmetic is imprecise. Therefore, we take a cue from standard Bresenham’s and scale all the error-term calculations up so that we can work with integers. The fractional X (major axis) advance per one-pixel Y (minor axis) advance is the fractional portion of XDelta/YDelta. This value is exactly equivalent to (XDelta % YDelta)/YDelta. We’ll scale this up by multiplying it by YDelta*2, so that the amount by which we adjust the error term up for each one-pixel minor-axis advance is (XDelta % YDelta)*2.

      We’ll similarly scale up the one pixel by which we adjust the error term down after it turns over, so our downward error-term adjustment is YDelta*2. Therefore, before drawing each run, we’ll add (XDelta % YDelta)*2 to the error term. If the error term runs over (reaches one full pixel), we’ll lengthen the run by 1, and subtract YDelta*2 from the error term. (All values are multiplied by 2 so that the initial error term, which involves a 0.5 term, can be scaled up to an integer, as discussed next.)

      @@ -70,7 +70,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/36-03.html b/36-03.html index 9b44d45..b2d14a1 100644 --- a/36-03.html +++ b/36-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Run-Length Slice Details

      +

      Run-Length Slice Details

      A couple of run-length slice implementation details yet remain. First is the matter of how error-term turnover is detected. This is done in much the same way as it is with standard Bresenham’s: The error term is maintained as a negative valve and advances for each step; when the error term reaches 0, it’s time to add an extra pixel to the current run. This means that we only have to test for carry after advancing the error term to determine whether or not to add an extra pixel to each run. (Actually, the code in this chapter tests for the error term being greater than zero, but the assembly code in the next chapter will use the very efficient carry approach.)

      The second and more difficult detail is balancing the runs so that they’re centered around the ideal line, and therefore draw the same pixels that standard Bresenham’s would draw. If we just drew full-length runs from the start, we’d end up with an unbalanced line, as shown in Figure 36.5. Instead, we have to split the initial pixel plus one full run as evenly as possible between the first and last runs of the line, and adjust the initial error term appropriately for the initial half-run.

      @@ -44,7 +44,7 @@

      The other trick here is that if an odd number of pixels are allocated between the first and last partial runs, we’ll end up with an odd pixel, since we are unable to draw a half-pixel. This odd pixel is accounted for by adding half a pixel to the error term.

      That’s all there is to run-length slice line drawing; the partial first and last runs are the only tricky part. Listing 36.1 is a run-length slice implementation in C. This is not an optimized implementation, nor is it meant to be; this listing is provided so that you can see how the run-length slice algorithm works. In the next chapter, I’ll move on to an optimized version, but for now, Listing 36.1 will make it much easier to grasp the principles of run-length slice drawing, and to understand the optimized code I’ll present in the next chapter.


      Figure 36.5
        Balancing run-length slice lines: a) unbalanced; b) balanced. +
      -->Figure 36.5  Balancing run-length slice lines: a) unbalanced; b) balanced.

      LISTING 36.1 L36-1.C

      @@ -302,7 +302,7 @@ void DrawVerticalRun(char far **ScreenPtr, int XAdvance,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/36-04.html b/36-04.html index def54fb..d155a33 100644 --- a/36-04.html +++ b/36-04.html @@ -24,7 +24,7 @@ - +
      @@ -129,7 +129,7 @@ int main()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/37-01.html b/37-01.html index 900b774..1df7cff 100644 --- a/37-01.html +++ b/37-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 37
      Dead Cats and Lightning Lines -

      -

      Optimizing Run-Length Slice Line Drawing in a Major Way

      +

      Chapter 37
      Dead Cats and Lightning Lines

      +

      Optimizing Run-Length Slice Line Drawing in a Major Way

      As I write this, the wife, the kid, and I are in the throes of yet another lightning-quick transcontinental move, this time to Redmond, Washington, to work for You Know Who. Moving is never fun, but what makes it worse for us is the pets. Getting them into kennels and to the airport is hard; there’s always the possibility that they might not be allowed to fly because of the weather; and, worst of all, they might not make it. Animals don’t usually end up injured or dead, but it does happen.

      In a (not notably successful) effort to cheer me up about the prospect of shipping my animals, a friend told me the following story, which he swears actually happened to a friend of his. I don’t know—to me, it has the ring of an urban legend, which is to say it makes a good story, but you can never track down the person it really happened to; it’s always a friend of a friend. But maybe it is true, and anyway, it’s a good story.

      @@ -46,7 +45,7 @@

      FOF knew how upset the owner would be, and came up with a plan to make everything better. At home, he had a cat of the same size, shape, and markings. He would substitute that cat, and since all cats treat all humans with equal disdain, the owner would never know the difference, and would never suffer the trauma of the loss of her cat. So FOF drove home, got his cat, put it in the kennel, and waited for the owner to show up—at which point, she took one look at the kennel and said, “This isn’t my cat. My cat is dead.”

      As it turned out, she had shipped her recently deceased feline home to be buried. History does not record how our FOF dug himself out of this one.

      Okay, but what’s the point? The point is, if it isn’t broken, don’t fix it. And if it is broken, maybe that’s all right, too. Which brings us, neat as a pin, to the topic of drawing lines in a serious hurry.

      -

      Fast Run-Length Slice Line Drawing

      +

      Fast Run-Length Slice Line Drawing

      In the last chapter, we examined the principles of run-length slice line drawing, which draws lines a run at a time rather than a pixel at a time, a run being a series of pixels along the major (longer) axis. It’s time to turn theory into useful practice by developing a fast assembly version. Listing 37.1 is the assembly version, in a form that’s plug-compatible with the C code from the previous chapter.

      LISTING 37.1 L37-1.ASM

      @@ -415,7 +414,7 @@ _LineDraw endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/37-02.html b/37-02.html index 0c140c2..d0ea1e1 100644 --- a/37-02.html +++ b/37-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      How Fast Is Fast?

      +

      How Fast Is Fast?

      Your first question is likely to be the following: Just how fast is Listing 37.1? Is it optimized to the hilt or just pretty fast? The quick answer is: It’s fast. Listing 37.1 draws lines at a rate of nearly 1 million pixels per second on my 486/33, and is capable of still faster drawing, as I’ll discuss shortly. (The heavily optimized AutoCAD line-drawing code that I mentioned in the last chapter drew 150,000 pixels per second on an EGA in a 386/16, and I thought I had died and gone to Heaven. Such is progress.) The full answer is a more complicated one, and ties in to the principle that if it is broken, maybe that’s okay—and to the principle of looking before you leap, also known as profiling before you optimize.

      When I went to speed up run-length slice lines, I initially manually converted the last chapter’s C code into assembly. Then I streamlined the register usage and used REP STOS wherever possible. Listing 37.1 is that code. At that point, line drawing was surely faster, although I didn’t know exactly how much faster. Equally surely, there were significant optimizations yet to be made, and I was itching to get on to them, for they were bound to be a lot more interesting than a basic C-to-assembly port.

      Ego intervened at this point, however. I wanted to know how much of a speed-up I had already gotten, so I timed the performance of the C code and compared it to the assembly code. To my horror, I found that I had not gotten even a two-times improvement! I couldn’t understand how that could be—the C code was decidedly unoptimized—until I hit on the idea of measuring the maximum memory speed of the VGA to which I was drawing.

      @@ -46,7 +46,7 @@

      Now it’s true that faster line-drawing code would likely be more beneficial on faster VGAs, especially local-bus VGAs, and in slower systems. For that reason, I’ll list a variety of potential optimizations to Listing 37.1. On the other hand, it’s also true that Listing 37.1 is capable of drawing lines at a rate of 2.2 million pixels per second on a 486/ 33, given fast enough VGA memory, so it should be able to drive almost any non-local-bus VGA at nearly full speed. In short, Listing 37.1 is very fast, and, in many systems, further optimization is basically a waste of time.

      Profile before you optimize.

      -

      Further Optimizations

      +

      Further Optimizations

      Following is a quick tour of some of the many possible further optimizations to Listing 37.1.

      The run-handling loops could be unrolled more than the current two times. However, bear in mind that a two-times unrolling gets more than half the maximum unrolling benefit with less overhead than a more heavily unrolled loop.

      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/38-01.html b/38-01.html index 834290d..3019574 100644 --- a/38-01.html +++ b/38-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,31 +36,30 @@


      -

      Chapter 38
      The Polygon Primeval -

      -

      Drawing Polygons Efficiently and Quickly

      +

      Chapter 38
      The Polygon Primeval

      +

      Drawing Polygons Efficiently and Quickly

      “Give me but one firm spot on which to stand, and I will move the Earth.”

      —Archimedes

      Were Archimedes alive today, he might say, “Give me but one fast polygon-fill routine on which to call, and I will draw the Earth.” Programmers often think of pixel drawing as being the basic graphics primitive, but filled polygons are equally fundamental and far more useful. Filled polygons can be used for constructs as diverse as a single pixel or a 3-D surface, and virtually everything in between.

      I’ll spend some time in this chapter and the next several developing routines to draw filled polygons and building more sophisticated graphics operations atop those routines. Once we have that foundation, I’ll get into 2-D manipulation and animation of polygon-based entities as preface to an exploration of 3-D graphics. You can’t get there from here without laying some groundwork, though, so in this chapter I’ll begin with the basics of filling a polygon. In the next chapter, we’ll see how to draw a polygon considerably faster. That’s my general approach for this sort of topic: High-level exploration of a graphics topic first, followed by a speedy hardware-specific implementation for the IBM PC/VGA combination, the most widely used graphics system around. Abstract, machine-independent graphics is a thing of beauty, but only by understanding graphics at all levels, including the hardware, can you boost performance into the realm of the sublime.

      And slow computer graphics is scarcely worth the bother.

      -

      Filled Polygons

      +

      Filled Polygons

      A polygon is simply a shape formed by lines laid end to end to form a continuous, closed path. A polygon is filled by setting all pixels within the polygon’s boundaries to a color or pattern. For now, we’ll work only with polygons filled with solid colors.

      You can divide polygons into three categories: convex, nonconvex, and complex, as shown in Figure 38.1. Convex polygons include what you’d normally think of as “convex” and more; as far as we’re concerned, a convex polygon is one for which any horizontal line drawn through the polygon encounters the right edge exactly once and the left edge exactly once, excluding horizontal and zero-length edge segments. Put another way, neither the right nor left edge of a convex polygon ever reverses direction from up to down, or vice-versa. Also, the right and left edges of a convex polygon may not cross one another, although they may touch so long as the right edge never crosses over to the left side of the left edge. (Check out the second polygon drawn in Listing 38.3, which certainly isn’t convex in the normal sense.) The boundaries of nonconvex polygons, on the other hand, can go in whatever directions they please, so long as they never cross. Complex polygons can have any boundaries you might imagine, which makes for interesting problems in deciding which interior spaces to fill and which not to fill. Each category is a superset of the previous one.

      (See Chapter 41 for a more detailed discussion of polygon types and naming.)

      Why bother to distinguish between convex, nonconvex, and complex polygons? Easy: performance, especially when it comes to filling convex polygons. We’re going to start with filled convex polygons; they’re widely useful and will serve well to introduce some of the subtler complexities of polygon drawing, not the least of which is the slippery concept of “inside.”

      -

      Which Side Is Inside?

      +

      Which Side Is Inside?

      The basic principle of polygon filling is decomposing each polygon into a series of horizontal lines, one for each horizontal row of pixels, or scan line, within the polygon (a process I’ll call scan conversion), and drawing the horizontal lines. I’ll refer to the entire process as rasterization. Rasterization of convex polygons is easily done by starting at the top of the polygon and tracing down the left and right sides, one scan line (one vertical pixel) at a time, filling the extent between the two edges on each scan line, until the bottom of the polygon is reached. At first glance, rasterization does not seem to be particularly complicated, although it should be apparent that this simple approach is inadequate for nonconvex polygons.


      Figure 38.1
        Convex, nonconvex, and complex polygons. +
      -->Figure 38.1  Convex, nonconvex, and complex polygons.

      There are a couple of complications, however. The lesser complication is how to rasterize the polygon efficiently, given that it’s difficult to write fast code that simultaneously traces two edges and fills the space between them. The solution is to decouple the process of scan-converting the polygon into a list of horizontal lines from that of drawing the horizontal lines. One device-independent routine can trace along the two edges and build a list of the beginning and end coordinates of the polygon on each raster line. Then a second, device-specific, routine can draw from the list after the entire polygon has been scanned. We’ll see this in action shortly.

      The second, greater complication arises because the definition of which pixels are “within” a polygon is a more complicated matter than you might imagine. You might think that scan-converting an edge of a polygon is analogous to drawing a line from one vertex to the next, but this is not so. A line by itself is a one-dimensional construct, and as such is approximated on a display by drawing the pixels nearest to the line on either side of the true line. A line serving as a polygon boundary, on the other hand, is part of a two-dimensional object. When filling a polygon, we want to draw the pixels within the polygon, but a standard vertex-to-vertex line-drawing algorithm will draw many pixels outside the polygon, as shown in Figure 38.2.

      It’s no crime to use standard lines to trace out a polygon, rather than drawing only interior pixels. In fact, there are certain advantages: For example, the edges of a filled polygon will match the edges of the same polygon drawn unfilled. Such polygons will look pretty much as they’re supposed to, and all drawing on raster displays is, after all, only an approximation of an ideal.


      Figure 38.2
        Drawing polygons with standard line-drawing algorithms. +
      -->Figure 38.2  Drawing polygons with standard line-drawing algorithms.

      There’s one great drawback to tracing polygons with standard lines, however: Adjacent polygons won’t fit together properly, as shown in Figure 38.3. If you use six equilateral triangles to make a hexagon, for example, the edges of the triangles will overlap when traced with standard lines, and more recently drawn triangles will wipe out portions of their predecessors. Worse still, odd color effects will show up along the polygon boundaries if XOR drawing is used. Consequently, filling out to the boundary lines just won’t do for drawing images composed of fitted-together polygons. And because fitting polygons together is exactly what I have in mind, we need a different approach.


      @@ -76,7 +75,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/38-02.html b/38-02.html index df1c6e4..d052ae1 100644 --- a/38-02.html +++ b/38-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,12 @@


      -

      How Do You Fit Polygons Together?

      +

      How Do You Fit Polygons Together?

      How, then, do you fit polygons together? Very carefully. First, the line-tracing algorithm must be adjusted so that it selects only those pixels that are truly inside the polygon. This basically requires shifting a standard line-drawing algorithm horizontally by one half-pixel toward the polygon’s interior. That leaves the issue of how to handle points that are exactly on the boundary, and points that lie at vertices, so that those points are drawn once and only once. To deal with that, we’re going to adopt the following rules:

      • Points located exactly on nonhorizontal edges are drawn only if the interior of the polygon is directly to the right (left edges are drawn, right edges aren’t). -


        Figure 38.3
          The adjacent polygons problem.

        +


        Figure 38.3
          The adjacent polygons problem.

      • Points located exactly on horizontal edges are drawn only if the interior of the polygon is directly below them (horizontal top edges are drawn, horizontal bottom edges aren’t).
      • A vertex is drawn only if all lines ending at that point meet the above conditions (no right or bottom edges end at that point). @@ -53,7 +53,7 @@

      For our purposes, nonoverlapping polygons are the way to go, so let’s have at them.

      -

      Filling Non-Overlapping Convex Polygons

      +

      Filling Non-Overlapping Convex Polygons

      Without further ado, Listing 38.1 contains a function, FillConvexPolygon, that accepts a list of points that describe a convex polygon, with the last point assumed to connect to the first, and scans it into a list of lines to fill, then passes that list to the function DrawHorizontalLineList in Listing 38.2. Listing 38.3 is a sample program that calls FillConvexPolygon to draw polygons of various sorts, and Listing 38.4 is a header file included by the other listings. Here are the listings; we’ll pick up discussion on the other side.

      LISTING 38.1 L38-1.C

      @@ -330,7 +330,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/38-03.html b/38-03.html index c862936..6763849 100644 --- a/38-03.html +++ b/38-03.html @@ -24,7 +24,7 @@ - +
      @@ -184,7 +184,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/38-04.html b/38-04.html index 6c577b8..7f84397 100644 --- a/38-04.html +++ b/38-04.html @@ -24,7 +24,7 @@ - +
      @@ -49,7 +49,7 @@

      Once we know where the left edge starts in the vertex list, we can scan-convert it a line segment at a time until the bottom vertex is reached. Each point is stored as the starting X coordinate for the corresponding scan line in the list we’ll pass to DrawHorizontalLineList. The nearest X coordinate on each scan line that’s on or to the right of the left edge is selected. The last point of each line segment making up the left edge isn’t scan-converted, producing two desirable effects. First, it avoids drawing each vertex twice; two lines come into every vertex, but we want to scan-convert each vertex only once. Second, not scan-converting the last point of each line causes the bottom scan line of the polygon not to be drawn, as required by our rules. The first scan line of the polygon is also skipped if the top isn’t flat.

      Now we need to scan-convert the right edge into the ending X coordinate fields of the line list. This is performed in the same manner as for the left edge, except that every line in the right edge is moved one pixel to the left before being scan-converted. Why? We want the nearest point to the left of but not on the right edge, so that the right edge itself isn’t drawn. As it happens, drawing the nearest point on or to the right of a line moved one pixel to the left is exactly the same as drawing the nearest point to the left of but not on that line in its original location. Sketch it out and you’ll see what I mean.

      Once the two edges are scan-converted, the whole line list is passed to DrawHorizontalLineList, and the polygon is drawn.

      Finis.

      -

      Oddball Cases

      +

      Oddball Cases

      Listing 38.1 handles zero-length segments (multiple vertices at the same location) by ignoring them, which will be useful down the road because scaled-down polygons can end up with nearby vertices moved to the same location. Horizontal line segments are fine anywhere in a polygon, too. Basically, Listing 38.1 scan-converts between active edges (the edges that define the extent of the polygon on each scan line) and both horizontal and zero-length lines are non-active; neither advances to another scan line, so they don’t affect the edges being scanned.

      I’ve limited this chapter’s code to merely demonstrating the principles of filling convex polygons, and the listings given are by no means fast. In the next chapter, we’ll spice things up by eliminating the floating point calculations and pixel-at-a-time drawing and tossing a little assembly language into the mix.


      @@ -65,7 +65,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/39-01.html b/39-01.html index 89c2e9c..dbafb56 100644 --- a/39-01.html +++ b/39-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 39
      Fast Convex Polygons -

      -

      Filling Polygons in a Hurry

      +

      Chapter 39
      Fast Convex Polygons

      +

      Filling Polygons in a Hurry

      In the previous chapter, we explored the surprisingly intricate process of filling convex polygons. Now we’re going to fill them an order of magnitude or so faster.

      Two thoughts may occur to some of you at this point: “Oh, no, he’s not going to get into assembly language and device-dependent code, is he?” and, “Why bother with polygon filling—or, indeed, any drawing primitives—anyway? Isn’t that what GUIs and third-party libraries are for?”

      @@ -47,7 +46,7 @@

      The “black box” approach does not, however, necessarily cause the software itself to become faster, smaller, or more innovative; quite the opposite, I suspect. I’ll reserve judgement on whether that is a good thing or not, but I’ll make a prediction: In the short run, the aforementioned techniques will lead to noticeably larger, slower programs, as programmers understand less and less of what the key parts of their programs do and rely increasingly on general-purpose code written by other people. (In the long run, programs will be bigger and slower yet, but computers will be so fast and will have so much memory that no one will care.) Over time, PC programs will also come to be more similar to one another—and to programs running on other platforms, such as the Mac—as regards both user interface and performance.

      Again, I am not saying that this is bad. It does, however, have major implications for the future nature of PC graphics programming, in ways that will directly affect the means by which many of you earn your livings. Not so very long from now, graphics programming—all programming, for that matter—will become mostly a matter of assembling in various ways components written by other people, and will cease to be the all-inclusively creative, mindbendingly complex pursuit it is today. (Using legally certified black boxes is, by the way, one direction in which the patent lawyers are leading us; legal considerations may be the final nail in the coffin of homegrown code.) For now, though, it’s still within your power, as a PC programmer, to understand and even control every single thing that happens on a computer if you so desire, to realize any vision you may have. Take advantage of this unique window of opportunity to create some magic!

      Neither does it hurt to understand what’s involved in drawing, say, a filled polygon, even if you are using a GUI. You will better understand the performance implications of the available GUI functions, and you will be able to fill in any gaps in the functions provided. You may even find that you can outperform the GUI on occasion by doing your own drawing into a system memory bitmap, then copying the result to the screen; for instance, you can do this under Windows by using the WinG library available from Microsoft. You will also be able to understand why various quirks exist, and will be able to put them to good use. For example, the X Window System follows the polygon drawing rules described in the previous chapter (although it’s not obvious from the X Window System documentation); if you understood the previous chapter’s discussion, you’re in good shape to use polygons under X.

      In short, even though doing so runs counter to current trends, it helps to understand how things work, especially when they’re very visible parts of the software you develop. That said, let’s learn more about filling convex polygons.

      -

      Fast Convex Polygon Filling

      +

      Fast Convex Polygon Filling

      In addressing the topic of filling convex polygons in the previous chapter, the implementation we came up with met all of our functional requirements. In particular, it met stringent rules that guaranteed that polygons would never overlap or have gaps at shared edges, an important consideration when building polygon-based images. Unfortunately, the implementation was also slow as molasses. In this chapter we’ll work up polygon-filling code that’s fast enough to be truly usable.

      Our original polygon filling code involved three major tasks, each performed by a separate function:

      @@ -57,7 +56,7 @@
    • Characterizing the polygon and coordinating the tracing and drawing (FillConvexPolygon ).
    • The amount of time that the previous chapter’s sample program spent in each of these areas is shown in Table 39.1. As you can see, half the time was spent drawing and the other half was spent tracing the polygon edges (the time spent in FillConvexPolygon was relatively minuscule), so we have our choice of where to begin optimizing.

      -

      Fast Drawing

      +

      Fast Drawing

      Let’s start with drawing, which is easily sped up. The previous chapter’s code used a double-nested loop that called a draw-pixel function to plot each pixel in the polygon individually. That’s a ridiculous approach in a graphics mode that offers linearly mapped memory, as does VGA mode 13H, the mode in which we’re working. At the very least, we could point a far pointer to the left edge of each polygon scan line, then draw each pixel in that scan line in quick succession, using something along the lines of *ScrPtr++ = FillColor; inside a loop.

      However, it seems silly to use a loop when the x86 has an instruction, REP STOS, that’s uniquely suited to filling linear memory buffers. There’s no way to use REP STOS directly in C code, but it’s a good bet that the memset library function uses REP STOS, so you could greatly enhance performance by using memset to draw each scan line of the polygon in a single shot. That, however, is easier said than done. The memset function linked in from the library is tied to the memory model in use; in small (which includes Tiny, Small, or Medium) data models memset accepts only near pointers, so it can’t be used to access screen memory. Consequently, a large (which includes Compact, Large, or Huge) data model must be used to allow memset to draw to display memory—a clear case of the tail wagging the dog. This is an excellent example of why, although it is possible to use C to do virtually anything, it’s sometimes much simpler just to use a little assembly code and be done with it.


      @@ -72,7 +71,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/39-02.html b/39-02.html index 835b429..dd0274a 100644 --- a/39-02.html +++ b/39-02.html @@ -24,7 +24,7 @@ - +
      @@ -149,7 +149,7 @@ void DrawHorizontalLineList(struct HLineList * HLineListPtr,

      At this point, I’d like to mention that benchmarks are notoriously unreliable; the results in Table 39.1 are accurate only for the test program, and only when running on a particular system. Results could be vastly different if smaller, larger, or more complex polygons were drawn, or if a faster or slower computer/VGA combination were used. These factors notwithstanding, the test program does fill a variety of polygons of varying complexity sized from large to small and in between, and certainly the order of magnitude difference between Listing 39.1 and the old version of DrawHorizontalLineList is a clear indication of which code is superior.

      Anyway, Listing 39.1 has the desired effect of vastly improving drawing time. There are cycles yet to be had in the drawing code, but as tracing polygon edges now takes 92 percent of the polygon filling time, it’s logical to optimize the tracing code next.

      -

      Fast Edge Tracing

      +

      Fast Edge Tracing

      There’s no secret as to why last chapter’s ScanEdge was so slow: It used floating point calculations. One secret of fast graphics is using integer or fixed-point calculations, instead. (Sure, the floating point code would run faster if a math coprocessor were installed, but it would still be slower than the alternatives; besides, why require a math coprocessor when you don’t have to?) Both integer and fixed-point calculations are fast. In many cases, fixed-point is faster, but integer calculations have one tremendous virtue: They’re completely accurate. The tiny imprecision inherent in either fixed or floating-point calculations can result in occasional pixels being one position off from their proper location. This is no great tragedy, but after going to so much trouble to ensure that polygons don’t overlap at common edges, why not get it exactly right?

      In fact, when I tested out the integer edge tracing code by comparing an integer-based test image to one produced by floating-point calculations, two pixels out of the whole screen differed, leading me to suspect a bug in the integer code. It turned out, however, that’s in those two cases, the floating point results were sufficiently imprecise to creep from just under an integer value to just over it, so that the ceil function returned a coordinate that was one too large.

      @@ -168,7 +168,7 @@ void DrawHorizontalLineList(struct HLineList * HLineListPtr,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/39-03.html b/39-03.html index b0ac0f2..2a6aa72 100644 --- a/39-03.html +++ b/39-03.html @@ -24,7 +24,7 @@ - +
      @@ -159,7 +159,7 @@ void ScanEdge(int X1, int Y1, int X2, int Y2, int SetXStart, } -

      The Finishing Touch: Assembly Language

      +

      The Finishing Touch: Assembly Language

      The C implementation in Listing 39.2 is now nearly 20 times as fast as the original, which is good enough for most purposes. Still, it requires that one of the large data models be used (for memset ), and it’s certainly not the fastest possible code. The obvious next step is assembly language.

      Listing 39.3 is an assembly language version of DrawHorizontalLineList . In actual use, it proved to be about 36 percent faster than Listing 39.1; better than a poke in the eye with a sharp stick, but just barely. There’s more to these timing results than meets that eye, though. Display memory generally responds much more slowly than system memory, especially in 386 and 486 systems. That means that much of the time taken by Listing 39.3 is actually spent waiting for display memory accesses to complete, with the processor forced to idle by wait states. If, instead, Listing 39.3 drew to a local buffer in system memory or to a particularly fast VGA, the assembly implementation might well display a far more substantial advantage over the C code.


      @@ -174,7 +174,7 @@ void ScanEdge(int X1, int Y1, int X2, int Y2, int SetXStart,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/39-04.html b/39-04.html index 6cc2f20..f47b5bc 100644 --- a/39-04.html +++ b/39-04.html @@ -24,7 +24,7 @@ - +
      @@ -134,10 +134,10 @@ _DrawHorizontalLineList endp end -

      Maximizing REP STOS

      +

      Maximizing REP STOS

      Listing 39.3 doesn’t take the easy way out and use REP STOSB to fill each scan line; instead, it uses REP STOSW to fill as many pixel pairs as possible via word-sized accesses, using STOSB only to do odd bytes. Word accesses to odd addresses are always split by the processor into 2-byte accesses. Such word accesses take twice as long as word accesses to even addresses, so Listing 39.3 makes sure that all word accesses occur at even addresses, by performing a leading STOSB first if necessary.

      Listing 39.3 is another case in which it’s worth knowing the environment in which your code will run. Extra code is required to perform aligned word-at-a-time filling, resulting in extra overhead. For very small or narrow polygons, that overhead might overwhelm the advantage of drawing a word at a time, making plain old REP STOSB faster.

      -

      Faster Edge Tracing

      +

      Faster Edge Tracing

      Finally, Listing 39.4 is an assembly language version of ScanEdge. Listing 39.4 is a relatively straightforward translation from C to assembly, but is nonetheless about twice as fast as Listing 39.2.

      The version of ScanEdge in Listing 39.4 could certainly be sped up still further by unrolling the loops. FillConvexPolygon, the overall coordination routine, hasn’t even been converted to assembly language, so that could be sped up as well. I haven’t bothered with these optimizations because all code other than DrawHorizontalLineList takes only 14 percent of the overall polygon filling time when drawing to display memory; the potential return on optimizing nondrawing code simply isn’t great enough to justify the effort. Part of the value of a profiler is being able to tell when to stop optimizing; with Listings 39.3 and 39.4 in use, more than two-thirds of the time taken to draw polygons is spent waiting for display memory, so optimization is pretty much maxed out. However, further optimization might be worthwhile when drawing to system memory, where wait states are out of the picture and the nondrawing code takes a significant portion (46 percent) of the overall time.

      Again, know where the cycles go .

      @@ -154,7 +154,7 @@ _DrawHorizontalLineList endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/39-05.html b/39-05.html index 9734241..8ef9a58 100644 --- a/39-05.html +++ b/39-05.html @@ -24,7 +24,7 @@ - +
      @@ -220,7 +220,7 @@ _ScanEdge endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/40-01.html b/40-01.html index 8922c3d..cc9c3af 100644 --- a/40-01.html +++ b/40-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,27 +36,26 @@


      -

      Chapter 40
      Of Songs, Taxes, and the Simplicity of Complex Polygons -

      -

      Dealing with Irregular Polygonal Areas

      +

      Chapter 40
      Of Songs, Taxes, and the Simplicity of Complex Polygons

      +

      Dealing with Irregular Polygonal Areas

      Every so often, my daughter asks me to sing her to sleep. (If you’ve ever heard me sing, this may cause you concern about either her hearing or her judgement, but love knows no bounds.) As any parent is well aware, singing a young child to sleep can easily take several hours, or until sunrise, whichever comes last. One night, running low on children’s songs, I switched to a Beatles medley, and at long last her breathing became slow and regular. At the end, I softly sang “A Hard Day’s Night,” then quietly stood up to leave. As I tiptoed out, she said, in a voice not even faintly tinged with sleep, “Dad, what do they mean, ‘working like a dog’? Chasing a stick? That doesn’t make sense; people don’t chase sticks.”

      That led us into a discussion of idioms, which made about as much sense to her as an explanation of quantum mechanics. Finally, I fell back on my standard explanation of the Universe, which is that a lot of the time it simply doesn’t make sense.

      As a general principle, that explanation holds up remarkably well. (In fact, having just done my taxes, I think Earth is actually run by blob-creatures from the planet Mrxx, who are helplessly doubled over with laughter at the ridiculous things they can make us do. “Let’s make them get Social Security numbers for their pets next year!” they’re saying right now, gasping for breath.) Occasionally, however, one has the rare pleasure of finding a corner of the Universe that makes sense, where everything fits together as if preordained.

      Filling arbitrary polygons is such a case.

      -

      Filling Arbitrary Polygons

      +

      Filling Arbitrary Polygons

      In Chapter 38, I described three types of polygons: convex, nonconvex, and complex. The RenderMan Companion, a terrific book by Steve Upstill (Addison-Wesley, 1990) has an intuitive definition of convex: If a rubber band stretched around a polygon touches all vertices in the order they’re defined, then the polygon is convex. If a polygon has intersecting edges, it’s complex. If a polygon doesn’t have intersecting edges but isn’t convex, it’s nonconvex. Nonconvex is a special case of complex, and convex is a special case of nonconvex. (Which, I’m well aware, makes nonconvex a lousy name—noncomplex would have been better—but I’m following X Window System nomenclature here.)

      The reason for distinguishing between these three types of polygons is that the more specialized types can be filled with markedly faster approaches. Complex polygons require the slowest approach; however, that approach will serve to fill any polygon of any sort. Nonconvex polygons require less sorting, because edges never cross. Convex polygons can be filled fastest of all by simply scanning the two sides of the polygon, as we saw in Chapter 39.

      Before we dive into complex polygon filling, I’d like to point out that the code in this chapter, like all polygon filling code I’ve ever seen, requires that the caller describe the type of the polygon to be filled. Often, however, the caller doesn’t know what type of polygon it’s passing, or specifies complex for simplicity, because that will work for all polygons; in such a case, the polygon filler will use the slow complex-fill code even if the polygon is, in fact, a convex polygon. In Chapter 41, I’ll discuss one way to improve this situation.

      -

      Active Edges

      +

      Active Edges

      The basic premise of filling a complex polygon is that for a given scan line, we determine all intersections between the polygon’s edges and that scan line and then fill the spans between the intersections, as shown in Figure 40.1. (Section 3.6 of Foley and van Dam’s Computer Graphics, Second Edition provides an overview of this and other aspects of polygon filling.) There are several rules that might be used to determine which spans are drawn and which aren’t; we’ll use the odd/even rule, which specifies that drawing turns on after odd-numbered intersections (first, third, and so on) and off after even-numbered intersections.

      The question then becomes how can we most efficiently determine which edges cross each scan line and where? As it happens, there is a great deal of coherence from one scan line to the next in a polygon edge list, because each edge starts at a given Y coordinate and continues unbroken until it ends. In other words, edges don’t leap about and stop and start randomly; the X coordinate of an edge at one scan line is a consistent delta from that edge’s X coordinate at the last scan line, and that is consistent for the length of the line.


      Figure 40.1
        Filling one scan line by finding intersecting edges. +
      -->Figure 40.1  Filling one scan line by finding intersecting edges.

      This allows us to reduce the number of edges that must be checked for intersection; on any given scan line, we only need to check for intersections with the currently active edges—edges that start on that scan line, plus all edges that start on earlier (above) scan lines and haven’t ended yet—as shown in Figure 40.2. This suggests that we can proceed from the top scan line of the polygon to the bottom, keeping a running list of currently active edges—called the active edge table (AET)—with the edges sorted in order of ascending X coordinate of intersection with the current scan line. Then, we can simply fill each scan line in turn according to the list of active edges at that line.


      Figure 40.2
        Checking currently active edges (solid lines). +
      -->Figure 40.2  Checking currently active edges (solid lines).

      Maintaining the AET from one scan line to the next involves three steps: First, we must add to the AET any edges that start on the current scan line, making sure to keep the AET X-sorted for efficient odd/even scanning. Second, we must remove edges that end on the current scan line. Third, we must advance the X coordinates of active edges with the same sort of error term-based, Bresenham’s-like approach we used for convex polygons, again ensuring that the AET is X-sorted after advancing the edges.


      @@ -72,7 +71,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/40-02.html b/40-02.html index 7629d14..3211acc 100644 --- a/40-02.html +++ b/40-02.html @@ -24,7 +24,7 @@ - +
      @@ -49,7 +49,7 @@
      7.  If either the AET or GET isn’t empty, go to step 2.


      Figure 40.3
        The global and active edge tables as linked lists. +
      -->Figure 40.3  The global and active edge tables as linked lists.

      That’s really all there is to it. Compare Listing 40.1 to the fast convex polygon filling code from Chapter 39, and you’ll see that, contrary to expectation, complex polygon filling is indeed one of the more sane and sensible corners of the universe.

      @@ -348,7 +348,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/40-03.html b/40-03.html index d747979..f8b5c82 100644 --- a/40-03.html +++ b/40-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Complex Polygon Filling: An Implementation

      +

      Complex Polygon Filling: An Implementation

      Listing 40.1 just shown presents a function, FillPolygon(), that fills polygons of all shapes. If CONVEX_FILL_LINKED is defined, the fast convex fill code from Chapter 39 is linked in and used to draw convex polygons. Otherwise, convex polygons are handled as if they were complex. Nonconvex polygons are also handled as complex, although this is not necessary, as discussed shortly.

      Listing 40.1 is a faithful implementation of the complex polygon filling approach just described, with separate functions corresponding to each of the tasks, such as building the GET and X-sorting the AET. Listing 40.2 provides the actual drawing code used to fill spans, built on a draw pixel routine that is the only hardware dependency anywhere in the C code. Listing 40.3 is the header file for the polygon filling code; note that it is an expanded version of the header file used by the fast convex polygon fill code from Chapter 39. (They may have the same name but are not the same file!) Listing 40.4 is a sample program that, when linked to Listings 40.1 and 40.2, demonstrates drawing polygons of various sorts.

      LISTING 40.2 L40-2.C

      @@ -214,7 +214,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/40-04.html b/40-04.html index d09bece..1d5f36e 100644 --- a/40-04.html +++ b/40-04.html @@ -24,7 +24,7 @@ - +
      @@ -40,10 +40,10 @@

      The set of V-shaped polygons drawn by Listing 40.4 demonstrate that polygons sharing common edges meet but do not overlap. This characteristic, which I discussed at length in Chapter 38, is not a trivial matter; it allows polygons to fit together without fear of overlapping or missed pixels. In general, Listing 40.1 guarantees that polygons are filled such that common boundaries and vertices are drawn once and only once. This has the side-effect for any individual polygon of not drawing pixels that lie exactly on the bottom or right boundaries or at vertices that terminate bottom or right boundaries.

      By the way, I have not seen polygon boundary filling handled precisely this way elsewhere. The boundary filling approach in Foley and van Dam is similar, but seems to me to not draw all boundary and vertex pixels once and only once.

      -

      More on Active Edges

      +

      More on Active Edges

      Edges of zero height—horizontal edges and edges defined by two vertices at the same location—never even make it into the GET in Listing 40.1. A polygon edge of zero height can never be an active edge, because it can never intersect a scan line; it can only run along the scan line, and the span it runs along is defined not by that edge but by the edges that connect to its endpoints.

      -

      Performance Considerations

      +

      Performance Considerations

      How fast is Listing 40.1? When drawing triangles on a 20-MHz 386, it’s less than one-fifth the speed of the fast convex polygon fill code. However, most of that time is spent drawing individual pixels; when Listing 40.2 is replaced with the fast assembly line segment drawing code in Listing 40.5, performance improves by two and one-half times, to about half as fast as the fast convex fill code. Even after conversion to assembly in Listing 40.5, DrawHorizontalLineSeg still takes more than half of the total execution time, and the remaining time is spread out fairly evenly over the various subroutines in Listing 40.1. Consequently, there’s no single place in which it’s possible to greatly improve performance, and the maximum additional improvement that’s possible looks to be a good deal less than two times; for that reason, and because of space limitations, I’m not going to convert the rest of the code to assembly. However, when filling a polygon with a great many edges, and especially one with a great many active edges at one time, relatively more time would be spent traversing the linked lists. In such a case, conversion to assembly (which does a very good job with linked list processing) could pay off reasonably well.

      LISTING 40.5 L40-5.ASM

      @@ -114,7 +114,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/40-05.html b/40-05.html index 3fa3083..84622d7 100644 --- a/40-05.html +++ b/40-05.html @@ -24,7 +24,7 @@ - +
      @@ -40,10 +40,10 @@

      The potential 1 to 5 percent speedup gained by optimizing AET sorting just isn’t worth it in any but the most demanding application—a good example of the need to keep an overall perspective when comparing the theoretical characteristics of various approaches.
      -

      Nonconvex Polygons

      +

      Nonconvex Polygons

      Nonconvex polygons can be filled somewhat faster than complex polygons. Because edges never cross or switch positions with other edges once they’re in the AET, the AET for a nonconvex polygon needs to be sorted only when new edges are added. In order for this to work, though, edges must be added to the AET in strict left-to-right order. Complications arise when dealing with two edges that start at the same point, because slopes must be compared to determine which edge is leftmost. This is certainly doable, but because of space limitations and limited performance returns, I haven’t implemented this in Listing 40.1.

      -

      Details, Details

      +

      Details, Details

      Every so often, a programming demon that I’d thought I’d forever laid to rest arises to haunt me once again. A minor example of this—an imp, if you will—is the use of “ = ” when I mean “ == ,” which I’ve done all too often in the past, and am sure I’ll do again. That’s minor deviltry, though, compared to the considerably greater evils of one of my personal scourges, of which I was recently reminded anew: too-close attention to detail. Not seeing the forest for the trees. Looking low when I should have looked high. Missing the big picture, if you catch my drift.

      Thoreau said it best: “Our life is frittered away by detail....Simplify, simplify.” That quote sprang to mind when I received a letter a while back from Anton Treuenfels of Fridley, Minnesota, thanking me for clarifying the principles of filling adjacent convex polygons in my ongoing writings on graphics programming. (You’ll find this material in the previous two chapters.) Anton then went on to describe his own method for filling convex polygons.

      @@ -64,7 +64,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/41-01.html b/41-01.html index ad35950..475b2da 100644 --- a/41-01.html +++ b/41-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,15 @@


      -

      Chapter 41
      Those Way-Down Polygon Nomenclature Blues -

      -

      Names Do Matter when You Conceptualize a Data Structure

      +

      Chapter 41
      Those Way-Down Polygon Nomenclature Blues

      +

      Names Do Matter when You Conceptualize a Data Structure

      After I wrote the columns on polygons in Dr. Dobb’s Journal that became Chapters 38-40, long-time reader Bill Huber wrote to take me to task—and a well-deserved kick in the fanny it was, I might add—for my use of non-standard polygon terminology in those columns. Unix’s X-Window System (XWS) defines three categories of polygons: complex, nonconvex, and convex. These three categories, each a specialized subset of the preceding category, not-so-coincidentally map quite nicely to three increasingly fast polygon filling techniques. Therefore, I used the XWS names to describe the sorts of polygons that can be drawn with each of the polygon filling techniques.

      The problem is that those names don’t accurately describe all the sorts of polygons that the techniques are capable of drawing. Convex polygons are those for which no interior angle is greater than 180 degrees. The “convex” drawing approach described in the previous few chapters actually handles a number of polygons that are not convex; in fact, it can draw any polygon through which no horizontal line can be drawn that intersects the boundary more than twice. (In other words, the boundary reverses the Y direction exactly twice, disregarding polygons that have degenerated into horizontal lines, which I’m going to ignore.)

      Bill was kind enough to send me the pages out of Computational Geometry, An Introduction (Springer-Verlag, 1988) that describe the correct terminology; such polygons are, in fact, “monotone with respect to a vertical line” (which unfortunately makes a rather long #define variable). Actually, to be a tad more precise, I’d call them “monotone with respect to a vertical line and simple,” where “simple” means “not self-intersecting.” Similarly, the polygon type I called “nonconvex” is actually “simple,” and I suppose what I called “complex” should be referred to as “nonsimple,” or maybe just “none of the above.”

      This may seem like nit-picking, but actually, it isn’t; what it’s really about is the tremendous importance of having a shared language. In one of his books, Richard Feynman describes having developed his own mathematical framework, complete with his own notation and terminology, in high school. When he got to college and started working with other people who were at his level, he suddenly understood that people can’t share ideas effectively unless they speak the same language; otherwise, they waste a great deal of time on misunderstandings and explanation.

      Or, as Bill Huber put it, “You are free to adopt your own terminology when it suits your purposes well. But you risk losing or confusing those who could be among your most astute readers—those who already have been trained in the same or a related field.” Ditto. Likewise. D’accord. And mea culpa ; I shall endeavor to watch my language in the future.

      -

      Nomenclature in Action

      +

      Nomenclature in Action

      Just to show you how much difference proper description and interchange of ideas can make, consider the case of identifying convex polygons. When I was writing about polygons in my column in DDJ, a nonfunctional method for identifying such polygons—checking for exactly two X direction changes and two Y direction changes around the perimeter of the polygon—crept into the column by accident. That method, as I noted in a later column, does not work. (That’s why you won’t find it in this book.) Still, a fast method of checking for convex polygons would be highly desirable, because such polygons can be drawn with the fast code from Chapter 39, rather than the relatively slow, general-purpose code from Chapter 40.

      Now consider Bill’s point that we’re not limited to drawing convex polygons in our “convex fill” code, but can actually handle any simple polygon that’s monotone with respect to a vertical line. Additionally, consider Anton Treuenfels’s point, made back in Chapter 40, that life gets simpler if we stop worrying about which edge of a polygon is the left edge and which is the right, and instead just scan out each raster line starting at whichever edge is left-most. Now, what do we have?

      What we have is an approach passed along by Jim Kent, of Autodesk Animator fame. If we modify the low-level code to check which edge is left-most on each scan line and start drawing there, as just described, then we can handle any polygon that’s monotone with respect to a vertical line regardless of whether the edges cross. (I’ll call this “monotone-vertical” from now on; if anyone wants to correct that terminology, jump right in.) In other words, we can then handle nonsimple polygons that are monotone-vertical; self-intersection is no longer a problem. We just scan around the polygon’s perimeter looking for exactly two direction reversals along the Y axis only, and if that proves to be the case, we can handle the polygon at high speed. Figure 41.1 shows polygons that can be drawn by a monotone-vertical capable filler; Figure 41.2 shows some that cannot. Listing 41.1 shows code to test whether a polygon is appropriately monotone.

      @@ -109,7 +108,7 @@ int PolygonIsMonotoneVertical(struct PointListHeader * VertexList)
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/41-02.html b/41-02.html index e35b22a..3a7c913 100644 --- a/41-02.html +++ b/41-02.html @@ -24,7 +24,7 @@ - +
      @@ -39,10 +39,10 @@

      Listings 41.2 and 41.3 are variants of the fast convex polygon fill code from Chapter 39, modified to be able to handle all monotone-vertical polygons, including nonsimple ones; the edge-scanning code (Listing 39.4 from Chapter 39) remains the same, and so is not shown again here.


      Figure 41.1
        Monotone-vertical polygons. +
      -->Figure 41.1  Monotone-vertical polygons.


      Figure 41.2
        Non-monotone-vertical polygons. +
      -->Figure 41.2  Non-monotone-vertical polygons.

      LISTING 41.2 L41-2.C

      @@ -177,7 +177,7 @@ int FillMonotoneVerticalPolygon(struct PointListHeader * VertexList,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/41-03.html b/41-03.html index 693fd7e..d1dab41 100644 --- a/41-03.html +++ b/41-03.html @@ -24,7 +24,7 @@ - +
      @@ -145,7 +145,7 @@ _DrawHorizontalLineList endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/41-04.html b/41-04.html index 43f0c8f..b3c87eb 100644 --- a/41-04.html +++ b/41-04.html @@ -24,7 +24,7 @@ - +
      @@ -382,7 +382,7 @@ struct RGB { unsigned char Red, Green, Blue, Spare; };
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/42-01.html b/42-01.html index 72e6398..8838d2c 100644 --- a/42-01.html +++ b/42-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 42
      Wu’ed in Haste; Fried, Stewed at Leisure -

      -

      Fast Antialiased Lines Using Wu’s Algorithm

      +

      Chapter 42
      Wu’ed in Haste; Fried, Stewed at Leisure

      +

      Fast Antialiased Lines Using Wu’s Algorithm

      The thought first popped into my head as I unenthusiastically picked through the salad bar at a local “family” restaurant, trying to decide whether the meatballs, the fried clams, or the lasagna was likely to shorten my life the least. I decided on the chicken in mystery sauce.

      The thought recurred when my daughter asked, “Dad, is that fried chicken?”

      @@ -48,13 +47,13 @@

      The thought I had was as follows: This is not good food. Not a profound thought, but it raises an interesting question: Why was I eating in this restaurant? The answer, to borrow a phrase from E.F. Schumacher, is appropriate technology. For a family on a budget, with a small child, tired of staring at each other over the kitchen table, this was a perfect place to eat. It was cheap, it had greasy food and ice cream, no one cared if children dropped things or talked loudly or walked around, and, most important of all, it wasn’t home. So what if the food was lousy? Good food was a luxury, a bonus; everything on the above list was necessary. A family restaurant was the appropriate dining-out technology, given the parameters within which we had to work.

      When I read through SIGGRAPH proceedings and other state-of-the-art computer-graphics material, all too often I feel like I’m dining at a four-star restaurant with two-year-old triplets and an empty wallet. We’re talking incredibly inappropriate technology for PC graphics here. Sure, I say to myself as I read about an antialiasing technique, that sounds wonderful—if I had 24-bpp color, and dedicated hardware to do the processing, and all day to wait to generate one image. Yes, I think, that is a good way to do hidden surface removal—in a system with hardware z-buffering. Most of the stuff in the journal Computer Graphics is riveting, but, alas, pretty much useless on PCs. When an x86 has to do all the work, speed becomes the overriding parameter, especially for real-time graphics.

      Literature that’s applicable to fast PC graphics is hard enough to find, but what we’d really like is above-average image quality combined with terrific speed, and there’s almost no literature of that sort around. There is some, however, and you folks are right on top of it. For example, alert reader Michael Chaplin, of San Diego, wrote to suggest that I might enjoy the line-antialiasing algorithm presented in Xiaolin Wu’s article, “An Efficient Antialiasing Technique,” in the July 1991 issue of Computer Graphics. Michael was dead-on right. This is a great algorithm, combining excellent antialiased line quality with speed that’s close to that of non-antialiased Bresenham’s line drawing. This is the sort of algorithm that makes you want to go out and write a wire-frame animation program, just so you can see how good those smooth lines look in motion. Wu antialiasing is a wonderful example of what can be accomplished on inexpensive, mass-market hardware with the proper programming perspective. In short, it’s a splendid example of appropriate technology for PCs.

      -

      Wu Antialiasing

      +

      Wu Antialiasing

      Antialiasing, as we’ve been discussing for the past few chapters, is the process of smoothing lines and edges so that they appear less jagged. Antialiasing is partly an aesthetic issue, because it makes images more attractive. It’s also partly an accuracy issue, because it makes it possible to position and draw images with effectively more precision than the resolution of the display. Finally, it’s partly a flat-out necessity, to avoid the horrible, crawling, jagged edges of temporal aliasing when performing animation.

      The basic premise of Wu antialiasing is almost ridiculously simple: As the algorithm steps one pixel unit at a time along the major (longer) axis of a line, it draws the two pixels bracketing the line along the minor axis at each point. Each of the two bracketing pixels is drawn with a weighted fraction of the full intensity of the drawing color, with the weighting for each pixel equal to one minus the pixel’s distance along the minor axis from the ideal line. Yes, it’s a mouthful, but Figure 42.1 illustrates the concept.

      The intensities of the two pixels that bracket the line are selected so that they always sum to exactly 1; that is, to the intensity of one fully illuminated pixel of the drawing color. The presence of aggregate full-pixel intensity means that at each step, the line has the same brightness it would have if a single pixel were drawn at precisely the correct location. Moreover, thanks to the distribution of the intensity weighting, that brightness is centered at the ideal line. Not coincidentally, a line drawn with pixel pairs of aggregate single-pixel intensity, centered on the ideal line, is perceived by the eye not as a jagged collection of pixel pairs, but as a smooth line centered on the ideal line. Thus, by weighting the bracketing pixels properly at each step, we can readily produce what looks like a smooth line at precisely the right location, rather than the jagged pattern of line segments that non-antialiased line-drawing algorithms such as Bresenham’s (see Chapters 35, 36, and 37) trace out.


      Figure 42.1
        The basic concept of Wu antialiasing. +
      -->Figure 42.1  The basic concept of Wu antialiasing.

      You might expect that the implementation of Wu antialiasing would fall into two distinct areas: tracing out the line (that is, finding the appropriate pixel pairs to draw) and calculating the appropriate weightings for each pixel pair. Not so, however. The weighting calculations involve only a few shifts, XORs, and adds; for all practical purposes, tracing and weighting are rolled into one step—and a very fast step it is. How fast is it? On a 33-MHz 486 with a fast VGA, a good but not maxed-out assembly implementation of Wu antialiasing draws a more than respectable 5,000 150-pixel-long vectors per second. That’s especially impressive considering that about 1,500,000 actual pixels are drawn per second, meaning that Wu antialiasing is drawing at around 50 percent of the maximum memory bandwidth—half the fastest theoretically possible drawing speed—of an AT-bus VGA. In short, Wu antialiasing is about as fast an antialiased line approach as you could ever hope to find for the VGA.


      @@ -70,7 +69,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/42-02.html b/42-02.html index 2045ff9..63dc1c1 100644 --- a/42-02.html +++ b/42-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,13 +36,13 @@


      -

      Tracing and Intensity in One

      +

      Tracing and Intensity in One

      Horizontal, vertical, and diagonal lines do not require Wu antialiasing because they pass through the center of every pixel they meet; such lines can be drawn with fast, special-case code. For all other cases, Wu lines are traced out one step at a time along the major axis by means of a simple, fixed-point algorithm. The move along the minor axis with respect to a one-pixel move along the major axis (the line slope for lines with slopes less than 1, 1/slope for lines with slopes greater than 1) is calculated with a single integer divide. This value, called the “error adjust,” is stored as a fixed-point fraction, in 0.16 format (that is, all bits are fractional, and the decimal point is just to the left of bit 15). An error accumulator, also in 0.16 format, is initialized to 0. Then the first pixel is drawn; no weighting is needed, because the line intersects its endpoints exactly.

      Now the error adjust is added to the error accumulator. The error accumulator indicates how far between pixels the line has progressed along the minor axis at any given step; when the error accumulator turns over, it’s time to advance one pixel along the minor axis. At each step along the line, the major-axis coordinate advances by one pixel. The two bracketing pixels to draw are simply the two pixels nearest the line along the minor axis. For instance, if X is the current major-axis coordinate and Y is the current minor-axis coordinate, the two pixels to be drawn are (X,Y) and (X,Y+1). In short, the derivation of the pixels at which to draw involves nothing more complicated than advancing one pixel along the major axis, adding the error adjust to the error accumulator, and advancing one pixel along the minor axis when the error accumulator turns over.

      So far, nothing special; but now we come to the true wonder of Wu antialiasing. We know which pair of pixels to draw at each step along the line, but we also need to generate the two proper intensities, which must be inversely proportional to distance from the ideal line and sum to 1, and that’s a potentially time-consuming operation. Let’s assume, however, that the number of possible intensity levels to be used for weighting is the value NumLevels = 2n for some integer n, with the minimum weighting (0 percent intensity) being the value 2n -1, and the maximum weighting (100 percent intensity) being the value 0. Given that, lo and behold, the most significant n bits of the error accumulator select the proper intensity value for one element of the pixel pair, as shown in Figure 42.2. Better yet, 2n-1 minus the intensity of the first pixel selects the intensity of the other pixel in the pair, because the intensities of the two pixels must sum to 1; as it happens, this result can be obtained simply by flipping the n least-significant bits of the first pixel’s value. All this works because what the error accumulator accumulates is precisely the ideal line’s current distance between the two bracketing pixels.


      Figure 42.2
        Wu intensity calculations. +
      -->Figure 42.2  Wu intensity calculations.

      The intensity calculations take longer to describe than they do to perform. All that’s involved is a shift of the error accumulator to right-justify the desired intensity weighting bits, and then an XOR to flip the least-significant n bits of the first pixel’s value in order to generate the second pixel’s value. Listing 42.1 illustrates just how efficient Wu antialiasing is; the intensity calculations take only three statements, and the entire Wu line-drawing loop is only nine statements long. Of course, a single C statement can hide a great deal of complexity, but Listing 42.6, an assembly implementation, shows that only 15 instructions are required per step along the major axis—and the number of instructions could be reduced to ten by special-casing and loop unrolling. Make no mistake about it, Wu antialiasing is fast.

      @@ -198,7 +198,7 @@ void DrawWuLine(int X0, int Y0, int X1, int Y1, int BaseColor, int NumLevels,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/42-03.html b/42-03.html index c0211c7..a159c27 100644 --- a/42-03.html +++ b/42-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Sample Wu Antialiasing

      +

      Sample Wu Antialiasing

      The true test of any antialiasing technique is how good it looks, so let’s have a look at Wu antialiasing in action. Listing 42.1 is a C implementation of Wu antialiasing. Listing 42.2 is a sample program that draws a variety of Wu-antialiased lines, followed by non-antialiased lines, for comparison. Listing 42.3 contains DrawPixel() and SetMode() functions for mode 13H, the VGA’s 320x200 256-color mode. Finally, Listing 42.4 is a simple, non-antialiased line-drawing routine. Link these four listings together and run the resulting program to see both Wu-antialiased and non-antialiased lines.

      LISTING 42.2 L42-2.C

      @@ -215,7 +215,7 @@ void SetMode()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/42-04.html b/42-04.html index 2843de7..f01c994 100644 --- a/42-04.html +++ b/42-04.html @@ -24,7 +24,7 @@ - +
      @@ -167,7 +167,7 @@ void SetMode()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/42-05.html b/42-05.html index 97664cf..da1bf3b 100644 --- a/42-05.html +++ b/42-05.html @@ -24,7 +24,7 @@ - +
      @@ -310,7 +310,7 @@ _DrawWuLine endp end -

      Notes on Wu Antialiasing

      +

      Notes on Wu Antialiasing

      Wu antialiasing can be applied to any curve for which it’s possible to calculate at each step the positions and intensities of two bracketing pixels, although the implementation will generally be nowhere near as efficient as it is for lines. However, Wu’s article in Computer Graphics does describe an efficient algorithm for drawing antialiased circles. Wu also describes a technique for antialiasing solids, such as filled circles and polygons. Wu’s approach biases the edges of filled objects outward. Although this is no good for adjacent polygons of the sort used in rendering, it’s certainly possible to design a more accurate polygon-antialiasing approach around Wu’s basic weighting technique. The results would not be quite so good as more sophisticated antialiasing techniques, but they would be much faster.

      In general, the results obtained by Wu antialiasing are only so-so, by theoretical measures. Wu antialiasing amounts to a simple box filter placed over a fixed-point step approximation of a line, and that process introduces a good deal of deviation from the ideal. On the other hand, Wu notes that even a 10 percent error in intensity doesn’t lead to noticeable loss of image quality, and for Wu-antialiased lines up to 1K pixels in length, the error is under 10 percent. If it looks good, it is good—and it looks good.
      @@ -331,7 +331,7 @@ _DrawWuLine endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-01.html b/43-01.html index 5d3d519..f835d5d 100644 --- a/43-01.html +++ b/43-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 43
      Bit-Plane Animation -

      -

      A Simple and Extremely Fast Animation Method for Limited Color

      +

      Chapter 43
      Bit-Plane Animation

      +

      A Simple and Extremely Fast Animation Method for Limited Color

      When it comes to computers, my first love is animation. There’s nothing quite like the satisfaction of fooling the eye and creating a miniature reality simply by rearranging a few bytes of display memory. What makes animation particularly interesting is that it has to happen fast (as measured in human time), and without blinking and flickering, or else you risk destroying the illusion of motion and solidity. Those constraints make animation the toughest graphics challenge—and also the most rewarding.

      It pains me to hear industry pundits rag on the PC when it comes to animation. Okay, I’ll grant you that the PC isn’t a Silicon Graphics workstation and never will be, but then neither is anything else on the market. The VGA offers good resolution and color, and while the hardware wasn’t designed for animation, that doesn’t mean we can’t put it to work in that capacity. One lesson that any good PC graphics or assembly programmer learns quickly is that it’s what the PC’s hardware can do—not what it was intended to do—that’s important. (By the way, if I were to pick one aspect of the PC to dump on, it would be sound, not animation. The PC’s sound circuity really is lousy, and it’s hard to understand why that should be, given that a cheap sound chip—which even the almost-forgotten PCjrhad—would have changed everything. I guess IBM figured “serious” computer users would be put off by a computer that could make fun noises.)

      @@ -47,22 +46,22 @@

      This chapter adds yet another sort of animation to the list. We’re going to take advantage of the bit-plane architecture and color palette of the VGA to develop an animation architecture that can handle several overlapping images with terrific speed and with virtually perfect visual quality. This technique produces no overlap effects or flicker and allows us to use the fastest possible method to draw images—the REP MOVS instruction. It has its limitations, but unlike Mode X and some other animation techniques, the techniques I’ll show you in this chapter will also work on the EGA, which may be important in some applications.

      As with any technique on the PC, there are tradeoffs involved with bit-plane animation. While bit-plane animation is extremely attractive as far as performance and visual quality are concerned, it is somewhat limited. Bit-plane animation supports only four colors plus the background color at any one time, each image must consist of only one of the four colors, and it’s preferable that images of the same color not intersect.

      It doesn’t much matter if bit-plane animation isn’t perfect for all applications, though. The real point of showing you bit-plane animation is to bring home the reality that the VGA is a complex adapter with many resources, and that you can do remarkable things if you understand those resources and come up with creative ways to put them to work at specific tasks.

      -

      Bit-Planes: The Basics

      +

      Bit-Planes: The Basics

      The underlying principle of bit-plane animation is extremely simple. The VGA has four separate bit planes in modes 0DH, 0EH, 10H, and 12H. Plane 0 normally contains data for the blue component of pixel color, plane 1 normally contains green pixel data, plane 2 red pixel data, and plane 3 intensity pixel data—but we’re going to mix that up a bit in a moment, so we’ll simply refer to them as planes 0, 1, 2, and 3 from now on.

      Each bit plane can be written to independently. The contents of the four bit planes are used to generate pixels, with the four bits that control the color of each pixel coming from the four planes. However, the bits from the planes go through a look-up stage on the way to becoming pixels—they’re used to look up a 6-bit color from one of the sixteen palette registers. Figure 43.1 shows how the bits from the four planes feed into the palette registers to select the color of each pixel. (On the VGA specifically, the output of the palette registers goes to the DAC for an additional look-up stage, as described in Chapters 33 and 34 and also Chapter A on the companion CD-ROM.)

      Take a good look at Figure 43.1. Any light bulbs going on over your head yet? If not, consider this. The general problem with VGA animation is that it’s complex and time-consuming to manipulate images that span the four planes (as most do), and that it’s hard to avoid interference problems when images intersect, since those images share the same bits in display memory. Since the four bit planes can be written to and read from independently, it should be apparent that if we could come up with a way to display images from each plane independently of whatever images are stored in the other planes, we would have four sets of images that we could manipulate very easily. There would be no interference effects between images in different planes, because images in one plane wouldn’t share bits with images in another plane. What’s more, since all the bits for a given image would reside in a single plane, we could do away with the cumbersome programming of the VGA’s complex hardware that is needed to manipulate images that span multiple planes.


      Figure 43.1
        How 4 bits of video data become 6 bits of color. +
      -->Figure 43.1  How 4 bits of video data become 6 bits of color.

      All in all, it would be a good deal if we could store each image in a single plane, as shown in Figure 43.2. However, a problem arises when images in different planes overlap, as shown in Figure 43.3. The combined bits from overlapping images generate new colors, so the overlapping parts of the images don’t look like they belong to either of the two images. What we really want, of course, is for one of the images to appear to be in front of the other. It would be better yet if the rearward image showed through any transparent (that is, background-colored) parts of the forward image. Can we do that?

      You bet.


      Figure 43.2
        Storing images in separate planes. +
      -->Figure 43.2  Storing images in separate planes.


      Figure 43.3
        The problem of overlapping colors. +
      -->Figure 43.3  The problem of overlapping colors.


      @@ -76,7 +75,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-02.html b/43-02.html index 9052a35..d15b653 100644 --- a/43-02.html +++ b/43-02.html @@ -24,7 +24,7 @@ - +
      @@ -37,7 +37,7 @@


      -

      Stacking the Palette Registers

      +

      Stacking the Palette Registers

      Suppose that instead of viewing the four bits per pixel coming out of display memory as selecting one of sixteen colors,we view those bits as selecting one of four colors. If the bit from plane 0 is 1, that would select color 0 (say, red). The bit from plane 1 would select color 1 (say, green), the bit from plane 2 would select color 2 (say, blue), and the bit from plane 3 would select color 3 (say, white). Whenever more than 1 bit is 1, the 1 bit from the lowest-numbered plane would determine the color, and 1 bits from all other planes would be ignored. Finally, the absence of any 1 bits at all would select the background color (say, black).

      That would give us four colors and the background color. It would also give us nifty image precedence, with images in plane 0 appearing to be in front of images from the other planes, images in plane 1 appearing to be in front of images from planes 2 and 3, and so on. It would even give us transparency, where rearward images would show through holes within and around the edges of images in forward planes. Finally, and most importantly, it would meet all the criteria needed to allow us to store each image in a single plane, letting us manipulate the images very quickly and with no reprogramming of the VGA’s hardware other than the few OUT instructions required to select the plane we want to write to.

      Which leaves only one question: How do we get this magical pixel-precedence scheme to work? As it turns out, all we need to do is reprogram the palette registers so that the 1 bit from the plane with the highest precedence determines the color. The palette RAM settings for the colors described above are summarized in Table 43.1.

      @@ -122,11 +122,11 @@


      Figure 43.4
        How pixel precedence works. +
      -->Figure 43.4  How pixel precedence works.

      Seems almost too easy, doesn’t it? Nonetheless, it works beautifully, as we’ll see very shortly. First, though, I’d like to point out that there’s nothing sacred about plane 0 having precedence. We could rearrange the palette register settings so that any plane had the highest precedence, followed by the other planes in any order. I’ve chosen to make plane 0 the highest precedence only because it seems simplest to think of plane 0 as appearing in front of plane 1, which is in front of plane 2, which is in front of plane 3.

      -

      Bit-Plane Animation in Action

      +

      Bit-Plane Animation in Action

      Without further ado, Listing 43.1 shows bit-plane animation in action. Listing 43.1 animates 13 rather large images (each 32 pixels on a side) over a complex background at a good clip even on a primordial 8088-based PC. Five of the images move very quickly, while the other 8 bounce back and forth at a steady pace.


      @@ -140,7 +140,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-03.html b/43-03.html index 3a3c86e..33fab0b 100644 --- a/43-03.html +++ b/43-03.html @@ -24,7 +24,7 @@ - +
      @@ -549,7 +549,7 @@ Code ends
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-04.html b/43-04.html index 7f4f57e..b4b4442 100644 --- a/43-04.html +++ b/43-04.html @@ -24,7 +24,7 @@ - +
      @@ -43,7 +43,7 @@

      I’m not going to discuss Listing 43.1 in detail; the code is very thoroughly commented and should speak for itself, and most of the individual components of Listing 43.1—the Map Mask register, mode sets, word versus byte OUT instructions to the VGA—have been covered in earlier chapters. Do notice, however, that Listing 43.1 sets the palette exactly as I described earlier. This is accomplished by passing a pointer to a 17-byte array (1 byte for each of the 16 palette registers, and 1 byte for the border color) to the BIOS video interrupt (INT 10H), function 10H, subfunction 2.

      Bit-plane animation does have inherent limitations, which we’ll get to in a second. One limitation that is not inherent to bit-plane animation but simply a shortcoming of Listing 43.1 is somewhat choppy horizontal motion. In the interests of both clarity and keeping Listing 43.1 to a reasonable length, I decided to byte-align all images horizontally. This saved the many tables needed to define the 7 non-byte-aligned rotations of the images, as well as the code needed to support rotation. Unfortunately, it also meant that the smallest possible horizontal movement was 8 pixels (1 byte of display memory), which is far enough to be noticeable at certain speeds. The situation is, however, easily correctable with the additional rotations and code. We’ll see an implementation of fully rotated images (in this case for Mode X, but the principles generalize nicely) in Chapter 49. Vertically, where there is no byte-alignment issue, the images move 4 or 6 pixels at a times, resulting in considerably smoother animation.

      The addition of code to support rotated images would also open the door to support for internal animation, where the appearance of a given image changes over time to suggest that the image is an active entity. For example, propellers could whirl, jaws could snap, and jets could flare. Bit-plane animation with bit-aligned images and internal animation can look truly spectacular. It’s a sight worth seeing, particularly for those who doubt the PC’s worth when it comes to animation.

      -

      Limitations of Bit-Plane Animation

      +

      Limitations of Bit-Plane Animation

      As I’ve said, bit-plane animation is not perfect. For starters, bit-plane animation can only be used in the VGA’s planar modes, modes 0DH, 0EH, 10H, and 12H. Also, the reprogramming of the palette registers that provides image precedence also reduces the available color set from the normal 16 colors to just 5 (one color per plane plus the background color). Worse still, each image must consist entirely of only one of the four colors. Mixing colors within an image is not allowed, since the bits for each image are limited to a single plane and can therefore select only one color. Finally, all images of the same precedence must be the same color.

      It is possible to work around the color limitations to some extent by using only one or two planes for bit-plane animation, while reserving the other planes for multi-color drawing. For example, you could use plane 3 for bit-plane animation while using planes 0-2 for normal 8-color drawing. The images in plane 3 would then appear to be in front of the 8-color images. If we wanted the plane 3 images to be yellow, we could set up the palette registers as shown in Table 43.2.

      @@ -60,7 +60,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-05.html b/43-05.html index 7383659..8af82f0 100644 --- a/43-05.html +++ b/43-05.html @@ -24,7 +24,7 @@ - +
      @@ -104,11 +104,11 @@

      Not allowing images in the same plane to overlap is actually less of a limitation than it seems. Run Listing 43.1 again. Unless you were looking for it, you’d never notice that images of the same color almost never overlap—there’s plenty of action to distract the eye, and the trajectories of images of the same color are arranged so that they have a full range of motion without running into each other. The only exception is the chain of green images, which occasionally doubles back on itself when it bounces directly into a corner and reverses direction. Here, however, the images are moving so quickly that the brief moment during which one image’s fringe blanks a portion of another image is noticeable only upon close inspection, and not particularly unaesthetic even then.


      Figure 43.5
        Pixel precedence for plane 3 only. +
      -->Figure 43.5  Pixel precedence for plane 3 only.

      When a technique has such tremendous visual and performance advantages as does bit-plane animation, it behooves you to design your animation software so that the limitations of the animation technique don’t get in the way. For example, you might design a shooting gallery game with all the images in a given plane marching along in step in a continuous band. The images could never overlap, so bit-plane animation would produce very high image quality.

      -

      Shearing and Page Flipping

      +

      Shearing and Page Flipping

      As Listing 43.1 runs, you may occasionally see an image shear, with the top and bottom parts of the image briefly offset. This is a consequence of drawing an image directly into memory as that memory is being scanned for video data. Occasionally the CRT controller scans a given area of display memory for pixel data just as the program is changing that same memory. If the CRT controller scans memory faster than the CPU can modify that memory, then the CRT controller can scan out the bytes of display memory that have been already been changed, pass the point in the image that the CPU is currently drawing, and start scanning out bytes that haven’t yet been changed. The result: Mismatched upper and lower portions of the image.


      @@ -123,7 +123,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/43-06.html b/43-06.html index ce996c4..f2e7222 100644 --- a/43-06.html +++ b/43-06.html @@ -24,7 +24,7 @@ - +
      @@ -44,7 +44,7 @@

      Also, page flipping requires that you keep the contents of both buffers up to date, which can require a good deal of extra drawing.

      Finally, page flipping requires that you wait until you’re sure the page has flipped before you start drawing to the other page. Otherwise, you could end up modifying a page while it’s still being displayed, defeating the whole purpose of page flipping. Waiting for pages to flip takes time and can slow overall performance significantly. What’s more, it’s sometimes difficult to be sure when the page has flipped, since not all VGA clones implement the display adapter status bits and page flip timing identically.

      To sum up, bit-plane animation by itself is very fast and looks good. In conjunction with page flipping, bit-plane animation looks a little better but is slower, and the overall animation scheme is more difficult to implement and perhaps a bit less reliable on some computers.

      -

      Beating the Odds in the Jaw-Dropping Contest

      +

      Beating the Odds in the Jaw-Dropping Contest

      Bit-plane animation is neat stuff. Heck, good animation of any sort is fun, and the PC is as good a place as any (well, almost any) to make people’s jaws drop. (Certainly it’s the place to go if you want to make a lot of jaws drop.) Don’t let anyone tell you that you can’t do good animation on the PC. You can—if you stretch your mind to find ways to bring the full power of the VGA to bear on your applications. Bit-plane animation isn’t for every task; neither are page flipping, exclusive-ORing, pixel panning, or any of the many other animation techniques you have available. One or more tricks from that grab-bag should give you what you need, though, and the bigger your grab-bag, the better your programs.


      @@ -58,7 +58,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-01.html b/44-01.html index daf7ed8..37a65b6 100644 --- a/44-01.html +++ b/44-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,20 +36,19 @@


      -

      Chapter 44
      Split Screens Save the Page Flipped Day -

      -

      640x480 Page Flipped Animation in 64K...Almost

      +

      Chapter 44
      Split Screens Save the Page Flipped Day

      +

      640x480 Page Flipped Animation in 64K...Almost

      Almost doesn’t count, they say—at least in horseshoes and maybe a few other things. This is especially true in digital circles, where if you need 12 MB of hard disk to install something and you only have 10 MB left (a situation that seems to be some sort of eternal law) you’re stuck.

      And that’s only infuriating until you dredge up the gumption to go in there and free up some space. How would you feel if you were up against an “almost-but-not-quite” kind of a wall that couldn’t be breached by freeing up something elsewhere? Suppose you were within a few KB of implementing a wonderful VGA animation scheme that provided lots of screen space, square pixels, smooth motion and more than adequate speed—but all the memory you have is all there is? What would you do?

      Scream a little. Or throw something that won’t break easily. Then you sit down and let your right brain do what it was designed to do. Sure enough, there’s a way, and in this chapter I’ll explain how a little VGA secret called page splitting can save the day for page flipped animation in 640x480 mode. But to do that, I have to lay a little groundwork first. Or maybe a lot of groundwork.

      No horseshoes here.

      -

      A Plethora of Challenges

      +

      A Plethora of Challenges

      In its simplest terms, computer animation consists of rapidly redrawing similar images at slightly differing locations, so that the eye interprets the successive images as a single object in motion over time. The fact that the world is an analog realm and the images displayed on a computer screen consist of discrete pixels updated at a maximum rate of about 70 Hz is irrelevant; your eye can interpret both real-world images and pixel patterns on the screen as objects in motion, and that’s that.

      One of the key problems of computer animation is that it takes time to redraw a screen, time during which the bitmap controlling the screen is in an intermediate state, with, quite possibly, many objects erased and others half-drawn. Even when only briefly displayed, a partially-updated screen can cause flicker at best, and at worst can destroy the illusion of motion entirely.

      Another problem of animation is that the screen must update often enough so that motion appears continuous. A moving object that moves just once every second, shifting by hundreds of pixels each time it does move, will appear to jump, not to move smoothly. Therefore, there are two overriding requirements for smooth animation: 1) the bitmap must be updated quickly (once per frame—60 to 70 Hz—is ideal, although 30 Hz will do fine), and, 2) the process of redrawing the screen must be invisible to the user; only the end result should ever be seen. Both of these requirements are met by the program presented in Listings 44.1 and 44.2.

      -

      A Page Flipping Animation Demonstration

      +

      A Page Flipping Animation Demonstration

      The listings taken together form a sample animation program, in which a single object bounces endlessly off other objects, with instructions and a count of bounces displayed at the bottom of the screen. I’ll discuss various aspects of Listings 44.1 and 44.2 during the balance of this article. The listings are too complex and involve too much VGA and animation knowledge for for me to discuss it all in exhaustive detail (and I’ve covered a lot of this stuff earlier in the book); instead, I’ll cover the major elements, leaving it to you to explore the finer points—and, hope, to experiment with and expand on the code I’ll provide.


      @@ -64,7 +63,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-02.html b/44-02.html index 9f30935..1cc652d 100644 --- a/44-02.html +++ b/44-02.html @@ -24,7 +24,7 @@ - +
      @@ -341,7 +341,7 @@ void MoveBouncer(bouncer *Bouncer, bumper *BumperPtr, int NumBumpers) {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-03.html b/44-03.html index 66db6aa..ab1c10c 100644 --- a/44-03.html +++ b/44-03.html @@ -24,7 +24,7 @@ - +
      @@ -376,7 +376,7 @@ CharUpLoop:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-04.html b/44-04.html index 39baf92..47eadfc 100644 --- a/44-04.html +++ b/44-04.html @@ -24,7 +24,7 @@ - +
      @@ -38,7 +38,7 @@


      Listing 44.1 is written in C. It could equally well have been written in assembly language, and would then have been somewhat faster. However, wanted to make the point (as I’ve made again and again) that assembly language, and, indeed, optimization in general, is needed only in the most critical portions of any program, and then only when the program would otherwise be too slow. Only in a highly performance-sensitive situation would the performance boost resulting from converting Listing 44.1 to assembly justify the time spent in coding and the bugs that would likely creep in—and the sample program already updates the screen at the maximum possible rate of once per frame even on a 1985-vintage 8-MHz AT. In this case, faster performance would result only in a longer wait for the page to flip.

      -

      Write Mode 3

      +

      Write Mode 3

      It’s possible to update the bitmap very efficiently on the VGA, because the VGA can draw up to 8 pixels at once, and because the VGA provides a number of hardware features to speed up drawing. This article makes considerable use of one particularly unusual hardware feature, write mode 3. We discussed write mode 3 back in Chapter 26, but we’ve covered a lot of ground since then—so I’m going to run through a quick refresher on write mode 3.

      Some background: In the standard VGA’s high-resolution mode, mode 12H (640x480 with 16 colors, the mode in which this chapter’s sample program runs), each byte of display memory controls 8 adjacent pixels on the screen. (The color of each pixel is, in turn, controlled by 4 bits spread across the four VGA memory planes, but we need not concern ourselves with that here.) Now, there will often be times when we want to change some but not all of the pixels controlled by a particular byte of display memory. This is not easily done, for there is no way to write half a byte, or two bits, or such to memory; it’s the whole byte or none of it at all.

      @@ -79,7 +79,7 @@ mov byte ptr es:[di],0ffh

      In short, write mode 3 is a good choice for single-color drawing that modifies individual pixels within display memory bytes. Not coincidentally, the sample application draws only single-color objects within the animation area; this allows write mode 3 to be used for all drawing, in keeping with our desire for speedy screen updates.

      -

      Drawing Text

      +

      Drawing Text

      We’ll need text in the sample application; is that also a good use for write mode 3? Sometimes it is, but not in this particular case.

      Each character in a font is represented by a pattern of bits, with 1-bits representing character pixels and 0-bits representing background pixels. Since we’ll be using the 8x8 font stored in the BIOS ROM (a pointer to which can be obtained by calling a BIOS service, as illustrated by Listing 44.2), each character is exactly 8 bits, or 1 byte wide. We’ll further insist that characters be placed on byte boundaries (that is, with their left edges only at pixels with X coordinates that are multiples of 8); this means that the character bytes in the font are automatically aligned with display memory, and no rotation or clipping of characters is needed. Finally, we’ll draw all text in white.


      @@ -95,7 +95,7 @@ mov byte ptr es:[di],0ffh
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-05.html b/44-05.html index 7499078..3e00c5d 100644 --- a/44-05.html +++ b/44-05.html @@ -24,7 +24,7 @@ - +
      @@ -42,13 +42,13 @@

      I’m not going to delve any deeper into the considerable issues of drawing VGA text; I just want to sensitize you to the existence of approaches other than the ones used in Listings 44.1 and 44.2. On the VGA, the rule is: If there’s something you want to do, there probably are 10 ways to do it, each with unique strengths and weaknesses. Your mission, should you decide to accept it, is to figure out which one is best for your particular application.

      -

      Page Flipping

      +

      Page Flipping

      Now that we know how to update the screen reasonably quickly, it’s time to get on to the fun stuff. Page flipping answers the second requirement for animation, by keeping bitmap changes off the screen until they’re complete. In other words, page flipping guarantees that partially updated bitmaps are never seen.

      How is it possible to update a bitmap without seeing the changes as they’re made? Easy—with page flipping, there are two bitmaps; the program shows you one bitmap while it updates the other. Conceptually, it’s that simple. In practice, unfortunately, it’s not so simple, because of the design of the VGA. To understand why that is, we must look at how the VGA turns bytes in display memory into pixels on the screen.

      The VGA bitmap is a linear 64 K block of memory. (True, most adapters nowadays are SuperVGAs with more than 256 K of display memory, but every make of SuperVGA has its own way of letting you access that extra memory, so going beyond standard VGA is a daunting and difficult task. Also, it’s hard to manipulate the large frame buffers of SuperVGA modes fast enough for real-time animation.) Normally, the VGA picks up the first byte of memory (the byte at offset 0) and displays the corresponding 8 pixels on the screen, then picks up the byte at offset 1 and displays the next 8 pixels, and so on to the end of the screen. However, the offset of the first byte of display memory picked up during each frame is not fixed at 0, but is rather programmable by way of the Start Address High and Low registers, which together store the 16-bit offset in display memory at which the bitmap to be displayed during the next frame starts. So, for example, in mode 10H (640x350, 16 colors), a large enough bitmap to store a complete screen of information can be stored at display memory offsets 0 through 27,999, and another full bitmap could be stored at offsets 28,000 through 55,999, as shown in Figure 44.1. (I’m discussing 640x350 mode at the moment for good reason; we’ll get to 640x480 shortly.) When the Start Address registers are set to 0, the first bitmap (or page) is displayed; when they are set to 28,000, the second bitmap is displayed. Page flipped animation can be performed by displaying page 0 and drawing to page 1, then setting the start address to page 1 to display that page and drawing to page 0, and so on ad infinitum.


      Figure 44.1
        Memory allocation for mode 10h page flipping. +
      -->Figure 44.1  Memory allocation for mode 10h page flipping.


      @@ -62,7 +62,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/44-06.html b/44-06.html index 7aa5dca..18b7711 100644 --- a/44-06.html +++ b/44-06.html @@ -24,7 +24,7 @@ - +
      @@ -37,20 +37,20 @@


      -

      Knowing When to Flip

      +

      Knowing When to Flip

      There’s a hitch, though, and that hitch is knowing exactly when it is that the page has flipped. The page doesn’t flip the instant that you set the Start Address registers. The VGA loads the starting offset from the Start Address registers once before starting each frame, then pays those registers no nevermind until the next frame comes around. This means that you can set the Start Address registers whenever you want—but the page actually being displayed doesn’t change until after the VGA loads that new offset in preparation for the next frame.

      The potential problem should be obvious. Suppose that page 1 is being displayed, and you’re updating page 0. You finish drawing to page 0, set the Start Address registers to 0 to switch to displaying page 0, and start updating page 1, which is no longer displayed. Or is it? If the VGA was in the middle of the current frame, displaying page 1, when you set the Start Address registers, then page 1 is going to be displayed for the rest of the frame, no matter what you do with the Start Address registers. If you start updating page 1 right away, any changes you make may well show up on the screen, because page 0 hasn’t yet flipped to being displayed in place of page 1—and that defeats the whole purpose of page flipping.

      To avoid this problem, it is mandatory that you wait until you’re sure the page has flipped. The Start Address registers are, according to my tests, loaded at the start of the Vertical Sync signal, although that may not be the case with all VGA clones. The Vertical Sync status is provided as bit 3 of the Input Status 1 register, so it would seem that all you need to do to flip a page is set the new Start Address registers, wait for the start of the Vertical Sync pulse that indicates that the page has flipped, and be on your merry way.

      Almost—but not quite. (Do I hear teeth gnashing in the background?) The problem is this: Suppose that, by coincidence, you set one of the Start Address registers just before the start of Vertical Sync, and the other right after the start of Vertical Sync. Why, then, for one frame the Start Address High value for one page would be mixed with the Start Address Low value for the other page, and, depending on the start address values, the whole screen could appear to shift any number of pixels for a single, horrible frame. This must never happen! The solution is to set the Start Address registers when you’re certain Vertical Sync is not about to start. The easiest way to know that is to check for the Display Enable status (bit 0 of the Input Status 1 register) being active; that means that bitmap-controlled pixels are being scanned onto the screen, and, since Vertical Sync happens in the middle of the vertical non-display portion of the frame, Vertical Sync can never be anywhere nearby if Display Enable is active. (Note that one good alternative is to set up both pages with a start address that’s a multiple of 256, and just change the Start Address High register and wait for Vertical Sync, with no Display Enable wait required.)

      So, to flip pages, you must complete all drawing to the non-displayed page, wait for Display Enable to be active, set the new start address, and wait for Vertical Sync to be active. At that point, you can be fully confident that the page that you just flipped off the screen is not displayed and can safely (invisibly) be updated. A side benefit of page flipping is that your program will automatically have a constant time base, with the rate at which new screens are drawn synchronized to the frame rate of the display (typically 60 or 70 Hz). However, complex updates may take more than one frame to complete, especially on slower processors; this can be compensated for by maintaining a count of new screens drawn and cross-referencing that to the BIOS timer count periodically, accelerating the overall pace of the animation (moving farther each time and the like) if updates are happening too slowly.

      -

      Enter the Split Screen

      +

      Enter the Split Screen

      So far, I’ve discussed page flipping in 640x350 mode. There’s a reason for that: 640x350 is the highest-resolution standard mode in which there’s enough display memory for two full pages on a standard VGA. It’s possible to program the VGA to a non-standard 640x400 mode and still have two full pages, but that’s pretty much the limit. One 640x480 page takes 38,400 bytes of display memory, and clearly there isn’t enough room in 64 K of display memory for two of those monster pages.

      And yet, 640x480 is a wonderful mode in many ways. It offers a 1:1 aspect ratio (square pixels), and it provides by far the best resolution of any 16-color mode. Surely there’s some way to bring the visual appeal of page flipping to this mode?

      Surely there is—but it’s an odd solution indeed. The VGA has a feature, known as the split screen, that allows you to force the offset from which the VGA fetches video data back to 0 after any desired scan line. For example, you can program the VGA to scan through display memory as usual until it finishes scan line number 338, and then get the first byte of information for scan line number 339 from offset 0 in display memory.

      That, in turn, allows us to divvy up display memory into three areas, as shown in Figure 44.2. The area from 0 to 11,279 is reserved for the split screen, the area from 11,280 to 38,399 is used for page 0, and the area from 38,400 to 65,519 is used for page 1. This allows page flipping to be performed in the top 339 scan lines (about 70 percent) of the screen, and leaves the bottom 141 scan lines for non-animation purposes, such as showing scores, instructions, statuses, and suchlike. (Note that the allocation of display memory and number of scan lines are dictated by the desire to have as many page-flipped scan lines as possible; you may, if you wish, have fewer page-flipped lines and reserve part of the bitmap for other uses, such as off-screen storage for images.)


      Figure 44.2
        Memory allocation for mode 12h page flipping. +
      -->Figure 44.2  Memory allocation for mode 12h page flipping.

      The sample program for this chapter uses the split screen and page flipping exactly as described above. The playfield through which the object bounces is the page-flipped portion of the screen, and the rectangle at the bottom containing the bounce count and the instructions is the split (that is, not animatable) portion of the screen. Of course, to the user it all looks like one screen. There are no visible boundaries between the two unless you choose to create them.

      @@ -68,7 +68,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-01.html b/45-01.html index 76f0176..0de35a5 100644 --- a/45-01.html +++ b/45-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,19 +36,18 @@


      -

      Chapter 45
      Dog Hair and Dirty Rectangles -

      -

      Different Angles on Animation

      +

      Chapter 45
      Dog Hair and Dirty Rectangles

      +

      Different Angles on Animation

      We brought our pets with us when we moved to Seattle. At about the same time, our Golden Retriever, Sam, observed his third birthday. Sam is relatively intelligent, in the sense that he is clearly smarter than a banana slug, although if he were in the same room with Jeff Duntemann’s dog Mr. Byte, there’s a reasonable chance that he would mistake Mr. Byte for something edible (a category that includes rocks, socks, and a surprising number of things too disgusting to mention), and Jeff would have to find a new source of things to write about.

      But that’s not important now. What is important is that—and I am not making this up—this morning I managed to find the one pair of socks Sam hadn’t chewed holes in. And what’s even more important is that after we moved and Sam turned three, he calmed down amazingly. We had been waiting for this magic transformation since Sam turned one, the age at which most puppies turn into normal dogs who lie around a lot, waking up to eat their Science Diet (motto, “The dog food that costs more than the average neurosurgeon makes in a year”) before licking themselves in embarrassing places and going back to sleep. When Sam turned one and remained hopelessly out of control we said, “Goldens take two years to calm down,” as if we had a clue. When he turned two and remained undeniably Sam we said, “Any day now.” By the time he turned three, we were reduced to figuring that it was only about seven more years until he expired, at which point we might be able to take all the fur he had shed in his lifetime and weave ourselves some clothes without holes in them, or quite possibly a house.

      But miracle of miracles, we moved, and Sam instantly turned into the dog we thought we’d gotten when we forked over $500—calm, sweet, and obedient. Weeks went by, and Sam was, if anything, better than ever. Clearly, the change was permanent.

      And then we took Sam to the vet for his annual check-up and found that he had an ear infection. Thanks to the wonders of modern animal medicine, a $5 bottle of liquid restored his health in just two days. And with his health, we got, as a bonus, the old Sam. You see, Sam hadn’t changed. He was just tired from being sick. Now he once again joyously knocks down any stranger who makes the mistake of glancing in his direction, and will, quite possibly, be booked any day now on suspicion of homicide by licking.

      -

      Plus ça Change

      +

      Plus ça Change

      Okay, you give up. What exactly does this have to do with graphics? I’m glad you asked. The lesson to be learned from Sam, The Dog With A Brain The Size Of A Walnut, is that while things may look like they’ve changed, in fact they often haven’t. Take VGA performance. If you buy a 486 with a SuperVGA, you’ll get performance that knocks your socks off, especially if you run Windows. Things are liable to be so fast that you’ll figure the SuperVGA has to deserve some of the credit. Well, maybe it does if it’s a local-bus VGA. But maybe it doesn’t, even if it is local bus—and it certainly doesn’t if it’s an ISA bus VGA, because no ISA bus VGA can run faster than about 300 nanoseconds per access, and VGAs capable of that speed have been common for at least a couple of years now.

      Your 486 VGA system is fast almost entirely because it has a 486 in it. (486 systems with graphics accelerators such as the ATI Ultra or Diamond Stealth are another story altogether.) Underneath it all, the VGA is still painfully slow—and if you have an old VGA or IBM’s original PS/2 motherboard VGA, it’s incredibly slow. The fastest ISA-bus VGA around is two to twenty times slower than system memory, and the slowest VGA around is as much as 100 times slower. In the old days, the rule was, “Display memory is slow, and should be avoided.” Nowadays, the rule is, “Display memory is not quite so slow, but should still be avoided.”

      So, as I say, sometimes things don’t change. Of course, sometimes they do change. For example, in just 49 dog years, I fully expect to own at least one pair of underwear without a single hole in it. Which brings us, deus ex machina and the creek don’t rise, to yet another animation method: dirty-rectangle animation.

      -

      VGA Access Times

      +

      VGA Access Times

      Actually, before we get to dirty rectangles, I’d like to take you through a quick refresher on VGA memory and I/O access times. I want to do this partly because the slow access times of the VGA make dirty-rectangle animation particularly attractive, and partly as a public service, because even I was shocked by the results of some I/O performance tests I recently ran.

      Table 45.1 shows the results of the aforementioned I/O performance tests, as run on two 486/33 SuperVGA systems under the Phar Lap 386|DOS-Extender. (The systems and VGAs are unnamed because this is a not-very-scientific spot test, and I don’t want to unfairly malign, say, a VGA whose only sin is being plugged into a lousy motherboard, or vice versa.) Under Phar Lap, 32-bit protected-mode apps run with full I/O privileges, meaning that the OUT instructions I measured had the best official cycle times possible on the 486: 10 cycles. OUT officially takes 16 cycles in real mode on a 486, and officially takes a mind-boggling 30 cycles in protected mode if running without full I/O privileges (as is normally the case for protected-mode applications). Basically, I/O is just plain slow on a 486.

      @@ -65,7 +64,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-02.html b/45-02.html index 21dfa5d..c732f82 100644 --- a/45-02.html +++ b/45-02.html @@ -24,7 +24,7 @@ - +
      @@ -90,16 +90,16 @@

      For graphics, this especially means using write mode 3 rather than the bit-mask register. When you must use the bit mask, arrange drawing so that you can set the bit mask once, then do a lot of drawing with that mask. For example, draw a whole edge at once, then the middle, then the other edge, rather than setting the bit mask several times on each scan line to draw the edge and middle bytes together. Don’t read from display memory if you don’t have to. Write each pixel once and only once.

      It is indeed a strange concept: The key to fast graphics is staying away from the graphics adapter as much as possible.

      -

      Dirty-Rectangle Animation

      +

      Dirty-Rectangle Animation

      The relative slowness of VGA hardware is part of the appeal of the technique that I call “dirty-rectangle” animation, in which a complete copy of the contents of display memory is maintained in offscreen system (nondisplay) memory. All drawing is done to this system buffer. As offscreen drawing is done, a list is maintained of the bounding rectangles for the drawn-to areas; these are the dirty rectangles, “dirty” in the sense that that have been altered and no longer match the contents of the screen. After all drawing for a frame is completed, all the dirty rectangles for that frame are copied to the screen in a burst, and then the cycle of off-screen drawing begins again.

      Why, exactly, would we want to go through all this complication, rather than simply drawing to the screen in the first place? The reason is visual quality. If we were to do all our drawing directly to the screen, there’d be a lot of flicker as objects were erased and then redrawn. Similarly, overlapped drawing done with the painter’s algorithm (in which farther objects are drawn first, so that nearer objects obscure them) would flicker as farther objects were visible for short periods. With dirty-rectangle animation, only the finished pixels for any given frame ever appear on the screen; intermediate results are never visible. Figure 45.1 illustrates the visual problems associated with drawing directly to the screen; Figure 45.2 shows how dirty-rectangle animation solves these problems.


      Figure 45.1
        Drawing directly to the screen. +
      -->Figure 45.1  Drawing directly to the screen.


      Figure 45.2
        Dirty rectangle animation. +
      -->Figure 45.2  Dirty rectangle animation.

      -

      So Why Not Use Page Flipping?

      +

      So Why Not Use Page Flipping?

      Well, then, if we want good visual quality, why not use page flipping? For one thing, not all adapters and all modes support page flipping. The CGA and MCGA don’t, and neither do the VGA’s 640x480 16-color or 320x200 256-color modes, or many SuperVGA modes. In contrast, all adapters support dirty-rectangle animation. Another advantage of dirty-rectangle animation is that it’s generally faster. While it may seem strange that it would be faster to draw off-screen and then copy the result to the screen, that is often the case, because dirty-rectangle animation usually reduces the number of times the VGA’s hardware needs to be touched, especially in 256-color modes.

      This reduction comes about because when dirty rectangles are erased, it’s done in system memory, not in display memory, and since most objects move a good deal less than their full width (that is, the new and old positions overlap), display memory is written to fewer times than with page flipping. (In 16-color modes, this is not necessarily the case, because of the parallelism obtained from the VGA’s planar hardware.) Also, read/modify/write operations are performed in fast system memory rather than slow display memory, so display memory rarely needs to be read. This is particularly good because display memory is generally even slower for reads than for writes.


      @@ -114,7 +114,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-03.html b/45-03.html index d6c7336..dceb30f 100644 --- a/45-03.html +++ b/45-03.html @@ -24,7 +24,7 @@ - +
      @@ -38,7 +38,7 @@


      Also, page flipping wastes a good deal of time waiting for the page to flip at the end of the frame. Dirty-rectangle animation never needs to wait for anything because partially drawn images are never present in display memory. Actually, in one sense, partially drawn images are sometimes present because it’s possible for a rectangle to be partially drawn when the scanning raster beam reaches that part of the screen. This causes the rectangle to appear partially drawn for one frame, producing a phenomenon I call “shearing.” Fortunately, shearing tends not to be particularly distracting, especially for fairly small images, but it can be a problem when copying large areas. This is one area in which dirty-rectangle animation falls short of page flipping, because page flipping has perfect display quality, never showing anything other than a completely finished frame. Similarly, dirty-rectangle copying may take two or more frame times to finish, so even if shearing doesn’t happen, it’s still possible to have the images in the various dirty rectangles show up non-simultaneously. In my experience, this latter phenomenon is not a serious problem, but do be aware of it.

      -

      Dirty Rectangles in Action

      +

      Dirty Rectangles in Action

      Listing 45.1 demonstrates dirty-rectangle animation. This is a very simple implementation, in several respects. For one thing, it’s written entirely in C, and animation fairly cries out for assembly language. For another thing, it uses far pointers, which C often handles with less than optimal efficiency, especially because I haven’t used library functions to copy and fill memory. (I did this so the code would work in any memory model.) Also, Listing 45.1 doesn’t attempt to coalesce rectangles so as to perform a minimum number of display-memory accesses; instead, it copies each dirty rectangle to the screen, even if it overlaps with another rectangle, so some pixels are copied multiple times. Listing 45.1 runs pretty well, considering all of its failings; on my 486/33, 10 11x11 images animate at a very respectable clip.

      LISTING 45.1 L45-1.C

      @@ -317,7 +317,7 @@ void EraseEntities()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-04.html b/45-04.html index 3f1e2e5..1622dc4 100644 --- a/45-04.html +++ b/45-04.html @@ -24,7 +24,7 @@ - +
      @@ -42,7 +42,7 @@

      If you keep a close watch, you’ll notice that many high-performance animation games similarly restrict their full-featured animation area to a relatively small region. Often, it’s hard to tell that this is the case, because the animation region is surrounded by flashy digitized graphics and by items such as scoreboards and status screens, but look closely and see if the animation region in your favorite game isn’t smaller than you thought.

      -

      Hi-Res VGA Page Flipping

      +

      Hi-Res VGA Page Flipping

      On a standard VGA, hi-res mode is mode 12H, which offers 640x480 resolution with 16 colors. That’s a nice mode, with plenty of pixels, and square ones at that, but it lacks one thing—page flipping. The problem is that the mode 12H bitmap is 150 K in size, and the standard VGA has only 256 K total, too little memory for two of those monster mode 12H pages. With only one page, flipping is obviously out of the question, and without page flipping, top-flight, hi-res animation can’t be implemented. The standard fallback is to use the EGA’s hi-res mode, mode 10H (640x350, 16 colors) for page flipping, but this mode is less than ideal for a couple of reasons: It offers sharply lower vertical resolution, and it’s lousy for handling scaled-up CGA graphics, because the vertical resolution is a fractional multiple—1.75 times, to be exact—of that of the CGA. CGA resolution may not seem important these days, but many images were originally created for the CGA, as were many graphics packages and games, and it’s at least convenient to be able to handle CGA graphics easily. Then, too, 640x350 is also a poor multiple of the 200 scan lines of the popular 320x200 256-color mode 13H of the VGA.

      There are a couple of interesting, if imperfect, solutions to the problem of hi-res page flipping. One is to use the split screen to enable page flipping only in the top two-thirds of the screen; see the previous chapter for details, and for details on the mechanics of page flipping generally. This doesn’t address the CGA problem, but it does yield square pixels and a full 640x480 screen resolution, although not all those pixels are flippable and thus animatable.

      @@ -97,7 +97,7 @@ void Set640x400()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-05.html b/45-05.html index 9dde36e..90d24a9 100644 --- a/45-05.html +++ b/45-05.html @@ -24,7 +24,7 @@ - +
      @@ -150,7 +150,7 @@ void Set640x400()
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/45-06.html b/45-06.html index a49fbcb..42eca64 100644 --- a/45-06.html +++ b/45-06.html @@ -24,7 +24,7 @@ - +
      @@ -38,7 +38,7 @@


      The 640x400 mode I’ve described here isn’t exactly earthshaking, but it can come in handy for page flipping and CGA emulation, and I’m sure that some of you will find it useful at one time or another.

      -

      Another Interesting Twist on Page Flipping

      +

      Another Interesting Twist on Page Flipping

      I’ve spent a fair amount of time exploring various ways to do animation. I thought I had pegged all the possible ways to do animation: exclusive-ORing; simply drawing and erasing objects; drawing objects with a blank fringe to erase them at their old locations as they’re drawn; page flipping; and, finally, drawing to local memory and copying the dirty (modified) rectangles to the screen, as I’ve discussed in this chapter.

      To my surprise, someone threw me an interesting and useful twist on animation not long ago, which turned out to be a cross between page flipping and dirty-rectangle animation. That someone was Serge Mathieu of Concepteva Inc., in Rosemere, Quebec, who informed me that he designs everything “from a game point de vue.”

      @@ -78,7 +78,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/46-01.html b/46-01.html index ebf6ed1..3ecc537 100644 --- a/46-01.html +++ b/46-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,15 @@


      -

      Chapter 46
      Who Was that Masked Image? -

      -

      Optimizing Dirty-Rectangle Animation

      +

      Chapter 46
      Who Was that Masked Image?

      +

      Optimizing Dirty-Rectangle Animation

      Programming is, by and large, a linear process. One statement or instruction follows another, in predictable sequences, with tiny building blocks strung together to make thinking, which is, of course, A Good Thing. Still, it’s important to keep in mind that there’s a large chunk of the human mind that doesn’t work in a linear fashion.

      I’ve written elsewhere about the virtues of nonlinear/right-brain/lateral/what-have-you thinking in solving tough programming problems, such as debugging or optimization, but it bears repeating. The mind can be an awesome pattern-matching and extrapolation tool, if you let it. For example, the other day was grinding my way through a particularly difficult bit of debugging. The code had been written by someone else, and, to my mind, there’s nothing worse than debugging someone else’s code; there’s always the nasty feeling that you don’t quite know what’s going on. The overall operation of this code wouldn’t come clear in my head, no matter how long stared at it, leaving me with a rising sense of frustration and a determination not to quit until got this bug.

      In the midst of this, a coworker poked his head through the door and told me he had something had to listen to. Reluctantly, went to his office, whereupon he played a tape of what is surely one of the most bizarre 911 calls in history. No doubt some of you have heard this tape, which will briefly describe as involving a deer destroying the interior of a car and biting a man in the neck. Perhaps you found it funny, perhaps not—but as for me, it hit me exactly right. started laughing helplessly, tears rolling down my face. When went back to work—presto!—the pieces of the debugging puzzle had come together in my head, and the work went quickly and easily.

      Obviously, my mind needed a break from linear, left-brain, push-it-out thinking, so it could do the sort of integrating work it does so well—but that it’s rarely willing to do under conscious control. It was exactly this sort of thinking had in mind when titled my 1989 optimization book of Zen of Assembly Language. (Although must admit that few people seem to have gotten the connection, and I’ve had to field a lot of questions about whether I’m a Zen disciple. I’m not—actually, I’m more of a Dave Barry disciple. If you don’t know who Dave Barry is, you should; he’s good for your right brain.) Give your mind a break once in a while, and I’ll bet you’ll find you’re more productive.

      We’re strange thinking machines, but we’re the best ones yet invented, and it’s worth learning how to tap our full potential. And with that, it’s back to dirty-rectangle animation.

      -

      Dirty-Rectangle Animation, Continued

      +

      Dirty-Rectangle Animation, Continued

      In the last chapter, Introduced the idea of dirty-rectangle animation. This technique is an alternative to page flipping that’s capable of producing animation of very high visual quality, without any help at all from video hardware, and without the need for any extra, nondisplayed video memory. This makes dirty-rectangle animation more widely usable than page flipping, because many adapters don’t support page flipping. Dirty-rectangle animation also tends to be simpler to implement than page flipping, because there’s only one bitmap to keep track of. A final advantage of dirty-rectangle animation is that it’s potentially somewhat faster than page flipping, because display-memory accesses can theoretically be reduced to exactly one access for each pixel that changes from one frame to the next.

      The speed advantage of dirty-rectangle animation was entirely theoretical in the previous chapter, because the implementation was completely in C, and because no attempt was made to minimize display memory accesses. The visual quality of Chapter 45’s animation was also less than ideal, for reasons we’ll explore shortly. The code in Listings 46.1 and 46.2 addresses the shortcomings of Chapter 45’s code.

      Listing 46.2 implements the low-level drawing routines in assembly language, which boosts performance a good deal. For maximum performance, it would be worthwhile to convert more of Listing 46.1 into assembly, so a call isn’t required for each animated image, and overall performance could be improved by streamlining the C code, but Listing 46.2 goes a long way toward boosting animation speed. This program now supports snappy animation of 15 images (as opposed to 10 for the software presented in the last chapter), and the images are now two pixels wider. That level of performance is all the more impressive considering that for this chapter I’ve converted the code from using rectangular images to using masked images.


      @@ -61,7 +60,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/46-02.html b/46-02.html index d218f2d..d462393 100644 --- a/46-02.html +++ b/46-02.html @@ -24,7 +24,7 @@ - +
      @@ -572,7 +572,7 @@ RowLoop3:
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/46-03.html b/46-03.html index a41cdef..0d452ad 100644 --- a/46-03.html +++ b/46-03.html @@ -24,7 +24,7 @@ - +
      @@ -36,19 +36,19 @@


      -

      Masked Images

      +

      Masked Images

      Masked images are rendered by drawing an object’s pixels through a mask; pixels are actually drawn only where the mask specifies that drawing is allowed. This makes it possible to draw nonrectangular objects that don’t improperly interfere with one another when they overlap. Masked images also make it possible to have transparent areas (windows) within objects. Masked images produce far more realistic animation than do rectangular images, and therefore are more desirable. Unfortunately, masked images are also considerably slower to draw—however, a good assembly language implementation can go a long way toward making masked images draw rapidly enough, as illustrated by this chapter’s code. (Masked images are also known as sprites; some video hardware supports sprites directly, but on the PC it’s necessary to handle sprites in software.)

      Masked images make it possible to render scenes so that a given image convincingly appears to be in front of or behind other images; that is, so images are displayed in z-order (by distance). By consistently drawing images that are supposed to be farther away before drawing nearer images, the nearer images will appear in front of the other images, and because masked images draw only precisely the correct pixels (as opposed to blank pixels in the bounding rectangle), there’s no interference between overlapping images to destroy the illusion.

      In this chapter, I’ve used the approach of having separate, paired masks and images. Another, quite different approach to masking is to specify a transparent color for copying, and copy only those pixels that are not the transparent color. This has the advantage of not requiring separate mask data, so it’s more compact, and the code to implement this is a little less complex than the full masking I’ve implemented. On the other hand, the transparent color approach is less flexible because it makes one color undrawable. Also, with a transparent color, it’s not possible to keep the same base image but use different masks, because the mask information is embedded in the image data.

      -

      Internal Animation

      +

      Internal Animation

      I’ve added another feature essential to producing convincing animation: internal animation, which is the process of changing the appearance of a given object over time, as distinguished from changing only the location of a given object. Internal animation makes images look active and alive. I’ve implemented the simplest possible form of internal animation in Listing 46.1—alternation between two images—but even this level of internal animation greatly improves the feel of the overall animation. You could easily increase the number of images cycled through, simply by increasing the value of InternalAnimateMax for a given entity. You could also implement more complex image-selection logic to produce more interesting and less predictable internal-animation effects, such as jumping, ducking, running, and the like.

      -

      Dirty-Rectangle Management

      +

      Dirty-Rectangle Management

      As mentioned above, dirty-rectangle animation makes it possible to access display memory a minimum number of times. The previous chapter’s code didn’t do any of that; instead, it copied all portions of every dirty rectangle to the screen, regardless of overlap between rectangles. The code I’ve presented in this chapter goes to the other extreme, taking great pains never to draw overlapped portions of rectangles more than once. This is accomplished by checking for overlap whenever a rectangle is to be added to the dirty list. When overlap with an existing rectangle is detected, the new rectangle is reduced to between zero and four nonoverlapping rectangles. Those rectangles are then again considered for addition to the dirty list, and may again be reduced, if additional overlap is detected.

      A good deal of code is required to generate a fully nonoverlapped dirty list. Is it worth it? It certainly can be, but in the case of Listing 46.1, probably not. For one thing, you’d need larger, heavily overlapped objects for this approach to pay off big. Besides, this program is mostly in C, and spends a lot of time doing things other than actually accessing display memory. It also takes a fair amount of time just to generate the nonoverlapped list; the overhead of all the looping, intersecting, and calling required to generate the list eats up a lot of the benefits of accessing display memory less often. Nonetheless, fully nonoverlapped drawing can be useful under the right circumstances, and I’ve implemented it in Listing 46.1 so you’ll have something to refer to should you decide to go this route.

      There are a couple of additional techniques you might try if you want to wring maximum performance out of dirty-rectangle animation. You could try coalescing rectangles as you generate the dirty-rectangle list. That is, you could detect pairs of rectangles that can be joined together into larger rectangles, so that fewer, larger rectangles would have to be copied. This would boost the efficiency of the low-level copying code, albeit at the cost of some cycles in the dirty-list management code.

      You might also try taking advantage of the natural coherence of animated graphics screens. In particular, because the rectangle used to erase an image at its old location often overlaps the rectangle within which the image resides at its new location, you could just directly generate the two or three nonoverlapped rectangles required to copy both the erase rectangle and the new-image rectangle for any single moving image. The calculation of these rectangles could be very efficient, given that you know in advance the direction of motion of your images. Handling this particular overlap case would eliminate most overlapped drawing, at a minimal cost. You might then decide to ignore overlapped drawing between different images, which tends to be both less common and more expensive to identify and handle.

      -

      Drawing Order and Visual Quality

      +

      Drawing Order and Visual Quality

      A final note on dirty-rectangle animation concerns the quality of the displayed screen image. In the last chapter, we simply stuffed dirty rectangles into a list in the order they became dirty, and then copied all of the rectangles in that same order. Unfortunately, this caused all of the erase rectangles to be copied first, followed by all of the rectangles of the images at their new locations. Consequently, there was a significant delay between the appearance of the erase rectangle for a given image and the appearance of the new rectangle. A byproduct was the fact that a partially complete—part old, part new—image was visible long enough to be noticed. In short, although the pixels ended up correct, they were in an intermediate, incorrect state for a sufficient period of time to make the animation look wrong.

      This violated a fundamental rule of animation: No pixel should ever be displayed in a perceptibly incorrect state. To correct the problem, I’ve sorted the dirty rectangles first by Y coordinate, and secondly by X coordinate. This means the screen updates from to draw a given image should be drawn nearly simultaneously. Run the code from the last chapter and then this chapter; you’ll see quite a difference in appearance.

      Avoid the trap of thinking animation is merely a matter of drawing the right pixels, one after another. Animation is the art of drawing the right pixels at the right times so that the eye and brain see what you want them to see. Animation is a lot more challenging than merely cranking out pixels, and it sure as heck isn’t a purely linear process.


      @@ -63,7 +63,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-01.html b/47-01.html index 7374b8a..a18f0bc 100644 --- a/47-01.html +++ b/47-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,15 @@


      -

      Chapter 47
      Mode X: 256-Color VGA Magic -

      -

      Introducing the VGA’s Undocumented “Animation-Optimal” Mode

      +

      Chapter 47
      Mode X: 256-Color VGA Magic

      +

      Introducing the VGA’s Undocumented “Animation-Optimal” Mode

      At a book signing for my book Zen of Code Optimization, an attractive young woman came up to me, holding my book, and said, “You’re Michael Abrash, aren’t you?” I confessed that I was, prepared to respond in an appropriately modest yet proud way to the compliments I was sure would follow. (It was my own book signing, after all.) It didn’t work out quite that way, though. The first thing out of her mouth was:

      “‘Mode X’ is a stupid name for a graphics mode.” As my jaw started to drop, she added, “And you didn’t invent the mode, either. My husband did it before you did.”

      And they say there are no groupies in programming!

      Well. I never claimed that I invented the mode (which is a 320x256-color mode with some very special properties, as we’ll see shortly). I did discover it independently, but so did other people in the game business, some of them no doubt before I did. The difference is that all those other people held onto this powerful mode as a trade secret, while I didn’t; instead, I spread the word as broadly as I could in my column in Dr. Dobb’s Journal, on the theory that the more people knew about this mode, the more valuable it would be. And I succeeded, as evidenced by the fact that this now widely-used mode is universally known by the name I gave it in DDJ, “Mode X.” Neither do I think that’s a bad name; it’s short, catchy, and easy to remember, and it befits the mystery status of this mode, which was omitted entirely from IBM’s documentation of the VGA.

      In fact, when all is said and done, Mode X is one of my favorite accomplishments. I remember reading that Charles Schultz, creator of “Peanuts,” was particularly proud of having introduced the phrase “security blanket” to the English language. I feel much the same way about Mode X; it’s now a firmly entrenched part of the computer lexicon, and how often do any of us get a chance to do that? And that’s not to mention all the excellent games that would not have been as good without Mode X.

      So, in the end, I’m thoroughly pleased with Mode X; the world is a better place for it, even if it did cost me my one potential female fan. (Contrary to popular belief, the lives of computer columnists and rock stars are not, repeat, not, all that similar.) This and the following two chapters are based on the DDJ columns that started it all back in 1991, three columns that generated a tremendous amount of interest and spawned a ton of games, and about which I still regularly get letters and e-mail. Ladies and gentlemen, I give you...Mode X.

      -

      What Makes Mode X Special?

      +

      What Makes Mode X Special?

      Consider the strange case of the VGA’s 320x256-color mode—Mode X—which is undeniably complex to program and isn’t even documented by IBM—but which is, nonetheless, perhaps the single best mode the VGA has to offer, especially for animation.

      We’ve seen the VGA’s undocumented 256-color modes, in Chapters 31 and 32, but now it’s time to delve into the wonders of Mode X itself. (Most of the performance tips I’ll discuss for this mode also apply to the other non-standard 256-color modes, however.) Five features set Mode X apart from other VGA modes. First, it has a 1:1 aspect ratio, resulting in equal pixel spacing horizontally and vertically (that is, square pixels). Square pixels make for the most attractive displays, and avoid considerable programming effort that would otherwise be necessary to adjust graphics primitives and images to match the screen’s pixel spacing. (For example, with square pixels, a circle can be drawn as a circle; otherwise, it must be drawn as an ellipse that corrects for the aspect ratio—a slower and considerably more complicated process.) In contrast, mode 13H, the only documented 256-color mode, provides a nonsquare 320x200 resolution.

      @@ -67,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-02.html b/47-02.html index 2ab0899..a861731 100644 --- a/47-02.html +++ b/47-02.html @@ -24,7 +24,7 @@ - +
      @@ -39,7 +39,7 @@

      Given the tremendous advantages of Mode X over the documented mode 13H, I’d very much like to get it into the hands of as many developers as possible, so I’m going to spend the next few chapters exploring this odd but worthy mode. I’ll provide mode set code, delineate the bitmap organization, and show how the basic write pixel and read pixel operations work. Then, I’ll move on to the magic stuff: rectangle fills, screen clears, scrolls, image copies, pixel inversion, and, yes, polygon fills (just a different driver for the polygon code), all blurry fast; hardware raster ops; and page flipping. In the end, I’ll build a working animation program that shows many of the features of Mode X in action.

      The mode set code is the logical place to begin.

      -

      Selecting 320x240 256-Color Mode

      +

      Selecting 320x240 256-Color Mode

      We could, if we wished, write our own mode set code for Mode X from scratch—but why bother? Instead, we’ll let the BIOS do most of the work by having it set up mode 13H, which we’ll then turn into Mode X by changing a few registers. Listing 47.1 does exactly that.

      The code in Listing 47.1 has been around for some time, and the very first version had a bug that serves up an interesting lesson. The original DDJ version made images roll on IBM’s fixed-frequency VGA monitors, a problem that didn’t come to my attention until the code was in print and shipped to 100,000 readers.

      @@ -154,7 +154,7 @@ _Set320x240Mode endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-03.html b/47-03.html index 39de5d0..d96e2f4 100644 --- a/47-03.html +++ b/47-03.html @@ -24,7 +24,7 @@ - +
      @@ -42,7 +42,7 @@

      It goes without saying that this is one ugly bitmap organization, requiring a lot of overhead to manipulate a single pixel. The write pixel code shown in Listing 47.2 must determine the appropriate plane and perform a 16-bit OUT to select that plane for each pixel written, and likewise for the read pixel code shown in Listing 47.3. Calculating and mapping in a plane once for each pixel written is scarcely a recipe for performance.

      That’s all right, though, because most graphics software spends little time drawing individual pixels. I’ve provided the write and read pixel routines as basic primitives, and so you’ll understand how the bitmap is organized, but the building blocks of high-performance graphics software are fills, copies, and bitblts, and it’s there that Mode X shines.


      Figure 47.1
        Mode X display memory organization. +
      -->Figure 47.1  Mode X display memory organization.

      LISTING 47.2 L47-2.ASM

      @@ -168,7 +168,7 @@ _ReadPixelX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-04.html b/47-04.html index c4abd43..bef22c6 100644 --- a/47-04.html +++ b/47-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Designing from a Mode X Perspective

      +

      Designing from a Mode X Perspective

      Listing 47.4 shows Mode X rectangle fill code. The plane is selected for each pixel in turn, with drawing cycling from plane 0 to plane 3, then wrapping back to plane 0. This is the sort of code that stems from a write-pixel line of thinking; it reflects not a whit of the unique perspective that Mode X demands, and although it looks reasonably efficient, it is in fact some of the slowest graphics code you will ever see. I’ve provided Listing 47.4 partly for illustrative purposes, but mostly so we’ll have a point of reference for the substantial speed-up that’s possible with code that’s designed from a Mode X perspective.

      LISTING 47.4 L47-4.ASM

      @@ -148,7 +148,7 @@ _FillRectangleX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-05.html b/47-05.html index c2d3848..32e7793 100644 --- a/47-05.html +++ b/47-05.html @@ -24,7 +24,7 @@ - +
      @@ -184,7 +184,7 @@ _FillRectangleX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-06.html b/47-06.html index 34d28a3..c4d136b 100644 --- a/47-06.html +++ b/47-06.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,12 @@


      -

      Hardware Assist from an Unexpected Quarter

      +

      Hardware Assist from an Unexpected Quarter

      Listing 47.5 illustrates the benefits of designing code from a Mode X perspective; this is the software aspect of Mode X optimization, which suffices to make Mode X about as fast as mode 13H. That alone makes Mode X an attractive mode, given its square pixels, page flipping, and offscreen memory, but superior performance would nonetheless be a pleasant addition to that list. Superior performance is indeed possible in Mode X, although, oddly enough, it comes courtesy of the VGA’s hardware, which was never designed to be used in 256-color modes.

      All of the VGA’s hardware assist features are available in Mode X, although some are not particularly useful. The VGA hardware feature that’s truly the key to Mode X performance is the ability to process four planes’ worth of data in parallel; this includes both the latches and the capability to fan data out to any or all planes. For rectangular fills, we’ll just need to fan the data out to various planes, so I’ll defer a discussion of other hardware features for now. (By the way, the ALUs, bit mask, and most other VGA hardware features are also available in mode 13H—but parallel data processing is not.)

      In planar modes, such as Mode X, a byte written by the CPU to display memory may actually go to anywhere between zero and four planes, as shown in Figure 47.2. Each plane for which the setting of the corresponding bit in the Map Mask register is 1 receives the CPU data, and each plane for which the corresponding bit is 0 is not modified.

      In 16-color modes, each plane contains one-quarter of each of eight pixels, with the 4 bits of each pixel spanning all four planes. Not so in Mode X. Look at Figure 47.1 again; each plane contains one pixel in its entirety, with four pixels at any given address, one per plane. Still, the Map Mask register does the same job in Mode X as in 16-color modes; set it to 0FH (all 1-bits), and all four planes will be written to by each CPU access. Thus, it would seem that up to four pixels could be set by a single Mode X byte-sized write to display memory, potentially speeding up operations like rectangle fills by four times.


      Figure 47.2
        Selecting planes with the Map Mask register. +
      -->Figure 47.2  Selecting planes with the Map Mask register.

      And, as it turns out, four-plane parallelism works quite nicely indeed. Listing 47.6 is yet another rectangle-fill routine, this time using the Map Mask to set up to four pixels per STOS. The only trick to Listing 47.6 is that any left or right edge that isn’t aligned to a multiple-of-four pixel column (that is, a column at which one four-pixel set ends and the next begins) must be clipped via the Map Mask register, because not all pixels at the address containing the edge are modified. Performance is as expected; Listing 47.6 is nearly ten times faster at clearing the screen than Listing 47.4 and just about four times faster than Listing 47.5—and also about four times faster than the same rectangle fill in mode 13H. Understanding the bitmap organization and display hardware of Mode X does indeed pay.

      Note that the return from Mode X’s parallelism is not always 4x; some adapters lack the underlying memory bandwidth to write data that fast. However, Mode X parallel access should always be faster than mode 13H access; the only question on any given adapter is how much faster.


      @@ -57,7 +57,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/47-07.html b/47-07.html index ba46dc3..1c507e0 100644 --- a/47-07.html +++ b/47-07.html @@ -24,7 +24,7 @@ - +
      @@ -199,7 +199,7 @@ void main() {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/48-01.html b/48-01.html index b8682f2..d0cbe38 100644 --- a/48-01.html +++ b/48-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,17 +36,16 @@


      -

      Chapter 48
      Mode X Marks the Latch -

      -

      The Internals of Animation’s Best Video Display Mode

      +

      Chapter 48
      Mode X Marks the Latch

      +

      The Internals of Animation’s Best Video Display Mode

      In the previous chapter, I introduced you to what I call Mode X, an undocumented 320x240 256-color mode of the VGA. Mode X is distinguished from mode 13H, the documented 320x200 256-color VGA mode, in that it supports page flipping, makes off-screen memory available, has square pixels, and, above all, lets you use the VGA’s hardware to increase performance by as much as four times. (Of course, those four times come at the cost of more complex and demanding programming, to be sure—but end users care about results, not how hard the code was to write, and Mode X delivers results in a big way.) In the previous chapter we saw how the VGA’s plane-oriented hardware can be used to speed solid fills. That’s a nice technique, but now we’re going to move up to the big guns—the VGA latches.

      The VGA has four latches, one for each plane of display memory. Each latch stores exactly one byte, and that byte is always the last byte read from the corresponding plane of display memory, as shown in Figure 48.1. Furthermore, whenever a given address in display memory is read, all four planes’ bytes at that address are read and stored in the corresponding latches, regardless of which plane supplied the byte returned to the CPU (as determined by the Read Map register). As with so much else about the VGA, the above will make little sense to VGA neophytes, but the important point is this: By reading one display memory byte, 4 bytes—one from each plane—can be loaded into the latches at once. Any or all of those 4 bytes can then be written anywhere in display memory with a single byte-sized write, as shown in Figure 48.2.


      Figure 48.1
        How the VGA latches are loaded. +
      -->Figure 48.1  How the VGA latches are loaded.


      Figure 48.2
        Writing 4 bytes to display memory in a single operation. +
      -->Figure 48.2  Writing 4 bytes to display memory in a single operation.

      The upshot is that the latches make it possible to copy data around from one part of display memory to another, 32 bits (four pixels) at a time—four times as fast as normal. (Recall from the previous chapter that in Mode X, pixels are stored one per byte, with four pixels in a row stored in successive planes at the same address, one pixel per plane.) However, any one latch can only be loaded from and written to the corresponding plane, so an individual latch can only work with every fourth pixel on the screen; the latch for plane 0 can work with pixels 0, 4, 8..., the latch for plane 1 with pixels 1, 5, 9..., and so on.

      @@ -114,7 +113,7 @@ void main() {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/48-02.html b/48-02.html index 1f51397..6588950 100644 --- a/48-02.html +++ b/48-02.html @@ -24,7 +24,7 @@ - +
      @@ -229,7 +229,7 @@ _FillPatternX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/48-03.html b/48-03.html index 9a1e738..ec9063b 100644 --- a/48-03.html +++ b/48-03.html @@ -24,7 +24,7 @@ - +
      @@ -39,17 +39,17 @@

      Four-pixel-wide patterns are more useful than you might imagine. There are actually 2128 possible patterns (16 pixels, each with 28 possible colors); that set is certainly large enough for most color-dithering purposes, and includes many often-used patterns, such as halftones, diagonal stripes, and crosshatches.

      Furthermore, eight-wide patterns, which are widely used, can be drawn with two passes, one for each half of the pattern. This principle can in fact be extended to patterns of arbitrary multiple-of-four widths. (Widths that aren’t multiples of four are considerably more difficult to handle, because the latches are four pixels wide; one possible solution is expanding such patterns via repetition until they are multiple-of-four widths.)

      -

      Allocating Memory in Mode X

      +

      Allocating Memory in Mode X

      Listing 48.2 raises some interesting questions about the allocation of display memory in Mode X. In Listing 48.2, whenever a pattern is to be drawn, that pattern is first drawn in its entirety at the very end of display memory; the latches are then loaded from that copy of the pattern before each scan line of the actual fill is drawn. Why this double copying process, and why is the pattern stored in that particular area of display memory?

      The double copying process is used because it’s the easiest way to load the latches. Remember, there’s no way to get information directly from the CPU to the latches; the information must first be written to some location in display memory, because the latches can be loaded only from display memory. By writing the pattern to off-screen memory, we don’t have to worry about interfering with whatever is currently displayed on the screen.

      As for why the pattern is stored exactly where it is, that’s part of a master memory allocation plan that will come to fruition in the next chapter, when I implement a Mode X animation program. Figure 48.3 shows this master plan; the first two pages of memory (each 76,800 pixels long, spanning 19,200 addresses—that is, 19,200 pixel quadruplets—in display memory) are reserved for page flipping, the next page of memory (also 76,800 pixels long) is reserved for storing the background (which is used to restore the holes left after images move), the last 16 pixels (four addresses) of display memory are reserved for the pattern buffer, and the remaining 31,728 pixels (7,932 addresses) of display memory are free for storage of icons, images, temporary buffers, or whatever.


      Figure 48.3
        A useful Mode X display memory layout. +
      -->Figure 48.3  A useful Mode X display memory layout.

      This is an efficient organization for animation, but there are certainly many other possible setups. For example, you might choose to have a solid-colored background, in which case you could dispense with the background page (instead using the solid rectangle fill routine to replace the background after images move), freeing up another 76,800 pixels of off-screen storage for images and buffers. You could even eliminate page-flipping altogether if you needed to free up a great deal of display memory. For example, with enough free display memory it is possible in Mode X to create a virtual bitmap three times larger than the screen, with the screen becoming a scrolling window onto that larger bitmap. This technique has been used to good effect in a number of animated games, with and without the use of Mode X.

      -

      Copying Pixel Blocks within Display Memory

      +

      Copying Pixel Blocks within Display Memory

      Another fine use for the latches is copying pixels from one place in display memory to another. Whenever both the source and the destination share the same nibble alignment (that is, their start addresses modulo four are the same), it is not only possible but quite easy to use the latches to copy four pixels at a time. Listing 48.3 shows a routine that copies via the latches. (When the source and destination do not share the same nibble alignment, the latches cannot be used because the source and destination planes for any given pixel differ. In that case, you can set the Read Map register to select a source plane and the Map Mask register to select the corresponding destination plane. Then, copy all pixels in that plane, repeating for all four planes.)

      Although copying through the latches is, in general, a speedy technique, especially on slower VGAs, it’s not always a win. Reading video memory tends to be quite a bit slower than writing, and on a fast VLB or PCI adapter, it can be faster to copy from main memory to display memory than it is to copy from display memory to display memory via the latches. @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/48-04.html b/48-04.html index f8d4434..cae3a84 100644 --- a/48-04.html +++ b/48-04.html @@ -24,7 +24,7 @@ - +
      @@ -227,7 +227,7 @@ _CopyScreenToScreenX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/48-05.html b/48-05.html index be20528..1690497 100644 --- a/48-05.html +++ b/48-05.html @@ -24,7 +24,7 @@ - +
      @@ -39,7 +39,7 @@

      Listing 48.3 has an important limitation: It does not guarantee proper handling when the source and destination overlap, as in the case of a downward scroll, for example. Listing 48.3 performs top-to-bottom, left-to-right copying. Downward scrolls require bottom-to-top copying; likewise, rightward horizontal scrolls require right-to-left copying. As it happens, my intended use for Listing 48.3 is to copy images between off-screen memory and on-screen memory, and to save areas under pop-up menus and the like, so I don’t really need overlap handling—and I do really need to keep the complexity of this discussion down. However, you will surely want to add overlap handling if you plan to perform arbitrary scrolling and copying in display memory.

      Now that we have a fast way to copy images around in display memory, we can draw icons and other images as much as four times faster than in mode 13H, depending on the speed of the VGA’s display memory. (In case you’re worried about the nibble-alignment limitation on fast copies, don’t be; I’ll address that fully in due time, but the secret is to store all four possible rotations in off-screen memory, then select the correct one for each copy.) However, before our fast display memory-to-display memory copy routine can do us any good, we must have a way to get pixel patterns from system memory into display memory, so that they can then be copied with the fast copy routine.

      -

      Copying to Display Memory

      +

      Copying to Display Memory

      The final piece of the puzzle is the system memory to display-memory-copy-routine shown in Listing 48.4. This routine assumes that pixels are stored in system memory in exactly the order in which they will ultimately appear on the screen; that is, in the same linear order that mode 13H uses. It would be more efficient to store all the pixels for one plane first, then all the pixels for the next plane, and so on for all four planes, because many OUTs could be avoided, but that would make images rather hard to create. And, while it is true that the speed of drawing images is, in general, often a critical performance factor, the speed of copying images from system memory to display memory is not particularly critical in Mode X. Important images can be stored in off-screen memory and copied to the screen via the latches much faster than even the speediest system memory-to-display memory copy routine could manage.

      I’m not going to present a routine to perform Mode X copies from display memory to system memory, but such a routine would be a straightforward inverse of Listing 48.4.

      LISTING 48.4 L48-4.ASM

      @@ -165,7 +165,7 @@ _CopySystemToScreenX endp end -

      Who Was that Masked Image Copier?

      +

      Who Was that Masked Image Copier?

      At this point, it’s getting to be time for us to take all the Mode X tools we’ve developed, together with one more tool—masked image copying—and the remaining unexplored feature of Mode X, page flipping, and build an animation application. I hope that when we’re done, you’ll agree with me that Mode X is the way to animate on the PC.

      In truth, though, it matters less whether or not you think that Mode X is the best way to animate than whether or not your users think it’s the best way based on results; end users care only about results, not how you produced them. For my writing, you folks are the end users—and notice how remarkably little you care about how this book gets written and produced. You care that it turned up in the bookstore, and you care about the contents, but you sure as heck don’t care about how it got that far from a bin of tree pulp. When you’re a creator, the process matters. When you’re a buyer, results are everything. All important. Sine qua non. The whole enchilada.

      If you catch my drift.


      @@ -181,7 +181,7 @@ _CopySystemToScreenX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/49-01.html b/49-01.html index 3e0c77e..3e9b08b 100644 --- a/49-01.html +++ b/49-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,12 +36,11 @@


      -

      Chapter 49
      Mode X 256-Color Animation -

      -

      How to Make the VGA Really Get up and Dance

      +

      Chapter 49
      Mode X 256-Color Animation

      +

      How to Make the VGA Really Get up and Dance

      Okay—no amusing stories or informative anecdotes to kick off this chapter; lotta ground to cover, gotta hurry—you’re impatient, I can smell it. I won’t talk about the time a friend made the mistake of loudly saying “$100 bill” during an animated discussion while walking among the bums on Market Street in San Francisco one night, thereby graphically illustrating that context is everything. I can’t spare a word about how my daughter thinks my 11-year-old floppy-disk-based CP/M machine is more powerful than my 386 with its 100-MB hard disk because the CP/M machine’s word processor loads and runs twice as fast as the 386’s Windows-based word processor, demonstrating that progress is not the neat exponential curve we’d like to think it is, and that features and performance are often conflicting notions. And, lord knows, I can’t take the time to discuss the habits of small white dogs, notwithstanding that such dogs seem to be relevant to just about every aspect of computing, as Jeff Duntemann’s writings make manifest. No lighthearted fluff for us; we have real work to do, for today we animate with 256 colors in Mode X.

      -

      Masked Copying

      +

      Masked Copying

      Over the past two chapters, we’ve put together most of the tools needed to implement animation in the VGA’s undocumented 320x240 256-color Mode X. We now have mode set code, solid and 4x4 pattern fills, system memory-to-display memory block copies, and display memory-to-display memory block copies. The final piece of the puzzle is the ability to copy a nonrectangular image to display memory. I call this masked copying.

      Masked copying is sort of like drawing through a stencil, in that only certain pixels within the destination rectangle are drawn. The objective is to fit the image seamlessly into the background, without the rectangular fringe that results when nonrectangular images are drawn by block copying their bounding rectangle. This is accomplished by using a second rectangular bitmap, separate from the image but corresponding to it on a pixel-by-pixel basis, to control which destination pixels are set from the source and which are left unchanged. With a masked copy, only those pixels properly belonging to an image are drawn, and the image fits perfectly into the background, with no rectangular border. In fact, masked copying even makes it possible to have transparent areas within images.

      Note that another way to achieve this effect is to implement copying code that supports a transparent color; that is, a color that doesn’t get copied but rather leaves the destination unchanged. Transparent copying makes for more compact images, because no separate mask is needed, and is generally faster in a software-only implementation. However, Mode X supports masked copying but not transparent copying in hardware, so we’ll use masked copying in this chapter.

      @@ -198,7 +197,7 @@ _CopySystemToScreenMaskedX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/49-02.html b/49-02.html index b679b7f..cebdf8d 100644 --- a/49-02.html +++ b/49-02.html @@ -24,7 +24,7 @@ - +
      @@ -36,7 +36,7 @@


      -

      Faster Masked Copying

      +

      Faster Masked Copying

      In the previous chapter we saw how the VGA’s latches can be used to copy four pixels at a time from one area of display memory to another in Mode X. We’ve further seen that in Mode X the Map Mask register can be used to select which planes are copied. That’s all we need to know to be able to perform fast masked copies; we can store an image in off-screen display memory, and set the Map Mask to the appropriate mask value as up to four pixels at a time are copied.

      There’s a slight hitch, though. The latches can only be used when the source and destination left edge coordinates, modulo four, are the same, as explained in the previous chapter. The solution is to copy all four possible alignments of each image to display memory, each properly positioned for one of the four possible destination-left-edge-modulo-four cases. These aligned images must be accompanied by the four possible alignments of the image mask, stored in system memory. Given all four image and mask alignments, masked copying is a simple matter of selecting the alignment that’s appropriate for the destination’s left edge, then setting the Map Mask with the 4-bit mask corresponding to each four-pixel set as we copy four pixels at a time via the latches.

      @@ -220,7 +220,7 @@ _CopyScreenToScreenMaskedX endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/49-03.html b/49-03.html index e621845..822b514 100644 --- a/49-03.html +++ b/49-03.html @@ -24,7 +24,7 @@ - +
      @@ -130,7 +130,7 @@ typedef struct { } MaskedImage; -

      Notes on Masked Copying

      +

      Notes on Masked Copying

      Listings 49.1 and 49.2, like all Mode X code I’ve presented, perform no clipping, because clipping code would complicate the listings too much. While clipping can be implemented directly in the low-level Mode X routines (at the beginning of Listing 49.1, for instance), another, potentially simpler approach would be to perform clipping at a higher level, modifying the coordinates and dimensions passed to low-level routines such as Listings 49.1 and 49.2 as necessary to accomplish the desired clipping. It is for precisely this reason that the low-level Mode X routines support programmable start coordinates in the source images, rather than assuming (0,0); likewise for the distinction between the width of the image and the width of the area of the image to draw.

      Also, it would be more efficient to make up structures that describe the source and destination bitmaps, with dimensions and coordinates built in, and simply pass pointers to these structures to the low level, rather than passing many separate parameters, as is now the case. I’ve used separate parameters for simplicity and flexibility.

      @@ -149,7 +149,7 @@ typedef struct {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/49-04.html b/49-04.html index 4de169b..17e11db 100644 --- a/49-04.html +++ b/49-04.html @@ -24,7 +24,7 @@ - +
      @@ -36,15 +36,15 @@


      -

      Animation

      +

      Animation

      Gosh. There’s just no way I can discuss high-level animation fundamentals in any detail here; I could spend an entire (and entirely separate) book on animation techniques alone. You might want to have a look at Chapters 43 through 46 before attacking the code in this chapter; that will have to do us for the present volume. (I will return to 3-D animation in the next chapter.)

      Basically, I’m going to perform page flipped animation, in which one page (that is, a bitmap large enough to hold a full screen) of display memory is displayed while another page is drawn to. When the drawing is finished, the newly modified page is displayed, and the other—now invisible—page is drawn to. The process repeats ad infinitum. For further information, some good places to start are Computer Graphics, by Foley and van Dam (Addison-Wesley); Principles of Interactive Computer Graphics, by Newman and Sproull (McGraw Hill); and “Real-Time Animation” by Rahner James (January 1990, Dr. Dobb’s Journal).

      Some of the code in this chapter was adapted for Mode X from the code in Chapter 44—yet another reason to read that chapter before finishing this one.

      -

      Mode X Animation in Action

      +

      Mode X Animation in Action

      Listing 49.5 ties together everything I’ve discussed about Mode X so far in a compact but surprisingly powerful animation package. Listing 49.5 first uses solid and patterned fills and system-memory-to-screen-memory masked copying to draw a static background containing a mountain, a sun, a plain, water, and a house with puffs of smoke coming out of the chimney, and sets up the four alignments of a masked kite image. The background is transferred to both display pages, and drawing of 20 kite images in the nondisplayed page using fast masked copying begins. After all images have been drawn, the page is flipped to show the newly updated screen, and the kites are moved and drawn in the other page, which is no longer displayed. Kites are erased at their old positions in the nondisplayed page by block copying from the background page. (See the discussion in the previous chapter for the display memory organization used by Listing 49.5.) So far as the displayed image is concerned, there is never any hint of flicker or disturbance of the background. This continues at a rate of up to 60 times a second until Esc is pressed to exit the program. See Figure 49.1 for a screen shot of the resulting image—add the animation in your imagination.


      Figure 49.1
        An animated Mode X screen. +
      -->Figure 49.1  An animated Mode X screen.

      LISTING 49.5 L49-5.C

      @@ -298,7 +298,7 @@ void MoveObject(AnimatedObject * ObjectToMove) {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/49-05.html b/49-05.html index ed8ae39..127192b 100644 --- a/49-05.html +++ b/49-05.html @@ -24,7 +24,7 @@ - +
      @@ -91,7 +91,7 @@ _ShowPage endp end -

      Works Fast, Looks Great

      +

      Works Fast, Looks Great

      We now end our exploration of Mode X, although we’ll use it again shortly for 3-D animation. Mode X admittedly has its complexities; that’s why I’ve provided a broad and flexible primitive set. Still, so what if it is complex? Take a look at Listing 49.5 in action. That sort of colorful, high-performance animation is worth jumping through a few hoops for; drawing 20, or even 10, fair-sized objects at a rate of 60 Hz, with no flicker, interference, or fringe, is no mean accomplishment, even on a 386.

      There’s much more we could do with animation in general and with Mode X in particular, but it’s time to move on to new challenges. In closing, I’d like to point out that all of the VGA’s hardware features, including the built-in AND, OR, and XOR functions, are available in Mode X, just as they are in the standard VGA modes. If you understand the VGA’s hardware in mode 12H, try applying that knowledge to Mode X; you might be surprised at what you find you can do.


      @@ -106,7 +106,7 @@ _ShowPage endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-01.html b/50-01.html index d05b1d3..7671a2e 100644 --- a/50-01.html +++ b/50-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 50
      Adding a Dimension -

      -

      3-D Animation Using Mode X

      +

      Chapter 50
      Adding a Dimension

      +

      3-D Animation Using Mode X

      When I first started programming micros, more than 11 years ago now, there wasn’t much money in it, or visibility, or anything you could call a promising career. Sometimes, it was a way to accomplish things that would never have gotten done otherwise because minicomputer time cost too much; other times, it paid the rent; mostly, though, it was just for fun. Given free computer time for the first time in my life, I went wild, writing versions of all sorts of software I had seen on mainframes, in arcades, wherever. It was a wonderful way to learn how computers work: Trial and error in an environment where nobody minded the errors, with no meter ticking.

      Many sorts of software demanded no particular skills other than a quick mind and a willingness to experiment: Space Invaders, for instance, or full-screen operating system shells. Others, such as compilers, required a good deal of formal knowledge. Still others required not only knowledge but also more horse-power than I had available. The latter I filed away on my ever-growing wish list, and then forgot about for a while.

      @@ -47,10 +46,10 @@

      With this chapter, we kick off an exploration of some of the sorts of 3-D animation that can be performed on the x86 family. Mind you, I’m talking about real-time 3-D animation, with all calculations and drawing performed on-the-fly. Generating frames ahead of time and playing them back is an excellent technique, but I’m interested in seeing how far we can push purely real-time animation. Granted, we’re not going to make it to the level of Terminator 2, but we should have some fun nonetheless. The first few chapters in this final section of the book may seem pretty basic to those of you experienced with 3-D programming, and, at the same time, 3-D neophytes will inevitably be distressed at the amount of material I skip or skim over. That can’t be helped, but at least there’ll be working code, the references mentioned later, and some explanation; that should be enough to start you on your way with 3-D.

      Animating in three dimensions is a complex task, so this will be the largest single section of the book, with later chapters building on earlier ones; and even this first 3-D chapter will rely on polygon fill and page-flip code from earlier chapters.

      In a sense, I’ve saved the best for last, because, to my mind, real-time 3-D animation is one of the most exciting things of any stripe that can be done with a computer—and because, with today’s hardware, it can in fact be done. Nay, it can be done amazingly well.

      -

      References on 3-D Drawing

      +

      References on 3-D Drawing

      There are several good sources for information about 3-D graphics. Foley and van Dam’s Computer Graphics: Principles and Practice (Second Edition, Addison-Wesley, 1990) provides a lengthy discussion of the topic and a great many references for further study. Unfortunately, this book is heavy going at times; a more approachable discussion is provided in Principles of Interactive Computer Graphics, by Newman and Sproull (McGraw-Hill, 1979). Although the latter book lacks the last decade’s worth of graphics developments, it nonetheless provides a good overview of basic 3-D techniques, including many of the approaches likely to work well in realtime on a PC.

      A source that you may or may not find useful is the series of six books on C graphics by Lee Adams, as exemplified by High-Performance CAD Graphics in C (Windcrest/Tab, 1986). (I don’t know if all six books discuss 3-D graphics, but the four I’ve seen do.) To be honest, this book has a number of problems, including: Relatively little theory and explanation; incomplete and sometimes erroneous discussions of graphics hardware; use of nothing but global variables, with cryptic names like “array3” and “B21;” and—well, you get the idea. On the other hand, the book at least touches on a great many aspects of 3-D drawing, and there’s a lot of C code to back that up. A number of people have spoken warmly to me of Adams’ books as their introduction to 3-D graphics. I wouldn’t recommend these books as your only 3-D references, but if you’re just starting out, you might want to look at one and see if it helps you bridge the gap between the theory and implementation of 3-D graphics.

      -

      The 3-D Drawing Pipeline

      +

      The 3-D Drawing Pipeline

      Each 3-D object that we’ll handle will be built out of polygons that represent the surface of the object. Figure 50.1 shows the stages a polygon goes through enroute to being drawn on the screen. (For the present, we’ll avoid complications such as clipping, lighting, and shading.) First, the polygon is transformed from object space, the coordinate system the object is defined in, to world space, the coordinate system of the 3-D universe. Transformation may involve rotating, scaling, and moving the polygon. Fortunately, applying the desired transformation to each of the polygon vertices in an object is equivalent to transforming the polygon; in other words, transformation of a polygon is fully defined by transformation of its vertices, so it is not necessary to transform every point in a polygon, just the vertices. Likewise, transformation of all the polygon vertices in an object fully transforms the object.

      Once the polygon is in world space, it must again be transformed, this time into view space, the space defined such that the viewpoint is at (0,0,0), looking down the Z axis, with the Y axis straight up and the X axis off to the right. Once in view space, the polygon can be perspective-projected to the screen, with the projected X and Y coordinates of the vertices finally being used to draw the polygon.

      @@ -67,7 +66,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-02.html b/50-02.html index b03e712..9e902ba 100644 --- a/50-02.html +++ b/50-02.html @@ -24,7 +24,7 @@ - +
      @@ -38,33 +38,33 @@


      One note: I’ll use a purely right-handed convention for coordinate systems. Right-handed means that if you hold your right hand with your fingers curled and the thumb sticking out, the thumb points along the Z axis and the fingers point in the direction of rotation from the X axis to the Y axis, as shown in Figure 50.2. Rotations about an axis are counter-clockwise, as viewed looking down an axis toward the origin. The handedness of a coordinate system is just a convention, and left-handed would do equally well; however, right-handed is generally used for object and world space. Sometimes, the handedness is flipped for view space, so that increasing Z equals increasing distance from the viewer along the line of sight, but I have chosen not to do that here, to avoid confusion. Therefore, Z decreases as distance along the line of sight increases; a view space coordinate of (0,0,-1000) is directly ahead, twice as far away as a coordinate of (0,0,-500).


      Figure 50.1
        The 3-D drawing pipeline. +
      -->Figure 50.1  The 3-D drawing pipeline.


      Figure 50.2
        A right-handed coordinate system. +
      -->Figure 50.2  A right-handed coordinate system.

      -

      Projection

      +

      Projection

      Working backward from the final image, we want to take the vertices of a polygon, as transformed into view space, and project them to 2-D coordinates on the screen, which, for projection purposes, is assumed to be centered on and perpendicular to the Z axis in view space, at some distance from the screen. We’re after visual realism, so we’ll want to do a perspective projection, in order that farther objects look smaller than nearer objects, and so that the field of view will widen with distance. This is done by scaling the X and Y coordinates of each point proportionately to the Z distance of the point from the viewer, a simple matter of similar triangles, as shown in Figure 50.3. It doesn’t really matter how far down the Z axis the screen is assumed to be; what matters is the ratio of the distance of the screen from the viewpoint to the width of the screen. This ratio defines the rate of divergence of the viewing pyramid—the full field of view—and is used for performing all perspective projections. Once perspective projection has been performed, all that remains before calling the polygon filler is to convert the projected X and Y coordinates to integers, appropriately clipped and adjusted as necessary to center the origin on the screen or otherwise map the image into a window, if desired.

      -

      Translation

      +

      Translation

      Translation means adding X, Y, and Z offsets to a coordinate to move it linearly through space. Translation is as simple as it seems; it requires nothing more than an addition for each axis. Translation is, for example, used to move objects from object space, in which the center of the object is typically the origin (0,0,0), into world space, where the object may be located anywhere.


      Figure 50.3
        Perspective projection. +
      -->Figure 50.3  Perspective projection.

      -

      Rotation

      +

      Rotation

      Rotation is the process of circularly moving coordinates around the origin. For our present purposes, it’s necessary only to rotate objects about their centers in object space, so as to turn them to the desired attitude before translating them into world space.

      Rotation of a point about an axis is accomplished by transforming it according to the formulas shown in Figure 50.4. These formulas map into the more generally useful matrix-multiplication forms also shown in Figure 50.4. Matrix representation is more useful for two reasons: First, it is possible to concatenate multiple rotations into a single matrix by multiplying them together in the desired order; that single matrix can then be used to perform the rotations more efficiently.


      Figure 50.4
        3-D rotation formulas. +
      -->Figure 50.4  3-D rotation formulas.

      Second, 3x3 rotation matrices can become the upper-left-hand portions of 4x4 matrices that also perform translation (and scaling as well, but we won’t need scaling in the near future), as shown in Figure 50.5. A 4x4 matrix of this sort utilizes homogeneous coordinates; that’s a topic way beyond this book, but, basically, homogeneous coordinates allow you to handle both rotations and translations with 4x4 matrices, thereby allowing the same code to work with either, and making it possible to concatenate a long series of rotations and translations into a single matrix that performs the same transformation as the sequence of rotations and transformations.

      There’s much more to be said about transformations and the supporting matrix math, but, in the interests of getting to working code in this chapter, I’ll leave that to be discussed as the need arises.

      -

      A Simple 3-D Example

      +

      A Simple 3-D Example

      At this point, we know enough to be able to put together a simple working 3-D animation example. The example will do nothing more complicated than display a single polygon as it sits in 3-D space, rotating around the Y axis. To make things a little more interesting, we’ll let the user move the polygon around in space with the arrow keys, and with the “A” (away), and “T” (toward) keys. The sample program requires two sorts of functionality: The ability to transform and project the polygon from object space onto the screen (3-D functionality), and the ability to draw the projected polygon (complete with clipping) and handle the other details of animation (2-D functionality).


      Figure 50.5
        A 4x4 Transformation Matrix. +
      -->Figure 50.5  A 4x4 Transformation Matrix.

      Happily (and not coincidentally), we put together a nice 2-D animation framework back in Chapters 47, 48, and 49, during our exploratory discussion of Mode X, so we don’t have much to worry about in terms of non-3-D details. Basically, we’ll use Mode X (320x240, 256 colors), and we’ll flip between two display pages, drawing to one while the other is displayed. One new 2-D element that we need is the ability to clip polygons; while we could avoid this for the moment by restricting the range of motion of the polygon so that it stays fully on the screen, certainly in the long run we’ll want to be able to handle partially or fully clipped polygons. Listing 50.1 is the low-level code for a Mode X polygon filler that supports clipping. (The high-level polygon fill code is mode independent, and is the same as that presented in Chapters 38, 39, and 40, as noted further on.) The clipping is implemented at the low level, by trimming the Y extent of the scan line list up front, then clipping the X coordinates of each scan line in turn. This is not a particularly fast approach to clipping—ideally, the polygon would be clipped before it was scanned into a line list, avoiding potentially wasted scanning and eliminating the line-by-line X clipping—but it’s much simpler, and, as we shall see, polygon filling performance is the least of our worries at the moment.


      @@ -80,7 +80,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-03.html b/50-03.html index 1e856da..6d74fdc 100644 --- a/50-03.html +++ b/50-03.html @@ -24,7 +24,7 @@ - +
      @@ -210,7 +210,7 @@ _DrawHorizontalLineList endp
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-04.html b/50-04.html index a814c43..a50081c 100644 --- a/50-04.html +++ b/50-04.html @@ -24,7 +24,7 @@ - +
      @@ -160,7 +160,7 @@ void XformAndProjectPoly(double Xform[4][4], struct Point3 * Poly,
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-05.html b/50-05.html index 6bc1172..c98383b 100644 --- a/50-05.html +++ b/50-05.html @@ -24,7 +24,7 @@ - +
      @@ -126,7 +126,7 @@ extern struct Rect EraseRect[];
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-06.html b/50-06.html index 485a52f..073eeb6 100644 --- a/50-06.html +++ b/50-06.html @@ -24,7 +24,7 @@ - +
      @@ -174,7 +174,7 @@ void main() {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/50-07.html b/50-07.html index d8b2534..7795841 100644 --- a/50-07.html +++ b/50-07.html @@ -24,7 +24,7 @@ - +
      @@ -36,14 +36,14 @@


      -

      Notes on the 3-D Animation Example

      +

      Notes on the 3-D Animation Example

      The sample program transforms the polygon’s vertices from object space to world space to view space to the screen, as described earlier. In this case, world space and view space are congruent—we’re looking right down the negative Z axis of world space—so the transformation matrix from world to view is the identity matrix; you might want to experiment with changing this matrix to change the viewpoint. The sample program uses 4x4 homogeneous coordinate matrices to perform transformations, as described above. Floating-point arithmetic is used for all 3-D calculations. Setting the translation from object space to world space is a simple matter of changing the appropriate entry in the fourth column of the object-to-world transformation matrix. Setting the rotation around the Y axis is almost as simple, requiring only the setting of the four matrix entries that control the Y rotation to the sines and cosines of the desired rotation. However, rotations involving more than one axis require multiple rotation matrices, one for each axis rotated around; those matrices are then concatenated together to produce the object-to-world transformation. This area is trickier than it might initially appear to be; more in the near future.

      The maximum translation along the Z axis is limited to -40; this keeps the polygon from extending past the viewpoint to positive Z coordinates. This would wreak havoc with the projection and 2-D clipping, and would require 3-D clipping, which is far more complicated than 2-D. We’ll get to 3-D clipping at some point, but, for now, it’s much simpler just to limit all vertices to negative Z coordinates. The polygon does get mighty close to the viewpoint, though; run the program and use the “T” key to move the polygon as close as possible—the near vertex swinging past provides a striking sense of perspective.

      The performance of Listing 50.5 is, perhaps, surprisingly good, clocking in at 16 frames per second on a 20 MHz 386 with a VGA of average speed and no 387, although there is, of course, only one polygon being drawn, rather than the hundreds or thousands we’d ultimately like. What’s far more interesting is where the execution time goes. Even though the program is working with only one polygon, 73 percent of the time goes for transformation and projection. An additional 7 percent is spent waiting to flip the screen. Only 20 percent of the total time is spent in all other activity—and only 2 percent is spent actually drawing polygons. Clearly, we’ll want to tackle transformation and projection first when we look to speed things up. (Note, however, that a math coprocessor would considerably decrease the time taken by floating-point calculations.)

      In Listing 50.3, when the extent of the bounding rectangle is calculated for later erasure purposes, that extent is clipped to the screen. This is due to the lack of clipping in the rectangle fill code from Listing 47.5 in Chapter 47; the problem would more appropriately be addressed by putting clipping into the fill code, but, unfortunately, I lack the space to do that here.

      Finally, observe the jaggies crawling along the edges of the polygon as it rotates. This is temporal aliasing at its finest! We won’t address antialiasing further, realtime antialiasing being decidedly nontrivial, but this should give you an idea of why antialiasing is so desirable.

      -

      An Ongoing Journey

      +

      An Ongoing Journey

      In the next chapter, we’ll assign fronts and backs to polygons, and start drawing only those that are facing the viewer. That will enable us to handle convex polyhedrons, such as tetrahedrons and cubes. We’ll also look at interactively controllable rotation, and at more complex rotations than the simple rotation around the Y axis that we did this time. In time, we’ll use fixed-point arithmetic to speed things up, and do some shading and texture mapping. The journey has only begun; we’ll get to all that and more soon.


      @@ -58,7 +58,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-01.html b/51-01.html index e98a118..8bc2f9e 100644 --- a/51-01.html +++ b/51-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,9 +36,8 @@


      -

      Chapter 51
      Sneakers in Space -

      -

      Using Backface Removal to Eliminate Hidden Surfaces

      +

      Chapter 51
      Sneakers in Space

      +

      Using Backface Removal to Eliminate Hidden Surfaces

      As I’m fond of pointing out, computer animation isn’t a matter of mathematically exact modeling or raw technical prowess, but rather of fooling the eye and the mind. That’s especially true for 3-D animation, where we’re not only trying to convince viewers that they’re seeing objects on a screen—when in truth that screen contains no objects at all, only gaggles of pixels—but we’re also trying to create the illusion that the objects exist in three-space, possessing four dimensions (counting movement over time as a fourth dimension) of their own. To make this magic happen, we must provide cues for the eye not only to pick out boundaries, but also to detect depth, orientation, and motion. This involves perspective, shading, proper handling of hidden surfaces, and rapid and smooth screen updates; the whole deal is considerably more difficult to pull off on a PC than 2-D animation.

      In some senses, however, 3-D animation is easier than 2-D. Because there’s more going on in 3-D animation, the eye and brain tend to make more assumptions, and so are more apt to see what they expect to see, rather than what’s actually there. @@ -47,7 +46,7 @@

      To what extent can you rely on the eye and mind to make up for imperfections in the 3-D animation process? In some areas, hardly at all; for example, jaggies crawling along edges stick out like red flags, and likewise for flicker. In other areas, though, the human perceptual system is more forgiving than you’d think. Consider this: At the end of Return of the Jedi, in the battle to end all battles around the Death Star, there is a sequence of about five seconds in which several spaceships are visible in the background. One of those spaceships (and it’s not very far in the background, either) looks a bit unusual. What it looks like is a sneaker. In fact, it is a sneaker—but unless you know to look for it, you’ll never notice it, because your mind is busy making simplifying assumptions about the complex scene it’s seeing—and one of those assumptions is that medium-sized objects floating in space are spaceships, unless proven otherwise. (Thanks to Chris Hecker for pointing this out. I’d never have noticed the sneaker, myself, without being tipped off—which is, of course, the whole point.)

      If it’s good enough for George Lucas, it’s good enough for us. And with that, let’s resume our quest for realtime 3-D animation on the PC.

      -

      One-sided Polygons: Backface Removal

      +

      One-sided Polygons: Backface Removal

      In the previous chapter, we implemented the basic polygon drawing pipeline, transforming a polygon all the way from its basic definition in object space, through the shared 3-D world space, and into the 3-D space as seen from the viewpoint, called view space. From view space, we performed a perspective projection to convert the polygon into screen space, then mapped the transformed and projected vertices to the nearest screen coordinates and filled the polygon. Armed with code that implemented this pipeline, we were able to watch as a polygon rotated about its Y axis, and were able to move the polygon around in space freely.

      One of the drawbacks of the previous chapter’s approach was that the polygon had two visible sides. Why is that a drawback? It isn’t, necessarily, but in our case we want to use polygons to build solid objects with continuous surfaces, and in that context, only one side of a polygon is visible; the other side always faces the inside of the object, and can never be seen. It would save time and simplify the process of hidden surface removal if we could quickly and easily determine whether the inside or outside face of each polygon was facing us, so that we could draw each polygon only if it were visible (that is, had the outside face pointing toward the viewer). On average, half the polygons in an object could be instantly rejected by a test of this sort. Such testing of polygon visibility goes by a number of names in the literature, including backplane culling, backface removal, and assorted variations thereon; I’ll refer to it as backface removal.


      @@ -62,7 +61,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-02.html b/51-02.html index 1562340..8a0b87f 100644 --- a/51-02.html +++ b/51-02.html @@ -24,7 +24,7 @@ - +
      @@ -42,18 +42,18 @@

      Given that I’ve convinced you that backface removal would be a handy thing to have, how do we actually do it? A logical approach, often implemented in the PC literature, would be to calculate the plane equation for the plane in which the polygon lies, and see which way the normal (perpendicular) vector to the plane points. That works, but there’s a more efficient way to calculate the normal to the polygon: as the cross-product of two of the polygon’s edges.

      The cross-product of two vectors is defined as the vector shown in Figure 51.1. One interesting property of the cross-product vector is that it is perpendicular to the plane in which the two original vectors lie. If we take the cross-product of the vectors that form two edges of a polygon, the result will be a vector perpendicular to the polygon; then, we’ll know that the polygon is visible if and only if the cross-product vector points toward the viewer. We need one more thing to make the cross-product approach work, though. The cross-product can actually point either way, depending on which edges of the polygon we choose to work with and the order in which we evaluate them, so we must establish some conventions for defining polygons and evaluating the cross-product.


      Figure 51.1
        The cross-product of two vectors. +
      -->Figure 51.1  The cross-product of two vectors.

      We’ll define only convex polygons, with the vertices defined in clockwise order, as viewed from the outside; that is, if you’re looking at the visible side of the polygon, the vertices will appear in the polygon definition in clockwise order. With those assumptions, the cross-product becomes a quick and easy indicator of polygon orientation with respect to the viewer; we’ll calculate it as the cross-product of the first and last vectors in a polygon, as shown in Figure 51.2, and if it’s pointing toward the viewer, we’ll know that the polygon is visible. Actually, we don’t even have to calculate the entire cross-product vector, because the Z component alone suffices to tell us which way the polygon is facing: positive Z means visible, negative Z means not. The Z component can be calculated very efficiently, with only two multiplies and a subtraction.

      The question remains of the proper space in which to perform backface removal. There’s a temptation to perform it in view space, which is, after all, the space defined with respect to the viewer, but view space is not a good choice. Screen space—the space in which perspective projection has been performed—is the best choice. The purpose of backface removal is to determine whether each polygon is visible to the viewer, and, despite its name, view space does not provide that information; unlike screen space, it does not reflect perspective effects.


      Figure 51.2
        Using the cross product to generate a polygon normal. +
      -->Figure 51.2  Using the cross product to generate a polygon normal.

      Backface removal may also be performed using the polygon vertices in screen coordinates, which are integers. This is less accurate than using the screen space coordinates, which are floating point, but is, by the same token, faster. In Listing 51.3, which we’ll discuss shortly, backface removal is performed in screen coordinates in the interests of speed.

      Backface removal, as implemented in Listing 51.3, will not work reliably if the polygon is not convex, if the vertices don’t appear in clockwise order, if either the first or last edge in a polygon has zero length, or if the first and last edges are collinear. These latter two points are the reason it’s preferable to work in screen space rather than screen coordinates (which suffer from rounding problems), speed considerations aside.

      -

      Backface Removal in Action

      +

      Backface Removal in Action

      Listings 51.1 through 51.5 together form a program that rotates a solid cube in real-time under user control. Listing 51.1 is the main program; Listing 51.2 performs transformation and projection; Listing 51.3 performs backface removal and draws visible faces; Listing 51.4 concatenates incremental rotations to the object-to-world transformation matrix; Listing 51.5 is the general header file. Also required from previous chapters are: Listings 50.1 and 50.2 from Chapter 50 (draw clipped line list, matrix math functions); Listings 47.1 and 47.6 from Chapter 47, (Mode X mode set, rectangle fill); Listing 49.6 from Chapter 49; Listing 39.4 from Chapter 39 (polygon edge scan); and the FillConvexPolygon() function from Listing 38.1 from Chapter 38. All necessary modules, along with a project file, will be present in the subdirectory for this chapter on the listings diskette, whether they were presented in this chapter or some earlier chapter. This may crowd the listings diskette a little bit, but it will certainly reduce confusion!


      @@ -67,7 +67,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-03.html b/51-03.html index d0482e4..2a1ab66 100644 --- a/51-03.html +++ b/51-03.html @@ -24,7 +24,7 @@ - +
      @@ -214,7 +214,7 @@ void main() {
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-04.html b/51-04.html index 4d82f41..2cdf158 100644 --- a/51-04.html +++ b/51-04.html @@ -24,7 +24,7 @@ - +
      @@ -139,11 +139,11 @@ void DrawVisibleFaces(struct Object * ObjectToXform)

      The sample program, as shown in Figure 51.3, places a cube, floating in three-space, under the complete control of the user. The arrow keys may be used to move the cube left, right, up, and down, and the A and T keys may be used to move the cube away from or toward the viewer. The F1 and F2 keys perform rotation around the Z axis, the axis running from the viewer straight into the screen. The 4 and 6 keys perform rotation around the Y (vertical) axis, and the 2 and 8 keys perform rotation around the X axis, which runs horizontally across the screen; the latter four keys are most conveniently used by flipping the keypad to the numeric state.


      Figure 51.3
        Sample screens from the 3-D cube program. +
      -->Figure 51.3  Sample screens from the 3-D cube program.

      The demo involves six polygons, one for each side of the cube. Each of the polygons must be transformed and projected, so it would seem that 24 vertices (four for each polygon) must be handled, but some steps have been taken to improve performance. All vertices for the object have been stored in a single list; the definition of each face contains not the vertices for that face themselves, but rather indexes into the object’s vertex list, as shown in Figure 51.4. This reduces the number of vertices to be manipulated from 24 to 8, for there are, after all, only eight vertices in a cube, with three faces sharing each vertex. In this way, the transformation burden is lightened by two-thirds. Also, as mentioned earlier, backface removal is performed with integers, in screen coordinates, rather than with floating-point values in screen space. Finally, the RecalcXForm flag is set whenever the user changes the object-to-world transformation. Only when this flag is set is the full object-to-view transformation recalculated and the object’s vertices transformed and projected again; otherwise, the values already stored within the object are reused. In the sample application, this brings no visual improvement, because there’s only the one object, but the underlying mechanism is sound: In a full-blown 3-D animation application, with multiple objects moving about the screen, it would help a great deal to flag which of the objects had moved with respect to the viewer, performing a new transformation and projection only for those that had.


      Figure 51.4
        The object data structure +
      -->Figure 51.4  The object data structure


      @@ -157,7 +157,7 @@ void DrawVisibleFaces(struct Object * ObjectToXform)
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-05.html b/51-05.html index ee0cfba..f14efb3 100644 --- a/51-05.html +++ b/51-05.html @@ -24,7 +24,7 @@ - +
      @@ -39,7 +39,7 @@

      With the above optimizations, the sample program is certainly adequately responsive on a 20 MHz 386 (sans 387; I’m sure it’s wonderfully responsive with a math coprocessor). Still, it couldn’t quite keep up with the keyboard when I modified it to read only one key each time through the loop—and we’re talking about only eight vertices here. This indicates that we’re already near the limit of animation complexity possible with our current approach. It’s time to start rethinking that approach; over two-thirds of the overall time is spent in floating-point calculations, and it’s there that we’ll begin to attack the performance bottleneck we find ourselves up against.

      -

      Incremental Transformation

      +

      Incremental Transformation

      Listing 51.4 contains three functions; each concatenates an additional rotation around one of the three axes to an existing rotation. To improve performance, only the matrix entries that are affected in a rotation around each particular axis are recalculated (all but four of the entries in a single-axis rotation matrix are either 0 or 1, as shown in Chapter 50). This cuts the number of floating-point multiplies from the 64 required for the multiplication of two 4x4 matrices to just 12, and floating point adds from 48 to 6.

      Be aware that Listing 51.4 performs an incremental rotation on top of whatever rotation is already in the matrix. The cube may already have been turned left, right, up, down, and sideways; regardless, Listing 51.4 just tacks the specified rotation onto whatever already exists. In this way, the object-to-world transformation matrix contains a history of all the rotations ever specified by the user, concatenated one after another onto the original matrix. Potential loss of precision is a problem associated with using such an approach to represent a very long concatenation of transformations, especially with fixed-point arithmetic; that’s not a problem for us yet, but we’ll run into it eventually.

      @@ -122,7 +122,7 @@
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/51-06.html b/51-06.html index 14357d3..f8fc10c 100644 --- a/51-06.html +++ b/51-06.html @@ -24,7 +24,7 @@ - +
      @@ -123,9 +123,9 @@ extern int DisplayedPage, NonDisplayedPage; extern struct Rect EraseRect[]; -

      A Note on Rounding Negative Numbers

      +

      A Note on Rounding Negative Numbers

      In the previous chapter, I added 0.5 and truncated in order to round values from floating-point to integer format. Here, in Listing 51.2, I’ve switched to adding 0.5 and using the floor() function. For positive values, the two approaches are equivalent; for negative values, only the floor() approach works properly.

      -

      Object Representation

      +

      Object Representation

      Each object consists of a list of vertices and a list of faces, with the vertices of each face defined by pointers into the vertex list; this allows each vertex to be transformed exactly once, even though several faces may share a single vertex. Each object contains the vertices not only in their original, untransformed state, but in three other forms as well: transformed to view space, transformed and projected to screen space, and converted to screen coordinates. Earlier, we saw that it can be convenient to store the screen coordinates within the object, so that if the object hasn’t moved with respect to the viewer, it can be redrawn without the need for recalculation, but why bother storing the view and screen space forms of the vertices as well?

      The screen space vertices are useful for some sorts of hidden surface removal. For example, to determine whether two polygons overlap as seen by the viewer, you must first know how they look to the viewer, accounting for perspective; screen space provides that information. (So do the final screen coordinates, but with less accuracy, and without any Z information.) The view space vertices are useful for collision and proximity detection; screen space can’t be used here, because objects are distorted by the perspective projection into screen space. World space would serve as well as view space for collision detection, but because it’s possible to transform directly from object space to view space with a single matrix, it’s often preferable to skip over world space. It’s not mandatory that vertices be stored for all these different spaces, but the coordinates in all those spaces have to be calculated as intermediate steps anyway, so we might as well keep them around for those occasions when they’re needed.


      @@ -141,7 +141,7 @@ extern struct Rect EraseRect[];
      -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
      diff --git a/52-01.html b/52-01.html index c934cfb..9dfbecf 100644 --- a/52-01.html +++ b/52-01.html @@ -24,7 +24,7 @@ - +
      @@ -36,16 +36,15 @@


      -

      Chapter 52
      Fast 3-D Animation: Meet X-Sharp -

      -

      The First Iteration of a Generalized 3-D Animation Package

      +

      Chapter 52
      Fast 3-D Animation: Meet X-Sharp

      +

      The First Iteration of a Generalized 3-D Animation Package

      Across the lake from Vermont, a few miles into upstate New York, the Ausable River has carved out a fairly impressive gorge known as “Ausable Chasm.” Impressive for the East, anyway; you might think of it as the poor man’s Grand Canyon. Some time back, I did the tour with my wife and five-year-old, and it was fun, although I confess that I didn’t loosen my grip on my daughter’s hand until we were on the bus and headed for home; that gorge is deep, and the railings tend to be of the single-bar, rusted-out variety.

      New Yorkers can drive straight to this wonder of nature, but Vermonters must take their cars across on the ferry; the alternative is driving three hours around the south end of Lake Champlain. No problem; the ferry ride is an hour well spent on a beautiful lake. Or, rather, no problem—once you’re on the ferry. Getting to New York is easy, but, as we found out, the line of cars waiting to come back from Ausable Chasm gets lengthy about mid-afternoon. The ferry can hold only so many cars, and we wound up spending an unexpected hour exploring the wonders of the ferry docks. Not a big deal, with a good-natured kid and an entertaining mom; we got ice cream, explored the beach, looked through binoculars, and told stories. It was a fun break, actually, and before we knew it, the ferry was steaming back to pick us up.

      A friend of mine, an elementary-school teacher, helped take 65 sixth graders to Ausable Chasm. Never mind the potential for trouble with 65 kids loose on a ferry. Never mind what it was like trying to herd that group around a gorge that looks like it was designed to swallow children and small animals without a trace. The hard part was getting back to the docks and finding they’d have to wait an hour for the next ferry. As my friend put it, “Let me tell you, an hour is an eternity with 65 sixth graders screaming the song ‘You Are My Sunshine.’”

      Apart from reminding you how lucky you are to be working in a quiet, air-conditioned room, in front of a gently humming computer, free to think deep thoughts and eat Cheetos to your heart’s content, this story provides a useful perspective on the malleable nature of time. An hour isn’t just an hour—it can be forever, or it can be the wink of an eye. Just think of the last hour you spent working under a deadline; I bet it went past in a flash. Which is not to say, mind you, that I recommend working in a bus full of screaming kids in order to make time pass more slowly; there are quality issues here as well.

      In our 3-D animation work so far, we’ve used floating-point arithmetic. Floating-point arithmetic—even with a floating-point processor but especially without one—is the microcomputer animation equivalent of working in a school bus: It takes forever to do anything, and you just know you’re never going to accomplish as much as you want to. In this chapter, we’ll address fixed-point arithmetic, which will give us an instant order-of-magnitude performance boost. We’ll also give our 3-D animation code a much more powerful and extensible framework, making it easy to add new and different sorts of objects. Taken together, these alterations will let us start to do some really interesting real-time animation.

      -

      This Chapter’s Demo Program

      +

      This Chapter’s Demo Program

      Three-dimensional animation is a complicated business, and it takes an astonishing amount of functionality just to get off the launching pad: page flipping, polygon filling, clipping, transformations, list management, and so forth. I’ve been building toward a critical mass of animation functionality over the course of this book, and this chapter’s code builds on the code from no fewer than five previous chapters. The code that’s required in order to link this chapter’s animation demo program is the following:

        @@ -69,7 +68,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-02.html b/52-02.html index 59ecd64..249fe92 100644 --- a/52-02.html +++ b/52-02.html @@ -24,7 +24,7 @@ - +
        @@ -176,7 +176,7 @@ void XformAndProjectPObject(PObject * ObjectToXform)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-03.html b/52-03.html index 64b02e3..500ead5 100644 --- a/52-03.html +++ b/52-03.html @@ -24,7 +24,7 @@ - +
        @@ -213,7 +213,7 @@ void InitializeFixedPoint()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-04.html b/52-04.html index bbfa45e..b5473c6 100644 --- a/52-04.html +++ b/52-04.html @@ -24,7 +24,7 @@ - +
        @@ -153,7 +153,7 @@ void DrawPObject(PObject * ObjectToXform)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-05.html b/52-05.html index 0c63d52..27d8101 100644 --- a/52-05.html +++ b/52-05.html @@ -24,7 +24,7 @@ - +
        @@ -176,7 +176,7 @@ void InitializeCubes()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-06.html b/52-06.html index 0767093..0c3f483 100644 --- a/52-06.html +++ b/52-06.html @@ -24,7 +24,7 @@ - +
        @@ -230,7 +230,7 @@ extern Point3 CubeVerts[];
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-07.html b/52-07.html index a038967..709b260 100644 --- a/52-07.html +++ b/52-07.html @@ -24,7 +24,7 @@ - +
        @@ -36,13 +36,13 @@


        -

        A New Animation Framework: X-Sharp

        +

        A New Animation Framework: X-Sharp

        Listings 52.1 through 52.10 shown earlier represent not merely faster animation in library form, but also a nearly complete, extensible, data-driven animation framework. Whereas much of the earlier animation code I’ve presented in this book was hardwired to demonstrate certain concepts, this chapter’s code is intended to serve as the basis for a solid animation package. Objects are stored, in their entirety, in customizable structures; new structures can be devised for new sorts of objects. Drawing, preparing for drawing, and moving are all vectored functions, so that variations such as shading or texturing, or even radically different sorts of graphics objects, such as scaled bitmaps, could be supported. The cube initialization is entirely data driven; more or different cubes, or other sorts of convex polyhedrons, could be added by simply changing the initialization data in Listing 52.8.

        Somewhere along the way in writing the material that became this section of the book, I realized that I had a generally useful animation package by the tail and gave it a name: X-Sharp. (X for Mode X, sharp because good animation looks sharp, and, well, who would want a flat animation package?)

        Note that the X-Sharp library as presented in this chapter (and, indeed, in this book) is not a fully complete 3-D library. Movement is supported only along the Z axis in this chapter’s version, and then in a non-general fashion. More interesting movement isn’t supported at this point because of one of the two missing features in X-Sharp: hidden-surface removal. (The other missing feature is general 3-D clipping.) Without hidden surface removal, nothing can safely overlap. It would actually be easy enough to perform hidden-surface removal by keeping the cubes in different Z bands and drawing them back to front, but this gets into sorting and list issues, and is not a complete solution—and I’ve crammed as much as will fit into one chapter’s code, anyway.

        I’m working toward a goal in this last section of the book, and there are many lessons to be learned and stories to be told along the way. So as X-Sharp grows, you’ll find its evolving implementations in the chapter subdirectories on the listings diskette. This chapter’s subdirectory, for example, contains the self-extracting archive file XSHARP14.EXE, (to extract its contents you simply run it as though it were a program) and the code in that archive is the code I’m speaking of specifically in this chapter, with all the limitations mentioned above. Chapter 53’s subdirectory, however, contains the file XSHARP15.EXE, which is the next step in the evolution of X-Sharp, and it is the version that I’ll be specifically talking about in that chapter. Later chapters will have their own implementations in their respective chapter subdirectories, in files of the form XSHARPxx.EXE, where xx is an ascending number indicating the version. The final and most recent X-Sharp version will be present in its own subdirectory called XSHARP22. If you’re intending to use X-Sharp in a real project, use the most recent version to be sure that you avail yourself of all new features and bug fixes.

        -

        Three Keys to Realtime Animation Performance

        +

        Three Keys to Realtime Animation Performance

        As of the previous chapter, we were at the point where we could rotate, move, and draw a solid cube in real time. Not too shabby...but the code I’m presenting in this chapter goes a bit further, rotating 12 solid cubes at an update rate of about 15 frames per second (fps) on a 20 MHz 386 with a slow VGA. That’s 12 transformation matrices, 72 polygons, and 96 vertices being handled in real time; not Star Wars, granted, but a giant step beyond a single cube. Run the program if you get a chance; you may be surprised at just how effective this level of animation is. I’d like to point out, in case anyone missed it, that this is fully general 3-D. I’m not using any shortcuts or tricks, like prestoring coordinates or pregenerating bitmaps; if you were to feed in different rotations or vertices, the animation would change accordingly.


        @@ -56,7 +56,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/52-08.html b/52-08.html index 528d303..73f146d 100644 --- a/52-08.html +++ b/52-08.html @@ -24,7 +24,7 @@ - +
        @@ -41,10 +41,10 @@

        The second performance key is the use of the 386’s native 32-bit multiply and divide instructions. C compilers operating in real mode call library routines to perform multiplications and divisions involving 32-bit values, and those library functions are fairly slow, especially for division. On a 386, 32-bit multiplication and division can be handled with the bit of code in Listing 52.9—and most of even that code is only for rounding.

        The third performance key is maintaining and operating on only the relevant portions of transformation matrices and coordinates. The bottom row of every transformation matrix we’ll use (in this book) is [0 0 0 1], so why bother using or recalculating it when concatenating transforms and transforming points? Likewise for the fourth element of a 3-D vector in homogeneous coordinates, which is always 1. Basically, transformation matrices are treated as consisting of a 3x3 rotation matrix and a 3x1 translation vector, and coordinates are treated as 3x1 vectors. This saves a great many multiplications in the course of transforming each point.

        Just for fun, I reimplemented the animation of Listings 52.1 through 52.10 with floating-point instructions. Together, the preceeding optimizations improve the performance of the entire animation—including drawing time and overhead, and not just math—by more than ten times over the code that uses the floating-point emulator. Amazing what one can accomplish with a few dozen lines of assembly and a switch in number format, isn’t it? Note that no assembly code other than the native 386 multiply and divide is used in Listings 52.1 through 52.10, although the polygon fill code is of course mostly in assembly; we’ve achieved 12 cubes animated at 15 fps while doing the 3-D work almost entirely in Borland C++, and we’re still doing sine and cosine via the floating-point emulator. Happily, we’re still nowhere near the upper limit on the animation potential of the PC.

        -

        Drawbacks

        +

        Drawbacks

        The techniques we’ve used to turbocharge 3-D animation are very powerful, but there’s a dark side to them as well. Obviously, native 386 instructions won’t work on 8088 and 286 machines. That’s rectifiable; equivalent multiplication and division routines could be implemented for real mode and performance would still be reasonable. It sure is nice to be able to plug in a 32-bit IMUL or DIV and be done with it, though. More importantly, 32-bit fixed-point arithmetic has limitations in range and accuracy. Points outside a 64Kx64Kx64K space can’t be handled, imprecision tends to creep in over the course of multiple matrix concatenations, and it’s quite possible to generate the dreaded divide by 0 interrupt if Z coordinates with absolute values less than one are used.

        I don’t have space to discuss these issues in detail, but here are some brief thoughts: The working 64Kx64Kx64K fixed-point space can be paged into a larger virtual space. Imprecision of a pixel or two rarely matters in terms of display quality, and deterioration of concatenated rotations can be corrected by restoring orthogonality, for example by periodically calculating one row of the matrix as the cross-product of the other two (forcing it to be perpendicular to both). Alternatively, transformations can be calculated from scratch each time an object or the viewer moves, so there’s no chance for cumulative error. 3-D clipping with a front clip plane of -1 or less can prevent divide overflow.

        -

        Where the Time Goes

        +

        Where the Time Goes

        The distribution of execution time in the animation code is no longer wildly biased toward transformation, but sine and cosine are certainly still sucking up cycles. Likewise, the overhead in the calls to FixedMul() and FixedDiv() is costly. Much of this is correctable with a little carefully crafted assembly language and a lookup table; I’ll provide that shortly.

        Regardless, with this chapter we have made the critical jump to a usable level of performance and a serviceable general-purpose framework. From here on out, it’s the fun stuff.


        @@ -59,7 +59,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/53-01.html b/53-01.html index db560bc..e5328b2 100644 --- a/53-01.html +++ b/53-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,16 +36,15 @@


        -

        Chapter 53
        Raw Speed and More -

        -

        The Naked Truth About Speed in 3-D Animation

        +

        Chapter 53
        Raw Speed and More

        +

        The Naked Truth About Speed in 3-D Animation

        Years ago, this friend of mine—let’s call him Bert—went to Hawaii with three other fellows to celebrate their graduation from high school. This was an unchaperoned trip, and they behaved pretty much as responsibly as you’d expect four teenagers to behave, which is to say, not; there’s a story about a rental car that, to this day, Bert can’t bring himself to tell. They had a good time, though, save for one thing: no girls.

        By and by, they met a group of girls by the pool, but the boys couldn’t get past the hi-howya-doin stage, so they retired to their hotel room to plot a better approach. This being the early ’70s, and them being slightly tipsy teenagers with raging hormones and the effective combined IQ of four eggplants, it took them no time at all to come up with a brilliant plan: streaking. The girls had mentioned their room number, so the boys piled into the elevator, pushed the button for the girls’ floor, shucked their clothes as fast as they could, and sprinted to the girls’ door. They knocked on the door and ran on down the hall. As the girls opened their door, Bert and his crew raced past, toward the elevator, laughing hysterically.

        Bert was by far the fastest of them all. He whisked between the elevator doors just as they started to close; by the time his friends got there, it was too late, and the doors slid shut in their faces. As the elevator began to move, Bert could hear the frantic pounding of six fists thudding on the closed doors. As Bert stood among the clothes littering the elevator floor, the thought of his friends stuck in the hall, naked as jaybirds, was just too much, and he doubled over with helpless laughter, tears streaming down his face. The universe had blessed him with one of those exceedingly rare moments of perfect timing and execution.

        The universe wasn’t done with Bert quite yet, though. He was still contorted with laughter—and still quite thoroughly undressed—when the elevator doors opened again. On the lobby.

        And with that, we come to this chapter’s topics: raw speed and hidden surfaces.

        -

        Raw Speed, Part 1: Assembly Language

        +

        Raw Speed, Part 1: Assembly Language

        I would like to state, here and for the record, that I am not an assembly language fanatic. Frankly, I prefer programming in C; assembly language is hard work, and I can get a whole lot more done with fewer hassles in C. However, I am a performance fanatic, performance being defined as having programs be as nimble as possible in those areas where the user wants fast response. And, in the course of pursuing performance, there are times when a little assembly language goes a long way.

        We’re now four chapters into development of the X-Sharp 3-D animation package. In realtime animation, performance is sine qua non (Latin for “Make it fast or find another line of work”), so some judiciously applied assembly language is in order. In the previous chapter, we got up to a serviceable performance level by switching to fixed-point math, then implementing the fixed-point multiplication and division functions in assembly in order to take advantage of the 386’s 32-bit capabilities. There’s another area of the program that fairly cries out for assembly language: matrix math. The function to multiply a matrix by a vector (XformVec()) and the function to concatenate matrices (ConcatXforms()) both loop heavily around calls to FixedMul(); a lot of calling and looping can be eliminated by converting these functions to pure assembly language.

        Listing 53.1 is the module FIXED.ASM from this chapter’s iteration of X-Sharp, with XformVec() and ConcatXforms() implemented in assembly language. The code is heavily optimized, to the extent of completely unrolling the loops via macros so that looping is eliminated altogether. FIXED.ASM is highly effective; the time taken for matrix math is now down to the point where it’s a fairly minor component of execution time, representing less than ten percent of the total. It’s time to turn our optimization sights elsewhere.


        @@ -61,7 +60,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/53-02.html b/53-02.html index 9342766..22ecc25 100644 --- a/53-02.html +++ b/53-02.html @@ -24,7 +24,7 @@ - +
        @@ -441,7 +441,7 @@ end
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/53-03.html b/53-03.html index 659d62c..fc8f890 100644 --- a/53-03.html +++ b/53-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,11 +36,11 @@


        -

        Raw Speed, Part II: Look it Up

        +

        Raw Speed, Part II: Look it Up

        It’s a funny thing about Turbo Profiler: Time spent in the Borland C++ 80x87 emulator doesn’t show up directly anywhere that I can see in the timing results. The only way to detect it is by way of the line that reports what percent of total time is represented by all the areas that were profiled; if you’re profiling all areas, whatever’s not explicitly accounted for seems to be the floating-point emulator time. This quirk fooled me for a while, leading me to think sine and cosine weren’t major drags on performance, because the sin() and cos() functions spend most of their time in the emulator, and that time doesn’t show up in Turbo Profiler’s statistics on those functions. Once I figured out what was going on, it turned out that not only were sin() and cos() major drags, they were taking up over half the total execution time by themselves.

        The solution is a lookup table. Listing 53.1 contains a function called CosSin() that calculates both the sine and cosine of an angle, via a lookup table. The function accepts angles in tenths of degrees; I decided to use tenths of degrees rather than radians because that way it’s always possible to look up the sine and cosine of the exact angle requested, rather than approximating, as would be required with radians. Tenths of degrees should be fine enough control for most purposes; if not, it’s easy to alter CosSin() for finer gradations yet. GENCOS.C, the program used to generate the lookup table (COSTABLE.INC), included in Listing 53.1, can be found in the XSHARP22 subdirectory on the listings diskette. GENCOS.C can generate a cosine table with any integral number of steps per degree.

        FIXED.ASM (Listing 53.1) speeds X-Sharp up quite a bit, and it changes the performance balance a great deal. When we started out with 3-D animation, calculation time was the dragon we faced; more than 90 percent of the total time was spent doing matrix and projection math. Additional optimizations in the area of math could still be made (using 32-bit multiplies in the backface-removal code, for example), but fixed-point math, the sine and cosine lookup, and selective assembly optimizations have done a pretty good job already. The bulk of the time taken by X-Sharp is now spent drawing polygons, drawing rectangles (to erase objects), and waiting for the page to flip. In other words, we’ve slain the dragon of 3-D math, or at least wounded it grievously; now we’re back to the dragon of polygon filling. We’ll address faster polygon filling soon, but for the moment, we have more than enough horsepower to have some fun with. First, though, we need one more feature: hidden surfaces.

        -

        Hidden Surfaces

        +

        Hidden Surfaces

        So far, we’ve made a number of simplifying assumptions in order to get the animation to look good; for example, all objects must currently be convex polyhedrons. What’s more, right now, objects can never pass behind or in front of each other. What that means is that it’s time to have a look at hidden surfaces.

        There are a passel of ways to do hidden surfaces. Way off at one end (the slow end) of the spectrum is Z-buffering, whereby each pixel of each polygon is checked as it’s drawn to see whether it’s the frontmost version of the pixel at those coordinates. At the other end is the technique of simply drawing the objects in back-to-front order, so that nearer objects are drawn on top of farther objects. The latter approach, depth sorting, is the one we’ll take today. (Actually, true depth sorting involves detecting and resolving possible ambiguities when objects overlap in Z; in this chapter, we’ll simply sort the objects on Z and leave it at that.)

        @@ -48,7 +48,7 @@

        For photo-realistic rendering, these are serious problems. For fast PC-based animation, however, they’re manageable. Choose objects that aren’t too elongated; arrange their paths of travel so they don’t intersect in problematic ways; and, if they do overlap incorrectly, trust that the glitch will be lost in the speed of the animation and the complexity of the screen.

        Listing 53.2 shows X-Sharp file OLIST.C, which includes the key routines for depth sorting. Objects are now stored in a linked list. The initial, empty list, created by InitializeObjectList(), consists of a sentinel entry at either end, one at the farthest possible z coordinate, and one at the nearest. New entries are inserted by AddObject() in z-sorted order. Each time the objects are moved, before they’re drawn at their new locations, SortObjects() is called to Z-sort the object list, so that drawing will proceed from back to front. The Z-sorting is done on the basis of the objects’ center points; a center-point field has been added to the object structure to support this, and the center point for each object is now transformed along with the vertices. That’s really all there is to depth sorting—and now we can have objects that overlap in X and Y.


        Figure 53.1
          Why back-to-front sorting doesn’t always work properly. +
        -->Figure 53.1  Why back-to-front sorting doesn’t always work properly.


        @@ -62,7 +62,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/53-04.html b/53-04.html index 9ad17b2..47ab5c9 100644 --- a/53-04.html +++ b/53-04.html @@ -24,7 +24,7 @@ - +
        @@ -123,10 +123,10 @@ void SortObjects() } -

        Rounding

        +

        Rounding

        FIXED.ASM contains the equate ROUNDING-ON. When this equate is 1, the results of multiplications and divisions are rounded to the nearest fixed-point values; when it’s 0, the results are truncated. The difference between the results produced by the two approaches is, at most, 2-16; you wouldn’t think that would make much difference, now, would you? But it does. When the animation is run with rounding disabled, the cubes start to distort visibly after a few minutes, and after a few minutes more they look like they’ve been run over. In contrast, I’ve never seen any significant distortion with rounding on, even after a half-hour or so. I think the difference with rounding is not that it’s so much more accurate, but rather that the errors are evenly distributed; with truncation, the errors are biased, and biased errors become very visible when they’re applied to right-angle objects. Even with rounding, though, the errors will eventually creep in, and reorthogonalization will become necessary at some point.

        -

        The performance cost of rounding is small, and the benefits are highly visible. Still, truncation errors become significant only when they accumulate over time, as, for example, when rotation matrices are repeatedly concatenated over the course of many transformations. Some time could be saved by rounding only in such cases. For example, division is performed only in the course of projection, and the results do not accumulate over time, so it would be reasonable to disable rounding for division.

        Having a Ball

        -

        +

        The performance cost of rounding is small, and the benefits are highly visible. Still, truncation errors become significant only when they accumulate over time, as, for example, when rotation matrices are repeatedly concatenated over the course of many transformations. Some time could be saved by rounding only in such cases. For example, division is performed only in the course of projection, and the results do not accumulate over time, so it would be reasonable to disable rounding for division.

        +

        Having a Ball

        So far in our exploration of 3-D animation, we’ve had nothing to look at but triangles and cubes. It’s time for something a little more visually appealing, so the demonstration program now features a 72-sided ball. What’s particularly interesting about this ball is that it’s created by the GENBALL.C program in the BALL subdirectory of X-Sharp, and both the size of the ball and the number of bands of faces are programmable. GENBALL.C spits out to a file all the arrays of vertices and faces needed to create the ball, ready for inclusion in INITBALL.C. True, if you change the number of bands, you must change the Colors array in INITBALL.C to match, but that’s a tiny detail; by and large, the process of generating a ball-shaped object is now automated. In fact, we’re not limited to ball-shaped objects; substitute a different vertex and face generation program for GENBALL.C, and you can make whatever convex polyhedron you want; again, all you have to do is change the Colors array correspondingly. You can easily create multiple versions of the base object, too; INITCUBE.C is an example of this, creating 11 different cubes.

        What we have here is the first glimmer of an object-editing system. GENBALL.C is the prototype for object definition, and INITBALL.C is the prototype for general-purpose object instantiation. Certainly, it would be nice to someday have an interactive 3-D object editing tool and resource management setup. We have our hands full with the drawing end of things at the moment, though, and for now it’s enough to be able to create objects in a semiautomated way.


        @@ -141,7 +141,7 @@ void SortObjects()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/54-01.html b/54-01.html index 4cf984d..c737968 100644 --- a/54-01.html +++ b/54-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,12 +36,11 @@


        -

        Chapter 54
        3-D Shading -

        -

        Putting Realistic Surfaces on Animated 3-D Objects

        +

        Chapter 54
        3-D Shading

        +

        Putting Realistic Surfaces on Animated 3-D Objects

        At the end of the previous chapter, X-Sharp had just acquired basic hidden-surface capability, and performance had been vastly improved through the use of fixed-point arithmetic. In this chapter, we’re going to add quite a bit more: support for 8088 and 80286 PCs, a general color model, and shading. That’s an awful lot to cover in one chapter (actually, it’ll spill over into the next chapter), so let’s get to it!

        -

        Support for Older Processors

        +

        Support for Older Processors

        To date, X-Sharp has run on only the 386 and 486, because it uses 32-bit multiply and divide instructions that sub-386 processors don’t support. I chose 32-bit instructions for two reasons: They’re much faster for 16.16 fixed-point arithmetic than any approach that works on the 8088 and 286; and they’re much easier to implement than any other approach. In short, I was after maximum performance, and I was perhaps just a little lazy.

        I should have known better than to try to sneak this one by you. The most common feedback I’ve gotten on X-Sharp is that I should make it support the 8088 and 286. Well, I can take a hint as well as the next guy. Listing 54.1 is an improved version of FIXED.ASM, containing dual 386/8088 versions of CosSin(), XformVec(), and ConcatXforms(), as well as FixedMul() and FixedDiv().

        @@ -60,7 +59,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/54-02.html b/54-02.html index 120306d..3816b62 100644 --- a/54-02.html +++ b/54-02.html @@ -24,7 +24,7 @@ - +
        @@ -913,7 +913,7 @@ end
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/54-03.html b/54-03.html index be49ba6..fa83082 100644 --- a/54-03.html +++ b/54-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,22 +36,22 @@


        -

        Shading

        +

        Shading

        So far, the polygons out of which our animated objects have been built have had colors of fixed intensities. For example, a face of a cube might be blue, or green, or white, but whatever color it is, that color never brightens or dims. Fixed colors are easy to implement, but they don’t make for very realistic animation. In the real world, the intensity of the color of a surface varies depending on how brightly it is illuminated. The ability to simulate the illumination of a surface, or shading, is the next feature we’ll add to X-Sharp.

        The overall shading of an object is the sum of several types of shading components. Ambient shading is illumination by what you might think of as background light, light that’s coming from all directions; all surfaces are equally illuminated by ambient light, regardless of their orientation. Directed lighting, producing diffuse shading, is illumination from one or more specific light sources. Directed light has a specific direction, and the angle at which it strikes a surface determines how brightly it lights that surface. Specular reflection is the tendency of a surface to reflect light in a mirrorlike fashion. There are other sorts of shading components, including transparency and atmospheric effects, but the ambient and diffuse-shading components are all we’re going to deal with in X-Sharp.

        -

        Ambient Shading

        +

        Ambient Shading

        The basic model for both ambient and diffuse shading is a simple one. Each surface has a reflectivity between 0 and 1, where 0 means all light is absorbed and 1 means all light is reflected. A certain amount of light energy strikes each surface. The energy (intensity) of the light is expressed such that if light of intensity 1 strikes a surface with reflectivity 1, then the brightest possible shading is displayed for that surface. Complicating this somewhat is the need to support color; we do this by separating reflectance and shading into three components each—red, green, and blue—and calculating the shading for each color component separately for each surface.

        Given an ambient-light red intensity of IAred and a surface red reflectance Rred, the displayed red ambient shading for that surface, as a fraction of the maximum red intensity, is simply min(IAredx Rred, 1). The green and blue color components are handled similarly. That’s really all there is to ambient shading, although of course we must design some way to map displayed color components into the available palette of colors; I’ll do that in the next chapter. Ambient shading isn’t the whole shading picture, though. In fact, scenes tend to look pretty bland without diffuse shading.

        -

        Diffuse Shading

        +

        Diffuse Shading

        Diffuse shading is more complicated than ambient shading, because the effective intensity of directed light falling on a surface depends on the angle at which it strikes the surface. According to Lambert’s law, the light energy from a directed light source striking a surface is proportional to the cosine of the angle at which it strikes the surface, with the angle measured relative to a vector perpendicular to the polygon (a polygon normal), as shown in Figure 54.1. If the red intensity of directed light is IDred, the red reflectance of the surface is Rred, and the angle between the incoming directed light and the surface’s normal is theta, then the displayed red diffuse shading for that surface, as a fraction of the largest possible red intensity, is min (IDredxRredxcos(θ), 1).

        That’s easy enough to calculate—but seemingly slow. Determining the cosine of an angle can be sped up with a table lookup, but there’s also the task of figuring out the angle, and, all in all, it doesn’t seem that diffuse shading is going to be speedy enough for our purposes. Consider this, however: According to the properties of the dot product (denoted by the operator “•”, as shown in Figure 54.2), cos(q)=(v•w)/ |v| x |w| ), where v and w are vectors, q is the angle between v and w, and |v| is the length of v. Suppose, now, that v and w are unit vectors; that is, vectors exactly one unit long. Then the above equation reduces to cos(q)=v•w. In other words, we can calculate the cosine between N, the unit-normal vector (one-unit-long perpendicular vector) of a polygon, and L', the reverse of a unit vector describing the direction of a light source, with just three multiplies and two adds. (I’ll explain why the light-direction vector must be reversed later.) Once we have that, we can easily calculate the red diffuse shading from a directed light source as min(IDredxRredx(L'• N), 1) and likewise for the green and blue color components.


        Figure 54.1
          Illumination by a directed light source +
        -->Figure 54.1  Illumination by a directed light source


        Figure 54.2
          The dot product of two vectors. +
        -->Figure 54.2  The dot product of two vectors.

        The overall red shading for each polygon can be calculated by summing the ambient-shading red component with the diffuse-shading component from each light source, as in min((IAredxRred) + (IDred0xRredx(L0' • N)) + (IDred1xRredx(L1' • N)) +..., 1) where IDred0 and L0' are the red intensity and the reversed unit-direction vector, respectively, for spotlight 0. Listing 54.2 shows the X-Sharp module DRAWPOBJ.C, which performs ambient and diffuse shading. Toward the end, you will find the code that performs shading exactly as described by the above equation, first calculating the ambient red, green, and blue shadings, then summing that with the diffuse red, green, and blue shadings generated by each directed light source.


        @@ -66,7 +66,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/54-04.html b/54-04.html index 2c43d16..73908c8 100644 --- a/54-04.html +++ b/54-04.html @@ -24,7 +24,7 @@ - +
        @@ -180,7 +180,7 @@ void DrawPObject(PObject * ObjectToXform)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/54-05.html b/54-05.html index 50ce8a5..86556f4 100644 --- a/54-05.html +++ b/54-05.html @@ -24,7 +24,7 @@ - +
        @@ -36,14 +36,14 @@


        -

        Shading: Implementation Details

        +

        Shading: Implementation Details

        In order to calculate the cosine of the angle between an incoming light source and a polygon’s unit normal, we must first have the polygon’s unit normal. This could be calculated by generating a cross-product on two polygon edges to generate a normal, then calculating the normal’s length and scaling to produce a unit normal. Unfortunately, that would require taking a square root, so it’s not a desirable course of action. Instead, I’ve made a change to X-Sharp’s polygon format. Now, the first vertex in a shaded polygon’s vertex list is the end-point of a unit normal that starts at the second point in the polygon’s vertex list, as shown in Figure 54.3. The first point isn’t one of the polygon’s vertices, but is used only to generate a unit normal. The second point, however, is a polygon vertex. Calculating the difference vector between the first and second points yields the polygon’s unit normal. Adding a unit-normal endpoint to each polygon isn’t free; each of those end-points has to be transformed, along with the rest of the vertices, and that takes time. Still, it’s faster than calculating a unit normal for each polygon from scratch.


        Figure 54.3
          The unit normal in the polygon data structure. +
        -->Figure 54.3  The unit normal in the polygon data structure.


        Figure 54.4
          The reversed light source vector. +
        -->Figure 54.4  The reversed light source vector.

        We also need a unit vector for each directed light source. The directed light sources I’ve implemented in X-Sharp are spotlights; that is, they’re considered to be point light sources that are infinitely far away. This allows the simplifying assumption that all light rays from a spotlight are parallel and of equal intensity throughout the displayed universe, so each spotlight can be represented with a single unit vector and a single intensity. The only trick is that in order to calculate the desired cos(theta) between the polygon unit normal and a spotlight’s unit vector, the direction of the spotlight’s unit vector must be reversed, as shown in Figure 54.4. This is necessary because the dot product implicitly places vectors with their start points at the same location when it’s used to calculate the cosine of the angle between two vectors. The light vector is incoming to the polygon surface, and the unit normal is outbound, so only by reversing one vector or the other will we get the cosine of the desired angle.

        @@ -60,7 +60,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/55-01.html b/55-01.html index 7338f8c..0ec64b0 100644 --- a/55-01.html +++ b/55-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 55
        Color Modeling in 256-Color Mode -

        -

        Pondering X-Sharp’s Color Model in an RGB State of Mind

        +

        Chapter 55
        Color Modeling in 256-Color Mode

        +

        Pondering X-Sharp’s Color Model in an RGB State of Mind

        Once she turned six, my daughter wanted some fairly sophisticated books read to her. Wind in the Willows. Little House on the Prairie. Pretty heady stuff for one so young, and sometimes I wondered how much of it she really understood. As an experiment, during one reading I stopped whenever I came to a word I thought she might not know, and asked her what it meant. One such word was “mulling.”

        “Do you know what ‘mulling’ means?” I asked.

        She thought about it for a while, then said, “Pondering.”

        @@ -47,13 +46,13 @@

        “Okay,” I said, “What does ‘pondering’ mean?”

        “Mulling,” she said.

        What does this anecdote tell us about the universe in which we live? Well, it certainly indicates that this universe is inhabited by at least one comedian and one good straight man. Beyond that, though, it can be construed as a parable about the difficulty of defining things properly; for example, consider the complications inherent in the definition of color on a 256-color display adapter such as the VGA. Coincidentally, VGA color modeling just happens to be this chapter’s topic, and the place to start is with color modeling in general.

        -

        A Color Model

        +

        A Color Model

        We’ve been developing X-Sharp for several chapters now. In the previous chapter, we added illumination sources and shading; that addition makes it necessary for us to have a general-purpose color model, so that we can display the gradations of color intensity necessary to render illuminated surfaces properly. In other words, when a bright light is shining straight at a green surface, we need to be able to display bright green, and as that light dims or tilts to strike the surface at a shallower angle, we need to be able to display progressively dimmer shades of green.

        The first thing to do is to select a color model in which to perform our shading calculations. I’ll use the dot product-based stuff I discussed in the previous chapter. The approach we’ll take is to select an ideal representation of the full color space and do our calculations there, as if we really could display every possible color; only as a final step will we map each desired color into the limited 256-color set of the VGA, or the color range of whatever adapter we happen to be working with. There are a number of color models that we might choose to work with, but I’m going to go with the one that’s both most familiar and, in my opinion, simplest: RGB (red, green, blue).

        In the RGB model, a given color is modeled as the mix of specific fractions of full intensities of each of the three color primaries. For example, the brightest possible pure blue is 0.0*R, 0.0*G, 1.0*B. Half-bright cyan is 0.0*R, 0.5*G, 0.5*B. Quarter-bright gray is 0.25*R, 0.25*G, 0.25*B. You can think of RGB color space as being a cube, as shown in Figure 55.1, with any particular color lying somewhere inside or on the cube.


        Figure 55.1
          The RGB color cube. +
        -->Figure 55.1  The RGB color cube.

        RGB is good for modeling colors generated by light sources, because red, green, and blue are the additive primaries; that is, all other colors can be generated by mixing red, green, and blue light sources. They’re also the primaries for color computer displays, and the RGB model maps beautifully onto the display capabilities of 15- and 24-bpp display adapters, which tend to represent pixels as RGB combinations in display memory.

        @@ -86,7 +85,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/55-02.html b/55-02.html index a9ca22d..6d57fc9 100644 --- a/55-02.html +++ b/55-02.html @@ -24,7 +24,7 @@ - +
        @@ -142,7 +142,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/55-03.html b/55-03.html index 8c35e5a..6414d7e 100644 --- a/55-03.html +++ b/55-03.html @@ -24,7 +24,7 @@ - +
        @@ -70,13 +70,13 @@

        Another approach would be to set up the palette with reasonably good mixes of two primaries but no mixes of three primaries, then use only two-primary colors in your applications (no grays or whites or other three-primary mixes). Or you could choose to shade only selected objects, using part of the palette for a good range of the colors of those objects, and reserving the rest of the palette for the fixed colors of the other, nonshaded objects. Jim Kent, author of Autodesk Animator, suggests dynamically adjusting the palette to the needs of each frame, for example by allocating the colors for each frame on a first-come, first-served basis. That wouldn’t be trivial to do in real time, but it would make for extremely efficient use of the palette.

        Another widely used solution is to set up a 2-2-2, 3-3-2, or 2.6-2.6-2.6 (6 levels per primary) palette, and dither colors. Dithering is an excellent solution, but outside the scope of this book. Take a look at Chapter 13 of Foley and Van Dam (cited in “Further Readings”) for an introduction to color perception and approximation.

        The sad truth is that the VGA’s 256-color palette is an inadequate resource for general RGB shading. The good news is that clever workarounds can make VGA graphics look nearly as good as 24-bpp graphics; but the burden falls on you, the programmer, to design your applications and color mapping to compensate for the VGA’s limitations. To experiment with a different 256-color model in X-Sharp, just change InitializePalette() to set up the desired palette and ModelColorToColorIndex() to map 24-bit RGB triplets into the palette you’ve set up. It’s that simple, and the results can be striking indeed.

        -

        A Bonus from the BitMan

        +

        A Bonus from the BitMan

        Finally, a note on fast VGA text, which came in from a correspondent who asked to be referred to simply as the BitMan. The BitMan passed along a nifty application of the VGA’s under-appreciated write mode 3 that is, under the proper circumstances, the fastest possible way to draw text in any 16-color VGA mode.

        The task at hand is illustrated by Figure 55.2. We want to draw what’s known as solid text, in which the effect is the same as if the cell around each character was drawn in the background color, and then each character was drawn on top of the background box. (This is in contrast to transparent text, where each character is drawn in the foreground color without disturbing the background.) Assume that each character fits in an eight-wide cell (as is the case with the standard VGA fonts), and that we’re drawing text at byte-aligned locations in display memory.

        Solid text is useful for drawing menus, text areas, and the like; basically, it can be used whenever you want to display text on a solid-color background. The obvious way to implement solid text is to fill the rectangle representing the background box, then draw transparent text on top of the background box. However, there are two problems with doing solid text this way. First, there’s some flicker, because for a little while the box is there but the text hasn’t yet arrived. More important is that the background-followed-by-foreground approach accesses display memory three times for each byte of font data: once to draw the background box, once to read display memory to load the latches, and once to actually draw the font pattern. Display memory is incredibly slow, so we’d like to reduce the number of accesses as much as possible. With the BitMan’s approach, we can reduce the number of accesses to just one per font byte, and eliminate flicker, too.


        Figure 55.2
          Drawing solid text. +
        -->Figure 55.2  Drawing solid text.

        The keys to fast solid text are the latches and write mode 3. The latches, as you may recall from earlier discussions in this book, are four internal VGA registers that hold the last bytes read from the VGA’s four planes; every read from VGA memory loads the latches with the values stored at that display memory address across the four planes. Whenever a write is performed to VGA memory, the latches can provide some, none, or all of the bits written to memory, depending on the bit mask, which selects between the latched data and the drawing data on a bit-by-bit basis. The latches solve half our problem; we can fill the latches with the background color, then use them to draw the background box. The trick now is drawing the text pixels in the foreground color at the same time.


        @@ -92,7 +92,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/55-04.html b/55-04.html index e68c6f5..058a6e2 100644 --- a/55-04.html +++ b/55-04.html @@ -24,7 +24,7 @@ - +
        @@ -39,7 +39,7 @@

        This is where it gets a little complicated. In write mode 3 (which incidentally is not available on the EGA), each byte value that the CPU writes to the VGA does not get written to display memory. Instead, it turns into the bit mask. (Actually, it’s ANDed with the Bit Mask register, and the result becomes the bit mask, but we’ll leave the Bit Mask register set to 0xFF, so the CPU value will become the bit mask.) The bit mask selects, on a bit-by-bit basis, between the data in the latches for each plane (the previously loaded background color, in this case) and the foreground color. Where does the foreground color come from, if not from the CPU? From the Set/Reset register, as shown in Figure 55.3. Thus, each byte written by the CPU (font data, presumably) selects foreground or background color for each of eight pixels, all done with a single write to display memory.


        Figure 55.3
          The data path in write mode 3. +
        -->Figure 55.3  The data path in write mode 3.

        I know this sounds pretty esoteric, but think of it this way: The latches hold the background color in a form suitable for writing eight background pixels (one full byte) at a pop. Write mode 3 allows each CPU byte to punch holes in the background color provided by the latches, holes through which the foreground color from the Set/Reset register can flow. The result is that a single write draws exactly the combination of foreground and background pixels described by each font byte written by the CPU. It may help to look at Listing 55.4, which shows The BitMan’s technique in action. And yes, this technique is absolutely worth the trouble; it’s about three times faster than the fill-then-draw approach described above, and about twice as fast as transparent text. So far as I know, there is no faster way to draw text on a VGA.

        @@ -231,7 +231,7 @@ DrawTextString endp
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/56-01.html b/56-01.html index 56a28ab..92713f1 100644 --- a/56-01.html +++ b/56-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 56
        Pooh and the Space Station -

        -

        Using Fast Texture Mapping to Place Pooh on a Polygon

        +

        Chapter 56
        Pooh and the Space Station

        +

        Using Fast Texture Mapping to Place Pooh on a Polygon

        So, here’s where Winnie the Pooh lives: in a space station orbiting Saturn. No, really; I have it straight from my daughter, and an eight-year-old wouldn’t make up something that important, would she? One day she wondered aloud, “Where is the Hundred Acre Wood, exactly?” and before I could give one of those boring parental responses about how it was imaginary—but A.A. Milne probably imagined it to be somewhere near London—my daughter announced that the Hundred Acre Wood was in a space station orbiting Saturn, and there you have it.

        As it turns out, that’s a very good location for the Hundred Acre Wood, leading to many exciting adventures for Pooh and Piglet. Consider the time they went down to the Jupiter gravity level (we’re talking centrifugal force here; the station is spinning, of course) and nearly turned into pancakes of the Pooh and Piglet varieties, respectively. Or the time they drifted out into the free-fall area at the core and had to be rescued by humans with wings strapped on (a tip of the hat to Robert Heinlein here). Or the time they were caught up by the current in the river through the Wood and drifted for weeks around the circumference of the station, meeting many cultures and finding many adventures along the way. (Yes, Farmer’s Riverworld; no one said the stories you tell your children need to be purely original, just interesting.)

        @@ -46,17 +45,17 @@

        Anyway, I bring up Pooh and the space station because the time has come to discuss fast texture mapping. Texture mapping is the process of mapping an image (in our case, a bitmap) onto the surface of a polygon that’s been transformed in the process of 3-D drawing. Up to this point, each polygon we’ve drawn in X-Sharp has been a single, solid color. Over the last couple of chapters we added the ability to shade polygons according to lighting, but each polygon was still a single color. Thus, in order to produce any sort of intricate design, a great many tiny polygons would have to be drawn. That would be very slow, so we need another approach. One such approach is texture mapping; that is, mapping the bitmap containing the desired image onto the pixels contained within the transformed polygon. Done properly, this should make it possible to change X-Sharp’s output from a bland collection of monocolor facets to a lively, detailed, and much more realistic scene.

        “What sort of scene?” you may well ask. This is where Pooh and the space station came in. When I sat down to think of a sample texture-mapping application, it occurred to me that the shaded ball demo we added to X-Sharp recently looked at least a bit like a spinning, spherical space station, and that the single unshaded, yellow polygon looked somewhat like a window in the space station, and it might be a nice example if someone were standing in the window....

        The rest is history.

        -

        Principles of Quick-and-Dirty Texture Mapping

        +

        Principles of Quick-and-Dirty Texture Mapping

        The key to our texture-mapping approach will be to quickly determine what pixel value to draw for each pixel in the transformed destination polygon. These polygon pixel values will be determined by mapping each destination pixel in the transformed polygon back to the image bitmap, via a reverse transformation, and seeing what color resides at the corresponding location in the image bitmap, as shown in Figure 56.1. It might seem more intuitive to map pixels the other way, from the image bitmap to the transformed polygon, but in fact it’s crucial that the mapping proceed backward from the destination to avoid gaps in the final image. With the approach of finding the right value for each destination pixel in turn, via a backward mapping, there’s no way we can miss any destination pixels. On the other hand, with the forward-mapping method, some destination pixels may be skipped or double-drawn, because this is not necessarily a one-to-one or one-to-many mapping. Although we’re not going to take advantage of it now, mapping back to the source makes it possible to average several neighboring image pixels together to calculate the value for each destination pixel; that is, to antialias the image. This can greatly improve texture quality, although it is slower.


        Figure 56.1
          Using reverse transformation to find the source pixel color. +
        -->Figure 56.1  Using reverse transformation to find the source pixel color.

        -

        Mapping Textures Made Easy

        +

        Mapping Textures Made Easy

        To understand how we’re going to map textures, consider Figure 56.2, which maps a bitmapped image directly onto an untransformed polygon. Here, we simply map the origin of the polygon’s untransformed coordinate system somewhere within the image, then map the vertices to the corresponding image pixels. (For simplicity, I’ll assume in this discussion that the polygon’s coordinate system is in units of pixels, but scaling images to polygons is eminently doable. This will become clearer when we look at mapping images onto transformed polygons, next.) Mapping the image to the polygon is then a simple matter of stepping one scan line at a time in both the image and the polygon, each time advancing the X coordinates of the edges according to the slopes of the lines, just as is normally done when filling a polygon. Since the polygon is untransformed, the stepping is identical in both the image and the polygon, and the pixel mapping is one-to-one, so the appropriate part of each scan line of the image can simply be block copied to the destination.


        Figure 56.2
          Mapping a texture onto an untransformed polygon. +
        -->Figure 56.2  Mapping a texture onto an untransformed polygon.

        Now, matters get more complicated. What if the destination polygon is rotated in two dimensions? We no longer have a neat direct mapping from image scan lines to destination polygon scan lines. We still want to draw across each destination scan line, but the proper source pixels for each destination scan line may now track across the source bitmap at an angle, as shown in Figure 56.3. What can we do?

        @@ -73,7 +72,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/56-02.html b/56-02.html index 18d55a9..dfe5241 100644 --- a/56-02.html +++ b/56-02.html @@ -24,7 +24,7 @@ - +
        @@ -38,18 +38,17 @@


        Ah, but what is an “equivalent amount”? Think of it this way. If a destination edge is 100 scan lines high, it will be stepped 100 times. Then, we’ll divide the SourceXWidth and SourceYHeight lengths of the source edge by 100, and add those amounts to the source edge’s coordinates each time the destination is stepped one scan line. Put another way, we have, as usual, arranged things so that in the destination polygon we step DestYHeight times, where DestYHeight is the height of the destination edge. The this approach arranges to step the source image edge DestYHeight times also, to match what the destination is doing.


        Figure 56.3
          Mapping a texture onto a 2-D rotated polygon. +
        -->Figure 56.3  Mapping a texture onto a 2-D rotated polygon.

        Now we’re able to track the coordinates of the polygon edges through the source image in tandem with the destination edges. Stepping across each destination scan line uses precisely the same technique, as shown in Figure 56.4. In the destination, we step DestXWidth times across each scan line of the polygon, once for each pixel on the scan line. (DestXWidth is the horizontal distance between the two edges being scanned on any given scan line.) To match this, we divide SourceXWidth and SourceYHeight (the lengths of the scan line in the source image, as determined by the source edge points we’ve been tracking, as just described) by the width of the destination scan line, DestXWidth, to produce SourceXStep and SourceYStep. Then, we just step DestXWidth times, adding SourceXStep and SourceYStep to SourceX and SourceY each time, and choose the nearest image pixel to (SourceX,SourceY) to copy to (DestX, DestY). (Note that the names used above, such as SourceXWidth, are used for descriptive purposes, and don’t necessarily correspond to the actual variable names used in Listing 56.2.)

        That’s a workable approach for 2-D rotated polygons—but what about 3-D rotated polygons, where the visible dimensions of the polygon can vary with 3-D rotation and perspective projection? First, I’d like to make it clear that texture mapping takes place from the source image to the destination polygon after the destination polygon is projected to the screen. That is, the image will be mapped after the destination polygon is in its final, drawable form. Given that, it should be apparent that the above approach automatically compensates for all changes in the dimensions of a polygon. You see, this approach divides source edges and scan lines into however many steps the destination polygon requires. If the destination polygon is much narrower than the source polygon, as a result of 3-D rotation and perspective projection, we just end up taking bigger steps through the source image and skipping a lot of source image pixels, as shown in Figure 56.5. The upshot is that the above approach handles all transformations and projections effortlessly. It could also be used to scale source images up to fit in larger polygons; all that’s needed is a list of where the polygon’s vertices map into the source image, and everything else happens automatically. In fact, mapping from any polygonal area of a bitmap to any destination polygon will work, given only that the two polygons have the same number of vertices.


        Figure 56.4
          Mapping a horizontal destination scan line back to the source image. +
        -->Figure 56.4  Mapping a horizontal destination scan line back to the source image.


        Figure 56.5
          Mapping a texture onto a narrower polygon. +
        -->Figure 56.5  Mapping a texture onto a narrower polygon.

        -

        Notes on DDA Texture Mapping

        -

        +

        Notes on DDA Texture Mapping

        That’s all there is to quick-and-dirty texture mapping. This technique basically uses a two-stage digital differential analyzer (DDA) approach to step through the appropriate part of the source image in tandem with the normal scan-line stepping through the destination polygon, so I’ll call it “DDA texture mapping.” It’s worth noting that there is no need for any trigonometric functions at all, and only two divides are required per scan line.

        This isn’t a perfect approach, of course. For one thing, it isn’t anywhere near as fast as drawing solid polygons; the speed is more comparable to drawing each polygon as a series of lines. Also, the DDA approach results in far from perfect image quality, since source pixels may be skipped or selected twice. I trust, however, that you can see how easy it would be to improve image quality by antialiasing with the DDA approach. For example, we could simply average the four surrounding pixels as we did for simple, unweighted antialiasing in Chapters F, G,Chapter K on the companion CD-ROM. Or, we could take a Wu antialiasing approach (see Chapter 57) and average the two bracketing pixels along each axis according to proximity. If we had cycles to waste (which, given that this is real-time animation on a PC, we don’t), we could improve image quality by putting the source pixels through a low-pass filter sized in X and Y according to the ratio of the source and destination dimensions (that is, how much the destination is scaled up or down from the source).

        Even more important is that the sort of texture mapping I’ll do in X-Sharp doesn’t correct for perspective. That doesn’t much matter for small polygons or polygons that are nearly parallel to the screen in 3-space, but it can produce very noticeable bowing of textures on large polygons at an angle to the screen. Perspective texture mapping is a complex subject that’s outside the scope of this book, but you should be aware of its existence, because perspective texture mapping is a key element of many games these days.

        @@ -67,7 +66,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/56-03.html b/56-03.html index 210eccb..aa24cbd 100644 --- a/56-03.html +++ b/56-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Fast Texture Mapping: An Implementation

        +

        Fast Texture Mapping: An Implementation

        As you might expect, I’ve implemented DDA texture mapping in X-Sharp, and the changes are reflected in the X-Sharp archive in this chapter’s subdirectory on the listings disk. Listing 56.1 shows the new header file entries, and Listing 56.2 shows the actual texture-mapped polygon drawer. The set-pixel routine that Listing 56.2 calls is a slight modification of the Mode X set-pixel routine from Chapter 47. In addition, INITBALL.C has been modified to create three texture-mapped polygons and define the texture bitmaps, and modifications have been made to allow the user to flip the axis of rotation. You will of course need the complete X-Sharp library to see texture mapping in action, but Listings 56.1 and 56.2 are the actual texture mapping code in its entirety.

        Here’s a major tip: DDA texture mapping looks best on fast-moving surfaces, where the eye doesn’t have time to pick nits with the shearing and aliasing that’s an inevi table by-product of such a crude approach. Compile DEMO1 from the X-Sharp archive in this chapter’s subdirectory of the listings disk, and run it. The initial display looks okay, but certainly not great, because the rotational speed is so slow. Now press the S key a few times to speed up the rotation and flip between different rotation axes. I think you’ll be amazed at how much better DDA texture mapping looks at high speed. This technique would be great for mapping textures onto hurtling asteroids or jets, but would come up short for slow, finely detailed movements. @@ -362,7 +362,7 @@ void ScanOutLine(EdgeScan * LeftEdge, EdgeScan * RightEdge)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/57-01.html b/57-01.html index 35ae87c..020f864 100644 --- a/57-01.html +++ b/57-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,20 +36,19 @@


        -

        Chapter 57
        10,000 Freshly Sheared Sheep on the Screen -

        -

        The Critical Role of Experience in Implementing Fast, Smooth Texture Mapping

        +

        Chapter 57
        10,000 Freshly Sheared Sheep on the Screen

        +

        The Critical Role of Experience in Implementing Fast, Smooth Texture Mapping

        I recently spent an hour or so learning how to shear a sheep. Among other things, I learned—in great detail—about the importance of selecting the proper comb for your shears, heard about the man who holds the world’s record for sheep sheared in a day (more than 600, if memory serves), and discovered, Lord help me, the many and varied ways in which the New Zealand Sheep Shearing Board improves the approved sheep-shearing method every year. The fellow giving the presentation did his best, but let’s face it, sheep just aren’t very interesting. If you have children, you’ll know why I was there; if you don’t, there’s no use explaining.

        The chap doing the shearing did say one thing that stuck with me, although it may not sound particularly profound. (Actually, it sounds pretty silly, but bear with me.) He said, “You don’t get really good at sheep shearing for 10 years, or 10,000 sheep.” I’ll buy that. In fact, to extend that morsel of wisdom to the greater, non-ovine-centric universe, it actually takes a good chunk of experience before you get good at anything worthwhile—especially graphics, for a couple of reasons. First, performance matters a lot in graphics, and performance programming is largely a matter of experience. You can’t speed up PC graphics simply by looking in a book for a better algorithm; you have to understand the code C compilers generate, assembly language optimization, VGA hardware, and the performance implications of various graphics-programming approaches and algorithms. Second, computer graphics is a matter of illusion, of convincing the eye to see what you want it to see, and that’s very much a black art based on experience.

        -

        Visual Quality: A Black Hole ... Er, Art

        +

        Visual Quality: A Black Hole ... Er, Art

        Pleasing the eye with realtime computer animation is something less than a science, at least at the PC level, where there’s a limited color palette and no time for antialiasing; in fact, sometimes it can be more than a little frustrating. As you may recall, in the previous chapter I implemented texture mapping in X-Sharp. There was plenty of experience involved there, some of which I didn’t mention. My first implementation was disappointing; the texture maps shimmied and sheared badly, like a loosely affiliated flock of pixels, each marching to its own drummer. Then, I added a control key to speed up the rotation; what a difference! The aliasing problems were still there, but with the faster rotation, the pixels moved too quickly for the eye to pick up on the aliasing; the rotating texture maps, and the rotating ball as a whole, crossed the threshold into being accepted by the eye as a viewed object, rather than simply a collection of pixels.

        The obvious lesson here is that adequate speed is important to convincing animation. There’s another, less obvious side to this lesson, though. I’d been running the texture-mapping demo on a 20 MHz 386 with a slow VGA when I discovered the beneficial effects of greater animation speed. When, some time later, I ran the demo on a 33 MHz 486 with a fast VGA, I found that the faster rotation was too fast! The ball spun so rapidly that the eye couldn’t blend successive images together into continuous motion, much like watching a badly flickering movie.

        So the second lesson is that either too little or too much speed can destroy the illusion. Unless you’re antialiasing, you need to tune the shifting of your images so that they’re in the “sweet spot” of apparent motion, in which the eye is willing to ignore the jumping and aliasing, and blend the images together into continuous motion. Only experience can give you a feel for that sweet spot.
        -

        Fixed-Point Arithmetic, Redux

        +

        Fixed-Point Arithmetic, Redux

        In the previous chapter I added texture mapping to X-Sharp, but lacked space to explain some of its finer points. I’ll pick up the thread now and cover some of those points here, and discuss the visual and performance enhancements that previous chapter’s code needed—and which are now present in the version of X-Sharp in this chapter’s subdirectory on the CD-ROM.

        Back in Chapter 38, I spent a good bit of time explaining exactly which pixels were inside a polygon and which were outside, and how to draw those pixels accordingly. This was important, I said, because only with a precise, consistent way of defining inside and outside would it be possible to draw adjacent polygons without either overlap or gaps between them.

        @@ -70,7 +69,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/57-02.html b/57-02.html index 8e10ae1..fc19f04 100644 --- a/57-02.html +++ b/57-02.html @@ -24,7 +24,7 @@ - +
        @@ -36,12 +36,12 @@


        -

        Texture Mapping: Orientation Independence

        +

        Texture Mapping: Orientation Independence

        The double-DDA texture-mapping code presented in the previous chapter worked adequately, but there were two things about it that left me less than satisfied. One flaw was performance; I’ll address that shortly. The other flaw was the way textures shifted noticeably as the orientations of the polygons onto which they were mapped changed.

        The previous chapter’s code followed the standard polygon inside/outside rule for determining which pixels in the source texture map were to be mapped: Pixels that mapped exactly to the left and top destination edges were considered to be inside, and pixels that mapped exactly to the right and bottom destination edges were considered to be outside. That’s fine for filling polygons, but when copying texture maps, it causes different edges of the texture map to be omitted, depending on the destination orientation, because different edges of the texture map correspond to the right and bottom destination edges, depending on the current rotation. Also, the previous chapter’s code truncated to get integer source coordinates. This, together with the orientation problem, meant that when a texture turned upside down, it slowed one new row and one new column of pixels from the next row and column of the texture map. This asymmetry was quite visible, and not at all the desired effect.


        Figure 57.1
          Gaps caused by mixing fixed-point and all-integer math. +
        -->Figure 57.1  Gaps caused by mixing fixed-point and all-integer math.

        Listing 57.1 is one solution to these problems. This code, which replaces the equivalently named function presented in the previous chapter (and, of course, is present in the X-Sharp archive in this chapter’s subdirectory of the listings disk), makes no attempt to follow the standard polygon inside/outside rules when mapping the source. Instead, it advances a half-step into the texture map before drawing the first pixel, so pixels along all edges are half included. Rounding rather than truncation to texture-map coordinates is also performed. The result is that the texture map stays pretty much centered within the destination polygon as the destination rotates, with a much-reduced level of orientation-dependent asymmetry.

        @@ -120,10 +120,10 @@ void ScanOutLine(EdgeScan * LeftEdge, EdgeScan * RightEdge) } -

        Mapping Textures across Multiple Polygons

        +

        Mapping Textures across Multiple Polygons

        One of the truly nifty things about double-DDA texture mapping is that it is not limited to mapping a texture onto a single polygon. A single texture can be mapped across any number of adjacent polygons simply by having polygons that share vertices in 3-space also share vertices in the texture map. In fact, the demonstration program DEMO1 in the X-Sharp archive maps a single texture across two polygons; this is the blue-on-green pattern that stretches across two panels of the spinning ball. This capability makes it easy to produce polygon-based objects with complex surfaces (such as banding and insignia on spaceships, or even human figures). Just map the desired texture onto the underlying polygonal framework of an object, and let double-DDA texture mapping do the rest.

        -

        Fast Texture Mapping

        +

        Fast Texture Mapping

        Of course, there’s a problem with mapping a texture across many polygons: Texture mapping is slow. If you run DEMO1 and move the ball up close to the screen, you’ll see that the ball slows considerably whenever a texture swings around into view. To some extent that can’t be helped, because each pixel of a texture-mapped polygon has to be calculated and drawn independently. Nonetheless, we can certainly improve the performance of texture mapping a good deal over what I presented in the previous chapter.

        By and large, there are two keys to improving PC graphics performance. The first—no surprise—is assembly language. The second, without which assembly language is far less effective, is understanding exactly where the cycles go in inner loops. In our case, that means understanding where the bottlenecks are in Listing 57.1.

        @@ -140,7 +140,7 @@ void ScanOutLine(EdgeScan * LeftEdge, EdgeScan * RightEdge)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/57-03.html b/57-03.html index d7c6bf6..73ee35c 100644 --- a/57-03.html +++ b/57-03.html @@ -24,7 +24,7 @@ - +
        @@ -353,7 +353,7 @@ ScanDone:
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/57-04.html b/57-04.html index 783e655..4934e58 100644 --- a/57-04.html +++ b/57-04.html @@ -24,7 +24,7 @@ - +
        @@ -53,7 +53,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/58-01.html b/58-01.html index 791aba9..8a2842f 100644 --- a/58-01.html +++ b/58-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 58
        Heinlein’s Crystal Ball, Spock’s Brain, and the 9-Cycle Dare -

        -

        Using the Whole-Brain Approach to Accelerate Texture Mapping

        +

        Chapter 58
        Heinlein’s Crystal Ball, Spock’s Brain, and the 9-Cycle Dare

        +

        Using the Whole-Brain Approach to Accelerate Texture Mapping

        I’ve had the pleasure recently of rereading several of the works of Robert A. Heinlein, and I’m as impressed as I was as a teenager—but in a different way. The first time around, I was wowed by the sheer romance of technology married to powerful stories; this time, I’m struck most of all by The Master’s remarkable prescience. “Blowups Happen” is about the risks of nuclear power, and their effects on human psychology—written before a chain reaction had ever happened on this planet. “Solution Unsatisfactory” is about the unsolvable dilemma—ultimate offense, no defense—posed by atomic weapons; this in 1941. And in Between Planets (1951), consider this minor bit of action:

        The doctor’s phone regretted politely that Dr. Jefferson was not at home and requested him to leave a message. He was dictating it when a warm voice interrupted: ‘I’m at home to you, Donald. Where are you, lad?’

        @@ -48,16 +47,16 @@

        Most telling, I think, is that in “Blowups Happen,” the engineers running the nuclear power plant—at considerable risk to both body and sanity—are the best of the best, highly skilled in math and required to ride the nuclear reaction on a second-to-second basis, with the risk of an explosion that might end life on Earth, and would surely kill them, if they slip. Contrast that with our present-day reality of nuclear plants run by generally competent technicians, with the occasional report of shoddy maintenance and bored power-plant employees using drugs, playing games, and falling asleep while on duty. Heinlein’s universe makes for a better story, of course, but, more than that, it shows the filters and biases through which he viewed the world. At least in print, Heinlein was an unwavering believer in science, technology, and rationality, and in his stories it is usually the engineers and scientists who are the heroes and push civilization forward, often kicking and screaming. In the real world, I have rarely observed that to be the case.

        But of course Heinlein was hardly the only person to have his or her perceptions of the universe, past, present, or future, blurred by his built-in assumptions; you and I, as programmers, are also on that list—and probably pretty near the top, at that. Performance programming is basically a process of going from the general to the specific, special-casing the code so that it does just what it has to, and no more. The greatest impediment to this process is seeing the problem in terms of what the code currently does, or what you already know, thereby ignoring many possible solutions. Put another way, how you look at an optimization problem determines how you’ll solve it; your assumptions may speed and simplify the process, but they are also your limitations. Consider, for example, how a seemingly intractable problem becomes eminently tractable the instant you learn that someone else has solved it.

        As Exhibit #1, I present my experience with speeding up the texture mapper in X-Sharp.

        -

        Texture Mapping Redux

        +

        Texture Mapping Redux

        We’ve spent the previous several chapters exploring the X Sharp graphics library, something I built over time as a serious exercise in 3-D graphics. When X-Sharp reached the point at which we left it at the end of the previous chapter, I was rather pleased with it—with one exception.

        My last addition to X-Sharp was a texture mapper, a routine that warped and rotated any desired bitmap to map onto an arbitrary convex polygon. Texture mappers are critical to good 3-D games; just a few texture-mapped polygons, backed with well-drawn bitmaps, can represent more detail and look more realistic than dozens or even hundreds of solid-color polygons. My X-Sharp texture mapper was in reasonable assembly—pretty good code, by most standards!—and I felt comfortable with my implementation; but then I got a letter from John Miles, who was at the time getting seriously into 3-D and is now the author of a 3-D game library. (Yes, you can license it from his company, Non-Linear Arts, if you’d like; John can be reached at 70322.2457@compuserve.com.) John wrote me as follows: “Hmm, so that’s how texture-mapping works. But 3 jumps per pixel? Hmph!”

        It was the “Hmph” that really got to me.

        -

        Left-Brain Optimization

        +

        Left-Brain Optimization

        That was the first shot of juice for my optimizer (or at least blow to my ego, which can be just as productive). John went on to say he had gotten texture mapping down to 9 cycles per pixel and one jump per scanline on a 486 (all cycle times will be for the 486 unless otherwise noted); given that my code took, on average, about 44 cycles and 2 taken jumps (plus 1 not taken) per pixel, I had a long way to go.

        The inner loop of my original texture-mapping code is shown in Listing 58.1. All this code does is draw a single texture-mapped scanline, as shown in Figure 58.1; an outer loop runs through all the scanlines in whatever polygon is being drawn. I immediately saw that I could eliminate nearly 10 percent of the cycles by unrolling the loop; obviously, John had done that, else there’s no way he could branch only once per scanline. (By the way, branching only once per scanline via a fully unrolled loop is not generally recommended. A branch every few pixels costs relatively little, and the cache effects of fully unrolled code are not good.) I quickly came up with several other ways to speed up the code, but soon realized that all the clever coding in the world wasn’t going to get me within 100 percent of John’s performance so long as I had to cycle from one plane to the next for every pixel.


        Figure 58.1
          Texture mapping a single horizontal scanline. +
        -->Figure 58.1  Texture mapping a single horizontal scanline.


        @@ -71,7 +70,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/58-02.html b/58-02.html index c159862..0eaae2e 100644 --- a/58-02.html +++ b/58-02.html @@ -24,7 +24,7 @@ - +
        @@ -91,14 +91,14 @@ NoExtraYAdvance:

        Figure 58.2 shows why this cycling is necessary. In Mode X, the page-flipped 256-color mode of the VGA, each successive pixel across a scanline is stored in a different hardware plane, and an OUT to the VGA’s hardware is needed to select the plane being drawn to. (See Chapters 47, 48, and 49 for details.) An OUT instruction by itself takes 16 cycles (and in the neighborhood of 30 cycles in virtual-86 or non-privileged protected mode), and an ROL takes 2 more, for a total of 18 cycles, double John’s 9 cycles, just to handle plane management. Clearly, getting plane control out of the inner loop was absolutely necessary.


        Figure 58.2
          Display memory organization in Mode X. +
        -->Figure 58.2  Display memory organization in Mode X.

        I must confess, with some embarrassment, that at this point I threw myself into designing a solution that involved executing the texture mapping code up to four times per scanline, once for the pixels in each plane. It’s hard to overstate the complexity of this approach, which involves quadrupling the normal pixel-to-pixel increments, adjusting the start value for each of the passes, and dealing with some nasty boundary cases. Make no mistake, the code was perfectly doable, and would in fact have gotten plane control out of the inner loop, but would have been very difficult to get exactly right, and would have suffered from substantial overhead.

        Fortunately, in the last sentence I was able to say “would have,” not “was,” because my friend Chris Hecker (checker@bix.com) came along to toss a figurative bucket of cold water on my right brain, which was evidently asleep. (Or possibly stolen by scantily-clad, attractive aliens; remember “Spock’s Brain”?) Chris is the author of the WinG Windows game graphics package, available from Microsoft via FTP, CompuServe, or MSDN Level 2; if, like me, you were at the Game Developers Conference in April 1994, you, along with everyone else, were stunned to see Id’s megahit DOOM running at full speed in a window, thanks to WinG. If you write games for a living, run, don’t walk, to check WinG out!

        Chris listened to my proposed design for all of maybe 30 seconds, growing visibly more horrified by the moment, before he said, “But why don’t you just draw vertical rather than horizontal scanlines?”

        Why indeed?

        -

        A 90-Degree Shift in Perspective

        +

        A 90-Degree Shift in Perspective

        As I said earlier, how you look at an optimization problem defines how you’ll be able to solve it. In order to boost performance, sometimes it’s necessary to look at things from a different angle—and for texture mapping this was literally as well as figuratively true. Chris suggested nothing more nor less than scanning out polygons at a 90-degree angle to normal, starting, say, at the left edge of the polygon, and texture-mapping vertically along each column of pixels, as shown in Figure 58.3. That way, all the pixels in each texture-mapped column would be in the same plane, and I would need to change planes only between columns—outside the inner loop. A trivial change, not fundamental in any sense—and yet just that one change, plus unrolling the loop, reduced the inner loop to the 22-cycles-per-pixel version shown in Listing 58.2. That’s exactly twice as fast as Listing 58.1—and given how incredibly slow most VGAs are at completing OUTs, the real-world speedup should be considerably greater still. (The fastest byte OUT I’ve ever measured for a VGA is 29 cycles, the slowest more than 60 cycles; in the latter case, Listing 58.2 would be on the order of four times faster than Listing 58.1.)

        LISTING 58.2 L58-2.ASM

        @@ -160,7 +160,7 @@ ENDM
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/58-03.html b/58-03.html index 3a1aff9..0bb38ab 100644 --- a/58-03.html +++ b/58-03.html @@ -24,7 +24,7 @@ - +
        @@ -41,12 +41,12 @@
        That’s what Zen programming is all about, though; tying together two pieces of seemingly unrelated information to good effect—and that’s what I had failed to do. Like Robert Heinlein—like all of us—I had viewed the world through a filter composed of my ingrained assumptions, and one of those assumptions, based on all my past experience, was that pixel processing proceeds left to right. Eventually, I might have come up with Chris’s approach; but I would only have come up with it when and if I relaxed and stepped back a little, and allowed myself—almost dared myself—to think of it. When you’re optimizing, be sure to leave quiet, nondirected time in which to conjure up those less obvious solutions, and periodically try to figure out what assumptions you’re making—and then question them!


        Figure 58.3
          Texture mapping a single vertical column. +
        -->Figure 58.3  Texture mapping a single vertical column.

        There are a few complications with Chris’s approach, not least that X-Sharp’s polygon-filling convention (top and left edges included, bottom and right edges excluded) is hard to reproduce for column-oriented texture mapping. I solved this in X-Sharp version 22 by tweaking the edge-scanning code to allow column-oriented texture mapping to match the current convention. (You’ll find X-Sharp 22 on the listings diskette in the directory for this chapter.)

        Chris also illustrated another important principle of optimization: A second pair of eyes is invaluable. Even the best of us have blind spots and get caught up in particular implementations; if you bounce your ideas off someone, you may well find them coming back with an unexpected—and welcome—spin.

        -

        That’s Nice—But it Sure as Heck Ain’t 9 Cycles

        +

        That’s Nice—But it Sure as Heck Ain’t 9 Cycles

        Excellent as Chris’s suggestion was, I still had work to do: Listing 58.2 is still more than twice as slow as John Miles’s code. Traditionally, I start the optimization process with algorithmic optimization, then try to tie the algorithm and the hardware together for maximum efficiency, and finish up with instruction-by-instruction, take-no-prisoners optimization. We’ve already done the first two steps, so it’s time to get down to the bare metal.

        Listing 58.2 contains three functional parts: Drawing the pixel, advancing the destination pointer, and advancing the source texture pointer. Each of the three parts is amenable to further acceleration.

        @@ -73,15 +73,15 @@ MOV [EDI+SCANOFFSET],AH

        Advancing the source texture pointer is more complex, but correspondingly more rewarding. Listing 58.2 uses a variant form of 32-bit fixed-point arithmetic to advance the source pointer, with the source texture coordinates and increments stored in 16.16 (16 bits of integer, 16 bits of fraction) format. The source coordinates are stored in a slightly unusual format, whereby the fractional X and Y coordinates are stored and advanced separately, but a single integer value, the source pointer, is used to reflect both the X and Y coordinates. In Listing 58.2, the integer and fractional parts are added into the current coordinates with four separate 16-bit operations, and carries from fractional to integer parts are detected via conditional jumps, as shown in Figure 58.4. There’s quite a lot we can do to improve this.


        Figure 58.4
          Original method for advancing the source texture pointer. +
        -->Figure 58.4  Original method for advancing the source texture pointer.

        First, we can sum the X and Y integer advance amounts outside the loop, then add them both to the source pointer with a single instruction. Second, we can recognize that X advances exactly one extra byte when its fractional part carries, and use ADC to account for X carries, as shown in Figure 58.5. That single ADC can add in not only any X carry, but both the X and Y integer advance amounts as well, thereby eliminating a good chunk of the source-advance code in Listing 58.2. Furthermore, we should somehow be able to use 32-bit registers and instructions to help with the 32-bit fixed-point arithmetic; true, the size override prefix (because we’re in a 16-bit segment) will cost a cycle per 32-bit instruction, but that’s better than the 3 cycles it takes to do 32-bit arithmetic with 16-bit instructions. It isn’t obvious, but there’s a nifty trick we can use here, again courtesy of Chris Hecker (who, as you can tell, has done a fair amount of thinking about the complexities of texture mapping).

        We can store the current fractional parts of both the X and Y source coordinates in a single 32-bit register, EDX, as shown in Figure 58.6. It’s important to note that the Y fraction is actually only 15 bits, with bit 15 of EDX always kept at zero; this allows bit 15 to store the carry status from each Y advance. We can similarly store the fractional X and Y advance amounts in ECX, and can store the sum of the integer parts of the X and Y advance amounts in BP. With this arrangement, the single instruction ADD EDX,ECX advances the fractional parts of both X and Y, and the following instruction ADC SI,BP finishes advancing the source pointer in X. That’s a mere 3 cycles, and all that remains is to finish advancing the source pointer in Y.


        Figure 58.5
          Efficient method for advancing source texture pointer. +
        -->Figure 58.5  Efficient method for advancing source texture pointer.


        Figure 58.6
          Storing both X and Y fractional coordinates in one register. +
        -->Figure 58.6  Storing both X and Y fractional coordinates in one register.

        Actually, we also advanced the source pointer by the Y integer amount back when we added BP to SI; all that’s left is to detect whether our addition to the Y fractional current coordinate produced a carry. That’s easily done by testing bit 15 of EDX; if it’s zero, there was no carry and we’re done; otherwise, Y carried, so we have to reset bit 15 and advance the source pointer by one scanline. The resulting program flow is shown in Figure 58.7. Note that unlike the X fractional addition, we can’t get away with just adding in the carry from the Y fractional addition, because when the Y fraction carries, it indicates a move not from one pixel to the next on a scanline (a single byte), but rather from one scanline to the next (a full scanline width).


        @@ -97,7 +97,7 @@ MOV [EDI+SCANOFFSET],AH
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/58-04.html b/58-04.html index 75bd53f..3cf5c61 100644 --- a/58-04.html +++ b/58-04.html @@ -24,7 +24,7 @@ - +
        @@ -52,7 +52,7 @@


        Figure 58.7
          Final method for advancing source texture pointer. +
        -->Figure 58.7  Final method for advancing source texture pointer.

        @@ -86,7 +86,7 @@ SCANOFFSET = SCANOFFSET + SCANWIDTH
              ENDM
         
        -

        Don’t Stop Thinking about Those Cycles

        +

        Don’t Stop Thinking about Those Cycles

        Remember what I said at the outset, that knowing something has been done makes it much easier to do? A corollary is that pushing past that point, once attained, is very difficult. It’s only natural to want to relax in the satisfaction of a job well done; then, too, the very nature of the work changes. Getting from 44 cycles down to John’s 9 cycles was a huge leap, but we knew it could be done—therefore the nature of the problem was to figure out how it was done; in cases like this, if we’re sharp enough (and of course we are!), we’re guaranteed eventual gratification. Now that we’ve reached John’s level of performance, the problem becomes whether the code can be made faster yet, and that’s a different kettle of fish altogether, for it may well be that after thinking about it for a while, we’ll conclude that it can’t. Not only will we have wasted time, but we’ll also never be sure we were right; we’ll know only that we couldn’t find a solution. That way lies madness.

        And yet—someone has to blaze the trail to higher performance, and that someone might as well be us. Let’s look for weaknesses in Listing 58.3. None are readily apparent; the only cycle that looks even slightly wasted is the size prefix on ADD EDX,ECX. As it turns out, that cycle really is wasted, for there’s a way to make the size prefix vanish without losing the benefits of 32-bit instructions: Move the code into a 32-bit segment and make all the instructions 32-bit. That’s what Listing 58.4 does; this code is similar to Listing 58.3, but runs in 8 cycles per pixel, a 12.5 percent speedup over Listing 58.3. Whether Listing 58.4 actually draws more pixels per second than Listing 58.3 depends on whether display memory is fast enough to handle pixels as rapidly as Listing 58.4 can deliver them. That speed, one pixel every 122 nanoseconds on a 486/66, is one that ISA adapters can’t hope to match, but fast VLB and PCI adapters can handle with ease. Be aware, too, that cache misses when reading the source texture will generally reduce performance below the calculated 8-cycles-per-pixel level, especially because textures, which can be scanned across at any angle, are rarely accessed at consecutive addresses, which is the arrangement that would make for the fewest cache misses.


        @@ -101,7 +101,7 @@ SCANOFFSET = SCANOFFSET + SCANWIDTH
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/58-05.html b/58-05.html index f7ba09e..456db5d 100644 --- a/58-05.html +++ b/58-05.html @@ -24,7 +24,7 @@ - +
        @@ -82,7 +82,7 @@ SCANOFFSET = SCANOFFSET + SCANWIDTH

        And there you have it: A five to 10-times speedup of a decent assembly language texture mapper. All it took was some help from my friends, a good, stiff jolt of right-brain thinking, and some solid left-brain polishing—plus the knowledge that such a speedup was possible. Treat every optimization task as if John Miles has just written to inform you that he’s made it faster than your wildest dreams, and you’ll be amazed at what you can do!

        -

        Texture Mapping Notes

        +

        Texture Mapping Notes

        Listing 58.3 contains no 486 pipeline stalls; it has Pentium stalls, but not much can be done for them because of the size prefix on ADD EDX,ECX, which takes 1 cycle to go through the U-pipe, and shuts down the V-pipe for that cycle. Listing 58.4, on the other hand, has been rearranged to eliminate all Pentium stalls save one. When the Y coordinate fractional part carries and ESI advances, the code executes as follows:

        @@ -112,7 +112,7 @@ ADD EDX,EBP     ;cycle 3 V-pipe
         
         
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-01.html b/59-01.html index 4fbfc66..fb43fda 100644 --- a/59-01.html +++ b/59-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 59
        The Idea of BSP Trees -

        -

        What BSP Trees Are and How to Walk Them

        +

        Chapter 59
        The Idea of BSP Trees

        +

        What BSP Trees Are and How to Walk Them

        The answer is: Wendy Tucker.

        The question that goes with that answer isn’t particularly interesting to anyone but me—but the manner in which I came up with the answer is.

        @@ -53,11 +52,11 @@

        The problem is, though, that neither you nor I will ever do anything great without inspiration and intuitive leaps, and especially not without stepping away from what’s known and venturing into territories beyond. The way to do that is not by trying harder but, paradoxically, by trying less hard, stepping back, and giving your right brain room to work, then listening for and nurturing whatever comes of that. On a small scale, that’s how I remembered Wendy’s name, and on a larger scale, that’s how programmers come up with products that are more than me-too, checklist-oriented software.

        Which, for a couple of reasons, brings us neatly to this chapter’s topic, Binary Space Partitioning (BSP) trees. First, games are probably the sort of software in which the right-brain element is most important—blockbuster games are almost always breakthroughs in one way or another—and some very successful games use BSP trees, most notably id Software’s megahit DOOM. Second, BSP trees aren’t intuitively easy to grasp, and considerable ingenuity and inventiveness is required to get the most from them.

        Before we begin, I’d like to thank John Carmack, the technical wizard behind DOOM, for generously sharing his knowledge of BSP trees with me.

        -

        BSP Trees

        +

        BSP Trees

        A BSP tree is, at heart, nothing more than a tree that subdivides space in order to isolate features of interest. Each node of a BSP tree splits an area or a volume (in 2-D or 3-D, respectively) into two parts along a line or a plane; thus the name “Binary Space Partitioning.” The subdivision is hierarchical; the root node splits the world into two subspaces, then each of the root’s two children splits one of those two subspaces into two more parts. This continues with each subspace being further subdivided, until each component of interest (each line segment or polygon, for example) has been assigned its own unique subspace. This is, admittedly, a pretty abstract description, but the workings of BSP trees will become clearer shortly; it may help to glance ahead to this chapter’s figures.

        Building a tree that subdivides space doesn’t sound particularly profound, but there’s a lot that can be done with such a structure. BSP trees can be used to represent shapes, and operating on those shapes is a simple matter of combining trees as needed; this makes BSP trees a powerful way to implement Constructive Solid Geometry (CSG). BSP trees can also be used for hit testing, line-of-sight determination, and collision detection.

        -

        Visibility Determination

        +

        Visibility Determination

        For the time being, I’m going to discuss only one of the many uses of BSP trees: The ability of a BSP tree to allow you to traverse a set of line segments or polygons in back-to-front or front-to-back order as seen from any arbitrary viewpoint. This sort of traversal can be very helpful in determining which parts of each line segment or polygon are visible and which are occluded from the current viewpoint in a 3-D scene. Thus, a BSP tree makes possible an efficient implementation of the painter’s algorithm, whereby polygons are drawn in back-to-front order, with closer polygons overwriting more distant ones that overlap, as shown in Figure 59.1. (The line segments in Figure 1(a) and in other figures in this chapter, represent vertical walls, viewed from directly above.) Alternatively, visibility determination can be performed by front-to-back traversal working in conjunction with some method for remembering which pixels have already been drawn. The latter approach is more complex, but has the potential benefit of allowing you to early-out from traversal of the scene database when all the pixels on the screen have been drawn.


        @@ -72,7 +71,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-02.html b/59-02.html index 362b44b..fa9f986 100644 --- a/59-02.html +++ b/59-02.html @@ -24,7 +24,7 @@ - +
        @@ -40,22 +40,22 @@

        It’s hard to get cheaper sorting than linear time, and BSP-based rendering stacks up well against alternatives such as z-buffering, octrees, z-scan sorting, and polygon sorting. Better yet, a scene database represented as a BSP tree can be clipped to the view pyramid very efficiently; huge chunks of a BSP tree can be lopped off when clipping to the view pyramid, because if the entire area or volume of a node lies entirely outside the view volume, then all nodes and leaves that are children of that node must likewise be outside the view volume, for reasons that will become clear as we delve into the workings of BSP trees.


        Figure 59.1
          The painter’s algorithm. +
        -->Figure 59.1  The painter’s algorithm.

        -

        Limitations of BSP Trees

        +

        Limitations of BSP Trees

        Powerful as they are, BSP trees aren’t perfect. By far the greatest limitation of BSP trees is that they’re time-consuming to build, enough so that, for all practical purposes, BSP trees must be precalculated, and cannot be built dynamically at runtime. In fact, a BSP-tree compiler that attempts to perform some optimization (limiting the number of surfaces that need to be split, for example) can easily take minutes or even hours to process large world databases.

        A fixed world database is fine for walkthrough or flythrough applications (where the viewpoint moves through a static scene), but not much use for games or virtual reality, where objects constantly move relative to one another. Consequently, various workarounds have been developed to allow moving objects to appear in BSP tree-based scenes. DOOM, for example, uses 2-D sprites mixed into BSP-based 3-D scenes; note, though, that this approach requires maintaining z information so that sprites can be drawn and occluded properly. Alternatively, movable objects could be represented as separate BSP trees and merged anew into the world BSP tree with each move. Dynamic merging may or may not be fast enough, depending on the scene, but merging BSP trees tends to be quicker than building them, because the BSP trees being merged are already spatially sorted.

        Another possibility would be to generate a per-pixel z-buffer for each frame as it’s rendered, to allow dynamically changing objects to be drawn into the BSP-based world. In this scheme, the BSP tree would allow fast traversal and clipping of the complex, static world, and the z-buffer would handle the relatively localized visibility determination involving moving objects. The drawback of this is the need for a memory-hungry z-buffer; a typical 640x480 z-buffer requires a fairly appalling 600K, with equally appalling cache-miss implications for performance.

        Yet another possibility would be to build the world so that each dynamic object falls entirely within a single subspace of the static BSP tree, rather than straddling splitting lines or planes. In this case, dynamic objects can be treated as points, which are then just sorted into the BSP tree on the fly as they move.

        The only other drawbacks of BSP trees that I know of are the memory required to store the tree, which amounts to a few pointers per node, and the relative complexity of debugging BSP-tree compilation and usage; debugging a large data set being processed by recursive code (which BSP code tends to be) can be quite a challenge. Tools like the BSP compiler I’ll present in the next chapter, which visually depicts the process of spatial subdivision as a BSP tree is constructed, help a great deal with BSP debugging.

        -

        Building a BSP Tree

        +

        Building a BSP Tree

        Now that we know a good bit about what a BSP tree is, how it helps in visible surface determination, and what its strengths and weaknesses are, let’s take a look at how a BSP tree actually works to provide front-to-back or back-to-front ordering. This chapter’s discussion will be at a conceptual level, with plenty of figures; in the next chapter we’ll get into mechanisms and implementation details.

        I’m going to discuss only 2-D BSP trees from here on out, because they’re much easier to draw and to grasp than their 3-D counterparts. Don’t worry, though; the principles of 2-D BSP trees using line segments generalize directly to 3-D BSP trees using polygons. Also, 2-D BSP trees are quite powerful in their own right, as evidenced by DOOM, which is built around 2-D BSP trees.

        First, let’s construct a simple BSP tree. Figure 59.2 shows a set of four lines that will constitute our sample world. I’ll refer to these as walls, because that’s one easily-visualized context in which a 2-D BSP tree would be useful in a game. Think of Figure 59.2 as depicting vertical walls viewed from directly above, so they’re lines for the purpose of the BSP tree. Note that each wall has a front side, denoted by a normal (perpendicular) vector, and a back side. To make a BSP tree for this sample set, we need to split the world in two, then each part into two again, and so on, until each wall resides in its own unique subspace. An obvious question, then, is how should we carve up the world of Figure 59.2?


        Figure 59.2
          A sample set of walls, viewed from above. +
        -->Figure 59.2  A sample set of walls, viewed from above.

        There are infinitely valid ways to carve up Figure 59.2, but the simplest is just to carve along the lines of the walls themselves, with each node containing one wall. This is not necessarily optimal, in the sense of producing the smallest tree, but it has the virtue of generating the splitting lines without expensive analysis. It also saves on data storage, because the data for the walls can do double duty in describing the splitting lines as well. (Putting one wall on each splitting line doesn’t actually create a unique subspace for each wall, but it does create a unique subspace boundary for each wall; as we’ll see, that spatial organization provides for the same unambiguous visibility ordering as a unique subspace would.)


        @@ -70,7 +70,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-03.html b/59-03.html index bca4c14..ab75075 100644 --- a/59-03.html +++ b/59-03.html @@ -24,7 +24,7 @@ - +
        @@ -39,34 +39,34 @@

        Creating a BSP tree is a recursive process, so we’ll perform the first split and go from there. Figure 59.3 shows the world carved along the line of wall C into two parts: walls that are in front of wall C, and walls that are behind. (Any of the walls would have been an equally valid choice for the initial split; we’ll return to the issue of choosing splitting walls in the next chapter.) This splitting into front and back is the essential dualism of BSP trees.


        Figure 59.3
          Initial split along the line of wall C. +
        -->Figure 59.3  Initial split along the line of wall C.

        Next, in Figure 59.4, the front subspace of wall C is split by wall D. This is the only wall in that subspace, so we’re done with wall C’s front subspace.

        Figure 59.5 shows the back subspace of wall C being split by wall B. There’s a difference here, though: Wall A straddles the splitting line generated from wall B. Does wall A belong in the front or back subspace of wall B?


        Figure 59.4
          Split of wall C’s front subspace along the line of wall D. +
        -->Figure 59.4  Split of wall C’s front subspace along the line of wall D.


        Figure 59.5
          Split of wall C’s back subspace along the line of wall B. +
        -->Figure 59.5  Split of wall C’s back subspace along the line of wall B.

        Both, actually. Wall A gets split into two pieces, which I’ll call wall A and wall E; each piece is assigned to the appropriate subspace and treated as a separate wall. As shown in Figure 59.6, each of the split pieces then has a subspace to itself, and each becomes a leaf of the tree. The BSP tree is now complete.

        -

        Visibility Ordering

        +

        Visibility Ordering

        Now that we’ve successfully built a BSP tree, you might justifiably be a little puzzled as to how any of this helps with visibility ordering. The answer is that each BSP node can definitively determine which of its child trees is nearer and which is farther from any and all viewpoints; applied throughout the tree, this principle makes it possible to establish visibility ordering for all the line segments or planes in a BSP tree, no matter what the viewing angle.

        Consider the world of Figure 59.2 viewed from an arbitrary angle, as shown in Figure 59.7. The viewpoint is in front of wall C; this tells us that all walls belonging to the front tree that descends from wall C are nearer along every ray from the viewpoint than wall C is (that is, they can’t be occluded by wall C). All the walls in wall C’s back tree are likewise farther away than wall C along any ray. Thus, for this viewpoint, we know for sure that if we’re using the painter’s algorithm, we want to draw all the walls in the back tree first, then wall C, and then the walls in the front tree. If the viewpoint had been on the back side of wall C, this order would have been reversed.

        Of course, we need more ordering information than wall C alone can give us, but we get that by traversing the tree recursively, making the same far-near decision at each node. Figure 59.8 shows the painter’s algorithm (back-to-front) traversal order of the tree for the viewpoint of Figure 59.7. At each node, we decide whether we’re seeing the front or back side of that node’s wall, then visit whichever of the wall’s children is on the far side from the viewpoint, draw the wall, and then visit the node’s nearer child, in that order. Visiting a child is recursive, involving the same far-near visiting order.


        Figure 59.6
          The final BSP tree. +
        -->Figure 59.6  The final BSP tree.


        Figure 59.7
          Viewing the BSP tree from an arbitrary angle. +
        -->Figure 59.7  Viewing the BSP tree from an arbitrary angle.

        The key is that each BSP splitting line separates all the walls in the current subspace into two groups relative to the viewpoint, and every single member of the farther group is guaranteed not to occlude every single member of the nearer. By applying this ordering recursively, the BSP tree can be traversed to provide back-to-front or front-to-back ordering, with each node being visited only once.


        Figure 59.8
          Back-to-front traversal of the BSP tree as viewed in Figure 59.7. +
        -->Figure 59.8  Back-to-front traversal of the BSP tree as viewed in Figure 59.7.

        The type of tree walk used to produce front-to-back or back-to-front BSP traversal is known as an inorder walk. More on this very shortly; you’re also likely to find a discussion of inorder walking in any good data structures book. The only special aspect of BSP walks is that a decision has to be made at each node about which way the node’s wall is facing relative to the viewpoint, so we know which child tree is nearer and which is farther.

        Listing 59.1 shows a function that draws a BSP tree back-to-front. The decision whether a node’s wall is facing forward, made by WallFacingForward() in Listing 59.1, can, in general, be made by generating a normal to the node’s wall in screenspace (perspective-corrected space as seen from the viewpoint) and checking whether the z component of the normal is positive or negative, or by checking the sign of the dot product of a viewspace (non-perspective corrected space as seen from the viewpoint) normal and a ray from the viewpoint to the wall. In 2-D, the decision can be made by enforcing the convention that when a wall is viewed from the front, the start vertex is leftmost; then a simple screenspace comparison of the x coordinates of the left and right vertices indicates which way the wall is facing.

        @@ -112,7 +112,7 @@ void WalkBSPTree(NODE *pNode)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-04.html b/59-04.html index b8ec5c1..8ee149e 100644 --- a/59-04.html +++ b/59-04.html @@ -24,7 +24,7 @@ - +
        @@ -36,13 +36,13 @@


        -

        Inorder Walks of BSP Trees

        +

        Inorder Walks of BSP Trees

        It was implementing BSP trees that got me to thinking about inorder tree traversal. In inorder traversal, the left subtree of each node gets visited first, then the node, and then the right subtree. You apply this sequence recursively to each node and its children until the entire tree has been visited, as shown in Figure 59.9. Walking a BSP tree is basically an inorder tree walk; the only difference is that with a BSP tree a decision is made before each descent as to which subtree to visit first, rather than simply visiting whatever’s pointed to by the left-subtree pointer. Conceptually, however, an inorder walk is what’s used to traverse a BSP tree; from now on I’ll discuss normal inorder walking, with the understanding that the same principles apply to BSP trees.

        As I’ve said again and again in my printed works over the years, you have to dig deep below the surface to really understand something if you want to get it right, and inorder walking turns out to be an excellent example of this. In fact, it’s such a good example that I routinely use it as an interview question for programmer candidates, and, to my astonishment, not one interviewee has done a good job with this one yet. I ask the question in two stages, and I get remarkably consistent results.

        First, I ask for an implementation of a function WalkTree() that visits each node in a passed-in tree in inorder sequence. Each candidate unhesitatingly writes something like the perfectly good code in Listings 59.2 and 59.3 shown next.


        Figure 59.9
          An inorder walk of a BSP tree. +
        -->Figure 59.9  An inorder walk of a BSP tree.

        Listing 59.2 L59_2.C

        @@ -89,8 +89,7 @@ struct _NODE *pRightChild;

        And then I sit back and squirm for a minimum of 15 minutes.

        I have never had anyone write a functional data-recursion inorder walk function in less time than that, and several people have simply never gotten the code to work at all. Even the best of them have fumbled their way through the code, sticking in a push here or a pop there, then working through sample scenarios in their head to see what’s broken, programming by trial and error until the errors seem to be gone. No one is ever sure they have it right; instead, when they can’t find any more bugs, they look at me hopefully to see if it’s thumbs-up or thumbs-down.

        And yet, a data-recursive inorder walk implementation has exactly the same flowchart and exactly the same functionality as the code-recursive version they’ve already written. They already have a fully functional model to follow, with all the problems solved, but they can’t make the connection between that model and the code they’re trying to implement. Why is this?

        -

        Know It Cold -

        +

        Know It Cold

        The problem is that these people don’t understand inorder walking through and through. They understand the concepts of visiting left and right subtrees, and they have a general picture of how traversal moves about the tree, but they do not understand exactly what the code-recursive version does. If they really comprehended everything that happens in each iteration of WalkTree()—how each call saves the state, and what that implies for the order in which operations are performed—they would simply and without fuss implement code like that in Listing 59.4, working with the code-recursive version as a model.

        Listing 59.4 L59_4.C

        @@ -180,7 +179,7 @@ void WalkTree(NODE *pNode)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-05.html b/59-05.html index 1c776d3..ace97d9 100644 --- a/59-05.html +++ b/59-05.html @@ -24,7 +24,7 @@ - +
        @@ -45,7 +45,7 @@
        The alternative is to develop and apply a unifying model. There aren’t really two types of right children; the rule is that all right children are visited after their parents are visited, period. The presence or absence of a left child is irrelevant. The possibility that a right child may be reached via different code paths depending on the presence of a left child does not affect the overall model. While this distinction may seem trivial it is in fact crucial, because if you have the model down cold, you can always tell if the implementation is correct by comparing it with the model.
        -

        Measure and Learn

        +

        Measure and Learn

        How much difference does all this fuss make, anyway? Listing 59.5 is a sample program that builds a tree, then calls WalkTree () to walk it 1,000 times, and times how long this takes. Using 32-bit Visual C++ 1.10 running on Windows NT, with default optimization selected, Listing 59.5 reports that Listing 59.4 is about 20 percent faster than Listing 59.2 on a 486/33, a reasonable return for a little code rearrangement, especially when you consider that the speedup is diluted by calling the Visit() function and by the cache miss that happens on virtually every node access. (Listing 59.5 builds a rather unique tree, one in which every node has exactly two children. Different sorts of trees can and do produce different performance results. Always know what you’re measuring!)

        Listing 59.5 L59_5.C

        @@ -132,7 +132,7 @@ void Visit(NODE *pNode)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/59-06.html b/59-06.html index 2669645..8911b26 100644 --- a/59-06.html +++ b/59-06.html @@ -24,7 +24,7 @@ - +
        @@ -50,9 +50,9 @@

        With each iteration you’ll dig deeper, learn more, and improve your ability to know where and how to focus your design and programming efforts. For example, with the C compilers I used five to 10 years ago, back when I learned about the relative strengths and weaknesses of code and data recursion, and with the processors then in use, Listing 59.4 would have blown away Listing 59.2. While doing this chapter, I’ve learned that given current processors and compiler technology, data recursion isn’t going to get me any big wins; and yes, that was news to me. That’s good; this information saves me from wasted effort in the future and tells me what to concentrate on when I use recursion.

        Assume nothing, keep digging deeper, and never stop learning and growing. The world won’t hold still for you, but fortunately you can run fast enough to keep up if you just keep at it.

        Depths within depths indeed!

        -

        Surfing Amidst the Trees

        +

        Surfing Amidst the Trees

        In the next chapter, we’ll build a BSP-tree compiler, and after that, we’ll put together a rendering system built around the BSP trees the compiler generates. If the subject of BSP trees really grabs your fancy (as it should if you care at all about performance graphics) there is at this writing (February 1996) a World Wide Web page on BSP trees that you must investigate at http://www.qualia.com/bspfaq/. It’s set up in the familiar Internet Frequently Asked Questions (FAQ) style, and is very good stuff.

        -

        Related Reading

        +

        Related Reading

        Foley, J., A. van Dam, S. Feiner, and J. Hughes, Computer Graphics: Principles and Practice (Second Edition), Addison Wesley, 1990, pp. 555-557, 675-680.

        Fuchs, H., Z. Kedem, and B. Naylor, “On Visible Surface Generation by A Priori Tree Structures,” Computer Graphics Vol. 17(3), June 1980, pp. 124-133.

        Gordon, D., and S. Chen, “Front-to-Back Display of BSP Trees,” IEEE Computer Graphics and Applications, September 1991, pp. 79-85.

        @@ -69,7 +69,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/60-01.html b/60-01.html index 740a40b..9be28ec 100644 --- a/60-01.html +++ b/60-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 60
        Compiling BSP Trees -

        -

        Taking BSP Trees from Concept to Reality

        +

        Chapter 60
        Compiling BSP Trees

        +

        Taking BSP Trees from Concept to Reality

        As long-time readers of my columns know, I tend to move my family around the country quite a bit. Change doesn’t come out of the blue, so there’s some interesting history to every move, but the roots of the latest move go back even farther than usual. To wit:

        In 1986, just after we moved from Pennsylvania to California, I started writing a column for Programmer’s Journal. I was paid peanuts for writing it, and I doubt if even 5,000 people saw some of the first issues the columns appeared in, but I had a lot of fun exploring fast graphics for the EGA and VGA.

        @@ -50,7 +49,7 @@

        I think there’s a worthwhile lesson to be learned from all this, a lesson that I’ve seen hold true for many other people, as well. If you do what you love, and do it as well as you can, good things will eventually come of it. Not necessarily quickly or easily, but if you stick with it, they will come. There are threads that run through our lives, and by the time we’ve been adults for a while, practically everything that happens has roots that run far back in time. The implication should be clear: If you want good things to happen in your future, stretch yourself and put in the extra effort now at whatever you care passionately about, so those roots will have plenty to work with down the road.

        All this is surprisingly closely related to this chapter’s topic, BSP trees, because John is the fellow who brought BSP trees into the spotlight by building DOOM around them. He also got me started with BSP trees by explaining how DOOM worked and getting me interested enough to want to experiment; the BSP compiler in this article is the direct result. Finally, John has been an invaluable help to me as I’ve learned about BSP trees, as will become evident when we discuss BSP optimization.

        Onward to compiling BSP trees.

        -

        Compiling BSP Trees

        +

        Compiling BSP Trees

        As you’ll recall from the previous chapter, a BSP tree is nothing more than a series of binary subdivisions that partion space into ever-smaller pieces. That’s a simple data structure, and a BSP compiler is a correspondingly simple tool. First, it groups all the surfaces (lines in 2-D, or polygons in 3-D) together into a single subspace that encompasses the entire world of the database. Then, it chooses one of the surfaces as the root node, and uses its line or plane to divide the remaining surfaces into two subspaces, splitting surfaces into two parts if they cross the line or plane of the root. Each of the two resultant subspaces is then processed in the same fashion, and so on, recursively, until the point is reached where all surfaces have been assigned to nodes, and each leaf surface subdivides a subspace that is empty except for that surface. Put another way, the root node carves space into two parts, and the root’s children carve each of those parts into two more parts, and so on, with each surface carving ever smaller subspaces, until all surfaces have been used. (Actually, there are many other lines or planes that a BSP tree can use to carve up space, but this is the approach we’ll use in the current discussion.)


        @@ -65,7 +64,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/60-02.html b/60-02.html index d767d19..f9c88fe 100644 --- a/60-02.html +++ b/60-02.html @@ -24,7 +24,7 @@ - +
        @@ -39,7 +39,7 @@

        If you find any of the above confusing (and it would be understandable if that were the case; BSP trees are not easy to get the hang of), you might want to refer back to the previous chapter. It would also be a good idea to get hold of the visual BSP compiler I’ll discuss shortly; when it comes to understanding BSP trees, there’s nothing quite like seeing one being built.

        So there are really only two interesting operations in building a BSP tree: choosing a root node for the current subspace (a “splitter”) and assigning surfaces to one side or another of the current root node, splitting any that straddle the splitter. We’ll get to the issue of choosing splitters shortly, but first let’s look at the process of splitting and assigning. To do that, we need to understand parametric lines.

        -

        Parametric Lines

        +

        Parametric Lines

        We’re all familiar with lines described in slope-intercept form, with y as a function of x

        y = mx + b

        @@ -52,23 +52,23 @@

        In our 2-D BSP compiler (as you’ll recall from the previous chapter, we’re working with 2-D trees for simplicity, but the principles generalize to 3-D), we’ll represent our walls (all vertical) as line segments viewed from above. The segments will be stored in parametric form, with the endpoints of the original line segment and two t values describing the endpoints of the current (possibly clipped) segment providing a complete specification for each segment, as shown in Figure 60.2.

        What does that do for us? For one thing, it keeps clipping errors from creeping in, because clipped line segments are always based on the original line segment, not derived from clipped versions. Also, it’s potentially a more compact format, because we need to store the endpoints only for the original line segments; for clipped line segments, we can just store pairs of t values, along with a pointer to the original line segment. The biggest win, however, is that it allows us to use parametric line clipping, a very clean form of clipping, indeed.


        Figure 60.1
          A sample parametric line. +
        -->Figure 60.1  A sample parametric line.


        Figure 60.2
          Line segment storage in the BSP compiler. +
        -->Figure 60.2  Line segment storage in the BSP compiler.

        -

        Parametric Line Clipping

        +

        Parametric Line Clipping

        In order to assign a line segment to one subspace or the other of a splitter, we must somehow figure out whether the line segment straddles the splitter or falls on one side or the other. In order to determine that, we first plug the line segment and splitter into the following parametric line intersection equation

        number = N (Lstart - Sstart) (Equation 1)
        denom = -N (Lend - Lstart) (Equation 2)
        tintersect = number / denom (Equation 3)

        where N is the normal of the splitter, Sstart is the start point of the splitting line segment in standard (x,y) form, and Lstart and Lend are the endpoints of the line segment being split, again in (x,y) form. Figure 60.3 illustrates the intersection calculation. Due to lack of space, I’m just going to present this equation and its implications as fact, rather than deriving them; if you want to know more, there’s an excellent explanation on page 117 of Computer Graphics: Principles and Practice, by Foley and van Dam (Addison Wesley, ISBN 0-201-12110-7), a book that you should certainly have in your library.

        If the denominator is zero, we know that the lines are parallel and don’t intersect, so we don’t divide, but rather check the sign of the numerator, which tells us which side of the splitter the line segment is on. Otherwise, we do the division, and the result is the t value for the intersection point, as shown in Figure 60.3. We then simply compare the t value to the t values of the endpoints of the line segment being split. If it’s between them, that’s where we split the line segment, otherwise, we can tell which side of the splitter the line segment is on by which side of the line segment’s t range it’s on. Simple comparisons do all the work, and there’s no need to do the work of generating actual x and y values. If you look closely at Listing 60.1, the core of the BSP compiler, you’ll see that the parametric clipping code itself is exceedingly short and simple.


        Figure 60.3
          How line intersection is calculated. +
        -->Figure 60.3  How line intersection is calculated.

        One interesting point about Listing 60.1 is that it generates normals to splitting surfaces simply by exchanging the x and y lengths of the splitting line segment and negating the resultant y value, thereby rotating the line 90 degrees. In 3-D, it’s not that simple to come by a normal; you could calculate the normal as the cross-product of two of the polygon’s edges, or precalculate it when you build the world database.

        -

        The BSP Compiler

        +

        The BSP Compiler

        Listing 60.1 shows the core of a BSP compiler—the code that actually builds the BSP tree. (Note that Listing 60.1 is excerpted from a C++ .CPP file, but in fact what I show here is very close to straight C. It may even compile as a .C file, though I haven’t checked.) The compiler begins by setting up an empty tree, then passes that tree and the complete set of line segments from which a BSP tree is to be generated to SelectBSPTree(), which chooses a root node and calls BuildBSPTree() to add that node to the tree and generate child trees for each of the node’s two subspaces. BuildBSPTree() calls SelectBSPTree() recursively to select a root node for each of those child trees, and this continues until all lines have been assigned nodes. SelectBSP() uses parametric clipping to decide on the splitter, as described below, and BuildBSPTree() uses parametric clipping to decide which subspace of the splitter each line belongs in, and to split lines, if necessary.


        @@ -82,7 +82,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/60-03.html b/60-03.html index 3eeea30..505045f 100644 --- a/60-03.html +++ b/60-03.html @@ -24,7 +24,7 @@ - +
        @@ -311,7 +311,7 @@ LINESEG * BuildBSPTree(LINESEG * plineseghead, LINESEG * prootline,
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/60-04.html b/60-04.html index 7aa98d6..a7dca27 100644 --- a/60-04.html +++ b/60-04.html @@ -24,7 +24,7 @@ - +
        @@ -38,7 +38,7 @@


        Listing 60.1 isn’t very long or complex, but it’s somewhat more complicated than it could be because it’s structured to allow visual display of the ongoing compilation process. That’s because Listing 60.1 is actually just a part of a BSP compiler for Win32 that visually depicts the progressive subdivision of space as the BSP tree is built. (Note that Listing 60.1 might not compile as printed; I may have missed copying some global variables that it uses.) The complete code is too large to print here in its entirety, but it’s on the CD-ROM in file DDJBSP.ZIP.

        -

        Optimizing the BSP Tree

        +

        Optimizing the BSP Tree

        In the previous chapter, I promised that I’d discuss how to go about deciding which wall to use as the splitter at each node in constructing a BSP tree. That turns out to be a far more difficult problem than one might think, but we can’t ignore it, because the choice of splitter can make a huge difference.

        Consider, for example, a BSP in which the line or plane of the splitter at the root node splits every single other surface in the world, doubling the total number of surfaces to be dealt with. Contrast that with a BSP built from the same surface set in which the initial splitter doesn’t split anything. Both trees provide a valid ordering, but one tree is much larger than the other, with twice as many polygons after the selection of just one node. Apply the same difference again to each node, and the relative difference in size (and, correspondingly, in traversal and rendering time) soon balloons astronomically. So we need to do something to optimize the BSP tree—but what? Before we can try to answer that, we need to know exactly what we’d like to optimize.

        @@ -46,7 +46,7 @@

        The BSP metric that seems most useful to me, however, is the number of polygons that are split into two polygons in the course of building a BSP tree. Fewer splits is better; the tree is smaller with fewer polygons, and drawing will go faster with fewer polygons to draw, due to per-polygon overhead. There’s a problem with the fewest-splits metric, though: There’s no sure way to achieve it.

        The obvious approach to minimizing polygon splits would be to try all possible trees to find the best one. Unfortunately, the order of that particular problem is N!, as I found to my dismay when I implemented brute-force optimization in the first version of my BSP compiler. Take a moment to calculate the number of operations for the 20-polygon set I originally tried brute-force optimization on. I’ll give you a hint: There are 19 digits in 20!, and if each operation takes only one microsecond, that’s over 70,000 years (or, if you prefer, over 500,000 dog years). Now consider that a single game level might have 5,000 to 10,000 polygons; there aren’t anywhere near enough dog years in the lifetime of the universe to handle that. We’re going to have to give up on optimal compilation and come up with a decent heuristic approach, no matter what optimization objective we select.

        In Listing 60.1, I’ve applied the popular heuristic of choosing as the splitter at each node the surface that splits the fewest of the other surfaces that are being considered for that node. In other words, I choose the wall that splits the fewest of the walls in the subspace it’s subdividing.

        -

        BSP Optimization: an Undiscovered Country

        +

        BSP Optimization: an Undiscovered Country

        Although BSP trees have been around for at least 15 years now, they’re still only partially understood and are a ripe area for applied research and general ingenuity. You might want to try your hand at inventing new BSP optimization approaches; it’s an interesting problem, and you might strike paydirt. There are many things that BSP trees can’t do well, because it takes so long to build them—but what they do, they do exceedingly well, so a better compilation approach that allowed BSP trees to be used for more purposes would be valuable, indeed.


        @@ -61,7 +61,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/61-01.html b/61-01.html index 12049c3..7c9102c 100644 --- a/61-01.html +++ b/61-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,21 +36,20 @@


        -

        Chapter 61
        Frames of Reference -

        -

        The Fundamentals of the Math behind 3-D Graphics

        +

        Chapter 61
        Frames of Reference

        +

        The Fundamentals of the Math behind 3-D Graphics

        Several years ago, I opened a column in Dr. Dobb’s Journal with a story about singing my daughter to sleep with Beatles’ songs. Beatles’ songs, at least the earlier ones, tend to be bouncy and pleasant, which makes them suitable goodnight fodder—and there are a lot of them, a useful hedge against terminal boredom. So for many good reasons, “Can’t Buy Me Love” and “A Hard Day’s Night” and “Help!” and the rest were evening staples for years.

        No longer, though. You see, I got my wife some Beatles tapes for Christmas, and we’ve all been listening to them in the car, and now that my daughter has heard the real thing, she can barely stand to be in the same room, much less fall asleep, when I sing those songs.

        What’s noteworthy is that the only variable involved in this change was my daughter’s frame of reference. My singing hasn’t gotten any worse over the last four years. (I’m not sure it’s possible for my singing to get worse.) All that changed was my daughter’s frame of reference for those songs. The rest of the universe stayed the same; the change was in her mind, lock, stock, and barrel.

        Often, the key to solving a problem, or to working on a problem efficiently, is having a proper frame of reference. The model you have of a problem you’re tackling often determines how deeply you can understand the problem, and how flexible and innovative you’ll be able to be in solving it.

        An excellent example of this, and one that I’ll discuss toward the end of this chapter, is that of 3-D transformation—the process of converting coordinates from one coordinate space to another, for example from worldspace to viewspace. The way this is traditionally explained is functional, but not particularly intuitive, and fairly hard to visualize. Recently, I’ve come across another way of looking at transforms that seems to me to be far easier to grasp. The two approaches are technically equivalent, so the difference is purely a matter of how we choose to view things—but sometimes that’s the most important sort of difference.

        Before we can talk about transforming between coordinate spaces, however, we need two building blocks: dot products and cross products.

        -

        3-D Math

        +

        3-D Math

        At this point in the book, I was originally going to present a BSP-based renderer, to complement the BSP compiler I presented in the previous chapter. What changed my plans was the considerable amount of mail about 3-D math that I’ve gotten in recent months. In every case, the writer has bemoaned his/her lack of expertise with 3-D math, and has asked what books about 3-D math I’d recommend, and how else he/she could learn more.

        That’s a commendable attitude, but the truth is, there’s not all that much to 3-D math, at least not when it comes to the sort of polygon-based, realtime 3-D that’s done on PCs. You really need only two basic math tools beyond simple arithmetic: dot products and cross products, and really mostly just the former. My friend Chris Hecker points out that this is an oversimplification; he notes that lots more math-related stuff, like BSP trees, graphs, discrete math for edge stepping, and affine and perspective texture mappings, goes into a production-quality game. While that’s surely true, dot and cross products, together with matrix math and perspective projection, constitute the bulk of what most people are asking about when they inquire about “3-D math,” and, as we’ll see, are key tools for a lot of useful 3-D operations.

        The other thing the mail made clear was that there are a lot of people out there who don’t understand either type of product, at least insofar as they apply to 3-D. Since much or even most advanced 3-D graphics machinery relies to a greater or lesser extent on dot products and cross products (even the line intersection formula I discussed in the last chapter is actually a quotient of dot products), I’m going to spend this chapter examining these basic tools and some of their 3-D applications. If this is old hat to you, my apologies, and I’ll return to BSP-based rendering in the next chapter.

        -

        Foundation Definitions

        +

        Foundation Definitions

        The dot and cross products themselves are straightforward and require almost no context to understand, but I need to define some terms I’ll use when describing applications of the products, so I’ll do that now, and then get started with dot products.

        I’m going to have to assume you have some math background, or we’ll never get to the good stuff. So, I’m just going to quickly define a vector as a direction and a magnitude, represented as a coordinate pair (in 2-D) or triplet (in 3-D), relative to the origin. That’s a pretty sloppy definition, but it’ll do for our purposes; if you want the Real McCoy, I suggest you check out Calculus and Analytic Geometry, by Thomas and Finney (Addison-Wesley: ISBN 0-201-52929-7).

        @@ -71,7 +70,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/61-02.html b/61-02.html index 4d5e8f9..8f26f5d 100644 --- a/61-02.html +++ b/61-02.html @@ -24,7 +24,7 @@ - +
        @@ -41,7 +41,7 @@

        For our purposes, projection is the process of mapping coordinates onto a line or surface. Perspective projection projects 3-D coordinates onto a viewplane, scaling coordinates according to their z distance from the viewpoint in order to provide proper perspective. Objectspace is the coordinate space in which an object is defined, independent of other objects and the world itself. Worldspace is the absolute frame of reference for a 3-D world; all objects’ locations and orientations are with respect to worldspace, and this is the frame of reference around which the viewpoint and view direction move. Viewspace is worldspace as seen from the viewpoint, looking in the view direction. Screenspace is viewspace after perspective projection and scaling to the screen.

        Finally, transformation is the process of converting points from one coordinate space into another; in our case, that’ll mean rotating and translating (moving) points from objectspace or worldspace to viewspace.

        For additional information, you might want to check out Foley & van Dam’s Computer Graphics (ISBN 0-201-12110-7), or the chapters in this book dealing with my X-Sharp 3-D graphics library.

        -

        The Dot Product

        +

        The Dot Product

        Now we’re ready to move on to the dot product. Given two vectors U = [u1 u2 u3] and V = [v1 v2 v3], their dot product, denoted by the symbol •, is calculated as:

        @@ -52,7 +52,7 @@

        (eq. 3)

        where q is the angle between the two vectors, and the other two terms are the lengths of the vectors, as shown in Figure 61.1. Although it’s not immediately obvious, equation 3 has a wide variety of applications in 3-D graphics.

        -

        Dot Products of Unit Vectors

        +

        Dot Products of Unit Vectors

        The simplest case of the dot product is when both vectors are unit vectors; that is, when their lengths are both one, as calculated as in Equation 1. In this case, equation 3 simplifies to:

        @@ -63,19 +63,19 @@

        (eq. 5)


        Figure 61.1
          The dot product. +
        -->Figure 61.1  The dot product.

        where Is is the intensity of illumination of the surface, Il is the intensity of the light, and q is the angle between -Dl (where Dl is the light direction vector) and the surface normal. If the inverse light vector and the surface normal are both unit vectors, then this calculation can be performed with four multiplies and three additions—and no explicit cosine calculations—as

        (eq. 6)

        where Ns is the surface unit normal and Dl is the light unit direction vector, as shown in Figure 61.2.

        -

        Cross Products and the Generation of Polygon Normals

        +

        Cross Products and the Generation of Polygon Normals

        One question equation 6 begs is where the surface unit normal comes from. One approach is to store the end of a surface normal as an extra data point with each polygon (with the start being some point that’s already in the polygon), and transform it along with the rest of the points. This has the advantage that if the normal starts out as a unit normal, it will end up that way too, if only rotations and translations (but not scaling and shears) are performed.

        The problem with having an explicit normal is that it will remain a normal—that is, perpendicular to the surface—only through viewspace. Rotation, translation, and scaling preserve right angles, which is why normals are still normals in viewspace, but perspective projection does not preserve angles, so vectors that were surface normals in viewspace are no longer normals in screenspace.


        Figure 61.2
          The dot product as used in calculating lighting intensity. +
        -->Figure 61.2  The dot product as used in calculating lighting intensity.


        @@ -89,7 +89,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/61-03.html b/61-03.html index 624b8e8..1b89786 100644 --- a/61-03.html +++ b/61-03.html @@ -24,7 +24,7 @@ - +
        @@ -40,7 +40,7 @@

        Why does this matter? It matters because, on average, half the polygons in any scene are facing away from the viewer, and hence shouldn’t be drawn. One way to identify such polygons is to see whether they’re facing toward or away from the viewer; that is, whether their normals have negative z values (so they’re visible) or positive z values (so they should be culled). However, we’re talking about screenspace normals here, because the perspective projection can shift a polygon relative to the viewpoint so that although its viewspace normal has a negative z, its screenspace normal has a positive z, and vice-versa, as shown in Figure 61.3. So we need screenspace normals, but those can’t readily be generated by transformation from worldspace.


        Figure 61.3
          A problem with determining front/back visibility. +
        -->Figure 61.3  A problem with determining front/back visibility.

        The solution is to use the cross product of two of the polygon’s edges to generate a normal. The formula for the cross product is:

        @@ -51,19 +51,19 @@
        In fact, we can cull with only one-third the work needed to generate a full cross product; because we’re interested only in the sign of the z component of the normal, we can skip entirely calculating the x and y components. The only caveat is to be careful that neither edge you choose is zero-length and that the edges aren’t collinear, because the dot product can’t produce a normal in those cases.


        Figure 61.4
          How the cross product of polygon edge vectors generates a polygon normal. +
        -->Figure 61.4  How the cross product of polygon edge vectors generates a polygon normal.

        Perhaps the most often asked question about cross products is “Which way do normals generated by cross products go?” In a left-handed coordinate system, curl the fingers of your left hand so the fingers curl through an angle of less than 180 degrees from the first vector in the cross product to the second vector. Your thumb now points in the direction of the normal.

        If you take the cross product of two orthogonal (right-angle) unit vectors, the result will be a unit vector that’s orthogonal to both of them. This means that if you’re generating a new coordinate space—such as a new viewing frame of reference—you only need to come up with unit vectors for two of the axes for the new coordinate space, and can then use their cross product to generate the unit vector for the third axis. If you need unit normals, and the two vectors being crossed aren’t orthogonal unit vectors, you’ll have to normalize the resulting vector; that is, divide each of the vector’s components by the length of the vector, to make it a unit long.

        -

        Using the Sign of the Dot Product

        +

        Using the Sign of the Dot Product

        The dot product is the cosine of the angle between two vectors, scaled by the magnitudes of the vectors. Magnitudes are always positive, so the sign of the cosine determines the sign of the result. The dot product is positive if the angle between the vectors is less than 90 degrees, negative if it’s greater than 90 degrees, and zero if the angle is exactly 90 degrees. This means that just the sign of the dot product suffices for tests involving comparisons of angles to 90 degrees, and there are more of those than you’d think.

        Consider, for example, the process of backface culling, which we discussed above in the context of using screenspace normals to determine polygon orientation relative to the viewer. The problem with that approach is that it requires each polygon to be transformed into viewspace, then perspective projected into screenspace, before the test can be performed, and that involves a lot of time-consuming calculation. Instead, we can perform culling way back in worldspace (or even earlier, in objectspace, if we transform the viewpoint into that frame of reference), given only a vertex and a normal for each polygon and a location for the viewer.

        Here’s the trick: Calculate the vector from the viewpoint to any vertex in the polygon and take its dot product with the polygon’s normal, as shown in Figure 61.5. If the polygon is facing the viewpoint, the result is negative, because the angle between the two vectors is greater than 90 degrees. If the polygon is facing away, the result is positive, and if the polygon is edge-on, the result is 0. That’s all there is to it—and this sort of backface culling happens before any transformation or projection at all is performed, saving a great deal of work for the half of all polygons, on average, that are culled.

        Backface culling with the dot product is just a special case of determining which side of a plane any point (in this case, the viewpoint) is on. The same trick can be applied whenever you want to determine whether a point is in front of or behind a plane, where a plane is described by any point that’s on the plane (which I’ll call the plane origin), plus a plane normal. One such application is in clipping a line (such as a polygon edge) to a plane. Just do a dot product between the plane normal and the vector from one line endpoint to the plane origin, and repeat for the other line endpoint. If the signs of the dot products are the same, no clipping is needed; if they differ, clipping is needed. And yes, the dot product is also the way to do the actual clipping; but before we can talk about that, we need to understand the use of the dot product for projection.


        Figure 61.5
          Backface culling with the dot product. +
        -->Figure 61.5  Backface culling with the dot product.


        @@ -77,7 +77,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/61-04.html b/61-04.html index 2368137..fb365a7 100644 --- a/61-04.html +++ b/61-04.html @@ -24,7 +24,7 @@ - +
        @@ -37,14 +37,14 @@


        -

        Using the Dot Product for Projection

        +

        Using the Dot Product for Projection

        Consider Equation 3 again, but this time make one of the vectors, say V, a unit vector. Now the equation reduces to:

        (eq. 8)

        In other words, the result is the cosine of the angle between the two vectors, scaled by the magnitude of the non-unit vector. Now, consider that cosine is really just the length of the adjacent leg of a right triangle, and think of the non-unit vector as the hypotenuse of a right triangle, and remember that all sides of similar triangles scale equally. What it all works out to is that the value of the dot product of any vector with a unit vector is the length of the first vector projected onto the unit vector, as shown in Figure 61.6.


        Figure 61.6
          How the dot product with a unit vector performs a projection. +
        -->Figure 61.6  How the dot product with a unit vector performs a projection.

        This unlocks all sorts of neat stuff. Want to know the distance from a point to a plane? Just dot the vector from the point P to the plane origin Op with the plane unit normal Np, to project the vector onto the normal, then take the absolute value

        @@ -89,11 +89,11 @@ void LineIntersectPlane (float *linestart, float *lineend, } -

        Rotation by Projection

        +

        Rotation by Projection

        We can use the dot product’s projection capability to look at rotation in an interesting way. Typically, rotations are represented by matrices. This is certainly a workable representation that encapsulates all aspects of transformation in a single object, and is ideal for concatenations of rotations and translations. One problem with matrices, though, is that many people, myself included, have a hard time looking at a matrix of sines and cosines and visualizing what’s actually going on. So when two 3-D experts, John Carmack and Billy Zelsnack, mentioned that they think of rotation differently, in a way that seemed more intuitive to me, I thought it was worth passing on.


        Figure 61.7
          Using the dot product to get the distance from a point to a plane. +
        -->Figure 61.7  Using the dot product to get the distance from a point to a plane.

        Their approach is this: Think of rotation as projecting coordinates onto new axes. That is, given that you have points in, say, worldspace, define the new coordinate space (viewspace, for example) you want to rotate to by a set of three orthogonal unit vectors defining the new axes, and then project each point onto each of the three axes to get the coordinates in the new coordinate space, as shown for the 2-D case in Figure 61.8. In 3-D, this involves three dot products per point, one to project the point onto each axis. Translation can be done separately from rotation by simple addition.

        @@ -102,7 +102,7 @@ void LineIntersectPlane (float *linestart, float *lineend,

        Three things I’ve learned over the years are that it never hurts to learn a new way of looking at things, that it helps to have a clearer, more intuitive model in your head of whatever it is you’re working on, and that new tools, or new ways to use old tools, are Good Things. My experience has been that rotation by projection, and dot product tricks in general, offer those sorts of benefits for 3-D.


        Figure 61.8
          Rotation to a new coordinate space by projection onto new axes. +
        -->Figure 61.8  Rotation to a new coordinate space by projection onto new axes.


        @@ -116,7 +116,7 @@ void LineIntersectPlane (float *linestart, float *lineend,
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/62-01.html b/62-01.html index 0ac4f88..a6c3584 100644 --- a/62-01.html +++ b/62-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 62
        One Story, Two Rules, and a BSP Renderer -

        -

        Taking a Compiled BSP Tree from Logical to Visual Reality

        +

        Chapter 62
        One Story, Two Rules, and a BSP Renderer

        +

        Taking a Compiled BSP Tree from Logical to Visual Reality

        As I’ve noted before, I’m working on Quake, id Software’s follow-up to DOOM. A month or so back, we added page flipping to Quake, and made the startling discovery that the program ran nearly twice as fast with page flipping as it did with the alternative method of drawing the whole frame to system memory, then copying it to the screen. We were delighted by this, but baffled. I did a few tests and came up with several possible explanations, including slow writes through the external cache, poor main memory performance, and cache misses when copying the frame from system memory to video memory. Although each of these can indeed affect performance, none seemed to account for the magnitude of the speedup, so I assumed there was some hidden hardware interaction at work. Anyway, “why” was secondary; what really mattered was that we had a way to double performance, which meant I had a lot of work to do to support page flipping as widely as possible.

        A few days ago, I was using the Pentium’s built-in performance counters to seek out areas for improvement in Quake and, for no particular reason, checked the number of writes performed while copying the frame to the screen in non-page-flipped mode. The answer was 64,000. That seemed odd, since there were 64,000 byte-sized pixels to copy, and I was calling memcpy(), which of course performs copies a dword at a time whenever possible. I thought maybe the Pentium counters report the number of bytes written rather than the number of writes performed, but fortunately, this time I tested my assumptions by writing an ASM routine to copy the frame a dword at a time, without the help of memcpy(). This time the Pentium counters reported 16,000 writes.

        @@ -50,12 +49,12 @@

        By the way, I have found the Pentium’s performance counters to be very useful in of information on the performance counters and other aspects of the Pentium is Mike Schmit’s book, Pentium Processor Optimization Tools, AP Professional, ISBN 0-12-627230-1.

        Onward to rendering from a BSP tree.

        -

        BSP-based Rendering

        +

        BSP-based Rendering

        For the last several chapters I’ve been discussing the nature of BSP (Binary Space Partitioning) trees, and in Chapter 60 I presented a compiler for 2-D BSP trees. Now we’re ready to use those compiled BSP trees to do realtime rendering.

        As you’ll recall, the BSP compiler took a list of vertical walls and built a 2-D BSP tree from the walls, as viewed from above. The result is shown in Figure 62.1. The world is split into two pieces by the line of the root wall, and each half of the world is then split again by the root’s children, and so on, until the world is carved into subspaces along the lines of all the walls.


        Figure 62.1
          Vertical walls and a BSP tree to represent them. +
        -->Figure 62.1  Vertical walls and a BSP tree to represent them.

        Our objective is to draw the world so that whenever walls overlap we see the nearer wall at each overlapped pixel. The simplest way to do that is with the painter’s algorithm; that is, drawing the walls in back-to-front order, assuming no polygons interpenetrate or form cycles. BSP trees guarantee that no polygons interpenetrate (such polygons are automatically split), and make it easy to walk the polygons in back-to-front (or front-to-back) order.

        @@ -72,7 +71,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/62-02.html b/62-02.html index 761e13d..beff329 100644 --- a/62-02.html +++ b/62-02.html @@ -24,7 +24,7 @@ - +
        @@ -493,7 +493,7 @@ void UpdateWorld()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/62-03.html b/62-03.html index f1873f4..549dba3 100644 --- a/62-03.html +++ b/62-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        The Rendering Pipeline

        +

        The Rendering Pipeline

        Conceptually rendering from a BSP tree really is that simple, but the implementation is a bit more complicated. The full rendering pipeline, as coordinated by UpdateWorld(), is this:

        • Update the current location.
        • @@ -46,27 +46,27 @@
        • Walk the walls back to front, and for each wall that lies at least partially in the view pyramid, perform backface culling (skip walls facing away from the viewer), and draw the wall if it’s not culled.

        Next, we’ll look at each part of the pipeline more closely. The pipeline is too complex for me to be able to discuss each part in complete detail. Some sources for further reading are Computer Graphics, by Foley and van Dam (ISBN 0-201-12110-7), and the DDJ Essential Books on Graphics Programming CD.

        -

        Moving the Viewer

        +

        Moving the Viewer

        The sample BSP program performs first-person rendering; that is, it renders the world as seen from your eyes as you move about. The rate of movement is controlled by key-handling code that’s not shown in Listing 62.1; however, the variables set by the key-handling code are used in UpdateViewPos() to bring the current location up to date.

        Note that the view position can change not only in x and z (movement around the but only viewing horizontally. Although the BSP tree is only 2-D, it is quite possible to support looking up and down to at least some extent, particularly if the world dataset is restricted so that, for example, there are never two rooms stacked on top of each other, or any tilted walls. For simplicity’s sake, I have chosen not to implement this in Listing 62.1, but you may find it educational to add it to the program yourself.

        -

        Transformation into Viewspace

        +

        Transformation into Viewspace

        The viewing angle (which controls direction of movement as well as view direction) can sweep through the full 360 degrees around the viewpoint, so long as it remains horizontal. The viewing angle is controlled by the key handler, and is used to define a unit vector stored in currentorientation that explicitly defines the view direction (the z axis of viewspace), and implicitly defines the x axis of viewspace, because that axis is at right angles to the z axis, where x increases to the right of the viewer.

        As I discussed in the previous chapter, rotation to a new coordinate system can be performed by using the dot product to project points onto the axes of the new coordinate system, and that’s what TransformVertices() does, after first translating (moving) the coordinate system to have its origin at the viewpoint. (It’s necessary to perform the translation first so that the viewing rotation is around the viewpoint.) Note that this operation can equivalently be viewed as a matrix math operation, and that this is in fact the more common way to handle transformations.

        At the same time, the points are scaled in x according to PROJECTION_RATIO to provide the desired field of view. Larger scale values result in narrower fields of view.

        When this is done the walls are in viewspace, ready to be clipped.

        -

        Clipping

        +

        Clipping

        In viewspace, the walls may be anywhere relative to the viewpoint: in front, behind, off to the side. We only want to draw those parts of walls that properly belong on the screen; that is, those parts that lie in the view pyramid (view frustum), as shown in Figure 62.2. Unclipped walls—walls that lie entirely in the frustum—should be drawn in their entirety, fully clipped walls should not be drawn, and partially clipped walls must be trimmed before being drawn.

        In Listing 62.1, ClipWalls() does this in three steps for each wall in turn. First, the z coordinates of the two ends of the wall are calculated. (Remember, walls are vertical and their ends go straight up and down, so the top and bottom of each end have the same x and z coordinates.) If both ends are on the near side of the front clip plane, then the polygon is fully clipped, and we’re done with it. If both ends are on the far side, then the polygon isn’t z-clipped, and we leave it unchanged. If the polygon straddles the near clip plane, then the wall is trimmed to stop at the near clip plane by adjusting the t value of the nearest endpoint appropriately; this calculation is a simple matter of scaling by z, because the near clip plane is at a constant z distance. (The use of t values for parametric lines was discussed in Chapter 60.) The process is further simplified because the walls can be treated as lines viewed from above, so we can perform 2-D clipping in z; this would not be the case if walls sloped or had sloping edges.

        After clipping in z, we clip by viewspace x coordinate, to ensure that we draw only wall portions that lie between the left and right edges of the screen. Like z-clipping, x-clipping can be done as a 2-D clip, because the walls and the left and right sides of the frustum are all vertical. We compare both the start and endpoint of each wall to the left and right sides of the frustum, and reject, accept, or clip each wall’s t values accordingly. The test for x clipping is very simple, because the edges of the frustum are defined as the planes where x==z and -x==z.


        Figure 62.2
          Clipping to the view pyramid. +
        -->Figure 62.2  Clipping to the view pyramid.

        The final clip stage is clipping by y coordinate, and this is the most complicated, because vertical walls can be clipped at an angle in y, as shown in Figure 62.3, so true 3-D clipping of all four wall vertices is involved. We handle this in ClipWalls() by detecting trivial rejection in y, using y==z and ==z as the y boundaries of the frustum. However, we leave partial clipping to be handled as a 2-D clipping problem; we are able to do this only because our earlier z-clip to the near clip plane guarantees that no remaining polygon point can have z<=0, ensuring that when we project we’ll always pass valid, y-clippable screenspace vertices to the polygon filler.

        -

        Projection to Screenspace

        +

        Projection to Screenspace

        At this point, we have viewspace vertices for each wall that’s at least partially visible. All we have to do is project these vertices according to z distance—that is, perform perspective projection—and scale the results to the width of the screen, then we’ll be ready to draw. Although this step is logically separate from clipping, it is performed as the last step for visible walls in ClipWalls().


        Figure 62.3
          Why y clipping is more complex than x or z clipping. +
        -->Figure 62.3  Why y clipping is more complex than x or z clipping.


        @@ -80,7 +80,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/62-04.html b/62-04.html index 35811e4..7a2ba6b 100644 --- a/62-04.html +++ b/62-04.html @@ -24,7 +24,7 @@ - +
        @@ -37,7 +37,7 @@


        -

        Walking the Tree, Backface Culling and Drawing

        +

        Walking the Tree, Backface Culling and Drawing

        Now that we have all the walls clipped to the frustum, with vertices projected into screen coordinates, all we have to do is draw them back to front; that’s the job of DrawWallsBackToFront(). Basically, this routine walks the BSP tree, descending recursively from each node to draw the farther children of each node first, then the wall at the node, then the nearer children. In the interests of efficiency, this particular implementation performs a data-recursive walk of the tree, rather than the more familiar code recursion. Interestingly, the performance speedup from data recursion turned out to be more modest than I had expected, based on past experience; see Chapter 59 for further details.

        As it comes to each wall, DrawWallsBackToFront() first descends to draw the farther subtree. Next, if the wall is both visible and pointing toward the viewer, it is drawn as a solid polygon. The polygon filler (not shown in Listing 62.1) is a modification of the polygon filler I presented in Chapters 38 and 39.

        It’s worth noting how backface culling and front/back wall orientation testing are performed. (Note that walls are always one-sided, visible only from the front.) I discussed backface culling in general in the previous chapter, and mentioned two possible approaches: generating a screenspace normal (perpendicular vector) to the polygon and seeing which way that points, or taking the world or screenspace dot product between the vector from the viewpoint to any polygon point and the polygon’s normal and checking the sign. Listing 62.1 does both, but because our BSP tree is 2-D and the viewer is always upright, we can save some work.

        @@ -45,9 +45,9 @@

        The wall orinetation test used for walking the BSP tree, performed in WallFacingViewer() takes the other approach, and checks the viewspace sign of the dot product of the wall’s normal with a vector from the viewpoint to the wall. Again, this code takes advantage of the 2-D nature of the tree to generate the wall normal by swapping x and z and altering signs. We can’t use the quicker screenspace x test here that we used for backface culling, because not all walls can be projected into screenspace; for example, trying to project a wall at z==0 would result in division by zero.

        All the visible, front-facing walls are drawn into a buffer by DrawWallsBackToFront(), then UpdateWorld() calls Win32 to copy the new frame to the screen. The frame of animation is complete.


        Figure 62.4
          Fast backspace culling test in screenspace. +
        -->Figure 62.4  Fast backspace culling test in screenspace.

        -

        Notes on the BSP Renderer

        +

        Notes on the BSP Renderer

        Listing 62.1 is far from complete or optimal. There is no such thing as a tiny BSP rendering demo, because 3D rendering, even when based on a 2-D BSP tree, requires a substantial amount of code and complexity. Listing 62.1 is reasonably close to a minimum rendering engine, and is specifically intended to illuminate basic BSP principles, given the space limitations of one chapter in a book that’s already larger than it should be. Think of Listing 62.1 as a learning tool and a starting point.

        The most obvious lack in Listing 62.1 is that there is no support for floors and ceilings; the walls float in space, unsupported. Is it necessary to go to 3-D BSP trees to get a normal-looking world?

        @@ -65,7 +65,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/63-01.html b/63-01.html index 96165f6..3393185 100644 --- a/63-01.html +++ b/63-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 63
        Floating-Point for Real-Time 3-D -

        -

        Knowing When to Hurl Conventional Math Wisdom Out the Window

        +

        Chapter 63
        Floating-Point for Real-Time 3-D

        +

        Knowing When to Hurl Conventional Math Wisdom Out the Window

        In a crisis, sometimes it’s best to go with the first solution that comes into your head—but not very often.

        When I turned 16, my mother had an aging, three-cylinder Saab—not one of the sporty Saabs that appeared in the late ’70s, but a blunt-nosed, ungainly little wagon that seated up to seven people in sardine-like comfort, with two of them perched on the gas tank. That was the car I learned to drive on, and the one I took whenever I wanted to go somewhere and my mother didn’t need it.

        @@ -52,14 +51,14 @@

        There’s a surprisingly close analog to this in programming. Often, when faced with a problem in his or her code, a programmer’s response is to come up with a solution as quickly as possible and immediately hack it in. For all but the simplest problems, though, there are side effects and design issues involved that should be thought through before any coding is done. I try to think of bugs and other problem situations as opportunities to reexamine how my code works, as well as chances to detect and correct structural defects I hadn’t previously suspected; in fact, I’m often able to simplify code as I fix a bug, thanks to the understanding I gain in the process.

        Taking that a step farther, it’s useful to reexamine assumptions periodically even if no bugs are involved. You might be surprised at how quickly assumptions that once were completely valid can deteriorate.

        For example, consider floating-point math.

        -

        Not Your Father’s Floating-Point

        +

        Not Your Father’s Floating-Point

        Until last year, I had never done any serious floating-point (FP) optimization, for the perfectly good reason that FP math had never been fast enough for any of the code I needed to write. It was an article of faith that FP, while undeniably convenient, because of its automatic support for constant precision over an enormous range of magnitudes, was just not fast enough for real-time programming, so I, like pretty much everyone else doing 3-D, expended a lot of time and effort in making fixed-point do the job.

        That article of faith was true up through the 486, but all the old assumptions are out the window on the Pentium, for three reasons: faster FP instructions, a pipelined floating-point unit (FPU), and the magic of a parallel FXCH. Taken together, these mean that FP addition and subtraction are nearly as fast as integer operations, and FP multiplication and division have the potential to be much faster—all with the range and precision advantages of FP. Better yet, the FPU has its own set of eight registers, so the use of floating-point can help relieve pressure on the x86’s integer registers, as well.

        One effect of all this is that with the Pentium, floating-point on the x86 has gone from being irrelevant to real-time 3-D to being a key element. Quake uses FP all the way down into the inner loop of the span rasterizer, performing several FP operations every 16 pixels.

        Floating-point has not only become important for real-time 3-D on the PC, but will soon become even more crucial. Hardware accelerators will take care of texture mapping and will increase feasible scene complexity, meaning the CPU will do less bit-twiddling and will have far more vertices to transform and project, and far more motion physics and line-of-sight calculations and the like as well.

        By way of getting you started with floating-point for real-time 3-D, in this chapter I’ll examine the basics of Pentium FP optimization, then look at how some key mathematical techniques for 3-D—dot product, cross product, transformation, and projection—can be accelerated.

        -

        Pentium Floating-Point Optimization

        +

        Pentium Floating-Point Optimization

        I’m going to assume you’re already familiar with x86 FP code in general; for additional information, check out Intel’s Pentium Processor User’s Manual (order #241430-001; 1-800-548-4725), a book that you should have if you’re doing Pentium programming of any sort. I’d also recommend taking a look around http://www.intel.com.

        I’m going to focus on six core instructions in this section: FLD, FST, FADD, FSUB, FMUL, and FDIV. First, let’s look at cycle times for these instructions. FLD takes 1 cycle; the value is pushed onto the FP stack and ready for use on the next cycle. FST takes 2 cycles, although when storing to memory, there’s a potential extra cycle that can be lost, as I’ll describe shortly.


        @@ -74,7 +73,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/63-02.html b/63-02.html index 44fb0b7..c1364ab 100644 --- a/63-02.html +++ b/63-02.html @@ -24,7 +24,7 @@ - +
        @@ -55,7 +55,7 @@ FST [temp]

        takes 6 cycles in all.) Again, it’s possible to execute integer-unit instructions during the 2 (or 3, for FST) cycles after one of these FP instructions starts. There’s a more exciting possibility here, though: Given properly structured code, the FPU is capable of averaging 1 cycle per FADD, FSUB, or FMUL. The secret is pipelining.

        -

        Pipelining, Latency, and Throughput

        +

        Pipelining, Latency, and Throughput

        The Pentium’s FPU is the first pipelined x86 FPU. Pipelining means that the FPU is capable of starting an instruction every cycle, and can simultaneously handle several instructions in various stages of completion. Only certain x86 FP instructions allow another instruction to start on the next cycle, though: FADD, FSUB, and FMUL are pipelined, but FST and FDIV are not. (FLD executes in a single cycle, so pipelining is not an issue.) Thus, in the code sequence

        @@ -100,7 +100,7 @@ FSUB ST(0),ST(1)
         
         

        where the ST(0) operand to FSUB is calculated by FADD. Here, FSUB can’t start until FADD has completed, so there are 2 stall cycles between the two instructions. When dependencies like this occur, the FPU runs at latency rather than throughput speeds, and performance can drop by as much as two-thirds.

        -

        FXCH

        +

        FXCH

        One piece of the puzzle is still missing. Clearly, to get maximum throughput, we need to interleave FP instructions, such that at any one time ideally three instructions are in the pipeline at once. Further, these instructions must not depend on one another for operands. But ST(0) must always be one of the operands; worse, FLD can only push into ST(0), and FST can only store from ST(0). How, then, can we keep three independent instructions going?

        The easy answer would be for Intel to change the FP registers from a stack to a set of independent registers. Since they couldn’t do that, thanks to compatibility issues, they did the next best thing: They made the FXCH instruction, which swaps ST(0) and any other FP register, virtually free. In general, if FXCH is both preceded and followed by FP instructions, then it takes no cycles to execute. (Application Note 500, “Optimizations for Intel’s 32-bit Processors,” February 1994, available from http://www.intel.com, describes all .the conditions under which FXCH is free.) This allows you to move the target of a pending operation from ST(0) to another register, at the same time bringing another register into ST(0) where it can be used, all at no cost. So, for example, we can start three multiplications, then use FXCH to swap back to start adding the results of the first two multiplications, without incurring any stalls, as shown in Listing 63.1.

        @@ -118,7 +118,7 @@ FSUB ST(0),ST(1) faddp st(2),st(0) ;starts on cycle 6
        -

        The Dot Product

        +

        The Dot Product

        Now we’re ready to look at fast FP for common 3-D operations; we’ll start by looking at how to speed up the dot product. As discussed in Chapter 30, the dot product is heavily used in 3-D to calculate cosines and to project points along vectors. The dot product is calculated as d = u1v1 + u2v2 + u3v3; with three loads, three multiplies, two adds, and a store, the theoretical minimum time for this calculation is 10 cycles.

        Listing 63.2 shows a straightforward dot product implementation. This version loses 7 cycles to stalls. Listing 63.3 cuts the loss to 5 cycles by doing all three FMULs first, then using FXCH to set the third FXCH aside to complete while the results of the first two FMULs, which have completed, are added. Listing 43.3 still loses 50 percent to stalls, but unless some other code is available to be interleaved with the dot product code, that’s all we can do to speed things up. Fortunately, dot products are often used in contexts where there’s plenty of interleaving potential, as we’ll see when we discuss transformation.


        @@ -133,7 +133,7 @@ FSUB ST(0),ST(1)
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/63-03.html b/63-03.html index 339839a..3522892 100644 --- a/63-03.html +++ b/63-03.html @@ -24,7 +24,7 @@ - +
        @@ -74,7 +74,7 @@ ; ends on cycle 14 -

        The Cross Product

        +

        The Cross Product

        When last we looked at the cross product, we found that it’s handy for generating a vector that’s normal to two other vectors. The cross product is calculated as [u2v3-u3v2 u3v1-u1v3 u1v2-u2v1]. The theoretical minimum cycle count for the cross product is 21 cycles. Listing 63.4 shows a straightforward implementation that calculates each component of the result separately, losing 15 cycles to stalls.

        Listing 63.4 L63-4.ASM

        @@ -142,7 +142,7 @@ ; ends on cycle 21 -

        Transformation

        +

        Transformation

        Transforming a point, for example from worldspace to viewspace, is one of the most heavily used FP operations in realtime 3-D. Conceptually, transformation is nothing more than three dot products and three additions, as I will discuss in Chapter 61. (Note that I’m talking about a subset of a general 4x4 transformation matrix, where the fourth row is always implicitly [0 0 0 1]. This limited form suffices for common transformations, and does 25 percent less work than a full 4x4 transformation.)

        Transformation is calculated as:

        @@ -178,7 +178,7 @@ v3 = m31u1 + m32u2 + m
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/63-04.html b/63-04.html index 69253df..fe98c12 100644 --- a/63-04.html +++ b/63-04.html @@ -24,7 +24,7 @@ - +
        @@ -83,14 +83,14 @@ ; ends on cycle 33 -

        Projection

        +

        Projection

        The final optimization we’ll look at is projection to screenspace. Projection itself is basically nothing more than a divide (to get 1/z), followed by two multiplies (to get x/z and y/z), so there wouldn’t seem to be much in the way of FP optimization possibilities there. However, remember that although FDIV has a latency of up to 39 cycles, it can overlap with integer instructions for all but one of those cycles. That means that if we can find enough independent integer work to do before we need the 1/z result, we can effectively reduce the cost of the FDIV to one cycle. Projection by itself doesn’t offer much with which to overlap, but other work such as clamping, window-relative adjustments, or 2-D clipping could be interleaved with the FDIV for the next point.

        Another dramatic speed-up is possible by setting the precision of the FPU down to single precision via FLDCW, thereby cutting the time FDIV takes to a mere 19 cycles. I don’t have the space to discuss reduced precision in detail in this book, but be aware that along with potentially greater performance, it carries certain risks, as well. The reduced precision, which affects FADD, FSUB, FMUL, FDIV, and FSQRT, can cause subtle differences from the results you’d get using compiler defaults. If you use reduced precision, you should be on the alert for precision-related problems, such as clipped values that vary more than you’d expect from the precise clip point, or the need for using larger epsilons in comparisons for point-on-plane tests.

        -

        Rounding Control

        +

        Rounding Control

        Another useful area that I can note only in passing here is that of leaving the FPU in a particular rounding mode while performing bulk operations of some sort. For example, conversion to int via the FIST instruction requires that the FPU be in chop mode. Unfortunately, the FLDCW instruction must be used to get the FPU into and out of chop mode, and each FLDCW takes 7 cycles, meaning that compilers often take at least 14 cycles for each float->int conversion. In assembly, you can just set the rounding state (or, likewise, the precision, for faster FDIVs) once at the start of the loop, and save all those FLDCW cycles each time through the loop. This is even more true for ceil(), which many compilers implement as horrendously inefficient subroutines, even though there are rounding modes for both ceil() and floor(). Again, though, be aware that results of FP calculations will be subtly different from compiler default behavior while chop, ceil, or floor mode is in effect.

        A final note: There are some speed-ups to be had by manipulating FP variables with integer instructions. Check out Chris Hecker’s column in the February/March 1996 issue of Game Developer for details.

        -

        A Farewell to 3-D Fixed-Point

        +

        A Farewell to 3-D Fixed-Point

        As with most optimizations, there are both benefits and hazards to floating-point acceleration, especially pedal-to-the-metal optimizations such as the last few I’ve mentioned. Nonetheless, I’ve found floating-point to be generally both more robust and easier to use than fixed-point even with those maximum optimizations. Now that floating-point is fast enough for real time, I don’t expect to be doing a whole lot of fixed-point 3-D math from here on out.

        And I won’t miss it a bit.


        @@ -106,7 +106,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/64-01.html b/64-01.html index 4bbf201..62eca81 100644 --- a/64-01.html +++ b/64-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 64
        Quake’s Visible-Surface Determination -

        -

        The Challenge of Separating All Things Seen from All Things Unseen

        +

        Chapter 64
        Quake’s Visible-Surface Determination

        +

        The Challenge of Separating All Things Seen from All Things Unseen

        Years ago, I was working at Video Seven, a now-vanished video adapter manufacturer, helping to develop a VGA clone. The fellow who was designing Video Seven’s VGA chip, Tom Wilson, had worked around the clock for months to make his VGA run as fast as possible, and was confident he had pretty much maxed out its performance. As Tom was putting the finishing touches on his chip design, however, news came fourth-hand that a competitor, Paradise, had juiced up the performance of the clone they were developing by putting in a FIFO.

        That was all he knew; there was no information about what sort of FIFO, or how much it helped, or anything else. Nonetheless, Tom, normally an affable, laid-back sort, took on the wide-awake, haunted look of a man with too much caffeine in him and no answers to show for it, as he tried to figure out, from hopelessly thin information, what Paradise had done. Finally, he concluded that Paradise must have put a write FIFO between the system bus and the VGA, so that when the CPU wrote to video memory, the write immediately went into the FIFO, allowing the CPU to keep on processing instead of stalling each time it wrote to display memory.

        @@ -52,7 +51,7 @@

        Generally, if you find your code getting more complex, you’re fine-tuning a frozen design, and it’s likely you can get more of a speed-up, with less code, by rethinking the design. A really good design should bring with it a moment of immense satisfaction in which everything falls into place, and you’re amazed at how little code is needed and how all the boundary cases just work properly.

        As for how to rethink the design, do it by pursuing whatever ideas occur to you, no matter how off-the-wall they seem. Many of the truly brilliant design ideas I’ve heard of over the years sounded like nonsense at first, because they didn’t fit my preconceived view of the world. Often, such ideas are in fact off-the-wall, but just as the news about Paradise’s chip sparked Tom’s imagination, aggressively pursuing seemingly outlandish ideas can open up new design possibilities for you.

        Case in point: The evolution of Quake’s 3-D graphics engine.

        -

        VSD: The Toughest 3-D Challenge of All

        +

        VSD: The Toughest 3-D Challenge of All

        I’ve spent most of my waking hours for the last several months working on Quake, id Software’s successor to DOOM, and I suspect I have a few more months to go. The very best things don’t happen easily, nor quickly—but when they happen, all the sweat becomes worthwhile.

        In terms of graphics, Quake is to DOOM as DOOM was to its predecessor, Wolfenstein 3-D. Quake adds true, arbitrary 3-D (you can look up and down, lean, and even fall on your side), detailed lighting and shadows, and 3-D monsters and players in place of DOOM’s sprites. Someday I hope to talk about how all that works, but for the here and now I want to talk about what is, in my opinion, the toughest 3-D problem of all: visible surface determination (drawing the proper surface at each pixel), and its close relative, culling (discarding non-visible polygons as quickly as possible, a way of accelerating visible surface determination). In the interests of brevity, I’ll use the abbreviation VSD to mean both visible surface determination and culling from now on.

        @@ -70,7 +69,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/64-02.html b/64-02.html index 7945d5c..2cc94f1 100644 --- a/64-02.html +++ b/64-02.html @@ -24,7 +24,7 @@ - +
        @@ -36,32 +36,32 @@


        -

        The Structure of Quake Levels

        +

        The Structure of Quake Levels

        Before diving into VSD, let me note that each Quake level is stored as a single huge 3-D BSP tree. This BSP tree, like any BSP, subdivides space, in this case along the planes of the polygons. However, unlike the BSP tree I presented in Chapter 62, Quake’s BSP tree does not store polygons in the tree nodes, as part of the splitting planes, but rather in the empty (non-solid) leaves, as shown in overhead view in Figure 64.1.

        Correct drawing order can be obtained by drawing the leaves in front-to-back or back-to-front BSP order, again as discussed in Chapter 62. Also, because BSP leaves are always convex and the polygons are on the boundaries of the BSP leaves, facing inward, the polygons in a given leaf can never obscure one another and can be drawn in any order. (This is a general property of convex polyhedra.)

        -

        Culling and Visible Surface Determination

        +

        Culling and Visible Surface Determination

        The process of VSD would ideally work as follows: First, you would cull all polygons that are completely outside the view frustum (view pyramid), and would clip away the irrelevant portions of any polygons that are partially outside. Then, you would draw only those pixels of each polygon that are actually visible from the current viewpoint, as shown in overhead view in Figure 64.2, wasting no time overdrawing pixels multiple times; note how little of the polygon sets in Figure 64.2 actually need to be drawn. Finally, in a perfect world, the tests to figure out what parts of which polygons are visible would be free, and the processing time would be the same for all possible viewpoints, giving the game a smooth visual flow.


        Figure 64.1
          Quake’s polygons are stored as empty leaves. +
        -->Figure 64.1  Quake’s polygons are stored as empty leaves.


        Figure 64.2
          Pixels visible from the current viewpoint. +
        -->Figure 64.2  Pixels visible from the current viewpoint.

        As it happens, it is easy to determine which polygons are outside the frustum or partially clipped, and it’s quite possible to figure out precisely which pixels need to be drawn. Alas, the world is far from perfect, and those tests are far from free, so the real trick is how to accelerate or skip various tests and still produce the desired result.

        As I discussed at length in Chapter 62, given a BSP, it’s easy and inexpensive to walk the world in front-to-back or back-to-front order. The simplest VSD solution, which I in fact demonstrated earlier, is to simply walk the tree back-to-front, clip each polygon to the frustum, and draw it if it’s facing forward and not entirely clipped (the painter’s algorithm). Is that an adequate solution?

        For relatively simple worlds, it is perfectly acceptable. It doesn’t scale very well, though. One problem is that as you add more polygons in the world, more transformations and tests have to be performed to cull polygons that aren’t visible; at some point, that will bog considerably performance down.

        -

        Nodes Inside and Outside the View Frustum

        +

        Nodes Inside and Outside the View Frustum

        Happily, there’s a good workaround for this particular problem. As discussed earlier, each leaf of a BSP tree represents a convex subspace, with the nodes that bound the leaf delimiting the space. Perhaps less obvious is that each node in a BSP tree also describes a subspace—the subspace composed of all the node’s children, as shown in Figure 64.3. Another way of thinking of this is that each node splits the subspace into two pieces created by the nodes above it in the tree, and the node’s children then further carve that subspace into all the leaves that descend from the node.


        Figure 64.3
          The substance described by node E. +
        -->Figure 64.3  The substance described by node E.

        Since a node’s subspace is bounded and convex, it is possible to test whether it is entirely outside the frustum. If it is, all of the node’s children are certain to be fully clipped and can be rejected without any additional processing. Since most of the world is typically outside the frustum, many of the polygons in the world can be culled almost for free, in huge, node-subspace chunks. It’s relatively expensive to perform a perfect test for subspace clipping, so instead bounding spheres or boxes are often maintained for each node, specifically for culling tests.

        So culling to the frustum isn’t a problem, and the BSP can be used to draw back-to- front. What, then, is the problem?

        -

        Overdraw

        +

        Overdraw

        The problem John Carmack, the driving technical force behind DOOM and Quake, faced when he designed Quake was that in a complex world, many scenes have an awful lot of polygons in the frustum. Most of those polygons are partially or entirely obscured by other polygons, but the painter’s algorithm described earlier requires that every pixel of every polygon in the frustum be drawn, often only to be overdrawn. In a 10,000-polygon Quake level, it would be easy to get a worst-case overdraw level of 10 times or more; that is, in some frames each pixel could be drawn 10 times or more, on average. No rasterizer is fast enough to compensate for an order of such magnitude and more work than is actually necessary to show a scene; worse still, the painter’s algorithm will cause a vast difference between best-case and worst-case performance, so the frame rate can vary wildly as the viewer moves around.

        So the problem John faced was how to keep overdraw down to a manageable level, preferably drawing each pixel exactly once, but certainly no more than two or three times in the worst case. As with frustum culling, it would be ideal if he could eliminate all invisible polygons in the frustum with virtually no work. It would also be a plus if he could manage to draw only the visible parts of partially-visible polygons, but that was a balancing act in that it had to be a lower-cost operation than the overdraw that would otherwise result.

        @@ -79,7 +79,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/64-03.html b/64-03.html index 90a9b83..66e5253 100644 --- a/64-03.html +++ b/64-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,37 +36,37 @@


        -

        The Beam Tree

        +

        The Beam Tree

        John’s original Quake design was to draw front-to-back, using a second BSP tree to keep track of what parts of the screen were already drawn and which were still empty and therefore drawable by the remaining polygons. Logically, you can think of this BSP tree as being a 2-D region describing solid and empty areas of the screen, as shown in Figure 64.4, but in fact it is a 3-D tree, of the sort known as a beam tree. A beam tree is a collection of 3-D wedges (beams), bounded by planes, projecting out from some center point, in this case the viewpoint, as shown in Figure 64.5.

        In John’s design, the beam tree started out consisting of a single beam describing the frustum; everything outside that beam was marked solid (so nothing would draw there), and the inside of the beam was marked empty. As each new polygon was reached while walking the world BSP tree front-to-back, that polygon was converted to a beam by running planes from its edges through the viewpoint, and any part of the beam that intersected empty beams in the beam tree was considered drawable and added to the beam tree as a solid beam. This continued until either there were no more polygons or the beam tree became entirely solid. Once the beam tree was completed, the visible portions of the polygons that had contributed to the beam tree were drawn.


        Figure 64.4
          Partitioning the screen into 2-D regions. +
        -->Figure 64.4  Partitioning the screen into 2-D regions.


        Figure 64.5
          Beams as wedges projecting from the viewpoint to polygon edges. +
        -->Figure 64.5  Beams as wedges projecting from the viewpoint to polygon edges.

        The advantage to working with a 3-D beam tree, rather than a 2-D region, is that determining which side of a beam plane a polygon vertex is on involves only checking the sign of the dot product of the ray to the vertex and the plane normal, because all beam planes run through the origin (the viewpoint). Also, because a beam plane is completely described by a single normal, generating a beam from a polygon edge requires only a cross-product of the edge and a ray from the edge to the viewpoint. Finally, bounding spheres of BSP nodes can be used to do the aforementioned bulk culling to the frustum.

        The early-out feature of the beam tree—stopping when the beam tree becomes solid—seems appealing, because it appears to cap worst-case performance. Unfortunately, there are still scenes where it’s possible to see all the way to the sky or the back wall of the world, so in the worst case, all polygons in the frustum will still have to be tested against the beam tree. Similar problems can arise from tiny cracks due to numeric precision limitations. Beam-tree clipping is fairly time-consuming, and in scenes with long view distances, such as views across the top of a level, the total cost of beam processing slowed Quake’s frame rate to a crawl. So, in the end, the beam-tree approach proved to suffer from much the same malady as the painter’s algorithm: The worst case was much worse than the average case, and it didn’t scale well with increasing level complexity.

        -

        3-D Engine du Jour

        +

        3-D Engine du Jour

        Once the beam tree was working, John relentlessly worked at speeding up the 3-D engine, always trying to improve the design, rather than tweaking the implementation. At least once a week, and often every day, he would walk into my office and say “Last night I couldn’t get to sleep, so I was thinking...” and I’d know that I was about to get my mind stretched yet again. John tried many ways to improve the beam tree, with some success, but more interesting was the profusion of wildly different approaches that he generated, some of which were merely discussed, others of which were implemented in overnight or weekend-long bursts of coding, in both cases ultimately discarded or further evolved when they turned out not to meet the design criteria well enough. Here are some of those approaches, presented in minimal detail in the hopes that, like Tom Wilson with the Paradise FIFO, your imagination will be sparked.

        -

        Subdividing Raycast

        +

        Subdividing Raycast

        Rays are cast in an 8x8 screen-pixel grid; this is a highly efficient operation because the first intersection with a surface can be found by simply clipping the ray into the BSP tree, starting at the viewpoint, until a solid leaf is reached. If adjacent rays don’t hit the same surface, then a ray is cast halfway between, and so on until all adjacent rays either hit the same surface or are on adjacent pixels; then the block around each ray is drawn from the polygon that was hit. This scales very well, being limited by the number of pixels, with no overdraw. The problem is dropouts; it’s quite possible for small polygons to fall between rays and vanish.

        -

        Vertex-Free Surfaces

        +

        Vertex-Free Surfaces

        The world is represented by a set of surface planes. The polygons are implicit in the plane intersections, and are extracted from the planes as a final step before drawing. This makes for fast clipping and a very small data set (planes are far more compact than polygons), but it’s time-consuming to extract polygons from planes.

        -

        The Draw-Buffer

        +

        The Draw-Buffer

        Like a z-buffer, but with 1 bit per pixel, indicating whether the pixel has been drawn yet. This eliminates overdraw, but at the cost of an inner-loop buffer test, extra writes and cache misses, and, worst of all, considerable complexity. Variations include testing the draw-buffer a byte at a time and completely skipping fully-occluded bytes, or branching off each draw-buffer byte to one of 256 unrolled inner loops for drawing 0-8 pixels, in the process possibly taking advantage of the ability of the x86 to do the perspective floating-point divide in parallel while 8 pixels are processed.

        -

        Span-Based Drawing

        +

        Span-Based Drawing

        Polygons are rasterized into spans, which are added to a global span list and clipped against that list so that only the nearest span at each pixel remains. Little sorting is needed with front-to-back walking, because if there’s any overlap, the span already in the list is nearer. This eliminates overdraw, but at the cost of a lot of span arithmetic; also, every polygon still has to be turned into spans.

        -

        Portals

        +

        Portals

        The holes where polygons are missing on surfaces are tracked, because it’s only through such portals that line-of-sight can extend. Drawing goes front-to-back, and when a portal is encountered, polygons and portals behind it are clipped to its limits, until no polygons or portals remain visible. Applied recursively, this allows drawing only the visible portions of visible polygons, but at the cost of a considerable amount of portal clipping.

        -

        Breakthrough!

        +

        Breakthrough!

        In the end, John decided that the beam tree was a sort of second-order structure, reflecting information already implicitly contained in the world BSP tree, so he tackled the problem of extracting visibility information directly from the world BSP tree. He spent a week on this, as a byproduct devising a perfect DOOM (2-D) visibility architecture, whereby a single, linear walk of a DOOM BSP tree produces zero-overdraw 2-D visibility. Doing the same in 3-D turned out to be a much more complex problem, though, and by the end of the week John was frustrated by the increasing complexity and persistent glitches in the visibility code. Although the direct-BSP approach was getting closer to working, it was taking more and more tweaking, and a simple, clean design didn’t seem to be falling out. When I left work one Friday, John was preparing to try to get the direct-BSP approach working properly over the weekend.


        @@ -81,7 +81,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/64-04.html b/64-04.html index 7bf1283..2bb1dd5 100644 --- a/64-04.html +++ b/64-04.html @@ -24,7 +24,7 @@ - +
        @@ -41,7 +41,7 @@

        Size was a concern; initially, a raw, uncompressed potentially visible set (PVS) was several megabytes in size. However, the PVS could be stored as a bit vector, with 1 bit per leaf, a structure that shrunk a great deal with simple zero-byte compression. Those steps, along with changing the BSP heuristic to generate fewer leaves (choosing as the next splitter the polygon that splits the fewest other polygons appears to be the best heuristic) and sealing the outside of the levels so the BSPer can remove the outside surfaces, which can never be seen, eventually brought the PVS down to about 20 Kb for a good-size level.

        In exchange for that 20 Kb, culling leaves outside the frustum is speeded up (because only leaves in the PVS are considered), and culling inside the frustum costs nothing more than a little overdraw (the PVS for a leaf includes all leaves visible from anywhere in the leaf, so some overdraw, typically on the order of 50 percent but ranging up to 150 percent, generally occurs). Better yet, precalculating the PVS results in a leveling of performance; worst case is no longer much worse than best case, because there’s no longer extra VSD processing—just more polygons and perhaps some extra overdraw—associated with complex scenes. The first time John showed me his working prototype, I went to the most complex scene I knew of, a place where the frame rate used to grind down into the single digits, and spun around smoothly, with no perceptible slowdown.

        John says precalculating the PVS was a logical evolution of the approaches he had been considering, that there was no moment when he said “Eureka!” Nonetheless, it was clearly a breakthrough to a brand-new, superior design, a design that, together with a still-in-development sorted-edge rasterizer that completely eliminates overdraw, comes remarkably close to meeting the “perfect-world” specifications we laid out at the start.

        -

        Simplify, and Keep on Trying New Things

        +

        Simplify, and Keep on Trying New Things

        What does it all mean? Exactly what I said up front: Simplify, and keep trying new things. The precalculated PVS is simpler than any of the other schemes that had been considered (although precalculating the PVS is an interesting task that I’ll discuss another time). In fact, at runtime the precalculated PVS is just a constrained version of the painter’s algorithm. Does that mean it’s not particularly profound?

        Not at all. All really great designs seem simple and even obvious—once they’ve been designed. But the process of getting there requires incredible persistence and a willingness to try lots of different ideas until the right one falls into place, as happened here.

        @@ -52,11 +52,11 @@

        The hardest thing in the world is to step outside a familiar, pretty good solution to a difficult problem and look for a different, better solution. The best ways I know to do that are to keep trying new, wacky things, and always, always, always try to simplify. One of John’s goals is to have fewer lines of code in each 3-D game than in the previous game, on the assumption that as he learns more, he should be able to do things better with less code.

        So far, it seems to have worked out pretty well for him.

        -

        Learn Now, Pay Forward

        +

        Learn Now, Pay Forward

        There’s one other thing I’d like to mention before I close this chapter. Much of what I’ve learned, and a great deal of what I’ve written, has been in the pages of Dr. Dobb’s Journal. As far back as I can remember, DDJ has epitomized the attitude that sharing programming information is A Good Thing. I know a lot of programmers who were able to leap ahead in their development because of Hendrix’s Tiny C, or Stevens’ D-Flat, or simply by browsing through DDJ’s annual collections. (Me, for one.) Understandably, most companies understandably view sharing information in a very different way, as potential profit lost—but that’s what makes DDJ so valuable to the programming community.

        It is in that spirit that id Software is allowing me to describe in these pages (which also appeared in one of the DDJ special issues) how Quake works, even before Quake has shipped. That’s also why id has placed the full source code for Wolfenstein 3-D on ftp.idsoftware.com/idstuff/source; and although you can’t just recompile the code and sell it, you can learn how a full-blown, successful game works. Check wolfsrc.txt in the above-mentioned directory for details on how the code may be used.

        So remember, when it’s legally possible, sharing information benefits us all in the long run. You can pay forward the debt for the information you gain here and elsewhere by sharing what you know whenever you can, by writing an article or book or posting on the Net. None of us learns in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!

        -

        References

        +

        References

        Foley, James D., et al., Computer Graphics: Principles and Practice, Addison Wesley, 1990, ISBN 0-201-12110-7 (beams, BSP trees, VSD).

        Teller, Seth, Visibility Computations in Densely Occluded Polyhedral Environments (dissertation), available on http://theory.lcs.mit.edu/~seth/ along with several other papers relevant to visibility determination.

        Teller, Seth, Visibility Preprocessing for Interactive Walkthroughs, SIGGRAPH 91 proceedings, pp. 61-69.


        @@ -72,7 +72,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/65-01.html b/65-01.html index 6702f27..67fdffc 100644 --- a/65-01.html +++ b/65-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 65
        3-D Clipping and Other Thoughts -

        -

        Determining What’s Inside Your Field of View

        +

        Chapter 65
        3-D Clipping and Other Thoughts

        +

        Determining What’s Inside Your Field of View

        Our part of the world is changing, and I’m concerned. By way of explanation, three anecdotes.

        Anecdote the first: In the introduction to one of his books, Frank Herbert, author of Dune, told how he had once been approached by a friend who claimed he (the friend) had a killer idea for an SF story, and offered to tell it to Herbert. In return, Herbert had to agree that if he used the idea in a story, he’d split the money from the story with this fellow. Herbert’s response was that ideas were a dime a dozen; he had more story ideas than he could ever write in a lifetime. The hard part was the writing, not the ideas.

        @@ -51,7 +50,7 @@

        Extend that to programming. The way it should work is that a steady flow of information circulates, so that everyone can do the best work they’re capable of. The idea is that I don’t gain by intellectually impoverishing you, and vice-versa; as we both compete and (intentionally or otherwise) share ideas, both our products become better, so the market grows larger and everyone benefits.

        That’s the way things have worked with programming for a long time. So far as I can see it has worked remarkably well, and the recent signs of change make me concerned about the future of our profession.

        Things aren’t changing everywhere, though; over the past year, I’ve circulated a good bit of info about 3-D graphics, and plan to keep on doing it as long as I can. Next, we’re going to take a look at 3-D clipping.

        -

        3-D Clipping Basics

        +

        3-D Clipping Basics

        Before I got deeply into 3-D, I kept hearing how difficult 3-D clipping was, so I was pleasantly surprised when I actually got around to doing it and found that it was quite straightforward, after all. At heart, 3-D clipping is nothing more than evaluating whether and where a line intersects a plane; in this context, the plane is considered to have an “inside” (a side on which points are to be kept) and an “outside” (a side on which points are to be removed or clipped). We can easily extend this single operation to polygon clipping, working with the line segments that form the edges of a polygon.

        The most common application of 3-D clipping is as part of the process of hidden surface removal. In this application, the four planes that make up the view volume, or view frustum, are used to clip away parts of polygons that aren’t visible. Sometimes this process includes clipping to near and far plane, to restrict the depth of the scene. Other applications include clipping to splitting planes while building BSP trees, and clipping moving objects to convex sectors such as BSP leaves. The clipping principles I’ll cover apply to any sort of 3-D clipping task, but clipping to the frustum is the specific context in which I’ll discuss clipping below.

        @@ -68,7 +67,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/65-02.html b/65-02.html index 0c0de44..7272119 100644 --- a/65-02.html +++ b/65-02.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Intersecting a Line Segment with a Plane

        +

        Intersecting a Line Segment with a Plane

        The fundamental 3-D clipping operation is clipping a line segment to a plane. There are two parts to this operation: determining if the line is clipped by (intersects) the plane at all and, if it is clipped, calculating the point of intersection.

        Before we can intersect a line segment with a plane, we must first define how we’ll represent the line segment and the plane. The segment will be represented in the obvious way by the (x,y,z) coordinates of its two endpoints; this extends well to polygons, where each vertex is an (x,y,z) point. Planes can be described in many ways, among them are three points on the plane, a point on the plane and a unit normal, or a unit normal and a distance from the origin along the normal; we’ll use the latter definition. Further, we’ll define the normal to point to the inside (unclipped side) of the plane. The structures for points, polygons, and planes are shown in Listing 65.1.

        @@ -83,15 +83,15 @@ typedef struct {

        Now, remember that our definition of a plane is a unit normal and a distance along the normal. That means that we have a distance for the plane as part of the plane structure, and we can get the distance at which the plane would have to be to touch the point from the dot product of the point and the normal; a simple comparison of the two values suffices to tell us which side of the plane the point is on. If the dot product of the point and the plane normal is greater than the plane distance, then the point is in front of the plane (inside the volume being clipped to); if it’s less, then the point is outside the volume and should be clipped.

        After we do this twice, once for each line endpoint, we know everything necessary to categorize our line segment. If both endpoints are on the same side of the plane, there’s nothing more to do, because the line is either completely inside or completely outside; otherwise, it’s on to the next step, clipping the line to the plane by replacing the outside vertex with the point of intersection of the line and the plane. Happily, it turns out that we already have all of the information we need to do this.

        From our earlier tests, we already know the length from the plane, measured along the normal, to the inside endpoint; that’s just the distance, along the normal, of the inside endpoint from the origin (the dot product of the endpoint with the normal), minus the plane distance, as shown in Figure 65.1. We also know the length of the line segment, again measured as projected onto the normal; that’s the difference between the distances along the normal of the inside and outside endpoints from the origin. The ratio of these two lengths is the fraction of the segment that remains after clipping. If we scale the x, y, and z lengths of the line segment by that fraction, and add the results to the inside endpoint, we get a new, clipped endpoint at the point of intersection.

        -

        Polygon Clipping

        +

        Polygon Clipping

        Line clipping is fine for wireframe rendering, but what we really want to do is polygon rendering of solid models, which requires polygon clipping. As with line segments, the clipping process with polygons is to determine if they’re inside, outside, or partially inside the clip volume, lopping off any vertices that are outside the clip volume and substituting vertices at the intersection between the polygon and the clip plane, as shown in Figure 65.2.

        An easy way to clip a polygon is to decompose it into a set of edges, and clip each edge separately as a line segment. Let’s define a polygon as a set of vertices that wind clockwise around the outside of the polygonal area, as viewed from the front side of the polygon; the edges are implicitly defined by the order of the vertices. Thus, an edge is the line segment described by the two adjacent vertices that form its endpoints. We’ll clip a polygon by clipping each edge individually, emitting vertices for the resulting polygon as appropriate, depending on the clipping state of the edge. If the start point of the edge is inside, that point is added to the output polygon. Then, if the start and end points are in different states (one inside and one outside), we clip the edge to the plane, as described above, and add the point at which the line intersects the clip plane as the next polygon vertex, as shown in Figure 65.3. Listing 65.2 shows a polygon-clipping function.


        Figure 65.1
          The distance from the plane to the inside endpoint, measured along the normal. +
        -->Figure 65.1  The distance from the plane to the inside endpoint, measured along the normal.


        Figure 65.2
          Clipping a polygon. +
        -->Figure 65.2  Clipping a polygon.


        @@ -105,7 +105,7 @@ typedef struct {
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/65-03.html b/65-03.html index 3a2f9ab..e037bb5 100644 --- a/65-03.html +++ b/65-03.html @@ -24,7 +24,7 @@ - +
        @@ -95,11 +95,11 @@ int ClipToPlane(polygon_t *pin, plane_t *pplane, polygon_t *pout)

        Believe it or not, this technique, applied in turn to each edge, is all that’s needed to clip a polygon to a plane. Better yet, a polygon can be clipped to multiple planes by repeating the above process once for each clip plane, with each interation trimming away any part of the polygon that’s clipped by that particular plane.

        One particularly useful aspect of 3-D clipping is that if you’re drawing texture mapped polygons, texture coordinates can be clipped in exactly the same way as (x,y,z) coordinates. In fact, the very same fraction that’s used to advance x, y, and z from the inside point to the point of intersection with the clip plane can be used to advance the texture coordinates as well, so only one extra multiply and one extra add are required for each texture coordinate.

        -

        Clipping to the Frustum

        +

        Clipping to the Frustum

        Given a polygon-clipping function, it’s easy to clip to the frustum: set up the four planes for the sides of the frustum, with another one or two planes for near and far clipping, if desired; next, clip each potentially visible polygon to each plane in turn; then draw whatever polygons emerge from the clipping process. Listing 65.3 is the core code for a simple 3-D clipping example that allows you to move around and look at polygonal models from any angle. The full code for this program is available on the CD-ROM in the file DDJCLIP.ZIP.


        Figure 65.3
          Clipping a polygon edge. +
        -->Figure 65.3  Clipping a polygon edge.

        LISTING 65.3 L65_3.c

        @@ -425,7 +425,7 @@ void UpdateWorld()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/65-04.html b/65-04.html index 8e5532b..697530a 100644 --- a/65-04.html +++ b/65-04.html @@ -24,7 +24,7 @@ - +
        @@ -36,19 +36,19 @@


        -

        The Lessons of Listing 65.3

        +

        The Lessons of Listing 65.3

        There are several interesting points to Listing 65.3. First, floating-point arithmetic is used throughout the clipping process. While it is possible to use fixed-point, doing so requires considerable care regarding range and precision. Floating-point is much easier—and, with the Pentium generation of processors, is generally comparable in speed. In fact, for some operations, such as multiplication in general and division when the floating-point unit is in single-precision mode, floating-point is much faster. Check out Chris Hecker’s column in the February 1996 Game Developer for an interesting discussion along these lines.

        Second, the planes that form the frustum are shifted ever so slightly inward from their proper positions at the edge of the field of view. This guarantees that it’s never possible to generate a visible vertex exactly at the eyepoint, averting the divide-by-zero error that such a vertex would cause when projected and at no performance cost.

        Third, the orientation of the viewer relative to the world is specified via yaw, pitch, and roll angles, successively applied in that order. These angles are accumulated from frame to frame according to user input, and for each frame are used to rotate the view up, view right, and viewplane normal vectors, which define the world coordinate system, into the viewspace coordinate system; those transformed vectors in turn define the rotation from worldspace to viewspace. (See Chapter 61 for a discussion of coordinate systems and rotation, and take a look at Chapters 5 and 6 of Computer Graphics, by Foley and van Dam, for a broader overview.) One attractive aspect of accumulating angular rotations that are then applied to the coordinate system vectors is that there is no deterioration of the rotation matrix over time. This is in contrast to my X-Sharp package, in which I accumulated rotations by keeping a cumulative matrix of all the rotations ever performed; unfortunately, that approach caused roundoff error to accumulate, so objects began to warp visibly after many rotations.

        Fourth, Listing 65.3 processes each input polygon into a clipped polygon, one line segment at a time. It would be more efficient to process all the vertices, categorizing whether and how they’re clipped, and then perform a test such as the Cohen-Sutherland outcode test to detect trivial acceptance (the polygon is entirely inside) and sometimes trivial rejection (the polygon is fully outside) without ever dealing with the edges, and to identify which planes actually need to be clipped against, as discussed in “Line-Segment Clipping Revisited,” Dr. Dobb’s Journal, January 1996. Some clipping approaches also minimize the number of intersection calculations when a segment is clipped by multiple planes. Further, Listing 65.3 clips a polygon against each plane in turn, generating a new output polygon for each plane; it is possible and can be more efficient to generate the final, clipped polygon without any intermediate representations. For further reading on advanced clipping techniques, see the discussion starting on page 271 of Foley and van Dam.

        Finally, clipping in Listing 65.3 is performed in worldspace, rather than in viewspace. The frustum is backtransformed from viewspace (where it is defined, since it exists relative to the viewer) to worldspace for this purpose. Worldspace clipping allows us to transform only those vertices that are visible, rather than transforming all vertices into viewspace, then clipping them. However, the decision whether to clip in worldspace or viewspace is not clear-cut and is affected by several factors.

        -

        Advantages of Viewspace Clipping

        +

        Advantages of Viewspace Clipping

        Although viewspace clipping requires transforming vertices that may not be drawn, it has potential performance advantages. For example, in worldspace, near and far clip planes are just additional planes that have to be tested and clipped to, using dot products. In viewspace, near and far clip planes are typically planes with constant z coordinates, so testing whether a vertex is near or far-clipped can be performed with a single z compare, and the fractional distance along a line segment to a near or far clip intersection can be calculated with a couple of z subtractions and a divide; no dot products are needed.

        Similarly, if the field of view is exactly 90 degrees, so the frustum planes go out at 45 degree angles relative to the viewplane, then x==z and y==z along the clip planes. This means that the clipping status of a vertex can be determined with a simple comparison, far more quickly than the standard dot-product test. This lends itself particularly well to outcode-based clipping algorithms, since each compare can set one outcode bit.

        For a game, 90 degrees is a pretty good field of view, but can we get the same sort of efficient clipping if we need some other field of view? Sure. All we have to do is scale the x and y results of the world-to-view transformation to account for the field of view, so that the coordinates lie in a viewspace that’s normalized such that the frustum planes extend along lines of x==z and y==z. The resulting visible projected points span the range -1 to 1 (before scaling up to get pixel coordinates), just as with a 90-degree field of view, so the rest of the drawing pipeline remains unchanged. Better yet, there is no cost in performance because the adjustment can be added to the transformation matrix.

        I didn’t implement normalized clipping in Listing 65.3 because I wanted to illustrate the general 3-D clipping mechanism without additional complications, and because for many applications the dot product (which, after all, takes only 10-20 cycles on a Pentium) is sufficient. However, the more frustum clipping you’re doing, especially if most of the polygons are trivially visible, the more attractive the performance advantages of normalized clipping become.

        -

        Further Reading

        +

        Further Reading

        You now have the basics of 3-D clipping, but because fast clipping is central to high-performance 3-D, there’s a lot more to be learned. One good place for further reading is Foley and van Dam; another is Procedural Elements of Computer Graphics, by David F. Rogers. Read and understand either of these books, and you’ll know everything you need for world-class clipping.

        And, as you read, you might take a moment to consider how wonderful it is that anyone who’s interested can tap into so much expert knowledge for the price of a book—or, on the Internet, for free—with no strings attached. Our part of the world is a pretty good place right now, isn’t it?


        @@ -63,7 +63,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/66-01.html b/66-01.html index 120848e..a498898 100644 --- a/66-01.html +++ b/66-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,26 +36,25 @@


        -

        Chapter 66
        Quake’s Hidden-Surface Removal -

        -

        Struggling with Z-Order Solutions to the Hidden Surface Problem

        +

        Chapter 66
        Quake’s Hidden-Surface Removal

        +

        Struggling with Z-Order Solutions to the Hidden Surface Problem

        Okay, I admit it: I’m sick and tired of classic rock. Admittedly, it’s been a while, about 20 years, since I was last excited to hear anything by the Cars or Boston, and I was never particularly excited in the first place about Bob Seger or Queen, to say nothing of Elvis, so some things haven’t changed. But I knew something was up when I found myself changing the station on the Allman Brothers and Steely Dan and Pink Floyd and, God help me, the Beatles (just stuff like “Hello Goodbye” and “I’ll Cry Instead,” though, not “Ticket to Ride” or “A Day in the Life”; I’m not that far gone). It didn’t take long to figure out what the problem was; I’d been hearing the same songs for a quarter-century, and I was bored.

        I tell you this by way of explaining why it was that when my daughter and I drove back from dinner the other night, the radio in my car was tuned, for the first time ever, to a station whose slogan is “There is no alternative.”

        Now, we’re talking here about a 10-year-old who worships the Beatles and has been raised on a steady diet of oldies. She loves melodies, catchy songs, and good singers, none of which you’re likely to find on an alternative rock station. So it’s no surprise that when I turned on the radio, the first word out of her mouth was “Yuck!”

        What did surprise me was that after listening for a while, she said, “You know, Dad, it’s actually kind of interesting.”

        Apart from giving me a clue as to what sort of music I can expect to hear blasting through our house when she’s a teenager, her quick uptake on alternative rock (versus my decades-long devotion to the music of my youth) reminded me of something that it’s easy to forget as we become older and more set in our ways. It reminded me that it’s essential to keep an open mind, and to be willing, better yet, eager, to try new things. Programmers tend to become attached to familiar approaches, and are inclined to stick with whatever is currently doing the job adequately well, but in programming there are always alternatives, and I’ve found that they’re often worth considering.

        Not that I should have needed any reminding, considering the ever-evolving nature of Quake.

        -

        Creative Flux and Hidden Surfaces

        +

        Creative Flux and Hidden Surfaces

        Back in Chapter 64, I described the creative flux that led to John Carmack’s decision to use a precalculated potentially visible set (PVS) of polygons for each possible viewpoint in Quake, the game we’re developing here at id Software. The precalculated PVS meant that instead of having to spend a lot of time searching through the world database to find out which polygons were visible from the current viewpoint, we could simply draw all the polygons in the PVS from back-to-front (getting the ordering courtesy of the world BSP tree) and get the correct scene drawn with no searching at all; letting the back-to-front drawing perform the final stage of hidden-surface removal (HSR). This was a terrific idea, but it was far from the end of the road for Quake’s design.

        -

        Drawing Moving Objects

        +

        Drawing Moving Objects

        For one thing, there was still the question of how to sort and draw moving objects properly; in fact, this is the single technical question I’ve been asked most often in recent months, so I’ll take a moment to address it here. The primary problem is that a moving model can span multiple BSP leaves, with the leaves that are touched varying as the model moves; that, together with the possibility of multiple models in one leaf, means there’s no easy way to use BSP order to draw the models in correctly sorted order. When I wrote Chapter 64, we were drawing sprites (such as explosions), moveable BSP models (such as doors), and polygon models (such as monsters) by clipping each into all the leaves it touched, then drawing the appropriate parts as each BSP leaf was reached in back-to-front traversal. However, this didn’t solve the issue of sorting multiple moving models in a single leaf against each other, and also left some ugly sorting problems with complex polygon models.

        John solved the sorting issue for sprites and polygon models in a startlingly low-tech way: We now z-buffer them. (That is, before we draw each pixel, we compare its distance, or z, value with the z value of the pixel currently on the screen, drawing only if the new pixel is nearer than the current one.) First, we draw the basic world, walls, ceilings, and the like. No z-buffer testing is involved at this point (the world visible surface determination is done in a different way, as we’ll see soon); however, we do fill the z-buffer with the z values (actually, 1/z values, as discussed below) for all the world pixels. Z-filling is a much faster process than z-buffering the entire world would be, because no reads or compares are involved, just writes of z values. Once the drawing and z-filling of the world is done, we can simply draw the sprites and polygon models with z-buffering and get perfect sorting all around.

        -

        Performance Impact

        +

        Performance Impact

        Whenever a z-buffer is involved, the questions inevitably are: What’s the memory footprint and what’s the performance impact? Well, the memory footprint at 320x200 is 128K, not trivial but not a big deal for a game that requires 8 MB to run. The performance impact is about 10 percent for z-filling the world, and roughly 20 percent (with lots of variation) for drawing sprites and polygon models. In return, we get a perfectly sorted world, and also the ability to do additional effects, such as particle explosions and smoke, because the z-buffer lets us flawlessly sort such effects into the world. All in all, the use of the z-buffer vastly improved the visual quality and flexibility of the Quake engine, and also simplified the code quite a bit, at an acceptable memory and performance cost.

        -

        Leveling and Improving Performance

        +

        Leveling and Improving Performance

        As I said above, in the Quake architecture, the world itself is drawn first, without z-buffer reads or compares, but filling the z-buffer with the world polygons’ z values, and then the moving objects are drawn atop the world, using full z-buffering. Thus far, I’ve discussed how to draw moving objects. For the rest of this chapter, I’m going to talk about the other part of the drawing equation; that is, how to draw the world itself, where the entire world is stored as a single BSP tree and never moves.


        @@ -70,7 +69,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/66-02.html b/66-02.html index e14da1a..a55f631 100644 --- a/66-02.html +++ b/66-02.html @@ -24,7 +24,7 @@ - +
        @@ -43,23 +43,23 @@

        The precalculated PVS was an important step toward both faster and more level performance, because it eliminated the need to identify visible polygons, a relatively slow step that tended to be at its worst in the most complex scenes. Nonetheless, in some spots in real game levels the precalculated PVS contains five times more polygons than are actually visible; together with the back-to-front HSR approach, this created hot spots in which the frame rate bogged down visibly as hundreds of polygons are drawn back-to- front, most of those immediately getting overdrawn by nearer polygons. Raw performance in general was also reduced by the typical 50% overdraw resulting from drawing everything in the PVS. So, although drawing the PVS back-to-front as the final HSR stage worked and was an improvement over previous designs, it was not ideal. Surely, John thought, there’s a better way to leverage the PVS than back-to-front drawing.

        And indeed there is.

        -

        Sorted Spans

        +

        Sorted Spans

        The ideal final HSR stage for Quake would reject all the polygons in the PVS that are actually invisible, and draw only the visible pixels of the remaining polygons, with no overdraw, that is, with every pixel drawn exactly once, all at no performance cost, of course. One way to do that (although certainly not at zero cost) would be to draw the polygons from front-to-back, maintaining a region describing the currently occluded portions of the screen and clipping each polygon to that region before drawing it. That sounds promising, but it is in fact nothing more or less than the beam tree approach I described in Chapter 64, an approach that we found to have considerable overhead and serious leveling problems.

        We can do much better if we move the final HSR stage from the polygon level to the span level and use a sorted-spans approach. In essence, this approach consists of turning each polygon into a set of spans, as shown in Figure 66.1, and then sorting and clipping the spans against each other until only the visible portions of visible spans are left to be drawn, as shown in Figure 66.2. This may sound a lot like z-buffering (which is simply too slow for use in drawing the world, although it’s fine for smaller moving objects, as described earlier), but there are crucial differences.


        Figure 66.1
          Span generation. +
        -->Figure 66.1  Span generation.

        By contrast with z-buffering, only visible portions of visible spans are scanned out pixel by pixel (although all polygon edges must still be rasterized). Better yet, the sorting that z-buffering does at each pixel becomes a per-span operation with sorted spans, and because of the coherence implicit in a span list, each edge is sorted only against some of the spans on the same line and is clipped only to the few spans that it overlaps horizontally. Although complex scenes still take longer to process than simple scenes, the worst case isn’t as bad as with the beam tree or back-to-front approaches, because there’s no overdraw or scanning of hidden pixels, because complexity is limited to pixel resolution and because span coherence tends to limit the worst-case sorting in any one area of the screen. As a bonus, the output of sorted spans is in precisely the form that a low-level rasterizer needs, a set of span descriptors, each consisting of a start coordinate and a length.

        In short, the sorted spans approach meets our original criteria pretty well; although it isn’t zero-cost, it’s not horribly expensive, it completely eliminates both overdraw and pixel scanning of obscured portions of polygons and it tends to level worst-case performance. We wouldn’t want to rely on sorted spans alone as our hidden-surface mechanism, but the precalculated PVS reduces the number of polygons to a level that sorted spans can handle quite nicely.

        So we’ve found the approach we need; now it’s just a matter of writing some code and we’re on our way, right? Well, yes and no. Conceptually, the sorted-spans approach is simple, but it’s surprisingly difficult to implement, with a couple of major design choices to be made, a subtle mathematical element, and some tricky gotchas that I’ll have to defer until Chapter 67. Let’s look at the design choices first.

        -

        Edges versus Spans

        +

        Edges versus Spans

        The first design choice is whether to sort spans or edges (both of which fall into the general category of “sorted spans”). Although the results are the same both ways, a list of spans to be drawn, with no overdraw, the implementations and performance implications are quite different, because the sorting and clipping are performed using very different data structures.

        With span-sorting, spans are stored in x-sorted, linked list buckets, typically with one bucket per scan line. Each polygon in turn is rasterized into spans, as shown in Figure 66.1, and each span is sorted and clipped into the bucket for the scan line the span is on, as shown in Figure 66.2, so that at any time each bucket contains the nearest spans encountered thus far, always with no overlap. This approach involves generating all spans for each polygon in turn, with each span immediately being sorted, clipped, and added to the appropriate bucket.


        Figure 66.2
          Two sets of spans sorted and clipped against one another. +
        -->Figure 66.2  Two sets of spans sorted and clipped against one another.

        With edge-sorting, edges are stored in x-sorted, linked list buckets according to their start scan line. Each polygon in turn is decomposed into edges, cumulatively building a list of all the edges in the scene. Once all edges for all polygons in the view frustum have been added to the edge list, the whole list is scanned out in a single top-to-bottom, left-to-right pass. An active edge list (AEL) is maintained. With each step to a new scan line, edges that end on that scan line are removed from the AEL, active edges are stepped to their new x coordinates, edges starting on the new scan line are added to the AEL, and the edges are sorted by current x coordinate.


        @@ -75,7 +75,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/66-03.html b/66-03.html index 9e6730f..dd99992 100644 --- a/66-03.html +++ b/66-03.html @@ -24,7 +24,7 @@ - +
        @@ -42,16 +42,16 @@

        The spans that are generated with edge-sorting are exactly the same spans that ultimately emerge from span-sorting; the difference lies in the intermediate data structures that are used to sort the spans in the scene. With edge-sorting, the spans are kept implicit in the edges until the final set of visible spans is generated, so the sorting, clipping, and span emission is done as each edge adds or removes a polygon, based on the span state implied by the edge and the set of active polygons. With span-sorting, spans are immediately made explicit when each polygon is rasterized, and those intermediate spans are then sorted and clipped against other the spans on the scan line to generate the final spans, so the states of the spans are explicit at all times, and all work is done directly with spans.

        Both span-sorting and edge-sorting work well, and both have been employed successfully in commercial projects. We’ve chosen to use edge-sorting in Quake partly because it seems inherently more efficient, with excellent horizontal coherence that makes for minimal time spent sorting, in contrast with the potentially costly sorting into linked lists that span-sorting can involve. A more important reason, though, is that with edge-sorting we’re able to share edges between adjacent polygons, and that cuts the work involved in sorting, clipping, and rasterizing edges nearly in half, while also shrinking the world database quite a bit due to the sharing.


        Figure 66.3
          Activating a polygon when a leading edge is encountered in the AEL. +
        -->Figure 66.3  Activating a polygon when a leading edge is encountered in the AEL.

        One final advantage of edge-sorting is that it makes no distinction between convex and concave polygons. That’s not an important consideration for most graphics engines, but in Quake, edge clipping, transformation, projection, and sorting have become a major bottleneck, so we’re doing everything we can to get the polygon and edge counts down, and concave polygons help a lot in that regard. While it’s possible to handle concave polygons with span-sorting, that can involve significant performance penalties.


        Figure 66.4
          Deactivating a polygon when a trailing edge is encountered in the AEL. +
        -->Figure 66.4  Deactivating a polygon when a trailing edge is encountered in the AEL.

        Nonetheless, there’s no cut-and-dried answer as to which approach is better. In the end, span-sorting and edge-sorting amount to the same functionality, and the choice between them is a matter of whatever you feel most comfortable with. In Chapter 67, I’ll go into considerable detail about edge-sorting, complete with a full implementation. I’m going the spend the rest of this chapter laying the foundation for Chapter 67 by discussing sorting keys and 1/z calculation. In the process, I’m going to have to make a few forward references to aspects of edge-sorting that I haven’t yet covered in detail; my apologies, but it’s unavoidable, and all should become clear by the end of Chapter 67.

        -

        Edge-Sorting Keys

        +

        Edge-Sorting Keys

        Now that we know we’re going to sort edges, using them to emit spans for the polygons nearest the viewer, the question becomes: How can we tell which polygons are nearest? Ideally, we’d just store a sorting key in each polygon, and whenever a new edge came along, we’d compare its surface’s key to the keys of other currently active polygons, and could easily tell which polygon was nearest.

        That sounds too good to be true, but it is possible. If, for example, your world database is stored as a BSP tree, with all polygons clipped into the BSP leaves, then BSP walk order is a valid drawing order. So, for example, if you walk the BSP back-to-front, assigning each polygon an incrementally higher key as you reach it, polygons with higher keys are guaranteed to be in front of polygons with lower keys. This is the approach Quake used for a while, although a different approach is now being used, for reasons I’ll explain shortly.

        @@ -70,7 +70,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/66-04.html b/66-04.html index 3f74813..95f7e1b 100644 --- a/66-04.html +++ b/66-04.html @@ -24,7 +24,7 @@ - +
        @@ -42,7 +42,7 @@

        1/z = (a/d)x’ - (b/d)y’ + c/d

        where z is the viewspace z coordinate of the point on the plane that projects to screen coordinate (x’,y’) (the origin for this calculation is the center of projection, the point on the screen straight ahead of the viewpoint), [a b c] is the plane normal in viewspace, and d is the distance from the viewspace origin to the plane along the normal. Division is done only once per plane, because a, b, c, and d are per-plane constants.

        The full 1/z calculation requires two multiplies and two adds, all of which should be floating-point to avoid range errors. That much floating-point math sounds expensive but really isn’t, especially on a Pentium, where a plane’s 1/z value at any point can be calculated in as little as six cycles in assembly language.

        -

        Where That 1/Z Equation Comes From

        +

        Where That 1/Z Equation Comes From

        For those who are interested, here’s a quick derivation of the 1/z equation. The plane equation for a plane is

        ax + by + cz - d = 0

        @@ -51,12 +51,12 @@

        Inverting and distributing yields:

        = ax’/d - by’/d + c/d

        We’ll see 1/z sorting in action in Chapter 67.

        -

        Quake and Z-Sorting

        +

        Quake and Z-Sorting

        I mentioned earlier that Quake no longer uses BSP order as the sorting key; in fact, it uses 1/z as the key now. Elegant as the gradients are, calculating 1/z from them is clearly slower than just doing a compare on a BSP-ordered key, so why have we switched Quake to 1/z?

        The primary reason is to reduce the number of polygons. Drawing in BSP order means following certain rules, including the rule that polygons must be split if they cross BSP planes. This splitting increases the numbers of polygons and edges considerably. By sorting on 1/z, we’re able to leave polygons unsplit but still get correct drawing order, so we have far fewer edges to process and faster drawing overall, despite the added cost of 1/z sorting.

        Another advantage of 1/z sorting is that it solves the sorting issues I mentioned at the start involving moving models that are themselves small BSP trees. Sorting in world BSP order wouldn’t work here, because these models are separate BSPs, and there’s no easy way to work them into the world BSP’s sequence order. We don’t want to use z-buffering for these models because they’re often large objects such as doors, and we don’t want to lose the overdraw-reduction benefits that closed doors provide when drawn through the edge list. With sorted spans, the edges of moving BSP models are simply placed in the edge list (first clipping polygons so they don’t cross any solid world surfaces, to avoid complications associated with interpenetration), along with all the world edges, and 1/z sorting takes care of the rest.

        -

        Decisions Deferred

        +

        Decisions Deferred

        There is, without a doubt, an awful lot of information in the preceding pages, and it may not all connect together yet in your mind. The code and accompanying explanation in the next chapter should help; if you want to peek ahead, the code is available on the CD-ROM as DDJZSORT.ZIP in the directory for Chapter 67. You may also want to take a look at Foley and van Dam’s Computer Graphics or Rogers’ Procedural Elements for Computer Graphics.

        As I write this, it’s unclear whether Quake will end up sorting edges by BSP order or 1/z. Actually, there’s no guarantee that sorted spans in any form will be the final design. Sometimes it seems like we change graphics engines as often as they play Elvis on the ‘50s oldies stations (but, one would hope, with more aesthetically pleasing results!) and no doubt we’ll be considering the alternatives right up until the day we ship.


        @@ -71,7 +71,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/67-01.html b/67-01.html index 400d5d2..b9974db 100644 --- a/67-01.html +++ b/67-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,14 +36,13 @@


        -

        Chapter 67
        Sorted Spans in Action -

        -

        Implementing Independent Span Sorting for Rendering without Overdraw

        +

        Chapter 67
        Sorted Spans in Action

        +

        Implementing Independent Span Sorting for Rendering without Overdraw

        In Chapter 66, we dove headlong into the intricacies of hidden surface removal by way of z-sorted (actually, 1/z-sorted) spans. At the end of that chapter, I noted that we were currently using 1/z-sorted spans in Quake, but it was unclear whether we’d switch back to BSP order. Well, some time after that writing, it’s become clear: We’re back to sorting spans by BSP order.

        In Robert A. Heinlein’s wonderful story “The Man Who Sold the Moon,” the chief engineer of the Moon rocket project tries to figure out how to get a payload of three astronauts to the Moon and back. He starts out with a four-stage rocket design, but finds that it won’t do the job, so he adds a fifth stage. The fifth stage helps, but not quite enough, “Because,” he explains, “I’ve had to add in too much dead weight, that’s why.” (The dead weight is the control and safety equipment that goes with the fifth stage.) He then tries adding yet another stage, only to find that the sixth stage actually results in a net slowdown. In the end, he has to give up on the three-person design and build a one-person spacecraft instead.

        1/z-sorted spans in Quake turned out pretty much the same way, as we’ll see in a moment. First, though, I’d like to note up front that this chapter is very technical and builds heavily on material I covered earlier in this section of the book; if you haven’t already read Chapters 59 through 66, you really should. Make no mistake about it, this is commercial-quality stuff; in fact, the code in this chapter uses the same sorting technique as the test version of Quake, QTEST1.ZIP, that id Software placed on the Internet in early March 1996. This material is the Real McCoy, true reports from the leading edge, and I trust that you’ll be patient if careful rereading and some occasional catch-up reading of earlier chapters are required to absorb everything contained herein. Besides, the ultimate reference for any design is working code, which you’ll find, in part, in Listing 67.1, and in its entirety in the file DDJZSORT.ZIP on the CD-ROM.

        -

        Quake and Sorted Spans

        +

        Quake and Sorted Spans

        As you’ll recall from Chapter 66, Quake uses sorted spans to get zero overdraw while rendering the world, thereby both improving overall performance and leveling frame rates by speeding up scenes that would otherwise experience heavy overdraw. Our original design used spans sorted by BSP order; because we traverse the world BSP tree from front-to-back relative to the viewpoint, the order in which BSP nodes are visited is a guaranteed front-to-back sorting order. We simply gave each node an increasing BSP sequence number as it was visited, set each polygon’s sort key to the BSP sequence number of the node (BSP splitting plane) it lay on, and used those sort keys when generating spans.

        (In a change from earlier designs, polygons now are stored on nodes, rather than leaves, which are the convex subspaces carved out by the BSP tree. Visits to potentially visible leaves are used only to mark that the polygons that touch those leaves are visible and need to be drawn, and each marked-visible polygon is then drawn after everything in front of its node has been drawn. This results in less BSP splitting of polygons, which is A Good Thing, as explained below.)

        @@ -64,7 +63,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/67-02.html b/67-02.html index 1de02b7..a14255b 100644 --- a/67-02.html +++ b/67-02.html @@ -24,7 +24,7 @@ - +
        @@ -41,24 +41,24 @@

        We could have fixed those errors too; we’ll take a quick look at how to deal with such cases shortly. However, like the sixth rocket stage, the fixes would have made Quake slower than it had been with BSP sorting. So we gave up and went back to BSP order, and now the code is simpler and sorting works reliably. It’s too bad our experiment didn’t work out, but it wasn’t wasted time because in trying what we did we learned quite a bit. In particular, we learned that the information provided by a simple, reliable world ordering mechanism, such as a BSP tree, can do more good than is immediately apparent, in terms of both performance and solid code.

        Nonetheless, sorting on 1/z can be a valuable tool, used in the right context; drawing a Quake world just doesn’t happen to be such a case. In fact, sorting on 1/z is how we’re now handling the sorting of multiple BSP models that lie within the same world leaf in Quake. In this case, we don’t have the option of using BSP order (because we’re drawing multiple independent trees), so we’ve set restrictions on the BSP models to avoid running into the types of 1/z sorting errors we encountered drawing the Quake world. Next, we’ll look at another application in which sorting on 1/z is quite useful, one where objects move freely through space. As is so often the case in 3-D, there is no one “right” technique, but rather a great many different techniques, each one handy in the right situations. Often, a combination of techniques is beneficial; for example, the combination in Quake of BSP sorting for the world and 1/z sorting for BSP models in the same world leaf.

        For the remainder of this chapter, I’m going to look at the three main types of 1/z span sorting, then discuss a sample 3-D app built around 1/z span sorting.

        -

        Types of 1/z Span Sorting

        +

        Types of 1/z Span Sorting

        As a quick refresher: With 1/z span sorting, all the polygons in a scene are treated as sets of screenspace pixel spans, and 1/z (where z is distance from the viewpoint in viewspace, as measured along the viewplane normal) is used to sort the spans so that the nearest span overlapping each pixel is drawn. As I discussed in Chapter 66, in the sample program we’re actually going to do all our sorting with polygon edges, which represent spans in an implicit form.

        There are three types of 1/z span sorting, each requiring a different implementation. In order of increasing speed and decreasing complexity, they are: intersecting, abutting, and independent. (These are names of my own devising; I haven’t come across any standard nomenclature in the literature.)

        -

        Intersecting Span Sorting

        +

        Intersecting Span Sorting

        Intersecting span sorting occurs when polygons can interpenetrate. Thus, two spans may cross such that part of each span is visible, in which case the spans have to be split and drawn appropriately, as shown in Figure 67.1.


        Figure 67.1
          Intersecting span sorting. +
        -->Figure 67.1  Intersecting span sorting.

        Intersecting is the slowest and most complicated type of span sorting, because it is necessary to compare 1/z values at two points in order to detect interpenetration, and additional work must be done to split the spans as necessary. Thus, although intersecting span sorting certainly works, it’s not the first choice for performance.

        -

        Abutting Span Sorting

        +

        Abutting Span Sorting

        Abutting span sorting occurs when polygons that are not part of a continuous surface can butt up against one another, but don’t interpenetrate, as shown in Figure 67.2. This is the sorting used in Quake, where objects like doors often abut walls and floors, and turns out to be more complicated than you might think. The problem is that when an abutting polygon starts on a given scan line, as with polygon B in Figure 67.2, it starts at exactly the same 1/z value as the polygon it abuts, in this case, polygon A, so additional sorting is needed when these ties happen. Of course, the two-point sorting used for intersecting polygons would work, but we’d like to find something faster.

        As it turns out, the additional sorting for abutting polygons is actually quite simple; whichever polygon has a greater 1/z gradient with respect to screen x (that is, whichever polygon is heading fastest toward the viewer along the scan line) is the front one. The hard part is identifying when ties—that is, abutting polygons—occur; due to floating-point imprecision, as well as fixed-point edge-stepping imprecision that can move an edge slightly on the screen, calculations of 1/z from the combination of screen coordinates and 1/z gradients (as discussed last time) can be slightly off, so most tie cases will show up as near matches, not exact matches. This imprecision makes it necessary to perform two comparisons, one with an adjust-up by a small epsilon and one with an adjust-down, creating a range in which near-matches are considered matches. Fine-tuning this epsilon to catch all ties, without falsely reporting close-but-not-abutting edges as ties, proved to be troublesome in Quake, and the epsilon calculations and extra comparisons slowed things down.


        Figure 67.2
          Abutting span sorting. +
        -->Figure 67.2  Abutting span sorting.

        I do think that abutting 1/z span sorting could have been made reliable enough for production use in Quake, were it not that we share edges between adjacent polygons in Quake, so that the world is a large polygon mesh. When a polygon ends and is followed by an adjacent polygon that shares the edge that just ended, we simply assume that the adjacent polygon sorts relative to other active polygons in the same place as the one that ended (because the mesh is continuous and there’s no interpenetration), rather than doing a 1/z sort from scratch. This speeds things up by saving a lot of sorting, but it means that if there is a sorting error, a whole string of adjacent polygons can be sorted incorrectly, pulled in by the one missorted polygon. Missorting is a very real hazard when a polygon is very nearly perpendicular to the screen, so that the 1/z calculations push the limits of numeric precision, especially in single-precision floating point.

        @@ -75,7 +75,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/67-03.html b/67-03.html index 50c936a..5d8ae92 100644 --- a/67-03.html +++ b/67-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,11 +36,11 @@


        -

        Independent Span Sorting

        +

        Independent Span Sorting

        Finally, we come to independent span sorting, the simplest and fastest of the three, and the type the sample code in Listing 67.1 uses. Here, polygons never intersect or touch any other polygons except adjacent polygons with which they form a continuous mesh. This means that when a polygon starts on a scan line, a single 1/z comparison between that polygon and the polygons it overlaps on the screen is guaranteed to produce correct sorting, with no extra calculations or tricky cases to worry about.

        Independent span sorting is ideal for scenes with lots of moving objects that never actually touch each other, such as a space battle. Next, we’ll look at an implementation of independent 1/z span sorting.

        -

        1/z Span Sorting in Action

        +

        1/z Span Sorting in Action

        Listing 67.1 is a portion of a program that demonstrates independent 1/z span sorting. This program is based on the sample 3-D clipping program from Chapter 65; however, the earlier program did hidden surface removal (HSR) by simply z-sorting whole objects and drawing them back-to-front, while Listing 67.1 draws all polygons by way of a 1/z-sorted edge list. Consequently, where the earlier program worked only so long as object centers correctly described sorting order, Listing 67.1 works properly for all combinations of non-intersecting and non-abutting polygons. In particular, Listing 67.1 correctly handles concave polyhedra; a new L-shaped object (the data for which is not included in Listing 67.1) has been added to the sample program to illustrate this capability. The ability to handle complex shapes makes Listing 67.1 vastly more useful for real-world applications than the 3-D clipping demo from Chapter 65.

        Listing 67.1 L67_1.C

        @@ -493,7 +493,7 @@ void UpdateWorld()
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/67-04.html b/67-04.html index ac55222..24e05bf 100644 --- a/67-04.html +++ b/67-04.html @@ -24,7 +24,7 @@ - +
        @@ -56,7 +56,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/67-05.html b/67-05.html index 95975ff..ab95bd8 100644 --- a/67-05.html +++ b/67-05.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Implementation Notes

        +

        Implementation Notes

        Finally, a few notes on Listing 67.1. First, you’ll notice that although we clip all polygons to the view frustum in worldspace, we nonetheless later clamp them to valid screen coordinates before adding them to the edge list. This catches any cases where arithmetic imprecision results in clipped polygon vertices that are a bit outside the frustum. I’ve only found such imprecision to be significant at very small z distances, so clamping would probably be unnecessary if there were a near clip plane, and might not even be needed in Listing 67.1, because of the slight nudge inward that we give the frustum planes, as described in Chapter 65. However, my experience has consistently been that relying on worldspace or viewspace clipping to produce valid screen coordinates 100 percent of the time leads to sporadic and hard-to-debug errors.

        There is no separate routine to clear the background in Listing 67.1. Instead, a special background surface at an effectively infinite distance is added, so whenever no polygons are active the background color is drawn. If desired, it’s a simple matter to flag the background surface and draw the background specially. For example, the background could be drawn as a starfield or a cloudy sky.

        @@ -55,7 +55,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/68-01.html b/68-01.html index 008bdf2..f553cf9 100644 --- a/68-01.html +++ b/68-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,23 +36,22 @@


        -

        Chapter 68
        Quake’s Lighting Model -

        -

        A Radically Different Approach to Lighting Polygons

        +

        Chapter 68
        Quake’s Lighting Model

        +

        A Radically Different Approach to Lighting Polygons

        It was during my senior year in college that I discovered computer games. Not Wizardry, or Choplifter, or Ultima, because none of those existed yet—the game that hooked me was the original Star Trek game, in which you navigated from one 8x8 quadrant to another in search of starbases, occasionally firing phasers or photon torpedoes. This was less exciting than it sounds; after each move, the current quadrant had to be reprinted from scratch, along with the current stats—and the output device was a 10 cps printball console. A typical game took over an hour, during which nothing particularly stimulating ever happened (Klingons appeared periodically, but they politely waited for your next move before attacking, and your photon torpedoes never missed, so the outcome was never in doubt), but none of that mattered; nothing could detract from the sheer thrill of being in a computer-simulated universe.

        Then the college got a PDP-11 with four CRT terminals, and suddenly Star Trek could redraw in a second instead of a minute. Better yet, I found the source code for the Star Trek program in the recesses of the new system, the first time I’d ever seen any real-world code other than my own, and excitedly dove into it. One evening, as I was looking through the code, a really cute girl at the next terminal asked me for help getting a program to run. After I had helped her, eager to get to know her better, I said, “Want to see something? This is the actual source for the Star Trek game!” and proceeded to page through the code, describing each subroutine. We got to talking, and eventually I worked up the nerve to ask her out. She said sure, and we ended up having a good time, although things soon fell apart because of her two or three other boyfriends (I never did get an exact count). The interesting thing, though, was her response when I finally got around to asking her out. She said, “It’s about time!” When I asked what she meant, she said, “I’ve been trying to get you to ask me out all evening—but it took you forever! You didn’t actually think I was interested in that Star Trek program, did you?”

        Actually, yes, I had thought that, because I was interested in it. One thing I learned from that experience, and have had reinforced countless times since, is that we—you, me, anyone who programs because they love it, who would do it for free if necessary—are a breed apart. We’re different, and luckily so; while everyone else is worrying about downsizing, we’re in one of the hottest industries in the world. And, so far as I can see, the biggest reason we’re in such a good situation isn’t intelligence, or hard work, or education, although those help; it’s that we actually like this stuff.

        It’s important to keep it that way. I’ve seen far too many people start to treat programming like a job, forgetting the joy of doing it, and burn out. So keep an eye on how you feel about the programming you’re doing, and if it’s getting stale, it’s time to learn something new; there’s plenty of interesting programming of all sorts to be done. Follow your interests—and don’t forget to have fun!

        -

        The Lighting Conundrum

        +

        The Lighting Conundrum

        I spent about two years working with John Carmack on Quake’s 3-D graphics engine. John faced several fundamental design issues while architecting Quake. I’ve written in earlier chapters about some of those issues, including eliminating non-visible polygons quickly via a precalculated potentially visible set (PVS), and improving performance by inserting potentially visible polygons into a global edge list and scanning out only the nearest polygon at each pixel.

        In this chapter, I’m going to talk about another, equally crucial design issue: how we developed our lighting approach for the part of the Quake engine that draws the world itself, the static walls and floors and ceilings. Monsters and players are drawn using completely different rendering code, with speed the overriding factor. A primary goal for the world, on the other hand, was to be as precise as possible, getting everything right so that polygons, textures, and sophisticated lighting would be pegged in place, with no visible shifting or distortion under all viewing conditions, for maximum player immersion—all with good performance, of course. As I’ll discuss, the twin goals of performance and rock-solid, complex lighting proved to be difficult to achieve with traditional lighting approaches; ultimately, a dramatically different approach was required.

        -

        Gouraud Shading

        +

        Gouraud Shading

        The traditional way to do realistic lighting in polygon pipelines is Gouraud shading (also known as smooth shading). Gouraud shading involves generating a lighting value at each polygon vertex by applying all relevant world lighting, linearly interpolating between lighting values down the edges of the polygon, and then linearly interpolating between the edges of the polygon across each span. If texture mapping is desired (and all polygons are texture mapped in Quake), then at each pixel in each span, the pixel’s corresponding texture map location (texel) is determined, and the interpolated lighting is applied to the texel to generate a final, lit pixel. Texels are generally taken from a 32x32 or 64x64 texture that’s tiled repeatedly across the polygon, for several reasons: performance (a 64x64 texture sits nicely in the 486 or Pentium cache), database size, and less artwork.

        The interpolated lighting can consist of either a color intensity value or three separate red, green, and blue values. RGB lighting produces more sophisticated results, such as colored lights, but is slower and best suited to RGB modes. Games like Quake that are targeted at palettized 256-color modes generally use intensity lighting; each pixel is lit by looking up the pixel color in a table, using the texel color and the lighting intensity as the look-up indices.

        Gouraud shading allows for decent lighting effects with a relatively small amount of calculation and a compact data set that’s a simple extension of the basic polygon model. However, there are several important drawbacks to Gouraud shading, as well.

        -

        Problems with Gouraud Shading

        +

        Problems with Gouraud Shading

        The quality of Gouraud shading depends heavily on the average size of the polygons being drawn. Linear interpolation is used, so highlights can only occur at vertices, and color gradients are monotonic across the face of each polygon. This can make for bland lighting effects if polygons are large, and makes it difficult to do spotlights and other detailed or dramatic lighting effects. After John brought the initial, primitive Quake engine up using Gouraud shading for lighting, the first thing he tried to improve lighting quality was adding a single vertex and creating new polygons wherever a spotlight was directly overhead a polygon, with the new vertex added directly underneath the light, as shown in Figure 68.1. This produced fairly attractive highlights, but simultaneously made evident several problems.


        @@ -67,7 +66,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/68-02.html b/68-02.html index b63c65c..8e34e44 100644 --- a/68-02.html +++ b/68-02.html @@ -24,7 +24,7 @@ - +
        @@ -40,9 +40,9 @@

        Similar problems occur with overlapping lights, and with shadows, where additional polygons are required in order to approximate lighting detail well. In particular, good shadow edges need small polygons, because otherwise the gradient between light and dark gets spread across too wide an area. Worse still, the rate of lighting change across a shadow edge can vary considerably as a function of the geometry the edge crosses; wider polygons stretch and diffuse the transition between light and shadow. A related problem is that lighting discontinuities can be very visible at t-junctions (although ultimately we had to add edges to eliminate t-junctions anyway, because otherwise dropouts can occur along polygon edges). These problems can be eased by adding extra edges, but that increases the rasterization load.


        Figure 68.1
          Adding an extra vertex directly beneath a light. +
        -->Figure 68.1  Adding an extra vertex directly beneath a light.

        -

        Perspective Correctness

        +

        Perspective Correctness

        Another problem is that Gouraud shading isn’t perspective-correct. With Gouraud shading, lighting varies linearly across the face of a polygon, in equal increments per pixel—but unless the polygon is parallel to the screen, the same sort of perspective correction is needed to step lighting across the polygon properly as is required for texture mapping. Lack of perspective correction is not as visibly wrong for lighting as it is for texture mapping, because smooth lighting gradients can tolerate considerably more warping than can the detailed bitmapped images used in texture mapping, but it nonetheless shows up in several ways.

        First, the extent of the mismatch between Gouraud shading and perspective lighting varies with the angle and orientation of the polygon being lit. As a polygon turns to become more on-edge, for example, the lighting warps more and therefore shifts relative to the perspective-texture mapped texels it’s shading, an effect I’ll call viewing variance. Lighting can similarly shift as a result of clipping, for example if one or more polygon edges are completely clipped; I’ll refer to this as clipping variance.

        @@ -50,16 +50,16 @@

        It was rotational variance that finally brought the lighting issue to a head for Quake. We’d look at the floors, which were Gouraud-shaded quads; then we’d pivot, and the lighting would shimmy and shift, especially where there were spotlights and shadows. Given the goal of rendering the world as accurately and convincingly as possible, this was unacceptable.

        The obvious solution to rotational variance is to use only triangles, but that brings with it a new set of problems. It takes twice as many triangles as quads to describe the same scene, increasing the size of the world database and requiring extra rasterization, at a performance cost. Triangles still don’t provide perspective lighting; their lighting is rotationally invariant, but it’s still wrong—just wrong in a more consistant way. Gouraud-shaded triangles still result in odd lighting patterns, and require lots of triangles to support shadowing and other lighting detail. Finally, triangles don’t solve clipping or viewing variance.


        Figure 68.2
          How Gouraud shading varies with polygon screen orientation. +
        -->Figure 68.2  How Gouraud shading varies with polygon screen orientation.

        Yet another problem is that while it may work well to add extra geometry so that spotlights and shadows show up well, that’s feasible only for static lighting. Dynamic lighting—light cast by sources that move—has to work with whatever geometry the world has to offer, because its needs are constantly changing.

        These issues led us to conclude that if we were going to use Gouraud shading, we would have to build Quake levels from many small triangles, with sufficiently finely detailed geometry so that complex lighting could be supported and the inaccuracies of Gouraud shading wouldn’t be too noticeable. Unfortunately, that line of thinking brought us back to the problem of a much larger world database and a much heavier rasterization load (all the worse because Gouraud shading requires an additional interpolant, slowing the inner rasterization loop), so that not only would the world still be less than totally solid, because of the limitations of Gouraud shading, but the engine would also be too slow to support the complex worlds we had hoped for in Quake.

        -

        The Quest for Alternative Lighting

        +

        The Quest for Alternative Lighting

        None of which is to say that Gouraud shading isn’t useful in general. Descent uses it to excellent effect, and in fact Quake uses Gouraud shading for moving entities, because these consist of small triangles and are always in motion, which helps hide the relatively small lighting errors. However, Gouraud shading didn’t seem capable of meeting our design goals for rendering quality and speed for drawing the world as a whole, so it was time to look for alternatives.

        There are many alternative lighting approaches, most of them higher-quality than Gouraud, starting with Phong shading, in which the surface normal is interpolated across the polygon’s surface, and going all the way up to ray-tracing lighting techniques in which full illumination calculations are performed for all direct and reflected paths from each light source for each pixel. What all these approaches have in common is that they’re slower than Gouraud shading, too slow for our purposes in Quake. For weeks, we kicked around and rejected various possibilities and continued working with Gouraud shading for lack of a better alternative—until the day John came into work and said, “You know, I have an idea....”

        -

        Decoupling Lighting from Rasterization

        +

        Decoupling Lighting from Rasterization

        John’s idea came to him while was looking at a wall that had been carved into several pieces because of a spotlight, with an ugly lighting glitch due to a t-junction. He thought to himself that if only there were some way to treat it as one surface, it would look better and draw faster—and then he realized that there was a way to do that.

        The insight was to split lighting and rasterization into two separate steps. In a normal Gouraud-based rasterizer, there’s first an off-line preprocessing step when the world database is built, during which polygons are added to support additional lighting detail as needed, and lighting values are calculated at the vertices of all polygons. At runtime, the lighting values are modified if dynamic lighting is required, and then the polygons are drawn with Gouraud shading.


        @@ -75,7 +75,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/68-03.html b/68-03.html index 9242b37..7ffdcc7 100644 --- a/68-03.html +++ b/68-03.html @@ -24,7 +24,7 @@ - +
        @@ -39,16 +39,16 @@

        Quake’s approach, which I’ll call surface-based lighting, preprocesses differently, and adds an extra rendering step. During off-line preprocessing, a grid, called a light map, is calculated for each polygon in the world, with a lighting value every 16 texels horizontally and vertically. This lighting is done by casting light from all the nearby lights in the world to each of the grid points on the polygon, and summing the results for each grid point. The Quake preprocessor filters the values, so shadow edges don’t have a stair-step appearance (a technique suggested by Billy Zelsnack); additional preprocessing could be done, for example Phong shading to make surfaces appear smoothly curved. Then, at runtime, the polygon’s texture is tiled into a buffer, with each texel lit according to the weighted average intensities of the four nearest light map points, as shown in Figure 68.3. If dynamic lighting is needed, the light map is modified accordingly before the buffer, which I’ll call a surface, is built. Then the polygon is drawn with perspective texture mapping, with the surface serving as the input texture, and with no lighting performed during the texture mapping.

        So what does surface-based lighting buy us? First and foremost, it provides consistent, perspective-correct lighting, eliminating all rotational, viewing, and clipping variance, because lighting is done in surface space rather than in screen space. By lighting in surface space, we bind the lighting to the texels in an invariant way, and then the lighting gets a free ride through the perspective texture mapper and ends up perfectly matched to the texels. Surface-based lighting also supports good, although not perfect, detail for overlapping lights and shadows. The 16-texel grid has a resolution of two feet in the Quake frame of reference, and this relatively fine resolution, together with the filtering performed when the light map is built, is sufficient to support complex shadows with smoothly fading edges. Additionally, surface-based lighting eliminates lighting glitches at t-junctions, because lighting is unrelated to vertices. In short, surface-based lighting meets all of Quake’s visual quality goals, which leaves only one question: How does it perform?

        -

        Size and Speed

        +

        Size and Speed

        As it turns out, the raw speed of surface-based lighting is pretty good. Although an extra step is required to build the surface, moving lighting and tiling into a separate loop from texture mapping allows each of the two loops to be optimized very effectively, with almost all variables kept in registers. The surface-building inner loop is particularly efficient, because it consists of nothing more than interpolating intensity, combining it with a texel and using the result to look up a lit texel color, and storing the results with a dword write every four texels. In assembly language, we got this code down to 2.25 cycles per lit texel in Quake. Similarly, the texture-mapping inner loop, which overlaps an FDIV for floating-point perspective correction with integer pixel drawing in 16-pixel bursts, has been squeezed down to 7.5 cycles per pixel on a Pentium, so the combined inner loop times for building and drawing a surface is roughly in the neighborhood of 10 cycles per pixel. It’s certainly possible to write a Gouraud-shaded perspective-correct texture mapper that’s somewhat faster than 10 cycles, but 10 cycles/pixel is fast enough to do 40 frames/second at 640x400 on a Pentium/100, so the cycle counts of surface-based lighting are acceptable. It’s worth noting that it’s possible to write a one-pass texture mapper that does approximately perspective-correct lighting. However, I have yet to hear of or devise such an inner loop that isn’t complicated and full of special cases, which makes it hard to optimize; worse, this approach doesn’t work well with the procedural and post-processing techniques I’ll discuss shortly.


        Figure 68.3
          Tiling the texture and lighting the texels from the light map. +
        -->Figure 68.3  Tiling the texture and lighting the texels from the light map.

        Moreover, surface-based lighting tends to spend more of its time in inner loops, because polygons can have any number of sides and don’t need to be split into multiple smaller polygons for lighting purposes; this reduces the amount of transformation and projection that are required, and makes polygon spans longer. So the performance of surface-based lighting stacks up very well indeed—except for caching.

        I mentioned earlier that a 64x64 texture tile fits nicely in the processor cache. A typical surface doesn’t. Every texel in every surface is unique, so even at 320x200 resolution, something on the rough order of 64,000 texels must be read in order to draw a single scene. (The number actually varies quite a bit, as discussed below, but 64,000 is in the ballpark.) This means that on a Pentium, we’re guaranteed to miss the cache once every 32 texels, and the number can be considerably worse than that if the texture access patterns are such that we don’t use every texel in a given cache line before that data gets thrown out of the cache. Then, too, when a surface is built, the surface buffer won’t be in the cache, so the writes will be uncached writes that have to go to main memory, then get read back from main memory at texture mapping time, potentially slowing things further still. All this together makes the combination of surface building and unlit texture mapping a potential performance problem, but that never posed a problem during the development of Quake, thanks to surface caching.

        -

        Surface Caching

        +

        Surface Caching

        When he thought of surface-based lighting, John immediately realized that surface building would be relatively expensive. (In fact, he assumed it would be considerably more expensive than it actually turned out to be with full assembly-language optimization.) Consequently, his design included the concept of caching surfaces, so that if the same surface were visible in the next frame, it could be reused without having to be rebuilt.

        With surface rebuilding needed only rarely, thanks to surface caching, Quake’s rasterization speed is generally the speed of the unlit, perspective-correct texture-mapping inner loop, which suffers from more cache misses than Gouraud-shaded, tiled texture mapping, but doesn’t have the overhead of Gouraud shading, and allows the use of larger polygons. In the worst case, where everything in a frame is a new surface, the speed of the surface-caching approach is somewhat slower than Gouraud shading, but generally surface caching provides equal or better performance, so once surface caching was implemented in Quake, performance was no longer a problem—but size became a concern.


        @@ -64,7 +64,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/68-04.html b/68-04.html index 976a479..8dc903c 100644 --- a/68-04.html +++ b/68-04.html @@ -24,7 +24,7 @@ - +
        @@ -38,17 +38,17 @@


        The amount of memory required for surface caching looked forbidding at first. Surfaces are large relative to texture tiles, because every texel of every surface is unique. Also, a surface can contain many texels relative to the number of pixels actually drawn on the screen, because due to perspective foreshortening, distant polygons have only a few pixels relative to the surface size in texels. Surfaces associated with partly hidden polygons must be fully built, even though only part of the polygon is visible, and if polygons are drawn back to front with overdraw, some polygons won’t even be visible, but will still require surface building and caching. What all this meant was that the surface cache initially looked to be very large, on the order of several megabytes, even at 320x200—too much for a game intended to run on an 8 MB machine.

        -

        Mipmapping To The Rescue

        +

        Mipmapping To The Rescue

        Two factors combined to solve this problem. First, polygons are drawn through an edge list with no overdraw, as I discussed a few chapters back, so no surface is ever built unless at least part of it is visible. Second, surfaces are built at four mipmap levels, depending on distance, with each mipmap level having one-quarter as many texels as the preceding level, as shown in Figure 68.4.

        For those whose heads haven’t been basted in 3-D technology for the past several years, mipmapping is 3-D graphics jargon for a process that normalizes the number of texels in a surface to be approximately equal to the number of pixels, reducing calculation time for distant surfaces containing only a few pixels. The mipmap level for a given surface is selected to result in a texel:pixel ratio approximately between 1:1 and 1:2, so texels map roughly to pixels, and more distant surfaces are correspondingly smaller. As a result, the number of surface texels required to draw a scene at 320x200 is on the rough order of 64,000; the number is actually somewhat higher, because of portions of surfaces that are obscured and viewspace-tilted polygons, which have high texel-to-pixel ratios along one axis, but not a whole lot higher. Thanks to mipmapping and the edge list, 600K has proven to be plenty for the surface cache at 320x200, even in the most complex scenes, and at 640x480, a little more than 1 MB suffices.


        Figure 68.4
          How mipmapping reduces surface caching requirements. +
        -->Figure 68.4  How mipmapping reduces surface caching requirements.

        All mipmapped texture tiles are generated as a preprocessing step, and loaded from disk at runtime. One interesting point is that a key to making mipmapping look good turned out to be box-filtering down from one level to the next by averaging four adjacent pixels, then using error diffusion dithering to generate the mipmapped texels.

        Also, mipmapping is done on a per-surface basis; the mipmap level for a whole surface is selected based on the distance from the viewer of the nearest vertex. This led us to limit surface size to a maximum of 256x256. Otherwise, surfaces such as floors would extend for thousands of texels, all at the mipmap level of the nearest vertex, and would require huge amounts of surface cache space while displaying a great deal of aliasing in distant regions due to a high texel:pixel ratio.

        -

        Two Final Notes on Surface Caching

        +

        Two Final Notes on Surface Caching

        Dynamic lighting has a significant impact on the performance of surface caching, because whenever the lighting on a surface changes, the surface has to be rebuilt. In the worst case, where the lighting changes on every visible surface, the surface cache provides no benefit, and rendering runs at the combined speed of surface building and texture mapping. This worst-case slowdown is tolerable but certainly noticeable, so it’s best to design games that use surface caching so only some of the surfaces change lighting at any one time. If necessary, you could alternate surface relighting so that half of the surfaces change on even frames, and half on odd frames, but large-scale, constant relighting is not surface caching’s strongest suit.

        Finally, Quake barely begins to tap surface caching’s potential. All sorts of procedural texturing and post-processing effects are possible. If a wall is shot, a sprite of pockmarks could be attached to the wall’s data structure, and the sprite could be drawn into the surface each time the surface is rebuilt. The same could be done for splatters, or graffiti, with translucency easily supported. These effects would then be cached and drawn as part of the surface, so the performance cost would be much less than effects done by on-screen overdraw every frame. Basically, the surface is a handy repository for all sorts of effects, because multiple techniques can be composited, because it caches the results for reuse without rebuilding, and because the texels constructed in a surface are automatically drawn in perspective.


        @@ -64,7 +64,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/69-01.html b/69-01.html index 7207df8..6635d23 100644 --- a/69-01.html +++ b/69-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,9 +36,8 @@


        -

        Chapter 69
        Surface Caching and Quake’s Triangle Models -

        -

        Probing Hardware-Assisted Surfaces and Fast Model Animation Without Sprites

        +

        Chapter 69
        Surface Caching and Quake’s Triangle Models

        +

        Probing Hardware-Assisted Surfaces and Fast Model Animation Without Sprites

        In the late ’70s, I spent a summer doing contract programming at a government-funded installation called the Northeast Solar Energy Center (NESEC). Those were heady times for solar energy, what with the oil shortages, and there was lots of money being thrown at places like NESEC, which was growing fast.

        NESEC was across the street from MIT, which made for good access to resources. Unfortunately, it also meant that NESEC was in a severely parking-impaired part of the world, what with the student population and Boston’s chronic parking shortage. The NESEC building did have its own parking lot, but it wasn’t nearly big enough, because students parked in it at every opportunity. The lot was posted, and cars periodically got towed, but King Canute stood a better chance against the tide than NESEC did against the student hordes, and late arrivals to work often had to park blocks away and hike to work, to their considerable displeasure.

        @@ -47,7 +46,7 @@

        The interesting point is that there was really no useful outcome that could have resulted from his outburst. Suppose I had been a student—what would he have accomplished by yelling at me? He let his emotions overrule his common sense, and as a result, did something he later wished he hadn’t. I’ve seen many programmers do the same thing, especially when they’re working long hours and not feeling adequately appreciated. For example, some time back I got mail from a programmer who complained bitterly that although he was critical to his company’s success, management didn’t appreciate his hard work and talent, and asked if I could help him find a better job. I suggested several ways that he might look for another job, but also asked if he had tried working his problems out with his employers; if he really was that valuable, what did he have to lose? He admitted he hadn’t, and recently he wrote back and said that he had talked to his boss, and now he was getting paid a lot more money, was getting credit for his work, and was just flat-out happy.

        We programmers think of ourselves as rational creatures, but most of us get angry at times, and when we do, like everyone else, we tend to be driven by our emotions instead of our minds. It’s my experience that thinking rationally under those circumstances can be difficult, but produces better long-term results every time—so if you find yourself in that situation, stay cool and think your way through it, and odds are you’ll be happier down the road.

        Of course, most of the time programmers really are rational creatures, and the more information we have, the better. In that spirit, let’s look at more of the stuff that makes Quake tick, starting with what I’ve recently learned about surface caching.

        -

        Surface Caching with Hardware Assistance

        +

        Surface Caching with Hardware Assistance

        In Chapter 68, I discussed in detail the surface caching technique that Quake uses to do detailed, high-quality lighting without lots of polygons. Since writing that chapter, I’ve gone further, and spent a considerable amount of time working on the port of Quake to Rendition’s Verite 3-D accelerator chip. So let me start off this chapter by discussing what I’ve learned about using surface caching in conjunction with hardware.

        As you’ll recall, the key to surface caching is that lighting information and polygon detail are stored separately, with lighting not tied to polygon vertices, then combined on demand into what I call surfaces: lit, textured rectangles that are used as the input to the texture mapper. Building surfaces takes time, so performance is enhanced by caching the surfaces from one frame to the next. As I pointed out in Chapter 68, 3-D hardware accelerators are designed to optimize Gouraud shading, but surface caching can also work on hardware accelerators, with some significant quality advantages.

        @@ -66,7 +65,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/69-02.html b/69-02.html index 48fbee5..cfa2501 100644 --- a/69-02.html +++ b/69-02.html @@ -24,7 +24,7 @@ - +
        @@ -36,18 +36,18 @@


        -

        Letting the Graphics Card Build the Textures

        +

        Letting the Graphics Card Build the Textures

        One obvious solution is to have the accelerator card build the textures, rather than having the CPU build and then download them. This eliminates downloading completely, and lets the accelerator, which should be faster at such things, do the texel manipulation. Whether this is actually faster depends on whether the CPU or the accelerator is doing more of the work overall, but it eliminates download time, which is a big help. This approach retains the ability to composite other effects, such as splatters and dents, onto surfaces, but by the same token retains the high memory requirements and dynamic lighting performance impact of the surface cache. It also requires that the 3-D API and accelerator being used allow drawing into a texture, which is not universally true. Neither do all APIs or accelerators allow applications enough control over the texture heap so that an efficient surface cache can be implemented, a point that favors non-caching approaches. (A similar option that wasn’t open to us due to time limitations is downloading 8-bpp surfaces and having the accelerator expand them to 16-bpp surfaces as it stores them in texture memory. Better yet, some accelerators support 8-bpp palettized hardware textures that are expanded to 16-bpp on the fly during texturing.)

        -

        The Light Map as Alpha Texture

        +

        The Light Map as Alpha Texture

        Another appealing non-caching approach is doing unlit texture-mapping in one pass, then lighting from the light map as a second pass, using the light map as an alpha texture. In other words, the textured polygon is drawn first, with no lighting, then the light map is textured on top of the polygon, with the light map intensity used as an alpha value to determine how brightly to light each texel. The hardware’s texture-mapping circuitry is used for both passes, so the lighting comes out perspective-correct and consistent under all viewing conditions, just as with the surface cache. The lighting polygons don’t even have to match the texture polygons, so they can represent dynamically changing lighting.

        Two-pass lighting not only looks good, but has no memory footprint other than texture and light map storage, and provides level performance, because it’s not dependent on surface cache hit rate. The primary downside to two-pass lighting is that it requires at least twice as much performance from the accelerator as single-pass drawing. The current crop of 3-D accelerators is not particularly fast, and few of them are up to the task of doing two passes at high resolution, although that will change soon. Another potential problem is that some accelerators don’t implement true alpha blending. Nonetheless, as accelerators get better, I expect two-pass drawing (or three-or-more-pass, for adding splatters and the like by overlaying sprite polygons) to be widely used. I also expect Gouraud shading to be widely used; it’s easy to use and fast. Also, speedier CPUs and accelerators will enable much more detailed geometry to be used, and the smaller that polygons become, the better Gouraud shading looks compared to surface caching and two-pass lighting.

        The next graphics engine you’ll see from id Software will be oriented heavily toward hardware accelerators, and at this point it’s a tossup whether the engine will use surface caching, Gouraud shading, or two-pass lighting.

        -

        Drawing Triangle Models

        +

        Drawing Triangle Models

        Most of the last group of chapters in this book discuss how Quake works. If you look closely, though, you’ll see that almost all of the information is about drawing the world—the static walls, floors, ceilings, and such. There are several reasons for this, in particular that it’s hard to get a world renderer working well, and that the world is the base on which everything else is drawn. However, moving entities, such as monsters, are essential to a useful game engine. Traditionally, these have been done with sprites, but when we set out to build Quake, we knew that it was time to move on to polygon-based models. (In the case of Quake, the models are composed of triangles.) We didn’t know exactly how we were going to make the drawing of these models fast enough, though, and went through quite a bit of experimentation and learning in the process of doing so. For the rest of this chapter I’ll discuss some interesting aspects of our triangle-model architecture, and present code for one useful approach for the rapid drawing of triangle models.

        -

        Drawing Triangle Models Fast

        +

        Drawing Triangle Models Fast

        We would have liked one rendering model, and hence one graphics pipeline, for all drawing in Quake; this would have simplified the code and tools, and would have made it much easier to focus our optimization efforts. However, when we tried adding polygon models to Quake’s global edge table, edge processing slowed down unacceptably. This isn’t that surprising, because the edge table was designed to handle 200 to 300 large polygons, not the 2,000 to 3,000 tiny triangles that a dozen triangle models in a scene can add. Restructuring the edge list to use trees rather than linked lists would have helped with the larger data sets, but the basic problem is that the edge table requires a considerable amount of overhead per edge per scan line, and triangle models have too few pixels per edge to justify that overhead. Also, the much larger edge table generated by adding triangle models doesn’t fit well in the CPU cache.

        Consequently, we implemented a separate drawing pipeline for triangle models, as shown in Figure 69.1. Unlike the world pipeline, the triangle-model pipeline is in most respects a traditional one, with a few exceptions, noted below. The entire world is drawn first, and then the triangle models are drawn, using z-buffering for proper visibility. For each triangle model, all vertices are transformed and projected first, and then each triangle is drawn separately.


        @@ -63,7 +63,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/69-03.html b/69-03.html index 1f48f96..85944bb 100644 --- a/69-03.html +++ b/69-03.html @@ -24,7 +24,7 @@ - +
        @@ -40,19 +40,19 @@

        Early on, we decided to allow lower drawing quality for triangle models than for the world, in the interests of speed. For example, the triangles in the models are small, and usually distant—and generally part of a quickly moving monster that’s trying its best to do you in—so the quality benefits of perspective texture mapping would add little value. Consequently, we chose to draw the triangles with affine texture mapping, avoiding the work required for perspective. Mind you, the models are perspective-correct at the vertices; it’s just the pixels between the vertices that suffer slight warping.


        Figure 69.1
          Quake’s triangle-model drawing pipeline. +
        -->Figure 69.1  Quake’s triangle-model drawing pipeline.

        -

        Trading Subpixel Precision for Speed

        +

        Trading Subpixel Precision for Speed

        Another sacrifice at the altar of performance was subpixel precision. Before each triangle is drawn, we snap its vertices to the nearest integer screen coordinates, rather than doing the extra calculations to handle fractional vertex coordinates. This causes some jumping of triangle edges, but again, is not a problem in normal gameplay, especially for the animation of figures in continuous motion.

        One interesting benefit of integer coordinates is that they let us do backface culling and rejection of degenerate triangles in one operation, because the cross-product z component used for backface culling returns zero for degenerate triangles. Conveniently, that cross-product component is also the denominator for the lighting and texture gradient calculations used in drawing each triangle, so as soon as we check the cross-product z value and determine that the triangle is drawable, we immediately start the FDIV to calculate the reciprocal. By the time we get around to calculating the gradients, the FDIV has completed execution, effectively taking only the one cycle required to issue it, because the integer execution pipes can process independently while FDIV executes.

        Finally, we decided to Gouraud-shade the triangle models, because this makes them look considerably more 3-D. However, we can’t afford to calculate where all the relevant light sources for each model are in each frame, or even which is the primary light source. Instead, we select each model’s lighting level based on how brightly the floor point it was standing on is lit, and use that lighting level for both ambient lighting (so all parts of the model have some illumination) and Gouraud shading—but the lighting vector for Gouraud shading is a fixed vector, so the model is always lit from the same direction. Somewhat surprisingly, in practice this looks considerably better than pure ambient lighting.

        -

        An Idea that Didn’t Work

        +

        An Idea that Didn’t Work

        As we implemented triangle models, we tried several ideas that didn’t work out. One that’s notable because it seems so appealing is caching a model’s image from one frame and reusing it in the next frame as a sprite. Our thinking was that clipping, transforming, projecting, and drawing a several-hundred-triangle model was going to be a lot more expensive than drawing a sprite, too expensive to allow very many models to be visible at once. We wanted to be able to display at least a dozen simultaneous models, so the idea was that for all but the closest models, we’d draw into a sprite, then reuse that sprite at the model’s new locations for the next two or three frames, amortizing the 3-D drawing cost over several frames and boosting overall model-drawing performance. The rendering wouldn’t be exactly right when the sprite was reused, because the view of the model would change from frame to frame as the viewer and model moved, but it didn’t seem likely that that slight inaccuracy would be noticeable for any but the nearest and largest models.

        As it turns out, though, we were wrong: The repeated frames were sometimes painfully visible, looking like jerky cardboard cutouts. In fact they looked a lot like the sprites used in DOOM—precisely the effect we were trying to avoid. This was especially true if we reused them more than once—and if we reused them only once, then we had to do one full 3-D rendering plus two sprite renderings every two frames, which wasn’t much faster than simply doing two 3-D renderings.

        The sprite architecture also introduced considerable code complexity, increased memory footprint because of the need to cache the sprites, and made it difficult to get hidden surfaces exactly right because sprites are unavoidably 2-D. The performance of drawing the sprites dropped sharply as models got closer, and that’s also where the sprites looked worse when they were reused, limiting sprites to use at a considerable distance. All these problems could have been worked out reasonably well if necessary, but the sprite architecture just had the feeling of being fundamentally not the right approach, so we tried thinking along different lines.

        -

        An Idea that Did Work

        +

        An Idea that Did Work

        John Carmack had the notion that it was just way too much effort per pixel to do all the work of scanning out the tiny triangles in distant models. After all, distant models are just indistinct blobs of pixels, suffering heavily from effects such as texture aliasing and pixel quantization, he reasoned, so it should work just as well if we could come up with another way of drawing blobs of approximately equal quality. The trick was to come up with such an alternative approach. We tossed around half-formed ideas like flood-filling the model’s image within its silhouette, or encoding the model as a set of deltas, picking a visible seed point, and working around the visible side of the model according to the deltas. The first approach that seemed practical enough to try was drawing the pixel at each vertex replicated to form a 2x2 box, with all the vertices together forming the approximate shape of the model. Sometimes this worked quite well, but there were gaps where the triangles were large, and the quality was very erratic. However, it did point the way to something that in the end did the trick.

        One morning I came in to the office to find that overnight (and well into the morning), John had designed and implemented a technique I’ll call subdivision rasterization. This technique scans out approximately the right pixels for each triangle, with almost no overhead, as follows. First, all vertices in the model are drawn. Ideally, only the vertices on the visible side of the model would be drawn, but determining which vertices those are would take time, and the occasional error from a visible back vertex is lost in the noise.


        @@ -68,7 +68,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/69-04.html b/69-04.html index 4885563..ae50c60 100644 --- a/69-04.html +++ b/69-04.html @@ -24,7 +24,7 @@ - +
        @@ -158,9 +158,9 @@ D_PolysetRecursiveTriangle (lp3, new, lp2);


        Figure 69.2
          One recursive subdivision triangle-drawing step. +
        -->Figure 69.2  One recursive subdivision triangle-drawing step.

        -

        More Ideas that Might Work

        +

        More Ideas that Might Work

        Useful as subdivision rasterization proved to be, we by no means think that we’ve maxed out triangle-model drawing, if only because we spent far less design and development time on subdivision than on the affine rasterizer, so it’s likely that there’s quite a bit more performance to be found for drawing small triangles. For example, it could be faster to precalculate drawing masks or even precompile drawing code for all possible small triangles (say, up to 4x4 or 5x5), and the memory footprint looks reasonable. (It’s worth noting that both precalculated drawing and subdivision rasterization are only possible because we snap to integer coordinates; none of this stuff works with fixed-point vertices.)

        More interesting still is the stack-based rendering described in the article “Time/Space Tradeoffs for Polygon Mesh Rendering,” by Bar-Yehuda and Gotsman, in the April, 1996 ACM Transactions on Graphics. Unfortunately, the article is highly abstract and slow going, but the bottom line is that it’s possible to represent a triangle mesh as a stream of commands that place vertices in a stack, remove them from the stack, and draw triangles using the vertices in the stack. This results in excellent CPU cache coherency, because rather than indirecting all over a vertex pool to retrieve vertex data, all vertices reside in a tiny stack that’s guaranteed to be in the cache. Local variables used while drawing can be stored in a small block next to the stack, and the stream of commands representing the model is accessed sequentially from start to finish, so cache utilization should be very high. As processors speed up at a much faster rate than main memory access, cache optimizations of this sort will become steadily more important in improving drawing performance.

        @@ -177,7 +177,7 @@ D_PolysetRecursiveTriangle (lp3, new, lp2);
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-01.html b/70-01.html index 82e54a1..02816c3 100644 --- a/70-01.html +++ b/70-01.html @@ -24,7 +24,7 @@ - +
        @@ -36,15 +36,14 @@


        -

        Chapter 70
        Quake: A Post-Mortem and a Glimpse into the Future -

        +

        Chapter 70
        Quake: A Post-Mortem and a Glimpse into the Future

        Why did not any of the children in the first group think of this faster method of going across the room? It is simple. They looked at what they were given to use for materials and, they are like all of us, they wanted to use everything. But they did not need everything. They could do better with less, in a different way.

        Frederik Pohl, The Gold at the Starbow’s End

        Eleven years ago, I started the first serious graphics article I ever wrote with the above quote. The point I was making at the time was that programming assumptions based on high-level languages or other processors had to be discarded in the quest for maximum x86 performance. While that’s certainly still true, time and the microcomputer world have moved on, and today there’s a more important lesson 3-D game programmers can draw from Frederik Pohl’s words. Nowadays, CPUs, 3-D hardware, 3-D algorithms, and 3-D data structures are evolving so rapidly that the enemy is now often the assumptions and techniques from the last product—and sometimes the assumptions and techniques in the current product. We all feel most comfortable with techniques we’ve already mastered, but leading-edge 3-D game technology is such a delicate balancing act between performance, features (particularly with game designers always wanting to add more), and workflow (as we’ll see, preprocessing that improves performance often hurts designer productivity) that it’s never safe to stop looking for a better approach until the game has actually shipped. Change is the rule, and we must always be looking to “do better with less, in a different way.”

        I’ve talked about Quake’s technology elsewhere in this book, However, those chapters focused on specific areas, not overall structure. Moreover, Quake changed in significant ways between the writing of those chapters and the final shipping. Then, after shipping, Quake was ported to 3-D hardware. And the post-Quake engine, code-named Trinity, is already in development at this writing (Spring 1997), with some promising results. So in wrapping up this book, I’ll recap Quake’s overall structure relatively quickly, then bring you up to date on the latest developments. And in the spirit of Frederik Pohl’s quote, I’ll point out that we implemented and discarded at least half a dozen 3-D engines in the course of developing Quake (and all of Quake’s code was written from scratch, rather than using Doom code), and almost switched to another one in the final month, as I’ll describe later. And even at this early stage, Trinity uses almost no Quake technology.

        In fact, I’ll take this opportunity to coin Carmack’s Law, as follows: Fight code entropy. If you have a new fundamental assumption, throw away your old code and rewrite it from scratch. Incremental patching and modifying seems easier at first, and is the normal course of things in software development, but ends up being much harder and producing bulkier, markedly inferior code in the long run, as we’ll see when we discuss the net code for QuakeWorld. It may seem safer to modify working code, but the nastiest bugs arise from unexpected side effects and incorrect assumptions, which almost always arise in patched-over code, not in code designed from the ground up. Do the hard work up front to make your code simple, elegant, great—and just plain right—and it’ll pay off many times over in the long run.

        Before I begin, I’d like to remind you that all of the Doom and Quake material I’m presenting in this book is presented in the spirit of sharing information to make our corner of the world a better place for everyone. I’d like to thank John Carmack, Quake’s architect and lead programmer, and id Software for allowing me to share this technology with you, and I encourage you to share your own insights by posting on the Internet and writing books and articles whenever you have the opportunity and the right to do so. (Of course, check with your employer first!) We’ve all benefited greatly from the shared wisdom of people like Knuth, Foley and van Dam, Jim Blinn, Jim Kajiya, and hundreds of others—are you ready to take a shot at making your own contribution to the future?

        -

        Preprocessing the World

        +

        Preprocessing the World

        For the most part, I’ll discuss Quake’s 3-D engine in this chapter, although I’ll touch on other areas of interest. For 3-D rendering purposes, Quake consists of two basic sorts of objects: the world, which is stored as a single BSP model and never changes shape or position; and potentially moving objects, called entities, which are drawn in several different ways. I’ll discuss each separately.

        The world is constructed from a set of brushes, which are n-sided convex polyhedra placed in a level by a designer using a map editor, with a selectable texture on each face. When a level is completed, a preprocessing program combines all brushes to form a skin around the solid areas of the world, so there is no interpenetration of polygons, just a continuous mesh delineating solid and empty areas. Once this is done, the next step is generating a BSP tree for the level.

        The BSP consists of splitting planes aligned with polygons, called nodes, and of leaves, which are the convex subspaces into which all the nodes carve space. The top node carves the world into two subspaces, and divides the remaining polygons into two sets, splitting any polygon that spans the node into two pieces. Each subspace is then similarly split by one node each, and so on until all polygons have been used to create nodes. A node’s subspace is the total space occupied by all its children: the subspace that the node splits into two parts, and that its children continue to subdivide. When the only polygon in a node’s subspace is the polygon that splits the subspace—the polygon whose plane defines the node—then the two child subspaces are called leaves, and are not divided any further.

        @@ -61,7 +60,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-02.html b/70-02.html index c7de4ec..7b2dcad 100644 --- a/70-02.html +++ b/70-02.html @@ -24,7 +24,7 @@ - +
        @@ -39,7 +39,7 @@

        Getting proper front-to-back drawing order is a little more complicated with polygons on nodes. As we walk the BSP tree front-to-back, in each leaf we mark the polygons that are at least partially in that leaf, and then after we’ve recursed and processed everything in front of a node, we then process all the marked polygons on that node, after which we recurse to process the polygons behind the node. So putting the polygons on the nodes saves memory and improves performance significantly, but loses the simple approach of simply recursing the tree and processing the polygons in each leaf as we come to it, in favor of recursing and marking in front of a node, processing marked polygons on the node, then recursing behind the node.

        After the BSP is built, the outer surfaces of the level, which no one can ever see (because levels are sealed spaces), are removed, so the interior of the level, containing all the empty space through which a player can move, is completely surrounded by a solid region. This eliminates a great many irrelevant polygons, and reduces the complexity of the next step, calculating the potentially visible set.

        -

        The Potentially Visible Set (PVS)

        +

        The Potentially Visible Set (PVS)

        After the BSP tree is built, the potentially visible set (PVS) for each leaf is calculated. The PVS for a leaf consists of all the leaves that can be seen from anywhere in that leaf, and is used to reduce to a near-minimum the polygons that have to be considered for drawing from a given viewpoint, as well as the entities that have to be updated over the network (for multiplayer games) and drawn. Calculating the PVS is expensive; Quake levels take 10 to 30 minutes to process on a four-processor Alpha, and even with speedup tweaks to the BSPer (the most effective of which was replacing many calls to malloc() with stack-based structures—beware of malloc() in performance-sensitive code), Quake 2 levels are taking up to an hour to process. (Note, however, that that includes BSPing, PVS calculations, and radiosity lighting, which I’ll discuss later.)

        Some good news, though, is that in the nearly two years since we got the Alpha, Pentium Pros have become as fast as that generation of Alphas, so it is now possible to calculate the PVS on an affordable machine. On the other hand, even 10 minutes of BSPing does hurt designer productivity. John has always been a big advocate of moving code out of the runtime program into utilities, and of preprocessing for performance and runtime simplicity, but even he thinks that in Quake, we may have pushed that to the point where it interfered too much with workflow. The real problem, of course, is that even a huge amount of money can’t buy orders of magnitude more performance than commodity computers; we are getting an eight-R10000 SGI compute server, but that’s only about twice as fast as an off-the-shelf four-processor Pentium Pro.

        The size of the PVS for each leaf is manageable because it is stored as a bit vector, with a 1-bit for the position in the overall leaf array of each leaf that’s visible from the current leaf. Most leaves are invisible from any one leaf, so the PVS for each leaf consists mostly of zeros, and compacts nicely with run-length encoding.

        @@ -58,7 +58,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-03.html b/70-03.html index 33a790a..1f5fcae 100644 --- a/70-03.html +++ b/70-03.html @@ -24,7 +24,7 @@ - +
        @@ -36,12 +36,12 @@


        -

        Passages: The Last-Minute Change that Didn’t Happen

        +

        Passages: The Last-Minute Change that Didn’t Happen

        Earlier, I mentioned that we almost changed 3-D engines again in the last month of Quake’s development. Here’s what happened: One of the alternatives to the PVS is the use of portals, where the focus is on the places where polygons don’t exist along leaf faces, rather than the more usual focus on the polygons themselves. These “empty” places are themselves polygons, called portals, that describe all the places that visibility can pass from one leaf to another. Portals are used by the PVS generator to determine visibility, and are used in other 3-D engines as the primary mechanism for determining leaf or sector visibility. For example, portals can be projected to screenspace, then used as a 2-D clipping region to restrict drawing of more distant polygons to only those that are visible through the portal. Or, as in Quake’s preprocessor, visibility boundary planes can be constructed from one portal to the next, and 3-D clipping to those planes can be used to determine visible polygons or leaves. Used either way, portals can support more changeable worlds than the PVS, because, unlike the PVS, the portals themselves can easily be changed on the fly.

        The problem with portal-based visibility is that it tends to perform at its worst in complex scenes, which can have many, many portals. Since those are the most expensive scenes to draw, as well, portals tend to worsen the worst case. However, late in Quake’s development, John realized that the approach of storing portals themselves in the world database could readily be improved upon. (To be clear, Quake wasn’t using portals at that point, and didn’t end up using them.) Since the aforementioned sets of 3-D visibility clipping planes between portals—which he named passages—were what actually got used for visibility, if he stored those, instead of generating them dynamically from the portals, he would be able to do visibility much faster than with standard portals. This would give a significantly tighter polygon set than the PVS, because it would be based on visibility through the passages from the viewpoint, rather than the PVS’s approach of visibility from anywhere in the leaf, and that would be a considerable help, because the level designers were running right up against performance limits, partly because of the PVS’s relatively loose polygon set. John immediately decided that passages-based visibility was a sufficiently superior approach that if it worked out, he would switch Quake to it, even at that late stage, and within a weekend, he had implemented it and had it working—only to find that, like portals, it improved best cases but worsened worst cases, and overall wasn’t a win for Quake. In truth, given how close we were to shipping, John was as much thankful as disappointed that passages didn’t work out, but the possibilities were too great for us not to have taken a shot at it.

        So why even bother mentioning this? Partly to show that not every interesting idea pans out; I tend to discuss those that did pan out, and it’s instructive to point out that many ideas don’t. That doesn’t mean you shouldn’t try promising ideas, though. First, some do pan out, and you’ll never know which unless you try. Second, an idea that doesn’t work out in one case can still be filed away for another case. It’s quite likely that passages will be useful in a different context in a future engine.

        The more approaches you try, the larger your toolkit and the broader your understanding will be when you tackle your next project.

        -

        Drawing the World

        +

        Drawing the World

        Everything described so far is a preprocessing step. When Quake is actually running, the world is drawn as follows: First, the PVS for the view leaf is decompressed, and each leaf flagged as visible is marked as being in the current frame’s PVS. (The marking is done by storing the current frame’s number in the leaf; this avoids having to clear the PVS marking each frame.) All the parent nodes of each leaf in the PVS are also marked; this information could have been stored as additional PVS flags, but to save space is bubbled up the BSP from each visible leaf.

        After the PVS is marked, the BSP is walked front-to-back. At each node, the bounding box of the node’s subspace is clipped against the view frustum; if the bounding box is fully clipped, then that node and all its children are ignored. Likewise, if the node is not in the PVS for the current viewpoint leaf, the node and all its children are ignored. If the bounding box is partially clipped or not clipped at all, that information is passed to the children so that any unnecessary clip tests can be avoided. The children in front of the node are then processed recursively. When a leaf is reached, polygons that touch that leaf are marked as potentially drawable. When recursion in front of a node is finished, all polygons on the front side of the node that are marked as potentially drawable are added to the edge list, and then the children on the back side of that node are similarly processed recursively.

        @@ -62,7 +62,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-04.html b/70-04.html index 53368b2..fb2af33 100644 --- a/70-04.html +++ b/70-04.html @@ -24,7 +24,7 @@ - +
        @@ -38,14 +38,14 @@


        The edge list is an atypical technology for John; it’s an extra stage in the engine, it’s complex, and it doesn’t scale well. A Quake level might have a maximum of 500 potentially drawable polygons that get placed into the edge list, and that runs fine, but if you were to try to put 5,000 polygons into the edge list, it would quickly bog down due to edge sorting, link following, and dataset size. Different data structures (like using a tree to store the edges rather than a linear linked list) would help to some degree, but basically the edge list has a relatively small window of applicability; it was appropriate technology for the degree of complexity possible in a Pentium-based game (and even then, only with the reduction in polygons made possible by the PVS), but will probably be poorly suited to more complex scenes. It served well in the Quake engine, but remains an inelegant solution, and, in the end, it feels like there’s something better we didn’t hit on. However, as John says, “I’m pragmatic above all else”—and the edge list did the job.

        -

        Rasterization

        +

        Rasterization

        Once the visible spans are scanned out of the edge list, they must still be drawn, with perspective-correct texture mapping and lighting. This involves hundreds of lines of heavily optimized assembly language, but is fundamentally pretty simple. In order to draw the spans for a given surface, the screenspace equations for 1/z, s/z, and t/z (where s and t are the texture coordinates and z is distance) are calculated for the surface. Then for each span, these values are calculated for the points at each end of the span, the reciprocal of 1/z is calculated with a divide, and s and t are then calculated as (s/z)*z and (t/z)*z. If the span is longer than 16 pixels, s and t are likewise calculated every 16 pixels along the span. Then each stretch of up to 16 pixels is drawn by linearly interpolating between these correctly calculated points. This introduces some slight error, but this is almost never visible, and even then is only a small ripple, well worth the performance improvement gained by doing the perspective-correct math only once every 16 pixels. To speed things up a little more, the FDIV to calculate the reciprocal of 1/z is overlapped with drawing 16 pixels, taking advantage of the Pentium’s ability to perform floating-point in parallel with integer instructions, so the FDIV effectively takes only one cycle.

        -

        Lighting

        +

        Lighting

        Lighting is less simple to explain. The traditional way of doing polygon lighting is to calculate the correct light at the vertices and linearly interpolate between those points (Gouraud shading), but this has several disadvantages; in particular, it makes it hard to get detailed lighting without creating a lot of extra polygons, the lighting isn’t perspective correct, and the lighting varies with viewing angle for polygons other than triangles. To address these problems, Quake uses surface-based lighting instead. In this approach, when it’s time to draw a surface (a world polygon), that polygon’s texture is tiled into a memory buffer. At the same time, the texture is lit according to the surface’s light map, as calculated during preprocessing. Lighting values are linearly interpolated between the light map’s 16-texel grid points, so the lighting effects are smooth, but slightly blurry. Then, the polygon is drawn to the screen using the perspective-correct texture mapping described above, with the prelit surface buffer being the source texture, rather than the original texture tile. No additional lighting is performed during texture mapping; all lighting is done when the surface buffer is created.

        Certainly it takes longer to build a surface buffer and then texture map from it than it does to do lighting and texture mapping in a single pass. However, surface buffers are cached for reuse, so only the texture mapping stage is usually needed. Quake surfaces tend to be big, so texture mapping is slowed by cache misses; however, the Quake approach doesn’t need to interpolate lighting on a pixel-by-pixel basis, which helps speed things up, and it doesn’t require additional polygons to provide sophisticated lighting. On balance, the performance of surface-based drawing is roughly comparable to tiled, Gouraud-shaded texture mapping—and it looks much better, being perspective correct, rotationally invariant, and highly detailed. Surface-based drawing also has the potential to support some interesting effects, because anything that can be drawn into the surface buffer can be cached as well, and is automatically drawn in correct perspective. For instance, paint splattered on a wall could be handled by drawing the splatter image as a sprite into the appropriate surface buffer, so that drawing the surface would draw the splatter as well.

        -

        Dynamic Lighting

        +

        Dynamic Lighting

        Here we come to a feature added to Quake after last year’s Computer Game Developer’s Conference (CGDC). At that time, Quake did not support dynamic lighting; that is, explosions and such didn’t produce temporary lighting effects. We hadn’t thought dynamic lighting would add enough to the game to be worth the trouble; however, at CGDC Billy Zelsnack showed us a demo of his latest 3-D engine, which was far from finished at the time, but did have impressive dynamic lighting effects. This caused us to move dynamic lighting up the priority list, and when I got back to id, I spent several days making the surface-building code as fast as possible (winding up at 2.25 cycles per texel in the inner loop) in anticipation of adding dynamic lighting, which would of course cause dynamically lit surfaces to constantly be rebuilt as the lighting changed. (A significant drawback of dynamic lighting is that it makes surface caching worthless for dynamically lit surfaces, but if most of the surfaces in a scene are not dynamically lit at any one time, it works out fine.) There things stayed for several weeks, while more critical work was done, and it was uncertain whether dynamic lighting would, in fact, make it into Quake.

        Then, one Saturday, John suggested that I take a shot at adding the high-level dynamic lighting code, the code that would take the dynamic light sources and project their sphere of illumination into the world, and which would then add the dynamic contributions into the appropriate light maps and rebuild the affected surfaces. I said I would as soon as I finished up the stuff I was working on, but it might be a day or two. A little while later, he said, “I bet I can get dynamic lighting working in less than an hour,” and dove into the code. One hour and nine minutes later, we had dynamic lighting, and it’s now hard to imagine Quake without it. (It sure is easier to imagine the impact of features and implement them once you’ve seen them done by someone else!)

        @@ -63,7 +63,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-05.html b/70-05.html index 387c18b..4ee7ef5 100644 --- a/70-05.html +++ b/70-05.html @@ -24,7 +24,7 @@ - +
        @@ -36,15 +36,15 @@


        -

        Entities

        +

        Entities

        So far, all we’ve drawn is the static, unchanging (apart from dynamic lighting) world. That’s an important foundation, but it’s certainly not a game; now we need to add moving objects. These objects fall into four very different categories: BSP models, polygon models, sprites, and particles.

        -

        BSP Models

        +

        BSP Models

        BSP models are just like the world, except that they can move. Examples include doors, moving bridges, and health and ammo boxes. The way these are rendered is by clipping their polygons into the world BSP tree, so each polygon fragment is in only one leaf. Then these fragments are added to the edge list, just like world polygons, and scanned out, along with the rest of the world, when the edge list is processed. The only trick here is front-to-back ordering. Each BSP model polygon fragment is given the BSP sorting order of the leaf in which it resides, allowing it to sort properly versus the world polygons. If two or more polygons from different BSP models are in the same leaf, however, BSP ordering is no longer useful, so we then sort those polygons by 1/z, calculated from the polygons’ plane equations.

        Interesting note: We originally tried to sort all world polygons on 1/z as well, the reason being that we could then avoid splitting polygons except when they actually intersected, rather than having to split them along the lines of parent nodes. This would result in fewer edges, and faster edge list processing and rasterization. Unfortunately, we found that precision errors and special cases such as seamlessly abutting objects made it difficult to get global 1/z sorting to work completely reliably, and the code that we had to add to work around these problems slowed things up to the point where we were getting no extra performance for all the extra code complexity. This is not to say that 1/z sorting can’t work (especially in something like a flight sim, where objects never abut), but BSP sorting order can be a wonderful thing, partly because it always works perfectly, and partly because it’s simpler and faster to sort on integer node and leaf orders than on floating-point 1/z values.

        BSP models take some extra time because of the cost of clipping them into the world BSP tree, but render just as fast as the rest of the world, again with no overdraw, so closed doors, for example, block drawing of whatever’s on the other side (although it’s still necessary to transform, project, and add to the edge list the polygons the door occludes, because they’re still in the PVS—they’re potentially visible if the door opens). This makes BSP models most suitable for fairly simple structures, such as boxes, which have relatively few polygons to clip, and cause relatively few edges to be added to the edge list.

        -

        Polygon Models and Z-Buffering

        +

        Polygon Models and Z-Buffering

        Polygon models, such as monsters, weapons, and projectiles, consist of a triangle mesh with front and back skins stretched over the model. For speed, the triangles are drawn with affine texture mapping; the triangles are small enough, and the models are generally distant enough, that affine distortion isn’t visible. (However, it is visible on the player’s weapon; this caused a lot of extra work for the artists, and we will probably implement a perspective-correct polygon-model rasterizer in Quake 2 for this specific purpose.) The triangles are also Gouraud shaded; interestingly, the light vector used to shade the models is always from the same direction, and has no relation to any actual lights in the world (although it does vary in intensity, along with the model’s ambient lighting, to match the brightness of the spot the player is standing above in the world). Even this highly inaccurate lighting works well, though; the Gouraud shading makes models look much more three-dimensional, and varying the lighting in even so crude a way allows hiding in shadows and illumination by explosions and muzzle flashes.

        One issue with polygon models was how to handle occlusion issues; that is, what parts of models were visible, and what surfaces they were in front of. We couldn’t add models to the edge list, because the hundreds of polygons per model would overwhelm the edge list. Our initial occlusion solution was to sort polygon-model polygons into the world BSP, drawing the portions in each leaf at the right points as we drew the world in BSP order. That worked reasonably well with respect to the world (not perfectly, though, because it would have been too expensive to clip all the polygon-model polygons into the world, so there was some occlusion error), but didn’t handle the case of sorting polygon models in the same leaf against each other, and also didn’t help the polygons in a given polygon model sort properly against each other.

        @@ -63,7 +63,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-06.html b/70-06.html index 62f51b4..47fd1c8 100644 --- a/70-06.html +++ b/70-06.html @@ -24,7 +24,7 @@ - +
        @@ -36,19 +36,19 @@


        -

        The Subdivision Rasterizer

        +

        The Subdivision Rasterizer

        This rasterizer, which we call the subdivision rasterizer, first draws all the vertices in the model. Then it takes each front-facing triangle, and determines if it has a side that’s at least two pixels long. If it does, we split that side into two pieces at the pixel nearest to the middle (using adds and shifts to average the endpoints of that side), draw the vertex at the split point, and process each of the two split triangles recursively, until we get down to triangles that have only one-pixel sides and hence have nothing left to draw. This approach is hideously slow and quite ugly (due to inaccuracies from integer quantization) for 100-pixel triangles—but it’s very fast for, say, five-pixel triangles, and is indistinguishable from more accurate rasterization when a model is 25 or 50 feet away. Better yet, the subdivider is ridiculously simple—a few dozen lines of code, far simpler than the affine rasterizer—and was implemented in an evening, immediately making the drawing of distant models about three times as fast, a very good return for a bit of conceptual work. The affine rasterizer got fairly close to the same performance with further optimization—in the range of 10% to 50% slower—but that took weeks of difficult programming.

        We switch between the two rasterizers based on the model’s distance and average triangle size, and in almost any scene, most models are far enough away so subdivision rasterization is used. There are undoubtedly faster ways yet to rasterize distant models adequately well, but the subdivider was clearly a win, and is a good example of how thinking in a radically different direction can pay off handsomely.

        -

        Sprites

        +

        Sprites

        We had hoped to be able to eliminate sprites completely, making Quake 100% 3-D, but sprites—although sometimes very visibly 2-D—were used for a few purposes, most noticeably the cores of explosions. As of CGDC last year, explosions consisted of an exploding spray of particles (discussed below), but there just wasn’t enough visual punch with that representation; adding a series of sprites animating an explosion did the trick. (In hindsight, we probably should have made the explosions polygon models rather than sprites; it would have looked about as good, and the few sprites we used didn’t justify the considerable amount of code and programming time required to support them.) Drawing a sprite is similar to drawing a normal polygon, complete with perspective correction, although of course the inner loop must detect and skip over transparent pixels, and must also perform z-buffering.

        -

        Particles

        +

        Particles

        The last drawing entity type is particles. Each particle is a solid-colored rectangle, scaled by distance from the viewer and drawn with z-buffering. There can be up to 2,000 particles in a scene, and they are used for rocket trails, explosions, and the like. In one sense, particles are very primitive technology, but they allow effects that would be extremely difficult to do well with the other types of entities, and they work well in tandem with other entities, as, for example, providing a trail of fire behind a polygon-model lava ball that flies into the air, or generating an expanding cloud around a sprite explosion core.

        -

        How We Spent Our Summer Vacation: After Shipping Quake

        +

        How We Spent Our Summer Vacation: After Shipping Quake

        Since shipping Quake in the summer of 1996, we’ve extended it in several ways: We’ve worked with Rendition to port it to the Verite accelerator chip, we’ve ported it to OpenGL, we’ve ported it to Win32, we’ve done QuakeWorld, and we’ve added features for Quake 2. I’ll discuss each of these briefly.

        -

        Verite Quake

        +

        Verite Quake

        Verite Quake (VQuake) was the first hardware-accelerated version of Quake. It looks extremely good, due to bilinear texture filtering, which eliminates most pixel aliasing, and because it provides good performance at higher resolutions such as 512x384 and 640x480. Implementing VQuake proved to be an interesting task, for two reasons: The Verite chip’s fill rate was marginal for Quake’s needs, and Verite contains a programmable RISC chip, enabling more sophisticated processing than most 3-D accelerators. The need to squeeze as much performance as possible out of Verite ruled out the use of a standard API such as Direct 3D or OpenGL; instead, VQuake uses Rendition’s proprietary API, Speedy3D, with the addition of some special calls and custom Verite code.

        Interestingly, VQuake is very similar to software Quake; in order to allow Verite to handle the high pixel processing loads of high-res, VQuake uses an edge list and builds span lists on the CPU, just as in software Quake, then Verite DMAs the span descriptors to onboard memory and draws them. (This was only possible because Verite is fully programmable; most accelerators wouldn’t be able to support this architecture.) Similarly, the CPU builds lit, tiled surfaces in system RAM, then Verite DMAs them to an onboard surface cache, from which they are texture-mapped. In short, VQuake is very much like normal Quake, except that the drawing of the spans is done by a specialized processor.

        @@ -66,7 +66,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-07.html b/70-07.html index c2ead2d..2f3eb38 100644 --- a/70-07.html +++ b/70-07.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        GLQuake

        +

        GLQuake

        The second (and, according to current plans, last) port of Quake to a hardware accelerator was an OpenGL version, GLQuake, a native Win32 application. I have no intention of getting into the 3-D API wars currently raging; the observation I want to make here is that GLQuake uses two-pass alpha lighting, and runs very well on fast chips such as the 3Dfx, but rather slowly on most of the current group of accelerators. The accelerators coming out this year should all run GLQuake fine, however. It’s also worth noting that we’ll be using two-pass alpha lighting in the N64 port of Quake; in fact, it looks like the N64’s hardware is capable of performing both texture-tiling and alpha-lighting in a single pass, which is pretty much an ideal hardware-acceleration architecture: It’s as good looking and generally faster than surface caching, without the need to build, download, and cache surfaces, and much better looking and about as fast as Gouraud shading. We hope to see similar capabilities implemented in PC accelerators and exposed by 3-D APIs in the near future.

        Dynamic lighting is done differently in GLQuake than in software Quake. It could have been implemented by changing the light maps, as usual, but current OpenGL drivers are not very fast at downloading textures (when the light maps are used as in GLQuake); also, it takes time to identify and change the affected light maps. Instead, GLQuake simply alpha-blends an approximate sphere around the light source. This requires very little calculation and no texture downloading, and as a bonus allows dynamic lights to be colored, so a rocket, for example, can cast a yellowish light.

        @@ -45,11 +45,11 @@

        One good illustration of how much easier a good 3-D API can make development is how quickly John was able to add two eye-candy features to GLQuake: dynamic shadows and reflections. Dynamic shadows were implemented by projecting a model’s silhouette onto the ground plane, then alpha-blending that silhouette into the world. This doesn’t always work properly—for example, if the player is standing at the edge of a cliff, the shadow sticks out in the air—but it was added in a few hours, and most of the time looks terrific. Implementing it properly will take only a day or two more and should run adequately fast; it’s a simple matter of projecting the silhouette into the world, and onto the surfaces it encounters.

        Reflections are a bit more complex, but again were implemented in a day. A special texture is designated as a mirror surface; when this is encountered while drawing, a hole is left. Then the z-range is changed so that everything drawn next is considered more distant than the scene just drawn, and a second scene is drawn, this time from the reflected viewpoint behind the mirror; this causes the mirror to be behind any nearer objects in the true scene. The only drawback to this approach (apart from the extra processing time to draw two scenes) is that because of the z-range change, the mirror must be against a sealed wall, with nothing in the PVS behind it, to ensure that a hole is left into which the reflection can be drawn. (Note that an OpenGL stencil buffer would be ideal here, but while OpenGL accelerators can be relied upon to support z-buffering and alpha-blending in hardware, the same is not yet true of stencil buffers.) As a final step, a marbled texture is blended into the mirror surface, to make the surface itself less than perfectly reflective and visible enough to seem real.

        Both alpha-blending and z-buffering are relatively new to PC games, but are standard equipment on accelerators, and it’s a lot of fun seeing what sorts of previously very difficult effects can now be up and working in a matter of hours.

        -

        WinQuake

        +

        WinQuake

        I’m not going to spend much time on the Win32 port of Quake; most of what I learned doing this consists of tedious details that are doubtless well covered elsewhere, and frankly it wasn’t a particularly interesting task and was harder than I expected, and I’m pretty much tired of the whole thing. However, I will say that Win32 is clearly the future, especially now that NT is coming on strong, and like it or not, you had best learn to write games for Win32. Also, Internet gaming is becoming ever more important, and Win32’s built-in TCP/IP support is a big advantage over DOS; that alone was enough to convince us we had to port Quake. As a last comment, I’d say that it is nice to have Windows take care of device configuration and interfacing—now if only we could get manufacturers to write drivers for those devices that actually worked reliably! This will come as no surprise to veteran Windows programmers, who have suffered through years of buggy 2-D Windows drivers, but if you’re new to Windows programming, be prepared to run into and learn to work around—or at least document in your readme files—driver bugs on a regular basis.

        Still, when you get down to it, the future of gaming is a networked Win32 world, and that’s that, so if you haven’t already moved to Win32, I’d say it’s time.

        -

        QuakeWorld

        +

        QuakeWorld

        QuakeWorld is a native Win32 multiplayer-only version of Quake, and was done as a learning experience; it is not a commercial product, but is freely distributed on the Internet. The idea behind it was to try to improve the multiplayer experience, especially for people linked by modem, by reducing actual and perceived latency. Before I discuss QuakeWorld, however, I should discuss the evolution of Quake’s multiplayer code.


        @@ -64,7 +64,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-08.html b/70-08.html index 2888ff6..387869a 100644 --- a/70-08.html +++ b/70-08.html @@ -24,7 +24,7 @@ - +
        @@ -47,7 +47,7 @@

        In the long run, it’s cheaper to rewrite than to patch and modify!

        So as of shipping Quake, multiplayer performance was quite smooth, but latency was still a major issue, often in the 250 to 400 ms range for modem players. QuakeWorld attacked this in two ways. First, it reduced latency by around 50 to 100 ms with a server change. The Quake server runs 10 or 20 times a second, batching up inputs in between ticks, and sending out results after the tick. By contrast, QuakeWorld servers run immediately whenever a client sends input, knocking up to 50 or 100 ms off response time, although at the cost of a greater server processing load. (A similar anti-latency idea that wasn’t implemented in QuakeWorld is having a separate thread that can send input off to the server as soon as it happens, instead of incurring up to a frame of latency.)

        The second way in which QuakeWorld attacks latency is by not interpolating. The player is actually predicted well ahead of the latest server packet (after all, the client has all the information needed to move the player, unless an outside force intervenes), giving very responsive control. The rest of the world is drawn as of the latest server packet; this is jerkier than Quake, again showing that smoothness is often a tradeoff for latency. The player’s prediction may, of course, result in a minor paradox; for example, if an explosion turns out to have knocked the player sideways, the player’s location may suddenly jump without warning as the server packet arrives with the correct location. In the latest version of QuakeWorld, the other players are predicted as well, with consequently more frequent paradoxes, but smoother, more convincing motion. Platforms and doors are still not predicted, and consequently are still pretty jerky. It is, of course, possible to predict more and more objects into the future; it’s a tradeoff of smoothness and perceived low latency for the frustration of paradoxes—and that’s the way it’s going to stay until most people are connected to the Internet by something better than modems.

        -

        Quake 2

        +

        Quake 2

        I can’t talk in detail about Quake 2 as a game, but I can describe some interesting technology features. The Quake 2 rendering engine isn’t going to change that much from Quake; the improvements are largely in areas such as physics, gameplay, artwork, and overall design. The most interesting graphics change is in the preprocessing, where John has added support for radiosity lighting; that is, the ability to put a light source into the world and have the light bounced around the world realistically. This is sometimes terrific—it makes for great glowing light around lava and hanging light panels—but in other cases it’s less spectacular than the effects that designers can get by placing lots of direct-illumination light sources in a room, so the two methods can be used as needed. Also, radiosity is very computationally expensive, approximately as expensive as BSPing. Most of the radiosity demos I’ve seen have been in one or two rooms, and the order of the problem goes up tremendously on whole Quake levels. Here’s another case where the PVS is essential; without it, radiosity processing time would be O(polygons2), but with the PVS it’s O(polygons*average_potentially_visible_polygons), which is over an order of magnitude less (and increases approximately linearly, rather than as a squared function, with greater-level complexity).


        @@ -61,7 +61,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/70-09.html b/70-09.html index 7483a67..ae06ad0 100644 --- a/70-09.html +++ b/70-09.html @@ -24,7 +24,7 @@ - +
        @@ -41,7 +41,7 @@

        Another likely change in Quake 2 is a shift from interpreted Quake-C code for game logic to compiled DLLs. Part of the incentive here is performance—interpretation isn’t cheap—and part is debugging, because the standard debugger can be used with DLLs. The drawback, of course, is portability; Quake-C program files are completely portable to any platform Quake runs on, with no modification or recompilation, but DLLs compiled for Win32 require a real porting effort to run anywhere else. Our thinking here is that there are almost no non-console platforms other than the PC that matter that much anymore, and for those few that do (notably the Mac and Linux), the DLLs can be ported along with the core engine code. It just doesn’t make sense for easy portability to tiny markets to impose a significant development and performance cost on the one huge market. Consoles will always require serious porting effort anyway, so going to Win32-specific DLLs for the PC version won’t make much difference in the ease of doing console ports.

        Finally, Internet support will improve in Quake 2. Some of the QuakeWorld latency improvements will doubtless be added, but more important, there will be a new interface, especially for monitoring and joining net games, in the form of an HTML page. John has always been interested in moving as much code as possible out of the game core, and letting the browser take care of most of the UI makes it possible to eliminate menuing and such from the Quake 2 engine. Think of being able to browse hundreds of Quake servers from a single Web page (much as you can today with QSpy, but with the advantage of a standard, familiar interface and easy extensibility), and I think you’ll see why John considers this the game interface of the future.

        By the way, Quake 2 is currently being developed as a native Win32 app only; no DOS version is planned.

        -

        Looking Forward

        +

        Looking Forward

        In my address to the Computer Game Developer’s Conference in 1996, I said that it wasn’t a bad time to start up a game company aimed at hardware-only rasterization, and trying to make a game that leapfrogged the competition. It looks like I was probably a year early, because hardware took longer to ship than I expected, although there was a good living to be made writing games that hardware vendors could bundle with their boards. Now, though, it clearly is time. By Christmas 1997, there will be several million fast accelerators out there, and by Christmas 1998, there will be tens of millions. At the same time, vastly more people are getting access to the Internet, and it’s from the convergence of these two trends that I think the technology for the next generation of breakthrough real-time games will emerge.

        John is already working on id’s next graphics engine, code-named Trinity and targeted around Christmas of 1998. Trinity is not only a hardware-only engine, its baseline system is a Pentium Pro 200-plus with MMX, 32 MB, and an accelerator capable of at least 50 megapixels and 300 K triangles per second with alpha blending and z-buffering. The goals of Trinity are quite different from those of Quake. Quake’s primary technical goals were to do high-quality, well-lit, complex indoor scenes with 6 degrees of freedom, and to support client-server Internet play. That was a good start, but only that. Trinity’s goals are to have much less-constrained, better-connected worlds than Quake. Imagine seeing through open landscape from one server to the next, and seeing the action on adjacent servers in detail, in real time, and you’ll have an idea of where things are heading in the near future.

        @@ -62,7 +62,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/about.html b/about.html index 54d59e3..e08b3f0 100644 --- a/about.html +++ b/about.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Foreword

        +

        Foreword

        I got my start programming on Apple II computers at school, and almost all of my early work was on the Apple platform. After graduating, it quickly became obvious that I was going to have trouble paying my rent working in the Apple II market in the late eighties, so I was forced to make a very rapid move into the Intel PC environment.

        What I was able to pick up over several years on the Apple, I needed to learn in the space of a few months on the PC.

        @@ -68,7 +68,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/about_author.html b/about_author.html index 0050192..9bb7752 100644 --- a/about_author.html +++ b/about_author.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Acknowledgments

        +

        Acknowledgments

        There are many people to thank—because this book was written over many years, in many different settings, an unusually large number of people have played a part in making this book possible. Thanks to Dan Illowsky for not only contributing ideas and encouragement, but also getting me started writing articles long ago, when I lacked the confidence to do it on my own—and for teaching me how to handle the business end of things. Thanks to Will Fastie for giving me my first crack at writing for a large audience in the long-gone but still-missed PC Tech Journal, and for showing me how much fun it could be in his even longer-vanished but genuinely terrific column in Creative Computing (the most enjoyable single column I have ever read in a computer magazine; I used to haunt the mailbox around the beginning of the month just to see what Will had to say). Thanks to Robert Keller, Erin O’Connor, Liz Oakley, Steve Baker, and the rest of the cast of thousands that made Programmer’s Journal a uniquely fun magazine—especially Erin, who did more than anyone to teach me the proper use of the English language. (To this day, Erin will still patiently explain to me when one should use “that” and when one should use “which,” even though eight years of instruction on this and related topics have left no discernible imprint on my brain.) Thanks to Tami Zemel, Monica Berg, and the rest of the Dr. Dobb’s Journal crew for excellent, professional editing, and for just being great people. Thanks to the Coriolis gang for their tireless hard work: Jeff Duntemann, Kim Eoff, Jody Kent, Robert Clarfield, and Anthony Stock. Thanks to Jack Tseng for teaching me a lot about graphics hardware, and even more about how much difference hard work can make. Thanks to John Cockerham, David Stafford, Terje Mathisen, the BitMan, Chris Hecker, Jim Mackraz, Melvin Lafitte, John Navas, Phil Coleman, Anton Truenfels, John Carmack, John Miles, John Bridges, Jim Kent, Hal Hardenbergh, Dave Miller, Steve Levy, Jack Davis, Duane Strong, Daev Rohr, Bill Weber, Dan Gochnauer, Patrick Milligan, Tom Wilson, Peter Klerings, Dave Methvin, Mick Brown, the people in the ibm.pc/fast.code topic on Bix, and all the rest of you who have been so generous with your ideas and suggestions. I’ve done my best to acknowledge contributors by name in this book, but if your name is omitted, my apologies, and consider yourself thanked; this book could not have happened without you. And, of course, thanks to Shay and Emily for their generous patience with my passion for writing and computers.


        @@ -50,7 +50,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/appendix-a.html b/appendix-a.html index c09fd9d..dfa17b3 100644 --- a/appendix-a.html +++ b/appendix-a.html @@ -23,7 +23,7 @@ - +
        @@ -35,7 +35,7 @@


        -

        Afterword

        +

        Afterword

        If you’ve followed me this far, you might agree that we’ve come through some rough country. Still, I’m of the opinion that hard-won knowledge is the best knowledge, not only because it sticks to you better, but also because winning a hard race makes it easier to win the next one.

        This is an unusual book in that sense: In addition to being a compilation of much of what I know about fast computer graphics, it is a journal recording some of the process by which I discovered and refined that knowledge. I didn’t just sit down one day to write this book—I wrote it over a period of years and published its component parts in many places. It is a journal of my successes and frustrations, with side glances of my life as it happened along the way.

        @@ -61,7 +61,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/book-index.html b/book-index.html index 8414b4e..093c26c 100644 --- a/book-index.html +++ b/book-index.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Index

        +

        Index

        Numbers
        1/z sorting @@ -4585,7 +4585,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/index.html b/index.html index eecb229..823e40b 100644 --- a/index.html +++ b/index.html @@ -24,9 +24,9 @@ - + -

        Michael Abrash's Graphics Programming Black Book Special Edition

        +

        Michael Abrash's Graphics Programming Black Book Special Edition


        @@ -35,9 +35,9 @@
        About the Author
        -
        Part I +
        Part I
        -
        Chapter 1—The Best Optimizer Is between Your Ears +
        Chapter 1—The Best Optimizer Is between Your Ears
        The Human Element of Code Optimization @@ -61,7 +61,7 @@
        -
        Chapter 2—A World Apart +
        Chapter 2—A World Apart
        The Unique Nature of Assembly Language Optimization @@ -78,7 +78,7 @@
        -
        Chapter 3—Assume Nothing +
        Chapter 3—Assume Nothing
        Understanding and Using the Zen Timer @@ -106,7 +106,7 @@
        -
        Chapter 4—In the Lair of the Cycle-Eaters +
        Chapter 4—In the Lair of the Cycle-Eaters
        How the PC Hardware Devours Code Performance @@ -144,7 +144,7 @@
        -
        Chapter 5—Crossing the Border +
        Chapter 5—Crossing the Border
        Searching Files with Restartable Blocks @@ -164,7 +164,7 @@
        Always Look Where Execution Is Going
        -
        Chapter 6—Looking Past Face Value +
        Chapter 6—Looking Past Face Value
        How Machine Instructions May Do More Than You Think @@ -178,7 +178,7 @@
        Multiplication with LEA Using Non-Powers of Two
        -
        Chapter 7—Local Optimization +
        Chapter 7—Local Optimization
        Optimizing Halfway between Algorithms and Cycle Counting @@ -198,7 +198,7 @@
        -
        Chapter 8—Speeding Up C with Assembly Language +
        Chapter 8—Speeding Up C with Assembly Language
        Jumping Languages When You Know It’ll Help @@ -217,7 +217,7 @@
        -
        Chapter 9—Hints My Readers Gave Me +
        Chapter 9—Hints My Readers Gave Me
        Optimization Odds and Ends from the Field @@ -235,7 +235,7 @@
        -
        Chapter 10—Patient Coding, Faster Code +
        Chapter 10—Patient Coding, Faster Code
        How Working Quickly Can Bring Execution to a Crawl @@ -252,7 +252,7 @@
        -
        Chapter 11—Pushing the 286 and 386 +
        Chapter 11—Pushing the 286 and 386
        New Registers, New Instructions, New Timings, New Complications @@ -281,7 +281,7 @@
        -
        Chapter 12—Pushing the 486 +
        Chapter 12—Pushing the 486
        It’s Not Just a Bigger 386 @@ -303,7 +303,7 @@
        The Story Continues
        -
        Chapter 13—Aiming the 486 +
        Chapter 13—Aiming the 486
        Pipelines and Other Hazards of the High End @@ -316,7 +316,7 @@
        32-Bit Addressing Modes
        -
        Chapter 14—Boyer-Moore String Searching +
        Chapter 14—Boyer-Moore String Searching
        Optimizing a Pretty Optimum Search Algorithm @@ -327,7 +327,7 @@
        Know What You Know
        -
        Chapter 15—Linked Lists and plain Unintended Challenges +
        Chapter 15—Linked Lists and plain Unintended Challenges
        Unfamiliar Problems with Familiar Data Structures @@ -337,7 +337,7 @@
        Hi/Lo in 24 Bytes
        -
        Chapter 16—There Ain’t No Such Thing as the Fastest Code +
        Chapter 16—There Ain’t No Such Thing as the Fastest Code
        Lessons Learned in the Pursuit of the Ultimate Word Counter @@ -362,7 +362,7 @@
        -
        Chapter 17—The Game of Life +
        Chapter 17—The Game of Life
        The Triumph of Algorithmic Optimization in a Cellular Automata Game @@ -381,7 +381,7 @@
        -
        Chapter 18—It’s a plain Wonderful Life +
        Chapter 18—It’s a plain Wonderful Life
        Optimization beyond the Pale @@ -393,7 +393,7 @@
        -
        Chapter 19—Pentium: Not the Same Old Song +
        Chapter 19—Pentium: Not the Same Old Song
        Learning a Whole Different Set of Optimization Rules @@ -412,7 +412,7 @@
        -
        Chapter 20—Pentium Rules +
        Chapter 20—Pentium Rules
        How Your Carbon-Based Optimizer Can Put the “Super” in Superscalar @@ -425,7 +425,7 @@
        -
        Chapter 21—Unleashing the Pentium’s V-Pipe +
        Chapter 21—Unleashing the Pentium’s V-Pipe
        Focusing on Keeping Both Pentium Pipes Full @@ -441,7 +441,7 @@
        -
        Chapter 22—Zenning and the Flexible Mind +
        Chapter 22—Zenning and the Flexible Mind
        Taking a Spin through What You’ve Learned @@ -450,9 +450,9 @@

        -
        Part II +
        Part II
        -
        Chapter 23—Bones and Sinew +
        Chapter 23—Bones and Sinew
        At the Very Heart of Standard PC Graphics @@ -470,7 +470,7 @@
        The Macro Assembler
        -
        Chapter 24—Parallel Processing with the VGA +
        Chapter 24—Parallel Processing with the VGA
        Taking on Graphics Memory Four Bytes at a Time @@ -478,7 +478,7 @@
        Notes on the ALU/Latch Demo Program
        -
        Chapter 25—VGA Data Machinery +
        Chapter 25—VGA Data Machinery
        The Barrel Shifter, Bit Mask, and Set/Reset Mechanisms @@ -493,7 +493,7 @@
        A Brief Note on Word OUTs
        -
        Chapter 26—VGA Write Mode 3 +
        Chapter 26—VGA Write Mode 3
        The Write Mode That Grows on You @@ -501,7 +501,7 @@
        A Note on Preserving Register Bits
        -
        Chapter 27—Yet Another VGA Write Mode +
        Chapter 27—Yet Another VGA Write Mode
        Write Mode 2, Chunky Bitmaps,and Text-Graphics Coexistence @@ -516,7 +516,7 @@
        Flipping Pages from Text to Graphics and Back
        -
        Chapter 28—Reading VGA Memory +
        Chapter 28—Reading VGA Memory
        Read Modes 0 and 1, and the Color Don’t Care Register @@ -525,7 +525,7 @@
        When all Planes “Don’t Care”
        -
        Chapter 29—Saving Screens and Other VGA Mysteries +
        Chapter 29—Saving Screens and Other VGA Mysteries
        Useful Nuggets from the VGA Zen File @@ -536,7 +536,7 @@
        Modifying VGA Registers
        -
        Chapter 30—Video Est Omnis Divisa +
        Chapter 30—Video Est Omnis Divisa
        The Joys and Galling Problems of Using Split Screens on the EGA and VGA @@ -556,7 +556,7 @@
        How Safe?
        -
        Chapter 31—Higher 256-Color Resolution on the VGA +
        Chapter 31—Higher 256-Color Resolution on the VGA
        When Is 320x200 Really 320x400? @@ -570,7 +570,7 @@
        Something to Think About
        -
        Chapter 32—Be It Resolved: 360x480 +
        Chapter 32—Be It Resolved: 360x480
        Taking 256-Color Modes About as Far as the Standard VGA Can Take Them @@ -584,7 +584,7 @@
        -
        Chapter 33—Yogi Bear and Eurythmics Confront VGA Colors +
        Chapter 33—Yogi Bear and Eurythmics Confront VGA Colors
        The Basics of VGA Color Generation @@ -601,7 +601,7 @@
        An Example of Setting the DAC
        -
        Chapter 34—Changing Colors without Writing Pixels +
        Chapter 34—Changing Colors without Writing Pixels
        Special Effects through Realtime Manipulation of DAC Colors @@ -621,7 +621,7 @@
        -
        Chapter 35—Bresenham Is Fast, and Fast Is Good +
        Chapter 35—Bresenham Is Fast, and Fast Is Good
        Implementing and Optimizing Bresenham’s Line-Drawing Algorithm @@ -640,7 +640,7 @@
        Bresenham’s Algorithm in Assembly
        -
        Chapter 36—The Good, the Bad, and the Run-Sliced +
        Chapter 36—The Good, the Bad, and the Run-Sliced
        Faster Bresenham Lines with Run-Length Slice Line Drawing @@ -649,7 +649,7 @@
        Run-Length Slice Details
        -
        Chapter 37—Dead Cats and Lightning Lines +
        Chapter 37—Dead Cats and Lightning Lines
        Optimizing Run-Length Slice Line Drawing in a Major Way @@ -660,7 +660,7 @@
        -
        Chapter 38—The Polygon Primeval +
        Chapter 38—The Polygon Primeval
        Drawing Polygons Efficiently and Quickly @@ -673,7 +673,7 @@
        Oddball Cases
        -
        Chapter 39—Fast Convex Polygons +
        Chapter 39—Fast Convex Polygons
        Filling Polygons in a Hurry @@ -689,7 +689,7 @@
        Faster Edge Tracing
        -
        Chapter 40—Of Songs, Taxes, and the Simplicity of Complex Polygons +
        Chapter 40—Of Songs, Taxes, and the Simplicity of Complex Polygons
        Dealing with Irregular Polygonal Areas @@ -708,14 +708,14 @@
        -
        Chapter 41—Those Way-Down Polygon Nomenclature Blues +
        Chapter 41—Those Way-Down Polygon Nomenclature Blues
        Names Do Matter when You Conceptualize a Data Structure
        Nomenclature in Action
        -
        Chapter 42—Wu’ed in Haste; Fried, Stewed at Leisure +
        Chapter 42—Wu’ed in Haste; Fried, Stewed at Leisure
        Fast Antialiased Lines Using Wu’s Algorithm @@ -727,7 +727,7 @@
        -
        Chapter 43—Bit-Plane Animation +
        Chapter 43—Bit-Plane Animation
        A Simple and Extremely Fast Animation Method for Limited Color @@ -741,7 +741,7 @@
        Beating the Odds in the Jaw-Dropping Contest
        -
        Chapter 44—Split Screens Save the Page Flipped Day +
        Chapter 44—Split Screens Save the Page Flipped Day
        640x480 Page Flipped Animation in 64K...Almost @@ -758,7 +758,7 @@
        -
        Chapter 45—Dog Hair and Dirty Rectangles +
        Chapter 45—Dog Hair and Dirty Rectangles
        Different Angles on Animation @@ -773,7 +773,7 @@
        Another Interesting Twist on Page Flipping
        -
        Chapter 46—Who Was that Masked Image? +
        Chapter 46—Who Was that Masked Image?
        Optimizing Dirty-Rectangle Animation @@ -788,7 +788,7 @@
        -
        Chapter 47—Mode X: 256-Color VGA Magic +
        Chapter 47—Mode X: 256-Color VGA Magic
        Introducing the VGA’s Undocumented “Animation-Optimal” Mode @@ -798,7 +798,7 @@
        Hardware Assist from an Unexpected Quarter
        -
        Chapter 48—Mode X Marks the Latch +
        Chapter 48—Mode X Marks the Latch
        The Internals of Animation’s Best Video Display Mode @@ -810,7 +810,7 @@
        Who Was that Masked Image Copier?
        -
        Chapter 49—Mode X 256-Color Animation +
        Chapter 49—Mode X 256-Color Animation
        How to Make the VGA Really Get up and Dance @@ -824,7 +824,7 @@
        Works Fast, Looks Great
        -
        Chapter 50—Adding a Dimension +
        Chapter 50—Adding a Dimension
        3-D Animation Using Mode X @@ -842,7 +842,7 @@
        An Ongoing Journey
        -
        Chapter 51—Sneakers in Space +
        Chapter 51—Sneakers in Space
        Using Backface Removal to Eliminate Hidden Surfaces @@ -855,7 +855,7 @@
        Object Representation
        -
        Chapter 52—Fast 3-D Animation: Meet X-Sharp +
        Chapter 52—Fast 3-D Animation: Meet X-Sharp
        The First Iteration of a Generalized 3-D Animation Package @@ -868,7 +868,7 @@
        -
        Chapter 53—Raw Speed and More +
        Chapter 53—Raw Speed and More
        The Naked Truth About Speed in 3-D Animation @@ -880,7 +880,7 @@
        -
        Chapter 54—3-D Shading +
        Chapter 54—3-D Shading
        Putting Realistic Surfaces on Animated 3-D Objects @@ -895,7 +895,7 @@
        -
        Chapter 55—Color Modeling in 256-Color Mode +
        Chapter 55—Color Modeling in 256-Color Mode
        Pondering X-Sharp’s Color Model in an RGB State of Mind @@ -905,7 +905,7 @@
        -
        Chapter 56—Pooh and the Space Station +
        Chapter 56—Pooh and the Space Station
        Using Fast Texture Mapping to Place Pooh on a Polygon @@ -916,7 +916,7 @@
        Fast Texture Mapping: An Implementation
        -
        Chapter 57—10,000 Freshly Sheared Sheep on the Screen +
        Chapter 57—10,000 Freshly Sheared Sheep on the Screen
        The Critical Role of Experience in Implementing Fast, Smooth Texture Mapping @@ -931,7 +931,7 @@
        -
        Chapter 58—Heinlein’s Crystal Ball, Spock’s Brain, and the 9-Cycle Dare +
        Chapter 58—Heinlein’s Crystal Ball, Spock’s Brain, and the 9-Cycle Dare
        Using the Whole-Brain Approach to Accelerate Texture Mapping @@ -947,7 +947,7 @@
        Texture Mapping Notes
        -
        Chapter 59—The Idea of BSP Trees +
        Chapter 59—The Idea of BSP Trees
        What BSP Trees Are and How to Walk Them @@ -971,7 +971,7 @@
        -
        Chapter 60—Compiling BSP Trees +
        Chapter 60—Compiling BSP Trees
        Taking BSP Trees from Concept to Reality @@ -985,7 +985,7 @@
        BSP Optimization: an Undiscovered Country
        -
        Chapter 61—Frames of Reference +
        Chapter 61—Frames of Reference
        The Fundamentals of the Math behind 3-D Graphics @@ -1003,7 +1003,7 @@
        Rotation by Projection
        -
        Chapter 62—One Story, Two Rules, and a BSP Renderer +
        Chapter 62—One Story, Two Rules, and a BSP Renderer
        Taking a Compiled BSP Tree from Logical to Visual Reality @@ -1021,7 +1021,7 @@
        -
        Chapter 63—Floating-Point for Real-Time 3-D +
        Chapter 63—Floating-Point for Real-Time 3-D
        Knowing When to Hurl Conventional Math Wisdom Out the Window @@ -1039,7 +1039,7 @@
        A Farewell to 3-D Fixed-Point
        -
        Chapter 64—Quake’s Visible-Surface Determination +
        Chapter 64—Quake’s Visible-Surface Determination
        The Challenge of Separating All Things Seen from All Things Unseen @@ -1065,7 +1065,7 @@
        References
        -
        Chapter 65—3-D Clipping and Other Thoughts +
        Chapter 65—3-D Clipping and Other Thoughts
        Determining What’s Inside Your Field of View @@ -1082,7 +1082,7 @@
        Further Reading
        -
        Chapter 66—Quake’s Hidden-Surface Removal +
        Chapter 66—Quake’s Hidden-Surface Removal
        Struggling with Z-Order Solutions to the Hidden Surface Problem @@ -1102,7 +1102,7 @@
        Decisions Deferred
        -
        Chapter 67—Sorted Spans in Action +
        Chapter 67—Sorted Spans in Action
        Implementing Independent Span Sorting for Rendering without Overdraw @@ -1119,7 +1119,7 @@
        -
        Chapter 68—Quake’s Lighting Model +
        Chapter 68—Quake’s Lighting Model
        A Radically Different Approach to Lighting Polygons @@ -1141,7 +1141,7 @@
        -
        Chapter 69—Surface Caching and Quake’s Triangle Models +
        Chapter 69—Surface Caching and Quake’s Triangle Models
        Probing Hardware-Assisted Surfaces and Fast Model Animation Without Sprites @@ -1160,7 +1160,7 @@
        -
        Chapter 70—Quake: A Post-Mortem and a Glimpse into the Future +
        Chapter 70—Quake: A Post-Mortem and a Glimpse into the Future
        Preprocessing the World @@ -1201,7 +1201,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash
        diff --git a/intro.html b/intro.html index 3734eac..ad0eead 100644 --- a/intro.html +++ b/intro.html @@ -24,7 +24,7 @@ - +
        @@ -36,7 +36,7 @@


        -

        Introduction

        +

        Introduction

        What was it like working with John Carmack on Quake? Like being strapped onto a rocket during takeoff—in the middle of a hurricane. It seemed like the whole world was watching, waiting to see if id Software could top Doom; every casual e-mail tidbit or conversation with a visitor ended up posted on the Internet within hours. And meanwhile, we were pouring everything we had into Quake’s technology; I’d often come in in the morning to find John still there, working on a new idea so intriguing that he couldn’t bear to sleep until he had tried it out. Toward the end, when I spent most of my time speeding things up, I would spend the day in a trance writing optimized assembly code, stagger out of the Town East Tower into the blazing Texas heat, and somehow drive home on LBJ Freeway without smacking into any of the speeding pickups whizzing past me on both sides. At home, I’d fall into a fitful sleep, then come back the next day in a daze and do it again. Everything happened so fast, and under so much pressure, that sometimes I wonder how any of us made it through that without completely burning out.

        At the same time, of course, it was tremendously exciting. John’s ideas were endless and brilliant, and Quake ended up establishing a new standard for Internet and first-person 3-D game technology. Happily, id has an enlightened attitude about sharing information, and was willing to let me write about the Quake technology—both how it worked and how it evolved. Over the two years I worked at id, I wrote a number of columns about Quake in Dr. Dobb’s Sourcebook, as well as a detailed overview for the 1997 Computer Game Developers Conference. You can find these in the latter part of this book; they represent a rare look into the development and inner workings of leading-edge software development, and I hope you enjoy reading them as much as I enjoyed developing the technology and writing about it.

        @@ -59,7 +59,7 @@
        -Graphics Programming Black Book © 2001 Michael Abrash +Graphics Programming Black Book © 2001 Michael Abrash