From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / glx / extrusion.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* extrusion --- extrusion module for xscreensaver */
3 /*-
4  * Permission to use, copy, modify, and distribute this software and its
5  * documentation for any purpose and without fee is hereby granted,
6  * provided that the above copyright notice appear in all copies and that
7  * both that copyright notice and this permission notice appear in
8  * supporting documentation.
9  *
10  * This file is provided AS IS with no warranties of any kind.  The author
11  * shall have no liability with respect to the infringement of copyrights,
12  * trade secrets or any patents by this file or any part thereof.  In no
13  * event will the author be liable for any lost revenue or profits or
14  * other special, indirect and consequential damages.
15
16  * Revision History:
17  * Tue Oct 19 22:24:47 PDT 1999    Initial creation by David Konerding
18  *                                 <dek@cgl.ucsf.edu>
19  *                                                                 
20  * Notes:
21  * This screensaver requires the GLE ("OpenGL Tubing and Extrusion Library")
22  * which can be obtained from http://www.linas.org/gle/index.html
23   */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #ifdef STANDALONE
30 #define DEFAULTS        "*delay:         20000  \n" \
31                                         "*showFPS:       False  \n" \
32                                         "*wireframe: False   \n"
33
34 # define refresh_extrusion 0
35 # define release_extrusion 0
36 # include "xlockmore.h"                         /* from the xscreensaver distribution */
37 #else /* !STANDALONE */
38 # include "xlock.h"                                     /* from the xlockmore distribution */
39 #endif /* !STANDALONE */
40
41 #ifdef USE_GL /* whole file */
42
43 #ifdef HAVE_XMU
44 # ifndef VMS
45 #  include <X11/Xmu/Drawing.h>
46 #else  /* VMS */
47 #  include <Xmu/Drawing.h>
48 # endif /* VMS */
49 #endif
50
51 #undef countof
52 #define countof(x) (sizeof((x))/sizeof((*x)))
53
54 #include "xpm-ximage.h"
55 #include "rotator.h"
56 #include "gltrackball.h"
57 #include "extrusion.h"
58
59 #define checkImageWidth 64
60 #define checkImageHeight 64
61
62
63 #define WIDTH 640
64 #define HEIGHT 480
65
66 #define DEF_LIGHT               "True"
67 #define DEF_TEXTURE             "False"
68 #define DEF_TEX_QUAL   "False"
69 #define DEF_MIPMAP      "False"
70 #define DEF_NAME        "RANDOM"
71 #define DEF_IMAGE       "BUILTIN"
72
73 static int do_light;
74 static int do_texture;
75 static int do_tex_qual;
76 static int do_mipmap;
77 static char *which_name;
78 static char *which_image;
79
80 static XrmOptionDescRec opts[] = {
81   {"-light",           ".extrusion.light",   XrmoptionNoArg, "true" },
82   {"+light",           ".extrusion.light",   XrmoptionNoArg, "false" },
83   {"-texture",         ".extrusion.texture", XrmoptionNoArg, "true" },
84   {"+texture",         ".extrusion.texture", XrmoptionNoArg, "false" },
85   {"-texture",         ".extrusion.texture", XrmoptionNoArg, "true" },
86   {"+texture_quality", ".extrusion.texture", XrmoptionNoArg, "false" },
87   {"-texture_quality", ".extrusion.texture", XrmoptionNoArg, "true" },
88   {"+mipmap",          ".extrusion.mipmap",  XrmoptionNoArg, "false" },
89   {"-mipmap",          ".extrusion.mipmap",  XrmoptionNoArg, "true" },
90   {"-name",            ".extrusion.name",    XrmoptionSepArg, 0 },
91   {"-image",           ".extrusion.image",   XrmoptionSepArg, 0 },
92 };
93
94
95 static argtype vars[] = {
96   {&do_light,    "light",           "Light",           DEF_LIGHT,    t_Bool},
97   {&do_texture,  "texture",         "Texture",         DEF_TEXTURE,  t_Bool},
98   {&do_tex_qual, "texture_quality", "Texture_Quality", DEF_TEX_QUAL, t_Bool},
99   {&do_mipmap,   "mipmap",          "Mipmap",          DEF_MIPMAP,   t_Bool},
100   {&which_name,  "name",            "Name",            DEF_NAME,     t_String},
101   {&which_image, "image",           "Image",           DEF_IMAGE,    t_String},
102 };
103
104
105 static OptionStruct desc[] =
106 {
107   {"-name num", "example 'name' to draw (helix2, helix3, helix4, joinoffset, screw, taper, twistoid)"},
108   {"-/+ light", "whether to do enable lighting (slower)"},
109   {"-/+ texture", "whether to apply a texture (slower)"},
110   {"-image <filename>", "texture image to load"},
111   {"-/+ texture_quality", "whether to use texture smoothing (slower)"},
112   {"-/+ mipmap", "whether to use texture mipmap (slower)"},
113 };
114
115 ENTRYPOINT ModeSpecOpt extrusion_opts = {countof(opts), opts, countof(vars), vars, desc};
116
117 #ifdef USE_MODULES
118 ModStruct   extrusion_description =
119 {"extrusion", "init_extrusion", "draw_extrusion", NULL,
120  "draw_extrusion", "init_extrusion", NULL, &extrusion_opts,
121  1000, 1, 2, 1, 4, 1.0, "",
122  "OpenGL extrusion", 0, NULL};
123 #endif
124
125
126 /* structure for holding the extrusion data */
127 typedef struct {
128   int screen_width, screen_height;
129   GLXContext *glx_context;
130   rotator *rot;
131   trackball_state *trackball;
132   Bool button_down_p;
133   Bool button2_down_p;
134   int mouse_start_x, mouse_start_y;
135   int mouse_x, mouse_y;
136   int mouse_dx, mouse_dy;
137   Window window;
138   XColor fg, bg;
139   int extrusion_number;
140 } extrusionstruct;
141
142 static extrusionstruct *Extrusion = NULL;
143
144
145
146 /* set up a light */
147 static const GLfloat lightOnePosition[] = {40.0, 40, 100.0, 0.0};
148 static const GLfloat lightOneColor[] = {0.99, 0.99, 0.00, 1.0}; 
149
150 static const GLfloat lightTwoPosition[] = {-40.0, 40, 100.0, 0.0};
151 static const GLfloat lightTwoColor[] = {0.00, 0.99, 0.99, 1.0}; 
152
153 float rot_x=0, rot_y=0, rot_z=0;
154 float lastx=0, lasty=0;
155
156 static float max_lastx=400,  max_lasty=400;
157 static float min_lastx=-400, min_lasty=-400;
158
159 struct functions {
160   void (*InitStuff)(void);
161   void (*DrawStuff)(void);
162   char *name;
163 };
164
165 /* currently joinoffset and twistoid look funny-
166    like we're looking at them from the back or something
167 */
168
169 static const struct functions funcs_ptr[] = {
170   {InitStuff_helix2, DrawStuff_helix2, "helix2"},
171   {InitStuff_helix3, DrawStuff_helix3, "helix3"},
172   {InitStuff_helix4, DrawStuff_helix4, "helix4"},
173   {InitStuff_joinoffset, DrawStuff_joinoffset, "joinoffset"},
174   {InitStuff_screw, DrawStuff_screw, "screw"},
175   {InitStuff_taper, DrawStuff_taper, "taper"},
176   {InitStuff_twistoid, DrawStuff_twistoid, "twistoid"},
177 };
178
179 static int num_extrusions = countof(funcs_ptr);
180
181
182 /* BEGINNING OF FUNCTIONS */
183
184
185 static GLubyte *
186 Generate_Image(int *width, int *height, int *format)
187 {
188   GLubyte *result;
189   int i, j, c;
190   int counter=0;
191
192   *width = checkImageWidth;
193   *height = checkImageHeight;
194   result = (GLubyte *)malloc(4 * (*width) * (*height));
195
196   counter = 0;
197   for (i = 0; i < checkImageWidth; i++) {
198     for (j = 0; j < checkImageHeight; j++) {
199       c = (((((i&0x8)==0))^(((j&0x8))==0)))*255;
200       result[counter++] = (GLubyte) c;
201       result[counter++] = (GLubyte) c;
202       result[counter++] = (GLubyte) c;
203       result[counter++] = (GLubyte) 255;
204     }
205   }
206
207   *format = GL_RGBA;
208   return result;
209 }
210
211
212 /* Create a texture in OpenGL.  First an image is loaded 
213    and stored in a raster buffer, then it's  */
214 static void Create_Texture(ModeInfo *mi, const char *filename)
215 {
216   int height, width;
217   GLubyte *image;
218   int format;
219
220   if ( !strncmp(filename, "BUILTIN", 7))
221     {
222     BUILTIN:
223       image = Generate_Image(&width, &height, &format);
224     }
225   else
226     {
227       XImage *ximage = xpm_file_to_ximage (MI_DISPLAY (mi), MI_VISUAL (mi),
228                                            MI_COLORMAP (mi), filename);
229       if (!ximage)
230         goto BUILTIN;
231       image  = (GLubyte *) ximage->data;
232       width  = ximage->width;
233       height = ximage->height;
234       format = GL_RGBA;
235     }
236
237   /* GL_MODULATE or GL_DECAL depending on what you want */
238   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
239   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
240   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
241   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
242   /* perhaps we can edge a bit more speed at the expense of quality */
243   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
244
245   if (do_tex_qual) {
246         /* with texture_quality, the min and mag filters look *much* nice but are *much* slower */
247         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
248         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
249   }
250   else {
251         /* default is to do it quick and dirty */
252         /* if you have mipmaps turned on, but not texture quality, nothing will happen! */
253         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
254         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
255   }
256
257   /* mipmaps make the image look much nicer */
258   if (do_mipmap)
259     {
260       int status;
261       clear_gl_error();
262       status = gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, format,
263                                  GL_UNSIGNED_BYTE, image);
264       if (status)
265         {
266           const char *s = (char *) gluErrorString (status);
267           fprintf (stderr, "%s: error mipmapping %dx%d texture: %s\n",
268                    progname, width, height,
269                    (s ? s : "(unknown)"));
270           exit (1);
271         }
272       check_gl_error("mipmapping");
273     }
274   else
275     {
276       clear_gl_error();
277       glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0,
278                    format, GL_UNSIGNED_BYTE, image);
279       check_gl_error("texture");
280     }
281 }
282
283
284 static void
285 init_rotation (ModeInfo *mi)
286 {
287   extrusionstruct *gp = &Extrusion[MI_SCREEN(mi)];
288   double spin_speed = 0.5;
289   gp->rot = make_rotator (spin_speed, spin_speed, spin_speed,
290                           0.2,
291                           0.005,
292                           True);
293   gp->trackball = gltrackball_init (True);
294
295   lastx = (random() % (int) (max_lastx - min_lastx)) + min_lastx;
296   lasty = (random() % (int) (max_lasty - min_lasty)) + min_lasty;
297 }
298
299
300 /* draw the extrusion once */
301 ENTRYPOINT void
302 draw_extrusion(ModeInfo * mi)
303 {
304   extrusionstruct *gp = &Extrusion[MI_SCREEN(mi)];
305   Display    *display = MI_DISPLAY(mi);
306   Window      window = MI_WINDOW(mi);
307
308   static const GLfloat color[4] = {0.6, 0.6, 0.4, 1.0};
309   /* static const GLfloat spec[4]  = {0.6, 0.6, 0.6, 1.0}; */
310   /* static const GLfloat shiny    = 40.0; */
311
312   double x, y, z;
313
314   if (!gp->glx_context)
315         return;
316
317   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(gp->glx_context));
318
319   glPushMatrix();
320
321   gltrackball_rotate (gp->trackball);
322
323   get_rotation (gp->rot, &x, &y, &z,
324                 !(gp->button_down_p || gp->button2_down_p));
325   glRotatef (x * 360, 1.0, 0.0, 0.0);
326   glRotatef (y * 360, 0.0, 1.0, 0.0);
327   glRotatef (z * 360, 0.0, 0.0, 1.0);
328
329   /* track the mouse only if a button is down. */
330   if (gp->button2_down_p)
331     {
332       gp->mouse_dx += gp->mouse_x - gp->mouse_start_x;
333       gp->mouse_dy += gp->mouse_y - gp->mouse_start_y;
334       gp->mouse_start_x = gp->mouse_x;
335       gp->mouse_start_y = gp->mouse_y;
336     }
337
338   {
339     float scale = (max_lastx - min_lastx);
340     get_position (gp->rot, &x, &y, &z,
341                   !(gp->button_down_p || gp->button2_down_p));
342     lastx = x * scale + min_lastx + gp->mouse_dx;
343     lasty = y * scale + min_lasty + gp->mouse_dy;
344   }
345
346   glScalef(0.5, 0.5, 0.5);
347
348   /* glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            spec); */
349   /* glMateriali  (GL_FRONT_AND_BACK, GL_SHININESS,           shiny); */
350
351   glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
352   glFrontFace(GL_CCW);
353
354   funcs_ptr[gp->extrusion_number].DrawStuff();
355           
356   glPopMatrix();
357
358   if (mi->fps_p) do_fps (mi);
359   glXSwapBuffers(display, window);
360 }
361
362
363 /* set up lighting conditions */
364 static void
365 SetupLight(void)
366 {
367   glLightfv (GL_LIGHT0, GL_POSITION, lightOnePosition);
368   glLightfv (GL_LIGHT0, GL_DIFFUSE, lightOneColor);
369   glLightfv (GL_LIGHT1, GL_POSITION, lightTwoPosition);
370   glLightfv (GL_LIGHT1, GL_DIFFUSE, lightTwoColor);
371
372   glEnable (GL_LIGHT0);
373   glEnable (GL_LIGHT1);
374   glEnable (GL_LIGHTING);
375
376   glColorMaterial (GL_FRONT, GL_DIFFUSE);
377   glColorMaterial (GL_BACK, GL_DIFFUSE);
378   glEnable (GL_COLOR_MATERIAL);
379 }
380
381 /* Standard reshape function */
382 ENTRYPOINT void
383 reshape_extrusion (ModeInfo *mi, int width, int height)
384 {
385   GLfloat h = (GLfloat) height / (GLfloat) width;
386
387   glViewport (0, 0, (GLint) width, (GLint) height);
388
389   glMatrixMode(GL_PROJECTION);
390   glLoadIdentity();
391   gluPerspective (30.0, 1/h, 1.0, 100.0);
392
393   glMatrixMode(GL_MODELVIEW);
394   glLoadIdentity();
395   gluLookAt( 0.0, 0.0, 30.0,
396              0.0, 0.0, 0.0,
397              0.0, 1.0, 0.0);
398
399   glClear(GL_COLOR_BUFFER_BIT);
400 }
401
402
403 /* decide which extrusion example to run */
404 static void
405 chooseExtrusionExample (ModeInfo *mi)
406 {
407   extrusionstruct *gp = &Extrusion[MI_SCREEN(mi)];
408   int i;
409   /* call the extrusion init routine */
410
411   if (!strncmp(which_name, "RANDOM", strlen(which_name))) {
412     gp->extrusion_number = random() % num_extrusions;
413   }
414   else {
415         gp->extrusion_number=-1;
416         for (i=0; i < num_extrusions; i++) {
417           if (!strncmp(which_name, funcs_ptr[i].name, strlen(which_name))) {
418                 gp->extrusion_number = i;
419           }
420         }         
421   }
422         
423   if (gp->extrusion_number < 0 || gp->extrusion_number >= num_extrusions) {
424         fprintf(stderr, "%s: invalid extrusion example number!\n", progname);
425         fprintf(stderr, "%s: known extrusions:\n", progname);
426         for (i=0; i < num_extrusions; i++)
427           fprintf(stderr,"\t%s\n", funcs_ptr[i].name);
428         exit(1);
429   }
430   init_rotation(mi);
431   funcs_ptr[gp->extrusion_number].InitStuff();
432 }
433
434
435 /* main OpenGL initialization routine */
436 static void
437 initializeGL(ModeInfo *mi, GLsizei width, GLsizei height) 
438 {
439   int style;
440   int mode;
441
442   reshape_extrusion(mi, width, height);
443   glViewport( 0, 0, width, height ); 
444
445   glEnable(GL_DEPTH_TEST);
446   glDisable (GL_CULL_FACE);
447   glLightModeli (GL_LIGHT_MODEL_TWO_SIDE, True);
448   glShadeModel(GL_SMOOTH);
449
450 # ifdef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
451   MI_IS_WIREFRAME(mi) = 0;
452 # endif
453
454   if (do_light)
455         SetupLight();
456   if (MI_IS_WIREFRAME(mi)) {
457         glPolygonMode(GL_FRONT,GL_LINE);
458         glPolygonMode(GL_BACK,GL_LINE);
459   }
460   if (do_texture) {
461         Create_Texture(mi, which_image);
462         glEnable(GL_TEXTURE_2D);
463
464         /* configure the pipeline */
465         style = TUBE_JN_CAP;
466         style |= TUBE_CONTOUR_CLOSED;
467         style |= TUBE_NORM_FACET;
468         style |= TUBE_JN_ANGLE;
469         gleSetJoinStyle (style);
470
471         if (do_texture) {
472           mode = GLE_TEXTURE_ENABLE | GLE_TEXTURE_VERTEX_MODEL_FLAT;
473           glMatrixMode (GL_TEXTURE); glLoadIdentity ();
474           glScalef (0.25, 0.1, 1); glMatrixMode (GL_MODELVIEW);
475           gleTextureMode (mode);
476         }
477   }
478
479 }
480
481 ENTRYPOINT Bool
482 extrusion_handle_event (ModeInfo *mi, XEvent *event)
483 {
484   extrusionstruct *gp = &Extrusion[MI_SCREEN(mi)];
485
486   if (event->xany.type == ButtonPress &&
487       (event->xbutton.button == Button4 ||
488        event->xbutton.button == Button5 ||
489        event->xbutton.button == Button6 ||
490        event->xbutton.button == Button7))
491     {
492     }
493   else if (event->xany.type == ButtonPress &&   /* rotate with left button */
494            !event->xbutton.state)               /* if no modifier keys */
495     {
496     }
497   else if (event->xany.type == ButtonPress)  /* deform with other buttons */
498     {                                        /* or with modifier keys */
499       gp->button2_down_p = True;
500     }
501   else if (event->xany.type == ButtonRelease)
502     {
503       gp->button_down_p = False;
504       gp->button2_down_p = False;
505     }
506   else if (event->xany.type == MotionNotify)
507     {
508       if (gp->button2_down_p)
509         {
510           gp->mouse_x = event->xmotion.x;
511           gp->mouse_y = event->xmotion.y;
512         }
513     }
514
515   if (gltrackball_event_handler (event, gp->trackball,
516                                  MI_WIDTH (mi), MI_HEIGHT (mi),
517                                  &gp->button_down_p))
518     return True;
519
520   return False;
521 }
522
523
524 /* xextrusion initialization routine */
525 ENTRYPOINT void
526 init_extrusion (ModeInfo * mi)
527 {
528   int screen = MI_SCREEN(mi);
529   extrusionstruct *gp;
530
531   if (MI_IS_WIREFRAME(mi)) do_light = 0;
532
533   MI_INIT(mi, Extrusion, NULL);
534   gp = &Extrusion[screen];
535
536   gp->window = MI_WINDOW(mi);
537   if ((gp->glx_context = init_GL(mi)) != NULL) {
538         reshape_extrusion(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
539         initializeGL(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
540         chooseExtrusionExample(mi);
541   } else {
542         MI_CLEARWINDOW(mi);
543   }
544
545 }
546
547 XSCREENSAVER_MODULE ("Extrusion", extrusion)
548
549 #endif  /* USE_GL */