From http://www.jwz.org/xscreensaver/xscreensaver-5.16.tar.gz
[xscreensaver] / hacks / glx / stairs.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* stairs --- Infinite Stairs, and Escher-like scene. */
3
4 #if 0
5 static const char sccsid[] = "@(#)stairs.c      4.07 97/11/24 xlockmore";
6 #endif
7
8 /*-
9  * Permission to use, copy, modify, and distribute this software and its
10  * documentation for any purpose and without fee is hereby granted,
11  * provided that the above copyright notice appear in all copies and that
12  * both that copyright notice and this permission notice appear in
13  * supporting documentation.
14  *
15  * This file is provided AS IS with no warranties of any kind.  The author
16  * shall have no liability with respect to the infringement of copyrights,
17  * trade secrets or any patents by this file or any part thereof.  In no
18  * event will the author be liable for any lost revenue or profits or
19  * other special, indirect and consequential damages.
20  *
21  * This mode shows some interesting scenes that are impossible OR very
22  * weird to build in the real universe. Much of the scenes are inspirated
23  * on Mauritz Cornelis stairs's works which derivated the mode's name.
24  * M.C. Escher (1898-1972) was a dutch artist and many people prefer to
25  * say he was a mathematician.
26  *
27  * Thanks goes to Brian Paul for making it possible and inexpensive to use 
28  * OpenGL at home.
29  *
30  * Since I'm not a native English speaker, my apologies for any grammatical
31  * mistake.
32  *
33  * My e-mail address is
34  * m-vianna@usa.net
35  *
36  * Marcelo F. Vianna (Jun-01-1997)
37  *
38  * Revision History:
39  * 07-Jan-98: This would be a scene for the escher mode, but now escher mode
40  *            was splitted in different modes for each scene. This is the
41  *            initial release and is not working yet.
42  *            Marcelo F. Vianna.
43  *
44  */
45
46 /*-
47  * Texture mapping is only available on RGBA contexts, Mono and color index
48  * visuals DO NOT support texture mapping in OpenGL.
49  *
50  * BUT Mesa do implements RGBA contexts in pseudo color visuals, so texture
51  * mapping shuld work on PseudoColor, DirectColor, TrueColor using Mesa. Mono
52  * is not officially supported for both OpenGL and Mesa, but seems to not crash
53  * Mesa.
54  *
55  * In real OpenGL, PseudoColor DO NOT support texture map (as far as I know).
56  */
57
58 #ifdef STANDALONE
59 # define DEFAULTS                       "*delay:                20000   \n" \
60                                                         "*showFPS:      False   \n"
61
62 # define refresh_stairs 0
63 # include "xlockmore.h"         /* from the xscreensaver distribution */
64 #else /* !STANDALONE */
65 # include "xlock.h"                     /* from the xlockmore distribution */
66
67 #endif /* !STANDALONE */
68
69 #ifdef USE_GL
70
71 #if 0
72 #include "e_textures.h"
73 #else
74 #include "xpm-ximage.h"
75 #include "../images/wood.xpm"
76 #endif
77
78 #include "sphere.h"
79 #include "gltrackball.h"
80
81 ENTRYPOINT ModeSpecOpt stairs_opts =
82 {0, NULL, 0, NULL, NULL};
83
84 #ifdef USE_MODULES
85 ModStruct   stairs_description =
86 {"stairs", "init_stairs", "draw_stairs", "release_stairs",
87  "draw_stairs", "change_stairs", NULL, &stairs_opts,
88  1000, 1, 1, 1, 4, 1.0, "",
89  "Shows Infinite Stairs, an Escher-like scene", 0, NULL};
90
91 #endif
92
93 #define Scale4Window               0.3
94 #define Scale4Iconic               0.4
95
96 #define sqr(A)                     ((A)*(A))
97
98 #ifndef Pi
99 #define Pi                         M_PI
100 #endif
101
102 /*************************************************************************/
103
104 typedef struct {
105         GLint       WindH, WindW;
106         GLfloat     step;
107         int         rotating;
108         int         AreObjectsDefined[1];
109         int         sphere_position;
110         int         sphere_tick;
111         GLXContext *glx_context;
112     trackball_state *trackball;
113     Bool button_down_p;
114     GLuint objects;
115 } stairsstruct;
116
117 static const float front_shininess[] = {60.0};
118 static const float front_specular[] = {0.7, 0.7, 0.7, 1.0};
119 static const float ambient[] = {0.0, 0.0, 0.0, 1.0};
120 static const float diffuse[] = {1.0, 1.0, 1.0, 1.0};
121 static const float position0[] = {1.0, 1.0, 1.0, 0.0};
122 static const float position1[] = {-1.0, -1.0, 1.0, 0.0};
123 static const float lmodel_ambient[] = {0.5, 0.5, 0.5, 1.0};
124 static const float lmodel_twoside[] = {GL_TRUE};
125
126 static const float MaterialYellow[] = {0.7, 0.7, 0.0, 1.0};
127 static const float MaterialWhite[] = {0.7, 0.7, 0.7, 1.0};
128
129 static const float ball_positions[] = {
130   -3.0, 3.0, 1.0,
131   -3.0, 2.8, 2.0,
132   -3.0, 2.6, 3.0,
133
134   -2.0, 2.4, 3.0,
135   -1.0, 2.2, 3.0,
136    0.0, 2.0, 3.0,
137    1.0, 1.8, 3.0,
138    2.0, 1.6, 3.0,
139
140    2.0, 1.5, 2.0,
141    2.0, 1.4, 1.0,
142    2.0, 1.3, 0.0,
143    2.0, 1.2, -1.0,
144    2.0, 1.1, -2.0,
145
146    1.0, 0.9, -2.0,
147    0.0, 0.7, -2.0,
148   -1.0, 0.5, -2.0,
149 };
150
151 #define NPOSITIONS ((sizeof ball_positions) / (sizeof ball_positions[0]) / 3)
152 #define SPHERE_TICKS 32
153
154 static stairsstruct *stairs = NULL;
155
156 static int
157 draw_block(GLfloat width, GLfloat height, GLfloat thickness)
158 {
159     int polys = 0;
160         glFrontFace(GL_CCW);
161         glBegin(GL_QUADS);
162         glNormal3f(0, 0, 1);
163         glTexCoord2f(0, 0);
164         glVertex3f(-width, -height, thickness);
165         glTexCoord2f(1, 0);
166         glVertex3f(width, -height, thickness);
167         glTexCoord2f(1, 1);
168         glVertex3f(width, height, thickness);
169         glTexCoord2f(0, 1);
170         glVertex3f(-width, height, thickness);
171     polys++;
172         glNormal3f(0, 0, -1);
173         glTexCoord2f(0, 0);
174         glVertex3f(-width, height, -thickness);
175         glTexCoord2f(1, 0);
176         glVertex3f(width, height, -thickness);
177         glTexCoord2f(1, 1);
178         glVertex3f(width, -height, -thickness);
179         glTexCoord2f(0, 1);
180         glVertex3f(-width, -height, -thickness);
181     polys++;
182         glNormal3f(0, 1, 0);
183         glTexCoord2f(0, 0);
184         glVertex3f(-width, height, thickness);
185         glTexCoord2f(1, 0);
186         glVertex3f(width, height, thickness);
187         glTexCoord2f(1, 1);
188         glVertex3f(width, height, -thickness);
189         glTexCoord2f(0, 1);
190         glVertex3f(-width, height, -thickness);
191     polys++;
192         glNormal3f(0, -1, 0);
193         glTexCoord2f(0, 0);
194         glVertex3f(-width, -height, -thickness);
195         glTexCoord2f(1, 0);
196         glVertex3f(width, -height, -thickness);
197         glTexCoord2f(1, 1);
198         glVertex3f(width, -height, thickness);
199         glTexCoord2f(0, 1);
200         glVertex3f(-width, -height, thickness);
201     polys++;
202         glNormal3f(1, 0, 0);
203         glTexCoord2f(0, 0);
204         glVertex3f(width, -height, thickness);
205         glTexCoord2f(1, 0);
206         glVertex3f(width, -height, -thickness);
207         glTexCoord2f(1, 1);
208         glVertex3f(width, height, -thickness);
209         glTexCoord2f(0, 1);
210         glVertex3f(width, height, thickness);
211     polys++;
212         glNormal3f(-1, 0, 0);
213         glTexCoord2f(0, 0);
214         glVertex3f(-width, height, thickness);
215         glTexCoord2f(1, 0);
216         glVertex3f(-width, height, -thickness);
217         glTexCoord2f(1, 1);
218         glVertex3f(-width, -height, -thickness);
219         glTexCoord2f(0, 1);
220         glVertex3f(-width, -height, thickness);
221     polys++;
222         glEnd();
223     return polys;
224 }
225
226 static void
227 draw_stairs_internal(ModeInfo * mi)
228 {
229         GLfloat     X;
230
231     mi->polygon_count = 0;
232
233         glPushMatrix();
234         glPushMatrix();
235         glTranslatef(-3.0, 0.1, 2.0);
236         for (X = 0; X < 2; X++) {
237         mi->polygon_count += draw_block(0.5, 2.7 + 0.1 * X, 0.5);
238                 glTranslatef(0.0, 0.1, -1.0);
239         }
240         glPopMatrix();
241         glTranslatef(-3.0, 0.0, 3.0);
242         glPushMatrix();
243
244         for (X = 0; X < 6; X++) {
245                 mi->polygon_count += draw_block(0.5, 2.6 - 0.1 * X, 0.5);
246                 glTranslatef(1.0, -0.1, 0.0);
247         }
248         glTranslatef(-1.0, -0.9, -1.0);
249         for (X = 0; X < 5; X++) {
250                 mi->polygon_count += draw_block(0.5, 3.0 - 0.1 * X, 0.5);
251                 glTranslatef(0.0, 0.0, -1.0);
252         }
253         glTranslatef(-1.0, -1.1, 1.0);
254         for (X = 0; X < 3; X++) {
255                 mi->polygon_count += draw_block(0.5, 3.5 - 0.1 * X, 0.5);
256                 glTranslatef(-1.0, -0.1, 0.0);
257         }
258         glPopMatrix();
259         glPopMatrix();
260 }
261
262 /*#define DEBUG*/
263 /*#define DEBUG_PATH*/
264
265 static int
266 draw_sphere(int pos, int tick)
267 {
268     int pos2 = (pos+1) % NPOSITIONS;
269     GLfloat x1 = ball_positions[pos*3];
270     GLfloat y1 = ball_positions[pos*3+1];
271     GLfloat z1 = ball_positions[pos*3+2];
272     GLfloat x2 = ball_positions[pos2*3];
273     GLfloat y2 = ball_positions[pos2*3+1];
274     GLfloat z2 = ball_positions[pos2*3+2];
275     GLfloat frac = tick / (GLfloat) SPHERE_TICKS;
276     GLfloat x = x1 + (x2 - x1) * frac;
277     GLfloat y = y1 + (y2 - y1) * frac + (2 * sin (M_PI * frac));
278     GLfloat z = z1 + (z2 - z1) * frac;
279     int polys = 0;
280
281         glPushMatrix();
282
283 # ifdef DEBUG_PATH
284     glVertex3f(x, y, z);
285     if (tick == 0) {
286       glVertex3f(x, y-7.5, z);
287       glVertex3f(x, y, z); glVertex3f(x, y, z-0.6);
288       glVertex3f(x, y, z); glVertex3f(x, y, z+0.6);
289       glVertex3f(x, y, z); glVertex3f(x+0.6, y, z);
290       glVertex3f(x, y, z); glVertex3f(x-0.6, y, z);
291       glVertex3f(x, y, z);
292     }
293
294 # else /* !DEBUG_PATH */
295     y += 0.5;
296     glTranslatef(x, y, z);
297
298     glScalef (0.5, 0.5, 0.5);
299
300     /* make ball a little smaller on the gap to obscure distance */
301         if (pos == NPOSITIONS-1)
302       glScalef (0.95, 0.95, 0.95);
303
304         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialYellow);
305     glDisable (GL_TEXTURE_2D);
306         glShadeModel(GL_SMOOTH);
307         glFrontFace(GL_CCW);
308     polys += unit_sphere (32, 32, False);
309         glShadeModel(GL_FLAT);
310     glEnable (GL_TEXTURE_2D);
311 #endif /* !DEBUG_PATH */
312
313         glPopMatrix();
314     return polys;
315 }
316
317
318
319 ENTRYPOINT void
320 reshape_stairs (ModeInfo * mi, int width, int height)
321 {
322         stairsstruct *sp = &stairs[MI_SCREEN(mi)];
323
324         glViewport(0, 0, sp->WindW = (GLint) width, sp->WindH = (GLint) height);
325         glMatrixMode(GL_PROJECTION);
326         glLoadIdentity();
327         glFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 15.0);
328         glMatrixMode(GL_MODELVIEW);
329         if (width >= 1024) {
330                 glLineWidth(3);
331                 glPointSize(3);
332         } else if (width >= 512) {
333                 glLineWidth(2);
334                 glPointSize(2);
335         } else {
336                 glLineWidth(1);
337                 glPointSize(1);
338         }
339 }
340
341 ENTRYPOINT Bool
342 stairs_handle_event (ModeInfo *mi, XEvent *event)
343 {
344   stairsstruct *sp = &stairs[MI_SCREEN(mi)];
345
346   if (event->xany.type == ButtonPress &&
347       event->xbutton.button == Button1)
348     {
349       sp->button_down_p = True;
350       gltrackball_start (sp->trackball,
351                          event->xbutton.x, event->xbutton.y,
352                          MI_WIDTH (mi), MI_HEIGHT (mi));
353       return True;
354     }
355   else if (event->xany.type == ButtonRelease &&
356            event->xbutton.button == Button1)
357     {
358       sp->button_down_p = False;
359       return True;
360     }
361   else if (event->xany.type == ButtonPress &&
362            (event->xbutton.button == Button4 ||
363             event->xbutton.button == Button5 ||
364             event->xbutton.button == Button6 ||
365             event->xbutton.button == Button7))
366     {
367       gltrackball_mousewheel (sp->trackball, event->xbutton.button, 10,
368                               !!event->xbutton.state);
369       return True;
370     }
371   else if (event->xany.type == MotionNotify &&
372            sp->button_down_p)
373     {
374       gltrackball_track (sp->trackball,
375                          event->xmotion.x, event->xmotion.y,
376                          MI_WIDTH (mi), MI_HEIGHT (mi));
377       return True;
378     }
379   else if (event->xany.type == KeyPress)
380     {
381       KeySym keysym;
382       char c = 0;
383       XLookupString (&event->xkey, &c, 1, &keysym, 0);
384       if (c == ' ')
385         {
386           gltrackball_reset (sp->trackball);
387           return True;
388         }
389     }
390
391   return False;
392 }
393
394
395 static void
396 pinit(ModeInfo *mi)
397 {
398   /* int status; */
399         glClearDepth(1.0);
400         glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
401         glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
402         glLightfv(GL_LIGHT0, GL_POSITION, position0);
403         glLightfv(GL_LIGHT1, GL_AMBIENT, ambient);
404         glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse);
405         glLightfv(GL_LIGHT1, GL_POSITION, position1);
406         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
407         glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
408         glEnable(GL_LIGHTING);
409         glEnable(GL_LIGHT0);
410         glEnable(GL_LIGHT1);
411         glEnable(GL_NORMALIZE);
412         glCullFace(GL_BACK);
413
414         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialWhite);
415         glShadeModel(GL_FLAT);
416         glEnable(GL_DEPTH_TEST);
417         glEnable(GL_TEXTURE_2D);
418         glEnable(GL_CULL_FACE);
419
420         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
421
422 #if 0
423     clear_gl_error();
424     status = gluBuild2DMipmaps(GL_TEXTURE_2D, 3,
425                                WoodTextureWidth, WoodTextureHeight,
426                                GL_RGB, GL_UNSIGNED_BYTE, WoodTextureData);
427     if (status)
428       {
429         const char *s = (char *) gluErrorString (status);
430         fprintf (stderr, "%s: error mipmapping %dx%d texture: %s\n",
431                  progname, WoodTextureWidth, WoodTextureHeight,
432                  (s ? s : "(unknown)"));
433         exit (1);
434       }
435     check_gl_error("mipmapping");
436 #else
437     {
438       XImage *img = xpm_to_ximage (mi->dpy,
439                                    mi->xgwa.visual,
440                                    mi->xgwa.colormap,
441                                    wood_texture);
442           glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA,
443                     img->width, img->height, 0,
444                     GL_RGBA,
445                     /* GL_UNSIGNED_BYTE, */
446                     GL_UNSIGNED_INT_8_8_8_8_REV,
447                     img->data);
448       check_gl_error("texture");
449       XDestroyImage (img);
450     }
451 #endif
452
453         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
454         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
455         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
456         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
457         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
458
459         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_shininess);
460         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_specular);
461 }
462
463 ENTRYPOINT void
464 init_stairs (ModeInfo * mi)
465 {
466         int         screen = MI_SCREEN(mi);
467         stairsstruct *sp;
468
469         if (stairs == NULL) {
470                 if ((stairs = (stairsstruct *) calloc(MI_NUM_SCREENS(mi),
471                                              sizeof (stairsstruct))) == NULL)
472                         return;
473         }
474         sp = &stairs[screen];
475
476         sp->step = 0.0;
477         sp->rotating = 0;
478         sp->sphere_position = NRAND(NPOSITIONS);
479         sp->sphere_tick = 0;
480
481         if ((sp->glx_context = init_GL(mi)) != NULL) {
482
483                 reshape_stairs(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
484                 glDrawBuffer(GL_BACK);
485                 if (!glIsList(sp->objects))
486                         sp->objects = glGenLists(1);
487                 pinit(mi);
488         } else {
489                 MI_CLEARWINDOW(mi);
490         }
491
492     sp->trackball = gltrackball_init ();
493 }
494
495 ENTRYPOINT void
496 draw_stairs (ModeInfo * mi)
497 {
498         stairsstruct *sp = &stairs[MI_SCREEN(mi)];
499
500         Display    *display = MI_DISPLAY(mi);
501         Window      window = MI_WINDOW(mi);
502
503         if (!sp->glx_context)
504                 return;
505
506         glXMakeCurrent(display, window, *(sp->glx_context));
507
508         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
509
510         glPushMatrix();
511
512         glTranslatef(0.0, 0.0, -10.0);
513
514         if (!MI_IS_ICONIC(mi)) {
515                 glScalef(Scale4Window * sp->WindH / sp->WindW, Scale4Window, Scale4Window);
516         } else {
517                 glScalef(Scale4Iconic * sp->WindH / sp->WindW, Scale4Iconic, Scale4Iconic);
518         }
519
520     gltrackball_rotate (sp->trackball);
521     glRotatef(current_device_rotation(), 0, 0, 1);
522
523     glTranslatef(0, 0.5, 0);
524         glRotatef(44.5, 1, 0, 0);
525     glRotatef(50, 0, 1, 0);
526
527     if (!sp->rotating) {
528       if ((LRAND() % 500) == 0)
529         sp->rotating = (LRAND() & 1) ? 1 : -1;
530     }
531
532     if (sp->rotating) {
533       glRotatef(sp->rotating * sp->step, 0, 1, 0);
534       if (sp->step >= 360) {
535         sp->rotating = 0;
536                 sp->step = 0;
537       }
538
539 # ifndef DEBUG
540       if (!sp->button_down_p)
541         sp->step += 2;
542 # endif /* DEBUG */
543     }
544
545         draw_stairs_internal(mi);
546
547
548 # ifdef DEBUG
549     {
550       int i, j;
551 #  ifdef DEBUG_PATH
552       glDisable(GL_LIGHTING);
553       glDisable(GL_TEXTURE_2D);
554       glBegin (GL_LINE_LOOP);
555 #  endif /* DEBUG_PATH */
556       for (i = 0; i < NPOSITIONS; i ++)
557         for (j = 0; j < SPHERE_TICKS; j++)
558           mi->polygon_count += draw_sphere(i, j);
559 #  ifdef DEBUG_PATH
560       glEnd();
561       glEnable(GL_LIGHTING);
562       glEnable(GL_TEXTURE_2D);
563 #  endif /* DEBUG_PATH */
564     }
565 #else  /* !DEBUG */
566     mi->polygon_count += draw_sphere(sp->sphere_position, sp->sphere_tick);
567 #endif /* !DEBUG */
568
569     if (sp->button_down_p)
570       ;
571     else if (++sp->sphere_tick >= SPHERE_TICKS)
572       {
573         sp->sphere_tick = 0;
574         if (++sp->sphere_position >= NPOSITIONS)
575           sp->sphere_position = 0;
576       }
577
578         glPopMatrix();
579
580     if (mi->fps_p) do_fps (mi);
581         glFlush();
582
583         glXSwapBuffers(display, window);
584 }
585
586 #ifndef STANDALONE
587 ENTRYPOINT void
588 change_stairs (ModeInfo * mi)
589 {
590         stairsstruct *sp = &stairs[MI_SCREEN(mi)];
591
592         if (!sp->glx_context)
593                 return;
594
595         glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(sp->glx_context));
596         pinit();
597 }
598 #endif /* !STANDALONE */
599
600 ENTRYPOINT void
601 release_stairs (ModeInfo * mi)
602 {
603         if (stairs != NULL) {
604       int i;
605       for (i = 0; i < MI_NUM_SCREENS(mi); i++) {
606         stairsstruct *sp = &stairs[i];
607         if (glIsList(sp->objects)) {
608           glDeleteLists(sp->objects, 1);
609         }
610       }
611       free(stairs);
612       stairs = NULL;
613         }
614         FreeAllGL(mi);
615 }
616
617 XSCREENSAVER_MODULE ("Stairs", stairs)
618
619 #endif