Quantcast
Channel: The Code Log » C
Viewing all articles
Browse latest Browse all 10

OpenGL Image Generator

$
0
0

The idea behind this post is very simple: generate m x n grid of pixels, with each pixel having a random color. Every time the user clicks the mouse or presses the ‘g’ key, a new random color is generated for each pixel. Since we are using the R, G and B components to represent a color, we can have up to 256 * 256 * 256 = 16,777,216 colors per pixel. Assuming m = 512 and n = 512, the total count of pixels is 512 * 512 = 2,704 pixels. The number of possible images that can be generated is 16,777,216 ^ 2,704 = 4.3913556324838811971996510547776e+19535. Suppose we are generating an image every 1 second, then it would take 1.4276931285385069435340105645214e+19528 years to generate all of the possible combinations, including images of our friends, nature, the past, the present, the future or some electronic gadget we have not yet invented. Well, a very unrealistic time. Limiting m x n to 16 x 16 and limiting colors to only black and white, we can generate up to 65,536 images in about 18 hours. Seems possible; maybe even worth doing.

The goal here is to demonstrate the usage of the glDrawPixels function to draw pixels in the frame buffer. First, we will create a 3-dimensional array representing m x n pixels having 3 color components.

GLubyte buffer[m][n][3];

Next, we need to generate random colors for each pixel.

//-------------------------------------------------------------------------
//  Generate new image with random colors
//-------------------------------------------------------------------------
void generateImage ()
{
    int i, j;

    for (i = 0; i < WINDOW_WIDTH; i++)
    {
        for (j = 0; j < WINDOW_HEIGHT; j++)
        {
            buffer[i][j][0] = (GLubyte) (rand () % 256);
            buffer[i][j][1] = (GLubyte) (rand () % 256);
            buffer[i][j][2] = (GLubyte) (rand () % 256);
        }
    }
}

Finally, we pass the buffer to the glDrawPixels, which will write the pixel data from the memory into the frame buffer.

void display ()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawPixels(m, n, GL_RGB, GL_UNSIGNED_BYTE, buffer);
    glutSwapBuffers ();
}

Download full source code here. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library.
Filed under: C, OpenGL Tagged: glDrawPixels

Viewing all articles
Browse latest Browse all 10

Trending Articles