Search code examples
c++visual-c++openglglut

Displayin two different images on a window in OpenGL


I am trying to display two different images on a window using OpenGL. Something like what has been shown in the below image.

First image on the left side of window: img [nc x nr]

Second image on the right side of window: img2 [nc x ns]

enter image description here image

I have written the below code for display routine:

void display(void)
{
   ///////////////////First Image////////////////////////
   glViewport( (GLsizei) 0, (GLsizei) 0, (GLsizei) nc, (GLsizei) nr );
   glClear(GL_COLOR_BUFFER_BIT);
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);               

   glRasterPos2i(0, 0);                                 
   glDrawPixels(nc,nr, GL_RGB, GL_UNSIGNED_BYTE, img);

   ///////////////////Second Image////////////////////////
   glViewport( (GLsizei) 0, (GLsizei) nc, (GLsizei) nc, (GLsizei) ns );
   glClear(GL_COLOR_BUFFER_BIT);
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);               

   glRasterPos2i(0, nc);                                    
   glDrawPixels(nc,ns, GL_RGB, GL_UNSIGNED_BYTE, img2); 
   //////////////////////////////////////////////////////

   glutSwapBuffers();                                   

}

When I run the program the window displays nothing; but when I comment out the display code for the second image, I can see image 1 in the left side of window.

Can anyone see what is wrong with my code?


Solution

  • void display(void)
    {
       // Size the viewport to be big enough for two images
       glViewport( (GLsizei) 0, (GLsizei) 0, (GLsizei) screen_width, (GLsizei) screen_height );
       glClear(GL_COLOR_BUFFER_BIT);
       glPixelStorei(GL_UNPACK_ALIGNMENT, 1);               
    
       // Position first image starting at 0, 0
       glRasterPos2i(0, 0);   
       // Get the width and height of image as first two params                              
       glDrawPixels(img.width,img.height, GL_RGB, GL_UNSIGNED_BYTE, img);
    
       // Position second image starting after the width of the first image
       glRasterPos2i(img.width, 0);   
       // get width and height of second image as first two params                                 
       glDrawPixels(img2.width,img2.height, GL_RGB, GL_UNSIGNED_BYTE, img2); 
    
       glutSwapBuffers();
    
    }
    

    This is the general idea. Obviously screen_height etc are named differently in your app but the viewport should be set to the size of the screen. The Raster position should be the start position of the images and the first 2 params of DrawPixels should be the width and height of your images. Each image does not need its own viewport, as this would be highly unmanageable(and extremely slow) when the number of images/models grow.