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