added the src/glut files eradbackport
authorJohn Tsiombikas <nuclear@member.fsf.org>
Tue, 16 Jun 2020 06:45:55 +0000 (09:45 +0300)
committerJohn Tsiombikas <nuclear@member.fsf.org>
Tue, 16 Jun 2020 06:45:55 +0000 (09:45 +0300)
GNUmakefile
src/glut/audio.c [new file with mode: 0644]
src/glut/gfx.h [new file with mode: 0644]
src/glut/main.c [new file with mode: 0644]
src/glut/miniglut.c [new file with mode: 0644]
src/glut/miniglut.h [new file with mode: 0644]
src/glut/w32_dirent.c [new file with mode: 0644]
src/glut/w32_dirent.h [new file with mode: 0644]

index c6e94c2..0054bbc 100644 (file)
@@ -15,7 +15,7 @@ warn = -pedantic -Wall -Wno-unused-variable -Wno-unused-function
 #opt = -O3 -ffast-math
 dbg = -g
 
-CFLAGS = $(arch) $(warn) $(opt) -fno-pie -fno-strict-aliasing $(dbg) $(inc)
+CFLAGS = $(arch) $(warn) -MMD $(opt) -fno-pie -fno-strict-aliasing $(dbg) $(inc)
 LDFLAGS = $(arch) -no-pie -Llibs/imago -Llibs/mikmod -limago -lmikmod \
                  $(sndlib_$(sys)) -lm
 
@@ -57,10 +57,6 @@ $(bin): $(obj) imago mikmod
 
 src/data.o: src/data.asm $(bindata)
 
-%.d: %.c
-       @echo dep $@
-       @$(CPP) $(CFLAGS) $< -MM -MT $(@:.d=.o) >$@
-
 .PHONY: libs
 libs: imago anim mikmod
 
diff --git a/src/glut/audio.c b/src/glut/audio.c
new file mode 100644 (file)
index 0000000..c776d3b
--- /dev/null
@@ -0,0 +1,237 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#if defined(__WATCOMC__) || defined(_WIN32) || defined(__DJGPP__)
+#include <malloc.h>
+#else
+#include <alloca.h>
+#endif
+#include "mikmod.h"
+#include "audio.h"
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <pthread.h>
+#include <unistd.h>
+#endif
+
+#define SET_MUS_VOL(vol) \
+       do { \
+               int mv = (vol) * vol_master >> 9; \
+               Player_SetVolume(mv ? mv + 1 : 0); \
+       } while(0)
+
+static struct au_module *curmod;
+static int vol_master, vol_mus, vol_sfx;
+
+#ifdef _WIN32
+static DWORD WINAPI upd_thread(void *cls);
+#else
+static void *update(void *cls);
+#endif
+
+int au_init(void)
+{
+       curmod = 0;
+       vol_master = vol_mus = vol_sfx = 255;
+
+#if defined(__linux__)
+       MikMod_RegisterDriver(&drv_alsa);
+#elif defined(__FreeBSD__)
+       MikMod_RegisterDriver(&drv_oss);
+#elif defined(__sgi__)
+       MikMod_RegisterDriver(&drv_sgi);
+#elif defined(_WIN32)
+       MikMod_RegisterDriver(&drv_ds);
+#else
+       MikMod_RegisterDriver(&drv_nos);
+#endif
+
+       MikMod_RegisterLoader(&load_it);
+       MikMod_RegisterLoader(&load_mod);
+       MikMod_RegisterLoader(&load_s3m);
+       MikMod_RegisterLoader(&load_xm);
+
+       if(MikMod_Init("")) {
+               fprintf(stderr, "failed ot initialize mikmod: %s\n", MikMod_strerror(MikMod_errno));
+               return -1;
+       }
+       MikMod_InitThreads();
+
+       {
+#ifdef _WIN32
+               HANDLE thr;
+               if((thr = CreateThread(0, 0, update, 0, 0, 0))) {
+                       CloseHandle(thr);
+               }
+#else
+               pthread_t upd_thread;
+               if(pthread_create(&upd_thread, 0, update, 0) == 0) {
+                       pthread_detach(upd_thread);
+               }
+#endif
+       }
+       return 0;
+}
+
+void au_shutdown(void)
+{
+       curmod = 0;
+       MikMod_Exit();
+}
+
+struct au_module *au_load_module(const char *fname)
+{
+       struct au_module *mod;
+       MODULE *mikmod;
+       char *name = 0, *end;
+
+       if(!(mod = malloc(sizeof *mod))) {
+               fprintf(stderr, "au_load_module: failed to allocate module\n");
+               return 0;
+       }
+
+       if(!(mikmod = Player_Load(fname, 128, 0))) {
+               fprintf(stderr, "au_load_module: failed to load module: %s: %s\n",
+                               fname, MikMod_strerror(MikMod_errno));
+               free(mod);
+               return 0;
+       }
+       mod->impl = mikmod;
+
+       if(mikmod->songname && *mikmod->songname) {
+               name = alloca(strlen(mikmod->songname) + 1);
+               strcpy(name, mikmod->songname);
+
+               end = name + strlen(name) - 1;
+               while(end >= name && isspace(*end)) {
+                       *end-- = 0;
+               }
+               if(!*name) name = 0;
+       }
+
+       if(!name) {
+               /* fallback to using the filename */
+               if((name = strrchr(fname, '/')) || (name = strrchr(fname, '\\'))) {
+                       name++;
+               } else {
+                       name = (char*)fname;
+               }
+       }
+
+       if(!(mod->name = malloc(strlen(name) + 1))) {
+               fprintf(stderr, "au_load_module: mod->name malloc failed\n");
+               Player_Free(mod->impl);
+               free(mod);
+               return 0;
+       }
+       strcpy(mod->name, name);
+
+       printf("loaded module \"%s\" (%s)\n", name, fname);
+       return mod;
+}
+
+void au_free_module(struct au_module *mod)
+{
+       if(!mod) return;
+
+       if(mod == curmod) {
+               au_stop_module(curmod);
+       }
+       Player_Free(mod->impl);
+       free(mod->name);
+       free(mod);
+}
+
+int au_play_module(struct au_module *mod)
+{
+       if(curmod) {
+               if(curmod == mod) return 0;
+               au_stop_module(curmod);
+       }
+
+       Player_Start(mod->impl);
+       SET_MUS_VOL(vol_mus);
+       curmod = mod;
+       return 0;
+}
+
+void au_update(void)
+{
+       if(!curmod) return;
+
+       if(!Player_Active()) {
+               Player_Stop();
+               curmod = 0;
+       }
+}
+
+#ifdef _WIN32
+static DWORD WINAPI upd_thread(void *cls);
+#else
+static void *update(void *cls)
+#endif
+{
+       for(;;) {
+               if(Player_Active()) {
+                       MikMod_Update();
+               }
+#ifdef _WIN32
+               Sleep(10);
+#else
+               usleep(10000);
+#endif
+       }
+       return 0;
+}
+
+int au_stop_module(struct au_module *mod)
+{
+       if(mod && curmod != mod) return -1;
+       if(!curmod) return -1;
+
+       Player_Stop();
+       curmod = 0;
+       return 0;
+}
+
+int au_module_state(struct au_module *mod)
+{
+       if(mod) {
+               return curmod == mod ? AU_PLAYING : AU_STOPPED;
+       }
+       return curmod ? AU_PLAYING : AU_STOPPED;
+}
+
+int au_volume(int vol)
+{
+       AU_VOLADJ(vol_master, vol);
+       if(vol != vol_master) {
+               vol_master = vol;
+
+               au_sfx_volume(vol_sfx);
+               au_music_volume(vol_mus);
+       }
+       return vol_master;
+}
+
+int au_sfx_volume(int vol)
+{
+       AU_VOLADJ(vol_sfx, vol);
+       vol_sfx = vol;
+       /* TODO */
+       return vol_sfx;
+}
+
+int au_music_volume(int vol)
+{
+       AU_VOLADJ(vol_mus, vol);
+       vol_mus = vol;
+
+       if(curmod) {
+               SET_MUS_VOL(vol);
+       }
+       return vol_mus;
+}
diff --git a/src/glut/gfx.h b/src/glut/gfx.h
new file mode 100644 (file)
index 0000000..8d5d81d
--- /dev/null
@@ -0,0 +1,31 @@
+#ifndef GFX_H_
+#define GFX_H_
+
+#include "inttypes.h"
+
+struct video_mode {
+       uint16_t mode;
+       short xsz, ysz, bpp, pitch;
+       short rbits, gbits, bbits;
+       short rshift, gshift, bshift;
+       uint32_t rmask, gmask, bmask;
+       uint32_t fb_addr;
+       short max_pages;
+       uint32_t bank_size;
+};
+
+struct video_mode *video_modes(void);
+int num_video_modes(void);
+
+#define VMODE_CURRENT  (-1)
+struct video_mode *get_video_mode(int idx);
+
+int match_video_mode(int xsz, int ysz, int bpp);
+
+/* argument is the mode list index [0, nmodes-1] */
+void *set_video_mode(int idx, int nbuf);
+
+void blit_frame(void *pixels, int vsync);
+void wait_vsync(void);
+
+#endif /* GFX_H_ */
diff --git a/src/glut/main.c b/src/glut/main.c
new file mode 100644 (file)
index 0000000..0e766bd
--- /dev/null
@@ -0,0 +1,521 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <assert.h>
+#include "miniglut.h"
+#include "demo.h"
+#include "gfx.h"
+#include "gfxutil.h"
+#include "timer.h"
+#include "audio.h"
+#include "cfgopt.h"
+#include "cgmath/cgmath.h"
+#include "util.h"
+
+static void display(void);
+static void idle(void);
+static void reshape(int x, int y);
+static void keydown(unsigned char key, int x, int y);
+static void keyup(unsigned char key, int x, int y);
+static void skeydown(int key, int x, int y);
+static void skeyup(int key, int x, int y);
+static int translate_special(int skey);
+static void mouse_button(int bn, int st, int x, int y);
+static void mouse_motion(int x, int y);
+static void sball_motion(int x, int y, int z);
+static void sball_rotate(int x, int y, int z);
+static void sball_button(int bn, int st);
+static void recalc_sball_matrix(float *xform);
+static unsigned int next_pow2(unsigned int x);
+static void set_fullscreen(int fs);
+static void set_vsync(int vsync);
+
+int have_joy;
+unsigned int joy_bnstate, joy_bndiff, joy_bnpress;
+
+#define MODE(w, h)     \
+       {0, w, h, 16, w * 2, 5, 6, 5, 11, 5, 0, 0xf800, 0x7e0, 0x1f, 0xbadf00d, 2, 0}
+static struct video_mode vmodes[] = {
+       MODE(320, 240), MODE(400, 300), MODE(512, 384), MODE(640, 480),
+       MODE(800, 600), MODE(1024, 768), MODE(1280, 960), MODE(1280, 1024),
+       MODE(1920, 1080), MODE(1600, 1200), MODE(1920, 1200)
+};
+static struct video_mode *cur_vmode;
+
+static unsigned int num_pressed;
+static unsigned char keystate[256];
+
+static unsigned long start_time;
+static unsigned int modkeys;
+
+static int win_width, win_height;
+static float win_aspect;
+static unsigned int tex;
+
+#ifdef __unix__
+#include <GL/glx.h>
+static Display *xdpy;
+static Window xwin;
+
+static void (*glx_swap_interval_ext)();
+static void (*glx_swap_interval_sgi)();
+#endif
+#ifdef _WIN32
+#include <windows.h>
+static PROC wgl_swap_interval_ext;
+#endif
+
+static int use_sball;
+static cgm_vec3 pos = {0, 0, 0};
+static cgm_quat rot = {0, 0, 0, 1};
+
+
+int main(int argc, char **argv)
+{
+       glutInit(&argc, argv);
+       glutInitWindowSize(800, 600);
+       glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
+       glutCreateWindow("Mindlapse");
+
+       glutDisplayFunc(display);
+       glutIdleFunc(idle);
+       glutReshapeFunc(reshape);
+       glutKeyboardFunc(keydown);
+       glutKeyboardUpFunc(keyup);
+       glutSpecialFunc(skeydown);
+       glutSpecialUpFunc(skeyup);
+       glutMouseFunc(mouse_button);
+       glutMotionFunc(mouse_motion);
+       glutPassiveMotionFunc(mouse_motion);
+       glutSpaceballMotionFunc(sball_motion);
+       glutSpaceballRotateFunc(sball_rotate);
+       glutSpaceballButtonFunc(sball_button);
+
+       glutSetCursor(GLUT_CURSOR_NONE);
+
+       glEnable(GL_TEXTURE_2D);
+       glEnable(GL_CULL_FACE);
+
+
+       if(!set_video_mode(match_video_mode(FB_WIDTH, FB_HEIGHT, FB_BPP), 1)) {
+               return 1;
+       }
+
+#ifdef __unix__
+       xdpy = glXGetCurrentDisplay();
+       xwin = glXGetCurrentDrawable();
+
+       if(!(glx_swap_interval_ext = glXGetProcAddress((unsigned char*)"glXSwapIntervalEXT"))) {
+               glx_swap_interval_sgi = glXGetProcAddress((unsigned char*)"glXSwapIntervalSGI");
+       }
+#endif
+#ifdef _WIN32
+       wgl_swap_interval_ext = wglGetProcAddress("wglSwapIntervalEXT");
+#endif
+
+       if(au_init() == -1) {
+               return 1;
+       }
+       time_msec = 0;
+       if(demo_init(argc, argv) == -1) {
+               return 1;
+       }
+       atexit(demo_cleanup);
+
+       if(opt.fullscreen) {
+               set_fullscreen(opt.fullscreen);
+       }
+
+       reset_timer();
+
+       glutMainLoop();
+       return 0;
+}
+
+void demo_quit(void)
+{
+       exit(0);
+}
+
+struct video_mode *video_modes(void)
+{
+       return vmodes;
+}
+
+int num_video_modes(void)
+{
+       return sizeof vmodes / sizeof *vmodes;
+}
+
+struct video_mode *get_video_mode(int idx)
+{
+       if(idx == VMODE_CURRENT) {
+               return cur_vmode;
+       }
+       return vmodes + idx;
+}
+
+int match_video_mode(int xsz, int ysz, int bpp)
+{
+       struct video_mode *vm = vmodes;
+       int i, count = num_video_modes();
+
+       for(i=0; i<count; i++) {
+               if(vm->xsz == xsz && vm->ysz == ysz && vm->bpp == bpp) {
+                       return i;
+               }
+               vm++;
+       }
+       return -1;
+}
+
+static int tex_xsz, tex_ysz;
+static uint32_t *convbuf;
+static int convbuf_size;
+
+void *set_video_mode(int idx, int nbuf)
+{
+       struct video_mode *vm = vmodes + idx;
+
+       if(cur_vmode == vm) {
+               return vmem;
+       }
+
+       glGenTextures(1, &tex);
+       glBindTexture(GL_TEXTURE_2D, tex);
+
+       tex_xsz = next_pow2(vm->xsz);
+       tex_ysz = next_pow2(vm->ysz);
+       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_xsz, tex_ysz, 0, GL_RGBA,
+                       GL_UNSIGNED_BYTE, 0);
+       if(opt.scaler == SCALER_LINEAR) {
+               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+       } else {
+               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+       }
+
+       glMatrixMode(GL_TEXTURE);
+       glLoadIdentity();
+       glScalef((float)vm->xsz / tex_xsz, (float)vm->ysz / tex_ysz, 1);
+
+       if(vm->xsz * vm->ysz > convbuf_size) {
+               convbuf_size = vm->xsz * vm->ysz;
+               free(convbuf);
+               convbuf = malloc(convbuf_size * sizeof *convbuf);
+       }
+
+       if(demo_resizefb(vm->xsz, vm->ysz, vm->bpp) == -1) {
+               fprintf(stderr, "failed to allocate virtual framebuffer\n");
+               return 0;
+       }
+       vmem = fb_pixels;
+
+       cur_vmode = vm;
+       return vmem;
+}
+
+void wait_vsync(void)
+{
+}
+
+void blit_frame(void *pixels, int vsync)
+{
+       int i;
+       uint32_t *dptr = convbuf;
+       uint16_t *sptr = pixels;
+       static int prev_vsync = -1;
+
+       if(vsync != prev_vsync) {
+               set_vsync(vsync);
+               prev_vsync = vsync;
+       }
+
+       for(i=0; i<FB_WIDTH * FB_HEIGHT; i++) {
+               int r = UNPACK_R16(*sptr);
+               int g = UNPACK_G16(*sptr);
+               int b = UNPACK_B16(*sptr);
+               *dptr++ = PACK_RGB32(b, g, r);
+               sptr++;
+       }
+
+       glBindTexture(GL_TEXTURE_2D, tex);
+       glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, FB_WIDTH, FB_HEIGHT, GL_RGBA,
+                       GL_UNSIGNED_BYTE, convbuf);
+
+       glMatrixMode(GL_MODELVIEW);
+       glLoadIdentity();
+       if(win_aspect >= FB_ASPECT) {
+               glScalef(FB_ASPECT / win_aspect, 1, 1);
+       } else {
+               glScalef(1, win_aspect / FB_ASPECT, 1);
+       }
+
+       glClear(GL_COLOR_BUFFER_BIT);
+
+       glBegin(GL_QUADS);
+       glTexCoord2f(0, 1);
+       glVertex2f(-1, -1);
+       glTexCoord2f(1, 1);
+       glVertex2f(1, -1);
+       glTexCoord2f(1, 0);
+       glVertex2f(1, 1);
+       glTexCoord2f(0, 0);
+       glVertex2f(-1, 1);
+       glEnd();
+
+       glutSwapBuffers();
+       assert(glGetError() == GL_NO_ERROR);
+}
+
+int kb_isdown(int key)
+{
+       switch(key) {
+       case KB_ANY:
+               return num_pressed;
+
+       case KB_ALT:
+               return keystate[KB_LALT] + keystate[KB_RALT];
+
+       case KB_CTRL:
+               return keystate[KB_LCTRL] + keystate[KB_RCTRL];
+       }
+
+       if(isalpha(key)) {
+               key = tolower(key);
+       }
+       return keystate[key];
+}
+
+/* timer */
+void init_timer(int res_hz)
+{
+}
+
+void reset_timer(void)
+{
+       start_time = glutGet(GLUT_ELAPSED_TIME);
+}
+
+unsigned long get_msec(void)
+{
+       return glutGet(GLUT_ELAPSED_TIME) - start_time;
+}
+
+#ifdef _WIN32
+#include <windows.h>
+
+void sleep_msec(unsigned long msec)
+{
+       Sleep(msec);
+}
+
+#else
+#include <unistd.h>
+
+void sleep_msec(unsigned long msec)
+{
+       usleep(msec * 1000);
+}
+#endif
+
+static void display(void)
+{
+       recalc_sball_matrix(sball_matrix);
+
+       time_msec = get_msec();
+       demo_draw();
+}
+
+static void idle(void)
+{
+       glutPostRedisplay();
+}
+
+static void reshape(int x, int y)
+{
+       win_width = x;
+       win_height = y;
+       win_aspect = (float)x / (float)y;
+       glViewport(0, 0, x, y);
+}
+
+static void keydown(unsigned char key, int x, int y)
+{
+       modkeys = glutGetModifiers();
+
+       if((key == '\n' || key == '\r') && (modkeys & GLUT_ACTIVE_ALT)) {
+               opt.fullscreen ^= 1;
+               set_fullscreen(opt.fullscreen);
+               return;
+       }
+       keystate[key] = 1;
+       demo_keyboard(key, 1);
+}
+
+static void keyup(unsigned char key, int x, int y)
+{
+       keystate[key] = 0;
+       demo_keyboard(key, 0);
+}
+
+static void skeydown(int key, int x, int y)
+{
+       if(key == GLUT_KEY_F5) {
+               opt.scaler = (opt.scaler + 1) % NUM_SCALERS;
+
+               if(opt.scaler == SCALER_LINEAR) {
+                       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+                       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+               } else {
+                       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+                       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+               }
+       }
+       key = translate_special(key);
+       keystate[key] = 1;
+       demo_keyboard(key, 1);
+}
+
+static void skeyup(int key, int x, int y)
+{
+       key = translate_special(key);
+       keystate[key] = 0;
+       demo_keyboard(key, 0);
+}
+
+static int translate_special(int skey)
+{
+       switch(skey) {
+       case 127:
+               return 127;
+       case GLUT_KEY_LEFT:
+               return KB_LEFT;
+       case GLUT_KEY_RIGHT:
+               return KB_RIGHT;
+       case GLUT_KEY_UP:
+               return KB_UP;
+       case GLUT_KEY_DOWN:
+               return KB_DOWN;
+       case GLUT_KEY_PAGE_UP:
+               return KB_PGUP;
+       case GLUT_KEY_PAGE_DOWN:
+               return KB_PGDN;
+       case GLUT_KEY_HOME:
+               return KB_HOME;
+       case GLUT_KEY_END:
+               return KB_END;
+       default:
+               if(skey >= GLUT_KEY_F1 && skey <= GLUT_KEY_F12) {
+                       return KB_F1 + skey - GLUT_KEY_F1;
+               }
+       }
+       return 0;
+}
+
+static void map_mouse_pos(int *xp, int *yp)
+{
+       int x = *xp;
+       int y = *yp;
+
+       /* TODO */
+       *xp = x * FB_WIDTH / win_width;
+       *yp = y * FB_HEIGHT / win_height;
+}
+
+static void mouse_button(int bn, int st, int x, int y)
+{
+       map_mouse_pos(&x, &y);
+       mouse_x = x;
+       mouse_y = y;
+
+       if(st == GLUT_DOWN) {
+               mouse_bmask |= 1 << bn;
+       } else {
+               mouse_bmask &= ~(1 << bn);
+       }
+}
+
+static void mouse_motion(int x, int y)
+{
+       map_mouse_pos(&x, &y);
+       mouse_x = x;
+       mouse_y = y;
+}
+
+static void sball_motion(int x, int y, int z)
+{
+       pos.x += x * 0.001f;
+       pos.y += y * 0.001f;
+       pos.z -= z * 0.001f;
+
+}
+
+static void sball_rotate(int rx, int ry, int rz)
+{
+       if(rx | ry | rz) {
+               float s = (float)rsqrt(rx * rx + ry * ry + rz * rz);
+               cgm_qrotate(&rot, 0.001f / s, rx * s, ry * s, -rz * s);
+       }
+}
+
+static void sball_button(int bn, int st)
+{
+       pos.x = pos.y = pos.z = 0;
+       rot.x = rot.y = rot.z = 0;
+       rot.w = 1;
+}
+
+static void recalc_sball_matrix(float *xform)
+{
+       cgm_mrotation_quat(xform, &rot);
+       xform[12] = pos.x;
+       xform[13] = pos.y;
+       xform[14] = pos.z;
+}
+
+
+static unsigned int next_pow2(unsigned int x)
+{
+       x--;
+       x |= x >> 1;
+       x |= x >> 2;
+       x |= x >> 4;
+       x |= x >> 8;
+       x |= x >> 16;
+       return x + 1;
+}
+
+static void set_fullscreen(int fs)
+{
+       static int win_x, win_y;
+
+       if(fs) {
+               win_x = glutGet(GLUT_WINDOW_WIDTH);
+               win_y = glutGet(GLUT_WINDOW_HEIGHT);
+               glutFullScreen();
+       } else {
+               glutReshapeWindow(win_x, win_y);
+       }
+}
+
+#ifdef __unix__
+static void set_vsync(int vsync)
+{
+       vsync = vsync ? 1 : 0;
+       if(glx_swap_interval_ext) {
+               glx_swap_interval_ext(xdpy, xwin, vsync);
+       } else if(glx_swap_interval_sgi) {
+               glx_swap_interval_sgi(vsync);
+       }
+}
+#endif
+#ifdef WIN32
+static void set_vsync(int vsync)
+{
+       if(wgl_swap_interval_ext) {
+               wgl_swap_interval_ext(vsync ? 1 : 0);
+       }
+}
+#endif
diff --git a/src/glut/miniglut.c b/src/glut/miniglut.c
new file mode 100644 (file)
index 0000000..eb63946
--- /dev/null
@@ -0,0 +1,2094 @@
+/*
+MiniGLUT - minimal GLUT subset without dependencies
+Copyright (C) 2020  John Tsiombikas <nuclear@member.fsf.org>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+#if defined(__unix__)
+
+#include <X11/Xlib.h>
+#include <X11/keysym.h>
+#include <X11/cursorfont.h>
+#include <GL/glx.h>
+#define BUILD_X11
+
+#ifndef GLX_SAMPLE_BUFFERS_ARB
+#define GLX_SAMPLE_BUFFERS_ARB 100000
+#define GLX_SAMPLES_ARB                        100001
+#endif
+#ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
+#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB       0x20b2
+#endif
+
+static Display *dpy;
+static Window win, root;
+static int scr;
+static GLXContext ctx;
+static Atom xa_wm_proto, xa_wm_del_win;
+static Atom xa_net_wm_state, xa_net_wm_state_fullscr;
+static Atom xa_motif_wm_hints;
+static Atom xa_motion_event, xa_button_press_event, xa_button_release_event, xa_command_event;
+static unsigned int evmask;
+
+static int have_netwm_fullscr(void);
+
+#elif defined(_WIN32)
+
+#include <windows.h>
+#define BUILD_WIN32
+
+static HRESULT CALLBACK handle_message(HWND win, unsigned int msg, WPARAM wparam, LPARAM lparam);
+
+static HINSTANCE hinst;
+static HWND win;
+static HDC dc;
+static HGLRC ctx;
+
+#else
+#error unsupported platform
+#endif
+#include <GL/gl.h>
+#include "miniglut.h"
+
+struct ctx_info {
+       int rsize, gsize, bsize, asize;
+       int zsize, ssize;
+       int dblbuf;
+       int samples;
+       int stereo;
+       int srgb;
+};
+
+static void cleanup(void);
+static void create_window(const char *title);
+static void get_window_pos(int *x, int *y);
+static void get_window_size(int *w, int *h);
+static void get_screen_size(int *scrw, int *scrh);
+
+static long get_msec(void);
+static void panic(const char *msg);
+static void sys_exit(int status);
+static int sys_write(int fd, const void *buf, int count);
+
+
+static int init_x = -1, init_y, init_width = 256, init_height = 256;
+static unsigned int init_mode;
+
+static struct ctx_info ctx_info;
+static int cur_cursor = GLUT_CURSOR_INHERIT;
+
+static glut_cb cb_display;
+static glut_cb cb_idle;
+static glut_cb_reshape cb_reshape;
+static glut_cb_state cb_vis, cb_entry;
+static glut_cb_keyb cb_keydown, cb_keyup;
+static glut_cb_special cb_skeydown, cb_skeyup;
+static glut_cb_mouse cb_mouse;
+static glut_cb_motion cb_motion, cb_passive;
+static glut_cb_sbmotion cb_sball_motion, cb_sball_rotate;
+static glut_cb_sbbutton cb_sball_button;
+
+static int fullscreen;
+static int prev_win_x, prev_win_y, prev_win_width, prev_win_height;
+
+static int win_width, win_height;
+static int mapped;
+static int quit;
+static int upd_pending;
+static int modstate;
+
+void glutInit(int *argc, char **argv)
+{
+#ifdef BUILD_X11
+       if(!(dpy = XOpenDisplay(0))) {
+               panic("Failed to connect to the X server\n");
+       }
+       scr = DefaultScreen(dpy);
+       root = RootWindow(dpy, scr);
+       xa_wm_proto = XInternAtom(dpy, "WM_PROTOCOLS", False);
+       xa_wm_del_win = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
+       xa_motif_wm_hints = XInternAtom(dpy, "_MOTIF_WM_HINTS", False);
+       if(have_netwm_fullscr()) {
+               xa_net_wm_state = XInternAtom(dpy, "_NET_WM_STATE", False);
+               xa_net_wm_state_fullscr = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
+       }
+
+       xa_motion_event = XInternAtom(dpy, "MotionEvent", True);
+       xa_button_press_event = XInternAtom(dpy, "ButtonPressEvent", True);
+       xa_button_release_event = XInternAtom(dpy, "ButtonReleaseEvent", True);
+       xa_command_event = XInternAtom(dpy, "CommandEvent", True);
+
+       evmask = ExposureMask | StructureNotifyMask;
+
+#endif
+#ifdef BUILD_WIN32
+       WNDCLASSEX wc = {0};
+
+       hinst = GetModuleHandle(0);
+
+       wc.cbSize = sizeof wc;
+       wc.hbrBackground = GetStockObject(BLACK_BRUSH);
+       wc.hCursor = LoadCursor(0, IDC_ARROW);
+       wc.hIcon = wc.hIconSm = LoadIcon(0, IDI_APPLICATION);
+       wc.hInstance = hinst;
+       wc.lpfnWndProc = handle_message;
+       wc.lpszClassName = "MiniGLUT";
+       wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+       if(!RegisterClassEx(&wc)) {
+               panic("Failed to register \"MiniGLUT\" window class\n");
+       }
+
+       if(init_x == -1) {
+               get_screen_size(&init_x, &init_y);
+               init_x >>= 3;
+               init_y >>= 3;
+       }
+#endif
+}
+
+void glutInitWindowPosition(int x, int y)
+{
+       init_x = x;
+       init_y = y;
+}
+
+void glutInitWindowSize(int xsz, int ysz)
+{
+       init_width = xsz;
+       init_height = ysz;
+}
+
+void glutInitDisplayMode(unsigned int mode)
+{
+       init_mode = mode;
+}
+
+void glutCreateWindow(const char *title)
+{
+       create_window(title);
+}
+
+void glutExit(void)
+{
+       quit = 1;
+}
+
+void glutMainLoop(void)
+{
+       while(!quit) {
+               glutMainLoopEvent();
+       }
+}
+
+void glutPostRedisplay(void)
+{
+       upd_pending = 1;
+}
+
+#define UPD_EVMASK(x) \
+       do { \
+               if(func) { \
+                       evmask |= x; \
+               } else { \
+                       evmask &= ~(x); \
+               } \
+               if(win) XSelectInput(dpy, win, evmask); \
+       } while(0)
+
+
+void glutIdleFunc(glut_cb func)
+{
+       cb_idle = func;
+}
+
+void glutDisplayFunc(glut_cb func)
+{
+       cb_display = func;
+}
+
+void glutReshapeFunc(glut_cb_reshape func)
+{
+       cb_reshape = func;
+}
+
+void glutVisibilityFunc(glut_cb_state func)
+{
+       cb_vis = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(VisibilityChangeMask);
+#endif
+}
+
+void glutEntryFunc(glut_cb_state func)
+{
+       cb_entry = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(EnterWindowMask | LeaveWindowMask);
+#endif
+}
+
+void glutKeyboardFunc(glut_cb_keyb func)
+{
+       cb_keydown = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(KeyPressMask);
+#endif
+}
+
+void glutKeyboardUpFunc(glut_cb_keyb func)
+{
+       cb_keyup = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(KeyReleaseMask);
+#endif
+}
+
+void glutSpecialFunc(glut_cb_special func)
+{
+       cb_skeydown = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(KeyPressMask);
+#endif
+}
+
+void glutSpecialUpFunc(glut_cb_special func)
+{
+       cb_skeyup = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(KeyReleaseMask);
+#endif
+}
+
+void glutMouseFunc(glut_cb_mouse func)
+{
+       cb_mouse = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(ButtonPressMask | ButtonReleaseMask);
+#endif
+}
+
+void glutMotionFunc(glut_cb_motion func)
+{
+       cb_motion = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(ButtonMotionMask);
+#endif
+}
+
+void glutPassiveMotionFunc(glut_cb_motion func)
+{
+       cb_passive = func;
+#ifdef BUILD_X11
+       UPD_EVMASK(PointerMotionMask);
+#endif
+}
+
+void glutSpaceballMotionFunc(glut_cb_sbmotion func)
+{
+       cb_sball_motion = func;
+}
+
+void glutSpaceballRotateFunc(glut_cb_sbmotion func)
+{
+       cb_sball_rotate = func;
+}
+
+void glutSpaceballButtonFunc(glut_cb_sbbutton func)
+{
+       cb_sball_button = func;
+}
+
+int glutGet(unsigned int s)
+{
+       int x, y;
+       switch(s) {
+       case GLUT_WINDOW_X:
+               get_window_pos(&x, &y);
+               return x;
+       case GLUT_WINDOW_Y:
+               get_window_pos(&x, &y);
+               return y;
+       case GLUT_WINDOW_WIDTH:
+               get_window_size(&x, &y);
+               return x;
+       case GLUT_WINDOW_HEIGHT:
+               get_window_size(&x, &y);
+               return y;
+       case GLUT_WINDOW_BUFFER_SIZE:
+               return ctx_info.rsize + ctx_info.gsize + ctx_info.bsize + ctx_info.asize;
+       case GLUT_WINDOW_STENCIL_SIZE:
+               return ctx_info.ssize;
+       case GLUT_WINDOW_DEPTH_SIZE:
+               return ctx_info.zsize;
+       case GLUT_WINDOW_RED_SIZE:
+               return ctx_info.rsize;
+       case GLUT_WINDOW_GREEN_SIZE:
+               return ctx_info.gsize;
+       case GLUT_WINDOW_BLUE_SIZE:
+               return ctx_info.bsize;
+       case GLUT_WINDOW_ALPHA_SIZE:
+               return ctx_info.asize;
+       case GLUT_WINDOW_DOUBLEBUFFER:
+               return ctx_info.dblbuf;
+       case GLUT_WINDOW_RGBA:
+               return 1;
+       case GLUT_WINDOW_NUM_SAMPLES:
+               return ctx_info.samples;
+       case GLUT_WINDOW_STEREO:
+               return ctx_info.stereo;
+       case GLUT_WINDOW_SRGB:
+               return ctx_info.srgb;
+       case GLUT_WINDOW_CURSOR:
+               return cur_cursor;
+       case GLUT_SCREEN_WIDTH:
+               get_screen_size(&x, &y);
+               return x;
+       case GLUT_SCREEN_HEIGHT:
+               get_screen_size(&x, &y);
+               return y;
+       case GLUT_INIT_DISPLAY_MODE:
+               return init_mode;
+       case GLUT_INIT_WINDOW_X:
+               return init_x;
+       case GLUT_INIT_WINDOW_Y:
+               return init_y;
+       case GLUT_INIT_WINDOW_WIDTH:
+               return init_width;
+       case GLUT_INIT_WINDOW_HEIGHT:
+               return init_height;
+       case GLUT_ELAPSED_TIME:
+               return get_msec();
+       default:
+               break;
+       }
+       return 0;
+}
+
+int glutGetModifiers(void)
+{
+       return modstate;
+}
+
+static int is_space(int c)
+{
+       return c == ' ' || c == '\t' || c == '\v' || c == '\n' || c == '\r';
+}
+
+static const char *skip_space(const char *s)
+{
+       while(*s && is_space(*s)) s++;
+       return s;
+}
+
+int glutExtensionSupported(char *ext)
+{
+       const char *str, *eptr;
+
+       if(!(str = (const char*)glGetString(GL_EXTENSIONS))) {
+               return 0;
+       }
+
+       while(*str) {
+               str = skip_space(str);
+               eptr = skip_space(ext);
+               while(*str && !is_space(*str) && *eptr && *str == *eptr) {
+                       str++;
+                       eptr++;
+               }
+               if((!*str || is_space(*str)) && !*eptr) {
+                       return 1;
+               }
+               while(*str && !is_space(*str)) str++;
+       }
+
+       return 0;
+}
+
+
+/* --------------- UNIX/X11 implementation ----------------- */
+#ifdef BUILD_X11
+enum {
+    SPNAV_EVENT_ANY,  /* used by spnav_remove_events() */
+    SPNAV_EVENT_MOTION,
+    SPNAV_EVENT_BUTTON  /* includes both press and release */
+};
+
+struct spnav_event_motion {
+    int type;
+    int x, y, z;
+    int rx, ry, rz;
+    unsigned int period;
+    int *data;
+};
+
+struct spnav_event_button {
+    int type;
+    int press;
+    int bnum;
+};
+
+union spnav_event {
+    int type;
+    struct spnav_event_motion motion;
+    struct spnav_event_button button;
+};
+
+
+static void handle_event(XEvent *ev);
+
+static int spnav_window(Window win);
+static int spnav_event(const XEvent *xev, union spnav_event *event);
+static int spnav_remove_events(int type);
+
+
+void glutMainLoopEvent(void)
+{
+       XEvent ev;
+
+       if(!cb_display) {
+               panic("display callback not set");
+       }
+
+       if(!upd_pending && !cb_idle) {
+               XNextEvent(dpy, &ev);
+               handle_event(&ev);
+               if(quit) goto end;
+       }
+       while(XPending(dpy)) {
+               XNextEvent(dpy, &ev);
+               handle_event(&ev);
+               if(quit) goto end;
+       }
+
+       if(cb_idle) {
+               cb_idle();
+       }
+
+       if(upd_pending && mapped) {
+               upd_pending = 0;
+               cb_display();
+       }
+
+end:
+       if(quit) {
+               cleanup();
+       }
+}
+
+static void cleanup(void)
+{
+       if(win) {
+               spnav_window(root);
+               glXMakeCurrent(dpy, 0, 0);
+               XDestroyWindow(dpy, win);
+       }
+}
+
+static KeySym translate_keysym(KeySym sym)
+{
+       switch(sym) {
+       case XK_Escape:
+               return 27;
+       case XK_BackSpace:
+               return '\b';
+       case XK_Linefeed:
+               return '\r';
+       case XK_Return:
+               return '\n';
+       case XK_Delete:
+               return 127;
+       case XK_Tab:
+               return '\t';
+       default:
+               break;
+       }
+       return sym;
+}
+
+static void handle_event(XEvent *ev)
+{
+       KeySym sym;
+       union spnav_event sev;
+
+       switch(ev->type) {
+       case MapNotify:
+               mapped = 1;
+               break;
+       case UnmapNotify:
+               mapped = 0;
+               break;
+       case ConfigureNotify:
+               if(cb_reshape && (ev->xconfigure.width != win_width || ev->xconfigure.height != win_height)) {
+                       win_width = ev->xconfigure.width;
+                       win_height = ev->xconfigure.height;
+                       cb_reshape(ev->xconfigure.width, ev->xconfigure.height);
+               }
+               break;
+
+       case ClientMessage:
+               if(ev->xclient.message_type == xa_wm_proto) {
+                       if(ev->xclient.data.l[0] == xa_wm_del_win) {
+                               quit = 1;
+                       }
+               }
+               if(spnav_event(ev, &sev)) {
+                       switch(sev.type) {
+                       case SPNAV_EVENT_MOTION:
+                               if(cb_sball_motion) {
+                                       cb_sball_motion(sev.motion.x, sev.motion.y, sev.motion.z);
+                               }
+                               if(cb_sball_rotate) {
+                                       cb_sball_rotate(sev.motion.rx, sev.motion.ry, sev.motion.rz);
+                               }
+                               spnav_remove_events(SPNAV_EVENT_MOTION);
+                               break;
+
+                       case SPNAV_EVENT_BUTTON:
+                               if(cb_sball_button) {
+                                       cb_sball_button(sev.button.bnum + 1, sev.button.press ? GLUT_DOWN : GLUT_UP);
+                               }
+                               break;
+
+                       default:
+                               break;
+                       }
+               }
+               break;
+
+       case Expose:
+               upd_pending = 1;
+               break;
+
+       case KeyPress:
+       case KeyRelease:
+               modstate = ev->xkey.state & (ShiftMask | ControlMask | Mod1Mask);
+               if(!(sym = XLookupKeysym(&ev->xkey, 0))) {
+                       break;
+               }
+               sym = translate_keysym(sym);
+               if(sym < 256) {
+                       if(ev->type == KeyPress) {
+                               if(cb_keydown) cb_keydown((unsigned char)sym, ev->xkey.x, ev->xkey.y);
+                       } else {
+                               if(cb_keyup) cb_keyup((unsigned char)sym, ev->xkey.x, ev->xkey.y);
+                       }
+               } else {
+                       if(ev->type == KeyPress) {
+                               if(cb_skeydown) cb_skeydown(sym, ev->xkey.x, ev->xkey.y);
+                       } else {
+                               if(cb_skeyup) cb_skeyup(sym, ev->xkey.x, ev->xkey.y);
+                       }
+               }
+               break;
+
+       case ButtonPress:
+       case ButtonRelease:
+               modstate = ev->xbutton.state & (ShiftMask | ControlMask | Mod1Mask);
+               if(cb_mouse) {
+                       int bn = ev->xbutton.button - Button1;
+                       cb_mouse(bn, ev->type == ButtonPress ? GLUT_DOWN : GLUT_UP,
+                                       ev->xbutton.x, ev->xbutton.y);
+               }
+               break;
+
+       case MotionNotify:
+               if(ev->xmotion.state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)) {
+                       if(cb_motion) cb_motion(ev->xmotion.x, ev->xmotion.y);
+               } else {
+                       if(cb_passive) cb_passive(ev->xmotion.x, ev->xmotion.y);
+               }
+               break;
+
+       case VisibilityNotify:
+               if(cb_vis) {
+                       cb_vis(ev->xvisibility.state == VisibilityFullyObscured ? GLUT_NOT_VISIBLE : GLUT_VISIBLE);
+               }
+               break;
+       case EnterNotify:
+               if(cb_entry) cb_entry(GLUT_ENTERED);
+               break;
+       case LeaveNotify:
+               if(cb_entry) cb_entry(GLUT_LEFT);
+               break;
+       }
+}
+
+void glutSwapBuffers(void)
+{
+       glXSwapBuffers(dpy, win);
+}
+
+/* BUG:
+ * set_fullscreen_mwm removes the decorations with MotifWM hints, and then it
+ * needs to resize the window to make it fullscreen. The way it does this is by
+ * querying the size of the root window (see get_screen_size), which in the
+ * case of multi-monitor setups will be the combined size of all monitors.
+ * This is problematic; the way to solve it is to use the XRandR extension, or
+ * the Xinerama extension, to figure out the dimensions of the correct video
+ * output, which would add potentially two extension support libraries to our
+ * dependencies list.
+ * Moreover, any X installation modern enough to support XR&R will almost
+ * certainly be running a window manager supporting the EHWM
+ * _NET_WM_STATE_FULLSCREEN method (set_fullscreen_ewmh), which does not rely
+ * on manual resizing, and is used in preference if available, making this
+ * whole endeavor pointless.
+ * So I'll just leave it with set_fullscreen_mwm covering the entire
+ * multi-monitor area for now.
+ */
+
+struct mwm_hints {
+       unsigned long flags;
+       unsigned long functions;
+       unsigned long decorations;
+       long input_mode;
+       unsigned long status;
+};
+
+#define MWM_HINTS_DECORATIONS  2
+#define MWM_DECOR_ALL                  1
+
+static void set_fullscreen_mwm(int fs)
+{
+       struct mwm_hints hints;
+       int scr_width, scr_height;
+
+       if(fs) {
+               get_window_pos(&prev_win_x, &prev_win_y);
+               get_window_size(&prev_win_width, &prev_win_height);
+               get_screen_size(&scr_width, &scr_height);
+
+               hints.decorations = 0;
+               hints.flags = MWM_HINTS_DECORATIONS;
+               XChangeProperty(dpy, win, xa_motif_wm_hints, xa_motif_wm_hints, 32,
+                               PropModeReplace, (unsigned char*)&hints, 5);
+
+               XMoveResizeWindow(dpy, win, 0, 0, scr_width, scr_height);
+       } else {
+               XDeleteProperty(dpy, win, xa_motif_wm_hints);
+               XMoveResizeWindow(dpy, win, prev_win_x, prev_win_y, prev_win_width, prev_win_height);
+       }
+}
+
+static int have_netwm_fullscr(void)
+{
+       int fmt;
+       long offs = 0;
+       unsigned long i, count, rem;
+       Atom prop[8], type;
+       Atom xa_net_supported = XInternAtom(dpy, "_NET_SUPPORTED", False);
+
+       do {
+               XGetWindowProperty(dpy, root, xa_net_supported, offs, 8, False, AnyPropertyType,
+                               &type, &fmt, &count, &rem, (unsigned char**)prop);
+
+               for(i=0; i<count; i++) {
+                       if(prop[i] == xa_net_wm_state_fullscr) {
+                               return 1;
+                       }
+               }
+               offs += count;
+       } while(rem > 0);
+
+       return 0;
+}
+
+static void set_fullscreen_ewmh(int fs)
+{
+       XClientMessageEvent msg = {0};
+
+       msg.type = ClientMessage;
+       msg.window = win;
+       msg.message_type = xa_net_wm_state;     /* _NET_WM_STATE */
+       msg.format = 32;
+       msg.data.l[0] = fs ? 1 : 0;
+       msg.data.l[1] = xa_net_wm_state_fullscr;        /* _NET_WM_STATE_FULLSCREEN */
+       msg.data.l[2] = 0;
+       msg.data.l[3] = 1;      /* source regular application */
+       XSendEvent(dpy, root, False, SubstructureNotifyMask | SubstructureRedirectMask, (XEvent*)&msg);
+}
+
+static void set_fullscreen(int fs)
+{
+       if(fullscreen == fs) return;
+
+       if(xa_net_wm_state && xa_net_wm_state_fullscr) {
+               set_fullscreen_ewmh(fs);
+               fullscreen = fs;
+       } else if(xa_motif_wm_hints) {
+               set_fullscreen_mwm(fs);
+               fullscreen = fs;
+       }
+}
+
+void glutPositionWindow(int x, int y)
+{
+       set_fullscreen(0);
+       XMoveWindow(dpy, win, x, y);
+}
+
+void glutReshapeWindow(int xsz, int ysz)
+{
+       set_fullscreen(0);
+       XResizeWindow(dpy, win, xsz, ysz);
+}
+
+void glutFullScreen(void)
+{
+       set_fullscreen(1);
+}
+
+void glutSetWindowTitle(const char *title)
+{
+       XTextProperty tprop;
+       if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
+               return;
+       }
+       XSetWMName(dpy, win, &tprop);
+       XFree(tprop.value);
+}
+
+void glutSetIconTitle(const char *title)
+{
+       XTextProperty tprop;
+       if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
+               return;
+       }
+       XSetWMIconName(dpy, win, &tprop);
+       XFree(tprop.value);
+}
+
+void glutSetCursor(int cidx)
+{
+       Cursor cur = None;
+
+       switch(cidx) {
+       case GLUT_CURSOR_LEFT_ARROW:
+               cur = XCreateFontCursor(dpy, XC_left_ptr);
+               break;
+       case GLUT_CURSOR_INHERIT:
+               break;
+       case GLUT_CURSOR_NONE:
+               /* TODO */
+       default:
+               return;
+       }
+
+       XDefineCursor(dpy, win, cur);
+       cur_cursor = cidx;
+}
+
+static XVisualInfo *choose_visual(unsigned int mode)
+{
+       XVisualInfo *vi;
+       int attr[32];
+       int *aptr = attr;
+       int *samples = 0;
+
+       if(mode & GLUT_DOUBLE) {
+               *aptr++ = GLX_DOUBLEBUFFER;
+       }
+
+       if(mode & GLUT_INDEX) {
+               *aptr++ = GLX_BUFFER_SIZE;
+               *aptr++ = 1;
+       } else {
+               *aptr++ = GLX_RGBA;
+               *aptr++ = GLX_RED_SIZE; *aptr++ = 4;
+               *aptr++ = GLX_GREEN_SIZE; *aptr++ = 4;
+               *aptr++ = GLX_BLUE_SIZE; *aptr++ = 4;
+       }
+       if(mode & GLUT_ALPHA) {
+               *aptr++ = GLX_ALPHA_SIZE;
+               *aptr++ = 4;
+       }
+       if(mode & GLUT_DEPTH) {
+               *aptr++ = GLX_DEPTH_SIZE;
+               *aptr++ = 16;
+       }
+       if(mode & GLUT_STENCIL) {
+               *aptr++ = GLX_STENCIL_SIZE;
+               *aptr++ = 1;
+       }
+       if(mode & GLUT_ACCUM) {
+               *aptr++ = GLX_ACCUM_RED_SIZE; *aptr++ = 1;
+               *aptr++ = GLX_ACCUM_GREEN_SIZE; *aptr++ = 1;
+               *aptr++ = GLX_ACCUM_BLUE_SIZE; *aptr++ = 1;
+       }
+       if(mode & GLUT_STEREO) {
+               *aptr++ = GLX_STEREO;
+       }
+       if(mode & GLUT_SRGB) {
+               *aptr++ = GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB;
+       }
+       if(mode & GLUT_MULTISAMPLE) {
+               *aptr++ = GLX_SAMPLE_BUFFERS_ARB;
+               *aptr++ = 1;
+               *aptr++ = GLX_SAMPLES_ARB;
+               samples = aptr;
+               *aptr++ = 32;
+       }
+       *aptr++ = None;
+
+       if(!samples) {
+               return glXChooseVisual(dpy, scr, attr);
+       }
+       while(!(vi = glXChooseVisual(dpy, scr, attr)) && *samples) {
+               *samples >>= 1;
+               if(!*samples) {
+                       aptr[-3] = None;
+               }
+       }
+       return vi;
+}
+
+static void create_window(const char *title)
+{
+       XSetWindowAttributes xattr = {0};
+       XVisualInfo *vi;
+       unsigned int xattr_mask;
+       unsigned int mode = init_mode;
+
+       if(!(vi = choose_visual(mode))) {
+               mode &= ~GLUT_SRGB;
+               if(!(vi = choose_visual(mode))) {
+                       panic("Failed to find compatible visual\n");
+               }
+       }
+
+       if(!(ctx = glXCreateContext(dpy, vi, 0, True))) {
+               XFree(vi);
+               panic("Failed to create OpenGL context\n");
+       }
+
+       glXGetConfig(dpy, vi, GLX_RED_SIZE, &ctx_info.rsize);
+       glXGetConfig(dpy, vi, GLX_GREEN_SIZE, &ctx_info.gsize);
+       glXGetConfig(dpy, vi, GLX_BLUE_SIZE, &ctx_info.bsize);
+       glXGetConfig(dpy, vi, GLX_ALPHA_SIZE, &ctx_info.asize);
+       glXGetConfig(dpy, vi, GLX_DEPTH_SIZE, &ctx_info.zsize);
+       glXGetConfig(dpy, vi, GLX_STENCIL_SIZE, &ctx_info.ssize);
+       glXGetConfig(dpy, vi, GLX_DOUBLEBUFFER, &ctx_info.dblbuf);
+       glXGetConfig(dpy, vi, GLX_STEREO, &ctx_info.stereo);
+       glXGetConfig(dpy, vi, GLX_SAMPLES_ARB, &ctx_info.samples);
+       glXGetConfig(dpy, vi, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &ctx_info.srgb);
+
+       xattr.background_pixel = BlackPixel(dpy, scr);
+       xattr.colormap = XCreateColormap(dpy, root, vi->visual, AllocNone);
+       xattr_mask = CWBackPixel | CWColormap | CWBackPixmap | CWBorderPixel;
+       if(!(win = XCreateWindow(dpy, root, init_x, init_y, init_width, init_height, 0,
+                       vi->depth, InputOutput, vi->visual, xattr_mask, &xattr))) {
+               XFree(vi);
+               glXDestroyContext(dpy, ctx);
+               panic("Failed to create window\n");
+       }
+       XFree(vi);
+
+       XSelectInput(dpy, win, evmask);
+
+       spnav_window(win);
+
+       glutSetWindowTitle(title);
+       glutSetIconTitle(title);
+       XSetWMProtocols(dpy, win, &xa_wm_del_win, 1);
+       XMapWindow(dpy, win);
+
+       glXMakeCurrent(dpy, win, ctx);
+}
+
+static void get_window_pos(int *x, int *y)
+{
+       Window child;
+       XTranslateCoordinates(dpy, win, root, 0, 0, x, y, &child);
+}
+
+static void get_window_size(int *w, int *h)
+{
+       XWindowAttributes wattr;
+       XGetWindowAttributes(dpy, win, &wattr);
+       *w = wattr.width;
+       *h = wattr.height;
+}
+
+static void get_screen_size(int *scrw, int *scrh)
+{
+       XWindowAttributes wattr;
+       XGetWindowAttributes(dpy, root, &wattr);
+       *scrw = wattr.width;
+       *scrh = wattr.height;
+}
+
+
+/* spaceball */
+enum {
+  CMD_APP_WINDOW = 27695,
+  CMD_APP_SENS
+};
+
+static Window get_daemon_window(Display *dpy);
+static int catch_badwin(Display *dpy, XErrorEvent *err);
+
+#define SPNAV_INITIALIZED      (xa_motion_event)
+
+static int spnav_window(Window win)
+{
+       int (*prev_xerr_handler)(Display*, XErrorEvent*);
+       XEvent xev;
+       Window daemon_win;
+
+       if(!SPNAV_INITIALIZED) {
+               return -1;
+       }
+
+       if(!(daemon_win = get_daemon_window(dpy))) {
+               return -1;
+       }
+
+       prev_xerr_handler = XSetErrorHandler(catch_badwin);
+
+       xev.type = ClientMessage;
+       xev.xclient.send_event = False;
+       xev.xclient.display = dpy;
+       xev.xclient.window = win;
+       xev.xclient.message_type = xa_command_event;
+       xev.xclient.format = 16;
+       xev.xclient.data.s[0] = ((unsigned int)win & 0xffff0000) >> 16;
+       xev.xclient.data.s[1] = (unsigned int)win & 0xffff;
+       xev.xclient.data.s[2] = CMD_APP_WINDOW;
+
+       XSendEvent(dpy, daemon_win, False, 0, &xev);
+       XSync(dpy, False);
+
+       XSetErrorHandler(prev_xerr_handler);
+       return 0;
+}
+
+static Bool match_events(Display *dpy, XEvent *xev, char *arg)
+{
+       int evtype = *(int*)arg;
+
+       if(xev->type != ClientMessage) {
+               return False;
+       }
+
+       if(xev->xclient.message_type == xa_motion_event) {
+               return !evtype || evtype == SPNAV_EVENT_MOTION ? True : False;
+       }
+       if(xev->xclient.message_type == xa_button_press_event ||
+                       xev->xclient.message_type == xa_button_release_event) {
+               return !evtype || evtype == SPNAV_EVENT_BUTTON ? True : False;
+       }
+       return False;
+}
+
+static int spnav_remove_events(int type)
+{
+       int rm_count = 0;
+       XEvent xev;
+       while(XCheckIfEvent(dpy, &xev, match_events, (char*)&type)) {
+               rm_count++;
+       }
+       return rm_count;
+}
+
+static int spnav_event(const XEvent *xev, union spnav_event *event)
+{
+       int i;
+       int xmsg_type;
+
+       xmsg_type = xev->xclient.message_type;
+
+       if(xmsg_type != xa_motion_event && xmsg_type != xa_button_press_event &&
+                       xmsg_type != xa_button_release_event) {
+               return 0;
+       }
+
+       if(xmsg_type == xa_motion_event) {
+               event->type = SPNAV_EVENT_MOTION;
+               event->motion.data = &event->motion.x;
+
+               for(i=0; i<6; i++) {
+                       event->motion.data[i] = xev->xclient.data.s[i + 2];
+               }
+               event->motion.period = xev->xclient.data.s[8];
+       } else {
+               event->type = SPNAV_EVENT_BUTTON;
+               event->button.press = xmsg_type == xa_button_press_event ? 1 : 0;
+               event->button.bnum = xev->xclient.data.s[2];
+       }
+       return event->type;
+}
+
+static int mglut_strcmp(const char *s1, const char *s2)
+{
+       while(*s1 && *s1 == *s2) {
+               s1++;
+               s2++;
+       }
+       return *s1 - *s2;
+}
+
+static Window get_daemon_window(Display *dpy)
+{
+       Window win;
+       XTextProperty wname;
+       Atom type;
+       int fmt;
+       unsigned long nitems, bytes_after;
+       unsigned char *prop;
+
+       XGetWindowProperty(dpy, root, xa_command_event, 0, 1, False, AnyPropertyType,
+                       &type, &fmt, &nitems, &bytes_after, &prop);
+       if(!prop) {
+               return 0;
+       }
+
+       win = *(Window*)prop;
+       XFree(prop);
+
+       if(!XGetWMName(dpy, win, &wname) || mglut_strcmp("Magellan Window", (char*)wname.value) != 0) {
+               return 0;
+       }
+
+       return win;
+}
+
+static int catch_badwin(Display *dpy, XErrorEvent *err)
+{
+       return 0;
+}
+
+
+
+#endif /* BUILD_X11 */
+
+
+/* --------------- windows implementation ----------------- */
+#ifdef BUILD_WIN32
+static int reshape_pending;
+
+static void update_modkeys(void);
+static int translate_vkey(int vkey);
+static void handle_mbutton(int bn, int st, WPARAM wparam, LPARAM lparam);
+
+#ifdef MINIGLUT_WINMAIN
+int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hprev, char *cmdline, int showcmd)
+{
+       int argc = 1;
+       char *argv[] = { "miniglut.exe", 0 };
+       return main(argc, argv);
+}
+#endif
+
+void glutMainLoopEvent(void)
+{
+       MSG msg;
+
+       if(!cb_display) {
+               panic("display callback not set");
+       }
+
+       if(reshape_pending && cb_reshape) {
+               reshape_pending = 0;
+               get_window_size(&win_width, &win_height);
+               cb_reshape(win_width, win_height);
+       }
+
+       if(!upd_pending && !cb_idle) {
+               GetMessage(&msg, 0, 0, 0);
+               TranslateMessage(&msg);
+               DispatchMessage(&msg);
+               if(quit) return;
+       }
+       while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
+               TranslateMessage(&msg);
+               DispatchMessage(&msg);
+               if(quit) return;
+       }
+
+       if(cb_idle) {
+               cb_idle();
+       }
+
+       if(upd_pending && mapped) {
+               upd_pending = 0;
+               cb_display();
+       }
+}
+
+static void cleanup(void)
+{
+       if(win) {
+               wglMakeCurrent(dc, 0);
+               wglDeleteContext(ctx);
+               UnregisterClass("MiniGLUT", hinst);
+       }
+}
+
+void glutSwapBuffers(void)
+{
+       SwapBuffers(dc);
+}
+
+void glutPositionWindow(int x, int y)
+{
+       RECT rect;
+       unsigned int flags = SWP_SHOWWINDOW;
+
+       if(fullscreen) {
+               rect.left = prev_win_x;
+               rect.top = prev_win_y;
+               rect.right = rect.left + prev_win_width;
+               rect.bottom = rect.top + prev_win_height;
+               SetWindowLong(win, GWL_STYLE, WS_OVERLAPPEDWINDOW);
+               fullscreen = 0;
+               flags |= SWP_FRAMECHANGED;
+       } else {
+               GetWindowRect(win, &rect);
+       }
+       SetWindowPos(win, HWND_NOTOPMOST, x, y, rect.right - rect.left, rect.bottom - rect.top, flags);
+}
+
+void glutReshapeWindow(int xsz, int ysz)
+{
+       RECT rect;
+       unsigned int flags = SWP_SHOWWINDOW;
+
+       if(fullscreen) {
+               rect.left = prev_win_x;
+               rect.top = prev_win_y;
+               SetWindowLong(win, GWL_STYLE, WS_OVERLAPPEDWINDOW);
+               fullscreen = 0;
+               flags |= SWP_FRAMECHANGED;
+       } else {
+               GetWindowRect(win, &rect);
+       }
+       SetWindowPos(win, HWND_NOTOPMOST, rect.left, rect.top, xsz, ysz, flags);
+}
+
+void glutFullScreen(void)
+{
+       RECT rect;
+       int scr_width, scr_height;
+
+       if(fullscreen) return;
+
+       GetWindowRect(win, &rect);
+       prev_win_x = rect.left;
+       prev_win_y = rect.top;
+       prev_win_width = rect.right - rect.left;
+       prev_win_height = rect.bottom - rect.top;
+
+       get_screen_size(&scr_width, &scr_height);
+
+       SetWindowLong(win, GWL_STYLE, 0);
+       SetWindowPos(win, HWND_TOPMOST, 0, 0, scr_width, scr_height, SWP_SHOWWINDOW);
+
+       fullscreen = 1;
+}
+
+void glutSetWindowTitle(const char *title)
+{
+       SetWindowText(win, title);
+}
+
+void glutSetIconTitle(const char *title)
+{
+}
+
+void glutSetCursor(int cidx)
+{
+       switch(cidx) {
+       case GLUT_CURSOR_NONE:
+               ShowCursor(0);
+               break;
+       case GLUT_CURSOR_INHERIT:
+       case GLUT_CURSOR_LEFT_ARROW:
+       default:
+               SetCursor(LoadCursor(0, IDC_ARROW));
+               ShowCursor(1);
+       }
+}
+
+#define WGL_DRAW_TO_WINDOW     0x2001
+#define WGL_SUPPORT_OPENGL     0x2010
+#define WGL_DOUBLE_BUFFER      0x2011
+#define WGL_STEREO                     0x2012
+#define WGL_PIXEL_TYPE         0x2013
+#define WGL_COLOR_BITS         0x2014
+#define WGL_RED_BITS           0x2015
+#define WGL_GREEN_BITS         0x2017
+#define WGL_BLUE_BITS          0x2019
+#define WGL_ALPHA_BITS         0x201b
+#define WGL_ACCUM_BITS         0x201d
+#define WGL_DEPTH_BITS         0x2022
+#define WGL_STENCIL_BITS       0x2023
+
+#define WGL_TYPE_RGBA          0x202b
+#define WGL_TYPE_COLORINDEX    0x202c
+
+#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB       0x20a9
+#define WGL_SAMPLE_BUFFERS_ARB                         0x2041
+#define WGL_SAMPLES_ARB                                                0x2042
+
+static PROC wglChoosePixelFormat;
+static PROC wglGetPixelFormatAttribiv;
+
+#define ATTR(a, v) \
+       do { *aptr++ = (a); *aptr++ = (v); } while(0)
+
+static unsigned int choose_pixfmt(unsigned int mode)
+{
+       unsigned int num_pixfmt, pixfmt = 0;
+       int attr[32] = { WGL_DRAW_TO_WINDOW, 1, WGL_SUPPORT_OPENGL, 1 };
+
+       int *aptr = attr;
+       int *samples = 0;
+
+       if(mode & GLUT_DOUBLE) {
+               ATTR(WGL_DOUBLE_BUFFER, 1);
+       }
+
+       ATTR(WGL_PIXEL_TYPE, mode & GLUT_INDEX ? WGL_TYPE_COLORINDEX : WGL_TYPE_RGBA);
+       ATTR(WGL_COLOR_BITS, 8);
+       if(mode & GLUT_ALPHA) {
+               ATTR(WGL_ALPHA_BITS, 4);
+       }
+       if(mode & GLUT_DEPTH) {
+               ATTR(WGL_DEPTH_BITS, 16);
+       }
+       if(mode & GLUT_STENCIL) {
+               ATTR(WGL_STENCIL_BITS, 1);
+       }
+       if(mode & GLUT_ACCUM) {
+               ATTR(WGL_ACCUM_BITS, 1);
+       }
+       if(mode & GLUT_STEREO) {
+               ATTR(WGL_STEREO, 1);
+       }
+       if(mode & GLUT_SRGB) {
+               ATTR(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, 1);
+       }
+       if(mode & GLUT_MULTISAMPLE) {
+               ATTR(WGL_SAMPLE_BUFFERS_ARB, 1);
+               *aptr++ = WGL_SAMPLES_ARB;
+               samples = aptr;
+               *aptr++ = 32;
+       }
+       *aptr++ = 0;
+
+       while((!wglChoosePixelFormat(dc, attr, 0, 1, &pixfmt, &num_pixfmt) || !num_pixfmt) && samples && *samples) {
+               *samples >>= 1;
+               if(!*samples) {
+                       aptr[-3] = 0;
+               }
+       }
+       return pixfmt;
+}
+
+static PIXELFORMATDESCRIPTOR tmppfd = {
+       sizeof tmppfd, 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
+       PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 8, 0,
+       PFD_MAIN_PLANE, 0, 0, 0, 0
+};
+#define TMPCLASS       "TempMiniGLUT"
+
+#define GETATTR(attr, vptr) \
+       do { \
+               int gattr = attr; \
+               wglGetPixelFormatAttribiv(dc, pixfmt, 0, 1, &gattr, vptr); \
+       } while(0)
+
+static int create_window_wglext(const char *title, int width, int height)
+{
+       WNDCLASSEX wc = {0};
+       HWND tmpwin = 0;
+       HDC tmpdc = 0;
+       HGLRC tmpctx = 0;
+       int pixfmt;
+
+       /* create a temporary window and GL context, just to query and retrieve
+        * the wglChoosePixelFormatEXT function
+        */
+       wc.cbSize = sizeof wc;
+       wc.hbrBackground = GetStockObject(BLACK_BRUSH);
+       wc.hCursor = LoadCursor(0, IDC_ARROW);
+       wc.hIcon = wc.hIconSm = LoadIcon(0, IDI_APPLICATION);
+       wc.hInstance = hinst;
+       wc.lpfnWndProc = DefWindowProc;
+       wc.lpszClassName = TMPCLASS;
+       wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+       if(!RegisterClassEx(&wc)) {
+               return 0;
+       }
+       if(!(tmpwin = CreateWindow(TMPCLASS, "temp", WS_OVERLAPPEDWINDOW, 0, 0,
+                                       width, height, 0, 0, hinst, 0))) {
+               goto fail;
+       }
+       tmpdc = GetDC(tmpwin);
+
+       if(!(pixfmt = ChoosePixelFormat(tmpdc, &tmppfd)) ||
+                       !SetPixelFormat(tmpdc, pixfmt, &tmppfd) ||
+                       !(tmpctx = wglCreateContext(tmpdc))) {
+               goto fail;
+       }
+       wglMakeCurrent(tmpdc, tmpctx);
+
+       if(!(wglChoosePixelFormat = wglGetProcAddress("wglChoosePixelFormatARB"))) {
+               if(!(wglChoosePixelFormat = wglGetProcAddress("wglChoosePixelFormatEXT"))) {
+                       goto fail;
+               }
+               if(!(wglGetPixelFormatAttribiv = wglGetProcAddress("wglGetPixelFormatAttribivEXT"))) {
+                       goto fail;
+               }
+       } else {
+               if(!(wglGetPixelFormatAttribiv = wglGetProcAddress("wglGetPixelFormatAttribivARB"))) {
+                       goto fail;
+               }
+       }
+       wglMakeCurrent(0, 0);
+       wglDeleteContext(tmpctx);
+       DestroyWindow(tmpwin);
+       UnregisterClass(TMPCLASS, hinst);
+
+       /* create the real window and context */
+       if(!(win = CreateWindow("MiniGLUT", title, WS_OVERLAPPEDWINDOW, init_x,
+                                       init_y, width, height, 0, 0, hinst, 0))) {
+               panic("Failed to create window\n");
+       }
+       dc = GetDC(win);
+
+       if(!(pixfmt = choose_pixfmt(init_mode))) {
+               panic("Failed to find suitable pixel format\n");
+       }
+       if(!SetPixelFormat(dc, pixfmt, &tmppfd)) {
+               panic("Failed to set the selected pixel format\n");
+       }
+       if(!(ctx = wglCreateContext(dc))) {
+               panic("Failed to create the OpenGL context\n");
+       }
+       wglMakeCurrent(dc, ctx);
+
+       GETATTR(WGL_RED_BITS, &ctx_info.rsize);
+       GETATTR(WGL_GREEN_BITS, &ctx_info.gsize);
+       GETATTR(WGL_BLUE_BITS, &ctx_info.bsize);
+       GETATTR(WGL_ALPHA_BITS, &ctx_info.asize);
+       GETATTR(WGL_DEPTH_BITS, &ctx_info.zsize);
+       GETATTR(WGL_STENCIL_BITS, &ctx_info.ssize);
+       GETATTR(WGL_DOUBLE_BUFFER, &ctx_info.dblbuf);
+       GETATTR(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, &ctx_info.srgb);
+       GETATTR(WGL_SAMPLES_ARB, &ctx_info.samples);
+       return 0;
+
+fail:
+       if(tmpctx) {
+               wglMakeCurrent(0, 0);
+               wglDeleteContext(tmpctx);
+       }
+       if(tmpwin) {
+               DestroyWindow(tmpwin);
+       }
+       UnregisterClass(TMPCLASS, hinst);
+       return -1;
+}
+
+
+static void create_window(const char *title)
+{
+       int pixfmt;
+       PIXELFORMATDESCRIPTOR pfd = {0};
+       RECT rect;
+       int width, height;
+
+       rect.left = init_x;
+       rect.top = init_y;
+       rect.right = init_x + init_width;
+       rect.bottom = init_y + init_height;
+       AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, 0);
+       width = rect.right - rect.left;
+       height = rect.bottom - rect.top;
+
+       if(create_window_wglext(title, width, height) == -1) {
+
+               if(!(win = CreateWindow("MiniGLUT", title, WS_OVERLAPPEDWINDOW,
+                                       rect.left, rect.top, width, height, 0, 0, hinst, 0))) {
+                       panic("Failed to create window\n");
+               }
+               dc = GetDC(win);
+
+               pfd.nSize = sizeof pfd;
+               pfd.nVersion = 1;
+               pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
+               if(init_mode & GLUT_STEREO) {
+                       pfd.dwFlags |= PFD_STEREO;
+               }
+               pfd.iPixelType = init_mode & GLUT_INDEX ? PFD_TYPE_COLORINDEX : PFD_TYPE_RGBA;
+               pfd.cColorBits = 24;
+               if(init_mode & GLUT_ALPHA) {
+                       pfd.cAlphaBits = 8;
+               }
+               if(init_mode & GLUT_ACCUM) {
+                       pfd.cAccumBits = 24;
+               }
+               if(init_mode & GLUT_DEPTH) {
+                       pfd.cDepthBits = 24;
+               }
+               if(init_mode & GLUT_STENCIL) {
+                       pfd.cStencilBits = 8;
+               }
+               pfd.iLayerType = PFD_MAIN_PLANE;
+
+               if(!(pixfmt = ChoosePixelFormat(dc, &pfd))) {
+                       panic("Failed to find suitable pixel format\n");
+               }
+               if(!SetPixelFormat(dc, pixfmt, &pfd)) {
+                       panic("Failed to set the selected pixel format\n");
+               }
+               if(!(ctx = wglCreateContext(dc))) {
+                       panic("Failed to create the OpenGL context\n");
+               }
+               wglMakeCurrent(dc, ctx);
+
+               DescribePixelFormat(dc, pixfmt, sizeof pfd, &pfd);
+               ctx_info.rsize = pfd.cRedBits;
+               ctx_info.gsize = pfd.cGreenBits;
+               ctx_info.bsize = pfd.cBlueBits;
+               ctx_info.asize = pfd.cAlphaBits;
+               ctx_info.zsize = pfd.cDepthBits;
+               ctx_info.ssize = pfd.cStencilBits;
+               ctx_info.dblbuf = pfd.dwFlags & PFD_DOUBLEBUFFER ? 1 : 0;
+               ctx_info.samples = 0;
+               ctx_info.srgb = 0;
+       }
+
+       ShowWindow(win, 1);
+       SetForegroundWindow(win);
+       SetFocus(win);
+       upd_pending = 1;
+       reshape_pending = 1;
+}
+
+static HRESULT CALLBACK handle_message(HWND win, unsigned int msg, WPARAM wparam, LPARAM lparam)
+{
+       static int mouse_x, mouse_y;
+       int x, y, key;
+
+       switch(msg) {
+       case WM_CLOSE:
+               if(win) DestroyWindow(win);
+               break;
+
+       case WM_DESTROY:
+               cleanup();
+               quit = 1;
+               PostQuitMessage(0);
+               break;
+
+       case WM_PAINT:
+               upd_pending = 1;
+               ValidateRect(win, 0);
+               break;
+
+       case WM_SIZE:
+               x = lparam & 0xffff;
+               y = lparam >> 16;
+               if(x != win_width && y != win_height) {
+                       win_width = x;
+                       win_height = y;
+                       if(cb_reshape) {
+                               reshape_pending = 0;
+                               cb_reshape(win_width, win_height);
+                       }
+               }
+               break;
+
+       case WM_SHOWWINDOW:
+               mapped = wparam;
+               if(cb_vis) cb_vis(mapped ? GLUT_VISIBLE : GLUT_NOT_VISIBLE);
+               break;
+
+       case WM_KEYDOWN:
+       case WM_SYSKEYDOWN:
+               update_modkeys();
+               key = translate_vkey(wparam);
+               if(key < 256) {
+                       if(cb_keydown) {
+                               cb_keydown((unsigned char)key, mouse_x, mouse_y);
+                       }
+               } else {
+                       if(cb_skeydown) {
+                               cb_skeydown(key, mouse_x, mouse_y);
+                       }
+               }
+               break;
+
+       case WM_KEYUP:
+       case WM_SYSKEYUP:
+               update_modkeys();
+               key = translate_vkey(wparam);
+               if(key < 256) {
+                       if(cb_keyup) {
+                               cb_keyup((unsigned char)key, mouse_x, mouse_y);
+                       }
+               } else {
+                       if(cb_skeyup) {
+                               cb_skeyup(key, mouse_x, mouse_y);
+                       }
+               }
+               break;
+
+       case WM_LBUTTONDOWN:
+               handle_mbutton(0, 1, wparam, lparam);
+               break;
+       case WM_MBUTTONDOWN:
+               handle_mbutton(1, 1, wparam, lparam);
+               break;
+       case WM_RBUTTONDOWN:
+               handle_mbutton(2, 1, wparam, lparam);
+               break;
+       case WM_LBUTTONUP:
+               handle_mbutton(0, 0, wparam, lparam);
+               break;
+       case WM_MBUTTONUP:
+               handle_mbutton(1, 0, wparam, lparam);
+               break;
+       case WM_RBUTTONUP:
+               handle_mbutton(2, 0, wparam, lparam);
+               break;
+
+       case WM_MOUSEMOVE:
+               if(wparam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) {
+                       if(cb_motion) cb_motion(lparam & 0xffff, lparam >> 16);
+               } else {
+                       if(cb_passive) cb_passive(lparam & 0xffff, lparam >> 16);
+               }
+               break;
+
+       case WM_SYSCOMMAND:
+               wparam &= 0xfff0;
+               if(wparam == SC_KEYMENU || wparam == SC_SCREENSAVE || wparam == SC_MONITORPOWER) {
+                       return 0;
+               }
+       default:
+               return DefWindowProc(win, msg, wparam, lparam);
+       }
+
+       return 0;
+}
+
+static void update_modkeys(void)
+{
+       if(GetKeyState(VK_SHIFT) & 0x8000) {
+               modstate |= GLUT_ACTIVE_SHIFT;
+       } else {
+               modstate &= ~GLUT_ACTIVE_SHIFT;
+       }
+       if(GetKeyState(VK_CONTROL) & 0x8000) {
+               modstate |= GLUT_ACTIVE_CTRL;
+       } else {
+               modstate &= ~GLUT_ACTIVE_CTRL;
+       }
+       if(GetKeyState(VK_MENU) & 0x8000) {
+               modstate |= GLUT_ACTIVE_ALT;
+       } else {
+               modstate &= ~GLUT_ACTIVE_ALT;
+       }
+}
+
+static int translate_vkey(int vkey)
+{
+       switch(vkey) {
+       case VK_PRIOR: return GLUT_KEY_PAGE_UP;
+       case VK_NEXT: return GLUT_KEY_PAGE_DOWN;
+       case VK_END: return GLUT_KEY_END;
+       case VK_HOME: return GLUT_KEY_HOME;
+       case VK_LEFT: return GLUT_KEY_LEFT;
+       case VK_UP: return GLUT_KEY_UP;
+       case VK_RIGHT: return GLUT_KEY_RIGHT;
+       case VK_DOWN: return GLUT_KEY_DOWN;
+       default:
+               break;
+       }
+
+       if(vkey >= 'A' && vkey <= 'Z') {
+               vkey += 32;
+       } else if(vkey >= VK_F1 && vkey <= VK_F12) {
+               vkey -= VK_F1 + GLUT_KEY_F1;
+       }
+
+       return vkey;
+}
+
+static void handle_mbutton(int bn, int st, WPARAM wparam, LPARAM lparam)
+{
+       int x, y;
+
+       update_modkeys();
+
+       if(cb_mouse) {
+               x = lparam & 0xffff;
+               y = lparam >> 16;
+               cb_mouse(bn, st ? GLUT_DOWN : GLUT_UP, x, y);
+       }
+}
+
+static void get_window_pos(int *x, int *y)
+{
+       RECT rect;
+       GetWindowRect(win, &rect);
+       *x = rect.left;
+       *y = rect.top;
+}
+
+static void get_window_size(int *w, int *h)
+{
+       RECT rect;
+       GetClientRect(win, &rect);
+       *w = rect.right - rect.left;
+       *h = rect.bottom - rect.top;
+}
+
+static void get_screen_size(int *scrw, int *scrh)
+{
+       *scrw = GetSystemMetrics(SM_CXSCREEN);
+       *scrh = GetSystemMetrics(SM_CYSCREEN);
+}
+#endif /* BUILD_WIN32 */
+
+#if defined(__unix__) || defined(__APPLE__)
+#include <sys/time.h>
+
+#ifdef MINIGLUT_USE_LIBC
+#define sys_gettimeofday(tv, tz)       gettimeofday(tv, tz)
+#else
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz);
+#endif
+
+static long get_msec(void)
+{
+       static struct timeval tv0;
+       struct timeval tv;
+
+       sys_gettimeofday(&tv, 0);
+       if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
+               tv0 = tv;
+               return 0;
+       }
+       return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
+}
+#endif /* UNIX */
+#ifdef _WIN32
+static long get_msec(void)
+{
+       static long t0;
+       long tm;
+
+#ifdef MINIGLUT_NO_WINMM
+       tm = GetTickCount();
+#else
+       tm = timeGetTime();
+#endif
+       if(!t0) {
+               t0 = tm;
+               return 0;
+       }
+       return tm - t0;
+}
+#endif
+
+static void panic(const char *msg)
+{
+       const char *end = msg;
+       while(*end) end++;
+       sys_write(2, msg, end - msg);
+       sys_exit(1);
+}
+
+
+#ifdef MINIGLUT_USE_LIBC
+#include <stdlib.h>
+#ifdef __unix__
+#include <unistd.h>
+#endif
+
+static void sys_exit(int status)
+{
+       exit(status);
+}
+
+static int sys_write(int fd, const void *buf, int count)
+{
+       return write(fd, buf, count);
+}
+
+#else  /* !MINIGLUT_USE_LIBC */
+
+#ifdef __linux__
+#ifdef __x86_64__
+static void sys_exit(int status)
+{
+       asm volatile(
+               "syscall\n\t"
+               :: "a"(60), "D"(status));
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+       long res;
+       asm volatile(
+               "syscall\n\t"
+               : "=a"(res)
+               : "a"(1), "D"(fd), "S"(buf), "d"(count));
+       return res;
+}
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+       int res;
+       asm volatile(
+               "syscall\n\t"
+               : "=a"(res)
+               : "a"(96), "D"(tv), "S"(tz));
+       return res;
+}
+#endif /* __x86_64__ */
+#ifdef __i386__
+static void sys_exit(int status)
+{
+       asm volatile(
+               "int $0x80\n\t"
+               :: "a"(1), "b"(status));
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+       int res;
+       asm volatile(
+               "int $0x80\n\t"
+               : "=a"(res)
+               : "a"(4), "b"(fd), "c"(buf), "d"(count));
+       return res;
+}
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+       int res;
+       asm volatile(
+               "int $0x80\n\t"
+               : "=a"(res)
+               : "a"(78), "b"(tv), "c"(tz));
+       return res;
+}
+#endif /* __i386__ */
+#endif /* __linux__ */
+
+#ifdef _WIN32
+static void sys_exit(int status)
+{
+       ExitProcess(status);
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+       unsigned long wrsz = 0;
+
+       HANDLE out = GetStdHandle(fd == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
+       if(!WriteFile(out, buf, count, &wrsz, 0)) {
+               return -1;
+       }
+       return wrsz;
+}
+#endif /* _WIN32 */
+#endif /* !MINIGLUT_USE_LIBC */
+
+
+/* ----------------- primitives ------------------ */
+#ifdef MINIGLUT_USE_LIBC
+#include <stdlib.h>
+#include <math.h>
+
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+       *sptr = sin(angle);
+       *cptr = cos(angle);
+}
+
+float mglut_atan(float x)
+{
+       return atan(x);
+}
+
+#else  /* !MINIGLUT_USE_LIBC */
+
+#ifdef __GNUC__
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+       asm volatile(
+               "flds %2\n\t"
+               "fsincos\n\t"
+               "fstps %1\n\t"
+               "fstps %0\n\t"
+               : "=m"(*sptr), "=m"(*cptr)
+               : "m"(angle)
+       );
+}
+
+float mglut_atan(float x)
+{
+       float res;
+       asm volatile(
+               "flds %1\n\t"
+               "fld1\n\t"
+               "fpatan\n\t"
+               "fstps %0\n\t"
+               : "=m"(res)
+               : "m"(x)
+       );
+       return res;
+}
+#endif
+
+#ifdef _MSC_VER
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+       float s, c;
+       __asm {
+               fld angle
+               fsincos
+               fstp c
+               fstp s
+       }
+       *sptr = s;
+       *cptr = c;
+}
+
+float mglut_atan(float x)
+{
+       float res;
+       __asm {
+               fld x
+               fld1
+               fpatan
+               fstp res
+       }
+       return res;
+}
+#endif
+
+#ifdef __WATCOMC__
+#pragma aux mglut_sincos = \
+       "fsincos" \
+       "fstp dword ptr [edx]" \
+       "fstp dword ptr [eax]" \
+       parm[8087][eax][edx]    \
+       modify[8087];
+
+#pragma aux mglut_atan = \
+       "fld1" \
+       "fpatan" \
+       parm[8087] \
+       value[8087] \
+       modify [8087];
+#endif /* __WATCOMC__ */
+
+#endif /* !MINIGLUT_USE_LIBC */
+
+#define PI     3.1415926536f
+
+void glutSolidSphere(float rad, int slices, int stacks)
+{
+       int i, j, k, gray;
+       float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
+       float du = 1.0f / (float)slices;
+       float dv = 1.0f / (float)stacks;
+
+       glBegin(GL_QUADS);
+       for(i=0; i<stacks; i++) {
+               v = i * dv;
+               for(j=0; j<slices; j++) {
+                       u = j * du;
+                       for(k=0; k<4; k++) {
+                               gray = k ^ (k >> 1);
+                               s = gray & 1 ? u + du : u;
+                               t = gray & 2 ? v + dv : v;
+                               theta = s * PI * 2.0f;
+                               phi = t * PI;
+                               mglut_sincos(theta, &sintheta, &costheta);
+                               mglut_sincos(phi, &sinphi, &cosphi);
+                               x = sintheta * sinphi;
+                               y = costheta * sinphi;
+                               z = cosphi;
+
+                               glColor3f(s, t, 1);
+                               glTexCoord2f(s, t);
+                               glNormal3f(x, y, z);
+                               glVertex3f(x * rad, y * rad, z * rad);
+                       }
+               }
+       }
+       glEnd();
+}
+
+void glutWireSphere(float rad, int slices, int stacks)
+{
+       glPushAttrib(GL_POLYGON_BIT);
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+       glutSolidSphere(rad, slices, stacks);
+       glPopAttrib();
+}
+
+void glutSolidCube(float sz)
+{
+       int i, j, idx, gray, flip, rotx;
+       float vpos[3], norm[3];
+       float rad = sz * 0.5f;
+
+       glBegin(GL_QUADS);
+       for(i=0; i<6; i++) {
+               flip = i & 1;
+               rotx = i >> 2;
+               idx = (~i & 2) - rotx;
+               norm[0] = norm[1] = norm[2] = 0.0f;
+               norm[idx] = flip ^ ((i >> 1) & 1) ? -1 : 1;
+               glNormal3fv(norm);
+               vpos[idx] = norm[idx] * rad;
+               for(j=0; j<4; j++) {
+                       gray = j ^ (j >> 1);
+                       vpos[i & 2] = (gray ^ flip) & 1 ? rad : -rad;
+                       vpos[rotx + 1] = (gray ^ (rotx << 1)) & 2 ? rad : -rad;
+                       glTexCoord2f(gray & 1, gray >> 1);
+                       glVertex3fv(vpos);
+               }
+       }
+       glEnd();
+}
+
+void glutWireCube(float sz)
+{
+       glPushAttrib(GL_POLYGON_BIT);
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+       glutSolidCube(sz);
+       glPopAttrib();
+}
+
+static void draw_cylinder(float rbot, float rtop, float height, int slices, int stacks)
+{
+       int i, j, k, gray;
+       float x, y, z, s, t, u, v, theta, phi, sintheta, costheta, sinphi, cosphi, rad;
+       float du = 1.0f / (float)slices;
+       float dv = 1.0f / (float)stacks;
+
+       rad = rbot - rtop;
+       phi = mglut_atan((rad < 0 ? -rad : rad) / height);
+       mglut_sincos(phi, &sinphi, &cosphi);
+
+       glBegin(GL_QUADS);
+       for(i=0; i<stacks; i++) {
+               v = i * dv;
+               for(j=0; j<slices; j++) {
+                       u = j * du;
+                       for(k=0; k<4; k++) {
+                               gray = k ^ (k >> 1);
+                               s = gray & 2 ? u + du : u;
+                               t = gray & 1 ? v + dv : v;
+                               rad = rbot + (rtop - rbot) * t;
+                               theta = s * PI * 2.0f;
+                               mglut_sincos(theta, &sintheta, &costheta);
+
+                               x = sintheta * cosphi;
+                               y = costheta * cosphi;
+                               z = sinphi;
+
+                               glColor3f(s, t, 1);
+                               glTexCoord2f(s, t);
+                               glNormal3f(x, y, z);
+                               glVertex3f(sintheta * rad, costheta * rad, t * height);
+                       }
+               }
+       }
+       glEnd();
+}
+
+void glutSolidCone(float base, float height, int slices, int stacks)
+{
+       draw_cylinder(base, 0, height, slices, stacks);
+}
+
+void glutWireCone(float base, float height, int slices, int stacks)
+{
+       glPushAttrib(GL_POLYGON_BIT);
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+       glutSolidCone(base, height, slices, stacks);
+       glPopAttrib();
+}
+
+void glutSolidCylinder(float rad, float height, int slices, int stacks)
+{
+       draw_cylinder(rad, rad, height, slices, stacks);
+}
+
+void glutWireCylinder(float rad, float height, int slices, int stacks)
+{
+       glPushAttrib(GL_POLYGON_BIT);
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+       glutSolidCylinder(rad, height, slices, stacks);
+       glPopAttrib();
+}
+
+void glutSolidTorus(float inner_rad, float outer_rad, int sides, int rings)
+{
+       int i, j, k, gray;
+       float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
+       float du = 1.0f / (float)rings;
+       float dv = 1.0f / (float)sides;
+
+       glBegin(GL_QUADS);
+       for(i=0; i<rings; i++) {
+               u = i * du;
+               for(j=0; j<sides; j++) {
+                       v = j * dv;
+                       for(k=0; k<4; k++) {
+                               gray = k ^ (k >> 1);
+                               s = gray & 1 ? u + du : u;
+                               t = gray & 2 ? v + dv : v;
+                               theta = s * PI * 2.0f;
+                               phi = t * PI * 2.0f;
+                               mglut_sincos(theta, &sintheta, &costheta);
+                               mglut_sincos(phi, &sinphi, &cosphi);
+                               x = sintheta * sinphi;
+                               y = costheta * sinphi;
+                               z = cosphi;
+
+                               glColor3f(s, t, 1);
+                               glTexCoord2f(s, t);
+                               glNormal3f(x, y, z);
+
+                               x = x * inner_rad + sintheta * outer_rad;
+                               y = y * inner_rad + costheta * outer_rad;
+                               z *= inner_rad;
+                               glVertex3f(x, y, z);
+                       }
+               }
+       }
+       glEnd();
+}
+
+void glutWireTorus(float inner_rad, float outer_rad, int sides, int rings)
+{
+       glPushAttrib(GL_POLYGON_BIT);
+       glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+       glutSolidTorus(inner_rad, outer_rad, sides, rings);
+       glPopAttrib();
+}
+
+void glutSolidTeapot(float size)
+{
+}
+
+void glutWireTeapot(float size)
+{
+}
diff --git a/src/glut/miniglut.h b/src/glut/miniglut.h
new file mode 100644 (file)
index 0000000..666e5fc
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+MiniGLUT - minimal GLUT subset without dependencies
+Copyright (C) 2020  John Tsiombikas <nuclear@member.fsf.org>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+#ifndef MINIGLUT_H_
+#define MINIGLUT_H_
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+
+#ifdef _MSC_VER
+#pragma comment (lib, "opengl32")
+#ifndef MINIGLUT_NO_WINMM
+#pragma comment (lib, "winmm")
+#endif
+#endif /* MSVC */
+
+#endif
+#include <GL/gl.h>
+
+/* mode flags for glutInitDisplayMode */
+#define GLUT_RGB                       0
+#define GLUT_RGBA                      0
+#define GLUT_INDEX                     0x001
+#define GLUT_SINGLE                    0
+#define GLUT_DOUBLE                    0x002
+#define GLUT_ACCUM                     0x004
+#define GLUT_ALPHA                     0x008
+#define GLUT_DEPTH                     0x010
+#define GLUT_STENCIL           0x020
+#define GLUT_STEREO                    0x040
+#define GLUT_MULTISAMPLE       0x100
+#define GLUT_SRGB                      0x200
+
+enum { GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, GLUT_RIGHT_BUTTON };
+enum { GLUT_UP, GLUT_DOWN };
+enum { GLUT_NOT_VISIBLE, GLUT_VISIBLE };
+enum { GLUT_LEFT, GLUT_ENTERED };
+
+/* cursors */
+enum {
+       GLUT_CURSOR_INHERIT,
+       GLUT_CURSOR_LEFT_ARROW,
+       GLUT_CURSOR_NONE
+};
+
+/* glutGet */
+enum {
+       GLUT_WINDOW_X,
+       GLUT_WINDOW_Y,
+       GLUT_WINDOW_WIDTH,
+       GLUT_WINDOW_HEIGHT,
+       GLUT_WINDOW_BUFFER_SIZE,
+       GLUT_WINDOW_STENCIL_SIZE,
+       GLUT_WINDOW_DEPTH_SIZE,
+       GLUT_WINDOW_RED_SIZE,
+       GLUT_WINDOW_GREEN_SIZE,
+       GLUT_WINDOW_BLUE_SIZE,
+       GLUT_WINDOW_ALPHA_SIZE,
+       GLUT_WINDOW_DOUBLEBUFFER,
+       GLUT_WINDOW_RGBA,
+       GLUT_WINDOW_NUM_SAMPLES,
+       GLUT_WINDOW_STEREO,
+       GLUT_WINDOW_SRGB,
+       GLUT_WINDOW_CURSOR,
+       GLUT_SCREEN_WIDTH,
+       GLUT_SCREEN_HEIGHT,
+       GLUT_INIT_DISPLAY_MODE,
+       GLUT_INIT_WINDOW_X,
+       GLUT_INIT_WINDOW_Y,
+       GLUT_INIT_WINDOW_WIDTH,
+       GLUT_INIT_WINDOW_HEIGHT,
+       GLUT_ELAPSED_TIME
+};
+
+enum {
+       GLUT_KEY_HOME = 0xff50,
+       GLUT_KEY_LEFT = 0xff51,
+       GLUT_KEY_UP,
+       GLUT_KEY_RIGHT,
+       GLUT_KEY_DOWN,
+       GLUT_KEY_PAGE_UP,
+       GLUT_KEY_PAGE_DOWN,
+       GLUT_KEY_END = 0xff57,
+       GLUT_KEY_INSERT = 0xff63,
+       GLUT_KEY_F1 = 0xffbe,
+       GLUT_KEY_F2,
+       GLUT_KEY_F3,
+       GLUT_KEY_F4,
+       GLUT_KEY_F5,
+       GLUT_KEY_F6,
+       GLUT_KEY_F7,
+       GLUT_KEY_F8,
+       GLUT_KEY_F9,
+       GLUT_KEY_F10,
+       GLUT_KEY_F11,
+       GLUT_KEY_F12
+};
+
+/* returned by glutGetModifiers */
+#define GLUT_ACTIVE_SHIFT      1
+#define GLUT_ACTIVE_CTRL       4
+#define GLUT_ACTIVE_ALT                8
+
+typedef void (*glut_cb)(void);
+typedef void (*glut_cb_reshape)(int x, int y);
+typedef void (*glut_cb_state)(int state);
+typedef void (*glut_cb_keyb)(unsigned char key, int x, int y);
+typedef void (*glut_cb_special)(int key, int x, int y);
+typedef void (*glut_cb_mouse)(int bn, int state, int x, int y);
+typedef void (*glut_cb_motion)(int x, int y);
+typedef void (*glut_cb_sbmotion)(int x, int y, int z);
+typedef void (*glut_cb_sbbutton)(int bn, int state);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void glutInit(int *argc, char **argv);
+void glutInitWindowPosition(int x, int y);
+void glutInitWindowSize(int xsz, int ysz);
+void glutInitDisplayMode(unsigned int mode);
+void glutCreateWindow(const char *title);
+
+void glutExit(void);
+void glutMainLoop(void);
+void glutMainLoopEvent(void);
+
+void glutPostRedisplay(void);
+void glutSwapBuffers(void);
+void glutPositionWindow(int x, int y);
+void glutReshapeWindow(int xsz, int ysz);
+void glutFullScreen(void);
+void glutSetWindowTitle(const char *title);
+void glutSetIconTitle(const char *title);
+void glutSetCursor(int cursor);
+
+void glutIdleFunc(glut_cb func);
+void glutDisplayFunc(glut_cb func);
+void glutReshapeFunc(glut_cb_reshape func);
+void glutVisibilityFunc(glut_cb_state func);
+void glutEntryFunc(glut_cb_state func);
+void glutKeyboardFunc(glut_cb_keyb func);
+void glutKeyboardUpFunc(glut_cb_keyb func);
+void glutSpecialFunc(glut_cb_special func);
+void glutSpecialUpFunc(glut_cb_special func);
+void glutMouseFunc(glut_cb_mouse func);
+void glutMotionFunc(glut_cb_motion func);
+void glutPassiveMotionFunc(glut_cb_motion func);
+void glutSpaceballMotionFunc(glut_cb_sbmotion func);
+void glutSpaceballRotateFunc(glut_cb_sbmotion func);
+void glutSpaceballButtonFunc(glut_cb_sbbutton func);
+
+int glutGet(unsigned int s);
+int glutGetModifiers(void);
+int glutExtensionSupported(char *ext);
+
+void glutSolidSphere(float rad, int slices, int stacks);
+void glutWireSphere(float rad, int slices, int stacks);
+void glutSolidCube(float sz);
+void glutWireCube(float sz);
+void glutSolidCone(float base, float height, int slices, int stacks);
+void glutWireCone(float base, float height, int slices, int stacks);
+void glutSolidCylinder(float rad, float height, int slices, int stacks);
+void glutSolidTorus(float inner_rad, float outer_rad, int sides, int rings);
+void glutWireTorus(float inner_rad, float outer_rad, int sides, int rings);
+void glutSolidTeapot(float size);
+void glutWireTeapot(float size);
+
+#ifdef __cplusplus
+}      /* extern "C" */
+#endif
+
+#endif /* MINIGLUT_H_ */
diff --git a/src/glut/w32_dirent.c b/src/glut/w32_dirent.c
new file mode 100644 (file)
index 0000000..d399023
--- /dev/null
@@ -0,0 +1,327 @@
+/*
+ * dirent.c
+ * This file has no copyright assigned and is placed in the Public Domain.
+ * This file is a part of the mingw-runtime package.
+ * No warranty is given; refer to the file DISCLAIMER within the package.
+ *
+ * Derived from DIRLIB.C by Matt J. Weinstein 
+ * This note appears in the DIRLIB.H
+ * DIRLIB.H by M. J. Weinstein   Released to public domain 1-Jan-89
+ *
+ * Updated by Jeremy Bettis <jeremy@hksys.com>
+ * Significantly revised and rewinddir, seekdir and telldir added by Colin
+ * Peters <colin@fu.is.saga-u.ac.jp>
+ *     
+ */
+#ifdef _MSC_VER
+
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <io.h>
+#include <direct.h>
+#include "w32_dirent.h"
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h> /* for GetFileAttributes */
+
+#define SUFFIX "*"
+#define        SLASH   "\\"
+
+/*
+ * opendir
+ *
+ * Returns a pointer to a DIR structure appropriately filled in to begin
+ * searching a directory.
+ */
+DIR * opendir (const char *szPath)
+{
+  DIR *nd;
+  unsigned int rc;
+  char szFullPath[MAX_PATH];
+       
+  errno = 0;
+
+  if (!szPath)
+    {
+      errno = EFAULT;
+      return (DIR *) 0;
+    }
+
+  if (szPath[0] == ('\0'))
+    {
+      errno = ENOTDIR;
+      return (DIR *) 0;
+    }
+
+  /* Attempt to determine if the given path really is a directory. */
+  rc = GetFileAttributes (szPath);
+  if (rc == (unsigned int)-1)
+    {
+      /* call GetLastError for more error info */
+      errno = ENOENT;
+      return (DIR *) 0;
+    }
+  if (!(rc & FILE_ATTRIBUTE_DIRECTORY))
+    {
+      /* Error, entry exists but not a directory. */
+      errno = ENOTDIR;
+      return (DIR *) 0;
+    }
+
+  /* Make an absolute pathname.  */
+  _fullpath (szFullPath, szPath, MAX_PATH);
+
+  /* Allocate enough space to store DIR structure and the complete
+   * directory path given. */
+  nd = (DIR *) malloc (sizeof (DIR) + (strlen (szFullPath)
+                                          + strlen (SLASH)
+                                          + strlen (SUFFIX) + 1)
+                                         * sizeof (char));
+
+  if (!nd)
+    {
+      /* Error, out of memory. */
+      errno = ENOMEM;
+      return (DIR *) 0;
+    }
+
+  /* Create the search expression. */
+  strcpy (nd->dd_name, szFullPath);
+
+  /* Add on a slash if the path does not end with one. */
+  if (nd->dd_name[0] != ('\0')
+      && strrchr (nd->dd_name, ('/')) != nd->dd_name
+                                           + strlen (nd->dd_name) - 1
+      && strrchr (nd->dd_name, ('\\')) != nd->dd_name
+                                            + strlen (nd->dd_name) - 1)
+    {
+      strcat (nd->dd_name, SLASH);
+    }
+
+  /* Add on the search pattern */
+  strcat (nd->dd_name, SUFFIX);
+
+  /* Initialize handle to -1 so that a premature closedir doesn't try
+   * to call _findclose on it. */
+  nd->dd_handle = -1;
+
+  /* Initialize the status. */
+  nd->dd_stat = 0;
+
+  /* Initialize the dirent structure. ino and reclen are invalid under
+   * Win32, and name simply points at the appropriate part of the
+   * findfirst structure. */
+  nd->dd_dir.d_ino = 0;
+  nd->dd_dir.d_reclen = 0;
+  nd->dd_dir.d_namlen = 0;
+  memset (nd->dd_dir.d_name, 0, FILENAME_MAX);
+
+  return nd;
+}
+
+
+/*
+ * readdir
+ *
+ * Return a pointer to a dirent structure filled with the information on the
+ * next entry in the directory.
+ */
+struct dirent *
+readdir (DIR * dirp)
+{
+  errno = 0;
+
+  /* Check for valid DIR struct. */
+  if (!dirp)
+    {
+      errno = EFAULT;
+      return (struct dirent *) 0;
+    }
+
+  if (dirp->dd_stat < 0)
+    {
+      /* We have already returned all files in the directory
+       * (or the structure has an invalid dd_stat). */
+      return (struct dirent *) 0;
+    }
+  else if (dirp->dd_stat == 0)
+    {
+      /* We haven't started the search yet. */
+      /* Start the search */
+      dirp->dd_handle = (long)_findfirst (dirp->dd_name, &(dirp->dd_dta));
+
+      if (dirp->dd_handle == -1)
+       {
+         /* Whoops! Seems there are no files in that
+          * directory. */
+         dirp->dd_stat = -1;
+       }
+      else
+       {
+         dirp->dd_stat = 1;
+       }
+    }
+  else
+    {
+      /* Get the next search entry. */
+      if (_findnext (dirp->dd_handle, &(dirp->dd_dta)))
+       {
+         /* We are off the end or otherwise error.     
+            _findnext sets errno to ENOENT if no more file
+            Undo this. */ 
+         DWORD winerr = GetLastError ();
+         if (winerr == ERROR_NO_MORE_FILES)
+           errno = 0;  
+         _findclose (dirp->dd_handle);
+         dirp->dd_handle = -1;
+         dirp->dd_stat = -1;
+       }
+      else
+       {
+         /* Update the status to indicate the correct
+          * number. */
+         dirp->dd_stat++;
+       }
+    }
+
+  if (dirp->dd_stat > 0)
+    {
+      /* Successfully got an entry. Everything about the file is
+       * already appropriately filled in except the length of the
+       * file name. */
+      dirp->dd_dir.d_namlen = (unsigned short)strlen (dirp->dd_dta.name);
+      strcpy (dirp->dd_dir.d_name, dirp->dd_dta.name);
+      return &dirp->dd_dir;
+    }
+
+  return (struct dirent *) 0;
+}
+
+
+/*
+ * closedir
+ *
+ * Frees up resources allocated by opendir.
+ */
+int
+closedir (DIR * dirp)
+{
+  int rc;
+
+  errno = 0;
+  rc = 0;
+
+  if (!dirp)
+    {
+      errno = EFAULT;
+      return -1;
+    }
+
+  if (dirp->dd_handle != -1)
+    {
+      rc = _findclose (dirp->dd_handle);
+    }
+
+  /* Delete the dir structure. */
+  free (dirp);
+
+  return rc;
+}
+
+/*
+ * rewinddir
+ *
+ * Return to the beginning of the directory "stream". We simply call findclose
+ * and then reset things like an opendir.
+ */
+void
+rewinddir (DIR * dirp)
+{
+  errno = 0;
+
+  if (!dirp)
+    {
+      errno = EFAULT;
+      return;
+    }
+
+  if (dirp->dd_handle != -1)
+    {
+      _findclose (dirp->dd_handle);
+    }
+
+  dirp->dd_handle = -1;
+  dirp->dd_stat = 0;
+}
+
+/*
+ * telldir
+ *
+ * Returns the "position" in the "directory stream" which can be used with
+ * seekdir to go back to an old entry. We simply return the value in stat.
+ */
+long
+telldir (DIR * dirp)
+{
+  errno = 0;
+
+  if (!dirp)
+    {
+      errno = EFAULT;
+      return -1;
+    }
+  return dirp->dd_stat;
+}
+
+/*
+ * seekdir
+ *
+ * Seek to an entry previously returned by telldir. We rewind the directory
+ * and call readdir repeatedly until either dd_stat is the position number
+ * or -1 (off the end). This is not perfect, in that the directory may
+ * have changed while we weren't looking. But that is probably the case with
+ * any such system.
+ */
+void
+seekdir (DIR * dirp, long lPos)
+{
+  errno = 0;
+
+  if (!dirp)
+    {
+      errno = EFAULT;
+      return;
+    }
+
+  if (lPos < -1)
+    {
+      /* Seeking to an invalid position. */
+      errno = EINVAL;
+      return;
+    }
+  else if (lPos == -1)
+    {
+      /* Seek past end. */
+      if (dirp->dd_handle != -1)
+       {
+         _findclose (dirp->dd_handle);
+       }
+      dirp->dd_handle = -1;
+      dirp->dd_stat = -1;
+    }
+  else
+    {
+      /* Rewind and read forward to the appropriate index. */
+      rewinddir (dirp);
+
+      while ((dirp->dd_stat < lPos) && readdir (dirp))
+       ;
+    }
+}
+
+#else
+
+int _utk_w32_dirent_c_shut_up_stupid_compiler_warning;
+
+#endif /* WIN32 */
diff --git a/src/glut/w32_dirent.h b/src/glut/w32_dirent.h
new file mode 100644 (file)
index 0000000..5b256bc
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * DIRENT.H (formerly DIRLIB.H)
+ * This file has no copyright assigned and is placed in the Public Domain.
+ * This file is a part of the mingw-runtime package.
+ * No warranty is given; refer to the file DISCLAIMER within the package.
+ *
+ */
+#ifndef W32_DIRENT_H_
+#define W32_DIRENT_H_
+
+#include <stdio.h>
+#include <io.h>
+
+#ifndef RC_INVOKED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct dirent
+{
+       long            d_ino;          /* Always zero. */
+       unsigned short  d_reclen;       /* Always zero. */
+       unsigned short  d_namlen;       /* Length of name in d_name. */
+       char            d_name[FILENAME_MAX]; /* File name. */
+};
+
+/*
+ * This is an internal data structure. Good programmers will not use it
+ * except as an argument to one of the functions below.
+ * dd_stat field is now int (was short in older versions).
+ */
+typedef struct
+{
+       /* disk transfer area for this dir */
+       struct _finddata_t      dd_dta;
+
+       /* dirent struct to return from dir (NOTE: this makes this thread
+        * safe as long as only one thread uses a particular DIR struct at
+        * a time) */
+       struct dirent           dd_dir;
+
+       /* _findnext handle */
+       long                    dd_handle;
+
+       /*
+         * Status of search:
+        *   0 = not started yet (next entry to read is first entry)
+        *  -1 = off the end
+        *   positive = 0 based index of next entry
+        */
+       int                     dd_stat;
+
+       /* given path for dir with search pattern (struct is extended) */
+       char                    dd_name[1];
+} DIR;
+
+DIR* __cdecl opendir (const char*);
+struct dirent* __cdecl readdir (DIR*);
+int __cdecl closedir (DIR*);
+void __cdecl rewinddir (DIR*);
+long __cdecl telldir (DIR*);
+void __cdecl seekdir (DIR*, long);
+
+
+/* wide char versions */
+
+struct _wdirent
+{
+       long            d_ino;          /* Always zero. */
+       unsigned short  d_reclen;       /* Always zero. */
+       unsigned short  d_namlen;       /* Length of name in d_name. */
+       wchar_t         d_name[FILENAME_MAX]; /* File name. */
+};
+
+/*
+ * This is an internal data structure. Good programmers will not use it
+ * except as an argument to one of the functions below.
+ */
+typedef struct
+{
+       /* disk transfer area for this dir */
+       struct _wfinddata_t     dd_dta;
+
+       /* dirent struct to return from dir (NOTE: this makes this thread
+        * safe as long as only one thread uses a particular DIR struct at
+        * a time) */
+       struct _wdirent         dd_dir;
+
+       /* _findnext handle */
+       long                    dd_handle;
+
+       /*
+         * Status of search:
+        *   0 = not started yet (next entry to read is first entry)
+        *  -1 = off the end
+        *   positive = 0 based index of next entry
+        */
+       int                     dd_stat;
+
+       /* given path for dir with search pattern (struct is extended) */
+       wchar_t                 dd_name[1];
+} _WDIR;
+
+
+
+_WDIR* __cdecl _wopendir (const wchar_t*);
+struct _wdirent*  __cdecl _wreaddir (_WDIR*);
+int __cdecl _wclosedir (_WDIR*);
+void __cdecl _wrewinddir (_WDIR*);
+long __cdecl _wtelldir (_WDIR*);
+void __cdecl _wseekdir (_WDIR*, long);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* Not RC_INVOKED */
+
+#endif /* Not _DIRENT_H_ */