From http://www.jwz.org/xscreensaver/xscreensaver-5.22.tar.gz
[xscreensaver] / hacks / glx / cubenetic.c
1 /* cubenetic, Copyright (c) 2002-2008 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
12 #define DEFAULTS        "*delay:        20000       \n" \
13                         "*count:        5           \n" \
14                         "*showFPS:      False       \n" \
15                         "*wireframe:    False       \n" \
16
17 # define refresh_cube 0
18 # define release_cube 0
19 #undef countof
20 #define countof(x) (sizeof((x))/sizeof((*x)))
21
22 #include "xlockmore.h"
23 #include "colors.h"
24 #include "rotator.h"
25 #include "gltrackball.h"
26 #include <ctype.h>
27
28 #ifdef USE_GL /* whole file */
29
30
31 #define DEF_SPIN        "XYZ"
32 #define DEF_WANDER      "True"
33 #define DEF_TEXTURE     "True"
34
35 #define DEF_WAVES       "3"
36 #define DEF_WAVE_SPEED  "80"
37 #define DEF_WAVE_RADIUS "512"
38
39 typedef struct {
40   int color;
41   GLfloat x, y, z;
42   GLfloat w, h, d;
43   int frame;
44   GLfloat dx, dy, dz;
45   GLfloat dw, dh, dd;
46 } cube;
47
48 typedef struct {
49   int x, y;
50   double xth, yth;
51 } wave_src;
52
53 typedef struct {
54   int nwaves;
55   int radius;
56   int speed;
57   wave_src *srcs;
58   int *heights;
59 } waves;
60
61
62 typedef struct {
63   GLXContext *glx_context;
64   rotator *rot;
65   trackball_state *trackball;
66   Bool button_down_p;
67
68   GLuint cube_list;
69   GLuint texture_id;
70   int cube_polys;
71   int ncubes;
72   cube *cubes;
73   waves *waves;
74
75   int texture_width, texture_height;
76   unsigned char *texture;
77
78   int ncolors;
79   XColor *cube_colors;
80   XColor *texture_colors;
81
82 } cube_configuration;
83
84 static cube_configuration *ccs = NULL;
85
86 static char *do_spin;
87 static Bool do_wander;
88 static Bool do_texture;
89
90 static int wave_count;
91 static int wave_speed;
92 static int wave_radius;
93 static int texture_size = 256;
94
95 static XrmOptionDescRec opts[] = {
96   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
97   { "+spin",   ".spin",   XrmoptionNoArg, "" },
98   { "-wander", ".wander", XrmoptionNoArg, "True" },
99   { "+wander", ".wander", XrmoptionNoArg, "False" },
100   {"-texture", ".texture", XrmoptionNoArg, "true" },
101   {"+texture", ".texture", XrmoptionNoArg, "false" },
102   {"-waves",       ".waves",      XrmoptionSepArg, 0 },
103   {"-wave-speed",  ".waveSpeed",  XrmoptionSepArg, 0 },
104   {"-wave-radius", ".waveRadius", XrmoptionSepArg, 0 },
105 };
106
107 static argtype vars[] = {
108   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
109   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
110   {&do_texture, "texture", "Texture", DEF_TEXTURE, t_Bool},
111   {&wave_count, "waves",     "Waves",      DEF_WAVES, t_Int},
112   {&wave_speed, "waveSpeed", "WaveSpeed",  DEF_WAVE_SPEED, t_Int},
113   {&wave_radius,"waveRadius","WaveRadius", DEF_WAVE_RADIUS,t_Int},
114 };
115
116 ENTRYPOINT ModeSpecOpt cube_opts = {countof(opts), opts, countof(vars), vars, NULL};
117
118
119 static int
120 unit_cube (Bool wire)
121 {
122   int polys = 0;
123   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* front */
124   glNormal3f (0, 0, 1);
125   glTexCoord2f(1, 0); glVertex3f ( 0.5, -0.5,  0.5);
126   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
127   glTexCoord2f(0, 1); glVertex3f (-0.5,  0.5,  0.5);
128   glTexCoord2f(1, 1); glVertex3f (-0.5, -0.5,  0.5);
129   polys++;
130   glEnd();
131
132   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* back */
133   glNormal3f (0, 0, -1);
134   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
135   glTexCoord2f(0, 1); glVertex3f (-0.5,  0.5, -0.5);
136   glTexCoord2f(1, 1); glVertex3f ( 0.5,  0.5, -0.5);
137   glTexCoord2f(1, 0); glVertex3f ( 0.5, -0.5, -0.5);
138   polys++;
139   glEnd();
140
141   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* left */
142   glNormal3f (-1, 0, 0);
143   glTexCoord2f(1, 1); glVertex3f (-0.5,  0.5,  0.5);
144   glTexCoord2f(1, 0); glVertex3f (-0.5,  0.5, -0.5);
145   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
146   glTexCoord2f(0, 1); glVertex3f (-0.5, -0.5,  0.5);
147   polys++;
148   glEnd();
149
150   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* right */
151   glNormal3f (1, 0, 0);
152   glTexCoord2f(1, 1); glVertex3f ( 0.5, -0.5, -0.5);
153   glTexCoord2f(1, 0); glVertex3f ( 0.5,  0.5, -0.5);
154   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
155   glTexCoord2f(0, 1); glVertex3f ( 0.5, -0.5,  0.5);
156   polys++;
157   glEnd();
158
159   if (wire) return polys;
160
161   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* top */
162   glNormal3f (0, 1, 0);
163   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
164   glTexCoord2f(0, 1); glVertex3f ( 0.5,  0.5, -0.5);
165   glTexCoord2f(1, 1); glVertex3f (-0.5,  0.5, -0.5);
166   glTexCoord2f(1, 0); glVertex3f (-0.5,  0.5,  0.5);
167   polys++;
168   glEnd();
169
170   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* bottom */
171   glNormal3f (0, -1, 0);
172   glTexCoord2f(1, 0); glVertex3f (-0.5, -0.5,  0.5);
173   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
174   glTexCoord2f(0, 1); glVertex3f ( 0.5, -0.5, -0.5);
175   glTexCoord2f(1, 1); glVertex3f ( 0.5, -0.5,  0.5);
176   polys++;
177   glEnd();
178   return polys;
179 }
180
181
182
183 /* Window management, etc
184  */
185 ENTRYPOINT void
186 reshape_cube (ModeInfo *mi, int width, int height)
187 {
188   GLfloat h = (GLfloat) height / (GLfloat) width;
189
190   glViewport (0, 0, (GLint) width, (GLint) height);
191
192   glMatrixMode(GL_PROJECTION);
193   glLoadIdentity();
194
195   gluPerspective (30.0, 1/h, 1.0, 100.0);
196   glMatrixMode(GL_MODELVIEW);
197   glLoadIdentity();
198   gluLookAt( 0.0, 0.0, 30.0,
199              0.0, 0.0, 0.0,
200              0.0, 1.0, 0.0);
201
202   glClear(GL_COLOR_BUFFER_BIT);
203 }
204
205
206 \f
207 /* Waves.
208    Adapted from ../hacks/interference.c by Hannu Mallat.
209  */
210
211 static void
212 init_wave (ModeInfo *mi)
213 {
214   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
215   waves *ww;
216   int i;
217   cc->waves = ww = (waves *) calloc (sizeof(*cc->waves), 1);
218   ww->nwaves = wave_count;
219   ww->radius = wave_radius;
220   ww->speed  = wave_speed;
221   ww->heights = (int *) calloc (sizeof(*ww->heights), ww->radius);
222   ww->srcs = (wave_src *) calloc (sizeof(*ww->srcs), ww->nwaves);
223
224   for (i = 0; i < ww->radius; i++)
225     {
226       float max = (cc->ncolors * (ww->radius - i) / (float) ww->radius);
227       ww->heights[i] = ((max + max * cos(i / 50.0)) / 2.0);
228     }
229
230   for (i = 0; i < ww->nwaves; i++)
231     {
232       ww->srcs[i].xth = frand(2.0) * M_PI;
233       ww->srcs[i].yth = frand(2.0) * M_PI;
234     }
235 }
236
237 static void
238 interference (ModeInfo *mi)
239 {
240   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
241   waves *ww = cc->waves;
242   int x, y, i;
243
244   /* Move the wave origins around
245    */
246   for (i = 0; i < ww->nwaves; i++)
247     {
248       ww->srcs[i].xth += (ww->speed / 1000.0);
249       if (ww->srcs[i].xth > 2*M_PI)
250         ww->srcs[i].xth -= 2*M_PI;
251       ww->srcs[i].yth += (ww->speed / 1000.0);
252       if (ww->srcs[i].yth > 2*M_PI)
253         ww->srcs[i].yth -= 2*M_PI;
254
255       ww->srcs[i].x = (cc->texture_width/2 +
256                        (cos (ww->srcs[i].xth) *
257                         cc->texture_width / 2));
258       ww->srcs[i].y = (cc->texture_height/2 +
259                        (cos (ww->srcs[i].yth) *
260                         cc->texture_height / 2));
261     }
262
263   /* Compute the effect of the waves on each pixel,
264      and generate the output map.
265    */
266   for (y = 0; y < cc->texture_height; y++)
267     for (x = 0; x < cc->texture_width; x++)
268       {
269         int result = 0;
270         unsigned char *o;
271         for (i = 0; i < ww->nwaves; i++)
272           {
273             int dx = x - ww->srcs[i].x;
274             int dy = y - ww->srcs[i].y;
275             int dist = sqrt (dx*dx + dy*dy);
276             result += (dist > ww->radius ? 0 : ww->heights[dist]);
277           }
278         result %= cc->ncolors;
279
280         o = cc->texture + (((y * cc->texture_width) + x) << 2);
281         o[0] = (cc->texture_colors[result].red   >> 8);
282         o[1] = (cc->texture_colors[result].green >> 8);
283         o[2] = (cc->texture_colors[result].blue  >> 8);
284      /* o[3] = 0xFF; */
285       }
286 }
287
288 \f
289 /* Textures
290  */
291
292 static void
293 init_texture (ModeInfo *mi)
294 {
295   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
296   int i;
297
298   glEnable(GL_TEXTURE_2D);
299
300   clear_gl_error();
301   glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
302   glGenTextures (1, &cc->texture_id);
303   glBindTexture (GL_TEXTURE_2D, cc->texture_id);
304   check_gl_error("texture binding");
305
306   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
307   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
308   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
309   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
310   glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
311   check_gl_error("texture initialization");
312
313   cc->texture_width  = texture_size;
314   cc->texture_height = texture_size;
315
316   i = texture_size * texture_size * 4;
317   cc->texture = (unsigned char *) malloc (i);
318   memset (cc->texture, 0xFF, i);
319 }
320
321
322 static void
323 shuffle_texture (ModeInfo *mi)
324 {
325   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
326   interference (mi);
327   clear_gl_error();
328   glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA,
329                 cc->texture_width, cc->texture_height, 0,
330                 GL_RGBA, GL_UNSIGNED_BYTE,
331                 cc->texture);
332   check_gl_error("texture");
333 }
334
335
336 ENTRYPOINT Bool
337 cube_handle_event (ModeInfo *mi, XEvent *event)
338 {
339   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
340
341   if (event->xany.type == ButtonPress &&
342       event->xbutton.button == Button1)
343     {
344       cc->button_down_p = True;
345       gltrackball_start (cc->trackball,
346                          event->xbutton.x, event->xbutton.y,
347                          MI_WIDTH (mi), MI_HEIGHT (mi));
348       return True;
349     }
350   else if (event->xany.type == ButtonRelease &&
351            event->xbutton.button == Button1)
352     {
353       cc->button_down_p = False;
354       return True;
355     }
356   else if (event->xany.type == ButtonPress &&
357            (event->xbutton.button == Button4 ||
358             event->xbutton.button == Button5 ||
359             event->xbutton.button == Button6 ||
360             event->xbutton.button == Button7))
361     {
362       gltrackball_mousewheel (cc->trackball, event->xbutton.button, 10,
363                               !!event->xbutton.state);
364       return True;
365     }
366   else if (event->xany.type == MotionNotify &&
367            cc->button_down_p)
368     {
369       gltrackball_track (cc->trackball,
370                          event->xmotion.x, event->xmotion.y,
371                          MI_WIDTH (mi), MI_HEIGHT (mi));
372       return True;
373     }
374
375   return False;
376 }
377
378
379 ENTRYPOINT void 
380 init_cube (ModeInfo *mi)
381 {
382   int i;
383   cube_configuration *cc;
384   int wire = MI_IS_WIREFRAME(mi);
385
386   if (!ccs) {
387     ccs = (cube_configuration *)
388       calloc (MI_NUM_SCREENS(mi), sizeof (cube_configuration));
389     if (!ccs) {
390       fprintf(stderr, "%s: out of memory\n", progname);
391       exit(1);
392     }
393   }
394
395   cc = &ccs[MI_SCREEN(mi)];
396
397   if ((cc->glx_context = init_GL(mi)) != NULL) {
398     reshape_cube (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
399   }
400
401   if (!wire)
402     {
403       static const GLfloat pos[4] = {1.0, 0.5, 1.0, 0.0};
404       static const GLfloat amb[4] = {0.2, 0.2, 0.2, 1.0};
405       static const GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
406
407       glLightfv(GL_LIGHT0, GL_POSITION, pos);
408       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
409       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
410
411       glEnable(GL_LIGHTING);
412       glEnable(GL_LIGHT0);
413       glEnable(GL_DEPTH_TEST);
414       glEnable(GL_CULL_FACE);
415     }
416
417
418   {
419     Bool spinx=False, spiny=False, spinz=False;
420     double spin_speed   = 1.0;
421     double wander_speed = 0.05;
422
423     char *s = do_spin;
424     while (*s)
425       {
426         if      (*s == 'x' || *s == 'X') spinx = True;
427         else if (*s == 'y' || *s == 'Y') spiny = True;
428         else if (*s == 'z' || *s == 'Z') spinz = True;
429         else if (*s == '0') ;
430         else
431           {
432             fprintf (stderr,
433          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
434                      progname, do_spin);
435             exit (1);
436           }
437         s++;
438       }
439
440     cc->rot = make_rotator (spinx ? spin_speed : 0,
441                             spiny ? spin_speed : 0,
442                             spinz ? spin_speed : 0,
443                             1.0,
444                             do_wander ? wander_speed : 0,
445                             (spinx && spiny && spinz));
446     cc->trackball = gltrackball_init ();
447   }
448
449   cc->ncolors = 256;
450   cc->texture_colors = (XColor *) calloc(cc->ncolors, sizeof(XColor));
451   cc->cube_colors    = (XColor *) calloc(cc->ncolors, sizeof(XColor));
452
453   {
454     double H[3], S[3], V[3];
455     int shift = 60;
456     H[0] = frand(360.0); 
457     H[1] = ((H[0] + shift) < 360) ? (H[0]+shift) : (H[0] + shift - 360);
458     H[2] = ((H[1] + shift) < 360) ? (H[1]+shift) : (H[1] + shift - 360);
459     S[0] = S[1] = S[2] = 1.0;
460     V[0] = V[1] = V[2] = 1.0;
461     make_color_loop(0, 0, 0,
462                     H[0], S[0], V[0], 
463                     H[1], S[1], V[1], 
464                     H[2], S[2], V[2], 
465                     cc->texture_colors, &cc->ncolors,
466                     False, False);
467
468     make_smooth_colormap (0, 0, 0,
469                           cc->cube_colors, &cc->ncolors, 
470                           False, 0, False);
471   }
472
473   cc->ncubes = MI_COUNT (mi);
474   cc->cubes = (cube *) calloc (sizeof(cube), cc->ncubes);
475   for (i = 0; i < cc->ncubes; i++)
476     {
477       cube *cube = &cc->cubes[i];
478       cube->color = random() % cc->ncolors;
479       cube->w = 1.0;
480       cube->h = 1.0;
481       cube->d = 1.0;
482       cube->dx = frand(0.1);
483       cube->dy = frand(0.1);
484       cube->dz = frand(0.1);
485       cube->dw = frand(0.1);
486       cube->dh = frand(0.1);
487       cube->dd = frand(0.1);
488     }
489
490   if (wire)
491     do_texture = False;
492     
493   if (do_texture)
494     {
495       init_texture (mi);
496       init_wave (mi);
497       shuffle_texture (mi);
498     }
499
500   cc->cube_list = glGenLists (1);
501   glNewList (cc->cube_list, GL_COMPILE);
502   cc->cube_polys = unit_cube (wire);
503   glEndList ();
504 }
505
506
507 static void
508 shuffle_cubes (ModeInfo *mi)
509 {
510   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
511   int i;
512   for (i = 0; i < cc->ncubes; i++)
513     {
514 #     define SINOID(SCALE,FRAME,SIZE) \
515         ((((1 + sin((FRAME * (SCALE)) / 2 * M_PI)) / 2.0) * (SIZE)) - (SIZE)/2)
516
517       cube *cube = &cc->cubes[i];
518       cube->x = SINOID(cube->dx, cube->frame, 0.5);
519       cube->y = SINOID(cube->dy, cube->frame, 0.5);
520       cube->z = SINOID(cube->dz, cube->frame, 0.5);
521       cube->w = SINOID(cube->dw, cube->frame, 0.9) + 1.0;
522       cube->h = SINOID(cube->dh, cube->frame, 0.9) + 1.0;
523       cube->d = SINOID(cube->dd, cube->frame, 0.9) + 1.0;
524       cube->frame++;
525 #     undef SINOID
526     }
527 }
528
529
530 ENTRYPOINT void
531 draw_cube (ModeInfo *mi)
532 {
533   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
534   Display *dpy = MI_DISPLAY(mi);
535   Window window = MI_WINDOW(mi);
536   int i;
537
538   if (!cc->glx_context)
539     return;
540
541   mi->polygon_count = 0;
542   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(cc->glx_context));
543
544   glShadeModel(GL_FLAT);
545
546   glEnable(GL_DEPTH_TEST);
547   glEnable(GL_NORMALIZE);
548   glEnable(GL_CULL_FACE);
549
550   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
551
552   glPushMatrix ();
553
554   glScalef(1.1, 1.1, 1.1);
555
556   {
557     double x, y, z;
558     get_position (cc->rot, &x, &y, &z, !cc->button_down_p);
559     glTranslatef((x - 0.5) * 8,
560                  (y - 0.5) * 6,
561                  (z - 0.5) * 15);
562
563     /* Do it twice because we don't track the device's orientation. */
564     glRotatef( current_device_rotation(), 0, 0, 1);
565     gltrackball_rotate (cc->trackball);
566     glRotatef(-current_device_rotation(), 0, 0, 1);
567
568     get_rotation (cc->rot, &x, &y, &z, !cc->button_down_p);
569     glRotatef (x * 360, 1.0, 0.0, 0.0);
570     glRotatef (y * 360, 0.0, 1.0, 0.0);
571     glRotatef (z * 360, 0.0, 0.0, 1.0);
572   }
573
574   glScalef (2.5, 2.5, 2.5);
575
576   for (i = 0; i < cc->ncubes; i++)
577     {
578       cube *cube = &cc->cubes[i];
579       GLfloat color[4];
580       color[0] = cc->cube_colors[cube->color].red   / 65536.0;
581       color[1] = cc->cube_colors[cube->color].green / 65536.0;
582       color[2] = cc->cube_colors[cube->color].blue  / 65536.0;
583       color[3] = 1.0;
584       cube->color++;
585       if (cube->color >= cc->ncolors) cube->color = 0;
586
587       glPushMatrix ();
588       glTranslatef (cube->x, cube->y, cube->z);
589       glScalef (cube->w, cube->h, cube->d);
590       glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
591       glCallList (cc->cube_list);
592       mi->polygon_count += cc->cube_polys;
593       glPopMatrix ();
594     }
595
596   shuffle_cubes (mi);
597   if (do_texture)
598     shuffle_texture (mi);
599
600   glPopMatrix();
601
602   if (mi->fps_p) do_fps (mi);
603   glFinish();
604
605   glXSwapBuffers(dpy, window);
606 }
607
608 XSCREENSAVER_MODULE_2 ("Cubenetic", cubenetic, cube)
609
610 #endif /* USE_GL */