ftp://ftp.linux.ncsu.edu/mirror/ftp.redhat.com/pub/redhat/linux/enterprise/4/en/os...
[xscreensaver] / hacks / glx / bouncingcow.c
1 /* bouncingcow, Copyright (c) 2003, 2004 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  * Boing, boing, boing.  Cow, cow, cow.
12  */
13
14 #include <X11/Intrinsic.h>
15
16 extern XtAppContext app;
17
18 #define PROGCLASS       "BouncingCow"
19 #define HACK_INIT       init_cow
20 #define HACK_DRAW       draw_cows
21 #define HACK_RESHAPE    reshape_cow
22 #define HACK_HANDLE_EVENT cow_handle_event
23 #define EVENT_MASK      PointerMotionMask
24 #define sws_opts        xlockmore_opts
25
26 #define DEF_SPEED       "0.7"
27 #define DEF_TEXTURE     "(none)"
28
29 #define DEFAULTS        "*delay:        30000       \n" \
30                         "*count:        1           \n" \
31                         "*showFPS:      False       \n" \
32                         "*wireframe:    False       \n" \
33                         "*speed:      " DEF_SPEED " \n" \
34                         "*texture:    " DEF_TEXTURE   "\n" \
35
36 /* #define DEBUG */
37
38 #undef countof
39 #define countof(x) (sizeof((x))/sizeof((*x)))
40
41 #undef BELLRAND
42 #define BELLRAND(n) ((frand((n)) + frand((n)) + frand((n))) / 3)
43 #undef RANDSIGN
44 #define RANDSIGN() ((random() & 1) ? 1 : -1)
45
46 #include "xlockmore.h"
47 #include "rotator.h"
48 #include "gltrackball.h"
49 #include "xpm-ximage.h"
50 #include <ctype.h>
51
52 #ifdef USE_GL /* whole file */
53
54 #include <GL/glu.h>
55
56
57 #include "gllist.h"
58
59 extern struct gllist
60  *cow_face, *cow_hide, *cow_hoofs, *cow_horns, *cow_tail, *cow_udder;
61
62 struct gllist **all_objs[] = {
63  &cow_face, &cow_hide, &cow_hoofs, &cow_horns, &cow_tail, &cow_udder
64 };
65
66 #define FACE    0
67 #define HIDE    1
68 #define HOOFS   2
69 #define HORNS   3
70 #define TAIL    4
71 #define UDDER   5
72
73 typedef struct {
74   GLfloat x, y, z;
75   GLfloat ix, iy, iz;
76   GLfloat dx, dy, dz;
77   GLfloat ddx, ddy, ddz;
78   rotator *rot;
79   Bool spinner_p;
80 } floater;
81
82 typedef struct {
83   GLXContext *glx_context;
84   trackball_state *trackball;
85   Bool button_down_p;
86
87   GLuint *dlists;
88   GLuint texture;
89
90   int nfloaters;
91   floater *floaters;
92
93 } cow_configuration;
94
95 static cow_configuration *bps = NULL;
96
97 static GLfloat speed;
98 static const char *do_texture;
99
100 static XrmOptionDescRec opts[] = {
101   { "-speed",      ".speed",     XrmoptionSepArg, 0 },
102   {"-texture",     ".texture",   XrmoptionSepArg, 0 },
103   {"+texture",     ".texture",   XrmoptionNoArg, "(none)" },
104 };
105
106 static argtype vars[] = {
107   {&speed,      "speed",      "Speed",   DEF_SPEED,     t_Float},
108   {&do_texture, "texture",    "Texture", DEF_TEXTURE,   t_String},
109 };
110
111 ModeSpecOpt sws_opts = {countof(opts), opts, countof(vars), vars, NULL};
112
113
114 #define BOTTOM 28.0
115
116 static void
117 reset_floater (ModeInfo *mi, floater *f)
118 {
119   cow_configuration *bp = &bps[MI_SCREEN(mi)];
120
121   f->y = -BOTTOM;
122   f->x = f->ix;
123   f->z = f->iz;
124
125   /* Yes, I know I'm varying the force of gravity instead of varying the
126      launch velocity.  That's intentional: empirical studies indicate
127      that it's way, way funnier that way. */
128
129   f->dy = 5.0;
130   f->dx = 0;
131   f->dz = 0;
132
133   /* -0.18 max  -0.3 top -0.4 middle  -0.6 bottom */
134   f->ddy = speed * (-0.6 + BELLRAND(0.45));
135   f->ddx = 0;
136   f->ddz = 0;
137
138   f->spinner_p = !(random() % (12 * bp->nfloaters));
139
140   if (! (random() % (30 * bp->nfloaters)))
141     {
142       f->dx = BELLRAND(1.8) * RANDSIGN();
143       f->dz = BELLRAND(1.8) * RANDSIGN();
144     }
145 }
146
147
148 static void
149 tick_floater (ModeInfo *mi, floater *f)
150 {
151   cow_configuration *bp = &bps[MI_SCREEN(mi)];
152
153   if (bp->button_down_p) return;
154
155   f->dx += f->ddx;
156   f->dy += f->ddy;
157   f->dz += f->ddz;
158
159   f->x += f->dx * speed;
160   f->y += f->dy * speed;
161   f->z += f->dz * speed;
162
163   if (f->y < -BOTTOM ||
164       f->x < -BOTTOM*8 || f->x > BOTTOM*8 ||
165       f->z < -BOTTOM*8 || f->z > BOTTOM*8)
166     reset_floater (mi, f);
167 }
168
169
170 /* Window management, etc
171  */
172 void
173 reshape_cow (ModeInfo *mi, int width, int height)
174 {
175   GLfloat h = (GLfloat) height / (GLfloat) width;
176
177   glViewport (0, 0, (GLint) width, (GLint) height);
178
179   glMatrixMode(GL_PROJECTION);
180   glLoadIdentity();
181   gluPerspective (30.0, 1/h, 1.0, 100);
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   glClear(GL_COLOR_BUFFER_BIT);
190 }
191
192
193 Bool
194 cow_handle_event (ModeInfo *mi, XEvent *event)
195 {
196   cow_configuration *bp = &bps[MI_SCREEN(mi)];
197
198   if (event->xany.type == ButtonPress &&
199       event->xbutton.button & Button1)
200     {
201       bp->button_down_p = True;
202       gltrackball_start (bp->trackball,
203                          event->xbutton.x, event->xbutton.y,
204                          MI_WIDTH (mi), MI_HEIGHT (mi));
205       return True;
206     }
207   else if (event->xany.type == ButtonRelease &&
208            event->xbutton.button & Button1)
209     {
210       bp->button_down_p = False;
211       return True;
212     }
213   else if (event->xany.type == MotionNotify &&
214            bp->button_down_p)
215     {
216       gltrackball_track (bp->trackball,
217                          event->xmotion.x, event->xmotion.y,
218                          MI_WIDTH (mi), MI_HEIGHT (mi));
219       return True;
220     }
221
222   return False;
223 }
224
225
226 /* Textures
227  */
228
229 static Bool
230 load_texture (ModeInfo *mi, const char *filename)
231 {
232   Display *dpy = mi->dpy;
233   Visual *visual = mi->xgwa.visual;
234   Colormap cmap = mi->xgwa.colormap;
235   char buf[1024];
236   XImage *image;
237
238   if (MI_IS_WIREFRAME(mi))
239     return False;
240
241   if (!filename ||
242       !*filename ||
243       !strcasecmp (filename, "(none)"))
244     {
245       glDisable (GL_TEXTURE_2D);
246       return False;
247     }
248
249   image = xpm_file_to_ximage (dpy, visual, cmap, filename);
250
251   clear_gl_error();
252   glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA,
253                 image->width, image->height, 0,
254                 GL_RGBA,
255                 /* GL_UNSIGNED_BYTE, */
256                 GL_UNSIGNED_INT_8_8_8_8_REV,
257                 image->data);
258   sprintf (buf, "texture: %.100s (%dx%d)",
259            filename, image->width, image->height);
260   check_gl_error(buf);
261
262   glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
263   glPixelStorei (GL_UNPACK_ROW_LENGTH, image->width);
264   glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
265   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
266   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
267   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
268   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
269
270   glEnable(GL_TEXTURE_GEN_S);
271   glEnable(GL_TEXTURE_GEN_T);
272   glEnable(GL_TEXTURE_2D);
273   return True;
274 }
275
276
277 void
278 init_cow (ModeInfo *mi)
279 {
280   cow_configuration *bp;
281   int wire = MI_IS_WIREFRAME(mi);
282   int i;
283
284   if (!bps) {
285     bps = (cow_configuration *)
286       calloc (MI_NUM_SCREENS(mi), sizeof (cow_configuration));
287     if (!bps) {
288       fprintf(stderr, "%s: out of memory\n", progname);
289       exit(1);
290     }
291
292     bp = &bps[MI_SCREEN(mi)];
293   }
294
295   bp = &bps[MI_SCREEN(mi)];
296
297   bp->glx_context = init_GL(mi);
298
299   reshape_cow (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
300
301   glShadeModel(GL_SMOOTH);
302
303   glEnable(GL_DEPTH_TEST);
304   glEnable(GL_NORMALIZE);
305   glEnable(GL_CULL_FACE);
306
307   if (!wire)
308     {
309       GLfloat pos[4] = {0.4, 0.2, 0.4, 0.0};
310 /*      GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};*/
311       GLfloat amb[4] = {0.2, 0.2, 0.2, 1.0};
312       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
313       GLfloat spc[4] = {1.0, 1.0, 1.0, 1.0};
314
315       glEnable(GL_LIGHTING);
316       glEnable(GL_LIGHT0);
317       glEnable(GL_DEPTH_TEST);
318       glEnable(GL_CULL_FACE);
319
320       glLightfv(GL_LIGHT0, GL_POSITION, pos);
321       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
322       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
323       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
324     }
325
326   bp->trackball = gltrackball_init ();
327
328   bp->dlists = (GLuint *) calloc (countof(all_objs)+1, sizeof(GLuint));
329   for (i = 0; i < countof(all_objs); i++)
330     bp->dlists[i] = glGenLists (1);
331
332   for (i = 0; i < countof(all_objs); i++)
333     {
334       GLfloat black[4] = {0, 0, 0, 1};
335       struct gllist *gll = *all_objs[i];
336       if (wire)
337         gll->primitive = GL_LINE_LOOP;
338
339       glNewList (bp->dlists[i], GL_COMPILE);
340
341       glMatrixMode(GL_MODELVIEW);
342       glPushMatrix();
343       glMatrixMode(GL_TEXTURE);
344       glPushMatrix();
345       glMatrixMode(GL_MODELVIEW);
346
347       glBindTexture (GL_TEXTURE_2D, 0);
348
349       if (i == HIDE)
350         {
351           GLfloat color[4] = {0.63, 0.43, 0.36, 1.00};
352
353           if (load_texture (mi, do_texture))
354             {
355               glBindTexture (GL_TEXTURE_2D, bp->texture);
356               glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
357               glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
358               glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
359
360               /* approximately line it up with ../images/earth.xpm */
361               glMatrixMode(GL_TEXTURE);
362               glTranslatef(0.45, 0.58, 0);
363               glScalef(0.08, 0.16, 1);
364               glRotatef(-5, 0, 0, 1);
365               glMatrixMode(GL_MODELVIEW);
366
367               /* if we have a texture, make the base color be white. */
368               color[0] = color[1] = color[2] = 1.0;
369             }
370
371           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
372           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            black);
373           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           128);
374         }
375       else if (i == TAIL)
376         {
377           GLfloat color[4] = {0.63, 0.43, 0.36, 1.00};
378           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
379           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            black);
380           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           128);
381         }
382       else if (i == UDDER)
383         {
384           GLfloat color[4] = {1.00, 0.53, 0.53, 1.00};
385           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
386           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            black);
387           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           128);
388         }
389       else if (i == HOOFS || i == HORNS)
390         {
391           GLfloat color[4] = {0.20, 0.20, 0.20, 1.00};
392           GLfloat spec[4]  = {0.30, 0.30, 0.30, 1.00};
393           GLfloat shiny    = 8.0;
394           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
395           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            spec);
396           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           shiny);
397         }
398       else if (i == FACE)
399         {
400           GLfloat color[4] = {0.10, 0.10, 0.10, 1.00};
401           GLfloat spec[4]  = {0.10, 0.10, 0.10, 1.00};
402           GLfloat shiny    = 8.0;
403           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
404           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            spec);
405           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           shiny);
406         }
407       else
408         {
409           GLfloat color[4] = {1.00, 1.00, 1.00, 1.00};
410           GLfloat spec[4]  = {1.00, 1.00, 1.00, 1.00};
411           GLfloat shiny    = 128.0;
412           glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
413           glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR,            spec);
414           glMaterialf  (GL_FRONT_AND_BACK, GL_SHININESS,           shiny);
415         }
416
417       renderList (gll);
418
419       glMatrixMode(GL_TEXTURE);
420       glPopMatrix();
421       glMatrixMode(GL_MODELVIEW);
422       glPopMatrix();
423
424       glEndList ();
425     }
426
427   bp->nfloaters = MI_COUNT (mi);
428   bp->floaters = (floater *) calloc (bp->nfloaters, sizeof (floater));
429
430   for (i = 0; i < bp->nfloaters; i++)
431     {
432       floater *f = &bp->floaters[i];
433       f->rot = make_rotator (10.0, 0, 0,
434                              4, 0.05 * speed,
435                              True);
436       if (bp->nfloaters == 2)
437         {
438           f->x = (i ? 6 : -6);
439         }
440       else if (i != 0)
441         {
442           double th = (i - 1) * M_PI*2 / (bp->nfloaters-1);
443           double r = 10;
444           f->x = r * cos(th);
445           f->z = r * sin(th);
446         }
447
448       f->ix = f->x;
449       f->iy = f->y;
450       f->iz = f->z;
451       reset_floater (mi, f);
452     }
453 }
454
455
456 static void
457 draw_floater (ModeInfo *mi, floater *f)
458 {
459   cow_configuration *bp = &bps[MI_SCREEN(mi)];
460   GLfloat n;
461   double x, y, z;
462
463   get_position (f->rot, &x, &y, &z, !bp->button_down_p);
464
465   glPushMatrix();
466   glTranslatef (f->x, f->y, f->z);
467
468   glRotatef (y * 360, 0.0, 1.0, 0.0);
469   if (f->spinner_p)
470     {
471       glRotatef (x * 360, 1.0, 0.0, 0.0);
472       glRotatef (z * 360, 0.0, 0.0, 1.0);
473     }
474
475   n = 1.5;
476   if      (bp->nfloaters > 99) n *= 0.05;
477   else if (bp->nfloaters > 25) n *= 0.18;
478   else if (bp->nfloaters > 9)  n *= 0.3;
479   else if (bp->nfloaters > 1)  n *= 0.7;
480   glScalef(n, n, n);
481
482   glCallList (bp->dlists[FACE]);
483   mi->polygon_count += (*all_objs[FACE])->points / 3;
484
485   glCallList (bp->dlists[HIDE]);
486   mi->polygon_count += (*all_objs[HIDE])->points / 3;
487
488   glCallList (bp->dlists[HOOFS]);
489   mi->polygon_count += (*all_objs[HOOFS])->points / 3;
490
491   glCallList (bp->dlists[HORNS]);
492   mi->polygon_count += (*all_objs[HORNS])->points / 3;
493
494   glCallList (bp->dlists[TAIL]);
495   mi->polygon_count += (*all_objs[TAIL])->points / 3;
496
497   glCallList (bp->dlists[UDDER]);
498   mi->polygon_count += (*all_objs[UDDER])->points / 3;
499
500   glPopMatrix();
501 }
502
503
504
505 void
506 draw_cows (ModeInfo *mi)
507 {
508   cow_configuration *bp = &bps[MI_SCREEN(mi)];
509   Display *dpy = MI_DISPLAY(mi);
510   Window window = MI_WINDOW(mi);
511   int i;
512
513   if (!bp->glx_context)
514     return;
515
516   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
517
518   glPushMatrix ();
519   gltrackball_rotate (bp->trackball);
520
521   glScalef (0.5, 0.5, 0.5);
522
523   mi->polygon_count = 0;
524
525 # if 0
526   {
527     floater F;
528     F.x = F.y = F.z = 0;
529     F.dx = F.dy = F.dz = 0;
530     F.ddx = F.ddy = F.ddz = 0;
531     F.rot = make_rotator (0, 0, 0, 1, 0, False);
532     glScalef(2,2,2);
533     draw_floater (mi, &F);
534   }
535 # else
536   for (i = 0; i < bp->nfloaters; i++)
537     {
538       /* "Don't kid yourself, Jimmy.  If a cow ever got the chance,
539          he'd eat you and everyone you care about!"
540              -- Troy McClure in "Meat and You: Partners in Freedom"
541        */
542       floater *f = &bp->floaters[i];
543       draw_floater (mi, f);
544       tick_floater (mi, f);
545     }
546 # endif
547
548   glPopMatrix ();
549
550   if (mi->fps_p) do_fps (mi);
551   glFinish();
552
553   glXSwapBuffers(dpy, window);
554 }
555
556 #endif /* USE_GL */