Home > Articles > Programming

This chapter is from the book

Blending

You already learned that OpenGL rendering places color values in the color buffer under normal circumstances. You also learned that depth values for each fragment are also placed in the depth buffer. When depth testing is turned off (disabled), new color values simply overwrite any other values already present in the color buffer. When depth testing is turned on (enabled), new color fragments replace an existing fragment only if they are deemed closer to the near clipping plane than the values already there. Under normal circumstances then, any drawing operation is either discarded entirely, or just completely overwrites any old color values, depending on the result of the depth test. This obliteration of the underlying color values no longer happens the moment you turn on OpenGL blending:

glEnable(GL_BLEND);

When blending is enabled, the incoming color is combined with the color value already present in the color buffer. How these colors are combined leads to a great many and varied special effects.

Combining Colors

First, we must introduce a more official terminology for the color values coming in and already in the color buffer. The color value already stored in the color buffer is called the destination color, and this color value contains the three individual red, green, and blue components, and optionally a stored alpha value as well. A color value that is coming in as a result of more rendering commands that may or may not interact with the destination color is called the source color. The source color also contains either three or four color components (red, green, blue, and optionally alpha). Note that anytime you omit an alpha value, OpenGL assumes it is 1.0.

How the source and destination colors are combined when blending is enabled is controlled by the blending equation. By default, the blending equation looks like this:

  • Cf = (Cs * S) + (Cd * D)

Here, Cf is the final computed color, Cs is the source color, Cd is the destination color, and S and D are the source and destination blending factors. These blending factors are set with the following function:

glBlendFunc(GLenum S, GLenum D);

As you can see, S and D are enumerants and not physical values that you specify directly. Table 3.3 lists the possible values for the blending function. The subscripts stand for source, destination, and color (for blend color, to be discussed shortly). R, G, B, and A stand for Red, Green, Blue, and Alpha, respectively.

Table 3.3. OpenGL Blending Factors

Function

RGB Blend Factors

Alpha Blend Factor

GL_ZERO

(0,0,0)

0

GL_ONE

(1,1,1)

1

GL_SRC_COLOR

(Rs,Gs,Bs)

As

GL_ONE_MINUS_SRC_COLOR

(1,1,1) – (Rs,Gs,Bs)

1 – As

GL_DST_COLOR

(Rd,Gd,Bd)

Ad

GL_ONE_MINUS_DST_COLOR

(1,1,1) – (Rd,Gd,Bd)

1 – Ad

GL_SRC_ALPHA

(As,As,As)

As

GL_ONE_MINUS_SRC_ALPHA

(1,1,1) – (As,As,As)

1 – As

GL_DST_ALPHA

(Ad,Ad,Ad)

Ad

GL_ONE_MINUS_DST_ALPHA

(1,1,1) – (Ad,Ad,Ad)

1 – Ad

GL_CONSTANT_COLOR

(Rc,Gc,Bc)

Ac

GL_ONE_MINUS_CONSTANT_COLOR

(1,1,1) – (Rc,Gc,Bc)

1 – Ac

GL_CONSTANT_ALPHA

(Ac,Ac,Ac)

Ac

GL_ONE_MINUS_CONSTANT_ALPHA

(1,1,1) – (Ac,Ac,Ac)

1 – Ac

GL_SRC_ALPHA_SATURATE

(f,f,f)*

1

Remember that colors are represented by floating-point numbers, so adding them, subtracting them, and even multiplying them are all perfectly valid operations. Table 3.3 may seem a bit bewildering, so let's look at a common blending function combination:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

This function tells OpenGL to take the source (incoming) color and multiply the color (the RGB values) by the alpha value. Add this to the result of multiplying the destination color by one minus the alpha value from the source. Say, for example, that you have the color Red (1.0f, 0.0f, 0.0f, 0.0f) already in the color buffer. This is the destination color, or Cd. If something is drawn over this with the color blue and an alpha of 0.6 (0.0f, 0.0f, 1.0f, 0.6f), you would compute the final color as shown here:

Cd = destination color = (1.0f, 0.0f, 0.0f, 0.0f)

Cs = source color = (0.0f, 0.0f, 1.0f, 0.6f)

S = source alpha = 0.6

D = one minus source alpha = 1.0 – 0.6 = 0.4

Now, the equation

  • Cf = (Cs * S) + (Cd * D)

evaluates to

  • Cf = (Blue * 0.6) + (Red * 0.4)

The final color is a scaled combination of the original red value and the incoming blue value. The higher the incoming alpha value, the more of the incoming color is added and the less of the original color is retained.

This blending function is often used to achieve the effect of drawing a transparent object in front of some other opaque object. This particular technique does require, however, that you draw the background object or objects first and then draw the transparent object blended over the top.

For example, in the Blending sample program, we use transparency to achieve the illusion of a partially transparent red rectangle that we can move about on a white background. Also in the window are a red, blue, green, and black rectangle. Using the cursor keys, you can move the transparent rectangle around and over the other colors. The output of this program is shown in Figure 3.26.

Figure 3.26

Figure 3.26 The movable red rectangle blending with the background colors.

This example is based on the Move example program from Chapter 2. In this case, however, the background is white, and we also draw the four other colored blocks in fixed locations. The red transparent block is drawn with blending turned on, and a red color that has an alpha set to 0.5.

GLfloat vRed[] = { 1.0f, 0.0f, 0.0f, 0.5f };
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vRed);
squareBatch.Draw();
glDisable(GL_BLEND);

It is interesting to note that the white simply dilutes the red color, the black darkens it, and blending red with red is simply...just still red.

Changing the Blending Equation

The blending equation we showed you earlier,

  • Cf = (Cs * S) + (Cd * D)

is the default blending equation. You can actually choose from five different blending equations, each given in Table 3.4 and selected with the following function:

void glBlendEquation(GLenum mode);

Table 3.4. Available Blend Equation Modes

Mode

Function

GL_FUNC_ADD (default)

Cf = (Cs * S) + (Cd * D)

GL_FUNC_SUBTRACT

Cf = (Cs * S) – (Cd * D)

GL_FUNC_REVERSE_SUBTRACT

Cf = (Cd * D) – (Cs * S)

GL_MIN

Cf = min(Cs, Cd)

GL_MAX

Cf = max(Cs, Cd)

In addition to glBlendFunc, you have even more flexibility with this function:

void glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);

Whereas glBlendFunc specifies the blend functions for source and destination RGBA values, glBlendFuncSeparate allows you to specify blending functions for the RGB and alpha components separately.

Finally, as shown in Table 3.4, the GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, and GL_ONE_MINUS_CONSTANT_ALPHA values all allow a constant blending color to be introduced to the blending equation. This constant blending color is initially black (0.0f, 0.0f, 0.0f, 0.0f), but it can be changed with this function:

void glBlendColor(GLclampf red, GLclampf green, Glclampf blue, GLclampf alpha);

Antialiasing

Another use for OpenGL's blending capabilities is antialiasing. Under most circumstances, individual rendered fragments are mapped to individual pixels on a computer screen. These pixels are square (or squarish), and usually you can spot the division between two colors quite clearly. These jaggies, as they are often called, catch the eye's attention and can destroy the illusion that the image is natural. These jaggies are a dead giveaway that the image is computer generated! For many rendering tasks, it is desirable to achieve as much realism as possible, particularly in games, simulations, or artistic endeavors. Figure 3.27 shows the output for the sample program Smoother. In Figure 3.28, we zoomed in on a line segment and some points to show the jagged edges.

Figure 3.27

Figure 3.27 Output from the program Smoother.

Figure 3.28

Figure 3.28 A closer look at some jaggies.

To get rid of the jagged edges between primitives, OpenGL uses blending to blend the color of the fragment with the destination color of the pixel and its surrounding pixels. In essence, pixel colors are smeared slightly to neighboring pixels along the edges of any primitives.

Turning on antialiasing is simple. First, you must enable blending and set the blending function to be the same as you used in the preceding section for transparency:

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

You also need to make sure the blend equation is set to GL_ADD, but because this is the default and most common blending equation, we don't show it here. After blending is enabled and the proper blending function and equation are selected, you can choose to antialias points, lines, and/or polygons (any solid primitive) by calling glEnable:

glEnable(GL_POINT_SMOOTH);    // Smooth out points
glEnable(GL_LINE_SMOOTH);     // Smooth out lines
glEnable(GL_POLYGON_SMOOTH);  // Smooth out polygon edges

You should use GL_POLYGON_SMOOTH with care. You might expect to smooth out edges on solid geometry, but there are other tedious rules to making this work. For example, geometry that overlaps requires a different blending mode, and you may need to sort your scene from front to back. We won't go into the details because this method of solid object antialiasing has fallen out of common use and has largely been replaced by a superior route to smoothing edges on 3D geometry called multisampling. This feature is discussed in the next section. Without multisampling, you can still get this overlapping geometry problem with antialiased lines that overlap. For wireframe rendering, for example, you can usually get away with just disabling depth testing to avoid the depth artifacts at the line intersections.

Listing 3.3 shows the code from the Smoother program that responds to a pop-up menu that allows the user to switch between antialiased and nonantialiased rendering modes. When this program is run with antialiasing enabled, the points and lines appear smoother (fuzzier). In Figure 3.29, a zoomed-in section shows the same area as Figure 3.27, but now with the jagged edges smoothed out.

Listing 3.3. Switching Between Antialiased and Normal Rendering

///////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
    {
    switch(value)
        {
        case 1:
            // Turn on antialiasing, and give hint to do the best
            // job possible.
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glEnable(GL_BLEND);
            glEnable(GL_POINT_SMOOTH);
            glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
            glEnable(GL_LINE_SMOOTH);
            glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
            glEnable(GL_POLYGON_SMOOTH);
            glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
            break;

        case 2:
            // Turn off blending and all smoothing
            glDisable(GL_BLEND);
            glDisable(GL_LINE_SMOOTH);
            glDisable(GL_POINT_SMOOTH);
            glDisable(GL_POLYGON_SMOOTH);
            break;

        default:
            break;
        }

    // Trigger a redraw
    glutPostRedisplay();
    }
Figure 3.29

Figure 3.29 No more jaggies!

Note especially here the calls to the glHint function discussed in Chapter 2. There are many algorithms and approaches to achieve antialiased primitives. Any specific OpenGL implementation may choose any one of those approaches, and perhaps even support two! You can ask OpenGL, if it does support multiple antialiasing algorithms, to choose one that is very fast (GL_FASTEST) or the one with the most accuracy in appearance (GL_NICEST).

Multisampling

One of the biggest advantages to antialiasing is that it smoothes out the edges of primitives and can lend a more natural and realistic appearance to renderings. Point and line smoothing is widely supported, but unfortunately polygon smoothing is not available on all platforms. Even when GL_POLYGON_SMOOTH is available, it is not as convenient a means of having your whole scene antialiased as you might think. Because it is based on the blending operation, you would need to sort all your primitives from front to back! Yuck.

A more modern addition to OpenGL to address this shortcoming is multisampling. When this feature is supported (it is an OpenGL 1.3 or later feature), an additional buffer is added to the framebuffer that includes the color, depth, and stencil values. All primitives are sampled multiple times per pixel, and the results are stored in this buffer. These samples are resolved to a single value each time the pixel is updated, so from the programmer's standpoint, it appears automatic and happens "behind the scenes." Naturally, this extra memory and processing that must take place are not without their performance penalties, and some implementations may not support multisampling for multiple rendering contexts.

To get multisampling, you must first obtain a rendering context that has support for a multisampled framebuffer. This varies from platform to platform, but GLUT exposes a bitfield (GLUT_MULTISAMPLE) that allows you to request this until you reach the operating system-specific chapters in Part III. For example, to request a multisampled, full-color, double-buffered framebuffer with depth, you would call

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE);

You can turn multisampling on and off using the glEnable/glDisable combination and the GL_MULTISAMPLE token:

glEnable(GL_MULTISAMPLE);

or

glDisable(GL_MULTISAMPLE);

Another important note about multisampling is that when it is enabled, the point, line, and polygon smoothing features via antialiasing are ignored if enabled. This means you cannot use point and line smoothing at the same time as multisampling. On a given OpenGL implementation, points and lines may look better with smoothing turned on instead of multisampling. To accommodate this, you might turn off multisampling before drawing points and lines and then turn on multisampling for other solid geometry. The following pseudocode shows a rough outline of how to do this:

glDisable(GL_MULTISAMPLE);
glEnable(GL_POINT_SMOOTH);

// Draw some smooth points
// ...
glDisable(GL_POINT_SMOOTH);
glEnable(GL_MULTISAMPLE);

Of course if you do not have a multisampled buffer to begin with, OpenGL behaves as if GL_MULTISAMPLE were disabled.

The multisample buffers use the RGB values of fragments by default and do not include the alpha component of the colors. You can change this by calling glEnable with one of the following three values:

  • GL_SAMPLE_ALPHA_TO_COVERAGEUse the alpha value.
  • GL_SAMPLE_ALPHA_TO_ONESet alpha to 1 and use it.
  • GL_SAMPLE_COVERAGEUse the value set with glSampleCoverage.

When GL_SAMPLE_COVERAGE is enabled, the glSampleCoverage function allows you to specify a value that is ANDed (bitwise) with the fragment coverage value:

void glSampleCoverage(GLclampf value, GLboolean invert);

This fine-tuning of how the multisample operation works is not strictly specified by the specification, and the exact results may vary from implementation to implementation.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020