Chapter 2 OpenGL programming guide: State management, geometric drawing

Source: Internet
Author: User

1. Drawing Basics

Clear window

Glclearcolor (0.0, 0.0, 0.0, 0.0 );
Glclear (gl_color_buffer_bit );

The first code sets "clear color", and the second code resets the current color buffer to "clear color ".

In addition to the color buffer (color buffer, corresponding pixel color on the screen), the graphic hardware also has other buffers, such as depth, stencer, accumulation, which are used to set the clearing values of these buffers respectively: glcleardepth (), glclearstencel (), glclearaccum (); the command for clearing is also glclear. The parameters are gl_depth_buffer_bit, gl_stencil_buffer_bit, and gl_accum_buffer_bit.

You can, from the perspective of efficiency, try to clear multiple buffers at a time, glclear (gl_color_buffer_bit | gl_depth_buffer_bit ).


Color

In OpenGL, drawing specific geometric elements is independent from the specified color. You should first set the color and then draw the element. Unless this color is set to another value, OpenGL will always use this color to draw the element.

Use the glcolor3f () and glcolor3fv () functions to specify the color.

2. point, line, and polygon

PointRepresented by a vector containing three floating point numbers, also known as vertex (vertex ). OpenGL uses the "homogeneous coordinates", so four floating point numbers (X, Y, Z, W) are used internally ). If W! = 0, equivalent to (x/W, Y/W, Z/W ).

Baidu Encyclopedia "homogeneous coordinates ":

Homogeneous coordinates are represented by an n + 1-dimension vector, which is originally an n-dimensional vector. For example, the homogeneous coordinates of two-dimensional points (x, y) are expressed as (HX, Hy, H ). From this we can see that the homogeneous representation of a vector is not unique, and H of the homogeneous coordinate takes different values to represent the same point, such as the homogeneous coordinate, 2) (, 1) represents two-dimensional points ).

Many graphics applications involve geometric transformations, including translation, rotation, and scaling. When these transformations are calculated using matrix expressions, translation is the addition of matrices, and rotation and scaling are the multiplication of matrices, in combination, it can be expressed as P' = m1 * P + m2 (M1 rotation and scaling matrix, M2 as the translation matrix, P as the original vector, and P' as the transformed vector ). The purpose of introducing homogeneous coordinates is mainly to merge the multiplication and addition methods in matrix operations, which are expressed in the form of p '= m * P. That is, it provides an effective method to transform a point set in a two-dimensional, three-dimensional, or even high-dimensional space from one coordinate system to another using matrix operations.

Second, it can represent infinite vertices. If H = 0 in the homogeneous coordinates of N + 1 dimension, it actually represents an infinite point of distance in the n-dimensional space.

LineDefined by two vertex

PolygonA group of sequentially connected and closed line segments can be defined by an ordered vertex group. OpenGL requires that the polygon be a "simple polygon": the edges of the polygon are not intersecting. The polygon must be a convex polygon. The line segments connected to any two nodes are all inside the polygon.

If the polygon you want to draw does not meet these two conditions, it can always be divided into polygon that meet the conditions.

Because the coordinates are three-dimensional, the polygon of the four vertices cannot ensure that all vertices are in the same plane. In this case, a simple quadrilateral, after rotation, scaling, and projection, it may not be a simple quadrilateral. Therefore, when multiple complex polygon are separated, they are generally divided into triangles.

The curve can be represented in a short segment,SurfaceIt can be represented by a large number of small polygon.


3. Draw Elements

Any geometric element is defined by a set of vertices. OpenGL uses the glvertex * () function to specify vertices.

The code for drawing an element is as follows:
Glbegin (gl_points)
Glvertex * (V1)
Glvertex * (V2)
...
Glend ()

Glbegin (gl_points) indicates that the elements to be drawn are vertices, and glend () indicates that the vertex data of the elements ends. To draw other elements, replace gl_points with gl_lines, gl_line_strip, gl_line_loop, gl_triangles, gl_triangle_strip, gl_triangle_fan, gl_quads, gl_quad_strip,
Gl_polygon.

To specify the vertex color, you only need to call glcolor in glvertex.


4. Basic Status Management

Glcolor * specifies the color, which is an OpenGL state. The final rendering effect of an element is affected by many States: texture, illumination, fog, etc. By default, many States are closed. gldisable (glenum
You can use glisenabled (glenum capability) to check whether the status is activated.

Some Status values are more complex than (true/false) values. You can use the following function to query them by setting special functions.

Void glgetbooleanv (glenum pname, glboolean * Params );
Void glgetintegerv (glenum pname, glint * Params );
Void glgetfloatv (glenum pname, glfloat * Params );
Void glgetdoublev( glenum pname, gldouble * Params );
Void glgetpointerv (glenum pname, glvoid ** Params );
For example, if glcolor3f sets the color, glgetfloatv (gl_current_color, Param) can be queried.


5. primitive style

Point:Glpointsize (glfloat size) is used to set the vertex size. OpenGL restricts the vertex size range and can be queried through related APIs.

Line:Gllinewidth (glfloat width) sets the line width, and its range is also limited. Line can also be characterized in a certain mode. The gllinestipple (gl_line_stipple) enables the characterization function. gllinestipple (glint factor, glushort pattern) sets the characterization mode. The second parameter is a 16-bit short, used as a single bit sequence. 1 indicates that the current pixel needs to be characterized, and 0 indicates that it is skipped. The first parameter is an extension factor, and each bit of pattern is extended by factor.

Polygon:The polygon has two sides: front and back. The two sides can be drawn in different modes. Glpolygonmode (glenum face, glenum mode), face can be gl_front_and_back, gl_front; mode can be gl_point, gl_line, or gl_fill.

Generally, if the vertices of a polygon are displayed in the clockwise direction, the polygon is oriented to the front. The "dable manifold" solid (the inverse example is the Klein bottle and the Mobius band) can be constructed through consistent multi-deformation. In mathematics, the orientation of multiple variants can be calculated by the following formula: a> 0, the front-face; otherwise, the back-face


Multi-deformation can also be characterized by a 32-bit * 32-bit pattern. First, call glable (gl_polygon_stipple) and then call glpolygonstipple (const glubyte * mask ).

If you divide a non-Simple Polygon into n simple polygon for plotting, you need to hide an edge of some polygon, gledgeflag *() command to hide the edges starting from the subsequent vertex.

Normal: The normal is a vector perpendicular to the surface. For the plane, the normal direction of all points is the same. For the surface, the normal direction of each point may be different. In OpenGL, only the normal of each vertex can be set, just like the color. For an object, the normal determines the direction of Space everywhere on the surface, which is very important for rendering the "illumination" effect. Set the normal to use the glnormal * function *.

For the point on the opposite side, there are two vectors perpendicular to the plane. Generally, the normal is the vector pointing to the outside. Therefore, if you want to reverse "external" and "internal", you only need to convert the normal (x, y, z) to (-X,-y,-Z.

The normal is used to indicate the direction, and its length is irrelevant, so it will eventually be normalized (normalized): The length is 1.


6. vertex Array

Using glvertex * to specify vertices requires a lot of function calls to draw elements. The vertex array can change this situation. Using the vertex array requires three steps:

Activate vertex array:The glableclientstate (glenum array) parameter array is the array to be activated. Possible parameter values include gl_vertex_array, gl_color_array, gl_secondary_color_array, gl_index_array, gl_normal_array, gl_fog_coord_array,
Gl_texture_coord_array, gl_edge_flag_array.
This function name implies that the vertex array is actually stored on the client side. Gldisableclientstate (glenum array) can close the corresponding array.

Note: The vertex array is interpreted as an array of vertex-related data, including coordinates, colors, and normal. The preceding parameters indicate the specific array type..

Assign values to Arrays: Each array has a value assignment function. vertex is used as an example:
Glvertexpointer (glint size, glenum type, glsizei stride, const glvoid * pointer)
Pointer -- data memory address
Type -- Data Element type, gl_short, gl_int, gl_float, gl_double
Size -- number of vertices, which are 2, 3, and 4
Stride -- the offset between consecutive vertex arrays. If it is zero, it means that vertex data is closely arranged.
For other array assignment functions, see the original book or OpenGL document.

Use Arrays:Glarrayelement (glint ith) uses the vertex array data at the specified position. It also uses the corresponding location data of all activated Arrays: color, normal, vertex coordinate; gldrawelements (glenum mode, glsizei count, glenum type, const glvoid * indices) uses an index array to draw elements using the vertex array. mode is used to specify the elements. Count is the number of vertices, and type is the element type of the index array, indice is the first address of the index array; gldrawarrays (glenum
Mode, glint first, glsizei count) from the array first position, use count vertices to draw the metamode.


7. Buffer Object Buffer object

Buffer object can be used to avoid frequent data transmission between memory and video cards. Compared with vertex arrays, buffer objects can store more data types.

Create Bo: Glgenbuffers (glsizei N, gluint * buffers) allocates n Bo IDs and stores them in the buffer. Glisbuffer (gluint
Buffer) can be used to query whether a certain ID is a valid Bo ID; gldeletebuffers can delete Bo, and Recycle resources include Bo ID.

Activate Bo: Glbindbuffer (glenum target, gluint buffer), buffer is Bo ID, target is used, such as gl_array_buffer,
Gl_element_array_buffer. If the buffer parameter is 0, it indicates that Bo is not used.

Initialize BO:Glbufferdata (glenum target, glsizeiptr size, const glvoid * data, glenum
Usage) can allocate space for Bo and initialize data. usage is the purpose of Bo and serves only as a prompt for OpenGL to optimize performance.

Update Data:Glbuffersubdata (glenum target, glintptr offset, glsizeiptr size, const
Glvoid * Data) Updates part of Bo data;
Glvoid * glmapbuffer (glenum target, glenum access) maps Bo to a local memory address. After the access, you need to call glunmapbuffer (glenum target) to end the access; glmapbufferrange provides more precise map functions.

Copy data between Bo: Glcopybuffersubdata (glenum readbuffer, glenum writebuffer, glintptr
Readoffset, glintptr writeoffset, glsizeiptr size) can be directly copied between Bo.

Use the vertex array BO:Bind Bo to gl_array_buffer,Initialize the data and then use the vertex array in the previous section. The only difference is glvertexpointer. The last parameter of glcolorpointer is the Bo offset value.

Note: gl_array_buffer indicates the data Array Buffer. If this type of Bo is activated, all operations that originally retrieve data from the local data array will point to Bo.

Vertex-array object:For complex programs, switching between multiple data arrays may be required. operations such as glvertexpointer () are very frequent. The vertex-array object combines vertex Data Binding operations to simplify operations. For more information, see the original document.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.