ftp://ftp.krokus.ru/pub/OpenBSD/distfiles/xscreensaver-5.01.tar.gz
[xscreensaver] / hacks / ripples.c
1 /* ripples, Copyright (c) 1999 Ian McConnell <ian@emit.demon.co.uk>
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 /*
13  * "Water" ripples that can cross and interfere with each other.
14  *
15  * I can't remember where I got this idea from, but it's been around for a
16  * while in various demos. Some inspiration from
17  *      water.txt by Tom Hammersley,tomh@globalnet.co.uk
18  *
19  * Options
20  * -delay       usleep every iteration
21  * -rate        Add one drop every "rate" iterations
22  * -box         Add big square splash every "box" iters (not very good)
23  * -water       Ripples on a grabbed background image
24  * -foreground  Interpolate ripples between these two colors
25  * -background
26  * -oily        Psychedelic colours like man
27  * -stir        Add a regular pattern of drops
28  * -fluidity    Between 0 and 16. 16 = big drops
29  * -light       Hack to add lighting effect
30  *
31  * Code mainly hacked from xflame and decayscreen.
32  */
33
34 /* Version history:
35  * 13 Oct 1999: Initial hack
36  * 30 Oct 1999: Speeded up graphics with dirty buffer. Returned to using
37  *              putpixel for greater portability
38  *              Added a variety of methods for splashing screen.
39  * 31 Oct 1999: Added in lighting hack
40  * 13 Nov 1999: Speed up tweaks
41  *              Adjust "light" for different bits per colour (-water only)
42  *
43  */
44
45 #include <math.h>
46 #include "screenhack.h"
47
48 typedef enum {ripple_drop, ripple_blob, ripple_box, ripple_stir} ripple_mode;
49
50 #ifdef HAVE_XSHM_EXTENSION
51 #include "xshm.h"
52 #endif /* HAVE_XSHM_EXTENSION */
53
54 #define TABLE 256
55
56 struct state {
57   Display *dpy;
58   Window window;
59   GC gc;
60   Visual *visual;
61
62   XImage *orig_map, *buffer_map;
63   int ctab[256];
64   Colormap colormap;
65   int ncolors;
66   int light;
67
68   int width, height; /* ripple size */
69   int bigwidth, bigheight; /* screen size */
70
71   Bool transparent;
72   short *bufferA, *bufferB, *temp;
73   char *dirty_buffer;
74
75   double cos_tab[TABLE];
76
77   Bool grayscale_p;
78
79   unsigned long rmask;  /* This builds on the warp effect by adding */
80   unsigned long gmask;  /* in a lighting effect: brighten pixels by an */
81   unsigned long bmask;  /* amount corresponding to the vertical gradient */
82
83   int rshift;
84   int gshift;
85   int bshift;
86
87   double stir_ang;
88
89   int draw_toggle;
90   int draw_count;
91
92   int iterations, delay, rate, box, oily, stir, fluidity;
93
94   void (*draw_transparent) (struct state *st, short *src);
95
96   async_load_state *img_loader;
97
98 #ifdef HAVE_XSHM_EXTENSION
99   Bool use_shm;
100   XShmSegmentInfo shm_info;
101 #endif /* HAVE_XSHM_EXTENSION */
102 };
103
104
105 /* Distribution of drops: many little ones and a few big ones. */
106 static const double drop_dist[] =
107   {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.6};
108
109
110 /* How hard to hit the water */
111 #define SPLASH 512
112 #undef  MIN
113 #define MIN(x, y) ((x) < (y) ? (x) : (y))
114 #undef  MAX
115 #define MAX(x, y) ((x) > (y) ? (x) : (y))
116 #undef  DIRTY
117 #define DIRTY 3 /* dirty >= 2, 1 = restore original pixel, 0 = leave alone */
118
119 /* From fortune(6) */
120 /* -- really weird C code to count the number of bits in a word */
121 #define BITCOUNT(x)     (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
122 #define BX_(x)          ((x) - (((x)>>1)&0x77777777) \
123                              - (((x)>>2)&0x33333333) \
124                              - (((x)>>3)&0x11111111))
125
126
127 static unsigned long grayscale(struct state *st, unsigned long color);
128
129 /*      -------------------------------------------             */
130
131
132 static int
133 map_color(struct state *st, int grey)
134 {
135   /* Clip it */
136   grey = st->ncolors * abs(grey) / (SPLASH/4);
137   if (grey > st->ncolors)
138     grey = st->ncolors;
139
140   /* Display it */
141   return st->ctab[grey];
142 }
143
144
145 static void
146 draw_ripple(struct state *st, short *src)
147 {
148   int across, down;
149   char *dirty = st->dirty_buffer;
150
151   for (down = 0; down < st->height - 1; down++, src += 1, dirty += 1)
152     for (across = 0; across < st->width - 1; across++, src++, dirty++) {
153       int v1, v2, v3, v4;
154       v1 = (int)*src;
155       v2 = (int)*(src + 1);
156       v3 = (int)*(src + st->width);
157       v4 = (int)*(src + st->width + 1);
158       if ((v1 == 0 && v2 == 0 && v3 == 0 && v4 == 0)) {
159         if (*dirty > 0)
160           (*dirty)--;
161       } else
162         *dirty = DIRTY;
163
164       if (*dirty > 0) {
165         int dx;
166         if (st->light > 0) {
167           dx = ((v3 - v1) + (v4 - v2)) << st->light; /* light from top */
168         } else
169           dx = 0;
170         XPutPixel(st->buffer_map,(across<<1),  (down<<1),  map_color(st, dx + v1));
171         XPutPixel(st->buffer_map,(across<<1)+1,(down<<1),  map_color(st, dx + ((v1 + v2) >> 1)));
172         XPutPixel(st->buffer_map,(across<<1),  (down<<1)+1,map_color(st, dx + ((v1 + v3) >> 1)));
173         XPutPixel(st->buffer_map,(across<<1)+1,(down<<1)+1,map_color(st, dx + ((v1 + v4) >> 1)));
174       }
175     }
176 }
177
178
179 /*      -------------------------------------------             */
180
181
182 /* Uses the horizontal gradient as an offset to create a warp effect  */
183 static void
184 draw_transparent_vanilla(struct state *st, short *src)
185 {
186   int across, down, pixel;
187   char *dirty = st->dirty_buffer;
188
189   pixel = 0;
190   for (down = 0; down < st->height - 2; down++, pixel += 2)
191     for (across = 0; across < st->width-2; across++, pixel++) {
192       int gradx, grady, gradx1, grady1;
193       int x0, x1, x2, y1, y2;
194
195       x0 = src[pixel];
196       x1 = src[pixel + 1];
197       x2 = src[pixel + 2];
198       y1 = src[pixel + st->width];
199       y2 = src[pixel + 2*st->width];
200
201       gradx = (x1 - x0);
202       grady = (y1 - x0);
203       gradx1= (x2 - x1);
204       grady1= (y2 - y1);
205       gradx1 = 1 + (gradx + gradx1) / 2;
206       grady1 = 1 + (grady + grady1) / 2;
207
208       if ((2*across+MIN(gradx,gradx1) < 0) ||
209           (2*across+MAX(gradx,gradx1) >= st->bigwidth)) {
210         gradx = 0;
211         gradx1= 1;
212       }
213       if ((2*down+MIN(grady,grady1) < 0) ||
214           (2*down+MAX(grady,grady1) >= st->bigheight)) {
215         grady = 0;
216         grady1 = 1;
217       }
218
219       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
220         if (dirty[pixel] > 0)
221           dirty[pixel]--;
222       } else
223         dirty[pixel] = DIRTY;
224
225       if (dirty[pixel] > 0) {
226         XPutPixel(st->buffer_map, (across<<1),  (down<<1),
227                   grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady)));
228         XPutPixel(st->buffer_map, (across<<1)+1,(down<<1),
229                   grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady)));
230         XPutPixel(st->buffer_map, (across<<1),  (down<<1)+1,
231                   grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady1)));
232         XPutPixel(st->buffer_map, (across<<1)+1,(down<<1)+1,
233                   grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady1)));
234       }
235     }
236 }
237
238
239 /*      -------------------------------------------             */
240
241
242 static void
243 set_mask(unsigned long color, unsigned long *mask, int *shift)
244 {
245   *shift = 0;
246   while (color != 0 && (color & 1) == 0) {
247     (*shift)++;
248     color >>= 1;
249   }
250   *mask = color;
251 }
252
253
254 static unsigned long
255 cadd(unsigned long color, int dx, unsigned long mask, int shift)
256 {
257   int x;
258   color >>= shift;
259   x = (color & mask);
260   x += dx;
261   if (x < 0) x = 0;
262   else if (x > (int)mask) x = mask;
263   color = x;
264   return color << shift;
265 }
266
267
268 static unsigned long
269 bright(struct state *st, int dx, unsigned long color)
270 {
271   return (cadd(color, dx, st->rmask, st->rshift) |
272           cadd(color, dx, st->gmask, st->gshift) |
273           cadd(color, dx, st->bmask, st->bshift));
274 }
275
276
277 static unsigned long
278 grayscale(struct state *st, unsigned long color)
279 {
280   int red;
281   int green;
282   int blue;
283   int total;
284   int gray_r;
285   int gray_g;
286   int gray_b;
287
288   if (!st->grayscale_p)
289     return color;
290   if (!st->transparent)
291     return color;
292   if ((st->rmask == 0) || (st->gmask == 0) || (st->bmask == 0))
293     return color;
294
295   red = ((color >> st->rshift) & st->rmask);
296   green =  ((color >> st->gshift) & st->gmask);
297   blue =  ((color >> st->bshift) & st->bmask);
298   total = red * st->gmask * st->bmask + green * st->rmask * st->bmask + blue * st->rmask * st->gmask;
299
300   gray_r = total / (3 * st->gmask * st->bmask);
301   if (gray_r < 0)
302     gray_r = 0;
303   if (gray_r > st->rmask)
304     gray_r = st->rmask;
305   
306   gray_g = total / (3 * st->rmask * st->bmask);
307   if (gray_g < 0)
308     gray_g = 0;
309   if (gray_g > st->gmask)
310     gray_g = st->gmask;
311
312   gray_b = total / (3 * st->rmask * st->gmask);
313   if (gray_b < 0)
314     gray_b = 0;
315   if (gray_b > st->bmask)
316     gray_b = st->bmask;
317
318   return ((unsigned long)
319           ((gray_r << st->rshift) | (gray_g << st->gshift) | (gray_b << st->bshift)));
320 }
321
322
323 static void
324 draw_transparent_light(struct state *st, short *src)
325 {
326   int across, down, pixel;
327   char *dirty = st->dirty_buffer;
328
329   pixel = 0;
330   for (down = 0; down < st->height - 2; down++, pixel += 2)
331     for (across = 0; across < st->width-2; across++, pixel++) {
332       int gradx, grady, gradx1, grady1;
333       int x0, x1, x2, y1, y2;
334
335       x0 = src[pixel];
336       x1 = src[pixel + 1];
337       x2 = src[pixel + 2];
338       y1 = src[pixel + st->width];
339       y2 = src[pixel + 2*st->width];
340
341       gradx = (x1 - x0);
342       grady = (y1 - x0);
343       gradx1= (x2 - x1);
344       grady1= (y2 - y1);
345       gradx1 = 1 + (gradx + gradx1) / 2;
346       grady1 = 1 + (grady + grady1) / 2;
347
348       if ((2*across+MIN(gradx,gradx1) < 0) ||
349           (2*across+MAX(gradx,gradx1) >= st->bigwidth)) {
350         gradx = 0;
351         gradx1= 1;
352       }
353       if ((2*down+MIN(grady,grady1) < 0) ||
354           (2*down+MAX(grady,grady1) >= st->bigheight)) {
355         grady = 0;
356         grady1 = 1;
357       }
358
359       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
360         if (dirty[pixel] > 0)
361           dirty[pixel]--;
362       } else
363         dirty[pixel] = DIRTY;
364
365       if (dirty[pixel] > 0) {
366         int dx;
367
368         /* light from top */
369         if (4-st->light >= 0)
370           dx = (grady + (src[pixel+st->width+1]-x1)) >> (4-st->light);
371         else
372           dx = (grady + (src[pixel+st->width+1]-x1)) << (st->light-4);
373
374         if (dx != 0) {
375           XPutPixel(st->buffer_map, (across<<1),  (down<<1),
376                     bright(st, dx, grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady))));
377           XPutPixel(st->buffer_map, (across<<1)+1,(down<<1),
378                     bright(st, dx, grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady))));
379           XPutPixel(st->buffer_map, (across<<1),  (down<<1)+1,
380                     bright(st, dx, grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady1))));
381           XPutPixel(st->buffer_map, (across<<1)+1,(down<<1)+1,
382                     bright(st, dx, grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady1))));
383         } else {
384           /* Could use XCopyArea, but XPutPixel is faster */
385           XPutPixel(st->buffer_map, (across<<1),  (down<<1),
386                     grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady)));
387           XPutPixel(st->buffer_map, (across<<1)+1,(down<<1),
388                     grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady)));
389           XPutPixel(st->buffer_map, (across<<1),  (down<<1)+1,
390                     grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx, (down<<1) + grady1)));
391           XPutPixel(st->buffer_map, (across<<1)+1,(down<<1)+1,
392                     grayscale(st, XGetPixel(st->orig_map, (across<<1) + gradx1,(down<<1) + grady1)));
393         }
394       }
395     }
396 }
397
398
399 /*      -------------------------------------------             */
400
401
402 #if 0
403 /* Doesn't go any faster and doesn't work at all colour depths */
404 static void
405 draw_transparent16l(short *src)
406 {
407   int across, down, bigpix, pixel;
408   char *dirty = st->dirty_buffer;
409   unsigned short *buffer, *orig;
410
411   buffer = (unsigned short *) st->buffer_map->data;
412   orig = (unsigned short *) st->orig_map->data;
413
414   for (pixel = bigpix = down = 0;
415        down < st->height - 2;
416        down++, pixel += 2, bigpix += st->bigwidth+4)
417     for (across = 0; across < st->width-2; across++, pixel++, bigpix+=2) {
418       int gradx, grady, gradx1, grady1;
419       int x0, x1, x2, y1, y2;
420
421       x0 = src[pixel];
422       x1 = src[pixel + 1];
423       x2 = src[pixel + 2];
424       y1 = src[pixel + st->width];
425       y2 = src[pixel + 2*st->width];
426
427       gradx = (x1 - x0);
428       grady = (y1 - x0);
429       gradx1= (x2 - x1);
430       grady1= (y2 - y1);
431       gradx1 = 1 + (gradx + gradx1) / 2;
432       grady1 = 1 + (grady + grady1) / 2;
433
434       if ((2*across+MIN(gradx,gradx1) < 0) ||
435           (2*across+MAX(gradx,gradx1) >= st->bigwidth)) {
436         gradx = 0;
437         gradx1= 1;
438       }
439       if ((2*down+MIN(grady,grady1) < 0) ||
440           (2*down+MAX(grady,grady1) >= st->bigheight)) {
441         grady = 0;
442         grady1 = 1;
443       }
444
445       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
446         if (dirty[pixel] > 0)
447           dirty[pixel]--;
448       } else
449         dirty[pixel] = DIRTY;
450
451       if (dirty[pixel] > 0) {
452         unsigned short *dest = buffer + bigpix;
453         unsigned short *image = orig + bigpix;
454         int dx;
455
456         /* light from top */
457         if (4-st->light >= 0)
458           dx = (grady + (src[pixel+st->width+1]-x1)) >> (4-st->light);
459         else
460           dx = (grady + (src[pixel+st->width+1]-x1)) << (st->light-4);
461
462         grady *= st->bigwidth;
463         grady1*= st->bigwidth;
464
465         if (dx != 0) {
466           *dest++ = dobright(dx, *(image + gradx  + grady));
467           *dest   = dobright(dx, *(image + gradx1 + grady));
468           dest   += st->bigwidth - 1;
469           *dest++ = dobright(dx, *(image + gradx  + grady1));
470           *dest   = dobright(dx, *(image + gradx1 + grady1));
471         } else {
472           *dest++ = *(image + gradx  + grady);
473           *dest   = *(image + gradx1 + grady);
474           dest   += st->bigwidth - 1;
475           *dest++ = *(image + gradx  + grady1);
476           *dest   = *(image + gradx1 + grady1);
477         }
478       }
479     }
480 }
481 #endif
482
483
484 /*      -------------------------------------------             */
485
486
487 static void
488 setup_X(struct state *st)
489 {
490   XWindowAttributes xgwa;
491   int depth;
492
493   XGetWindowAttributes(st->dpy, st->window, &xgwa);
494   depth = xgwa.depth;
495   st->colormap = xgwa.colormap;
496   st->bigwidth = xgwa.width;
497   st->bigheight = xgwa.height;
498   st->visual = xgwa.visual;
499
500
501   /* This causes buffer_map to be 1 pixel taller and wider than orig_map,
502      which can cause the two XImages to have different bytes-per-line,
503      which causes stair-stepping.  So this better not be necessary...
504      -jwz, 23-Nov-01
505    */
506 #if 0 /* I'm not entirely sure if I need this */
507   if (st->bigwidth % 2)
508     st->bigwidth++;
509   if (st->bigheight % 2)
510     st->bigheight++;
511 #endif
512
513
514   st->width = st->bigwidth / 2;
515   st->height = st->bigheight / 2;
516
517   if (st->transparent) {
518     XGCValues gcv;
519     long gcflags;
520
521     gcv.function = GXcopy;
522     gcv.subwindow_mode = IncludeInferiors;
523
524     gcflags = GCFunction;
525     if (use_subwindow_mode_p(xgwa.screen, st->window))  /* see grabscreen.c */
526       gcflags |= GCSubwindowMode;
527
528     st->gc = XCreateGC(st->dpy, st->window, gcflags, &gcv);
529
530     st->img_loader = load_image_async_simple (0, xgwa.screen, st->window,
531                                               st->window, 0, 0);
532   } else {
533     XGCValues gcv;
534
535     st->gc = XCreateGC(st->dpy, st->window, 0, &gcv);
536     st->orig_map = 0;
537   }
538
539   if (!st->gc) {
540     fprintf(stderr, "XCreateGC failed\n");
541     exit(1);
542   }
543
544   st->buffer_map = 0;
545
546 #ifdef HAVE_XSHM_EXTENSION
547   if (st->use_shm) {
548     st->buffer_map = create_xshm_image(st->dpy, xgwa.visual, depth,
549                                    ZPixmap, 0, &st->shm_info, st->bigwidth, st->bigheight);
550     if (!st->buffer_map) {
551       st->use_shm = False;
552       fprintf(stderr, "create_xshm_image failed\n");
553     }
554   }
555 #endif /* HAVE_XSHM_EXTENSION */
556
557   if (!st->buffer_map) {
558     st->buffer_map = XCreateImage(st->dpy, xgwa.visual,
559                               depth, ZPixmap, 0, 0,
560                               st->bigwidth, st->bigheight, 8, 0);
561     st->buffer_map->data = (char *)
562       calloc(st->buffer_map->height, st->buffer_map->bytes_per_line);
563   }
564 }
565
566
567 static void
568 DisplayImage(struct state *st)
569 {
570 #ifdef HAVE_XSHM_EXTENSION
571   if (st->use_shm)
572     XShmPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, 0, 0,
573                  st->bigwidth, st->bigheight, False);
574   else
575 #endif /* HAVE_XSHM_EXTENSION */
576     XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, 0, 0,
577               st->bigwidth, st->bigheight);
578 }
579
580
581 /*      -------------------------------------------             */
582
583
584 static int
585 cinterp(double a, int bg, int fg)
586 {
587   int result;
588   result = (int)((1-a) * bg + a * fg + 0.5);
589   if (result < 0) result = 0;
590   if (result > 255) result = 255;
591   return result;
592 }
593
594
595 /* Interpolate the ripple colours between the background colour and
596    foreground colour */
597 static void
598 init_linear_colors(struct state *st)
599 {
600   int i, j, red, green, blue, bred, bgreen, bblue;
601   XColor fg, bg;
602
603   if (st->ncolors < 2 || mono_p)
604     st->ncolors = 2;
605   if (st->ncolors <= 2)
606     mono_p = True;
607
608   /* Make it possible to set the color of the ripples,
609      Based on work by Raymond Medeiros <ray@stommel.marine.usf.edu> and jwz.
610    */
611   fg.pixel = get_pixel_resource(st->dpy, st->colormap, "foreground", "Foreground");
612   XQueryColor(st->dpy, st->colormap, &fg);
613   red = (fg.red >> 8);
614   green = (fg.green >> 8);
615   blue = (fg.blue >> 8);
616
617   bg.pixel = get_pixel_resource(st->dpy, st->colormap, "background", "Background");
618   XQueryColor(st->dpy, st->colormap, &bg);
619   bred = (bg.red >> 8);
620   bgreen = (bg.green >> 8);
621   bblue = (bg.blue >> 8);
622
623   j = 0;
624   for (i = 0; i < st->ncolors+1; i++) {
625     XColor xcl;
626     double a = (double)i / st->ncolors;
627     int r = cinterp(a, bred, red);
628     int g = cinterp(a, bgreen, green);
629     int b = cinterp(a, bblue, blue);
630
631     xcl.red = (unsigned short) ((r << 8) | r);
632     xcl.green = (unsigned short) ((g << 8) | g);
633     xcl.blue = (unsigned short) ((b << 8) | b);
634     xcl.flags = DoRed | DoGreen | DoBlue;
635
636     XAllocColor(st->dpy, st->colormap, &xcl);
637
638     st->ctab[j++] = (int) xcl.pixel;
639   }
640 }
641
642
643 static void
644 init_oily_colors(struct state *st)
645 {
646   XColor *colors = NULL;
647
648   if (st->ncolors < 2 || mono_p)
649     st->ncolors = 2;
650   if (st->ncolors <= 2)
651     mono_p = True;
652   colors = 0;
653
654   if (!mono_p) {
655     colors = (XColor *)malloc(sizeof(*colors) * (st->ncolors+1));
656     make_smooth_colormap(st->dpy, st->visual, st->colormap, colors, &st->ncolors,
657                          True, /* allocate */
658                          False, /* not writable */
659                          True); /* verbose (complain about failure) */
660     if (st->ncolors <= 2) {
661       if (colors)
662         free (colors);
663       colors = 0;
664       mono_p = True;
665     }
666   }
667   if (!mono_p) {
668     int i, j = 0;
669     for (i = 0; i < st->ncolors+1; i++) {
670       XAllocColor(st->dpy, st->colormap, colors+i);
671       st->ctab[j++] = (int) colors[i].pixel;
672     }
673     free (colors);
674   } else {
675     st->ncolors = 2;
676     st->ctab[1] = get_pixel_resource(st->dpy, st->colormap, "foreground", "Foreground");
677     st->ctab[0] = get_pixel_resource(st->dpy, st->colormap, "background", "Background");
678   }
679 }
680
681
682 /*      -------------------------------------------             */
683
684
685 static void
686 init_cos_tab(struct state *st)
687 {
688   int i;
689   for (i = 0; i < TABLE; i++)
690     st->cos_tab[i] = cos(i * M_PI/2 / TABLE);
691 }
692
693
694 /* Shape of drop to add */
695 static double
696 sinc(struct state *st, double x)
697 {
698 #if 1
699   /* cosine hump */
700   int i;
701   i = (int)(x * TABLE + 0.5);
702   if (i >= TABLE) i = (TABLE-1) - (i-(TABLE-1));
703   return st->cos_tab[i];
704 #elif 0
705   return cos(x * M_PI/2);
706 #else
707   if (fabs(x) < 0.1)
708     return 1 - x*x;
709   else
710     return sin(x) / x;
711 #endif
712 }
713
714
715 static void
716 add_circle_drop(struct state *st, int x, int y, int radius, int dheight)
717 {
718   int i, r2, cx, cy;
719   short *buf = (random()&1) ? st->bufferA : st->bufferB;
720
721   i = y * st->width + x;
722   r2 = radius * radius;
723
724   for (cy = -radius; cy <= radius; cy++)
725     for (cx = -radius; cx <= radius; cx++) {
726       int r = cx*cx + cy*cy;
727       if (r <= r2) {
728         buf[i + cx + cy*st->width] =
729           (short)(dheight * sinc(st, sqrt(r)/radius));
730       }
731     }
732 }
733
734
735 static void
736 add_drop(struct state *st, ripple_mode mode, int drop)
737 {
738   int newx, newy, dheight;
739   int radius = MIN(st->width, st->height) / 50;
740   /* Don't put drops too near the edge of the screen or they get stuck */
741   int border = 8;
742
743   switch (mode) {
744   default:
745   case ripple_drop: {
746     int x;
747
748     dheight = 1 + (random() % drop);
749     newx = border + (random() % (st->width - 2*border));
750     newy = border + (random() % (st->height - 2*border));
751     x = newy * st->width + newx;
752     st->bufferA[x + 1] = st->bufferA[x] = st->bufferA[x + st->width] = st->bufferA[x + st->width + 1] =
753       st->bufferB[x + 1] = st->bufferB[x] = st->bufferB[x + st->width] = st->bufferB[x + st->width + 1] =
754       dheight;
755   }
756   break;
757   case ripple_blob: {
758     double power;
759
760     int tmp_i, tmp_j;
761     power = drop_dist[random() % (sizeof(drop_dist)/sizeof(drop_dist[0]))]; /* clumsy */
762     dheight = (int)(drop * (power + 0.01));
763     tmp_i = (int)(st->width - 2*border - 2*radius*power);
764     tmp_j = (int)(st->height - 2*border - 2*radius*power);
765     newx = radius + border + ((tmp_i > 0) ? random() % tmp_i : 0);
766     newy = radius + border + ((tmp_j > 0) ? random() % tmp_j : 0);
767     add_circle_drop(st, newx, newy, radius, dheight);
768   }
769   break;
770   /* Adding too many boxes too quickly (-box 1) doesn't give the waves time
771      to disperse and the waves build up (and overflow) */
772   case ripple_box: {
773     int x;
774     int cx, cy;
775     short *buf = (random()&1) ? st->bufferA : st->bufferB;
776     int tmp_i, tmp_j;
777
778     radius = (1 + (random() % 5)) * (1 + (random() % 5));
779     dheight = drop / 128;
780     if (random() & 1) dheight = -dheight;
781     tmp_i = st->width - 2*border - 2*radius;
782     tmp_j = st->height - 2*border - 2*radius;
783     newx = radius + border + ((tmp_i > 0) ? random() % tmp_i : 0);
784     newy = radius + border + ((tmp_j > 0) ? random() % tmp_j : 0);
785     x = newy * st->width + newx;
786     for (cy = -radius; cy <= radius; cy++)
787       for (cx = -radius; cx <= radius; cx++)
788         buf[x + cx + cy*st->width] = (short)(dheight);
789   }
790   break;
791   case ripple_stir: {
792     border += radius;
793     newx = border + (int)((st->width-2*border) * (1+cos(3*st->stir_ang)) / 2);
794     newy = border + (int)((st->height-2*border) * (1+sin(2*st->stir_ang)) / 2);
795     add_circle_drop(st, newx, newy, radius, drop / 10);
796     st->stir_ang += 0.02;
797     if (st->stir_ang > 12*M_PI) st->stir_ang = 0;
798   }
799   break;
800   }
801 }
802
803
804 static void
805 init_ripples(struct state *st, int ndrops, int splash)
806 {
807   int i;
808
809   st->bufferA = (short *)calloc(st->width * st->height, sizeof(*st->bufferA));
810   st->bufferB = (short *)calloc(st->width * st->height, sizeof(*st->bufferB));
811   st->temp = (short *)calloc(st->width * st->height, sizeof(*st->temp));
812
813   st->dirty_buffer = (char *)calloc(st->width * st->height, sizeof(*st->dirty_buffer));
814
815   for (i = 0; i < ndrops; i++)
816     add_drop(st, ripple_blob, splash);
817
818   if (st->transparent) {
819     if (st->grayscale_p)
820     {
821       int across, down;
822       for (down = 0; down < st->bigheight; down++)
823         for (across = 0; across < st->bigwidth; across++)
824           XPutPixel(st->buffer_map, across, down,
825                     grayscale(st, XGetPixel(st->orig_map, across, down)));
826     }
827     else
828     {  
829     /* There's got to be a better way of doing this  XCopyArea? */
830     memcpy(st->buffer_map->data, st->orig_map->data,
831            st->bigheight * st->buffer_map->bytes_per_line);
832     }
833   } else {
834     int across, down, color;
835
836     color = map_color(st, 0); /* background colour */
837     for (down = 0; down < st->bigheight; down++)
838       for (across = 0; across < st->bigwidth; across++)
839         XPutPixel(st->buffer_map,across,  down,  color);
840   }
841
842   DisplayImage(st);
843 }
844
845
846 /*
847  Explanation from hq_water.zip (Arturo R Montesinos (ARM) arami@fi.upm.es)
848
849  Differential equation is:  u  = a ( u  + u  )
850                              tt       xx   yy
851
852  Where a = tension * gravity / surface_density.
853
854  Approximating second derivatives by central differences:
855
856   [ u(t+1)-2u(t)+u(t-1) ] / dt = a [ u(x+1)+u(x-1)+u(y+1)+u(y-1)-4u ] / h
857
858  where dt = time step squared, h = dx*dy = mesh resolution squared.
859
860  From where u(t+1) may be calculated as:
861
862             dt  |   1   |                   dt
863  u(t+1) = a --  | 1 0 1 |u - u(t-1) + (2-4a --)u
864             h   |   1   |                    h
865
866  When a*dt/h = 1/2 last term vanishes, giving:
867
868                  1 |   1   |
869         u(t+1) = - | 1 0 1 |u - u(t-1)
870                  2 |   1   |
871
872  (note that u(t-1,x,y) is only used to calculate u(t+1,x,y) so
873   we can use the same array for both t-1 and t+1, needing only
874   two arrays, U[0] and U[1])
875
876  Dampening is simulated by subtracting 1/2^n of result.
877  n=4 gives best-looking result
878  n<4 (eg 2 or 3) thicker consistency, waves die out immediately
879  n>4 (eg 8 or 12) more fluid, waves die out slowly
880  */
881
882 static void
883 ripple(struct state *st)
884 {
885   int across, down, pixel;
886   short *src, *dest;
887
888   if (st->draw_toggle == 0) {
889     src = st->bufferA;
890     dest = st->bufferB;
891     st->draw_toggle = 1;
892   } else {
893     src = st->bufferB;
894     dest = st->bufferA;
895     st->draw_toggle = 0;
896   }
897
898   switch (st->draw_count) {
899   case 0: case 1:
900     pixel = 1 * st->width + 1;
901     for (down = 1; down < st->height - 1; down++, pixel += 2 * 1)
902       for (across = 1; across < st->width - 1; across++, pixel++) {
903         st->temp[pixel] =
904           (((src[pixel - 1] + src[pixel + 1] +
905              src[pixel - st->width] + src[pixel + st->width]) / 2)) - dest[pixel];
906       }
907
908     /* Smooth the output */
909     pixel = 1 * st->width + 1;
910     for (down = 1; down < st->height - 1; down++, pixel += 2 * 1)
911       for (across = 1; across < st->width - 1; across++, pixel++) {
912         if (st->temp[pixel] != 0) { /* Close enough for government work */
913           int damp =
914             (st->temp[pixel - 1] + st->temp[pixel + 1] +
915              st->temp[pixel - st->width] + st->temp[pixel + st->width] +
916              st->temp[pixel - st->width - 1] + st->temp[pixel - st->width + 1] +
917              st->temp[pixel + st->width - 1] + st->temp[pixel + st->width + 1] +
918              st->temp[pixel]) / 9;
919           dest[pixel] = damp - (damp >> st->fluidity);
920         } else
921           dest[pixel] = 0;
922       }
923     break;
924   case 2: case 3:
925     pixel = 1 * st->width + 1;
926     for (down = 1; down < st->height - 1; down++, pixel += 2 * 1)
927       for (across = 1; across < st->width - 1; across++, pixel++) {
928         int damp =
929           (((src[pixel - 1] + src[pixel + 1] +
930              src[pixel - st->width] + src[pixel + st->width]) / 2)) - dest[pixel];
931         dest[pixel] = damp - (damp >> st->fluidity);
932       }
933     break;
934   }
935   if (++st->draw_count > 3) st->draw_count = 0;
936
937   if (st->transparent)
938     st->draw_transparent(st, dest);
939   else
940     draw_ripple(st, dest);
941 }
942
943
944 /*      -------------------------------------------             */
945
946 static void *
947 ripples_init (Display *disp, Window win)
948 {
949   struct state *st = (struct state *) calloc (1, sizeof(*st));
950   st->dpy = disp;
951   st->window = win;
952   st->iterations = 0;
953   st->delay = get_integer_resource(disp, "delay", "Integer");
954   st->rate = get_integer_resource(disp, "rate", "Integer");
955   st->box = get_integer_resource(disp, "box", "Integer");
956   st->oily = get_boolean_resource(disp, "oily", "Boolean");
957   st->stir = get_boolean_resource(disp, "stir", "Boolean");
958   st->fluidity = get_integer_resource(disp, "fluidity", "Integer");
959   st->transparent = get_boolean_resource(disp, "water", "Boolean");
960   st->grayscale_p = get_boolean_resource(disp, "grayscale", "Boolean");
961 #ifdef HAVE_XSHM_EXTENSION
962   st->use_shm = get_boolean_resource(disp, "useSHM", "Boolean");
963 #endif /* HAVE_XSHM_EXTENSION */
964   st->light = get_integer_resource(disp, "light", "Integer");
965
966   if (st->fluidity <= 1) st->fluidity = 1;
967   if (st->fluidity > 16) st->fluidity = 16; /* 16 = sizeof(short) */
968   if (st->light < 0) st->light = 0;
969
970   init_cos_tab(st);
971   setup_X(st);
972
973   st->ncolors = get_integer_resource (disp, "colors", "Colors");
974   if (0 == st->ncolors)         /* English spelling? */
975     st->ncolors = get_integer_resource (disp, "colours", "Colors");
976
977   if (st->ncolors > sizeof(st->ctab)/sizeof(*st->ctab))
978     st->ncolors = sizeof(st->ctab)/sizeof(*st->ctab);
979
980   if (st->oily)
981     init_oily_colors(st);
982   else
983     init_linear_colors(st);
984
985   if (st->transparent && st->light > 0) {
986     int maxbits;
987     st->draw_transparent = draw_transparent_light;
988     set_mask(st->visual->red_mask,   &st->rmask, &st->rshift);
989     set_mask(st->visual->green_mask, &st->gmask, &st->gshift);
990     set_mask(st->visual->blue_mask,  &st->bmask, &st->bshift);
991     if (st->rmask == 0) st->draw_transparent = draw_transparent_vanilla;
992
993     /* Adjust the shift value "light" when we don't have 8 bits per colour */
994     maxbits = MIN(MIN(BITCOUNT(st->rmask), BITCOUNT(st->gmask)), BITCOUNT(st->bmask));
995     st->light -= 8-maxbits;
996     if (st->light < 0) st->light = 0;
997   } else {
998     if (st->grayscale_p)
999     { 
1000       set_mask(st->visual->red_mask,   &st->rmask, &st->rshift);
1001       set_mask(st->visual->green_mask, &st->gmask, &st->gshift);
1002       set_mask(st->visual->blue_mask,  &st->bmask, &st->bshift);
1003     }
1004     st->draw_transparent = draw_transparent_vanilla;
1005   }
1006   
1007   if (!st->transparent)
1008     init_ripples(st, 0, -SPLASH); /* Start off without any drops */
1009
1010   return st;
1011 }
1012
1013 static unsigned long
1014 ripples_draw (Display *dpy, Window window, void *closure)
1015 {
1016   struct state *st = (struct state *) closure;
1017
1018   if (st->img_loader)   /* still loading */
1019     {
1020       st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0, 0);
1021       if (! st->img_loader) {  /* just finished */
1022         XWindowAttributes xgwa;
1023         XGetWindowAttributes(st->dpy, st->window, &xgwa);
1024         st->orig_map = XGetImage (st->dpy, st->window, 0, 0, 
1025                                   xgwa.width, xgwa.height,
1026                                   ~0L, ZPixmap);
1027         init_ripples(st, 0, -SPLASH); /* Start off without any drops */
1028       }
1029       return st->delay;
1030     }
1031
1032     if (st->rate > 0 && (st->iterations % st->rate) == 0)
1033       add_drop(st, ripple_blob, -SPLASH);
1034     if (st->stir)
1035       add_drop(st, ripple_stir, -SPLASH);
1036     if (st->box > 0 && (random() % st->box) == 0)
1037       add_drop(st, ripple_box, -SPLASH);
1038
1039     ripple(st);
1040     DisplayImage(st);
1041
1042     st->iterations++;
1043
1044     return st->delay;
1045 }
1046
1047
1048 static void
1049 ripples_reshape (Display *dpy, Window window, void *closure, 
1050                  unsigned int w, unsigned int h)
1051 {
1052 }
1053
1054 static Bool
1055 ripples_event (Display *dpy, Window window, void *closure, XEvent *event)
1056 {
1057   return False;
1058 }
1059
1060 static void
1061 ripples_free (Display *dpy, Window window, void *closure)
1062 {
1063   struct state *st = (struct state *) closure;
1064   free (st);
1065 }
1066
1067 static const char *ripples_defaults[] =
1068 {
1069   ".background:         black",
1070   ".foreground:         #FFAF5F",
1071   "*colors:             200",
1072   "*dontClearRoot:      True",
1073   "*delay:              50000",
1074   "*rate:               5",
1075   "*box:                0",
1076   "*water:              False",
1077   "*oily:               False",
1078   "*stir:               False",
1079   "*fluidity:           6",
1080   "*light:              0",
1081   "*grayscale:          False",
1082 #ifdef HAVE_XSHM_EXTENSION
1083   "*useSHM: True",
1084 #else
1085   "*useSHM: False",
1086 #endif
1087   0
1088 };
1089
1090 static XrmOptionDescRec ripples_options[] =
1091 {
1092   { "-colors",  ".colors",      XrmoptionSepArg, 0},
1093   { "-colours", ".colors",      XrmoptionSepArg, 0},
1094   {"-delay",    ".delay",       XrmoptionSepArg, 0},
1095   {"-rate",     ".rate",        XrmoptionSepArg, 0},
1096   {"-box",      ".box",         XrmoptionSepArg, 0},
1097   {"-water",    ".water",       XrmoptionNoArg, "True"},
1098   {"-oily",     ".oily",        XrmoptionNoArg, "True"},
1099   {"-stir",     ".stir",        XrmoptionNoArg, "True"},
1100   {"-fluidity", ".fluidity",    XrmoptionSepArg, 0},
1101   {"-light",    ".light",       XrmoptionSepArg, 0},
1102   {"-grayscale",        ".grayscale",   XrmoptionNoArg, "True"},
1103   {"-shm",      ".useSHM",      XrmoptionNoArg, "True"},
1104   {"-no-shm",   ".useSHM",      XrmoptionNoArg, "False"},
1105   {0, 0, 0, 0}
1106 };
1107
1108
1109 XSCREENSAVER_MODULE ("Ripples", ripples)