Home>Articles>Programming>Graphic Programming

Drawing with OpenGL

This chapter is from the book

OpenGL Drawing Commands

大多数OpenGL绘制命令从单词开始Draw.7The drawing commands are roughly broken into two subsets—indexed and nonindexed draws. Indexed draws use an array of indices stored in a buffer object bound to the GL_ELEMENT_ARRAY_BUFFER binding that is used to indirectly index into the enabled vertex arrays. On the other hand, nonindexed draws do not use the GL_ELEMENT_ARRAY_BUFFER at all, and simply read the vertex data sequentially. The most basic, nonindexed drawing command in OpenGL isglDrawArrays().

Similarly, the most basicindexeddrawing command isglDrawElements().

Each of these functions causes vertices to be read from the enabled vertex-attribute arrays and used to construct primitives of the type specified bymode. Vertex-attribute arrays are enabled usingglEnableVertexAttribArray()as described in Chapter 1.glDrawArrays()just uses the vertices in the buffer objects associated with the enabled vertex attributes in the order they appear.glDrawElements()uses the indices in the element array buffer to index into the vertex attribute arrays. Each of the more complex OpenGL drawing functions essentially builds functionality on top of these two functions. For example,glDrawElementsBaseVertex()allows the indices in the element array buffer to be offset by a fixed amount.

glDrawElementsBaseVertex()allows the indices in the element array buffer to be interpreted relative to some base index. For example, multiple versions of a model (say, frames of an animation) can be stored in a single set of vertex buffers at different offsets within the buffer.glDrawElementsBaseVertex()可以用来画框架,animati吗on by simply specifying the first index that corresponds to that frame. The same set of indices can be used to reference every frame.

Another command that behaves similarly toglDrawElements()isglDrawRangeElements().

Various combinations of functionality are available through even more advanced commands—for example,glDrawRangeElementsBaseVertex()combines the features ofglDrawElementsBaseVertex()with the contractual arrangement ofglDrawRangeElements().

Instancedversions of both of these functions are also available. Instancing will be covered in “Instanced Rendering” on Page 128. The instancing commands includeglDrawArraysInstanced(),glDrawElementsInstanced(), and evenglDrawElementsInstancedBaseVertex(). Finally, there are two commands that take their parameters not from your program directly, but from abuffer object. These are the draw-indirect functions, and to use them, a buffer object must be bound to the GL_DRAW_INDIRECT_BUFFER binding. The first is the indirect version ofglDrawArrays(),glDrawArraysIndirect().

InglDrawArraysIndirect(), the parameters for the actual draw command are taken from a structure stored at offsetindirectinto thedraw indirectbuffer. The structure’s declaration in “C” is presented in Example 3.3:

Example 3.3. Declaration of the DrawArraysIndirectCommand Structure

typedef structDrawArraysIndirectCommand_t { GLuint count; GLuint primCount; GLuint first; GLuint baseInstance; } DrawArraysIndirectCommand;

The fields of theDrawArraysIndirectCommandstructure are interpreted as if they were parameters to a call toglDrawArraysInstanced().firstandare passed directly to the internal function. TheprimCountfield is the instance count, and thebaseInstancefield becomes thebaseInstanceoffset to any instanced vertex attributes (don’t worry, the instanced rendering commands will be described shortly).

The indirect version ofglDrawElements()isglDrawElementsIndirect()and its prototype is as follows:

As withglDrawArraysIndirect(), the parameters for the draw command inglDrawElementsIndirect()come from a structure stored at offsetindirectstored in the element array buffer. The structure’s declaration in “C” is presented in Example 3.4:

Example 3.4. Declaration of the DrawElementsIndirectCommand Structure

typedef structDrawElementsIndirectCommand_t { GLuint count; GLuint primCount; GLuint firstIndex; GLuint baseVertex; GLuint baseInstance; } DrawElementsIndirectCommand;

As with theDrawArraysIndirectCommandstructure, the fields of theDrawElementsIndirectCommandstructure are also interpreted as calls to theglDrawElementsInstancedBaseVertex()command.andbaseVertexare passed directly to the internal function. As inglDrawArraysIndirect(),primCountis the instance count.firstVertexis used, along with the size of the indices implied by thetypeparameter to calculate the value ofindicesthat would have been passed toglDrawElementsInstancedBaseVertex(). Again,baseInstancebecomes the instance offset to any instanced vertex attributes used by the resulting drawing commands.

Now, we come to the drawing commands that do not start withDraw. These are the multivariants of the drawing commands,glMultiDrawArrays(),glMultiDrawElements(), andglMultiDrawElementsBaseVertex(). Each one takes an array offirstparameters, and an array ofparameters acts as if the nonmultiversion of the function had been called once for each element of the array. For example, look at the prototype forglMultiDrawArrays().

CallingglMultiDrawArrays()is equivalent to the following OpenGL code sequence:

voidglMultiDrawArrays(GLenum mode,constGLint * first,constGLint * count, GLsizei primcount) { GLsizei i;for(i = 0; i < primcount; i++) { glDrawArrays(mode, first[i], count[i]); } }

Similarly, the multiversion ofglDrawElements()isglMultiDrawElements(), and its prototype is as follows:

CallingglMultiDrawElements()is equivalent to the following OpenGL code sequence:

voidglMultiDrawElements(GLenum mode,constGLsizei * count, GLenum type,constGLvoid *const* indices, GLsizei primcount); { GLsizei i;for(i = 0; i < primcount; i++) { glDrawElements(mode, count[i], type, indices[i]); } }

An extension ofglMultiDrawElements()to include abaseVertexparameter isglMultiDrawElementsBaseVertex(). Its prototype is as follows:

As with the previously described OpenGL multidrawing commands,glMultiDrawElementsBaseVertex()is equivalent to another code sequence that ends up calling the nonmultiversion of the function.

voidglMultiDrawElementsBaseVertex(GLenum mode,constGLsizei * count, GLenum type,constGLvoid *const* indices, GLsizei primcount,const\GLint * baseVertex); { GLsizei i;for(i = 0; i < primcount; i++) { glDrawElements(mode, count[i], type, indices[i], baseVertex[i]); } }

Finally, if you have a large number of draws to perform and the parameters are already in a buffer object suitable for use byglDrawArraysIndirect()orglDrawElementsIndirect(), it is possible to use themultiversions of these two functions,glMultiDrawArraysIndirect()andglMultiDrawElementsIndirect().

OpenGL Drawing Exercises

This is a relatively simple example of using a few of the OpenGL drawing commands covered so far in this chapter. Example 3.5 shows how the data is loaded into the buffers required to use the draw commands in the example. Example 3.6 shows how the drawing commands are called.

Example 3.5. Setting up for the Drawing Command Example

// A four verticesstatic constGLfloat vertex_positions[] = { -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, }; // Color for each vertexstatic constGLfloat vertex_colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f }; // Three indices (we’re going to draw one triangle at a timestatic constGLushort vertex_indices[] = { 0, 1, 2 }; // Set up the element array buffer glGenBuffers(1, ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(vertex_indices), vertex_indices, GL_STATIC_DRAW); // Set up the vertex attributes glGenVertexArrays(1, vao); glBindVertexArray(vao[0]); glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER,sizeof(vertex_positions) +sizeof(vertex_colors), NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0,sizeof(vertex_positions), vertex_positions); glBufferSubData(GL_ARRAY_BUFFER,sizeof(vertex_positions),sizeof(vertex_colors), vertex_colors);

Example 3.6. Drawing Commands Example

// DrawArrays model_matrix = vmath::translation(-3.0f, 0.0f, -5.0f); glUniformMatrix4fv(render_model_matrix_loc, 4, GL_FALSE, model_matrix); glDrawArrays(GL_TRIANGLES, 0, 3); // DrawElements model_matrix = vmath::translation(-1.0f, 0.0f, -5.0f); glUniformMatrix4fv(render_model_matrix_loc, 4, GL_FALSE, model_matrix); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, NULL); // DrawElementsBaseVertex model_matrix = vmath::translation(1.0f, 0.0f, -5.0f); glUniformMatrix4fv(render_model_matrix_loc, 4, GL_FALSE, model_matrix); glDrawElementsBaseVertex(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, NULL, 1); // DrawArraysInstanced model_matrix = vmath::translation(3.0f, 0.0f, -5.0f); glUniformMatrix4fv(render_model_matrix_loc, 4, GL_FALSE, model_matrix); glDrawArraysInstanced(GL_TRIANGLES, 0, 3, 1);

The result of the program in Examples 3.5 and 3.6 is shown inFigure 3.5. It’s not terribly exciting, but you can see four similar triangles, each rendered using a different drawing command.

Figure 3.5

Figure 3.5. Simple example of drawing commands

Restarting Primitives

As you start working with larger sets of vertex data, you are likely to find that you need to make numerous calls to the OpenGL drawing routines, usually rendering the same type of primitive (such as GL_TRIANGLE_STRIP) that you used in the previous drawing call. Of course, you can use the glMultiDraw*() routines, but they require the overhead of maintaining the arrays for the starting index and length of each primitive.

OpenGL has the ability to restart primitives within the same drawing command by specifying a special value, theprimitive restart index, which is specially processed by OpenGL. When the primitive restart index is encountered in a draw call, a new rendering primitive of the same type is started with the vertex following the index. The primitive restart index is specified by theglPrimitiveRestartIndex()function.

As vertices are rendered with one of theglDrawElements()derived function calls, it can watch for the index specified byglPrimitiveRestartIndex()to appear in the element array buffer. However, it watches only for this index to appear if primitive restating is enabled. Primitive restarting is controlled by callingglEnable()orglDisable()with the GL_PRIMITIVE_RESTART parameter.

To illustrate, consider the layout of vertices inFigure 3.6, which shows how a triangle strip would be broken in two by using primitive restarting. In this figure, the primitive restart index has been set to 8. As the triangles are rendered, OpenGL watches for the index 8 to be read from the element array buffer, and when it sees it go by, rather than creating a vertex, it ends the current triangle strip. The next vertex (vertex 9) becomes the first vertex of a new triangle strip, and so in this case two triangle strips are created.

Figure 3.6

Figure 3.6. Using primitive restart to break a triangle strip

The following example demonstrates a simple use of primitive restart—it draws a cube as a pair of triangle strips separated by a primitive restart index. Examples 3.7 and 3.8 demonstrate how the data for the cube is specified and then drawn.

Example 3.7. Intializing Data for a Cube Made of Two Triangle Strips

// 8 corners of a cube, side length 2, centered on the originstatic constGLfloat cube_positions[] = { -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; // Color for each vertexstatic constGLfloat cube_colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f }; // Indices for the triangle stripsstatic constGLushort cube_indices[] = { 0, 1, 2, 3, 6, 7, 4, 5, // First strip 0xFFFF, // <<-- This is the restart index 2, 6, 0, 4, 1, 5, 3, 7 // Second strip }; // Set up the element array buffer glGenBuffers(1, ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(cube_indices), cube_indices, GL_STATIC_DRAW); // Set up the vertex attributes glGenVertexArrays(1, vao); glBindVertexArray(vao[0]); glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER,sizeof(cube_positions) +sizeof(cube_colors), NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0,sizeof(cube_positions), cube_positions); glBufferSubData(GL_ARRAY_BUFFER,sizeof(cube_positions),sizeof(cube_colors), cube_colors); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (constGLvoid *)sizeof(cube_positions)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1);

Figure 3.7shows how the vertex data given in Example 3.7 represents the cube as two independent triangle strips.

Figure 3.7

Figure 3.7. Two triangle strips forming a cube

Example 3.8. Drawing a Cube Made of Two Triangle Strips Using Primitive Restart

// Set up for a glDrawElements call glBindVertexArray(vao[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[0]);#ifUSE_PRIMITIVE_RESTART // When primitive restart is on, we can call one draw command glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(0xFFFF); glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL);#else// Without primitive restart, we need to call two draw commands glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, NULL); glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, (constGLvoid *)(9 *sizeof(GLushort))); #endif

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, simplyemailinformation@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

我们定期与用户沟通公关ovide 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 ourContact 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.

皮尔森可能会提供个人信息结合起来d 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 theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand 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.e-skidka.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 toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains 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
  • 有关销售、合资企业或另外一些er 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


Pleasecontact usabout 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