Monday, May 30, 2016

Stencil.Buffer

State
Cited Tutorial
http://www.learnopengl.com/#!Advanced-OpenGL/Stencil-testing

Pipeline

Once the fragment shader has processed the fragment a so called stencil test is executed that, just like the depth test, has the possibility of discarding fragments. Then the remaining fragments get passed to the depth test that could possibly discard even more fragments. The stencil test is based on the content of yet another buffer called the stencil buffer that we're allowed to update during rendering to achieve interesting effects.

Stencil-Test

A stencil buffer (usually) contains 8 bits per stencil value that amounts to a total of 256 different stencil values per pixel/fragment. We can then set these stencil values to values of our liking and then we can discard or keep fragments whenever a particular fragment has a certain stencil value.
A simple example of a stencil buffer is shown below:

The stencil buffer is first cleared with zeros and then an open rectangle of 1s is set in the stencil buffer. The fragments of the scene are then only rendered (the others are discarded) wherever the stencil value of that fragment contains a 1. 
Stencil buffer operations allow us to set the stencil buffer at specific values wherever we're rendering fragments. By changing the content of the stencil buffer while we're rendering, we're writing to the stencil buffer. In the same (or following) render iteration(s) we can then read these values to discard or pass certain fragments. When using stencil buffers you can get as crazy as you like, but the general outline is usually as follows:
  • Enable writing to the stencil buffer.
  • Render objects, updating the content of the stencil buffer.
  • Disable writing to the stencil buffer.
  • Render (other) objects, this time discarding certain fragments based on the content of the stencil buffer.
By using the stencil buffer we can thus discard certain fragments based on the fragments of other drawn objects in the scene.

[]
.......................

Define: Depth Buffer .. z- buffer

Depth-buffer

The depth-buffer is a buffer, a kind of logical buffer of Framebuffer. The depth-buffer is a buffer, just like the COLOR-BUFFER (that stores all the fragment-colors: the visual output), stores information per fragment and (usually) has the same width and height as the COLOR-BUFFER. The Depth-Buffer is automatically created by the windowing system and stores its depth values as 16,24 or 32 bit floats. In most systems you'll see a depth buffer with a precision of 24-bits-floats...When the depth-testing is enabled OpenGL tests the depth value of a fragment against the content of the depth buffer. 
OpenGL performs a depth test.If this test passes, the depth buffer is updated with the new depth valueIf the depth test fails, the fragment is discarded.
Depth testing is done in screen space after the fragment shader has run (and after stencil testing has run which we'll discuss in the next tutorial). 
The screen space coordinates relate directly to the viewport defined by OpenGL's glViewport function and can be accessed via GLSL's built-in gl_FragCoord variable in the fragment shader.  
The x and y components of gl_FragCoord represent the fragment's screen-space coordinates (with (0,0) being the bottom-left corner).  
The gl_FragCoord also contains a z-component which contains the actual depth value of the fragment. This z-component, i.e. z value, is the value that is compared to the depth buffer's content.


[]
..................


Sunday, May 29, 2016

framebuffer_object.specs

Cited Official
https://www.opengl.org/registry/specs/EXT/framebuffer_object.txt



Following are source contents

Overview
    This extension defines a simple interface for drawing to rendering
    destinations other than the buffers provided to the GL by the
    window-system.

    In this extension, these newly defined rendering destinations are
    known collectively as "framebuffer-attachable images".  This
    extension provides a mechanism for attaching framebuffer-attachable
    images to the GL framebuffer as one of the standard GL logical
    buffers: color, depth, and stencil.  (Attaching a
    framebuffer-attachable image to the accum logical buffer is left for
    a future extension to define).  When a framebuffer-attachable image
    is attached to the framebuffer, it is used as the source and
    destination of fragment operations as described in Chapter 4.

    By allowing the use of a framebuffer-attachable image as a rendering
    destination, this extension enables a form of "offscreen" rendering.
    Furthermore, "render to texture" is supported by allowing the images
    of a texture to be used as framebuffer-attachable images.  A
    particular image of a texture object is selected for use as a
    framebuffer-attachable image by specifying the mipmap level, cube
    map face (for a cube map texture), and z-offset (for a 3D texture)
    that identifies the image.  The "render to texture" semantics of
    this extension are similar to performing traditional rendering to
    the framebuffer, followed immediately by a call to CopyTexSubImage.
    However, by using this extension instead, an application can achieve
    the same effect, but with the advantage that the GL can usually
    eliminate the data copy that would have been incurred by calling
    CopyTexSubImage.

    This extension also defines a new GL object type, called a
    "renderbuffer", which encapsulates a single 2D pixel image.  The
    image of renderbuffer can be used as a framebuffer-attachable image
    for generalized offscreen rendering and it also provides a means to
    support rendering to GL logical buffer types which have no
    corresponding texture format (stencil, accum, etc).  A renderbuffer
    is similar to a texture in that both renderbuffers and textures can
    be independently allocated and shared among multiple contexts.  The
    framework defined by this extension is general enough that support
    for attaching images from GL objects other than textures and
    renderbuffers could be added by layered extensions.

    To facilitate efficient switching between collections of
    framebuffer-attachable images, this extension introduces another new
    GL object, called a framebuffer object.  A framebuffer object
    contains the state that defines the traditional GL framebuffer,
    including its set of images.  Prior to this extension, it was the
    window-system which defined and managed this collection of images,
    traditionally by grouping them into a "drawable".  The window-system
    API's would also provide a function (i.e., wglMakeCurrent,
    glXMakeCurrent, aglSetDrawable, etc.) to bind a drawable with a GL
    context (as is done in the WGL_ARB_pbuffer extension).  In this
    extension however, this functionality is subsumed by the GL and the
    GL provides the function BindFramebufferEXT to bind a framebuffer
    object to the current context.  Later, the context can bind back to
    the window-system-provided framebuffer in order to display rendered
    content.

    Previous extensions that enabled rendering to a texture have been
    much more complicated.  One example is the combination of
    ARB_pbuffer and ARB_render_texture, both of which are window-system
    extensions.  This combination requires calling MakeCurrent, an
    operation that may be expensive, to switch between the window and
    the pbuffer drawables.  An application must create one pbuffer per
    renderable texture in order to portably use ARB_render_texture.  An
    application must maintain at least one GL context per texture
    format, because each context can only operate on a single
    pixelformat or FBConfig.  All of these characteristics make
    ARB_render_texture both inefficient and cumbersome to use.

    EXT_framebuffer_object, on the other hand, is both simpler to use
    and more efficient than ARB_render_texture.  The
    EXT_framebuffer_object API is contained wholly within the GL API and
    has no (non-portable) window-system components.  Under
    EXT_framebuffer_object, it is not necessary to create a second GL
    context when rendering to a texture image whose format differs from
    that of the window.  Finally, unlike the pbuffers of
    ARB_render_texture, a single framebuffer object can facilitate
    rendering to an unlimited number of texture objects.

Glossary of Helpful Terms

logical buffer:
One of 
  • the color, 
  • the depth, or 
  • the stencil buffers 
of the framebuffer.

        framebuffer:
  • The collection of logical buffers and 
  • associated state
  • defining where the output of GL rendering is directed.

        texture:
  • an object which consists of one or more 2D arrays of pixel images
  • associated states
  • can be used as a source of data during the texture-mapping process described in section 3.8.

        texture image:
  • one of the 2D arrays of pixels that 
  • are part of a texture object as defined in section 3.8.  
  • Texture images contain and define the texels of the texture object.

        renderbuffer:
  • A new type of storage object which contains a single 2D array of pixels
  • associated state that 
  • can be used as a destination for pixel data written during the rendering process described in Chapter 4.

        renderbuffer image:
  • The 2D array of pixels that 
  • is part of a renderbuffer object.  
  • A renderbuffer image contains and defines the pixels of the renderbuffer object.

        framebuffer-attachable image:
  • A 2D pixel image that 
  • can be attached to one of the logical buffer attachment points of a framebuffer object.  
  • Texture images and renderbuffer images are two examples of framebuffer-attachable images.

        attachment point:
  • The set of state which 
  • references a specific framebuffer-attachable image, and 
  • allows that framebuffer-attachable image to be used to store the contents of a logical buffer of a framebuffer object.  
  • There is an attachment point state vector for each color, depth, and stencil buffer of a framebuffer.

        attach:
            The act of connecting one object to another object.
            An "attach" operation is similar to a "bind" operation
            in that 
            both represent a reference to the attached or bound
            object for the purpose of managing object lifetimes and 
            both enable manipulation of the state of the attached or bound
            object.

            However, an "attach" is also different from a "bind" in that
            "binding" an unused object creates a new object, while
            "attaching" does not.  Additionally, "bind" establishes a
            connection between a context and an object, while "attach"
            establishes a connection between two objects.

            Finally, if object "A" is attached to object "B" and object
            "B" is bound to context "C", then in most respects, we treat
            "A" as if it is <implicitly> bound to "C".

        framebuffer attachment completeness:
            Similar to texture "mipmap" or "cube" completeness from
            section 3.8.10, defines a minimum set of criteria for
            framebuffer attachment points.  (for complete definition,
            see section 4.4.4.1)

        framebuffer completeness:
            Similar to texture "mipmap cube completeness", defines a
            composite set of "completeness" requirements and
            relationships among the attached framebuffer-attachable
            images.  (for complete definition, see section 4.4.4.2)
________________________________________________________________

Notions: OpenGL Frame Buffer Object (FBO) -- redirect the rendering output to the AC-FrameBuffer Object.

State..to.be.continued 

Overview

In OpenGl rendering pipeline,
the geometry data and textures are transformed and passed several tests,
and then finally rendered onto a screen as 2D pixels. 
The final rendering destination of the OpenGL pipeline is called framebuffer. 
Framebuffer is
a collection of
2D arrays or storages utilized by OpenGL;


  • color buffers,
  • depth buffer,
  • stencil buffer and
  • accumulation buffer..
By default, 
OpenGLuses the framebuffer as a rendering destinationthat iscreated andmanagedentirely by the window system.
this default framebuffer is called window-system provided framebuffer.




the OpenGL extension,
GL_ARB_framebuffer_object provides an interface
to create additional non-displayable framebuffer objects (FBO). 
this framebuffer is called application-created framebuffer
in order to distinguish from the default window-system-provided framebuffer. 
by using framebuffer object (FBO),
an OpenGL application can redirect the rendering outputto the application-created framebuffer object (FBO)other than the traditional window-system-provided framebuffer.
and, it is fully controlled by OpenGL.

Similar to window-system-provided framebuffer,
a FBO contains a collection of rendering destination;


  • color,
  • depth and
  • stencil buffer..
  • (note that accumulation buffer is not defined in FBO.)
these logical buffers in a FBO are called framebuffer-attachable images,
which 2D arrays of pixels that can be attached to a framebuffer object.

There are two types of framebuffer-attachable images

  • texture images and
  •  renderbuffer images
If an image of a texture object is attached to a framebuffer, OpenGL performs "render to texture".If an image of a renderbuffer object is attached to a framebuffer, OpenGL performs "offscreen rendering".

By the way, renderbuffer object is a new type of storage object defined in GL_ARB_framebuffer_object extension. It is used as a rendering destination for a single 2D image during rendering process.

The following diagram shows the connectivity among the framebuffer object, texture object and renderbuffer object. Multiple texture objects or renderbuffer objects can be attached to a framebuffer object through the attachment points.

There are multiple color attachment points (GL_COLOR_ATTACHMENT0,..., GL_COLOR_ATTACHMENTn), one depth attachment point (GL_DEPTH_ATTACHMENT), and one stencil attachment point (GL_STENCIL_ATTACHMENT) in a framebuffer object. The number of color attachment points is implementation dependent, but each FBO must have at least one color attachement point. You can query the maximum number of color attachement points with GL_MAX_COLOR_ATTACHMENTS, which are supported by a graphics card. The reason that a FBO has multiple color attachement points is to allow to render the color buffer to multiple destinations at the same time. This "multiple render targets" (MRT) can be accomplished byGL_ARB_draw_buffers extension. Notice that the framebuffer object itself does not have any image storage(array) in it, but, it has only multiple attachment points. 
Framebuffer object (FBO) provides an efficient switching mechanism; detach the previous framebuffer-attachable image from a FBO, and attach a new framebuffer-attachable image to the FBO. Switching framebuffer-attachable images is much faster than switching between FBOs. FBO provides glFramebufferTexture2D() to switch 2D texture objects, and glFramebufferRenderbuffer() to switch renderbuffer objects.
...

Creating Frame Buffer Object (FBO)

Creating framebuffer objects is similar to generating vertex buffer objects (VBO).

glGenFramebuffers()

void glGenFramebuffers(GLsizei n, GLuint* ids)
void glDeleteFramebuffers(GLsizei n, const GLuint* ids)
glGenFramebuffers() requires 2 parameters; the first one is the number of framebuffers to create, and the second parameter is the pointer to a GLuint variable or an array to store a single ID or multiple IDs. It returns the IDs of unused framebuffer objects. ID 0 means the default framebuffer, which is the window-system-provided framebuffer.
And, FBO may be deleted by calling glDeleteFramebuffers() when it is not used anymore.

glBindFramebuffer()

Once a FBO is created, it has to be bound before using it.
void glBindFramebuffer(GLenum target, GLuint id)
The first parameter, target, should be GL_FRAMEBUFFER, and the second parameter is the ID of a framebuffer object. Once a FBO is bound, all OpenGL operations affect onto the current bound framebuffer object. The object ID 0 is reserved for the default window-system provided framebuffer. Therefore, in order to unbind the current framebuffer (FBO), use ID 0 in glBindFramebuffer().

Renderbuffer Object

In addition, renderbuffer object is newly introduced for offscreen rendering. It allows to render a scene directly to a renderbuffer object, instead of rendering to a texture object. Renderbuffer is simply a data storage object containing a single image of a renderable internal format. It is used to store OpenGL logical buffers that do not have corresponding texture format, such as stencil or depth buffer.

glGenRenderbuffers()

void glGenRenderbuffers(GLsizei n, GLuint* ids)
void glDeleteRenderbuffers(GLsizei n, const Gluint* ids)
Once a renderbuffer is created, it returns non-zero positive integer. ID 0 is reserved for OpenGL.

glBindRenderbuffer()

void glBindRenderbuffer(GLenum target, GLuint id)
Same as other OpenGL objects, you have to bind the current renderbuffer object before referencing it. The target parameter should be GL_RENDERBUFFER for renderbuffer object.

glRenderbufferStorage()

void glRenderbufferStorage(GLenum  target,
                           GLenum  internalFormat,
                           GLsizei width,
                           GLsizei height)
When a renderbuffer object is created, it does not have any data storage, so we have to allocate a memory space for it. This can be done by using glRenderbufferStorage(). The first parameter must be GL_RENDERBUFFER. The second parameter would be color-renderable (GL_RGB, GL_RGBA, etc.), depth-renderable (GL_DEPTH_COMPONENT), or stencil-renderable formats (GL_STENCIL_INDEX). The width and height are the dimension of the renderbuffer image in pixels.
The width and height should be less than GL_MAX_RENDERBUFFER_SIZE, otherwise, it generates GL_INVALID_VALUE error.

glGetRenderbufferParameteriv()

void glGetRenderbufferParameteriv(GLenum target,
                                  GLenum param,
                                  GLint* value)
You also get various parameters of the currently bound renderbuffer object. target should be GL_RENDERBUFFER, and the second parameter is the name of parameter. The last is the pointer to an integer variable to store the returned value. The available names of the renderbuffer parameters are;

GL_RENDERBUFFER_WIDTH
GL_RENDERBUFFER_HEIGHT
GL_RENDERBUFFER_INTERNAL_FORMAT
GL_RENDERBUFFER_RED_SIZE
GL_RENDERBUFFER_GREEN_SIZE
GL_RENDERBUFFER_BLUE_SIZE
GL_RENDERBUFFER_ALPHA_SIZE
GL_RENDERBUFFER_DEPTH_SIZE
GL_RENDERBUFFER_STENCIL_SIZE

Attaching images to FBO

FBO itself does not have any image storage(buffer) in it. Instead, we must attach framebuffer-attachable images (texture or renderbuffer objects) to the FBO. This mechanism allows that FBO quickly switch (detach and attach) the framebuffer-attachable images in a FBO. It is much faster to switch framebuffer-attachable images than to switch between FBOs. And, it saves unnecessary data copies and memory consumption. For example, a texture can be attached to multiple FBOs, and its image storage can be shared by multiple FBOs.

Attaching a 2D texture image to FBO

glFramebufferTexture2D(GLenum target,
                       GLenum attachmentPoint,
                       GLenum textureTarget,
                       GLuint textureId,
                       GLint  level)
glFramebufferTexture2D() is to attach a 2D texture image to a FBO. The first parameter must be GL_FRAMEBUFFER, and the second parameter is the attachment point where to connect the texture image. A FBO has multiple color attachment points (GL_COLOR_ATTACHMENT0, ..., GL_COLOR_ATTACHMENTn), GL_DEPTH_ATTACHMENT, and GL_STENCIL_ATTACHMENT. The third parameter, "textureTarget" is GL_TEXTURE_2D in most cases. The fourth parameter is the identifier of the texture object. The last parameter is the mipmap level of the texture to be attached.
If the textureId parameter is set to 0, then, the texture image will be detached from the FBO. If a texture object is deleted while it is still attached to a FBO, then, the texture image will be automatically detached from the currently bound FBO. However, if it is attached to multiple FBOs and deleted, then it will be detached from only the bound FBO, but will not be detached from any other un-bound FBOs.

Attaching a Renderbuffer image to FBO

void glFramebufferRenderbuffer(GLenum target,
                               GLenum attachmentPoint,
                               GLenum renderbufferTarget,
                               GLuint renderbufferId)
A renderbuffer image can be attached by calling glFramebufferRenderbuffer(). The first and second parameters are same as glFramebufferTexture2D(). The third parameter must be GL_RENDERBUFFER, and the last parameter is the ID of the renderbuffer object.
If renderbufferId parameter is set to 0, the renderbuffer image will be detached from the attachment point in the FBO. If a renderbuffer object is deleted while it is still attached in a FBO, then it will be automatically detached from the bound FBO. However, it will not be detached from any other non-bound FBOs.

Checking FBO Status

Once attachable images (textures and renderbuffers) are attached to a FBO and before performing FBO operation, you must validate if the FBO status is complete or incomplete by using glCheckFramebufferStatus(). If the FBO is not complete, then any drawing and reading command (glBegin(), glCopyTexImage2D(), etc) will be failed.
GLenum glCheckFramebufferStatus(GLenum target)
glCheckFramebufferStatus() validates all its attached images and framebuffer parameters on the currently bound FBO. And, this function cannot be called within glBegin()/glEnd() pair. The target parameter should be GL_FRAMEBUFFER. It returns non-zero value after checking the FBO. If all requirements and rules are satisfied, then it returns GL_FRAMEBUFFER_COMPLETE. Otherwise, it returns a relevant error value, which tells what rule is violated.
The rules of FBO completeness are:
  • The width and height of framebuffer-attachable image must be not zero.
  • If an image is attached to a color attachment point, then the image must have a color-renderable internal format. (GL_RGBA, GL_DEPTH_COMPONENT, GL_LUMINANCE, etc)
  • If an image is attached to GL_DEPTH_ATTACHMENT, then the image must have a depth-renderable internal format. (GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT24, etc)
  • If an image is attached to GL_STENCIL_ATTACHMENT, then the image must have a stencil-renderable internal format. (GL_STENCIL_INDEX, GL_STENCIL_INDEX8, etc)
  • FBO must have at least one image attached.
  • All images attached a FBO must have the same width and height.
  • All images attached the color attachment points must have the same internal format.
Note that even though all of the above conditions are satisfied, your OpenGL driver may not support some combinations of internal formats and parameters. If a particular implementation is not supported by OpenGL driver, then glCheckFramebufferStatus() returns GL_FRAMEBUFFER_UNSUPPORTED.
The sample code provides some utility functions to report the information of the current FBO; printFramebufferInfo() and checkFramebufferStatus().

Example: Render To Texture

OpenGL FBO Example: Render To Texture OpenGL FBO Example: Depth Buffer
Download the source and binary: fbo.zip (Updated: 2014-05-03)
Extras:
- Rendering to the depth buffer only: fboDepth.zip
- Rendering the outlines of an object using stencil buffer: fboStencil.zip
- Bliting between 2 FBOs using glBlitFramebuffer()fboBlit.zip
Sometimes, you need to generate dynamic textures on the fly. The most common examples are generating mirroring/reflection effects, dynamic cube/environment maps and shadow maps. Dynamic texturing can be accomplished by rendering the scene to a texture. A traditional way of render-to-texture is to draw a scene to the framebuffer as normal, and then copy the framebuffer image to a texture by using glCopyTexSubImage2D().
Using FBO, we can render a scene directly onto a texture, so we don't have to use the window-system-provided framebuffer at all. Further more, we can eliminate an additional data copy (from framebuffer to texture).
This demo program performs render to texture operation with/without FBO, and compares the performance difference. Other than performance gain, there is another advantage of using FBO. If the texture resolution is larger than the size of the rendering window in traditional render-to-texture mode (without FBO), then the area out of the window region will be clipped. However, FBO does not suffer from this clipping problem. You can create a framebuffer-renderable image larger than the display window.
The following codes is to setup a FBO and framebuffer-attachable images before the rendering loop is started. Note that not only a texture image is attached to the FBO, but also, a renderbuffer image is attached to the depth attachment point of the FBO. We do not actually use this depth buffer, however, the FBO itself needs it for depth test. If we don't attach this depth renderable image to the FBO, then the rendering output will be corrupted because of missing depth test. If stencil test is also required during FBO rendering, then additional renderbuffer image should be attached to GL_STENCIL_ATTACHMENT.

...
// create a texture object
GLuint textureId;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0,
             GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);

// create a renderbuffer object to store depth info
GLuint rboId;
glGenRenderbuffers(1, &rboId);
glBindRenderbuffer(GL_RENDERBUFFER, rboId);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
                      TEXTURE_WIDTH, TEXTURE_HEIGHT);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

// create a framebuffer object
GLuint fboId;
glGenFramebuffers(1, &fboId);
glBindFramebuffer(GL_FRAMEBUFFER, fboId);

// attach the texture to FBO color attachment point
glFramebufferTexture2D(GL_FRAMEBUFFER,        // 1. fbo target: GL_FRAMEBUFFER 
                       GL_COLOR_ATTACHMENT0,  // 2. attachment point
                       GL_TEXTURE_2D,         // 3. tex target: GL_TEXTURE_2D
                       textureId,             // 4. tex ID
                       0);                    // 5. mipmap level: 0(base)

// attach the renderbuffer to depth attachment point
glFramebufferRenderbuffer(GL_FRAMEBUFFER,      // 1. fbo target: GL_FRAMEBUFFER
                          GL_DEPTH_ATTACHMENT, // 2. attachment point
                          GL_RENDERBUFFER,     // 3. rbo target: GL_RENDERBUFFER
                          rboId);              // 4. rbo ID

// check FBO status
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(status != GL_FRAMEBUFFER_COMPLETE)
    fboUsed = false;

// switch back to window-system-provided framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
...

The rendering procedure of render-to-texture is almost same as normal drawing. We only need to switch the rendering destination from the window-system-provided to the non-displayable, application-created framebuffer (FBO).

...
// set rendering destination to FBO
glBindFramebuffer(GL_FRAMEBUFFER, fboId);

// clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// draw a scene to a texture directly
draw();

// unbind FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0);

// trigger mipmaps generation explicitly
// NOTE: If GL_GENERATE_MIPMAP is set to GL_TRUE, then glCopyTexSubImage2D()
// triggers mipmap generation automatically. However, the texture attached
// onto a FBO should generate mipmaps manually via glGenerateMipmap().
glBindTexture(GL_TEXTURE_2D, textureId);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
...

Note that glGenerateMipmap() is also included as part of FBO extension in order to generate mipmaps explicitly after modifying the base level texture image. If GL_GENERATE_MIPMAP is set to GL_TRUE, then glTex{Sub}Image2D() and glCopyTex{Sub}Image2D() trigger automatic mipmap generation (in OpenGL version 1.4 or greater). However, FBO operation does not generate its mipmaps automatically when the base level texture is modified because FBO does not call glCopyTex{Sub}Image2D() to modify the texture. Therefore, glGenerateMipmap() must be explicitly called for mipmap generation.
If you need to a post processing of the texture, it is possible to combine with Pixel Buffer Object (PBO) to modify the texture efficiently.


...


Semantics.Structure.Frame.Buffer

State

to be continued...

 Framebuffer Object

...

Semantics

Framebuffer objects are very complicated. As such, we need to explicitly define certain terminology.
Image
For the purposes of this article, an image is a single 2D array of pixels. It has a specific format for these pixels.
Layered Image
For the purposes of this article, a layered image is a sequence of images of a particular size and format. Layered images come from single mipmap levels of certain Texture types.
Texture
For the purposes of this article, a texture is an object that contains some number of images, as defined above. All of the images have the same format, but they do not have to have the same size (different mip-maps, for example). Textures can be accessed from Shaders via various methods.
Renderbuffer
A renderbuffer is an object that contains a single image. Renderbuffers cannot be accessed by Shaders in any way. The only way to work with a renderbuffer, besides creating it, is to put it into an FBO.
Attach
To connect one object to another. This term is used across all of OpenGL, but FBOs make the most use of the concept. Attachment is different from binding. Objects are bound to the context; objects are attached to one another.
Attachment point
A named location within a framebuffer object that a framebuffer-attachable image or layered image can be attached to. Attachment points restrict the general kind of Image Format for images attached to them.
Framebuffer-attachable image
Any image, as previously described, that can be attached to a framebuffer object.
Framebuffer-attachable layered image
Any layered image, as previously described, that can be attached to a framebuffer object.
...

Framebuffer Object Structure

As standard OpenGL Objects, FBOs have the usual glGenFramebuffers and glDeleteFramebuffers functions. As expected, it also has the usual glBindFramebuffer function, to bind an FBO to the context.
The target​ parameter for this object can take one of 3 values: GL_FRAMEBUFFERGL_READ_FRAMEBUFFER, or GL_DRAW_FRAMEBUFFER. The last two allow you to bind an FBO so that reading commands (glReadPixels, etc) and writing commands (all rendering commands) can happen to two different framebuffers. The GL_FRAMEBUFFER binding target simply sets both the read and the write to the same FBO.
When an FBO is bound to a target, the available buffer names. The default framebuffer has buffer names like GL_FRONTGL_BACKGL_AUXiGL_ACCUM, and so forth. FBOs do not have these.
Instead, FBOs have a different set of image names. Each FBO image represents an attachment point, a location in the FBO where an image can be attached. FBOs have the following attachment points:
  • GL_COLOR_ATTACHMENTi: These are an implementation-dependent number of attachment points. You can query GL_MAX_COLOR_ATTACHMENTS to determine the number of color attachments that an implementation will allow. The minimum value for this is 8, so you are guaranteed to be able to have at least color attachments 0-7. These attachment points can only have images bound to them with color-renderable formats. All compressed image formats are not color-renderable, and thus cannot be attached to an FBO.
  • GL_DEPTH_ATTACHMENT: This attachment point can only have images with depth formats bound to it. The image attached becomes the Depth Buffer for the FBO. **NOTE** Even if you don't plan on reading from this depth_attachment, an off screen buffer that will be rendered to should have a depth attachment.
  • GL_STENCIL_ATTACHMENT: This attachment point can only have images with stencil formats bound to it. The image attached becomes the stencil buffer for the FBO.
  • GL_DEPTH_STENCIL_ATTACHMENT: This is shorthand for "both depth and stencil". The image attached becomes both the depth and stencil buffers.
Note: If you use GL_DEPTH_STENCIL_ATTACHMENT, you should use a packed depth-stencil internal format for the texture or renderbuffer you are attaching.
...

________________________________________________________________________________
________________________________________________________________________________


.FrameBuffer

Cited Official Site
https://www.opengl.org/wiki/Framebuffer
..
Framebuffer is a collection of buffers that can be used as the destination for rendering. OpenGL has two kinds of framebuffers: the Default Framebuffer, which is provided by the OpenGL Context; and user-created framebuffers called Framebuffer Objects (FBOs). 
The buffers for default framebuffers are part of the context and usually represent a window or display device. 
The buffers for FBOs reference images from either Textures or Renderbuffers; they are never directly visible.
Note that the term "buffer" here refers to a specific location in the framebuffer. An image may or may not be associated with a particular buffer in a framebuffer. Buffers in FBOs are also called "attachment points"; they're the locations where images can be attached. 
Default framebuffers cannot change their buffer attachments, but a particular default framebuffer may not have images associated with certain buffers. For example the GL_BACK_RIGHTbuffer will only have an image if the default framebuffer is double-buffered and uses stereoscopic 3D. 
The default framebuffer's buffer names are separate from framebuffer object buffer names.

Bind points

glBindFramebuffer is used to bind framebuffers to the context. They can be bound to one of two targets: GL_DRAW_FRAMEBUFFER and GL_READ_FRAMEBUFFER. The draw framebuffer is used as the destination for rendering, clearing, and other writing operations. The read framebuffer is used as the source for reading operations. 
Binding to the GL_FRAMEBUFFER target is equivalent to binding that framebuffer to both GL_DRAW_FRAMEBUFFER and GL_READ_FRAMEBUFFER. Note that most other uses ofGL_FRAMEBUFFER mean the draw framebuffer; this is the case when it means both.


Saturday, May 28, 2016

unit.conversion.for.physics

[State]
to be continued...

[ Key Word ]
how to change the physical unit size of a pixel in OpenGL?



[Unit conversion for physics]

[Project Dumbo Dev]

...
Gave you the tick, changing the scale of world space solved all my problems. Now everything is more manageable and clear than working with -1 to 1 range. Thanks! 
...




Thursday, May 26, 2016

How to change visual studio 2013 language to English 100%

[Visual Studio 2013]


[ Environmental Language Setting ]


[https://www.youtube.com/watch?v=O_h8wGcJArY]

...

...

1st download english language pack for visualstudio2013
    https://www.microsoft.com/en-us/download/confirmation.aspx?id=40783

2nd install it online

3rd open visual studio 2013

4th go to tools and click to option

5th go to Environment and click international setting

6th change the language to english

7th restart the visual studio 2013

...



Sunday, May 22, 2016

Matrix.Definition


[ State ]

    TO BE Continued...

[Source Tutorial Site]

    http://www.3dgep.com/understanding-the-view-matrix/

[ Contents ]
...

[ Column Major Matrix ]

...

Convention

In this article I will consider matrices to be column major. That is, in a 4×4 homogeneous transformation matrix, column 1 represents the “right” (X) vector, column 2 represents the “up” (Y), column 3 represents the “forward” (Z) vector and column 4 represents the translation (origin or position) of the space represented by the transformation matrix (W).
http://www.3dgep.com/understanding-the-view-matrix/
http://www.songho.ca/opengl/gl_transform.html



Using this convention, we must pre-multiply column vectors to transform a vector by a transformation matrix. That is, in order to transform a vector V by a transformation matrix M we would need to pre-multiply the column vector V by the matrix M on the left.

And to concatenate a set of affine transformations (such translation (T), scale (S), and rotation R)) we must apply the transformations from left to right:
M = T * R * S
This transformation can be stated in words as “first translate, then rotate, then scale”.
And to transform a child node in a scene graph by the transform of it’s parent you would pre-multiply the child’s local (relative to it’s parent) transformation matrix by it’s parents world transform on the left:

Of course, if the node in the scene graph does not have a parent (the root node of the scene graph) then the node’s world transform is the same as its local (relative to its parent which in this case is just the identity matrix) transform:


Memory Layout of Column-Major Matrices


Using column matrices, the memory layout of the components in computer memory of a matrix are sequential in the columns of the matrix:

This has the annoying consequence that if we want to initialize the values of a matrix we must actually transpose the values in order to load the matrix correctly.
For example, the following layout is the correct way to load a column-major matrix in a C program:
Loading a matrix in column-major order.
1
2
3
4
5
6
7
8
9
10
11
float right[4]    = { 1, 0, 0, 0 };
float up[4]       = { 0, 1, 0, 0 };
float forward[4]  = { 0, 0, 1, 0 };
float position[4] = { 0, 0, 0, 1 };
float matrix[4][4] = {
    {   right[0],    right[1],    right[2],    right[3] }, // First col
    {      up[0],       up[1],       up[2],       up[3] }, // Second col
    { forward[0],  forward[1],  forward[2],  forward[3] }, // Third col
    {position[0], position[1], position[2], position[3] }  // Forth col
};

At first glance, you will be thinking “wait a minute, that matrix is expressed in row-major format!”. Yes, this is actually true. A row-major matrix stores it’s elements in the same order in memory except the individual vectors are considered rows instead of columns.
So what is the big difference then? The difference is seen in the functions which perform matrix multiplication. Let’s see an example.
Suppose we have the following C++ definitions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
struct vec4
{
    float values[4];
    vec4()
    {
        values[0] = values[1] = values[2] = values[3] = 0;
    }
    vec4( float x, float y, float z, float w )
    {
        values[0] = x;
        values[1] = y;
        values[2] = z;
        values[3] = w;
    }
    // Provide array-like index operators for the vector components.
    const float& operator[] ( int index ) const
    {
        return values[index];
    }
    float& operator[] ( int index )
    {
        return values[index];
    }
};
struct mat4
{
    vec4 columns[4];
    mat4()
    {
        columns[0] = vec4( 1, 0, 0, 0 );
        columns[1] = vec4( 0, 1, 0, 0 );
        columns[2] = vec4( 0, 0, 1, 0 );
        columns[3] = vec4( 0, 0, 0, 1 );
    }
    mat4( vec4 x, vec4 y, vec4 z, vec4 w )
    {
        columns[0] = x;
        columns[1] = y;
        columns[2] = z;
        columns[3] = w;
    }
    // Provide array-like index operators for the columns of the matrix.
    const vec4& operator[]( int index ) const
    {
        return columns[index];
    }
    vec4& operator[]( int index )
    {
        return columns[index];
    }
};

The vec4 struct provides the index operator to allow for the use of indices to access the individual vector components. This will make the code slightly easier to read. It is interesting to note that the vec4 structure could be interpreted as either a row-vector or a column-vector. There is no way to differentiate the difference in this context.
The mat4 struct provides the index operator to allow for the use of indices to access the individual columns (not rows!) of the matrix.
Using this technique, in order to access the i<th> row and the j<th> column of matrix M we would need to access the elements of the matrix like this:
main.cpp
1
2
3
4
5
6
int i = row;
int j = column;
mat4 M;
// Access the i-th row and the j-th column of matrix M
float m_ij = M[j][i];

This is quite annoying that we have to swap theandindices in order to access the correct matrix element. This is probably a good reason to use row-major matrices instead of column-major matrices when programming however the most common convention in linear algebra textbooks and academic research papers is to use column-major matrices. So the preference to use column-major matrices is mostly for historical reasons.
Suppose now that we define the following functions:
Matrix-vector multiplication
1
2
3
4
5
6
// Pre-multiply a vector by a multiplying a matrix on the left.
vec4 operator*( const mat4& m, const vec4& v );
// Post-multiply a vector by multiplying a matrix on the right.
vec4 operator*( const vec4& v, const mat4& m );
// Matrix multiplication
mat4 operator*( const mat4& m1, const mat4& m2 );
The first method performs pre-multiplication of 4-component column vector with a 4×4 matrix. The second method performs post-multiplication of a 4-component row vector with a 4×4 matrix.
And the third method performs 4×4 matrix-matrix multiplication.
Then the pre-multiply method would look like this:
Pre-multiply vector by a matrix on the left.
1
2
3
4
5
6
7
8
9
10
// Pre-multiply a vector by a matrix on the left.
vec4 operator*( const mat4& m, const vec4& v )
{
    return vec4(
        m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2] + m[3][0] * v[3],
        m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2] + m[3][1] * v[3],
        m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2] + m[3][2] * v[3],
        m[0][3] * v[0] + m[1][3] * v[1] + m[2][3] * v[2] + m[3][3] * v[3]
    );
}
Notice that we still multiply the rows of matrix m with the column vector v but the indices ofm simply appear swapped.
And similarly the function which takes a 4-component row-vector v and pre-multiplies it by a 4×4 matrix m.
Post-multiply a vector by a matrix on the right.
1
2
3
4
5
6
7
8
9
10
// Pre-multiply a vector by a matrix on the right.
vec4 operator*( const vec4& v, const mat4& m )
{
    return vec4(
        v[0] * m[0][0] + v[1] * m[0][1] + v[2] * m[0][2] + v[3] * m[0][3],
        v[0] * m[1][0] + v[1] * m[1][1] + v[2] * m[1][2] + v[3] * m[1][3],
        v[0] * m[2][0] + v[1] * m[2][1] + v[2] * m[2][2] + v[3] * m[2][3],
        v[0] * m[3][0] + v[1] * m[3][1] + v[2] * m[3][2] + v[3] * m[3][3]
    );
}
In this case we multiply the row vector v by the columns of matrix m. Notice that we still need to swap the indices to access the correct column and row of matrix m.
And the final function which performs a matrix-matrix multiply:
Matrix-matrix multiply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Matrix multiplication
mat4 operator*( const mat4& m1, const mat4& m2 )
{
    vec4 X(
        m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3],
        m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3],
        m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3],
        m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3]
    );
    vec4 Y(
        m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3],
        m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3],
        m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3],
        m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3]
    );
    vec4 Z(
        m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3],
        m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3],
        m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3],
        m1[0][3] * m2[2][0] + m1[1][3] * m2[2][1] + m1[2][3] * m2[2][2] + m1[3][3] * m2[2][3]
    );
    vec4 W(
        m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3],
        m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3],
        m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2] + m1[3][2] * m2[3][3],
        m1[0][3] * m2[3][0] + m1[1][3] * m2[3][1] + m1[2][3] * m2[3][2] + m1[3][3] * m2[3][3]
    );
    return mat4( X, Y, Z, W );
}
This function multiplies the rows of m1 by the columns of m2. Notice we have to swap the indices in both m1 and m2.
This function can be written slightly simplified if we reuse the pre-multiply function:
Matrix-matrix multiply (simplified)
1
2
3
4
5
6
7
8
9
10
// Matrix multiplication
mat4 operator*( const mat4& m1, const mat4& m2 )
{
    vec4 X = m1 * m2[0];
    vec4 Y = m1 * m2[1];
    vec4 Z = m1 * m2[2];
    vec4 W = m1 * m2[3];
    return mat4( X, Y, Z, W );
}
The main point is that whatever convention you use, you stick with it and be consistent and always make sure you document clearly in your API which convention you are using.



...