Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

2.3 Drawing Details

When an application submits a primitive to OpenGL for rendering, OpenGL uses the current state to determine what operations to perform on the primitive data.

OpenGL supports a variety of flexible features that affect the appearance of rendered geometry. Some of the more complex operations, such as viewing, lighting, and texture mapping, are covered in their own chapters. This section explains a few of the simpler operations. OpenGL® Programming Guide and OpenGL® Shading Language present the complete OpenGL feature set.

2.3.1 Clearing the Framebuffer

Before issuing the first rendering command and periodically thereafter (typically, at the start of each frame), applications need to clear the contents of the framebuffer. OpenGL provides the glClear () command to perform this operation.


void glClear( GLbitfield mask );

Clears the framebuffer contents. mask is one or more bit values combined with the bitwise OR operator that specify the portion of the framebuffer to clear. If GL_COLOR_BUFFER_BIT is present in mask, glClear () clears the color buffer. If GL_DEPTH_BUFFER_BIT is present in mask, glClear () clears the depth buffer. If both bit values are present, glClear () clears both the color and depth buffers.

glClear () can also clear other parts of the framebuffer, such as the stencil and accumulation buffers. For a complete list of bit values accepted by glClear (), see "glClear" in OpenGL® Reference Manual.

U25B8.GIF OpenGL version: 1.0 and later.

Typically, applications clear both the color and depth buffers with a single glClear () call at the start of each frame.

glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

Clearing multiple buffers with a single glClear () call is more efficient than clearing separate buffers with separate glClear () calls. There are rendering techniques that require clearing the depth and color buffer separately, however. Try to clear both buffers at the same time when possible.

Your application controls the color that glClear () writes to the color buffer by calling glClearColor ().


void glClearColor( GLclampf red, GLclampf green, GLclampf blue,
  GLclampf alpha );

Specifies the clear color used by glClear (). red, green, blue, and alpha are four values specifying an RGBA color value and should be in the range 0.0 to 1.0. Subsequent calls to glClear () use this color value when clearing the color buffer.

U25B8.GIF OpenGL version: 1.0 and later.

glClearColor () sets the current clear color, which is black by default (0.0, 0.0, 0.0, 0.0). This is adequate for some applications. Applications that set the clear color usually do so at program init time.

Note that not all framebuffers contain an alpha channel. If the framebuffer doesn't have an alpha channel, OpenGL effectively ignores the alpha parameter when clearing. Specify whether your framebuffer contains an alpha channel with the GLUT command glutInitDisplayMode () or platform-specific framebuffer configuration calls.

You can also specify the depth value written into the depth buffer by glClear (). By default, glClear ( GL_DEPTH)BUFFER_BIT ) clears the depth buffer to the maximum depth value, which is adequate for many applications. To change this default, see "glDepthValue" in OpenGL® Reference Manual.

2.3.2 Modeling Transformations

Complex 3D scenes typically are composed of several objects or models displayed at specific locations within the scene. These objects are routinely modeled in their own modeling-coordinate system and transformed by the application to specific locations and orientations in the world-coordinate system. Consider a scene composed of an aircraft flying over a terrain model. Modelers create the aircraft by using a modeling software package and might use a coordinate system with the origin located in the center of the fuselage, with the aircraft nose oriented toward positive y and the top of the aircraft oriented toward positive z. To position and orient this aircraft model relative to the terrain model, the application must translate it laterally to the correct position and vertically to the correct altitude, and orient it to the desired pitch, roll, and aircraft heading.

OpenGL transforms all vertices through a geometry pipeline. The first stage of this pipeline is the modeling transformation stage. Your application specifies modeling transformations to position and orient models in the scene. To manage the transformation of your geometry effectively, you need to understand the full OpenGL transformation pipeline. See Chapter 3, "Transformation and Viewing," for details.

2.3.3 Smooth and Flat Shading

To simulate a smooth surface, OpenGL interpolates vertex colors during rasterization. To simulate a flat or faceted surface, change the default shade model from GL_SMOOTH to GL_FLAT by calling glShadeModel ( GL_FLAT ).


void glShadeModel( GLenum mode );

Specifies smooth or flat shading. mode is either GL_SMOOTH or GL_FLAT. The default value of GL_SMOOTH causes OpenGL to use Gouraud shading to interpolate vertex color values during rasterization. GL_FLAT causes OpenGL to color subsequent primitives with the color of the vertex that completes the primitive.

U25B8.GIF OpenGL version: 1.0 and later.

To determine the color of a primitive in flat shade mode, OpenGL uses the color of the vertex that completes the primitive. For GL_POINTS, this is simply the color of the vertex. For all line primitives (GL_LINES, GL_LINE_STRIP, and GL_LINE_LOOP), this is the color of the second vertex in a line segment.

For GL_TRIANGLES, OpenGL colors each triangle with the color of every third vertex. For both GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN, OpenGL colors the first triangle with the color of the third vertex and colors each subsequent triangle with the color of each subsequent vertex.

For GL_QUADS, OpenGL colors each quadrilateral with the color of every fourth vertex. For GL_QUAD_STRIP, OpenGL uses the color of the fourth vertex to color the first quadrilateral in the strip and every other vertex thereafter to color subsequent quadrilaterals.

For GL_POLYGON, OpenGL colors the entire polygon with the color of the final vertex.

2.3.4 Polygon Mode

It shouldn't be a surprise that filled primitives are drawn filled by default. Applications can specify, however, that OpenGL render filled primitives as lines or points with the glPolygonMode () command.


void glPolygonMode( GLenum face, GLenum mode );

Specifies the rendering style for filled primitives. mode is GL_POINT, GL_LINE, or GL_FILL; and face must be GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK to specify whether mode applies to front- or back-facing primitives, or both.

U25B8.GIF OpenGL version: 1.0 and later.

Polygon mode is useful for design applications that allow the user to switch between solid and wireframe rendering. Many applications also use it to highlight selected primitives or groups of primitives.

2.3.5 The Depth Test

OpenGL supports the depth test (or z-buffer) hidden-surface-removal algorithm (Catmull 1974).

To use the depth test, your application must allocate a depth buffer when creating its display window. In GLUT, use a bitwise OR to include the GLUT_DEPTH bit in the parameter to glutInitDisplayMode () before calling glutCreateWindow (). Applications typically specify a double-buffered RGB window with a depth buffer by using the following call:

glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );

The depth test is disabled by default. Enable it with glEnable ( GL_DEPTH_TEST ).

The depth-test feature discards a fragment if it fails to pass the depth comparison test. Typically, applications use the default comparison test, GL_LESS. In this case, a fragment passes the depth test if its window-space z value is less than the stored depth buffer value. Applications can change the default comparison test by calling glDepthFunc (). The GL_LEQUAL comparison test, which passes a fragment if its z value is less than or equal to the stored depth value, is useful in multipass algorithms. See "glDepthFunc" in OpenGL® Reference Manual for a complete description of this function.

OpenGL executes commands in the order in which they are sent by the application. This rule extends to rendering primitives; OpenGL processes vertex array rendering commands in the order in which they are sent by the application and renders primitives within a single vertex array in the order that the array indices specify. This feature allows applications to use the painter's algorithm to remove hidden surfaces, rendering a scene in order of decreasing distance. When applications disable the depth test, the first primitives rendered are overwritten by those that are rendered later.

2.3.6 Co-Planar Primitives

You might expect that fragments with the same window-space x and y values from co-planar primitives would also have identical window-space z values. OpenGL guarantees this only under certain circumstances. [4] When co-planar filled primitives have different vertices, floating-point roundoff error usually results in different window-space z values for overlapping pixels. Furthermore, because line primitives don't have plane equations, it's impossible for unextended OpenGL to generate identical window-space z values for co-planar lines and filled primitives. For this reason, setting glDepthFunc ( GL_LEQUAL ) is insufficient to cause co-planar primitives to pass the depth test.

Applications can apply a depth offset to polygonal primitives to resolve coplanarity issues.


void glPolygonOffset( GLfloat factor, GLfloat units );

Specifies parameters for altering fragment depth values. OpenGL scales the maximum window-space z slope of the current polygonal primitive by factor, scales the minimum resolvable depth buffer unit by units, and sums the results to obtain a depth offset value. When enabled, OpenGL adds this value to the window-space z value of each fragment before performing the depth test.

The depth offset feature is also referred to as polygon offset because it applies only to polygonal primitives.

U25B8.GIF OpenGL version: 1.1 and later.

Depth offset applies to polygonal primitives but can be separately enabled and disabled for each of the three polygon modes. To enable depth offset in fill mode, call glEnable ( GL_POLYGON_OFFSET_FILL ). Use GL_POLYGON_OFFSET_POINT and GL_POLYGON_OFFSET_LINE to enable or disable depth offset for point and line mode, respectively.

Typically, applications call glPolygonOffset ( 1.f, 1.f ) and glEnable ( GL_POLYGON_OFFSET_FILL ) to render filled primitives that are pushed back slightly into the depth buffer, then disable depth offset and draw co-planar geometry.

Figure 2-4 illustrates rendering co-planar primitives with and without depth offset.

02fig04.jpg

Figure 2-4 This figure illustrates the result of rendering Co-planar primitivesco-planar primitives. When depth offset is disabled (left), differences in rasterization of co-planar primitives results in rendering artifacts known as "z-fighting." Depth offset (right) eliminates these artifacts.

The following code was used to render the cylinders in Figure 2-4:

if (enableOffset)
    glEnable( GL_POLYGON_OFFSET_FILL );
else
    glDisable( GL_POLYGON_OFFSET_FILL );

// Draw the large white cylinder
glPolygonOffset( 2.f, 2.f );
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
glColor3f( 1.f, 1.f, 1.f );
cylBody.draw();

// Draw the cylinder's center stripe
glPolygonOffset( 1.f, 1.f );
glColor3f( .6f, .6f, 1.f );
cylStripe.draw();

// Draw the cylinder in line mode
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glColor3f( 0.f, 0.f, 0.f );
cylBody.draw();

cylBody and cylStripe are instantiations of the Cylinder object defined in the example code. Cylinder::draw() appears in Listing 2-1. The full DepthOffset example source code is available from the book's Web site.

The code either enables or disables depth offset for filled primitives based on a Boolean variable. It draws the white cylinder with glPolygonOffset ( 2.f, 2.f ) to push it back in the depth buffer. The cylinder's bluish stripe is drawn with glPolygonOffset ( 1.f, 1.f ), which also pushes it back, but not as far as the first cylinder, to prevent z-fighting. Finally, the first cylinder draws a second time in line mode. Because depth offset isn't enabled for line mode, it's drawn with no offset.

When drawing 3D scenes with co-planar primitives, applications generally set factor and units to the same value. This ensures that depth offset resolves the co-planarity regardless of the primitive orientation.

2.3.7 Alpha and Transparency

Internally, OpenGL colors have four components: red, green, blue, and alpha. You can specify each of these components with glColor4f ( r, g, b, a ), but even if you specify a color with three components, such as glColor3f ( r, g, b ), OpenGL uses a full-intensity alpha internally.

Applications often store an opacity value in the alpha component, and use the OpenGL blending and alpha test features to render translucent and transparent primitives.

2.3.7.1 Blending

The blending feature combines the incoming (or source) fragment color with the stored (or destination) color in the framebuffer. Commonly used to simulate translucent and transparent surfaces in 3D rendering, blending also has applications in image processing.

This chapter covers simple OpenGL blending. Blending supports many variants that are not covered in this book. For full details on blending, see Section 4.1.8, "Blending," of The OpenGL Graphics System and Chapter 6, "Blending, Antialiasing, Fog, and Polygon Offset," of OpenGL® Programming Guide.

To use blending, your application must enable it and set an appropriate blending function. Enable and disable blending with GL_BLEND. Call glEnable ( GL_BLEND ) to enable blending, for example. Set the blend function with the glBlendFunc () command.


void glBlendFunc( GLenum src, GLenum dst );

Sets blending function parameters that control the combination of stored framebuffer colors with fragment colors. src and dst specify functions that operate on the source and destination colors, respectively. When blending is enabled, OpenGL replaces the fragment color with the sum of the output of these functions.

U25B8.GIF OpenGL version: 1.0 and later.

When simulating translucent surfaces, applications typically call glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ). This multiplies the source fragment color by the source alpha value (typically small to simulate a nearly transparent surface) and multiplies the destination color by 1 minus the source alpha value.

For a complete list of valid src and dst values, see Table 4.2 in The OpenGL Graphics System.

To render translucent surfaces correctly, applications should first render all opaque geometry into the framebuffer. Applications should further sort translucent geometry by distance from the viewer and render it in back-to-front order.

2.3.7.2 Alpha Test

The alpha-test feature discards fragments that have alpha values that fail to pass an application-specified comparison test. Applications use the alpha test to discard partially or completely transparent fragments that, if rendered, would have little or no effect on the color buffer.

To use the alpha test, your application must enable it and specify the comparison test. Enable and disable the alpha test with GL_ALPHA_TEST. Enable it by calling glEnable ( GL_ALPHA_TEST ), for example. To specify the comparison test, use glAlphaFunc ().


void glAlphaFunc( GLenum func, GLclampf ref );

Specifies how the alpha test discards fragments. func specifies a comparison function and may be GL_ALWAYS, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_LEQUAL, GL_LESS, GL_NEVER, or GL_NOTEQUAL. ref specifies a constant floating-point reference value used in the comparison.

U25B8.GIF OpenGL version: 1.0 and later.

Consider setting the following alpha-test state:

glEnable( GL_ALPHA_TEST );
glAlphaFunc( GL_NOTEQUAL, 0.f );

In this case, OpenGL renders fragments from subsequent geometry only if the fragment alpha value isn't equal to zero.

You might also want to discard fragments with an alpha that doesn't exceed a certain threshold. Setting the alpha function to glAlphaFunc ( GL_GREATER, 0.1f ) passes fragments only if their alpha value is greater than 0.1.

  • + Share This
  • 🔖 Save To Your Account

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