/*
 * $Id: gltest.c,v 1.8 2005/02/21 00:54:37 potse Exp $
 *
 * Minimal X-windows / OpenGL application
 *
 */

#include <X11/Xlib.h>   /* the most basic X library */
#include <stdio.h>
#include <unistd.h>	/* sleep(), etc.  */
#include <GL/gl.h>      /* OpenGL */
#include <GL/glx.h>     /* OpenGL to X interface */

main(int argc, char **argv) {

  int wdx=300, wdy=200, wx0=300, wy0=200; /* window geometry */  
  Display *dispy;
  int  screen;      /* X-windows display:screen identifiers */
  Window wn;        /* handle of our window */
  XSetWindowAttributes attr;
  XVisualInfo *visinfo;    /* X-windows "visual" handle */
  char *name;            /* application name for X */
  XSizeHints sizehints;
  
  GLXContext ctx;
  static int attribs[] = { GLX_RGBA,
			   GLX_RED_SIZE, 1,
			   GLX_GREEN_SIZE, 1,
			   GLX_BLUE_SIZE, 1,
			   GLX_DEPTH_SIZE, 1,
			   None};

  name = argv[0];
  if(!(dispy = XOpenDisplay(NULL)))  /* connect to the X server */
    fprintf(stderr, "%s: cannot connect to X server\n", name);
    exit(1);
  }  
  screen = DefaultScreen(dispy);
  
  if (!(visinfo = glXChooseVisual(dispy, DefaultScreen(dispy), attribs))){
    printf("trouble\n");
    exit(1);
  }
  
  attr.background_pixel = 0; /* set up arguments for XCreateWindow() */
  attr.border_pixel = 0;
  attr.colormap = XCreateColormap( dispy,
				   RootWindow(dispy, screen),
				   visinfo->visual,
				   AllocNone);
  attr.event_mask = 0;
  wn = XCreateWindow(dispy,
		     RootWindow(dispy, screen),
		     wx0, wy0,
		     wdx, wdy,
		     2,                 /* border width */
		     visinfo->depth,
		     InputOutput,
		     visinfo->visual,
		     CWBackPixel|CWBorderPixel|CWColormap, /* mask */
		     &attr);

  sizehints.x = wx0;     /* hints for the window manager */
  sizehints.y = wy0;
  sizehints.width  = wdx;
  sizehints.height = wdy;
  sizehints.flags = USSize | USPosition;
  XSetNormalHints(dispy, wn, &sizehints);
  XSetStandardProperties(dispy, wn, name, name,
			 None, (char **)NULL, 0, &sizehints);
  
  if(!(ctx = glXCreateContext(dispy, visinfo, 0, GL_TRUE))) {
    printf("Error: glXCreateContext failed\n");
    exit(1);
  }   
  
  XMapWindow(dispy, wn);  /* actually put it on the screen */
  
  glXMakeCurrent(dispy, wn, ctx);  /* connect OpenGL to X */
   
  glColor3f(1.0, 0.5, 0.2);   /* do some OpenGL drawing */
  glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
  glBegin(GL_POLYGON);
    glVertex2f(-0.5, -0.5);
    glVertex2f(-0.5, 0.5);
    glVertex2f(0.5, 0.5);
    glVertex2f(0.5, -0.5);
  glEnd();
  glFlush();   /* execute GL commands */
  
  sleep(4);
  XCloseDisplay(dispy);    /* close the connection to the X server. */
}
