Sunday, May 1, 2016

Buffer Objects

[State]
    To Be Continued...
[Concept]
    Buffer Objects

[URL]
    http://www.informit.com/articles/article.aspx?p=1377833&seqNum=7

    [Contents]

There are many operations in OpenGL where you send a large block of data to OpenGL, such as passing vertex array data for processing. Transferring that data may be as simple as copying from your system’s memory down to your graphics card. However, because OpenGL was designed as a client-server model, any time that OpenGL needs data, it will have to be transferred from the client’s memory. If that data doesn’t change, or if the client and server reside on different computers (distributed rendering), that data transfer may be slow, or redundant. 
Buffer objects were added to OpenGL Version 1.5 to allow an application to explicitly specify which data it would like to be stored in the graphics server.
          //----------
Many different types of buffer objects are used in the current versions of OpenGL:
  • Vertex data in arrays can be stored in server-side buffer objects starting with OpenGL Version 1.5. They are described in “Using Buffer Objects with Vertex-Array Data” on page 102 of this chapter. 
  • Support for storing pixel data, such as texture maps or blocks of pixels, in buffer objects was added into OpenGL Version 2.1 It is described in “Using Buffer Objects with Pixel Rectangle Data” in Chapter 8. 
  • Version 3.1 added uniform buffer objects for storing blocks of uniform-variable data for use with shaders.
You will find many other features in OpenGL that use the term “objects,” but not all apply to storing blocks of data. For example, texture objects (introduced in OpenGL Version 1.1) merely encapsulate various state settings associated with texture maps (See “Texture Objects” on page 437). Likewise, vertex-array objects, added in Version 3.0, encapsulate the state parameters associated with using vertex arrays. These types of objects allow you to alter numerous state settings with many fewer function calls. For maximum performance, you should try to use them whenever possible, once you’re comfortable with their operation.
An object is referred to by its name, which is an unsigned integer identifier. Starting with Version 3.1, all names must be generated by OpenGL using one of the glGen*() routines; user-defined names are no longer accepted.
          //----------

Creating Buffer Objects

In OpenGL Version 3.0, any nonzero unsigned integer may used as a buffer object identifier. You may either arbitrarily select representative values or let OpenGL allocate and manage those identifiers for you. Why the difference? By having OpenGL allocate identifiers, you are guaranteed to avoid an already used buffer object identifier. This helps to eliminate the risk of modifying data unintentionally. In fact, OpenGL Version 3.1 requires that all object identifiers be generated, disallowing user-defined names.

Making a Buffer Object Active

To make a buffer object active, it needs to be bound. Binding selects which buffer object future operations will affect, either for initializing data or using that buffer for rendering. That is, if you have more than one buffer object in your application, you’ll likely call glBindBuffer() multiple times: once to initialize the object and its data, and then subsequent times either to select that object for use in rendering or to update its data.

Allocating and Initializing Buffer Objects with Data

Once you’ve bound a buffer object, you need to reserve space for storing your data. This is done by calling glBufferData().
void glBufferData(GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
Allocates size storage units (usually bytes) of OpenGL server memory for storing vertex array data or indices. Any previous data associated with the currently bound object will be deleted.
  • target may be either GL_ARRAY_BUFFER for vertex data; GL_ELEMENT_ARRAY_BUFFER for index data; GL_PIXEL_UNPACK_BUFFER for pixel data being passed into OpenGL; GL_PIXEL_PACK_BUFFER for pixel data being retrieved from OpenGL; GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER for data copied between buffers; GL_TEXTURE_BUFFER for texture data stored as a texture buffer; GL_TRANSFORM_FEEDBACK_BUFFER for results from executing a transform feedback shader; or GL_UNIFORM_BUFFER for uniform variable values. 
  • size is the amount of storage required for storing the respective data. This value is generally number of elements in the data multiplied by their respective storage size. 
  • data is either a pointer to a client memory that is used to initialize the buffer object or NULL. If a valid pointer is passed, size units of storage are copied from the client to the server. If NULL is passed, size units of storage are reserved for use, but are left uninitialized. 
  • usage provides a hint as to how the data will be read and written after allocation. Valid values are GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, GL_DYNAMIC_COPY.
glBufferData() will generate a GL_OUT_OF_MEMORY error if the requested size exceeds what the server is able to allocate. It will generate a GL_INVALID_VALUE error if usage is not one of the permitted values. 

Updating Data Values in Buffer Objects

There are two methods for updating data stored in a buffer object. 
The first method assumes that you have data of the same type prepared in a buffer in your application. glBufferSubData() will replace some subset of the data in the bound buffer object with the data you provide.
void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
Update size bytes starting at offset (also measured in bytes) in the currently bound buffer object associated with target using the data pointed to by data. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_PIXEL_PACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER.
glBufferSubData() will generate a GL_INVALID_VALUE error if size is less than zero or if size + offset is greater than the original size specified when the buffer object was created.
The second method allows you more control over which data values are updated in the buffer.glMapBuffer() and glMapBufferRange() return a pointer to the buffer object memory, into which you can write new values (or simply read the data, depending on your choice of memory access permissions), just as if you were assigning values to an array. When you’ve completed updating the values in the buffer, you call glUnmapBuffer() to signify that you’ve completed updating the data.

Copying Data Between Buffer Objects

On some occasions, you may need to copy data from one buffer object to another. In versions of OpenGL prior to Version 3.1, this would be a two-step process:
  1. Copy the data from the buffer object into memory in your application. You would do this either by mapping the buffer and copying it into a local memory buffer, or by callingglGetBufferSubData() to copy the data from the server.
  2. Update the data in another buffer object by binding to the new object and then sending the new data using glBufferData() (or glBufferSubData() if you’re replacing only a subset). Alternatively, you could map the buffer, and then copy the data from a local memory buffer into the mapped buffer.
In OpenGL Version 3.1, the glCopyBufferSubData() command copies data without forcing it to make a temporary stop in your application’s memory.

Cleaning Up Buffer Objects

When you’re finished with a buffer object, you can release its resources and make its identifier available by calling glDeleteBuffers(). Any bindings to currently bound objects that are deleted are reset to zero.

Using Buffer Objects with Vertex-Array Data

To store your vertex-array data in buffer objects, you will need to add a few steps to your application. 
  1. (Optional) Generate buffer object identifiers. 
  2. Bind a buffer object, specifying that it will be used for either storing vertex data or indices. 
  3. Request storage for your data, and optionally initialize those data elements. 
  4. Specify offsets relative to the start of the buffer object to initialize the vertex-array functions, such as glVertexPointer(). 
  5. Bind the appropriate buffer object to be utilized in rendering. 
  6. Render using an appropriate vertex-array rendering function, such as glDrawArrays() orglDrawElements(). 
If you need to initialize multiple buffer objects, you will repeat steps 2 through 4 for each buffer object. 
Both “formats” of vertex-array data are available for use in buffer objects. As described in “Step 2: Specifying Data for the Arrays,” vertex, color, lighting normal, or any other type of associated vertex data can be stored in a buffer object. Additionally, interleaved vertex array data, as described in “Interleaved Arrays,” can also be stored in a buffer object. In either case, you would create a single buffer object to hold all of the data to be used as vertex arrays. 
As compared to specifying a memory address in the client’s memory where OpenGL should access the vertex-array data, you specify the offset in machine units (usually bytes) to the data in the buffer. To help illustrate computing the offset, and to frustrate the purists in the audience, we’ll use the following macro to simplify expressing the offset: 
#define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes))
[ *** ]
...

[ Making a Buffer Object Active ]

...
To make a buffer object active, it needs to be bound. Binding selects which buffer object future operations will affect, either for initializing data or using that buffer for rendering. That is, if you have more than one buffer object in your application, you’ll likely call glBindBuffer() multiple times: once to initialize the object and its data, and then subsequent times either to select that object for use in rendering or to update its data.
To disable use of buffer objects, call glBindBuffer() with zero as the buffer identifier. This switches OpenGL to the default mode of not using buffer objects.

void glBindBuffer(GLenum target, GLuint buffer);
Specifies the current active buffer object. target must be set to one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. buffer specifies the buffer object to be bound to. 
glBindBuffer() does three things: 
  1. When using buffer of an unsigned integer other than zero for the first time, a new buffer object is created and assigned that name.
  2. When binding to a previously created buffer object, that buffer object becomes the active buffer object.
  3. When binding to a buffer value of zero, OpenGL stops using buffer objects.
...

[ Allocating and Initializing Buffer Object with Data ]

...
Once you’ve bound a buffer object, you need to reserve space for storing your data. This is done by calling glBufferData().
void glBufferData(GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage); 
Allocates size storage units (usually bytes) of OpenGL server memory for storing vertex array data or indices. Any previous data associated with the currently bound object will be deleted. 
target may be either GL_ARRAY_BUFFER for vertex data; GL_ELEMENT_ARRAY_BUFFER for index data; GL_PIXEL_UNPACK_BUFFER for pixel data being passed into OpenGL; GL_PIXEL_PACK_BUFFER for pixel data being retrieved from OpenGL; GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER for data copied between buffers; GL_TEXTURE_BUFFER for texture data stored as a texture buffer; GL_TRANSFORM_FEEDBACK_BUFFER for results from executing a transform feedback shader; or GL_UNIFORM_BUFFER for uniform variable values. 
size is the amount of storage required for storing the respective data. This value is generally number of elements in the data multiplied by their respective storage size. 
data is either a pointer to a client memory that is used to initialize the buffer object or NULL. If a valid pointer is passed, size units of storage are copied from the client to the server. If NULL is passed, size units of storage are reserved for use, but are left uninitialized. 
usage provides a hint as to how the data will be read and written after allocation. Valid values are GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, GL_DYNAMIC_COPY. 
glBufferData() will generate a GL_OUT_OF_MEMORY error if the requested size exceeds what the server is able to allocate. It will generate a GL_INVALID_VALUE error if usage is not one of the permitted values.
glBufferData() first allocates memory in the OpenGL server for storing your data. If you request too much memory, a GL_OUT_OF_MEMORY error will be set. Once the storage has been reserved, and if the data parameter is not NULL, size units of storage (usually bytes) are copied from the client’s memory into the buffer object. However, if you need to dynamically load the data at some point after the buffer is created, pass NULL in for the data pointer. This will reserve the appropriate storage for your data, but leave it uninitialized. 
The final parameter to glBufferData(), usage, is a performance hint to OpenGL. Based upon the value you specify for usage, OpenGL may be able to optimize the data for better performance, or it can choose to ignore the hint. There are three operations that can be done to buffer object data: 
  1. Drawing—the client specifies data that is used for rendering.
  2. Reading—data values are read from an OpenGL buffer (such as the framebuffer) and used in the application in various computations not immediately related to rendering.
  3. Copying—data values are read from an OpenGL buffer and then used as data for rendering. 
Additionally, depending upon how often you intend to update the data, there are various operational hints for describing how often the data will be read or used in rendering: 
  1. Stream mode—you specify the data once, and use it only a few times in drawing or other operations.
  2. Static mode—you specify the data once, but use the values often.
  3. Dynamic mode—you may update the data often and use the data values in the buffer object many times as well.
...
[ *** ]

[ Updating Data Values in Buffer Objects ]

...
There are two methods for updating data stored in a buffer object: glBufferSubData() and glMapBufferRange()
The first method assumes that you have data of the same type prepared in a buffer in your application. glBufferSubData() will replace some subset of the data in the bound buffer object with the data you provide.

void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); 
Update size bytes starting at offset (also measured in bytes) in the currently bound buffer object associated with target using the data pointed to by data. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_PIXEL_PACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. 
glBufferSubData() will generate a GL_INVALID_VALUE error if size is less than zero or if size + offset is greater than the original size specified when the buffer object was created. 
The second method allows you more control over which data values are updated in the buffer.glMapBuffer() and glMapBufferRange() return a pointer to the buffer object memory, into which you can write new values (or simply read the data, depending on your choice of memory access permissions), just as if you were assigning values to an array. When you’ve completed updating the values in the buffer, you call glUnmapBuffer() to signify that you’ve completed updating the data. 
glMapBuffer() provides access to the entire set of data contained in the buffer object. This approach is useful if you need to modify much of the data in buffer, but may be inefficient if you have a large buffer and need to update only a small portion of the values.

GLvoid *glMapBuffer(GLenum target, GLenum access); 
Returns a pointer to the data storage for the currently bound buffer object associated with target, which must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. access must be either GL_READ_ONLY, GL_WRITE_ONLY, or GL_READ_WRITE, indicating the operations that a client may do on the data. 
glMapBuffer() will return NULL either if the buffer cannot be mapped (setting the OpenGL error state to GL_OUT_OF_MEMORY) or if the buffer was already mapped previously (where the OpenGL error state will be set to GL_INVALID_OPERATION). 
When you’ve completed accessing the storage, you can unmap the buffer by calling glUnmapBuffer().
GLboolean glUnmapBuffer(GLenum target); 
Indicates that updates to the currently bound buffer object are complete, and the buffer may be released. target must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. 
As a simple example of how you might selectively update elements of your data, we’ll use glMapBuffer() to obtain a pointer to the data in a buffer object containing three-dimensional positional coordinates, and then update only the z-coordinates. 
          GLfloat* data;
data = (GLfloat*) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);
if (data != (GLfloat*) NULL) {
    for( i = 0; i < 8; ++i ) {
        data[3*i+2] *= 2.0; /* Modify Z values */
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);
} else {
    /* Handle not being able to update data */
}
If you need to update only a relatively small number of values in the buffer (as compared to its total size), or small contiguous ranges of values in a very large buffer object, it may be more efficient to use glMapBufferRange(). It allows you to map only the range of data values you need.
GLvoid *glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
Returns a pointer into the data storage for the currently bound buffer object associated with target, which must be one of GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. offset and length specify the range to be mapped. access is a bitmask composed of GL_MAP_READ_BIT, GL_MAP_WRITE_BIT, which indicate the operations that a client may do on the data, and optionally GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT, GL_MAP_FLUSH_EXPLICIT_BIT, or GL_MAP_UNSYNCHRONIZED_BIT, which provide hints on how OpenGL should manage the data in the buffer. 
glMapBufferRange() will return NULL if an error occurs. GL_INVALID_VALUE is generated ifoffset or length are negative, or offset+length is greater than the buffer size. GL_OUT_OF_MEMORY error is generated if adequate memory cannot be obtained to map the buffer. GL_INVALID_OPERATION is generated if any of the following occur: The buffer is already mapped; access does not have either GL_MAP_READ_BIT or GL_MAP_WRITE_BIT set; accesshas GL_MAP_READ_BIT set and any of GL_MAP_INVALIDATE_RANGE_BIT, GL_MAP_INVALIDATE_BUFFER_BIT, or GL_MAP_UNSYNCHRONIZED_BIT is also set; or both GL_MAP_WRITE_BIT and GL_MAP_FLUSH_EXPLICIT_BIT are set in access. 
Using glMapBufferRange(), you can specify optional hints by setting additional bits within access.These flags describe how the OpenGL server needs to preserve data that was originally in the buffer before you mapped it. The hints are meant to aid the OpenGL implementation in determining which data values it needs to retain, or for how long, to keep any internal copies of the data correct and consistent. 
As described in Table 2-7, specifying GL_MAP_FLUSH_EXPLICIT_BIT in the access flags when mapping a buffer region with glMapBufferRange() requires ranges modified within the mapped buffer to be indicated to the OpenGL by a call to glFlushMappedBufferRange()
GLvoid glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length);
Signal that values within a mapped buffer range have been modified, which may cause the OpenGL server to update cached copies of the buffer object. target must be one of the following: GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER, GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, GL_TRANSFORM_FEEDBACK_BUFFER, or GL_UNIFORM_BUFFER. offset and length specify the range of the mapped buffer region, relative to the beginning of the mapped range of the buffer. 
A GL_INVALID_VALUE error is generated if offset or length is negative or if offset+length is greater than the size of the mapped region. A GL_INVALID_OPERATION error is generated if there is no buffer bound to target (i.e., zero was specified as the buffer to be bound in a call to glBindBuffer() for target), or if the buffer bound to target is not mapped, or if it is mapped without having set the GL_MAP_FLUSH_EXPLICIT_BIT.
...

[ Cleaning Up Buffer Objecs ]

...
When you’re finished with a buffer object, you can release its resources and make its identifier available by calling glDeleteBuffers(). Any bindings to currently bound objects that are deleted are reset to zero.
void glDeleteBuffers(GLsizei n, const GLuint *buffers);

Deletes n buffer objects, named by elements in the array buffers. The freed buffer objects may now be reused (for example, by glGenBuffers()).

If a buffer object is deleted while bound, all bindings to that object are reset to the default buffer object, as if glBindBuffer() had been called with zero as the specified buffer object. Attempts to delete nonexistent buffer objects or the buffer object named zero are ignored without generating an error.
...
[ *** ]
[  ]
...

...



No comments:

Post a Comment