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