home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 1.iso / toolbox / src / tutorials / custEducation / opengl1 / demos / glxdino.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-11-11  |  14.0 KB  |  364 lines

  1. /* Copyright (c) Silcon Graphics, Inc. 1995 */
  2.  
  3.  
  4. /* Copyright (c) Mark J. Kilgard, 1994. */
  5.  
  6. /* compile: cc -o glxdino glxdino.c -lGLU -lGL -lXmu -lX11 */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <math.h>               /* for cos(), sin(), and sqrt() */
  11. #include <GL/glx.h>             /* this includes X and gl.h headers */
  12. #include <GL/glu.h>             /* gluPerspective(), gluLookAt(), GLU polygon
  13.                                  * tesselator */
  14. #include <X11/Xatom.h>          /* for XA_RGB_DEFAULT_MAP atom */
  15. #include <X11/Xmu/StdCmap.h>    /* for XmuLookupStandardColormap() */
  16. #include <X11/keysym.h>         /* for XK_Escape keysym */
  17.  
  18. typedef enum {
  19.     RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE,
  20.     LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE, DINOSAUR
  21. }               displayLists;
  22.  
  23. Display *dpy;
  24. Window win;
  25. GLfloat angle = -150;   /* in degrees */
  26. GLboolean doubleBuffer = GL_TRUE, iconic = GL_FALSE, keepAspect = GL_FALSE;
  27. int W = 300, H = 300;
  28. XSizeHints sizeHints = {0};
  29. GLdouble bodyWidth = 2.0;
  30. int configuration[] = {GLX_DOUBLEBUFFER, GLX_RGBA, GLX_DEPTH_SIZE, 16, None};
  31. GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5},
  32.     {11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16},
  33.     {8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2},
  34.     {1, 2} };
  35. GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9},
  36.     {15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10},
  37.     {13, 9}, {11, 11}, {9, 11} };
  38. GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0},
  39.     {12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} };
  40. GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15},
  41.     {9.6, 15.25}, {9, 15.25} };
  42. GLfloat lightZeroPosition[] = {10.0, 4.0, 10.0, 1.0};
  43. GLfloat lightZeroColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */
  44. GLfloat lightOnePosition[] = {-1.0, -2.0, 1.0, 0.0};
  45. GLfloat lightOneColor[] = {0.6, 0.3, 0.2, 1.0};  /* red-tinted */
  46. GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0};
  47.  
  48. void
  49. fatalError(char *message)
  50. {
  51.     fprintf(stderr, "glxdino: %s\n", message);
  52.     exit(1);
  53. }
  54.  
  55. Colormap
  56. getColormap(XVisualInfo * vi)
  57. {
  58.     Status          status;
  59.     XStandardColormap *standardCmaps;
  60.     Colormap        cmap;
  61.     int             i, numCmaps;
  62.  
  63.     /* be lazy; using DirectColor too involved for this example */
  64.     if (vi->class != TrueColor)
  65.         fatalError("no support for non-TrueColor visual");
  66.     /* if no standard colormap but TrueColor, just make an unshared one */
  67.     status = XmuLookupStandardColormap(dpy, vi->screen, vi->visualid,
  68.         vi->depth, XA_RGB_DEFAULT_MAP, /* replace */ False, /* retain */ True);
  69.     if (status == 1) {
  70.         status = XGetRGBColormaps(dpy, RootWindow(dpy, vi->screen),
  71.                              &standardCmaps, &numCmaps, XA_RGB_DEFAULT_MAP);
  72.         if (status == 1)
  73.             for (i = 0; i < numCmaps; i++)
  74.                 if (standardCmaps[i].visualid == vi->visualid) {
  75.                     cmap = standardCmaps[i].colormap;
  76.                     XFree(standardCmaps);
  77.                     return cmap;
  78.                 }
  79.     }
  80.     cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen),
  81.         vi->visual, AllocNone);
  82.     return cmap;
  83. }
  84.  
  85. void
  86. extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize,
  87.     GLdouble thickness, GLuint side, GLuint edge, GLuint whole)
  88. {
  89.     static GLUtriangulatorObj *tobj = NULL;
  90.     GLdouble        vertex[3], dx, dy, len;
  91.     int             i;
  92.     int             count = dataSize / (2 * sizeof(GLfloat));
  93.  
  94.     if (tobj == NULL) {
  95.         tobj = gluNewTess();    /* create and initialize a GLU polygon
  96.                                  * tesselation object */
  97.         gluTessCallback(tobj, GLU_BEGIN, glBegin);
  98.         gluTessCallback(tobj, GLU_VERTEX, glVertex2fv); /* semi-tricky */
  99.         gluTessCallback(tobj, GLU_END, glEnd);
  100.     }
  101.     glNewList(side, GL_COMPILE);
  102.         glShadeModel(GL_SMOOTH); /* smooth minimizes seeing tessellation */
  103.         gluBeginPolygon(tobj);
  104.             for (i = 0; i < count; i++) {
  105.                 vertex[0] = data[i][0];
  106.                 vertex[1] = data[i][1];
  107.                 vertex[2] = 0;
  108.                 gluTessVertex(tobj, vertex, &data[i]);
  109.             }
  110.         gluEndPolygon(tobj);
  111.     glEndList();
  112.     glNewList(edge, GL_COMPILE);
  113.         glShadeModel(GL_FLAT);  /* flat shade keeps angular hands from being
  114.                                  * "smoothed" */
  115.         glBegin(GL_QUAD_STRIP);
  116.         for (i = 0; i <= count; i++) {
  117.             /* mod function handles closing the edge */
  118.             glVertex3f(data[i % count][0], data[i % count][1], 0.0);
  119.             glVertex3f(data[i % count][0], data[i % count][1], thickness);
  120.             /* Calculate a unit normal by dividing by Euclidean distance. We
  121.              * could be lazy and use glEnable(GL_NORMALIZE) so we could pass in
  122.              * arbitrary normals for a very slight performance hit. */
  123.             dx = data[(i + 1) % count][1] - data[i % count][1];
  124.             dy = data[i % count][0] - data[(i + 1) % count][0];
  125.             len = sqrt(dx * dx + dy * dy);
  126.             glNormal3f(dx / len, dy / len, 0.0);
  127.         }
  128.         glEnd();
  129.     glEndList();
  130.     glNewList(whole, GL_COMPILE);
  131.         glFrontFace(GL_CW);
  132.         glCallList(edge);
  133.         glNormal3f(0.0, 0.0, -1.0); /* constant normal for side */
  134.         glCallList(side);
  135.         glPushMatrix();
  136.             glTranslatef(0.0, 0.0, thickness);
  137.             glFrontFace(GL_CCW);
  138.             glNormal3f(0.0, 0.0, 1.0); /* opposite normal for other side */
  139.             glCallList(side);
  140.         glPopMatrix();
  141.     glEndList();
  142. }
  143.  
  144. void
  145. makeDinosaur(void)
  146. {
  147.     GLfloat         bodyWidth = 3.0;
  148.  
  149.     extrudeSolidFromPolygon(body, sizeof(body), bodyWidth,
  150.         BODY_SIDE, BODY_EDGE, BODY_WHOLE);
  151.     extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4,
  152.         ARM_SIDE, ARM_EDGE, ARM_WHOLE);
  153.     extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2,
  154.         LEG_SIDE, LEG_EDGE, LEG_WHOLE);
  155.     extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2,
  156.         EYE_SIDE, EYE_EDGE, EYE_WHOLE);
  157.     glNewList(DINOSAUR, GL_COMPILE);
  158.         glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor);
  159.         glCallList(BODY_WHOLE);
  160.         glPushMatrix();
  161.             glTranslatef(0.0, 0.0, bodyWidth);
  162.             glCallList(ARM_WHOLE);
  163.             glCallList(LEG_WHOLE);
  164.             glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4);
  165.             glCallList(ARM_WHOLE);
  166.             glTranslatef(0.0, 0.0, -bodyWidth / 4);
  167.             glCallList(LEG_WHOLE);
  168.             glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1);
  169.             glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor);
  170.             glCallList(EYE_WHOLE);
  171.         glPopMatrix();
  172.     glEndList();
  173. }
  174.  
  175. void
  176. redraw(void)
  177. {
  178.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  179.     glCallList(DINOSAUR);
  180.     if (doubleBuffer)
  181.         glXSwapBuffers(dpy, win);       /* buffer swap does implicit glFlush */
  182.     else glFlush();             /* explicit flush for single buffered case */
  183. }
  184.  
  185. void
  186. main(int argc, char **argv)
  187. {
  188.     XVisualInfo    *vi;
  189.     Colormap        cmap;
  190.     XSetWindowAttributes swa;
  191.     XWMHints       *wmHints;
  192.     Atom            wmDeleteWindow;
  193.     GLXContext      cx;
  194.     XEvent          event;
  195.     KeySym          ks;
  196.     GLboolean       needRedraw = GL_FALSE, recalcModelView = GL_TRUE;
  197.     char           *display = NULL, *geometry = NULL;
  198.     int             flags, x, y, width, height, lastX, i;
  199.  
  200.     /*** (1) process normal X command line arguments ***/
  201.     for (i = 1; i < argc; i++) {
  202.         if (!strcmp(argv[i], "-geometry")) {
  203.             if (++i >= argc)
  204.                 fatalError("follow -geometry option with geometry parameter");
  205.             geometry = argv[i];
  206.         } else if (!strcmp(argv[i], "-display")) {
  207.             if (++i >= argc)
  208.                 fatalError("follow -display option with display parameter");
  209.             display = argv[i];
  210.         } else if (!strcmp(argv[i], "-iconic")) iconic = GL_TRUE;
  211.         else if (!strcmp(argv[i], "-keepaspect")) keepAspect = GL_TRUE;
  212.         else if (!strcmp(argv[i], "-single")) doubleBuffer = GL_FALSE;
  213.         else fatalError("bad option");
  214.     }
  215.  
  216.     /*** (2) open a connection to the X server ***/
  217.     dpy = XOpenDisplay(display);
  218.     if (dpy == NULL) fatalError("could not open display");
  219.  
  220.     /*** (3) make sure OpenGL's GLX extension supported ***/
  221.     if (!glXQueryExtension(dpy, NULL, NULL))
  222.         fatalError("X server has no OpenGL GLX extension");
  223.  
  224.     /*** (4) find an appropriate visual and a colormap for it ***/
  225.     /* find an OpenGL-capable RGB visual with depth buffer */
  226.     if (!doubleBuffer) goto SingleBufferOverride;
  227.     vi = glXChooseVisual(dpy, DefaultScreen(dpy), configuration);
  228.     if (vi == NULL) {
  229.       SingleBufferOverride:
  230.         vi = glXChooseVisual(dpy, DefaultScreen(dpy), &configuration[1]);
  231.         if (vi == NULL)
  232.             fatalError("no appropriate RGB visual with depth buffer");
  233.         doubleBuffer = GL_FALSE;
  234.     }
  235.     cmap = getColormap(vi);
  236.  
  237.     /*** (5) create an OpenGL rendering context  ***/
  238.     /* create an OpenGL rendering context */
  239.     cx = glXCreateContext(dpy, vi, /* no sharing of display lists */ NULL,
  240.                            /* direct rendering if possible */ GL_TRUE);
  241.     if (cx == NULL) fatalError("could not create rendering context");
  242.  
  243.     /*** (6) create an X window with selected visual and right properties ***/
  244.     flags = XParseGeometry(geometry, &x, &y,
  245.         (unsigned int *) &width, (unsigned int *) &height);
  246.     if (WidthValue & flags) {
  247.         sizeHints.flags |= USSize;
  248.         sizeHints.width = width;
  249.         W = width;
  250.     }
  251.     if (HeightValue & flags) {
  252.         sizeHints.flags |= USSize;
  253.         sizeHints.height = height;
  254.         H = height;
  255.     }
  256.     if (XValue & flags) {
  257.         if (XNegative & flags)
  258.             x = DisplayWidth(dpy, DefaultScreen(dpy)) + x - sizeHints.width;
  259.         sizeHints.flags |= USPosition;
  260.         sizeHints.x = x;
  261.     }
  262.     if (YValue & flags) {
  263.         if (YNegative & flags)
  264.             y = DisplayHeight(dpy, DefaultScreen(dpy)) + y - sizeHints.height;
  265.         sizeHints.flags |= USPosition;
  266.         sizeHints.y = y;
  267.     }
  268.     if (keepAspect) {
  269.         sizeHints.flags |= PAspect;
  270.         sizeHints.min_aspect.x = sizeHints.max_aspect.x = W;
  271.         sizeHints.min_aspect.y = sizeHints.max_aspect.y = H;
  272.     }
  273.     swa.colormap = cmap;
  274.     swa.border_pixel = 0;
  275.     swa.event_mask = ExposureMask | StructureNotifyMask |
  276.         ButtonPressMask | Button1MotionMask | KeyPressMask;
  277.     win = XCreateWindow(dpy, RootWindow(dpy, vi->screen),
  278.                         sizeHints.x, sizeHints.y, W, H,
  279.                         0, vi->depth, InputOutput, vi->visual,
  280.                         CWBorderPixel | CWColormap | CWEventMask, &swa);
  281.     XSetStandardProperties(dpy, win, "OpenGLosaurus", "glxdino",
  282.         None, argv, argc, &sizeHints);
  283.     wmHints = XAllocWMHints();
  284.     wmHints->initial_state = iconic ? IconicState : NormalState;
  285.     wmHints->flags = StateHint;
  286.     XSetWMHints(dpy, win, wmHints);
  287.     wmDeleteWindow = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  288.     XSetWMProtocols(dpy, win, &wmDeleteWindow, 1);
  289.  
  290.     /*** (7) bind the rendering context to the window ***/
  291.     glXMakeCurrent(dpy, win, cx);
  292.  
  293.     /*** (8) make the desired display lists ***/
  294.     makeDinosaur();
  295.  
  296.     /*** (9) configure the OpenGL context for rendering ***/
  297.     glEnable(GL_CULL_FACE);     /* ~50% better perfomance than no back-face
  298.                                  * culling on Entry Indigo */
  299.     glEnable(GL_DEPTH_TEST);    /* enable depth buffering */
  300.     glEnable(GL_LIGHTING);      /* enable lighting */
  301.     glMatrixMode(GL_PROJECTION);/* set up projection transform */
  302.     gluPerspective( /* field of view in degree */ 40.0, /* aspect ratio */ 1.0,
  303.                     /* Z near */ 1.0, /* Z far */ 40.0);
  304.     glMatrixMode(GL_MODELVIEW); /* now change to modelview */
  305.     gluLookAt(0.0, 0.0, 30.0,   /* eye is at (0,0,30) */
  306.               0.0, 0.0, 0.0,    /* center is at (0,0,0) */
  307.               0.0, 1.0, 0.);    /* up is in postivie Y direction */
  308.     glPushMatrix();             /* dummy push so we can pop on model recalc */
  309.     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  310.     glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
  311.     glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor);
  312.     glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
  313.     glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
  314.     glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
  315.     glLightfv(GL_LIGHT1, GL_DIFFUSE, lightOneColor);
  316.     glEnable(GL_LIGHT0);
  317.     glEnable(GL_LIGHT1);        /* enable both lights */
  318.  
  319.     /*** (10) request the X window to be displayed on the screen ***/
  320.     XMapWindow(dpy, win);
  321.  
  322.     /*** (11) dispatch X events ***/
  323.     while (1) {
  324.         do {
  325.             XNextEvent(dpy, &event);
  326.             switch (event.type) {
  327.             case ConfigureNotify:
  328.                 glViewport(0, 0,
  329.                     event.xconfigure.width, event.xconfigure.height);
  330.                 /* fall through... */
  331.             case Expose:
  332.                 needRedraw = GL_TRUE;
  333.                 break;
  334.             case MotionNotify:
  335.                 recalcModelView = GL_TRUE;
  336.                 angle -= (lastX - event.xmotion.x);
  337.             case ButtonPress:
  338.                 lastX = event.xbutton.x;
  339.                 break;
  340.             case KeyPress:
  341.                 ks = XLookupKeysym((XKeyEvent *) & event, 0);
  342.                 if (ks == XK_Escape) exit(0);
  343.                 break;
  344.             case ClientMessage:
  345.                 if (event.xclient.data.l[0] == wmDeleteWindow) exit(0);
  346.                 break;
  347.             }
  348.         } while (XPending(dpy));/* loop to compress events */
  349.         if (recalcModelView) {
  350.             glPopMatrix();      /* pop old rotated matrix (or dummy matrix if
  351.                                  * first time) */
  352.             glPushMatrix();
  353.             glRotatef(angle, 0.0, 1.0, 0.0);
  354.             glTranslatef(-8, -8, -bodyWidth / 2);
  355.             recalcModelView = GL_FALSE;
  356.             needRedraw = GL_TRUE;
  357.         }
  358.         if (needRedraw) {
  359.             redraw();
  360.             needRedraw = GL_FALSE;
  361.         }
  362.     }
  363. }
  364.