From http://www.jwz.org/xscreensaver/xscreensaver-5.30.tar.gz
[xscreensaver] / hacks / glx / carousel.c
1 /* carousel, Copyright (c) 2005-2014 Jamie Zawinski <jwz@jwz.org>
2  * Loads a sequence of images and rotates them around.
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or
10  * implied warranty.
11  *
12  * Created: 21-Feb-2005
13  */
14
15 #define DEF_FONT "-*-helvetica-bold-r-normal-*-240-*"
16 #define DEFAULTS  "*count:           7         \n" \
17                   "*delay:           10000     \n" \
18                   "*wireframe:       False     \n" \
19                   "*showFPS:         False     \n" \
20                   "*fpsSolid:        True      \n" \
21                   "*useSHM:          True      \n" \
22                   "*font:          " DEF_FONT "\n" \
23                   "*desktopGrabber:  xscreensaver-getimage -no-desktop %s\n" \
24                   "*grabDesktopImages:   False \n" \
25                   "*chooseRandomImages:  True  \n"
26
27 # define refresh_carousel 0
28 # define release_carousel 0
29 # include "xlockmore.h"
30
31 #undef countof
32 #define countof(x) (sizeof((x))/sizeof((*x)))
33
34 #ifdef USE_GL
35
36 # define DEF_SPEED          "1.0"
37 # define DEF_DURATION       "20"
38 # define DEF_TITLES         "True"
39 # define DEF_ZOOM           "True"
40 # define DEF_TILT           "XY"
41 # define DEF_MIPMAP         "True"
42 # define DEF_DEBUG          "False"
43
44 #include "rotator.h"
45 #include "gltrackball.h"
46 #include "grab-ximage.h"
47 #include "texfont.h"
48
49 # ifndef HAVE_COCOA
50 #  include <X11/Intrinsic.h>     /* for XrmDatabase in -debug mode */
51 # endif
52
53 /* Should be in <GL/glext.h> */
54 # ifndef  GL_TEXTURE_MAX_ANISOTROPY_EXT
55 #  define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
56 # endif
57 # ifndef  GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
58 #  define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
59 # endif
60
61 typedef struct {
62   double x, y, w, h;
63 } rect;
64
65 typedef enum { EARLY, NORMAL, LOADING, OUT, IN, DEAD } fade_mode;
66 static int fade_ticks = 60;
67
68 typedef struct {
69   char *title;                  /* the filename of this image */
70   int w, h;                     /* size in pixels of the image */
71   int tw, th;                   /* size in pixels of the texture */
72   XRectangle geom;              /* where in the image the bits are */
73   GLuint texid;
74 } image;
75
76 typedef struct {
77   ModeInfo *mi;
78   image current, loading;
79   GLfloat r, theta;             /* radius and rotation on the tube */
80   rotator *rot;                 /* for zoomery */
81   Bool from_top_p;              /* whether this image drops in or rises up */
82   time_t expires;               /* when this image should be replaced */
83   fade_mode mode;               /* in/out animation state */
84   int mode_tick;
85   Bool loaded_p;                /* whether background load is done */
86 } image_frame;
87
88
89 typedef struct {
90   GLXContext *glx_context;
91   GLfloat anisotropic;
92   rotator *rot;
93   trackball_state *trackball;
94   Bool button_down_p;
95   time_t button_down_time;
96
97   int nframes;                  /* how many frames are loaded */
98   int frames_size;
99   image_frame **frames;         /* pointers to the frames */
100
101   Bool awaiting_first_images_p;
102   int loads_in_progress;
103
104   texture_font_data *texfont;
105
106   fade_mode mode;
107   int mode_tick;
108
109   int loading_sw, loading_sh;
110
111   time_t last_time, now;
112   int draw_tick;
113
114 } carousel_state;
115
116 static carousel_state *sss = NULL;
117
118
119 /* Command-line arguments
120  */
121 static GLfloat speed;       /* animation speed scale factor */
122 static int duration;        /* reload images after this long */
123 static Bool mipmap_p;       /* Use mipmaps instead of single textures. */
124 static Bool titles_p;       /* Display image titles. */
125 static Bool zoom_p;         /* Throb the images in and out as they spin. */
126 static char *tilt_str;
127 static Bool tilt_x_p;       /* Tilt axis towards the viewer */
128 static Bool tilt_y_p;       /* Tilt axis side to side */
129 static Bool debug_p;        /* Be loud and do weird things. */
130
131
132 static XrmOptionDescRec opts[] = {
133   {"-zoom",         ".zoom",          XrmoptionNoArg, "True"  },
134   {"-no-zoom",      ".zoom",          XrmoptionNoArg, "False" },
135   {"-tilt",         ".tilt",          XrmoptionSepArg, 0  },
136   {"-no-tilt",      ".tilt",          XrmoptionNoArg, ""  },
137   {"-titles",       ".titles",        XrmoptionNoArg, "True"  },
138   {"-no-titles",    ".titles",        XrmoptionNoArg, "False" },
139   {"-mipmaps",      ".mipmap",        XrmoptionNoArg, "True"  },
140   {"-no-mipmaps",   ".mipmap",        XrmoptionNoArg, "False" },
141   {"-duration",     ".duration",      XrmoptionSepArg, 0 },
142   {"-debug",        ".debug",         XrmoptionNoArg, "True"  },
143   {"-font",         ".font",          XrmoptionSepArg, 0 },
144   {"-speed",        ".speed",         XrmoptionSepArg, 0 },
145 };
146
147 static argtype vars[] = {
148   { &mipmap_p,      "mipmap",       "Mipmap",       DEF_MIPMAP,      t_Bool},
149   { &debug_p,       "debug",        "Debug",        DEF_DEBUG,       t_Bool},
150   { &titles_p,      "titles",       "Titles",       DEF_TITLES,      t_Bool},
151   { &zoom_p,        "zoom",         "Zoom",         DEF_ZOOM,        t_Bool},
152   { &tilt_str,      "tilt",         "Tilt",         DEF_TILT,        t_String},
153   { &speed,         "speed",        "Speed",        DEF_SPEED,       t_Float},
154   { &duration,      "duration",     "Duration",     DEF_DURATION,    t_Int},
155 };
156
157 ENTRYPOINT ModeSpecOpt carousel_opts = {countof(opts), opts, countof(vars), vars, NULL};
158
159
160 /* Allocates a frame structure and stores it in the list.
161  */
162 static image_frame *
163 alloc_frame (ModeInfo *mi)
164 {
165   carousel_state *ss = &sss[MI_SCREEN(mi)];
166   image_frame *frame = (image_frame *) calloc (1, sizeof (*frame));
167
168   frame->mi = mi;
169   frame->mode = EARLY;
170   frame->rot = make_rotator (0, 0, 0, 0, 0.04 * frand(1.0) * speed, False);
171
172   glGenTextures (1, &frame->current.texid);
173   glGenTextures (1, &frame->loading.texid);
174   if (frame->current.texid <= 0) abort();
175   if (frame->loading.texid <= 0) abort();
176
177   if (ss->frames_size <= ss->nframes)
178     {
179       ss->frames_size = (ss->frames_size * 1.2) + ss->nframes;
180       ss->frames = (image_frame **)
181         realloc (ss->frames, ss->frames_size * sizeof(*ss->frames));
182       if (! ss->frames)
183         {
184           fprintf (stderr, "%s: out of memory (%d images)\n",
185                    progname, ss->frames_size);
186           exit (1);
187         }
188     }
189
190   ss->frames[ss->nframes++] = frame;
191
192   return frame;
193 }
194
195
196 static void image_loaded_cb (const char *filename, XRectangle *geom,
197                              int image_width, int image_height,
198                              int texture_width, int texture_height,
199                              void *closure);
200
201
202 /* Load a new file into the given image struct.
203  */
204 static void
205 load_image (ModeInfo *mi, image_frame *frame)
206 {
207   carousel_state *ss = &sss[MI_SCREEN(mi)];
208   int wire = MI_IS_WIREFRAME(mi);
209
210   if (debug_p && !wire && frame->current.w != 0)
211     fprintf (stderr, "%s:  dropped %4d x %-4d  %4d x %-4d  \"%s\"\n",
212              progname, 
213              frame->current.geom.width, 
214              frame->current.geom.height, 
215              frame->current.tw, frame->current.th,
216              (frame->current.title ? frame->current.title : "(null)"));
217
218   switch (frame->mode) 
219     {
220     case EARLY:  break;
221     case NORMAL: frame->mode = LOADING; break;
222     default: abort();
223     }
224
225   ss->loads_in_progress++;
226
227   if (wire)
228     image_loaded_cb (0, 0, 0, 0, 0, 0, frame);
229   else
230     {
231       int w = (MI_WIDTH(mi)  / 2) - 1;
232       int h = (MI_HEIGHT(mi) / 2) - 1;
233       if (w <= 10) w = 10;
234       if (h <= 10) h = 10;
235       load_texture_async (mi->xgwa.screen, mi->window, *ss->glx_context, w, h,
236                           mipmap_p, frame->loading.texid, 
237                           image_loaded_cb, frame);
238     }
239 }
240
241
242 /* Callback that tells us that the texture has been loaded.
243  */
244 static void
245 image_loaded_cb (const char *filename, XRectangle *geom,
246                  int image_width, int image_height,
247                  int texture_width, int texture_height,
248                  void *closure)
249 {
250   image_frame *frame = (image_frame *) closure;
251   ModeInfo *mi = frame->mi;
252   carousel_state *ss = &sss[MI_SCREEN(mi)];
253   int wire = MI_IS_WIREFRAME(mi);
254
255   if (wire)
256     {
257       frame->loading.w = MI_WIDTH (mi) * (0.5 + frand (1.0));
258       frame->loading.h = MI_HEIGHT (mi);
259       frame->loading.geom.width  = frame->loading.w;
260       frame->loading.geom.height = frame->loading.h;
261       goto DONE;
262     }
263
264   if (image_width == 0 || image_height == 0)
265     exit (1);
266
267   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
268   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
269                    mipmap_p ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
270
271   if (ss->anisotropic >= 1.0)
272     glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 
273                      ss->anisotropic);
274
275   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
276   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
277
278   frame->loading.w  = image_width;
279   frame->loading.h  = image_height;
280   frame->loading.tw = texture_width;
281   frame->loading.th = texture_height;
282   frame->loading.geom = *geom;
283
284   if (frame->loading.title)
285     free (frame->loading.title);
286   frame->loading.title = (filename ? strdup (filename) : 0);
287
288   /* xscreensaver-getimage returns paths relative to the image directory
289      now, so leave the sub-directory part in.  Unless it's an absolute path.
290   */
291   if (frame->loading.title && frame->loading.title[0] == '/')
292     {    /* strip filename to part after last /. */
293       char *s = strrchr (frame->loading.title, '/');
294       if (s) strcpy (frame->loading.title, s+1);
295     }
296
297   if (debug_p)
298     fprintf (stderr, "%s:   loaded %4d x %-4d  %4d x %-4d  \"%s\"\n",
299              progname,
300              frame->loading.geom.width, 
301              frame->loading.geom.height, 
302              frame->loading.tw, frame->loading.th,
303              (frame->loading.title ? frame->loading.title : "(null)"));
304
305  DONE:
306
307   frame->loaded_p = True;
308
309   if (ss->loads_in_progress <= 0) abort();
310   ss->loads_in_progress--;
311
312   /* This image expires N seconds after it finished loading. */
313   frame->expires = time((time_t *) 0) + (duration * MI_COUNT(mi));
314
315   switch (frame->mode) 
316     {
317     case EARLY:         /* part of the initial batch of images */
318       {
319         image swap = frame->current;
320         frame->current = frame->loading;
321         frame->loading = swap;
322       }
323       break;
324     case LOADING:       /* start dropping the old image out */
325       {
326         frame->mode = OUT;
327         frame->mode_tick = fade_ticks / speed;
328         frame->from_top_p = random() & 1;
329       }
330       break;
331     default:
332       abort();
333     }
334 }
335
336
337 static void loading_msg (ModeInfo *mi, int n);
338
339 static Bool
340 load_initial_images (ModeInfo *mi)
341 {
342   carousel_state *ss = &sss[MI_SCREEN(mi)];
343   int i;
344   Bool all_loaded_p = True;
345   for (i = 0; i < ss->nframes; i++)
346     if (! ss->frames[i]->loaded_p)
347       all_loaded_p = False;
348
349   if (all_loaded_p)
350     {
351       if (ss->nframes < MI_COUNT (mi))
352         {
353           /* The frames currently on the list are fully loaded.
354              Start the next one loading.  (We run the image loader
355              asynchronously, but we load them one at a time.)
356            */
357           load_image (mi, alloc_frame (mi));
358         }
359       else
360         {
361           /* The first batch of images are now all loaded!
362              Stagger the expire times so that they don't all drop out at once.
363            */
364           time_t now = time((time_t *) 0);
365           int i;
366
367           for (i = 0; i < ss->nframes; i++)
368             {
369               image_frame *frame = ss->frames[i];
370               frame->r = 1.0;
371               frame->theta = i * 360.0 / ss->nframes;
372               frame->expires = now + (duration * (i + 1));
373               frame->mode = NORMAL;
374             }
375
376           /* Instead of always going clockwise, shuffle the expire times
377              of the frames so that they drop out in a random order.
378           */
379           for (i = 0; i < ss->nframes; i++)
380             {
381               image_frame *frame1 = ss->frames[i];
382               image_frame *frame2 = ss->frames[random() % ss->nframes];
383               time_t swap = frame1->expires;
384               frame1->expires = frame2->expires;
385               frame2->expires = swap;
386             }
387
388           ss->awaiting_first_images_p = False;
389         }
390     }
391       
392   loading_msg (mi, ss->nframes-1);
393
394   return !ss->awaiting_first_images_p;
395 }
396
397
398 ENTRYPOINT void
399 reshape_carousel (ModeInfo *mi, int width, int height)
400 {
401   GLfloat h = (GLfloat) height / (GLfloat) width;
402
403   glViewport (0, 0, (GLint) width, (GLint) height);
404
405   glMatrixMode(GL_PROJECTION);
406   glLoadIdentity();
407   gluPerspective (60.0, 1/h, 1.0, 8.0);
408
409   glMatrixMode(GL_MODELVIEW);
410   glLoadIdentity();
411   gluLookAt( 0.0, 0.0, 2.6,
412              0.0, 0.0, 0.0,
413              0.0, 1.0, 0.0);
414
415   glClear(GL_COLOR_BUFFER_BIT);
416 }
417
418
419 ENTRYPOINT Bool
420 carousel_handle_event (ModeInfo *mi, XEvent *event)
421 {
422   carousel_state *ss = &sss[MI_SCREEN(mi)];
423
424   if (event->xany.type == ButtonPress &&
425       event->xbutton.button == Button1)
426     {
427       if (! ss->button_down_p)
428         ss->button_down_time = time((time_t *) 0);
429     }
430   else if (event->xany.type == ButtonRelease &&
431            event->xbutton.button == Button1)
432     {
433       if (ss->button_down_p)
434         {
435           /* Add the time the mouse was held to the expire times of all
436              frames, so that mouse-dragging doesn't count against
437              image expiration.
438            */
439           int secs = time((time_t *) 0) - ss->button_down_time;
440           int i;
441           for (i = 0; i < ss->nframes; i++)
442             ss->frames[i]->expires += secs;
443         }
444     }
445
446   if (gltrackball_event_handler (event, ss->trackball,
447                                  MI_WIDTH (mi), MI_HEIGHT (mi),
448                                  &ss->button_down_p))
449     return True;
450   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
451     {
452       int i = random() % ss->nframes;
453       ss->frames[i]->expires  = 0;
454       return True;
455     }
456
457   return False;
458 }
459
460
461 /* Kludge to add "-v" to invocation of "xscreensaver-getimage" in -debug mode
462  */
463 static void
464 hack_resources (Display *dpy)
465 {
466 # ifndef HAVE_COCOA
467   char *res = "desktopGrabber";
468   char *val = get_string_resource (dpy, res, "DesktopGrabber");
469   char buf1[255];
470   char buf2[255];
471   XrmValue value;
472   XrmDatabase db = XtDatabase (dpy);
473   sprintf (buf1, "%.100s.%.100s", progname, res);
474   sprintf (buf2, "%.200s -v", val);
475   value.addr = buf2;
476   value.size = strlen(buf2);
477   XrmPutResource (&db, buf1, "String", &value);
478 # endif /* !HAVE_COCOA */
479 }
480
481
482 static void
483 loading_msg (ModeInfo *mi, int n)
484 {
485   carousel_state *ss = &sss[MI_SCREEN(mi)];
486   int wire = MI_IS_WIREFRAME(mi);
487   char text[100];
488
489   if (wire) return;
490
491   if (n == 0)
492     sprintf (text, "Loading images...");
493   else
494     sprintf (text, "Loading images...  (%d%%)",
495              (int) (n * 100 / MI_COUNT(mi)));
496
497   if (ss->loading_sw == 0)    /* only do this once, so that the string doesn't move. */
498     ss->loading_sw = texture_string_width (ss->texfont, text, &ss->loading_sh);
499
500   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
501
502   glMatrixMode(GL_PROJECTION);
503   glPushMatrix();
504   glLoadIdentity();
505
506   glMatrixMode(GL_MODELVIEW);
507   glPushMatrix();
508   glLoadIdentity();
509
510   {
511     double rot = current_device_rotation();
512     glRotatef(rot, 0, 0, 1);
513     if ((rot >  45 && rot <  135) ||
514         (rot < -45 && rot > -135))
515       {
516         GLfloat s = MI_WIDTH(mi) / (GLfloat) MI_HEIGHT(mi);
517         glScalef (s, 1/s, 1);
518       }
519   }
520
521   if (MI_WIDTH(mi) < MI_HEIGHT(mi))  /* USE_IPHONE portrait orientation */
522     {
523       GLfloat s = (MI_WIDTH(mi) / (GLfloat) MI_HEIGHT(mi));
524       glScalef (s, s, s);
525       glTranslatef(-s/2, 0, 0);
526     }
527
528   glOrtho(0, MI_WIDTH(mi), 0, MI_HEIGHT(mi), -1, 1);
529   glTranslatef ((MI_WIDTH(mi)  - ss->loading_sw) / 2,
530                 (MI_HEIGHT(mi) - ss->loading_sh) / 2,
531                 0);
532   glColor3f (1, 1, 0);
533   glEnable (GL_TEXTURE_2D);
534   glDisable (GL_DEPTH_TEST);
535   print_texture_string (ss->texfont, text);
536   glEnable (GL_DEPTH_TEST);
537   glPopMatrix();
538
539   glMatrixMode(GL_PROJECTION);
540   glPopMatrix();
541
542   glMatrixMode(GL_MODELVIEW);
543
544   glFinish();
545   glXSwapBuffers (MI_DISPLAY (mi), MI_WINDOW(mi));
546 }
547
548
549 ENTRYPOINT void
550 init_carousel (ModeInfo *mi)
551 {
552   int screen = MI_SCREEN(mi);
553   carousel_state *ss;
554   int wire = MI_IS_WIREFRAME(mi);
555   
556   if (sss == NULL) {
557     if ((sss = (carousel_state *)
558          calloc (MI_NUM_SCREENS(mi), sizeof(carousel_state))) == NULL)
559       return;
560   }
561   ss = &sss[screen];
562
563   if ((ss->glx_context = init_GL(mi)) != NULL) {
564     reshape_carousel (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
565     clear_gl_error(); /* WTF? sometimes "invalid op" from glViewport! */
566   } else {
567     MI_CLEARWINDOW(mi);
568   }
569
570   if (!tilt_str || !*tilt_str)
571     ;
572   else if (!strcasecmp (tilt_str, "0"))
573     ;
574   else if (!strcasecmp (tilt_str, "X"))
575     tilt_x_p = 1;
576   else if (!strcasecmp (tilt_str, "Y"))
577     tilt_y_p = 1;
578   else if (!strcasecmp (tilt_str, "XY"))
579     tilt_x_p = tilt_y_p = 1;
580   else
581     {
582       fprintf (stderr, "%s: tilt must be 'X', 'Y', 'XY' or '', not '%s'\n",
583                progname, tilt_str);
584       exit (1);
585     }
586
587   {
588     double spin_speed   = speed * 0.2;    /* rotation of tube around axis */
589     double spin_accel   = speed * 0.1;
590     double wander_speed = speed * 0.001;  /* tilting of axis */
591
592     spin_speed   *= 0.9 + frand(0.2);
593     wander_speed *= 0.9 + frand(0.2);
594
595     ss->rot = make_rotator (spin_speed, spin_speed, spin_speed,
596                             spin_accel, wander_speed, True);
597
598     ss->trackball = gltrackball_init (False);
599   }
600
601   if (strstr ((char *) glGetString(GL_EXTENSIONS),
602               "GL_EXT_texture_filter_anisotropic"))
603     glGetFloatv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &ss->anisotropic);
604   else
605     ss->anisotropic = 0.0;
606
607   glDisable (GL_LIGHTING);
608   glEnable (GL_DEPTH_TEST);
609   glDisable (GL_CULL_FACE);
610
611   if (! wire)
612     {
613       glShadeModel (GL_SMOOTH);
614       glEnable (GL_LINE_SMOOTH);
615       /* This gives us a transparent diagonal slice through each image! */
616       /* glEnable (GL_POLYGON_SMOOTH); */
617       glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
618       glEnable (GL_BLEND);
619       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
620       glEnable (GL_ALPHA_TEST);
621
622       glEnable (GL_POLYGON_OFFSET_FILL);
623       glPolygonOffset (1.0, 1.0);
624
625     }
626
627   ss->texfont = load_texture_font (MI_DISPLAY(mi), "font");
628
629   if (debug_p)
630     hack_resources (MI_DISPLAY (mi));
631
632   ss->nframes = 0;
633   ss->frames_size = 10;
634   ss->frames = (image_frame **)
635     calloc (1, ss->frames_size * sizeof(*ss->frames));
636
637   ss->mode = IN;
638   ss->mode_tick = fade_ticks / speed;
639
640   ss->awaiting_first_images_p = True;
641 }
642
643
644 static void
645 draw_frame (ModeInfo *mi, image_frame *frame, time_t now, Bool body_p)
646 {
647   carousel_state *ss = &sss[MI_SCREEN(mi)];
648   int wire = MI_IS_WIREFRAME(mi);
649
650   GLfloat texw  = frame->current.geom.width  / (GLfloat) frame->current.tw;
651   GLfloat texh  = frame->current.geom.height / (GLfloat) frame->current.th;
652   GLfloat texx1 = frame->current.geom.x / (GLfloat) frame->current.tw;
653   GLfloat texy1 = frame->current.geom.y / (GLfloat) frame->current.th;
654   GLfloat texx2 = texx1 + texw;
655   GLfloat texy2 = texy1 + texh;
656   GLfloat aspect = ((GLfloat) frame->current.geom.height /
657                     (GLfloat) frame->current.geom.width);
658
659   glBindTexture (GL_TEXTURE_2D, frame->current.texid);
660
661   glPushMatrix();
662
663   /* Position this image on the wheel.
664    */
665   glRotatef (frame->theta, 0, 1, 0);
666   glTranslatef (0, 0, frame->r);
667
668   /* Scale down the image so that all N frames fit on the wheel
669      without bumping in to each other.
670   */
671   {
672     GLfloat t, s;
673     switch (ss->nframes)
674       {
675       case 1:  t = -1.0; s = 1.7; break;
676       case 2:  t = -0.8; s = 1.6; break;
677       case 3:  t = -0.4; s = 1.5; break;
678       case 4:  t = -0.2; s = 1.3; break;
679       default: t =  0.0; s = 6.0 / ss->nframes; break;
680       }
681     glTranslatef (0, 0, t);
682     glScalef (s, s, s);
683   }
684
685   /* Center this image on the wheel plane.
686    */
687   glTranslatef (-0.5, -(aspect/2), 0);
688
689   /* Move as per the "zoom in and out" setting.
690    */
691   if (zoom_p)
692     {
693       double x, y, z;
694       /* Only use the Z component of the rotator for in/out position. */
695       get_position (frame->rot, &x, &y, &z, !ss->button_down_p);
696       glTranslatef (0, 0, z/2);
697     }
698
699   /* Compute the "drop in and out" state.
700    */
701   switch (frame->mode)
702     {
703     case EARLY:
704       abort();
705       break;
706     case NORMAL:
707       if (!ss->button_down_p &&
708           now >= frame->expires &&
709           ss->loads_in_progress == 0)  /* only load one at a time */
710         load_image (mi, frame);
711       break;
712     case LOADING:
713       break;
714     case OUT:
715       if (--frame->mode_tick <= 0) {
716         image swap = frame->current;
717         frame->current = frame->loading;
718         frame->loading = swap;
719
720         frame->mode = IN;
721         frame->mode_tick = fade_ticks / speed;
722       }
723       break;
724     case IN:
725       if (--frame->mode_tick <= 0)
726         frame->mode = NORMAL;
727       break;
728     default:
729       abort();
730     }
731
732   /* Now translate for current in/out state.
733    */
734   if (frame->mode == OUT || frame->mode == IN)
735     {
736       GLfloat t = (frame->mode == OUT
737                    ? frame->mode_tick / (fade_ticks / speed)
738                    : (((fade_ticks / speed) - frame->mode_tick + 1) /
739                       (fade_ticks / speed)));
740       t = 5 * (1 - t);
741       if (frame->from_top_p) t = -t;
742       glTranslatef (0, t, 0);
743     }
744
745   if (body_p)                                   /* Draw the image quad. */
746     {
747       if (! wire)
748         {
749           glColor3f (1, 1, 1);
750           glNormal3f (0, 0, 1);
751           glEnable (GL_TEXTURE_2D);
752           glBegin (GL_QUADS);
753           glNormal3f (0, 0, 1);
754           glTexCoord2f (texx1, texy2); glVertex3f (0, 0, 0);
755           glTexCoord2f (texx2, texy2); glVertex3f (1, 0, 0);
756           glTexCoord2f (texx2, texy1); glVertex3f (1, aspect, 0);
757           glTexCoord2f (texx1, texy1); glVertex3f (0, aspect, 0);
758           glEnd();
759         }
760
761       /* Draw a box around it.
762        */
763       glLineWidth (2.0);
764       glColor3f (0.5, 0.5, 0.5);
765       glDisable (GL_TEXTURE_2D);
766       glBegin (GL_LINE_LOOP);
767       glVertex3f (0, 0, 0);
768       glVertex3f (1, 0, 0);
769       glVertex3f (1, aspect, 0);
770       glVertex3f (0, aspect, 0);
771       glEnd();
772
773     }
774   else                                  /* Draw a title under the image. */
775     {
776       int sw, sh;
777       GLfloat scale = 0.05;
778       char *title = frame->current.title ? frame->current.title : "(untitled)";
779       sw = texture_string_width (ss->texfont, title, &sh);
780
781       glTranslatef (0, -scale, 0);
782
783       scale /= sh;
784       glScalef (scale, scale, scale);
785
786       glTranslatef (((1/scale) - sw) / 2, 0, 0);
787       glColor3f (1, 1, 1);
788
789       if (!wire)
790         {
791           glEnable (GL_TEXTURE_2D);
792           print_texture_string (ss->texfont, title);
793         }
794       else
795         {
796           glBegin (GL_LINE_LOOP);
797           glVertex3f (0,  0,  0);
798           glVertex3f (sw, 0,  0);
799           glVertex3f (sw, sh, 0);
800           glVertex3f (0,  sh, 0);
801           glEnd();
802         }
803     }
804
805   glPopMatrix();
806 }
807
808
809 ENTRYPOINT void
810 draw_carousel (ModeInfo *mi)
811 {
812   carousel_state *ss = &sss[MI_SCREEN(mi)];
813   int i;
814
815   if (!ss->glx_context)
816     return;
817
818   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(ss->glx_context));
819
820   if (ss->awaiting_first_images_p)
821     if (!load_initial_images (mi))
822       return;
823
824   /* Only check the wall clock every 10 frames */
825   {
826     if (ss->now == 0 || ss->draw_tick++ > 10)
827       {
828         ss->now = time((time_t *) 0);
829         if (ss->last_time == 0) ss->last_time = ss->now;
830         ss->draw_tick = 0;
831       }
832   }
833
834
835   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
836
837   glPushMatrix();
838
839   glRotatef(current_device_rotation(), 0, 0, 1);
840
841
842   /* Run the startup "un-shrink" animation.
843    */
844   switch (ss->mode)
845     {
846     case IN:
847       if (--ss->mode_tick <= 0)
848         {
849           ss->mode = NORMAL;
850           ss->last_time = time((time_t *) 0);
851         }
852       break;
853     case NORMAL:
854       break;
855     default:
856       abort();
857     }
858
859
860   /* Scale as per the startup "un-shrink" animation.
861    */
862   if (ss->mode != NORMAL)
863     {
864       GLfloat s = (ss->mode == OUT
865                    ? ss->mode_tick / (fade_ticks / speed)
866                    : (((fade_ticks / speed) - ss->mode_tick + 1) /
867                       (fade_ticks / speed)));
868       glScalef (s, s, s);
869     }
870
871   /* Rotate and tilt as per the user, and the motion modeller.
872    */
873   {
874     double x, y, z;
875     gltrackball_rotate (ss->trackball);
876
877     /* Tilt the tube up or down by up to 30 degrees */
878     get_position (ss->rot, &x, &y, &z, !ss->button_down_p);
879     if (tilt_x_p)
880       glRotatef (15 - (x * 30), 1, 0, 0);
881     if (tilt_y_p)
882       glRotatef (7  - (y * 14), 0, 0, 1);
883
884     /* Only use the Y component of the rotator. */
885     get_rotation (ss->rot, &x, &y, &z, !ss->button_down_p);
886     glRotatef (y * 360, 0, 1, 0);
887   }
888
889   /* First draw each image, then draw the titles.  GL insists that you
890      draw back-to-front in order to make alpha blending work properly,
891      so we need to draw all of the 100% opaque images before drawing
892      any of the not-100%-opaque titles.
893    */
894   for (i = 0; i < ss->nframes; i++)
895     draw_frame (mi, ss->frames[i], ss->now, True);
896   if (titles_p)
897     for (i = 0; i < ss->nframes; i++)
898       draw_frame (mi, ss->frames[i], ss->now, False);
899
900   glPopMatrix();
901
902   if (mi->fps_p) do_fps (mi);
903   glFinish();
904   glXSwapBuffers (MI_DISPLAY (mi), MI_WINDOW(mi));
905 }
906
907 XSCREENSAVER_MODULE ("Carousel", carousel)
908
909 #endif /* USE_GL */