5278e6d36b62f61bf8fc2ee468ea2ae6ef0cdbb7
[xscreensaver] / hacks / glx / quasicrystal.c
1 /* quasicrystal, 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  * Overlapping sine waves create interesting plane-tiling interference
12  * patterns.  Created by jwz, Jul 2013.  Inspired by
13  * http://mainisusuallyafunction.blogspot.com/2011/10/quasicrystals-as-sums-of-waves-in-plane.html
14  */
15
16
17 #define DEFAULTS        "*delay:        30000       \n" \
18                         "*spin:         True        \n" \
19                         "*wander:       True        \n" \
20                         "*symmetric:    True        \n" \
21                         "*count:        17          \n" \
22                         "*contrast:     30          \n" \
23                         "*showFPS:      False       \n" \
24                         "*wireframe:    False       \n" \
25                         "*suppressRotationAnimation: True\n" \
26
27 # define free_quasicrystal 0
28 # define release_quasicrystal 0
29 #undef countof
30 #define countof(x) (sizeof((x))/sizeof((*x)))
31
32 #include "xlockmore.h"
33 #include "colors.h"
34 #include "rotator.h"
35 #include <ctype.h>
36
37 #ifdef USE_GL /* whole file */
38
39 #define DEF_SPEED  "1.0"
40
41 typedef struct {
42   rotator *rot, *rot2;
43   GLuint texid;
44 } plane;
45
46 typedef struct {
47   GLXContext *glx_context;
48   Bool button_down_p;
49   Bool symmetric_p;
50   GLfloat contrast;
51   int count;
52   int ncolors, ccolor;
53   XColor *colors;
54   plane *planes;
55   int mousex, mousey;
56
57 } quasicrystal_configuration;
58
59 static quasicrystal_configuration *bps = NULL;
60
61 static GLfloat speed;
62
63 static XrmOptionDescRec opts[] = {
64   { "-spin",         ".spin",      XrmoptionNoArg, "True"  },
65   { "+spin",         ".spin",      XrmoptionNoArg, "False" },
66   { "-wander",       ".wander",    XrmoptionNoArg, "True"  },
67   { "+wander",       ".wander",    XrmoptionNoArg, "False" },
68   { "-symmetry",     ".symmetric", XrmoptionNoArg, "True"   },
69   { "-no-symmetry",  ".symmetric", XrmoptionNoArg, "False"  },
70   { "-speed",        ".speed",     XrmoptionSepArg, 0 },
71   { "-contrast",     ".contrast",  XrmoptionSepArg, 0 },
72 };
73
74 static argtype vars[] = {
75   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
76 };
77
78 ENTRYPOINT ModeSpecOpt quasicrystal_opts = {countof(opts), opts, countof(vars), vars, NULL};
79
80
81
82 /* Window management, etc
83  */
84 ENTRYPOINT void
85 reshape_quasicrystal (ModeInfo *mi, int width, int height)
86 {
87   GLfloat h = (GLfloat) height / (GLfloat) width;
88
89   glViewport (0, 0, (GLint) width, (GLint) height);
90
91   glMatrixMode(GL_PROJECTION);
92   glLoadIdentity();
93   glOrtho (0, 1, 1, 0, -1, 1);
94
95   glMatrixMode(GL_MODELVIEW);
96   glLoadIdentity();
97   glTranslatef (0.5, 0.5, 0);
98   glScalef (h, 1, 1);
99   if (width > height)
100     glScalef (1/h, 1/h, 1);
101   glTranslatef (-0.5, -0.5, 0);
102   glClear(GL_COLOR_BUFFER_BIT);
103 }
104
105
106 ENTRYPOINT Bool
107 quasicrystal_handle_event (ModeInfo *mi, XEvent *event)
108 {
109   quasicrystal_configuration *bp = &bps[MI_SCREEN(mi)];
110
111   if (event->xany.type == ButtonPress &&
112       event->xbutton.button == Button1)
113     {
114       bp->button_down_p = True;
115       bp->mousex = event->xbutton.x;
116       bp->mousey = event->xbutton.y;
117       return True;
118     }
119   else if (event->xany.type == ButtonRelease &&
120            event->xbutton.button == Button1)
121     {
122       bp->button_down_p = False;
123       return True;
124     }
125   else if (event->xany.type == ButtonPress &&   /* wheel up or right */
126            (event->xbutton.button == Button4 ||
127             event->xbutton.button == Button7))
128     {
129     UP:
130       if (bp->contrast <= 0) return False;
131       bp->contrast--;
132       return True;
133     }
134   else if (event->xany.type == ButtonPress &&   /* wheel down or left */
135            (event->xbutton.button == Button5 ||
136             event->xbutton.button == Button6))
137     {
138     DOWN:
139       if (bp->contrast >= 100) return False;
140       bp->contrast++;
141       return True;
142     }
143   else if (event->xany.type == MotionNotify &&
144            bp->button_down_p)
145     {
146       /* Dragging up and down tweaks contrast */
147
148       int dx = event->xmotion.x - bp->mousex;
149       int dy = event->xmotion.y - bp->mousey;
150
151       if (abs(dy) > abs(dx))
152         {
153           bp->contrast += dy / 40.0;
154           if (bp->contrast < 0)   bp->contrast = 0;
155           if (bp->contrast > 100) bp->contrast = 100;
156         }
157
158       bp->mousex = event->xmotion.x;
159       bp->mousey = event->xmotion.y;
160       return True;
161     }
162   else
163     {
164       if (event->xany.type == KeyPress)
165         {
166           KeySym keysym;
167           char c = 0;
168           XLookupString (&event->xkey, &c, 1, &keysym, 0);
169           if (c == '<' || c == ',' || c == '-' || c == '_' ||
170               keysym == XK_Left || keysym == XK_Up || keysym == XK_Prior)
171             goto UP;
172           else if (c == '>' || c == '.' || c == '=' || c == '+' ||
173                    keysym == XK_Right || keysym == XK_Down ||
174                    keysym == XK_Next)
175             goto DOWN;
176         }
177
178       return screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event);
179     }
180
181   return False;
182 }
183
184
185
186 ENTRYPOINT void 
187 init_quasicrystal (ModeInfo *mi)
188 {
189   quasicrystal_configuration *bp;
190   int wire = MI_IS_WIREFRAME(mi);
191   unsigned char *tex_data = 0;
192   int tex_width;
193   int i;
194
195   MI_INIT (mi, bps);
196
197   bp = &bps[MI_SCREEN(mi)];
198
199   bp->glx_context = init_GL(mi);
200
201   reshape_quasicrystal (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
202
203   glDisable (GL_DEPTH_TEST);
204   glEnable (GL_CULL_FACE);
205
206   bp->count = MI_COUNT(mi);
207   if (bp->count < 1) bp->count = 1;
208
209   if (! wire)
210     {
211       unsigned char *o;
212
213       tex_width = 4096;
214       glGetIntegerv (GL_MAX_TEXTURE_SIZE, &tex_width);
215       if (tex_width > 4096) tex_width = 4096;
216
217       tex_data = (unsigned char *) calloc (4, tex_width);
218       o = tex_data;
219       for (i = 0; i < tex_width; i++)
220         {
221           unsigned char y = 255 * (1 + sin (i * M_PI * 2 / tex_width)) / 2;
222           *o++ = y;
223           *o++ = y;
224           *o++ = y;
225           *o++ = 255;
226         }
227     }
228
229   bp->symmetric_p =
230     get_boolean_resource (MI_DISPLAY (mi), "symmetry", "Symmetry");
231
232   bp->contrast = get_float_resource (MI_DISPLAY (mi), "contrast", "Contrast");
233   if (bp->contrast < 0 || bp->contrast > 100) 
234     {
235       fprintf (stderr, "%s: contrast must be between 0 and 100%%.\n", progname);
236       bp->contrast = 0;
237     }
238
239   {
240     Bool spinp   = get_boolean_resource (MI_DISPLAY (mi), "spin", "Spin");
241     Bool wanderp = get_boolean_resource (MI_DISPLAY (mi), "wander", "Wander");
242     double spin_speed   = 0.01;
243     double wander_speed = 0.0001;
244     double spin_accel   = 10.0;
245     double scale_speed  = 0.005;
246
247     bp->planes = (plane *) calloc (sizeof (*bp->planes), bp->count);
248
249     bp->ncolors = 256;  /* ncolors affects color-cycling speed */
250     bp->colors = (XColor *) calloc (bp->ncolors, sizeof(XColor));
251     make_smooth_colormap (0, 0, 0, bp->colors, &bp->ncolors,
252                           False, 0, False);
253     bp->ccolor = 0;
254
255     for (i = 0;  i < bp->count; i++)
256       {
257         plane *p = &bp->planes[i];
258         p->rot = make_rotator (0, 0,
259                                spinp ? spin_speed : 0,
260                                spin_accel,
261                                wanderp ? wander_speed : 0,
262                                True);
263         p->rot2 = make_rotator (0, 0,
264                                 0, 0,
265                                scale_speed,
266                                True);
267         if (! wire)
268           {
269             clear_gl_error();
270
271             glGenTextures (1, &p->texid);
272             glBindTexture (GL_TEXTURE_1D, p->texid);
273             glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
274             glTexImage1D (GL_TEXTURE_1D, 0, GL_RGBA,
275                           tex_width, 0,
276                           GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
277             check_gl_error("texture");
278
279             glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
280             glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_REPEAT);
281
282             glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
283             glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
284
285             glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
286           }
287       }
288   }
289
290   if (tex_data) free (tex_data);
291
292   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
293 }
294
295
296 ENTRYPOINT void
297 draw_quasicrystal (ModeInfo *mi)
298 {
299   quasicrystal_configuration *bp = &bps[MI_SCREEN(mi)];
300   Display *dpy = MI_DISPLAY(mi);
301   Window window = MI_WINDOW(mi);
302   int wire = MI_IS_WIREFRAME(mi);
303   double r=0, ps=0;
304   int i;
305
306   if (!bp->glx_context)
307     return;
308
309   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
310
311   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
312
313   mi->polygon_count = 0;
314
315   glShadeModel(GL_FLAT);
316   glDisable(GL_DEPTH_TEST);
317   glDisable(GL_CULL_FACE);
318   glDisable (GL_LIGHTING);
319   if (!wire)
320     {
321       glEnable (GL_TEXTURE_1D);
322 # ifdef HAVE_JWZGLES
323       glEnable (GL_TEXTURE_2D);  /* jwzgles needs this, bleh. */
324 # endif
325     }
326
327   glEnable (GL_BLEND);
328   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
329
330   glPushMatrix ();
331   glTranslatef (0.5, 0.5, 0);
332   glScalef (3, 3, 3);
333
334   if (wire) glScalef (0.2, 0.2, 0.2);
335
336   for (i = 0;  i < bp->count; i++)
337     {
338       plane *p = &bp->planes[i];
339       double x, y, z;
340       double scale = (wire ? 10 : 700.0 / bp->count);
341       double pscale;
342
343       glPushMatrix();
344
345       get_position (p->rot, &x, &y, &z, !bp->button_down_p);
346       glTranslatef((x - 0.5) * 0.3333,
347                    (y - 0.5) * 0.3333,
348                    0);
349
350       /* With -symmetry, keep the planes' scales in sync.
351          Otherwise, they scale independently.
352        */
353       if (bp->symmetric_p && i > 0)
354         pscale = ps;
355       else
356         {
357           get_position (p->rot2, &x, &y, &z, !bp->button_down_p);
358           pscale = 1 + (4 * z);
359           ps = pscale;
360         }
361
362       scale *= pscale;
363
364
365       /* With -symmetry, evenly distribute the planes' rotation.
366          Otherwise, they rotate independently.
367        */
368       if (bp->symmetric_p && i > 0)
369         z = r + (i * M_PI * 2 / bp->count);
370       else
371         {
372           get_rotation (p->rot, &x, &y, &z, !bp->button_down_p);
373           r = z;
374         }
375
376
377       glRotatef (z * 360, 0, 0, 1);
378       glTranslatef (-0.5, -0.5, 0);
379
380       glColor4f (1, 1, 1, (wire ? 0.5 : 1.0 / bp->count));
381
382       if (!wire)
383         glBindTexture (GL_TEXTURE_1D, p->texid);
384
385       glBegin (wire ? GL_LINE_LOOP : GL_QUADS);
386       glNormal3f (0, 0, 1);
387       glTexCoord2f (-scale/2,  scale/2); glVertex3f (0, 1, 0);
388       glTexCoord2f ( scale/2,  scale/2); glVertex3f (1, 1, 0);
389       glTexCoord2f ( scale/2, -scale/2); glVertex3f (1, 0, 0);
390       glTexCoord2f (-scale/2, -scale/2); glVertex3f (0, 0, 0);
391       glEnd();
392
393       if (wire)
394         {
395           float j;
396           glDisable (GL_TEXTURE_1D);
397           glColor4f (1, 1, 1, 1.0 / bp->count);
398           for (j = 0; j < 1; j += (1 / scale))
399             {
400               glBegin (GL_LINES);
401               glVertex3f (j, 0, 0);
402               glVertex3f (j, 1, 0);
403               mi->polygon_count++;
404               glEnd();
405             }
406         }
407
408       glPopMatrix();
409
410       mi->polygon_count++;
411     }
412
413   /* Colorize the grayscale image. */
414   {
415     GLfloat c[4];
416     c[0] = bp->colors[bp->ccolor].red   / 65536.0;
417     c[1] = bp->colors[bp->ccolor].green / 65536.0;
418     c[2] = bp->colors[bp->ccolor].blue  / 65536.0;
419     c[3] = 1;
420
421     /* Brighten the colors. */
422     c[0] = (0.6666 + c[0]/3);
423     c[1] = (0.6666 + c[1]/3);
424     c[2] = (0.6666 + c[2]/3);
425
426     glBlendFunc (GL_DST_COLOR, GL_SRC_COLOR);
427     glDisable (GL_TEXTURE_1D);
428     glColor4fv (c);
429     glTranslatef (-0.5, -0.5, 0);
430     glBegin (GL_QUADS);
431     glVertex3f (0, 1, 0);
432     glVertex3f (1, 1, 0);
433     glVertex3f (1, 0, 0);
434     glVertex3f (0, 0, 0);
435     glEnd();
436     mi->polygon_count++;
437   }
438
439   /* Clip the colors to simulate contrast. */
440
441   if (bp->contrast > 0)
442     {
443       /* If c > 0, map 0 - 100 to 0.5 - 1.0, and use (s & ~d) */
444       GLfloat c = 1 - (bp->contrast / 2 / 100.0);
445       glDisable (GL_TEXTURE_1D);
446       glDisable (GL_BLEND);
447       glEnable (GL_COLOR_LOGIC_OP);
448       glLogicOp (GL_AND_REVERSE);
449       glColor4f (c, c, c, 1);
450       glBegin (GL_QUADS);
451       glVertex3f (0, 1, 0);
452       glVertex3f (1, 1, 0);
453       glVertex3f (1, 0, 0);
454       glVertex3f (0, 0, 0);
455       glEnd();
456       mi->polygon_count++;
457       glDisable (GL_COLOR_LOGIC_OP);
458     }
459
460   /* Rotate colors. */
461   bp->ccolor++;
462   if (bp->ccolor >= bp->ncolors)
463     bp->ccolor = 0;
464
465
466   glPopMatrix ();
467
468   if (mi->fps_p) do_fps (mi);
469   glFinish();
470
471   glXSwapBuffers(dpy, window);
472 }
473
474 XSCREENSAVER_MODULE ("QuasiCrystal", quasicrystal)
475
476 #endif /* USE_GL */