From http://www.jwz.org/xscreensaver/xscreensaver-5.38.tar.gz
[xscreensaver] / hacks / glx / spheremonics.c
1 /* xscreensaver, Copyright (c) 2002-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  * Algorithm by Paul Bourke <pbourke@swin.edu.au>
12  * http://astronomy.swin.edu.au/~pbourke/geometry/sphericalh/
13  * Screensaver veneer and parameter selection by jwz.
14  *
15  *  Paul says:
16  *
17  * These closed objects are commonly called spherical harmonics,
18  * although they are only remotely related to the mathematical
19  * definition found in the solution to certain wave functions, most
20  * notable the eigenfunctions of angular momentum operators.
21  *
22  * The formula is quite simple: the form used here is based upon
23  * spherical (polar) coordinates (radius, theta, phi).
24  *
25  *    r = sin(m0 phi)   ^ m1 + 
26  *        cos(m2 phi)   ^ m3 + 
27  *        sin(m4 theta) ^ m5 + 
28  *        cos(m6 theta) ^ m7 
29  *
30  * Where phi ranges from 0 to pi (lines of latitude), and theta ranges
31  * from 0 to 2 pi (lines of longitude), and r is the radius.  The
32  * parameters m0, m1, m2, m3, m4, m5, m6, and m7 are all integers
33  * greater than or equal to 0.
34  *
35  * As the degree increases, the objects become increasingly "pointed"
36  * and a large number of polygons are required to represent the surface
37  * faithfully.
38  *
39  * jwz adds:
40  * 
41  * The eight parameters live in the `cc->m' array.
42  * Each time we permute the image, we alter *one* of those eight parameters.
43  * Each time we alter a parameter, we move it in the same direction (either
44  * toward larger or smaller values) in the range [0, 3].
45  *
46  * By altering only one parameter at a time, and only by small amounts,
47  * we tend to produce successive objects that are pretty similar to each
48  * other, so you can see a progression.
49  *
50  * It'd be nice if they were even closer together, so that it looked more
51  * like a morph, but, well, that's not how it works.
52  *
53  * There tends to be a dark stripe in the colormaps.  I don't know why.
54  * Perhaps utils/colors.c is at fault?
55  *
56  * Note that this equation sometimes generates faces that are inside out:
57  *     -parameters 01210111
58  * To make this work, we need to render back-faces with two-sided lighting:
59  * figuring out how to correct the winding and normals on those inside out
60  * surfaces would be too hard.
61  */
62
63 #define DEFAULTS "*delay:       30000       \n" \
64                  "*showFPS:     False       \n" \
65                  "*wireframe:   False       \n" \
66                  "*suppressRotationAnimation: True\n" \
67          "*labelfont:   -*-helvetica-medium-r-normal-*-*-180-*-*-*-*-*-*\n"
68
69 # define free_spheremonics 0
70 # define release_spheremonics 0
71 #undef countof
72 #define countof(x) (sizeof((x))/sizeof((*x)))
73
74 #include "xlockmore.h"
75 #include "texfont.h"
76 #include "normals.h"
77 #include "colors.h"
78 #include "rotator.h"
79 #include "gltrackball.h"
80 #include <ctype.h>
81
82 #ifdef USE_GL /* whole file */
83
84 #define DEF_DURATION    "100"
85 #define DEF_SPIN        "XYZ"
86 #define DEF_WANDER      "False"
87 #define DEF_RESOLUTION  "64"
88 #define DEF_BBOX        "False"
89 #define DEF_GRID        "True"
90 #define DEF_SMOOTH      "True"
91 #define DEF_PARMS       "(default)"
92
93 typedef struct {
94   GLXContext *glx_context;
95   rotator *rot;
96   trackball_state *trackball;
97   Bool button_down_p;
98
99   GLuint dlist, dlist2;
100   GLfloat scale;
101   XYZ bbox[2];
102
103   int resolution;
104   int ncolors;
105   XColor *colors;
106
107   int m[8];
108   int dm[8];
109   int m_max;
110
111   int tracer;
112   int mesher;
113   int polys1, polys2;  /* polygon counts */
114
115   texture_font_data *font_data;
116
117   int change_tick;
118   int done_once;
119
120 } spheremonics_configuration;
121
122 static spheremonics_configuration *ccs = NULL;
123
124 static char *do_spin;
125 static Bool do_wander;
126 static Bool do_bbox;
127 static Bool do_grid;
128 static int smooth_p;
129 static char *static_parms;
130 static int res;
131 static int duration;
132
133 static XrmOptionDescRec opts[] = {
134   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
135   { "+spin",   ".spin",   XrmoptionNoArg, "" },
136   { "-wander", ".wander", XrmoptionNoArg, "True" },
137   { "+wander", ".wander", XrmoptionNoArg, "False" },
138   { "-resolution", ".resolution", XrmoptionSepArg, 0 },
139   { "-duration",   ".duration",   XrmoptionSepArg, 0 },
140   { "-bbox",   ".bbox",  XrmoptionNoArg, "True" },
141   { "+bbox",   ".bbox",  XrmoptionNoArg, "False" },
142   { "-grid",   ".grid",  XrmoptionNoArg, "True" },
143   { "+grid",   ".grid",  XrmoptionNoArg, "False" },
144   {"-smooth",  ".smooth", XrmoptionNoArg, "True" },
145   {"+smooth",  ".smooth", XrmoptionNoArg, "False" },
146   { "-parameters", ".parameters", XrmoptionSepArg, 0 },
147 };
148
149 static argtype vars[] = {
150   {&do_spin,      "spin",       "Spin",       DEF_SPIN,       t_String},
151   {&do_wander,    "wander",     "Wander",     DEF_WANDER,     t_Bool},
152   {&res,          "resolution", "Resolution", DEF_RESOLUTION, t_Int},
153   {&duration,     "duration",   "Duration",   DEF_DURATION,   t_Int},
154   {&do_bbox,      "bbox",       "BBox",       DEF_BBOX,       t_Bool},
155   {&do_grid,      "grid",       "Grid",       DEF_GRID,       t_Bool},
156   {&smooth_p,     "smooth",     "Smooth",     DEF_SMOOTH,     t_Bool},
157   {&static_parms, "parameters", "Parameters", DEF_PARMS,      t_String},
158 };
159
160 ENTRYPOINT ModeSpecOpt spheremonics_opts = {countof(opts), opts, countof(vars), vars, NULL};
161
162
163 /* Window management, etc
164  */
165 ENTRYPOINT void
166 reshape_spheremonics (ModeInfo *mi, int width, int height)
167 {
168   GLfloat h = (GLfloat) height / (GLfloat) width;
169   int y = 0;
170
171   if (width > height * 5) {   /* tiny window: show middle */
172     height = width * 9/16;
173     y = -height/2;
174     h = height / (GLfloat) width;
175   }
176
177   glViewport (0, y, (GLint) width, (GLint) height);
178
179   glMatrixMode(GL_PROJECTION);
180   glLoadIdentity();
181   gluPerspective (30.0, 1/h, 1.0, 100.0);
182
183   glMatrixMode(GL_MODELVIEW);
184   glLoadIdentity();
185   gluLookAt( 0.0, 0.0, 30.0,
186              0.0, 0.0, 0.0,
187              0.0, 1.0, 0.0);
188
189 # ifdef HAVE_MOBILE     /* Keep it the same relative size when rotated. */
190   {
191     int o = (int) current_device_rotation();
192     if (o != 0 && o != 180 && o != -180)
193       glScalef (1/h, 1/h, 1/h);
194   }
195
196 # endif
197   glClear(GL_COLOR_BUFFER_BIT);
198 }
199
200
201 static void
202 gl_init (ModeInfo *mi)
203 {
204 /*  spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)]; */
205   int wire = MI_IS_WIREFRAME(mi);
206
207   static const GLfloat pos[4] = {5.0, 5.0, 10.0, 1.0};
208
209   glEnable(GL_NORMALIZE);
210
211   if (!wire)
212     {
213       glLightfv(GL_LIGHT0, GL_POSITION, pos);
214       glEnable(GL_LIGHTING);
215       glEnable(GL_LIGHT0);
216       glEnable(GL_DEPTH_TEST);
217
218       /* With objects that have proper winding and normals set up on all
219          their faces, one can cull back-faces; however, these equations
220          generate objects that are sometimes "inside out", and determining
221          whether a facet has been inverted like that is really hard.
222          So we render both front and back faces, at a probable performance
223          penalty on non-accelerated systems.
224
225          When rendering back faces, we also need to do two-sided lighting,
226          or the fact that the normals are flipped gives us too-dark surfaces
227          on the inside-out surfaces.
228
229          This isn't generally something you'd want, because you end up
230          with half the lighting dynamic range (kind of.)  So if you had
231          a sphere with correctly pointing normals, and a single light
232          source, it would be illuminated from two sides.  In this case,
233          though, it saves us from a difficult and time consuming
234          inside/outside test.  And we don't really care about a precise
235          lighting effect.
236        */
237       glDisable(GL_CULL_FACE);
238       glLightModeli (GL_LIGHT_MODEL_TWO_SIDE, True);
239     }
240
241   if (smooth_p) 
242     {
243       glEnable (GL_LINE_SMOOTH);
244       glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
245       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
246       glEnable (GL_BLEND);
247     }
248 }
249
250
251 \f
252 /* generate the object */
253
254 static XYZ
255 sphere_eval (double theta, double phi, int *m)
256 {
257   double r = 0;
258   XYZ p;
259
260   r += pow (sin(m[0] * phi),  (double)m[1]);
261   r += pow (cos(m[2] * phi),  (double)m[3]);
262   r += pow (sin(m[4] * theta),(double)m[5]);
263   r += pow (cos(m[6] * theta),(double)m[7]);
264
265   p.x = r * sin(phi) * cos(theta);
266   p.y = r * cos(phi);
267   p.z = r * sin(phi) * sin(theta);
268
269   return (p);
270 }
271
272
273 static void
274 do_color (int i, XColor *colors)
275 {
276   GLfloat c[4];
277   c[0] = colors[i].red   / 65535.0;
278   c[1] = colors[i].green / 65535.0;
279   c[2] = colors[i].blue  / 65535.0;
280   c[3] = 1.0;
281   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, c);
282   glColor3f (c[0], c[1], c[2]);
283 }
284
285
286 static void
287 draw_circle (ModeInfo *mi, Bool teeth_p)
288 {
289   GLfloat th;
290   int tick = 0;
291   GLfloat x, y;
292   GLfloat step = (M_PI / 180);
293
294   glBegin(GL_LINE_LOOP);
295   for (th = 0; th < M_PI*2; th += step*5)
296     {
297       GLfloat r1 = 0.5;
298       x = cos (th);
299       y = sin (th);
300       glVertex3f(x*r1, y*r1,  0);
301     }
302   glEnd();
303
304   if (!teeth_p) return;
305
306   glBegin(GL_LINES);
307   for (th = 0; th < M_PI*2; th += step)
308     {
309       GLfloat r1 = 0.5;
310       GLfloat r2 = r1 - 0.01;
311       if (! (tick % 10))
312         r2 -= 0.02;
313       else if (! (tick % 5))
314         r2 -= 0.01;
315       tick++;
316
317       x = cos (th);
318       y = sin (th);
319       glVertex3f(x*r1, y*r1,  0);
320       glVertex3f(x*r2, y*r2,  0);
321     }
322   glEnd();
323 }
324
325
326 static void
327 draw_bounding_box (ModeInfo *mi)
328 {
329   /* spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)]; */
330
331   static const GLfloat c1[4] = { 0.2, 0.2, 0.6, 1.0 };
332   static const GLfloat c2[4] = { 1.0, 0.0, 0.0, 1.0 };
333   int wire = MI_IS_WIREFRAME(mi);
334
335   GLfloat x1,y1,z1,x2,y2,z2;
336
337 # if 0
338   x1 = cc->bbox[0].x;
339   y1 = cc->bbox[0].y;
340   z1 = cc->bbox[0].z;
341   x2 = cc->bbox[1].x;
342   y2 = cc->bbox[1].y;
343   z2 = cc->bbox[1].z;
344 # else
345   x1 = y1 = z1 = -0.5;
346   x2 = y2 = z2 =  0.5;
347 # endif
348
349   if (do_bbox && !wire)
350     {
351       glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, c1);
352       glFrontFace(GL_CCW);
353       glEnable(GL_CULL_FACE);
354
355       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
356       glNormal3f(0, 1, 0);
357       glVertex3f(x1, y1, z1); glVertex3f(x1, y1, z2);
358       glVertex3f(x2, y1, z2); glVertex3f(x2, y1, z1);
359       glEnd();
360       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
361       glNormal3f(0, -1, 0);
362       glVertex3f(x2, y2, z1); glVertex3f(x2, y2, z2);
363       glVertex3f(x1, y2, z2); glVertex3f(x1, y2, z1);
364       glEnd();
365       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
366       glNormal3f(0, 0, 1);
367       glVertex3f(x1, y1, z1); glVertex3f(x2, y1, z1);
368       glVertex3f(x2, y2, z1); glVertex3f(x1, y2, z1);
369       glEnd();
370       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
371       glNormal3f(0, 0, -1);
372       glVertex3f(x1, y2, z2); glVertex3f(x2, y2, z2);
373       glVertex3f(x2, y1, z2); glVertex3f(x1, y1, z2);
374       glEnd();
375       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
376       glNormal3f(1, 0, 0);
377       glVertex3f(x1, y2, z1); glVertex3f(x1, y2, z2);
378       glVertex3f(x1, y1, z2); glVertex3f(x1, y1, z1);
379       glEnd();
380       glBegin(wire ? GL_LINE_LOOP : GL_QUADS);
381       glNormal3f(-1, 0, 0);
382       glVertex3f(x2, y1, z1); glVertex3f(x2, y1, z2);
383       glVertex3f(x2, y2, z2); glVertex3f(x2, y2, z1);
384       glEnd();
385       glDisable(GL_CULL_FACE);
386     }
387
388   if (do_grid)
389     {
390       glDisable (GL_LIGHTING);
391       glColor3f (c2[0], c2[1], c2[2]);
392       glPushMatrix();
393       glBegin(GL_LINES);
394       glVertex3f(0, -0.66, 0);
395       glVertex3f(0,  0.66, 0); 
396       glEnd();
397       draw_circle (mi, True);
398       glRotatef(90, 1, 0, 0);
399       draw_circle (mi, True);
400       glRotatef(90, 0, 1, 0);
401       draw_circle (mi, True);
402       glPopMatrix();
403     }
404   else
405     {
406 #if 0
407       glBegin(GL_LINES);
408       if (x1 > 0) x1 = 0; if (x2 < 0) x2 = 0;
409       if (y1 > 0) y1 = 0; if (y2 < 0) y2 = 0;
410       if (z1 > 0) z1 = 0; if (z2 < 0) z2 = 0;
411       glVertex3f(x1, 0,  0);  glVertex3f(x2, 0,  0); 
412       glVertex3f(0 , y1, 0);  glVertex3f(0,  y2, 0); 
413       glVertex3f(0,  0,  z1); glVertex3f(0,  0,  z2); 
414       glEnd();
415 #endif
416     }
417 }
418
419
420 static void
421 do_tracer (ModeInfo *mi)
422 {
423   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
424
425   if (cc->tracer == -1 &&
426       cc->mesher == -1 &&
427       !(random() % (duration * 4)))
428     {
429       if (random() & 1)
430         cc->tracer = ((random() & 1) ? 0 : 180);
431       else
432         cc->mesher = ((random() % ((duration / 3) + 1)) +
433                       (random() % ((duration / 3) + 1)));
434     }
435
436   if (cc->tracer >= 0)
437     {
438       int d = (90 - cc->tracer);
439       GLfloat th = d * (M_PI / 180);
440       GLfloat x = cos (th);
441       GLfloat y = sin (th);
442       GLfloat s = 1.5 / cc->scale;
443
444       if (s > 0.001)
445         {
446           static const GLfloat c[4] = { 0.6, 0.5, 1.0, 1.0 };
447
448           glDisable (GL_LIGHTING);
449
450           glPushMatrix();
451           glRotatef (90, 1, 0, 0);
452           glTranslatef (0, 0, y*s/2);
453           s *= x;
454           glScalef(s, s, s);
455           glColor3f (c[0], c[1], c[2]);
456           draw_circle (mi, False);
457           glPopMatrix();
458
459           if (! MI_IS_WIREFRAME(mi)) glEnable (GL_LIGHTING);
460         }
461
462       cc->tracer += 5;
463       if (cc->tracer == 180 || cc->tracer == 360)
464         cc->tracer = -1;
465     }
466 }
467
468
469 static int
470 unit_spheremonics (ModeInfo *mi,
471                    int resolution, Bool wire, int *m, XColor *colors)
472 {
473   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
474   int polys = 0;
475   int i, j;
476   double du, dv;
477   XYZ q[4];
478   XYZ n[4];
479   int res = (wire == 2
480              ? resolution / 2
481              : resolution);
482
483   cc->bbox[0].x = cc->bbox[0].y = cc->bbox[0].z = 0;
484   cc->bbox[1].x = cc->bbox[1].y = cc->bbox[1].z = 0;
485
486   du = (M_PI+M_PI) / (double)res; /* Theta */
487   dv = M_PI        / (double)res; /* Phi   */
488
489   if (wire)
490     glColor3f (1, 1, 1);
491
492   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);
493
494   for (i = 0; i < res; i++) {
495     double u = i * du;
496     for (j = 0; j < res; j++) {
497       double v = j * dv;
498       q[0] = sphere_eval (u, v, m);
499       n[0] = calc_normal(q[0],
500                          sphere_eval (u+du/10, v, m),
501                          sphere_eval (u, v+dv/10, m));
502       glNormal3f(n[0].x,n[0].y,n[0].z);
503       if (!wire) do_color (i, colors);
504       glVertex3f(q[0].x,q[0].y,q[0].z);
505
506       q[1] = sphere_eval (u+du, v, m);
507       n[1] = calc_normal(q[1],
508                          sphere_eval (u+du+du/10, v, m),
509                          sphere_eval (u+du, v+dv/10, m));
510       glNormal3f(n[1].x,n[1].y,n[1].z);
511       if (!wire) do_color ((i+1)%res, colors);
512       glVertex3f(q[1].x,q[1].y,q[1].z);
513
514       q[2] = sphere_eval (u+du, v+dv, m);
515       n[2] = calc_normal(q[2],
516                          sphere_eval (u+du+du/10, v+dv, m),
517                          sphere_eval (u+du, v+dv+dv/10, m));
518       glNormal3f(n[2].x,n[2].y,n[2].z);
519       if (!wire) do_color ((i+1)%res, colors);
520       glVertex3f(q[2].x,q[2].y,q[2].z);
521
522       q[3] = sphere_eval (u,v+dv, m);
523       n[3] = calc_normal(q[3],
524                          sphere_eval (u+du/10, v+dv, m),
525                          sphere_eval (u, v+dv+dv/10, m));
526       glNormal3f(n[3].x,n[3].y,n[3].z);
527       if (!wire) do_color (i, colors);
528       glVertex3f(q[3].x,q[3].y,q[3].z);
529
530       polys++;
531
532 # define CHECK_BBOX(N) \
533          if (q[(N)].x < cc->bbox[0].x) cc->bbox[0].x = q[(N)].x; \
534          if (q[(N)].y < cc->bbox[0].y) cc->bbox[0].y = q[(N)].y; \
535          if (q[(N)].z < cc->bbox[0].z) cc->bbox[0].z = q[(N)].z; \
536          if (q[(N)].x > cc->bbox[1].x) cc->bbox[1].x = q[(N)].x; \
537          if (q[(N)].y > cc->bbox[1].y) cc->bbox[1].y = q[(N)].y; \
538          if (q[(N)].z > cc->bbox[1].z) cc->bbox[1].z = q[(N)].z
539
540       CHECK_BBOX(0);
541       CHECK_BBOX(1);
542       CHECK_BBOX(2);
543       CHECK_BBOX(3);
544 # undef CHECK_BBOX
545     }
546   }
547   glEnd();
548
549   {
550     GLfloat w = cc->bbox[1].x - cc->bbox[0].x;
551     GLfloat h = cc->bbox[1].y - cc->bbox[0].y;
552     GLfloat d = cc->bbox[1].z - cc->bbox[0].z;
553     GLfloat wh = (w > h ? w : h);
554     GLfloat hd = (h > d ? h : d);
555     GLfloat scale = (wh > hd ? wh : hd);
556
557     cc->scale = 1/scale;
558
559     if (wire < 2 && (do_bbox || do_grid))
560       {
561         GLfloat s = scale * 1.5;
562         glPushMatrix();
563         glScalef(s, s, s);
564         draw_bounding_box (mi);
565         glPopMatrix();
566       }
567   }
568   return polys;
569 }
570
571
572 static void
573 init_colors (ModeInfo *mi)
574 {
575   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
576   int i;
577   cc->ncolors = cc->resolution;
578   cc->colors = (XColor *) calloc(cc->ncolors, sizeof(XColor));
579   make_smooth_colormap (0, 0, 0,
580                         cc->colors, &cc->ncolors, 
581                         False, 0, False);
582
583   /* brighter colors, please... */
584   for (i = 0; i < cc->ncolors; i++)
585     {
586       cc->colors[i].red   = (cc->colors[i].red   / 2) + 32767;
587       cc->colors[i].green = (cc->colors[i].green / 2) + 32767;
588       cc->colors[i].blue  = (cc->colors[i].blue  / 2) + 32767;
589     }
590 }
591
592
593 /* Pick one of the parameters to the function and tweak it up or down.
594  */
595 static void
596 tweak_parameters (ModeInfo *mi)
597 {
598   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
599
600   /* If the -parameters command line option was specified, just use that
601      all the time.
602    */
603   if (static_parms &&
604       *static_parms &&
605       !!strcasecmp (static_parms, "(default)"))
606     {
607       unsigned long n;
608       char dummy;
609       if (8 == sscanf (static_parms, "%d %d %d %d %d %d %d %d %c",
610                        &cc->m[0], &cc->m[1], &cc->m[2], &cc->m[3],
611                        &cc->m[4], &cc->m[5], &cc->m[6], &cc->m[7],
612                        &dummy))
613         return;
614       else if (strlen (static_parms) == 8 &&
615                1 == sscanf (static_parms, "%lu %c", &n, &dummy))
616         {
617           const char *s = static_parms;
618           int i = 0;
619           while (*s)
620             cc->m[i++] = (*s++)-'0';
621           return;
622         }
623       fprintf (stderr,
624                "%s: -parameters must be a string of 8 ints (not \"%s\")\n",
625                progname, static_parms);
626       exit (1);
627     }
628
629   static_parms = 0;
630
631
632 # define SHIFT(N) do { \
633     int n = (N); \
634     cc->m[n] += cc->dm[n]; \
635     if (cc->m[n] <= 0) \
636       cc->m[n] = 0, cc->dm[n] = -cc->dm[n]; \
637     else if (cc->m[n] >= cc->m_max) \
638       cc->m[n] = cc->m_max, cc->dm[n] = -cc->dm[n]; \
639   } while(0)
640
641 /*    else if (cc->m[n] >= cc->m_max/2 && (! (random() % 3))) \
642       cc->m[n] = cc->m_max/2, cc->dm[n] = -cc->dm[n]; \
643 */
644
645   switch(random() % 8)
646     {
647     case 0: SHIFT(0); break;
648     case 1: SHIFT(1); break;
649     case 2: SHIFT(2); break;
650     case 3: SHIFT(3); break;
651     case 4: SHIFT(4); break;
652     case 5: SHIFT(5); break;
653     case 6: SHIFT(6); break;
654     case 7: SHIFT(7); break;
655     default: abort(); break;
656     }
657 # undef SHIFT
658
659 #if 0
660     printf ("%s: state: %d %d %d %d %d %d %d %d\n",
661             progname,
662             cc->m[0], cc->m[1], cc->m[2], cc->m[3],
663             cc->m[4], cc->m[5], cc->m[6], cc->m[7]);
664 #endif
665
666 }
667
668
669 static void
670 generate_spheremonics (ModeInfo *mi)
671 {
672   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
673   int wire = MI_IS_WIREFRAME(mi);
674
675   tweak_parameters (mi);
676
677   if (!cc->done_once || (0 == (random() % 20)))
678     {
679       init_colors (mi);
680       cc->done_once = True;
681     }
682
683   {
684     glNewList(cc->dlist, GL_COMPILE);
685     cc->polys1 = unit_spheremonics (mi, cc->resolution, wire,cc->m,cc->colors);
686     glEndList();
687
688     glNewList(cc->dlist2, GL_COMPILE);
689     glPushMatrix();
690     glScalef (1.05, 1.05, 1.05);
691     cc->polys2 = unit_spheremonics (mi, cc->resolution, 2, cc->m, cc->colors);
692     glPopMatrix();
693     glEndList();
694   }
695 }
696
697
698 \f
699
700 ENTRYPOINT void 
701 init_spheremonics (ModeInfo *mi)
702 {
703   spheremonics_configuration *cc;
704
705   MI_INIT (mi, ccs);
706
707   cc = &ccs[MI_SCREEN(mi)];
708
709   if ((cc->glx_context = init_GL(mi)) != NULL) {
710     gl_init(mi);
711     reshape_spheremonics (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
712   }
713
714   {
715     Bool spinx=False, spiny=False, spinz=False;
716     double spin_speed   = 1.0;
717     double wander_speed = 0.03;
718
719     char *s = do_spin;
720     while (*s)
721       {
722         if      (*s == 'x' || *s == 'X') spinx = True;
723         else if (*s == 'y' || *s == 'Y') spiny = True;
724         else if (*s == 'z' || *s == 'Z') spinz = True;
725         else if (*s == '0') ;
726         else
727           {
728             fprintf (stderr,
729          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
730                      progname, do_spin);
731             exit (1);
732           }
733         s++;
734       }
735
736     cc->rot = make_rotator (spinx ? spin_speed : 0,
737                             spinz ? spin_speed : 0,
738                             spiny ? spin_speed : 0,
739                             1.0,
740                             do_wander ? wander_speed : 0,
741                             (spinx && spiny && spinz));
742     cc->trackball = gltrackball_init (True);
743   }
744
745   cc->tracer = -1;
746   cc->mesher = -1;
747
748   cc->resolution = res;
749
750   cc->font_data = load_texture_font (mi->dpy, "labelfont");
751
752   cc->dlist = glGenLists(1);
753   cc->dlist2 = glGenLists(1);
754
755   cc->m_max = 4; /* 9? */
756   {
757     unsigned int i;
758     for (i = 0; i < countof(cc->dm); i++)
759       cc->dm[i] = 1;  /* going up! */
760
761     /* Generate a few more times so we don't always start off with a sphere */
762     for (i = 0; i < 5; i++)
763       tweak_parameters (mi);
764   }
765
766   generate_spheremonics(mi);
767 }
768
769
770 ENTRYPOINT Bool
771 spheremonics_handle_event (ModeInfo *mi, XEvent *event)
772 {
773   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
774
775   if (gltrackball_event_handler (event, cc->trackball,
776                                  MI_WIDTH (mi), MI_HEIGHT (mi),
777                                  &cc->button_down_p))
778     return True;
779   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
780     {
781       cc->change_tick = duration;
782       return True;
783     }
784
785   return False;
786 }
787
788
789 ENTRYPOINT void
790 draw_spheremonics (ModeInfo *mi)
791 {
792   spheremonics_configuration *cc = &ccs[MI_SCREEN(mi)];
793   Display *dpy = MI_DISPLAY(mi);
794   Window window = MI_WINDOW(mi);
795
796   if (!cc->glx_context)
797     return;
798
799   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(cc->glx_context));
800
801   gl_init(mi);
802
803   glShadeModel(GL_SMOOTH);
804
805   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
806
807   glPushMatrix ();
808
809   glScalef(1.1, 1.1, 1.1);
810
811   {
812     double x, y, z;
813     get_position (cc->rot, &x, &y, &z, !cc->button_down_p);
814     glTranslatef((x - 0.5) * 8,
815                  (y - 0.5) * 6,
816                  (z - 0.5) * 8);
817
818     gltrackball_rotate (cc->trackball);
819
820     get_rotation (cc->rot, &x, &y, &z, !cc->button_down_p);
821     glRotatef (x * 360, 1.0, 0.0, 0.0);
822     glRotatef (y * 360, 0.0, 1.0, 0.0);
823     glRotatef (z * 360, 0.0, 0.0, 1.0);
824   }
825
826   glScalef(7,7,7);
827
828   mi->polygon_count = 0;
829
830   glScalef (cc->scale, cc->scale, cc->scale);
831   glCallList (cc->dlist);
832   mi->polygon_count += cc->polys1;
833
834   if (cc->mesher >= 0 /* || cc->button_down_p */)
835     {
836       glDisable (GL_LIGHTING);
837       glCallList (cc->dlist2);
838       mi->polygon_count += cc->polys2;
839       if (cc->mesher >= 0)
840         cc->mesher--;
841     }
842   do_tracer(mi);
843
844
845   if (cc->button_down_p)
846     {
847       char buf[200];
848       sprintf (buf,
849                ((cc->m[0]<10 && cc->m[1]<10 && cc->m[2]<10 && cc->m[3]<10 &&
850                  cc->m[4]<10 && cc->m[5]<10 && cc->m[6]<10 && cc->m[7]<10)
851                 ? "%d%d%d%d%d%d%d%d"
852                 : "%d %d %d %d %d %d %d %d"),
853                cc->m[0], cc->m[1], cc->m[2], cc->m[3],
854                cc->m[4], cc->m[5], cc->m[6], cc->m[7]);
855
856       glColor3f(1.0, 1.0, 0.0);
857       print_texture_label (mi->dpy, cc->font_data,
858                            mi->xgwa.width, mi->xgwa.height,
859                            1, buf);
860     }
861
862   if (!static_parms)
863     {
864       if (cc->change_tick++ >= duration && !cc->button_down_p)
865         {
866           generate_spheremonics(mi);
867           cc->change_tick = 0;
868           cc->mesher = -1;  /* turn off the mesh when switching objects */
869         }
870     }
871
872   glPopMatrix();
873
874   if (mi->fps_p) do_fps (mi);
875   glFinish();
876
877   glXSwapBuffers(dpy, window);
878 }
879
880 XSCREENSAVER_MODULE ("Spheremonics", spheremonics)
881
882 #endif /* USE_GL */