#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <intuition/intuition.h>
#include <clib/exec_protos.h>
#include <clib/graphics_protos.h>

#define SHARED                  /* we use the shared library */
#define GL_APICOMPATIBLE        /* we use stubs from cybergl.lib */

#include "cybergl.h"
#include "cybergl_protos.h"
#include "display.h"

#ifdef SHARED
#include "cybergl_pragmas.h"
extern  struct  Library *CyberGLBase;
#endif

#define WIDTH    600
#define HEIGHT   450

void handle_window_events (struct Window *window)
{
  struct IntuiMessage *msg;
  int                  done = 0;

  while (!done)
  {
    Wait (1L << window->UserPort->mp_SigBit);
    while ((!done) && (msg = (struct IntuiMessage *) GetMsg (window->UserPort)))
    {
      switch (msg->Class)
      {
        case IDCMP_CLOSEWINDOW:
          done = 1;
          break;
      }
      ReplyMsg ((struct Message *) msg);
    }
  }
}

void drawTriangles (int num)
{
  int count;

  glMatrixMode   (GL_PROJECTION);
  glLoadIdentity ();
  glOrtho        (-400.0, 400.0, -300.0, 300.0, 500.0, -500.0);
  srand (time (NULL));
  for (count = 0; count < num; count++)
  {
    glBegin (GL_TRIANGLES);
      glColor3ub (rand () % 256, rand () % 256, rand () % 256);
      glVertex3i (rand () % 800 - 400, rand () % 600 - 300, rand () % 1000 - 500);
      glColor3ub (rand () % 256, rand () % 256, rand () % 256);
      glVertex3i (rand () % 800 - 400, rand () % 600 - 300, rand () % 1000 - 500);
      glColor3ub (rand () % 256, rand () % 256, rand () % 256);
      glVertex3i (rand () % 800 - 400, rand () % 600 - 300, rand () % 1000 - 500);
    glEnd ();
  }
}

void main (int argc, char *argv[])
{
  void     *window;
  window  = openGLWindowTags (WIDTH, HEIGHT, GLWA_Title, "Triangles",
                                             GLWA_IDCMP, IDCMP_CLOSEWINDOW | IDCMP_VANILLAKEY,
                                             GLWA_CloseGadget, TRUE,
                                             GLWA_DepthGadget, TRUE,
                                             GLWA_DragBar,     TRUE,
                                             GLWA_Activate, TRUE,
                                             GLWA_RGBAMode, GL_TRUE,
                                             TAG_DONE);
  if (window)
  {
    glEnable         (GL_DEPTH_TEST);
    glEnable         (GL_DITHER);
    glShadeModel     (GL_SMOOTH);
    glClear          (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawTriangles    (500);
    handle_window_events (getWindow (window));
    closeGLWindow (window);
  }
}
