From http://www.jwz.org/xscreensaver/xscreensaver-5.16.tar.gz
[xscreensaver] / hacks / glx / tronbit.c
1 /* tronbit, Copyright (c) 2011-2012 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:        30000       \n" \
13                         "*count:        30          \n" \
14                         "*showFPS:      False       \n" \
15                         "*wireframe:    False       \n"
16
17 # define refresh_bit 0
18 # define release_bit 0
19 #undef countof
20 #define countof(x) (sizeof((x))/sizeof((*x)))
21
22 #include "xlockmore.h"
23 #include "colors.h"
24 #include "sphere.h"
25 #include "rotator.h"
26 #include "gltrackball.h"
27 #include <ctype.h>
28
29 #ifdef USE_GL /* whole file */
30
31 #include "gllist.h"
32
33 extern const struct gllist *tronbit_idle1, *tronbit_idle2,
34   *tronbit_no, *tronbit_yes;
35 static const struct gllist * const *all_objs[] = {
36   &tronbit_idle1, &tronbit_idle2, &tronbit_no, &tronbit_yes };
37
38
39 #define DEF_SPIN        "True"
40 #define DEF_WANDER      "True"
41 #define DEF_SPEED       "1.0"
42
43 #define HISTORY_LENGTH 512
44 typedef enum { BIT_IDLE1, BIT_IDLE2, BIT_NO, BIT_YES } bit_state;
45 #define MODELS 4
46
47
48 typedef struct {
49   GLXContext *glx_context;
50   rotator *rot;
51   trackball_state *trackball;
52   Bool button_down_p;
53
54   double frequency;
55   double confidence;
56
57   double last_time;
58   unsigned char history   [HISTORY_LENGTH];
59   unsigned char histogram [HISTORY_LENGTH];
60   int history_fp, histogram_fp;
61
62   GLuint dlists[MODELS], polys[MODELS];
63   char kbd;
64
65 } bit_configuration;
66
67 static bit_configuration *bps = NULL;
68
69 static const GLfloat colors[][4] = {
70   { 0.66, 0.85, 1.00, 1.00 },
71   { 0.66, 0.85, 1.00, 1.00 },
72   { 1.00, 0.12, 0.12, 1.00 },
73   { 0.98, 0.85, 0.30, 1.00 }
74 };
75
76
77 static Bool do_spin;
78 static GLfloat speed;
79 static Bool do_wander;
80
81 static XrmOptionDescRec opts[] = {
82   { "-spin",   ".spin",   XrmoptionNoArg, "True" },
83   { "+spin",   ".spin",   XrmoptionNoArg, "False" },
84   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
85   { "-wander", ".wander", XrmoptionNoArg, "True" },
86   { "+wander", ".wander", XrmoptionNoArg, "False" }
87 };
88
89 static argtype vars[] = {
90   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_Bool},
91   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
92   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
93 };
94
95 ENTRYPOINT ModeSpecOpt bit_opts = {countof(opts), opts, countof(vars), vars, NULL};
96
97
98 /* Returns the current time in seconds as a double.
99  */
100 static double
101 double_time (void)
102 {
103   struct timeval now;
104 # ifdef GETTIMEOFDAY_TWO_ARGS
105   struct timezone tzp;
106   gettimeofday(&now, &tzp);
107 # else
108   gettimeofday(&now);
109 # endif
110
111   return (now.tv_sec + ((double) now.tv_usec * 0.000001));
112 }
113
114
115 static int
116 make_bit (ModeInfo *mi, bit_state which)
117 {
118   static const GLfloat spec[4] = {1.0, 1.0, 1.0, 1.0};
119   static const GLfloat shiny   = 128.0;
120   const GLfloat *color = colors[which];
121   int wire = MI_IS_WIREFRAME(mi);
122   int polys = 0;
123   GLfloat s;
124   const struct gllist *gll;
125
126   glMaterialfv (GL_FRONT, GL_SPECULAR,            spec);
127   glMateriali  (GL_FRONT, GL_SHININESS,           shiny);
128   glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
129   glColor4f (color[0], color[1], color[2], color[3]);
130
131   glPushMatrix();
132   switch (which)
133     {
134     case BIT_IDLE1:
135       glRotatef (-44, 0, 1, 0);   /* line up the models with each other */
136       glRotatef (-11, 1, 0, 0);
137       glRotatef (  8, 0, 0, 1);
138       s = 1.0;
139       break;
140     case BIT_IDLE2:
141       glRotatef ( 16.0, 0, 0, 1);
142       glRotatef (-28.0, 1, 0, 0);
143       s = 1.0;
144       break;
145     case BIT_NO:
146       glRotatef ( 16.0, 0, 0, 1);
147       glRotatef (-28.0, 1, 0, 0);
148       s = 1.6;
149       break;
150     case BIT_YES:
151       glRotatef (-44.0, 0, 1, 0);
152       glRotatef (-32.0, 1, 0, 0);
153       s = 1.53;
154       break;
155     default:
156       abort();
157       break;
158     }
159   glScalef (s, s, s);
160   gll = *all_objs[which];
161   renderList (gll, wire);
162   polys += gll->points / 3;
163   glPopMatrix();
164
165   return polys;
166 }
167
168
169 static void
170 tick_bit (ModeInfo *mi, double now)
171 {
172   bit_configuration *bp = &bps[MI_SCREEN(mi)];
173   double freq = bp->frequency;
174   int n = bp->history[bp->history_fp];
175   int histogram_speed = 3 * speed;
176   int i;
177
178   if (histogram_speed < 1) histogram_speed = 1;
179
180   if (n == BIT_YES || n == BIT_NO)
181     freq *= 2;
182
183   if (bp->button_down_p) return;
184
185   for (i = 0; i < histogram_speed; i++)
186     {
187       int nn = (n == BIT_YES ? 240 : n == BIT_NO  ? 17 : 128);
188       int on = bp->histogram[(bp->histogram_fp-1) % countof(bp->histogram)];
189
190       /* smooth out the square wave a little bit */
191
192       if (!(nn > 100 && nn < 200) !=
193           !(on > 100 && on < 200))
194         nn += (((random() % 48) - 32) *
195                ((on > 100 && on < 200) ? 1 : -1));
196
197       nn += (random() % 16) - 8;
198
199       bp->histogram_fp++;
200       if (bp->histogram_fp >= countof(bp->history))
201         bp->histogram_fp = 0;
202       bp->histogram [bp->histogram_fp] = nn;
203     }
204
205
206   if (bp->last_time + freq > now && !bp->kbd) return;
207
208   bp->last_time = now;
209
210   bp->history_fp++;
211   if (bp->history_fp >= countof(bp->history))
212     bp->history_fp = 0;
213
214   if (bp->kbd)
215     {
216       n = (bp->kbd == '1' ? BIT_YES :
217            bp->kbd == '0' ? BIT_NO :
218            (random() & 1) ? BIT_YES : BIT_NO);
219       bp->kbd = 0;
220     }
221   else if (n == BIT_YES || 
222            n == BIT_NO ||
223            frand(1.0) >= bp->confidence)
224     n = (n == BIT_IDLE1 ? BIT_IDLE2 : BIT_IDLE1);
225   else
226     n = (random() & 1) ? BIT_YES : BIT_NO;
227
228   bp->history [bp->history_fp] = n;
229 }
230
231
232 static int
233 animate_bits (ModeInfo *mi, bit_state omodel, bit_state nmodel, GLfloat ratio)
234 {
235   bit_configuration *bp = &bps[MI_SCREEN(mi)];
236   int polys = 0;
237   GLfloat scale = sin (ratio * M_PI / 2);
238   GLfloat osize, nsize, small;
239   int wire = MI_IS_WIREFRAME(mi);
240
241   glShadeModel(GL_SMOOTH);
242
243   glEnable(GL_DEPTH_TEST);
244   glEnable(GL_NORMALIZE);
245   glEnable(GL_CULL_FACE);
246
247   if (!wire)
248     {
249       glEnable(GL_LIGHTING);
250       glEnable(GL_DEPTH_TEST);
251       glEnable(GL_CULL_FACE);
252     }
253
254  if ((omodel == BIT_IDLE1 || omodel == BIT_IDLE2) &&
255      (nmodel == BIT_IDLE1 || nmodel == BIT_IDLE2))
256    small = 0.9;
257  else
258    small = 0.5;
259
260   nsize = small + (1 - small) * scale;
261   osize = small + (1 - small) * (1 - scale);
262
263   glPushMatrix();
264   glScalef (osize, osize, osize);
265   glCallList (bp->dlists [omodel]);
266   polys += bp->polys [omodel];
267   glPopMatrix();
268
269   glPushMatrix();
270   glScalef (nsize, nsize, nsize);
271   glCallList (bp->dlists [nmodel]);
272   polys += bp->polys [nmodel];
273   glPopMatrix();
274
275   return polys;
276 }
277
278
279 static int
280 draw_histogram (ModeInfo *mi, GLfloat ratio)
281 {
282   bit_configuration *bp = &bps[MI_SCREEN(mi)];
283   int samples = countof (bp->histogram);
284   GLfloat scalex = (GLfloat) mi->xgwa.width / samples;
285   GLfloat scaley = mi->xgwa.height / 255.0 / 4;  /* about 1/4th of screen */
286   int polys = 0;
287   int overlays = 5;
288   int k;
289   
290   glDisable (GL_TEXTURE_2D);
291   glDisable (GL_LIGHTING);
292   glDisable (GL_BLEND);
293   glDisable (GL_DEPTH_TEST);
294   glDisable (GL_CULL_FACE);
295
296   glMatrixMode(GL_PROJECTION);
297   glPushMatrix();
298   {
299     glLoadIdentity();
300     glMatrixMode(GL_MODELVIEW);
301     glPushMatrix();
302
303     glLoadIdentity();
304     glRotatef(current_device_rotation(), 0, 0, 1);
305     glOrtho (0, mi->xgwa.width, 0, mi->xgwa.height, -1, 1);
306
307     for (k = 0; k < overlays; k++)
308       {
309         int i, j;
310         GLfloat a = (GLfloat) k / overlays;
311
312         glColor3f (0.3 * a, 0.7 * a, 1.0 * a);
313
314         glBegin (GL_LINE_STRIP);
315
316         j = bp->histogram_fp + 1;
317         for (i = 0; i < samples; i++)
318           {
319             GLfloat x = i;
320             GLfloat y = bp->histogram[j];
321             GLfloat z = 0;
322
323             y += (int) ((random() % 16) - 8);
324             y += 16;  /* margin at bottom of screen */
325
326             x *= scalex;
327             y *= scaley;
328
329             glVertex3f (x, y, z);
330             if (++j >= samples) j = 0;
331             polys++;
332           }
333         glEnd();
334       }
335
336     glPopMatrix();
337   }
338   glMatrixMode(GL_PROJECTION);
339   glPopMatrix();
340
341   glMatrixMode(GL_MODELVIEW);
342
343   return polys;
344 }
345
346
347 /* Window management, etc
348  */
349 ENTRYPOINT void
350 reshape_bit (ModeInfo *mi, int width, int height)
351 {
352   GLfloat h = (GLfloat) height / (GLfloat) width;
353
354   glViewport (0, 0, (GLint) width, (GLint) height);
355
356   glMatrixMode(GL_PROJECTION);
357   glLoadIdentity();
358   gluPerspective (30.0, 1/h, 1.0, 100.0);
359
360   glMatrixMode(GL_MODELVIEW);
361   glLoadIdentity();
362   gluLookAt( 0.0, 0.0, 30.0,
363              0.0, 0.0, 0.0,
364              0.0, 1.0, 0.0);
365
366   glClear(GL_COLOR_BUFFER_BIT);
367 }
368
369
370
371 ENTRYPOINT Bool
372 bit_handle_event (ModeInfo *mi, XEvent *event)
373 {
374   bit_configuration *bp = &bps[MI_SCREEN(mi)];
375
376   if (event->xany.type == ButtonPress &&
377       event->xbutton.button == Button1)
378     {
379       bp->button_down_p = True;
380       gltrackball_start (bp->trackball,
381                          event->xbutton.x, event->xbutton.y,
382                          MI_WIDTH (mi), MI_HEIGHT (mi));
383       return True;
384     }
385   else if (event->xany.type == ButtonRelease &&
386            event->xbutton.button == Button1)
387     {
388       bp->button_down_p = False;
389       return True;
390     }
391   else if (event->xany.type == ButtonPress &&
392            (event->xbutton.button == Button4 ||
393             event->xbutton.button == Button5 ||
394             event->xbutton.button == Button6 ||
395             event->xbutton.button == Button7))
396     {
397       gltrackball_mousewheel (bp->trackball, event->xbutton.button, 3,
398                               !!event->xbutton.state);
399       return True;
400     }
401   else if (event->xany.type == MotionNotify &&
402            bp->button_down_p)
403     {
404       gltrackball_track (bp->trackball,
405                          event->xmotion.x, event->xmotion.y,
406                          MI_WIDTH (mi), MI_HEIGHT (mi));
407       return True;
408     }
409   else if (event->xany.type == KeyPress)
410     {
411       KeySym keysym;
412       char c = 0;
413       XLookupString (&event->xkey, &c, 1, &keysym, 0);
414       if (c == ' ' || c == '1' || c == '0')
415         {
416           bp->kbd = c;
417           return True;
418         }
419     }
420
421   return False;
422 }
423
424
425 ENTRYPOINT void 
426 init_bit (ModeInfo *mi)
427 {
428   bit_configuration *bp;
429   int i;
430
431   if (!bps) {
432     bps = (bit_configuration *)
433       calloc (MI_NUM_SCREENS(mi), sizeof (bit_configuration));
434     if (!bps) {
435       fprintf(stderr, "%s: out of memory\n", progname);
436       exit(1);
437     }
438   }
439
440   bp = &bps[MI_SCREEN(mi)];
441
442   bp->glx_context = init_GL(mi);
443
444   reshape_bit (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
445
446   {
447     double spin_speed   = 3.0;
448     double wander_speed = 0.03 * speed;
449     double spin_accel   = 4.0;
450
451     bp->rot = make_rotator (do_spin ? spin_speed : 0,
452                             do_spin ? spin_speed : 0,
453                             do_spin ? spin_speed : 0,
454                             spin_accel,
455                             do_wander ? wander_speed : 0,
456                             False);
457     bp->trackball = gltrackball_init ();
458   }
459
460   for (i = 0; i < countof(bp->dlists); i++)
461     {
462       bp->dlists[i] = glGenLists (1);
463       glNewList (bp->dlists[i], GL_COMPILE);
464       bp->polys [i] = make_bit (mi, i);
465       glEndList ();
466     }
467
468   bp->frequency  = 0.30 / speed;        /* parity around 3x/second */
469   bp->confidence = 0.06;                /* provide answer 1/15 or so */
470
471   for (i = 0; i < countof(bp->histogram); i++)
472     bp->histogram[i] = 128 + (random() % 16) - 8;
473 }
474
475
476 ENTRYPOINT void
477 draw_bit (ModeInfo *mi)
478 {
479   bit_configuration *bp = &bps[MI_SCREEN(mi)];
480   Display *dpy = MI_DISPLAY(mi);
481   Window window = MI_WINDOW(mi);
482   int wire = MI_IS_WIREFRAME(mi);
483
484   if (!bp->glx_context)
485     return;
486
487   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
488
489   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
490
491   if (!wire)
492     {
493       GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
494       GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
495       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
496       GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};
497
498       glEnable(GL_LIGHTING);
499       glEnable(GL_LIGHT0);
500       glLightfv(GL_LIGHT0, GL_POSITION, pos);
501       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
502       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
503       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
504     }
505
506   glPushMatrix ();
507   glRotatef(current_device_rotation(), 0, 0, 1);
508
509   glScalef(1.1, 1.1, 1.1);
510
511   {
512     double x, y, z;
513     get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
514     glTranslatef((x - 0.5) * 11,
515                  (y - 0.5) * 5,
516                  (z - 0.5) * 3);
517
518     glRotatef(-current_device_rotation(), 0, 0, 1);
519     gltrackball_rotate (bp->trackball);
520     glRotatef(current_device_rotation(), 0, 0, 1);
521
522     get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p);
523     glRotatef (x * 360, 1.0, 0.0, 0.0);
524     glRotatef (y * 360, 0.0, 1.0, 0.0);
525     glRotatef (z * 360, 0.0, 0.0, 1.0);
526   }
527
528   mi->polygon_count = 0;
529
530   glScalef (6, 6, 6);
531
532   {
533     int nmodel = bp->history [bp->history_fp];
534     int omodel = bp->history [bp->history_fp > 0
535                               ? bp->history_fp-1
536                               : countof(bp->history)-1];
537     double now = double_time();
538     double ratio = 1 - ((bp->last_time + bp->frequency) - now) / bp->frequency;
539     if (ratio > 1) ratio = 1;
540     mi->polygon_count += draw_histogram (mi, ratio);
541     mi->polygon_count += animate_bits (mi, omodel, nmodel, ratio);
542     tick_bit (mi, now);
543   }
544   glPopMatrix ();
545
546   if (mi->fps_p) do_fps (mi);
547   glFinish();
548
549   glXSwapBuffers(dpy, window);
550 }
551
552 XSCREENSAVER_MODULE_2 ("TronBit", tronbit, bit)
553
554 #endif /* USE_GL */