Multisampling

From OpenGL.org
(Redirected from Multisample)
Jump to: navigation, search

Multisampling, also known as multisample antialiasing (MSAA), is one method for achieving full-screen antialiasing (FSAA). With multisampling, each pixel at the edge of a polygon is sampled multiple times. For each sample-pass, a slight offset is applied to all screen coordinates. This offset is smaller than the actual size of the pixels. By averaging all these samples, the result is a smoother transition of the colors at the edges. Unlike supersampling (SSAA) which can result in the same pixel being shaded multiple times per pixel, multisampling runs the fragment program just once per pixel rasterized. However with MSAA multiple depth/stencil comparisons are performed per pixel, one for each of the subsamples, which gives you sub-pixel spatial precision on your geometry and nice, smoothed edges on your polygons.

History

Before GL_ARB_multisample extension, the edges of lines, polygons, and points could be selectively antialiased using using glEnable(GL_LINE_SMOOTH), glEnable(GL_POLYGON_SMOOTH), glEnable(GL_POINT_SMOOTH) respectively, combined with a blending function, such as glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). Such features were typically not implemented in hardware in early consumer graphics cards at the time, and were done in software resulting in poor performance. More expensive "workstation" graphics cards from HP, Sun, and SGI at the time did implement these features in hardware. Modern programs should not make use of these features.

Rendering with Multisampling

There are two pieces to rendering with multisampling:

  1. Allocating a multisample render target (window or FBO), and
  2. Enabling multisample rasterization (i.e. glEnable( GL_MULTISAMPLE ))

While the second step is standardized across all render target types and platforms, the first is only standardized for FBOs (as it is totally internal to GL). When rendering to a window, the allocation method depends on the platform-specific GL integration layer in-use (e.g. WGL, GLX, AGL, etc.). GLUT provides a wrapper around some of these so you don't have to care.

The following sections describe how to perform MSAA render target allocation (#1) for various render target types and platforms.

Allocating a Multisample Render Target

Render-to-FBO

As mentioned, allocation of multisample off-screen FBOs is platform independent. Here's an example:

  glGenTextures( 1, &tex );
  glBindTexture( GL_TEXTURE_2D_MULTISAMPLE, tex );
  glTexImage2DMultisample( GL_TEXTURE_2D_MULTISAMPLE, num_samples, GL_RGBA8, width, height, false );

  glGenFramebuffers( 1, &fbo );
  glBindFramebuffer( GL_FRAMEBUFFER, fbo );
  glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, tex, 0 );

  GLenum status = glCheckFramebufferStatus( target );
  ...

Once you've rendered your scene into the multisampled FBO, you can display the anti-aliased result on the screen by blitting your multisampled FBO to the back buffer using glBlitFramebuffer(). Before doing so, you must first remember to specify the back buffer as your draw buffer, and to specify your multisampled FBO as the read frame buffer, like so:

  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);   // Make sure no FBO is set as the draw framebuffer
  glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); // Make sure your multisampled FBO is the read framebuffer
  glDrawBuffer(GL_BACK);                       // Set the back buffer as the draw buffer
  glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);

Doing this blit will automatically resolve the multisampled FBO. In other words, for each texel in the multisampled FBO, the blit will blend together the texel's samples, and this blended color is what is written into the corresponding pixel on the back buffer. If you wish, you can resolve your multisampled FBO into a different off-screen FBO by setting that FBO as your draw buffer.

Render-to-Window

Microsoft Windows (using wgl)

The wgl functions required to create a multisampled OpenGL context are not available until a valid OpenGL context is made current to the thread. This leads to a temporary context code path which can get very involved with platform specific detailed. Users of libraries such as GLUT, GLEW, or GLee can significantly reduce the amount of effort required. The rest of this section assumes that valid context is present and all wgl extension function pointers have been obtained, if not, please see how to create a temporary context.

A valid pixel format for the framebuffer is choose using the wglChoosePixelFormatARB function with a list of attributes to specify the multisampling properties. In order to choose a framebuffer format that incorporates multisampling, you must add it to the list of attributes. For example, this list of attributes does not select a multisampled pixel format:

   int attributes[] = {
   WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
   WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
   WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
   WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
   WGL_COLOR_BITS_ARB, 32,
   WGL_DEPTH_BITS_ARB, 24,
   WGL_STENCIL_BITS_ARB, 8,
   0
   };

To consider multisampled visuals, the WGL_SAMPLE_BUFFERS_ARB and WGL_SAMPLES_ARB attributes must be present. The WGL_SAMPLE_BUFFERS_ARB must be set to 1, and WGL_SAMPLES_ARB is the number of samples, e.g. for 8x multisampling, WGL_SAMPLES_ARB would be set to 8. This attribute list is the same as above, but considers 4x multisampled pixel formats too:

   int attributes[] = {
   WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
   WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
   WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
   WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
   WGL_COLOR_BITS_ARB, 32,
   WGL_DEPTH_BITS_ARB, 24,
   WGL_STENCIL_BITS_ARB, 8,
   WGL_SAMPLE_BUFFERS_ARB, 1, //Number of buffers (must be 1 at time of writing)
   WGL_SAMPLES_ARB, 4,        //Number of samples
   0
   };

Once the correct pixel format is found, creating a context proceeds as normal.

X Windows (using GLX)

This is the method you'd use on UNIX/Linux if you want to create an X window with multisampling capability. There are a few methods for doing this, but the following locates an MSAA FBConfig, looks up its XVisual, and then creates an X window in that visual. You'll notice some similarities with the WGL method above.

  // --- Find a MSAA FBConfig ---
  static const int Visual_attribs[] =
    {
      GLX_X_RENDERABLE    , True,
      GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
      GLX_RENDER_TYPE     , GLX_RGBA_BIT,
      GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
      GLX_RED_SIZE        , 8,
      GLX_GREEN_SIZE      , 8,
      GLX_BLUE_SIZE       , 8,
      GLX_ALPHA_SIZE      , 8,
      GLX_DEPTH_SIZE      , 24,
      GLX_STENCIL_SIZE    , 8,
      GLX_DOUBLEBUFFER    , True,
      GLX_SAMPLE_BUFFERS  , 1,            // <-- MSAA
      GLX_SAMPLES         , 4,            // <-- MSAA
      None
    };

  int attribs [ 100 ] ;
  memcpy( attribs, Visual_attribs, sizeof( Visual_attribs ) );

  GLXFBConfig fbconfig = 0;
  int         fbcount;
  GLXFBConfig *fbc = glXChooseFBConfig( display, screen, attribs, &fbcount );
  if ( fbc )
  {
    if ( fbcount >= 1 )
      fbconfig = fbc[0];
    XFree( fbc );
  }

  if ( !fbconfig )
  {
    printf( "Failed to get MSAA GLXFBConfig\n" );
    exit(1);
  }

  // --- Get its VisualInfo ---
  XVisualInfo *visinfo = glXGetVisualFromFBConfig( display, fbconfig );
  if ( !visinfo )
  {
    printf( "Failed to get XVisualInfo\n" );
    exit(1);
  }
  printf( "X Visual ID = 0x%.2x\n", int( visinfo->visualid ) );

  // --- Now just create an X window in that visual ---
  XSetWindowAttributes winAttr ;

  winAttr.event_mask = StructureNotifyMask | KeyPressMask ;
  winAttr.background_pixmap = None ;
  winAttr.background_pixel  = 0    ;
  winAttr.border_pixel      = 0    ;

  winAttr.colormap = XCreateColormap( display, root_win,
                                      visinfo->visual, AllocNone );
  
  unsigned int mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;

  Window win = XCreateWindow ( display, root_win, 
                               WIN_XPOS, WIN_YPOS, 
                               WIN_XRES, WIN_YRES, 0, 
                               visinfo->depth, InputOutput, 
                               visinfo->visual, mask, &winAttr ) ;

  XStoreName( display, win, "My GLX Window");

MacOS X (using Cocoa)

TBD

Cross-platform (using GLUT)

GLUT is a wrapper around the platform-specific GL integration layers (e.g. WGL, GLX, etc.) which allows you to prototype simple cross-platform GL examples quickly. In GLUT, the key to allocating an MSAA window is this:

 glutInitDisplayMode( ... | GLUT_MULTISAMPLE );

which directs GLUT to allocate an MSAA-capable window. The following is a complete example showing how to render with multisampling in a simple GLUT test program:

#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/glu.h>

#include <stdio.h>

float rotation_angle=0;
int msaa=1;

void reshape(int width, int height)
{
  glViewport(0, 0, width, height);
}

void mouse(int button, int state, int x, int y)
{
  if (state==GLUT_DOWN) 
  {
    msaa = !msaa;
    glutPostRedisplay();
  }
}


void display()
{
  int err=0;
  glClear(GL_COLOR_BUFFER_BIT);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-1,1,-1,1,-1,1);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glRotatef(rotation_angle, 0,0,1);

  glColor4f(1,0,0,1);

  if (msaa) 
  {
    glEnable(GL_MULTISAMPLE_ARB);
    printf("msaa on\n");
  } 
  else 
  {
    printf("msaa off\n");
    glDisable(GL_MULTISAMPLE_ARB);
  }

  glRectf(-.5,-.5,.5,.5);
  
  glutSwapBuffers();
  err = glGetError();
  if (err)
    fprintf(stderr, "%s\n", gluErrorString(err));
}

int
main (int argc, char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE);
  glutCreateWindow(argv[0]);

  glutDisplayFunc(display);
  glutMouseFunc(mouse);
  glutReshapeFunc(reshape);
  
  glutReshapeWindow(400,400);

  printf("%s\n",glGetString(GL_RENDERER));

  rotation_angle=30;

  glutMainLoop();
  return 0;
}

Extension References

- http://www.opengl.org/registry/specs/ARB/multisample.txt

These might interest you : - http://www.opengl.org/registry/specs/NV/multisample_filter_hint.txt - http://www.opengl.org/registry/specs/NV/explicit_multisample.txt - http://www.opengl.org/registry/specs/NV/multisample_coverage.txt

Conclusion

Setting up FSAA takes a few steps but it is worth it. Today's GPUs are very rapid and the user wants control over the quality of the game's graphics.
On Windows, the extension we are interested in are WGL_ARB_extensions_string which defines wglGetExtensionsStringARB, but the only way to check if this is available is to call wglGetExtensionsStringARB. So this is a chicken and egg situation. Just get the function pointer to wglGetExtensionsStringARB and use it to see if you have WGL_ARB_pixel_format and WGL_ARB_multisample.