Unique Color For Every Primitive

From OpenGL Wiki
Revision as of 16:07, 30 April 2006 by Marco (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

You need to know the depth of each component in your color buffer. The previous question contains the code to obtain these values. The depth tells you the number of unique color values you can render. For example, if you use the code from the previous question, which retrieves the color depth in redBits, greenBits, and blueBits, the number of unique colors available is 2^(redBits+greenBits+blueBits).

If this number is greater than the number of primitives you want to render, there is no problem. You need to use glColor3ui() (or glColor3us(), etc) to specify each color, and store the desired color in the most significant bits of each parameter. You can code a loop to render each primitive in a unique color with the following:

    Given: numPrims is the number of primitives to render.
    Given void renderPrimitive(unsigned long) is a routine to render the primitive specified by the given parameter index.
    Given GLuint makeMask (GLint) returns a bit mask for the number of bits specified.

  GLuint redMask = makeMask(redBits) << (greenBits + blueBits);
  GLuint greenMask = makeMask(greenBits) << blueBits;
  GLuint blueMask = makeMask(blueBits);
  int redShift = 32 - (redBits+greenBits+blueBits);
  int greenShift = 32 - (greenBits+blueBits);
  int blueShift = 32 - blueBits;
  unsigned long indx;
  for (indx=0; indx<numPrims, indx++) {
     glColor3ui (indx & redMask << redShift,
                 indx & greenMask << greenShift,
                 indx & blueMask << blueShift);
     renderPrimitive (indx);

Also, make sure you disable any state that could alter the final color. See the question above for a code snippet to accomplish this.

If you're using this for picking instead of the ususal Selection feature, any color subsequently read back from the color buffer can easily be converted to the index value of the primitive rendered in that color.