From http://www.jwz.org/xscreensaver/xscreensaver-5.22.tar.gz
[xscreensaver] / hacks / glx / kaleidocycle.c
1 /* kaleidocycle, Copyright (c) 2013 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  * A loop of rotating tetrahedra.  Created by jwz, July 2013.
12  * Inspired by, and some math borrowed from:
13  * http://www.kaleidocycles.de/pdf/kaleidocycles_theory.pdf
14  * http://intothecontinuum.tumblr.com/post/50873970770/an-even-number-of-at-least-8-regular-tetrahedra
15  */
16
17
18 #define DEFAULTS        "*delay:        30000       \n" \
19                         "*count:        16          \n" \
20                         "*showFPS:      False       \n" \
21                         "*wireframe:    False       \n" \
22
23 # define refresh_kaleidocycle 0
24 # define release_kaleidocycle 0
25 #undef countof
26 #define countof(x) (sizeof((x))/sizeof((*x)))
27
28 #include "xlockmore.h"
29 #include "colors.h"
30 #include "normals.h"
31 #include "rotator.h"
32 #include "gltrackball.h"
33 #include <ctype.h>
34
35 #ifdef USE_GL /* whole file */
36
37 #define DEF_SPIN        "Z"
38 #define DEF_WANDER      "False"
39 #define DEF_SPEED       "1.0"
40
41 typedef struct {
42   GLXContext *glx_context;
43   rotator *rot, *rot2;
44   trackball_state *trackball;
45   Bool button_down_p;
46
47   int min_count, max_count;
48   Bool startup_p;
49
50   int ncolors;
51   XColor *colors;
52   int ccolor;
53
54   GLfloat count;
55   GLfloat th, dth;
56
57   enum { STATIC, IN, OUT } mode, prev_mode;
58
59 } kaleidocycle_configuration;
60
61 static kaleidocycle_configuration *bps = NULL;
62
63 static char *do_spin;
64 static GLfloat speed;
65 static Bool do_wander;
66
67 static XrmOptionDescRec opts[] = {
68   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
69   { "+spin",   ".spin",   XrmoptionNoArg, "" },
70   { "-wander", ".wander", XrmoptionNoArg, "True" },
71   { "+wander", ".wander", XrmoptionNoArg, "False" },
72   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
73 };
74
75 static argtype vars[] = {
76   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
77   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
78   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
79 };
80
81 ENTRYPOINT ModeSpecOpt kaleidocycle_opts = {countof(opts), opts, countof(vars), vars, NULL};
82
83
84
85 /* Window management, etc
86  */
87 ENTRYPOINT void
88 reshape_kaleidocycle (ModeInfo *mi, int width, int height)
89 {
90   GLfloat h = (GLfloat) height / (GLfloat) width;
91
92   glViewport (0, 0, (GLint) width, (GLint) height);
93
94   glMatrixMode(GL_PROJECTION);
95   glLoadIdentity();
96   gluPerspective (30.0, 1/h, 1.0, 100.0);
97
98   glMatrixMode(GL_MODELVIEW);
99   glLoadIdentity();
100   gluLookAt( 0.0, 0.0, 30.0,
101              0.0, 0.0, 0.0,
102              0.0, 1.0, 0.0);
103
104   glClear(GL_COLOR_BUFFER_BIT);
105 }
106
107
108 ENTRYPOINT Bool
109 kaleidocycle_handle_event (ModeInfo *mi, XEvent *event)
110 {
111   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
112
113   if (event->xany.type == ButtonPress &&
114       event->xbutton.button == Button1)
115     {
116       bp->button_down_p = True;
117       gltrackball_start (bp->trackball,
118                          event->xbutton.x, event->xbutton.y,
119                          MI_WIDTH (mi), MI_HEIGHT (mi));
120       return True;
121     }
122   else if (event->xany.type == ButtonRelease &&
123            event->xbutton.button == Button1)
124     {
125       bp->button_down_p = False;
126       return True;
127     }
128   else if (event->xany.type == ButtonPress &&
129            (event->xbutton.button == Button4 ||
130             event->xbutton.button == Button5 ||
131             event->xbutton.button == Button6 ||
132             event->xbutton.button == Button7))
133     {
134       gltrackball_mousewheel (bp->trackball, event->xbutton.button, 5,
135                               !!event->xbutton.state);
136       return True;
137     }
138   else if (event->xany.type == MotionNotify &&
139            bp->button_down_p)
140     {
141       gltrackball_track (bp->trackball,
142                          event->xmotion.x, event->xmotion.y,
143                          MI_WIDTH (mi), MI_HEIGHT (mi));
144       return True;
145     }
146
147   return False;
148 }
149
150
151
152 ENTRYPOINT void 
153 init_kaleidocycle (ModeInfo *mi)
154 {
155   kaleidocycle_configuration *bp;
156   int wire = MI_IS_WIREFRAME(mi);
157   int i;
158
159   if (!bps) {
160     bps = (kaleidocycle_configuration *)
161       calloc (MI_NUM_SCREENS(mi), sizeof (kaleidocycle_configuration));
162     if (!bps) {
163       fprintf(stderr, "%s: out of memory\n", progname);
164       exit(1);
165     }
166   }
167
168   bp = &bps[MI_SCREEN(mi)];
169
170   bp->glx_context = init_GL(mi);
171
172   reshape_kaleidocycle (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
173
174   glLineWidth (4);
175
176   if (!wire)
177     {
178       GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
179       GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
180       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
181       GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};
182
183       glEnable(GL_LIGHTING);
184       glEnable(GL_LIGHT0);
185       glEnable(GL_DEPTH_TEST);
186       glEnable(GL_CULL_FACE);
187
188       glLightfv(GL_LIGHT0, GL_POSITION, pos);
189       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
190       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
191       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
192
193       glEnable (GL_BLEND);
194       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
195     }
196
197   {
198     Bool spinx = False, spiny = False, spinz = False;
199     double spin_speed   = 0.25;
200     double wander_speed = 0.005;
201     double spin_accel   = 0.2;
202     double twist_speed  = 0.25;
203     double twist_accel  = 1.0;
204
205     char *s = do_spin;
206     while (*s)
207       {
208         if      (*s == 'x' || *s == 'X') spinx = True;
209         else if (*s == 'y' || *s == 'Y') spiny = True;
210         else if (*s == 'z' || *s == 'Z') spinz = True;
211         else if (*s == '0') ;
212         else
213           {
214             fprintf (stderr,
215          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
216                      progname, do_spin);
217             exit (1);
218           }
219         s++;
220       }
221
222     bp->rot = make_rotator (spinx ? spin_speed : 0,
223                             spiny ? spin_speed : 0,
224                             spinz ? spin_speed : 0,
225                             spin_accel,
226                             do_wander ? wander_speed : 0,
227                             False);
228     bp->rot2 = make_rotator (twist_speed, 0, 0, twist_accel, 0, True);
229
230     bp->trackball = gltrackball_init ();
231   }
232
233   if (MI_COUNT(mi) < 8) MI_COUNT(mi) = 8;
234   if (MI_COUNT(mi) & 1) MI_COUNT(mi)++;
235
236   bp->min_count = 8;
237   bp->max_count = 12 + MI_COUNT(mi) * 1.3;
238   if (bp->max_count & 1) bp->max_count++;
239   bp->startup_p = True;
240
241   bp->count = 0;
242   bp->mode = IN;
243   bp->prev_mode = IN;
244
245 /*
246   bp->count = MI_COUNT(mi);
247   bp->mode = STATIC;
248 */
249
250   bp->ncolors = 512;
251   if (! bp->colors)
252     bp->colors = (XColor *) calloc(bp->ncolors, sizeof(XColor));
253   make_uniform_colormap (0, 0, 0,
254                          bp->colors, &bp->ncolors,
255                          False, 0, False);
256
257   for (i = 0; i < bp->ncolors; i++)
258     {
259       /* make colors twice as bright */
260       bp->colors[i].red   = (bp->colors[i].red   >> 2) + 0x7FFF;
261       bp->colors[i].green = (bp->colors[i].green >> 2) + 0x7FFF;
262       bp->colors[i].blue  = (bp->colors[i].blue  >> 2) + 0x7FFF;
263     }
264
265   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
266 }
267
268
269
270 /* t = toroidal rotation, a = radial position
271    colors = 4 colors, 4 channels each.
272  */
273 static void
274 draw_tetra (ModeInfo *mi, double t, double a, Bool reflect_p,
275             GLfloat *colors)
276 {
277   int wire = MI_IS_WIREFRAME(mi);
278
279   XYZ v1, v2, v3, P, Q;
280   XYZ verts[4];
281   int i;
282
283   double scale;
284   double sint = sin(t);
285   double cost = cos(t);
286   double tana = tan(a);
287   double sint2 = sint * sint;
288   double tana2 = tana * tana;
289
290   v1.x = cost;
291   v1.y = 0;
292   v1.z = sint;
293
294   scale = 1 / sqrt (1 + sint2 * tana2);
295   v2.x = scale * -sint;
296   v2.y = scale * -sint * tana;
297   v2.z = scale * cost;
298
299   v3.x = scale * -sint2 * tana;
300   v3.y = scale;
301   v3.z = scale * cost * sint * tana;
302
303   P.x = v3.y / tana - v3.x;
304   P.y = 0;
305   P.z = -v3.z / 2;
306
307   Q.x = v3.y / tana;
308   Q.y = v3.y;
309   Q.z = v3.z / 2;
310
311   verts[0] = P;
312   verts[1] = P;
313   verts[2] = Q;
314   verts[3] = Q;
315
316   scale = sqrt(2) / 2;
317   verts[0].x = P.x - scale * v1.x;
318   verts[0].y = P.y - scale * v1.y;
319   verts[0].z = P.z - scale * v1.z;
320
321   verts[1].x = P.x + scale * v1.x;
322   verts[1].y = P.y + scale * v1.y;
323   verts[1].z = P.z + scale * v1.z;
324
325   verts[2].x = Q.x - scale * v2.x;
326   verts[2].y = Q.y - scale * v2.y;
327   verts[2].z = Q.z - scale * v2.z;
328
329   verts[3].x = Q.x + scale * v2.x;
330   verts[3].y = Q.y + scale * v2.y;
331   verts[3].z = Q.z + scale * v2.z;
332
333   for (i = 0; i < 4; i++)
334     {
335       Bool reflect2_p = ((i + (reflect_p != 0)) & 1);
336       XYZ a = verts[(i+1) % 4];
337       XYZ b = verts[(i+2) % 4];
338       XYZ c = verts[(i+3) % 4];
339       XYZ n = ((i & 1)
340                ? calc_normal (b, a, c)
341                : calc_normal (a, b, c));
342       if (wire)
343         glColor4fv (colors + (i * 4));
344       else
345         glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colors + (i * 4));
346
347       glFrontFace (reflect2_p ? GL_CW : GL_CCW);
348       glBegin (wire ? GL_LINE_LOOP : GL_TRIANGLES);
349       glNormal3f (n.x, n.y, n.z);
350       glVertex3f (a.x, a.y, a.z);
351       glVertex3f (b.x, b.y, b.z);
352       glVertex3f (c.x, c.y, c.z);
353       glEnd();
354     }
355 }
356
357
358 /* Reflect through the plane normal to the given vector.
359  */
360 static void
361 reflect (double x, double y, double z)
362 {
363   GLfloat m[4][4];
364
365   m[0][0] = 1 - (2 * x * x);
366   m[1][0] = -2 * x * y;
367   m[2][0] = -2 * x * z;
368   m[3][0] = 0;
369
370   m[0][1] = -2 * x * y;
371   m[1][1] = 1 - (2 * y * y);
372   m[2][1] = -2 * y * z;
373   m[3][1] = 0;
374
375   m[0][2] = -2 * x * z;
376   m[1][2] = -2 * y * z;
377   m[2][2] = 1 - (2 * z * z);
378   m[3][2] = 0;
379
380   m[0][3] = 0;
381   m[1][3] = 0;
382   m[2][3] = 0;
383   m[3][3] = 1;
384
385   glMultMatrixf (&m[0][0]);
386 }
387
388
389 ENTRYPOINT void
390 draw_kaleidocycle (ModeInfo *mi)
391 {
392   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
393   Display *dpy = MI_DISPLAY(mi);
394   Window window = MI_WINDOW(mi);
395   GLfloat colors[4*4];
396   GLfloat count;
397   double t, a;
398   int i;
399
400   GLfloat bspec[4] = {1.0, 1.0, 1.0, 1.0};
401   GLfloat bshiny   = 128.0;
402
403   if (!bp->glx_context)
404     return;
405
406   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
407
408   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
409
410   mi->polygon_count = 0;
411
412   glShadeModel(GL_SMOOTH);
413   glEnable(GL_DEPTH_TEST);
414   glEnable(GL_NORMALIZE);
415   glEnable(GL_CULL_FACE);
416
417   glPushMatrix ();
418
419   {
420     double x, y, z;
421     get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
422     glTranslatef((x - 0.5) * 5,
423                  (y - 0.5) * 5,
424                  (z - 0.5) * 10);
425
426     /* Do it twice because we don't track the device's orientation. */
427     glRotatef( current_device_rotation(), 0, 0, 1);
428     gltrackball_rotate (bp->trackball);
429     glRotatef(-current_device_rotation(), 0, 0, 1);
430
431     get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p);
432     glRotatef (x * 360, 1, 0, 0);
433     glRotatef (y * 360, 0, 1, 0);
434     glRotatef (z * 360, 0, 0, 1);
435
436     get_rotation (bp->rot2, &x, &y, &z, !bp->button_down_p);
437     bp->th = x * 360 * 10 * speed;
438
439     /* Make sure the twist is always in motion.  Without this, the rotator
440        sometimes stops, and for too long, and it's boring looking.
441      */
442     bp->th += speed * bp->dth++;
443     while (bp->dth > 360) bp->dth -= 360;
444     while (bp->th  > 360) bp->th  -= 360;
445   }
446
447   glMaterialfv (GL_FRONT, GL_SPECULAR,  bspec);
448   glMateriali  (GL_FRONT, GL_SHININESS, bshiny);
449
450
451   /* Evenly spread the colors of the faces, and cycle them together.
452    */
453   for (i = 0; i < 4; i++)
454     {
455       int o  = bp->ncolors / 4;
456       int c = (bp->ccolor + (o*i)) % bp->ncolors;
457       colors[i*4+0] = bp->colors[c].red   / 65536.0;
458       colors[i*4+1] = bp->colors[c].green / 65536.0;
459       colors[i*4+2] = bp->colors[c].blue  / 65536.0;
460       colors[i*4+3] = 1;
461     }
462   bp->ccolor++;
463   if (bp->ccolor >= bp->ncolors) bp->ccolor = 0;
464
465
466   count = (int) floor (bp->count);
467   while (count < 8) count++;
468   if (((int) floor (count)) & 1) count++;
469
470   a = 2 * M_PI / (bp->count < 8 ? 8 : bp->count);
471   t = bp->th / (180 / M_PI);
472
473   glScalef (3, 3, 3);
474   glScalef (a, a, a);
475   glRotatef (90, 0, 0, 1);
476 /*  glRotatef (45, 0, 1, 0); */
477
478   for (i = 0; i <= (int) floor (bp->count); i++)
479     {
480       Bool flip_p = (i & 1);
481       glPushMatrix();
482       glRotatef ((i/2) * 4 * 180 / bp->count, 0, 0, 1);
483       if (flip_p) reflect (-sin(a), cos(a), 0);
484
485       if (bp->mode != STATIC && i >= (int) floor (bp->count))
486         {
487           /* Fractional bp->count means the last piece is in transition */
488           GLfloat scale = bp->count - (int) floor (bp->count);
489           GLfloat tick = 0.07 * speed;
490           GLfloat ocount = bp->count;
491           GLfloat alpha;
492
493           /* Fill in faster if we're starting up */
494           if (bp->count < MI_COUNT(mi))
495             tick *= 2;
496
497           glScalef (scale, scale, scale);
498
499           switch (bp->mode) {
500           case IN: break;
501           case OUT: tick = -tick; break;
502           case STATIC: tick = 0; break;
503           }
504
505           bp->count += tick;
506
507           if (bp->mode == IN
508               ? floor (ocount) != floor (bp->count)
509               : ceil  (ocount) != ceil  (bp->count))
510             {
511               if (bp->mode == IN)
512                 bp->count = floor (ocount) + 1;
513               else
514                 bp->count = ceil  (ocount) - 1;
515
516               if (((int) floor (bp->count)) & 1 ||
517                   (bp->mode == IN && 
518                    (bp->count < MI_COUNT(mi) &&
519                     bp->startup_p)))
520                 {
521                   /* keep going if it's odd, or less than 8. */
522                   bp->count = round(bp->count);
523                 }
524               else
525                 {
526                   bp->mode = STATIC;
527                   bp->startup_p = False;
528                 }
529             }
530
531           alpha = (scale * scale * scale * scale);
532           if (alpha < 0.4) alpha = 0.4;
533           colors[3] = colors[7] = colors[11] = colors[15] = alpha;
534         }
535
536       draw_tetra (mi, t, a, flip_p, colors);
537       mi->polygon_count += 4;
538
539       glPopMatrix();
540     }
541
542   if (bp->mode == STATIC && !(random() % 200)) {
543     if (bp->count <= bp->min_count)
544       bp->mode = IN;
545     else if (bp->count >= bp->max_count)
546       bp->mode = OUT;
547     else
548       bp->mode = bp->prev_mode;
549
550     bp->prev_mode = bp->mode;
551   }
552
553
554   mi->recursion_depth = ceil (bp->count);
555
556   glPopMatrix ();
557
558   if (mi->fps_p) do_fps (mi);
559   glFinish();
560
561   glXSwapBuffers(dpy, window);
562 }
563
564 XSCREENSAVER_MODULE ("Kaleidocycle", kaleidocycle)
565
566 #endif /* USE_GL */