Unique Color For Every Primitive

From OpenGL Wiki
Jump to: navigation, search

You need to know the depth of each component in your color buffer. The page Specify An Exact Color 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 glColor4ub() 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 void renderPrimitive(X) is a routine to render the primitive.
    Given GLuint makeMask (GLint) returns a bit mask for the number of bits specified.

  uint color32Bit = 0;
  for(i=0; i<numPrims; i++)
     glColor4ub((ubyte *)&color32Bit);

Also, make sure you disable any state that could alter the final color. Again, see the page Specify An Exact Color above for a code snippet to accomplish this.

If you're using this for picking instead of the usual 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.