http://ftp.ksu.edu.tw/FTP/FreeBSD/distfiles/xscreensaver-4.20.tar.gz
[xscreensaver] / hacks / glx / glknots.c
1 /* glknots, Copyright (c) 2003, 2004 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  *
11  * Generates some 3D knots (closed loops).
12  * Inspired by Paul Bourke <pbourke@swin.edu.au> at
13  * http://astronomy.swin.edu.au/~pbourke/curves/knot/
14  */
15
16 #include <X11/Intrinsic.h>
17
18 extern XtAppContext app;
19
20 #define PROGCLASS       "GLKnots"
21 #define HACK_INIT       init_knot
22 #define HACK_DRAW       draw_knot
23 #define HACK_RESHAPE    reshape_knot
24 #define HACK_HANDLE_EVENT knot_handle_event
25 #define EVENT_MASK      PointerMotionMask
26 #define sws_opts        xlockmore_opts
27
28 #define DEF_SPIN        "XYZ"
29 #define DEF_WANDER      "True"
30 #define DEF_SPEED       "1.0"
31 #define DEF_THICKNESS   "0.3"
32 #define DEF_SEGMENTS    "800"
33 #define DEF_DURATION    "8"
34
35 #define DEFAULTS        "*delay:        30000       \n" \
36                         "*showFPS:      False       \n" \
37                         "*wireframe:    False       \n" \
38                         "*speed:      " DEF_SPEED " \n" \
39                         "*spin:       " DEF_SPIN   "\n" \
40                         "*wander:     " DEF_WANDER "\n" \
41                         "*thickness:  " DEF_THICKNESS "\n" \
42                         "*segments:   " DEF_SEGMENTS "\n" \
43                         "*duration:   " DEF_DURATION "\n" \
44
45 #undef countof
46 #define countof(x) (sizeof((x))/sizeof((*x)))
47
48 #include "xlockmore.h"
49 #include "colors.h"
50 #include "tube.h"
51 #include "rotator.h"
52 #include "gltrackball.h"
53 #include <ctype.h>
54
55 #ifdef USE_GL /* whole file */
56
57 #include <GL/glu.h>
58
59 typedef struct {
60   GLXContext *glx_context;
61   rotator *rot;
62   trackball_state *trackball;
63   Bool button_down_p;
64
65   GLuint knot_list;
66
67   int ncolors;
68   XColor *colors;
69   int ccolor;
70
71   int mode;  /* 0 = normal, 1 = out, 2 = in */
72   int mode_tick;
73   Bool clear_p;
74
75 } knot_configuration;
76
77 static knot_configuration *bps = NULL;
78
79 static char *do_spin;
80 static GLfloat speed;
81 static Bool do_wander;
82 static GLfloat thickness;
83 static unsigned int segments;
84 static int duration;
85
86 static XrmOptionDescRec opts[] = {
87   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
88   { "+spin",   ".spin",   XrmoptionNoArg, "" },
89   { "-wander", ".wander", XrmoptionNoArg, "True" },
90   { "+wander", ".wander", XrmoptionNoArg, "False" },
91   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
92   { "-thickness", ".thickness",  XrmoptionSepArg, 0 },
93   { "-segments",  ".segments",   XrmoptionSepArg, 0 },
94   { "-duration",  ".duration",   XrmoptionSepArg, 0 },
95 };
96
97 static argtype vars[] = {
98   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
99   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
100   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
101   {&thickness, "thickness", "Thickness",  DEF_THICKNESS, t_Float},
102   {&segments,  "segments",  "Segments",   DEF_SEGMENTS,  t_Int},
103   {&duration,  "duration",  "Duration",   DEF_DURATION,  t_Int},
104 };
105
106 ModeSpecOpt sws_opts = {countof(opts), opts, countof(vars), vars, NULL};
107
108
109 static void
110 make_knot (ModeInfo *mi)
111 {
112   int wire = MI_IS_WIREFRAME(mi);
113
114   GLfloat diam = (4 * thickness);
115   int faces = (wire ? 3 : 6);
116
117   unsigned int i;
118   double x, y, z, ox=0, oy=0, oz=0;
119   double mu;
120
121   double p[9];
122
123   Bool blobby_p = (0 == (random() % 5));
124   Bool type = (random() % 2);
125
126   for (i = 0; i < countof(p); i++)
127     {
128       p[i] = 1 + (random() % 4);
129       if (! (random() % 3))
130         p[i] += (random() % 5);
131     }
132
133   if (type == 1)
134     {
135       p[0] += 4;
136       p[1] *= ((p[0] + p[0]) / 10);
137       blobby_p = False;
138     }
139
140   mi->polygon_count = 0;
141
142   for (i = 0; i <= segments; i++)
143     {
144       if (type == 0)
145         {
146           mu = i * (M_PI * 2) / segments;
147           x = 10 * (cos(mu) + cos(p[0]*mu)) + cos(p[1]*mu) + cos(p[2]*mu);
148           y = 6 * sin(mu) + 10 * sin(p[3]*mu);
149           z = 16 * sin(p[4]*mu) * sin(p[5]*mu/2) + p[6]*sin(p[7]*mu) -
150             2 * sin(p[8]*mu);
151         }
152       else if (type == 1)
153         {
154           mu = i * (M_PI * 2) * p[0] / (double) segments;
155           x = 10 * cos(mu) * (1 + cos(p[1] * mu/ p[0]) / 2.0);
156           y = 25 * sin(p[1] * mu / p[0]) / 2.0;
157           z = 10 * sin(mu) * (1 + cos(p[1] * mu/ p[0]) / 2.0);
158         }
159       else
160         abort();
161
162       if (i != 0)
163         {
164           GLfloat dist = sqrt ((x-ox)*(x-ox) +
165                                (y-oy)*(y-oy) +
166                                (z-oz)*(z-oz));
167           GLfloat di;
168           if (!blobby_p)
169             di = diam;
170           else
171             {
172               di = dist * (segments / 500.0);
173               di = (di * di * 3);
174             }
175
176           tube (ox, oy, oz,
177                 x, y, z,
178                 di, dist/3,
179                 faces, True, wire, wire);
180
181           mi->polygon_count += faces;
182         }
183
184       ox = x;
185       oy = y;
186       oz = z;
187    }
188 }
189
190
191 /* Window management, etc
192  */
193 void
194 reshape_knot (ModeInfo *mi, int width, int height)
195 {
196   GLfloat h = (GLfloat) height / (GLfloat) width;
197
198   glViewport (0, 0, (GLint) width, (GLint) height);
199
200   glMatrixMode(GL_PROJECTION);
201   glLoadIdentity();
202   gluPerspective (30.0, 1/h, 1.0, 100.0);
203
204   glMatrixMode(GL_MODELVIEW);
205   glLoadIdentity();
206   gluLookAt( 0.0, 0.0, 30.0,
207              0.0, 0.0, 0.0,
208              0.0, 1.0, 0.0);
209
210   glClear(GL_COLOR_BUFFER_BIT);
211 }
212
213
214 static void
215 new_knot (ModeInfo *mi)
216 {
217   knot_configuration *bp = &bps[MI_SCREEN(mi)];
218   int i;
219
220   bp->clear_p = !!(random() % 15);
221
222   bp->ncolors = 128;
223   bp->colors = (XColor *) calloc(bp->ncolors, sizeof(XColor));
224   make_smooth_colormap (0, 0, 0,
225                         bp->colors, &bp->ncolors,
226                         False, 0, False);
227
228   for (i = 0; i < bp->ncolors; i++)
229     {
230       /* make colors twice as bright */
231       bp->colors[i].red   = (bp->colors[i].red   >> 2) + 0x7FFF;
232       bp->colors[i].green = (bp->colors[i].green >> 2) + 0x7FFF;
233       bp->colors[i].blue  = (bp->colors[i].blue  >> 2) + 0x7FFF;
234     }
235
236   glNewList (bp->knot_list, GL_COMPILE);
237   make_knot (mi);
238   glEndList ();
239 }
240
241
242 Bool
243 knot_handle_event (ModeInfo *mi, XEvent *event)
244 {
245   knot_configuration *bp = &bps[MI_SCREEN(mi)];
246
247   if (event->xany.type == ButtonPress &&
248       event->xbutton.button == Button1)
249     {
250       bp->button_down_p = True;
251       gltrackball_start (bp->trackball,
252                          event->xbutton.x, event->xbutton.y,
253                          MI_WIDTH (mi), MI_HEIGHT (mi));
254       return True;
255     }
256   else if (event->xany.type == ButtonRelease &&
257            event->xbutton.button == Button1)
258     {
259       bp->button_down_p = False;
260       return True;
261     }
262   else if (event->xany.type == ButtonPress &&
263            (event->xbutton.button == Button4 ||
264             event->xbutton.button == Button5))
265     {
266       gltrackball_mousewheel (bp->trackball, event->xbutton.button, 5,
267                               !!event->xbutton.state);
268       return True;
269     }
270   else if (event->xany.type == MotionNotify &&
271            bp->button_down_p)
272     {
273       gltrackball_track (bp->trackball,
274                          event->xmotion.x, event->xmotion.y,
275                          MI_WIDTH (mi), MI_HEIGHT (mi));
276       return True;
277     }
278
279   return False;
280 }
281
282
283
284 void 
285 init_knot (ModeInfo *mi)
286 {
287   knot_configuration *bp;
288   int wire = MI_IS_WIREFRAME(mi);
289
290   if (!bps) {
291     bps = (knot_configuration *)
292       calloc (MI_NUM_SCREENS(mi), sizeof (knot_configuration));
293     if (!bps) {
294       fprintf(stderr, "%s: out of memory\n", progname);
295       exit(1);
296     }
297
298     bp = &bps[MI_SCREEN(mi)];
299   }
300
301   bp = &bps[MI_SCREEN(mi)];
302
303   bp->glx_context = init_GL(mi);
304
305   if (thickness <= 0) thickness = 0.001;
306   else if (thickness > 1) thickness = 1;
307
308   if (segments < 10) segments = 10;
309
310   reshape_knot (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
311
312   if (!wire)
313     {
314       GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
315       GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
316       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
317       GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};
318
319       glEnable(GL_LIGHTING);
320       glEnable(GL_LIGHT0);
321       glEnable(GL_DEPTH_TEST);
322       glEnable(GL_CULL_FACE);
323
324       glLightfv(GL_LIGHT0, GL_POSITION, pos);
325       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
326       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
327       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
328     }
329
330   {
331     Bool spinx=False, spiny=False, spinz=False;
332     double spin_speed   = 2.0;
333     double wander_speed = 0.05;
334     double spin_accel   = 0.2;
335
336     char *s = do_spin;
337     while (*s)
338       {
339         if      (*s == 'x' || *s == 'X') spinx = True;
340         else if (*s == 'y' || *s == 'Y') spiny = True;
341         else if (*s == 'z' || *s == 'Z') spinz = True;
342         else
343           {
344             fprintf (stderr,
345          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
346                      progname, do_spin);
347             exit (1);
348           }
349         s++;
350       }
351
352     bp->rot = make_rotator (spinx ? spin_speed : 0,
353                             spiny ? spin_speed : 0,
354                             spinz ? spin_speed : 0,
355                             spin_accel,
356                             do_wander ? wander_speed : 0,
357                             (spinx && spiny && spinz));
358     bp->trackball = gltrackball_init ();
359   }
360
361   bp->knot_list = glGenLists (1);
362   new_knot(mi);
363
364   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
365 }
366
367
368 void
369 draw_knot (ModeInfo *mi)
370 {
371   knot_configuration *bp = &bps[MI_SCREEN(mi)];
372   Display *dpy = MI_DISPLAY(mi);
373   Window window = MI_WINDOW(mi);
374
375   static GLfloat bcolor[4] = {0.0, 0.0, 0.0, 1.0};
376   static GLfloat bspec[4]  = {1.0, 1.0, 1.0, 1.0};
377   static GLfloat bshiny    = 128.0;
378
379   static time_t last_time = 0;
380
381   if (!bp->glx_context)
382     return;
383
384   if (bp->mode == 0)
385     {
386       static int tick = 0;
387       if (tick++ > 10)
388         {
389           time_t now = time((time_t *) 0);
390           if (last_time == 0) last_time = now;
391           tick = 0;
392           if (!bp->button_down_p &&
393               now - last_time >= duration)
394             {
395               bp->mode = 1;    /* go out */
396               bp->mode_tick = 10 * speed;
397               last_time = now;
398             }
399         }
400     }
401   else if (bp->mode == 1)   /* out */
402     {
403       if (--bp->mode_tick <= 0)
404         {
405           new_knot (mi);
406           bp->mode_tick = 10 * speed;
407           bp->mode = 2;  /* go in */
408         }
409     }
410   else if (bp->mode == 2)   /* in */
411     {
412       if (--bp->mode_tick <= 0)
413         bp->mode = 0;  /* normal */
414     }
415   else
416     abort();
417
418   glShadeModel(GL_SMOOTH);
419
420   glEnable(GL_DEPTH_TEST);
421   glEnable(GL_NORMALIZE);
422   glEnable(GL_CULL_FACE);
423
424   if (bp->clear_p)
425     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
426
427   glPushMatrix ();
428
429   {
430     double x, y, z;
431     get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
432     glTranslatef((x - 0.5) * 8,
433                  (y - 0.5) * 8,
434                  (z - 0.5) * 15);
435
436     gltrackball_rotate (bp->trackball);
437
438     get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p);
439
440     glRotatef (x * 360, 1.0, 0.0, 0.0);
441     glRotatef (y * 360, 0.0, 1.0, 0.0);
442     glRotatef (z * 360, 0.0, 0.0, 1.0);
443   }
444
445   bcolor[0] = bp->colors[bp->ccolor].red   / 65536.0;
446   bcolor[1] = bp->colors[bp->ccolor].green / 65536.0;
447   bcolor[2] = bp->colors[bp->ccolor].blue  / 65536.0;
448   bp->ccolor++;
449   if (bp->ccolor >= bp->ncolors) bp->ccolor = 0;
450
451   glMaterialfv (GL_FRONT, GL_SPECULAR,            bspec);
452   glMateriali  (GL_FRONT, GL_SHININESS,           bshiny);
453   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, bcolor);
454
455   glScalef(0.25, 0.25, 0.25);
456
457   if (bp->mode != 0)
458     {
459       GLfloat s = (bp->mode == 1
460                    ? bp->mode_tick / (10 * speed)
461                    : ((10 * speed) - bp->mode_tick + 1) / (10 * speed));
462       glScalef (s, s, s);
463     }
464
465   glCallList (bp->knot_list);
466
467   glPopMatrix ();
468
469   if (mi->fps_p) do_fps (mi);
470   glFinish();
471
472   glXSwapBuffers(dpy, window);
473 }
474
475 #endif /* USE_GL */