http://slackware.bholcomb.com/slackware/slackware-11.0/source/xap/xscreensaver/xscree...
[xscreensaver] / hacks / distort.c
1 /* -*- mode: C; tab-width: 4 -*-
2  * xscreensaver, Copyright (c) 1992-2006 Jamie Zawinski <jwz@jwz.org>
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
13 /* distort
14  * by Jonas Munsin (jmunsin@iki.fi) and Jamie Zawinski <jwz@jwz.org>
15  * TODO:
16  *      -check the allocations in init_round_lense again, maybe make it possible again
17  *       to use swamp without pre-allocating/calculating (although that
18  *       makes it slower) - -swamp is memory hungry
19  *      -more distortion matrices (fortunately, I'm out of ideas :)
20  * Stuff that would be cool but probably too much of a resource hog:
21  *      -some kind of interpolation to avoid jaggies
22  *    -large speed values leaves the image distorted
23  * program idea borrowed from a screensaver on a non-*NIX OS,
24  *
25  * 28 Sep 1999 Jonas Munsin (jmunsin@iki.fi)
26  *    Added about 10x faster algortim for 8, 16 and 32 bpp (modifies pixels
27  *    directly avoiding costly XPutPixle(XGetPixel()) calls, inspired by
28  *    xwhirl made by horvai@clipper.ens.fr (Peter Horvai) and the XFree86
29  *    Xlib sources.
30  *    This piece of code is really horrible, but it works, and at the moment
31  *    I don't have time or inspiration to fix something that works (knock
32  *    on wood).
33  * 08 Oct 1999 Jonas Munsin (jmunsin@iki.fi)
34  *      Corrected several bugs causing references beyond allocated memory.
35  */
36
37 #include <math.h>
38 #include "screenhack.h"
39 /*#include <X11/Xmd.h>*/
40
41 #ifdef HAVE_XSHM_EXTENSION
42 # include "xshm.h"
43 #endif /* HAVE_XSHM_EXTENSION */
44
45 #define CARD32 unsigned int
46 #define CARD16 unsigned short
47 #define CARD8  unsigned char
48
49
50 struct coo {
51         int x;
52         int y;
53         int r, r_change;
54         int xmove, ymove;
55 };
56
57 struct state {
58   Display *dpy;
59   Window window;
60
61   struct coo xy_coo[10];
62
63   int delay, radius, speed, number, blackhole, vortex, magnify, reflect, slow;
64   XWindowAttributes xgwa;
65   GC gc;
66   unsigned long black_pixel;
67
68   XImage *orig_map, *buffer_map;
69   unsigned long *buffer_map_cache;
70
71   int ***from;
72   int ****from_array;
73   int *fast_from;
74
75   int bpp_size;
76
77 #ifdef HAVE_XSHM_EXTENSION
78   Bool use_shm;
79   XShmSegmentInfo shm_info;
80 #endif /* HAVE_XSHM_EXTENSION */
81
82   void (*effect) (struct state *, int);
83   void (*draw) (struct state *, int);
84   void (*draw_routine) (struct state *st, XImage *, XImage *, int, int, int *);
85
86   async_load_state *img_loader;
87 };
88
89
90 static void move_lense(struct state *, int);
91 static void swamp_thing(struct state *, int);
92 static void new_rnd_coo(struct state *, int);
93 static void init_round_lense(struct state *st);
94 static void reflect_draw(struct state *, int);
95 static void plain_draw(struct state *, int);
96
97 static void fast_draw_8 (struct state *st, XImage *, XImage *, int, int, int *);
98 static void fast_draw_16(struct state *st, XImage *, XImage *, int, int, int *);
99 static void fast_draw_32(struct state *st, XImage *, XImage *, int, int, int *);
100 static void generic_draw(struct state *st, XImage *, XImage *, int, int, int *);
101
102
103 static void distort_finish_loading (struct state *);
104
105 static void *
106 distort_init (Display *dpy, Window window)
107 {
108   struct state *st = (struct state *) calloc (1, sizeof(*st));
109         XGCValues gcv;
110         long gcflags;
111         int i;
112     char *s;
113
114     st->dpy = dpy;
115     st->window = window;
116
117         st->delay = get_integer_resource(st->dpy, "delay", "Integer");
118         st->radius = get_integer_resource(st->dpy, "radius", "Integer");
119         st->speed = get_integer_resource(st->dpy, "speed", "Integer");
120         st->number = get_integer_resource(st->dpy, "number", "Integer");
121
122 #ifdef HAVE_XSHM_EXTENSION
123         st->use_shm = get_boolean_resource(st->dpy, "useSHM", "Boolean");
124 #endif /* HAVE_XSHM_EXTENSION */
125         
126         st->blackhole = get_boolean_resource(st->dpy, "blackhole", "Boolean");
127         st->vortex = get_boolean_resource(st->dpy, "vortex", "Boolean");
128         st->magnify = get_boolean_resource(st->dpy, "magnify", "Boolean");
129         st->reflect = get_boolean_resource(st->dpy, "reflect", "Boolean");
130         st->slow = get_boolean_resource(st->dpy, "slow", "Boolean");
131         
132     st->effect = NULL;
133     s = get_string_resource(st->dpy, "effect", "String");
134         if (s && !strcasecmp(s,"swamp"))
135       st->effect = &swamp_thing;
136     else if (s && !strcasecmp(s,"bounce"))
137       st->effect = &move_lense;
138     else if (s && !strcasecmp(s,"none"))
139       ;
140     else if (s && *s)
141       fprintf(stderr,"%s: bogus effect: %s\n", progname, s);
142
143         XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
144
145         if (st->effect == NULL && st->radius == 0 && st->speed == 0 && st->number == 0
146                 && !st->blackhole && !st->vortex && !st->magnify && !st->reflect) {
147 /* if no cmdline options are given, randomly choose one of:
148  * -radius 50 -number 4 -speed 1 -bounce
149  * -radius 50 -number 4 -speed 1 -blackhole
150  * -radius 50 -number 4 -speed 1 -vortex
151  * -radius 50 -number 4 -speed 1 -vortex -magnify
152  * -radius 50 -number 4 -speed 1 -vortex -magnify -blackhole
153  * -radius 100 -number 1 -speed 2 -bounce
154  * -radius 100 -number 1 -speed 2 -blackhole
155  * -radius 100 -number 1 -speed 2 -vortex
156  * -radius 100 -number 1 -speed 2 -vortex -magnify
157  * -radius 100 -number 1 -speed 2 -vortex -magnify -blackhole
158  * -radius 80 -number 1 -speed 2 -reflect
159  * -radius 50 -number 3 -speed 2 -reflect
160  * jwz: not these
161  *   -radius 50 -number 4 -speed 2 -swamp
162  *   -radius 50 -number 4 -speed 2 -swamp -blackhole
163  *   -radius 50 -number 4 -speed 2 -swamp -vortex
164  *   -radius 50 -number 4 -speed 2 -swamp -vortex -magnify
165  *   -radius 50 -number 4 -speed 2 -swamp -vortex -magnify -blackhole
166  */
167                 
168                 i = (random() % 12 /* 17 */);
169
170                 st->draw = &plain_draw;
171
172                 switch (i) {
173                         case 0:
174                                 st->radius=50;st->number=4;st->speed=1;
175                                 st->effect=&move_lense;break;
176                         case 1:
177                                 st->radius=50;st->number=4;st->speed=1;st->blackhole=1;
178                                 st->effect=&move_lense;break;
179                         case 2:
180                                 st->radius=50;st->number=4;st->speed=1;st->vortex=1;
181                                 st->effect=&move_lense;break;
182                         case 3:
183                                 st->radius=50;st->number=4;st->speed=1;st->vortex=1;st->magnify=1;
184                                 st->effect=&move_lense;break;
185                         case 4:
186                                 st->radius=50;st->number=4;st->speed=1;st->vortex=1;st->magnify=1;st->blackhole=1;
187                                 st->effect=&move_lense;break;
188                         case 5:
189                                 st->radius=100;st->number=1;st->speed=2;
190                                 st->effect=&move_lense;break;
191                         case 6:
192                                 st->radius=100;st->number=1;st->speed=2;st->blackhole=1;
193                                 st->effect=&move_lense;break;
194                         case 7:
195                                 st->radius=100;st->number=1;st->speed=2;st->vortex=1;
196                                 st->effect=&move_lense;break;
197                         case 8:
198                                 st->radius=100;st->number=1;st->speed=2;st->vortex=1;st->magnify=1;
199                                 st->effect=&move_lense;break;
200                         case 9:
201                                 st->radius=100;st->number=1;st->speed=2;st->vortex=1;st->magnify=1;st->blackhole=1;
202                                 st->effect=&move_lense;break;
203
204                         case 10:
205                                 st->radius=80;st->number=1;st->speed=2;st->reflect=1;
206                                 st->draw = &reflect_draw;st->effect = &move_lense;break;
207                         case 11:
208                                 st->radius=50;st->number=4;st->speed=2;st->reflect=1;
209                                 st->draw = &reflect_draw;st->effect = &move_lense;break;
210
211 #if 0 /* jwz: not these */
212                         case 12:
213                                 st->radius=50;st->number=4;st->speed=2;
214                                 effect=&swamp_thing;break;
215                         case 13:
216                                 st->radius=50;st->number=4;st->speed=2;st->blackhole=1;
217                                 effect=&swamp_thing;break;
218                         case 14:
219                                 st->radius=50;st->number=4;st->speed=2;st->vortex=1;
220                                 effect=&swamp_thing;break;
221                         case 15:
222                                 st->radius=50;st->number=4;st->speed=2;st->vortex=1;st->magnify=1;
223                                 effect=&swamp_thing;break;
224                         case 16:
225                                 st->radius=50;st->number=4;st->speed=2;st->vortex=1;st->magnify=1;st->blackhole=1;
226                                 effect=&swamp_thing;break;
227 #endif
228
229             default:
230                 abort(); break;
231                 }
232
233         /* but if the window is small, reduce default radius */
234         if (st->xgwa.width < st->radius * 8)
235           st->radius = st->xgwa.width/8;
236         }
237
238     /* never allow the radius to be too close to the min window dimension
239      */
240     if (st->radius >= st->xgwa.width  * 0.45) st->radius = st->xgwa.width  * 0.45;
241     if (st->radius >= st->xgwa.height * 0.45) st->radius = st->xgwa.height * 0.45;
242
243
244     /* -swamp mode consumes vast amounts of memory, proportional to radius --
245        so throttle radius to a small-ish value (60 => ~30MB.)
246      */
247     if (st->effect == &swamp_thing && st->radius > 60)
248       st->radius = 60;
249
250         if (st->delay < 0)
251                 st->delay = 0;
252         if (st->radius <= 0)
253                 st->radius = 60;
254         if (st->speed <= 0) 
255                 st->speed = 2;
256         if (st->number <= 0)
257                 st->number=1;
258         if (st->number >= 10)
259                 st->number=1;
260         if (st->effect == NULL)
261                 st->effect = &move_lense;
262         if (st->reflect) {
263                 st->draw = &reflect_draw;
264                 st->effect = &move_lense;
265         }
266         if (st->draw == NULL)
267                 st->draw = &plain_draw;
268
269         st->black_pixel = BlackPixelOfScreen( st->xgwa.screen );
270
271         gcv.function = GXcopy;
272         gcv.subwindow_mode = IncludeInferiors;
273         gcflags = GCFunction;
274         if (use_subwindow_mode_p(st->xgwa.screen, st->window)) /* see grabscreen.c */
275                 gcflags |= GCSubwindowMode;
276         st->gc = XCreateGC (st->dpy, st->window, gcflags, &gcv);
277
278     st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
279                                               st->window, 0, 0);
280     return st;
281 }
282
283 static void
284 distort_finish_loading (struct state *st)
285 {
286     int i;
287
288         st->buffer_map = 0;
289         st->orig_map = XGetImage(st->dpy, st->window, 0, 0, st->xgwa.width, st->xgwa.height,
290                                                  ~0L, ZPixmap);
291         st->buffer_map_cache = malloc(sizeof(unsigned long)*(2*st->radius+st->speed+2)*(2*st->radius+st->speed+2));
292
293         if (st->buffer_map_cache == NULL) {
294                 perror("distort");
295                 exit(EXIT_FAILURE);
296         }
297
298 # ifdef HAVE_XSHM_EXTENSION
299
300         if (st->use_shm)
301           {
302                 st->buffer_map = create_xshm_image(st->dpy, st->xgwa.visual, st->orig_map->depth,
303                                                                            ZPixmap, 0, &st->shm_info,
304                                                                            2*st->radius + st->speed + 2,
305                                                                            2*st->radius + st->speed + 2);
306                 if (!st->buffer_map)
307                   st->use_shm = False;
308           }
309 # endif /* HAVE_XSHM_EXTENSION */
310
311         if (!st->buffer_map)
312           {
313                 st->buffer_map = XCreateImage(st->dpy, st->xgwa.visual,
314                                                                   st->orig_map->depth, ZPixmap, 0, 0,
315                                                                   2*st->radius + st->speed + 2, 2*st->radius + st->speed + 2,
316                                                                   8, 0);
317                 st->buffer_map->data = (char *)
318                   calloc(st->buffer_map->height, st->buffer_map->bytes_per_line);
319         }
320
321         if ((st->buffer_map->byte_order == st->orig_map->byte_order)
322                         && (st->buffer_map->depth == st->orig_map->depth)
323                         && (st->buffer_map->format == ZPixmap)
324                         && (st->orig_map->format == ZPixmap)
325                         && !st->slow) {
326                 switch (st->orig_map->bits_per_pixel) {
327                         case 32:
328                                 st->draw_routine = &fast_draw_32;
329                                 st->bpp_size = sizeof(CARD32);
330                                 break;
331                         case 16:
332                                 st->draw_routine = &fast_draw_16;
333                                 st->bpp_size = sizeof(CARD16);
334                                 break;
335                         case 8:
336                                 st->draw_routine = &fast_draw_8;
337                                 st->bpp_size = sizeof(CARD8);
338                                 break;
339                         default:
340                                 st->draw_routine = &generic_draw;
341                                 break;
342                 }
343         } else {
344                 st->draw_routine = &generic_draw;
345         }
346         init_round_lense(st);
347
348         for (i = 0; i < st->number; i++) {
349                 new_rnd_coo(st,i);
350                 if (st->number != 1)
351                         st->xy_coo[i].r = (i*st->radius)/(st->number-1); /* "randomize" initial */
352                 else
353                          st->xy_coo[i].r = 0;
354                 st->xy_coo[i].r_change = st->speed + (i%2)*2*(-st->speed);      /* values a bit */
355                 st->xy_coo[i].xmove = st->speed + (i%2)*2*(-st->speed);
356                 st->xy_coo[i].ymove = st->speed + (i%2)*2*(-st->speed);
357         }
358 }
359
360 /* example: initializes a "see-trough" matrix */
361 /* static void make_null_lense(struct state *st)
362 {
363         int i, j;
364         for (i = 0; i < 2*radius+speed+2; i++) {
365                 for (j = 0 ; j < 2*radius+speed+2 ; j++) {
366                         from[i][j][0]=i;
367                         from[i][j][1]=j;
368                 }
369         } 
370 }
371 */
372 static void convert(struct state *st) 
373 {
374         int *p;
375         int i, j;
376         st->fast_from = calloc(1, sizeof(int)*((st->buffer_map->bytes_per_line/st->bpp_size)*(2*st->radius+st->speed+2) + 2*st->radius+st->speed+2));
377         if (st->fast_from == NULL) {
378                 perror("distort");
379                 exit(EXIT_FAILURE);
380         }
381         p = st->fast_from;
382         for (i = 0; i < 2*st->radius+st->speed+2; i++) {
383                 for (j = 0; j < 2*st->radius+st->speed+2; j++) {
384                         *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size)
385                                 = st->from[i][j][0] + st->xgwa.width*st->from[i][j][1];
386                         if (*(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) < 0
387                                         || *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) >= st->orig_map->height*st->orig_map->width) {
388                                 *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) = 0;
389                         }
390                 }
391         }
392 }
393
394 /* makes a lense with the Radius=loop and centred in
395  * the point (radius, radius)
396  */
397 static void make_round_lense(struct state *st, int radius, int loop)
398 {
399         int i, j;
400
401         for (i = 0; i < 2*radius+st->speed+2; i++) {
402                 for(j = 0; j < ((0 == st->bpp_size) ? (2*radius+st->speed+2) : (st->buffer_map->bytes_per_line/st->bpp_size)); j++) {
403                         double r, d;
404                         r = sqrt ((i-radius)*(i-radius)+(j-radius)*(j-radius));
405                         if (loop == 0)
406                           d=0.0;
407                         else
408                           d=r/loop;
409
410                         if (r < loop-1) {
411
412                                 if (st->vortex) { /* vortex-twist effect */
413                                         double angle;
414                 /* this one-line formula for getting a nice rotation angle is borrowed
415                  * (with permission) from the whirl plugin for gimp,
416                  * Copyright (C) 1996 Federico Mena Quintero
417                  */
418                 /* 5 is just a constant used because it looks good :) */
419                                         angle = 5*(1-d)*(1-d);
420
421         /* Avoid atan2: DOMAIN error message */
422                                         if ((radius-j) == 0.0 && (radius-i) == 0.0) {
423                                                 st->from[i][j][0] = radius + cos(angle)*r;
424                                                 st->from[i][j][1] = radius + sin(angle)*r;
425                                         } else {
426                                                 st->from[i][j][0] = radius +
427                                                         cos(angle - atan2(radius-j, -(radius-i)))*r;
428                                                 st->from[i][j][1] = radius +
429                                                         sin(angle - atan2(radius-j, -(radius-i)))*r;
430                                         }
431                                         if (st->magnify) {
432                                                 r = sin(d*M_PI_2);
433                                                 if (st->blackhole && r != 0) /* blackhole effect */
434                                                         r = 1/r;
435                                                 st->from[i][j][0] = radius + (st->from[i][j][0]-radius)*r;
436                                                 st->from[i][j][1] = radius + (st->from[i][j][1]-radius)*r;
437                                         }
438                                 } else { /* default is to magnify */
439                                         r = sin(d*M_PI_2);
440                                 
441         /* raising r to different power here gives different amounts of
442          * distortion, a negative value sucks everything into a black hole
443          */
444                                 /*      r = r*r; */
445                                         if (st->blackhole && r != 0) /* blackhole effect */
446                                                 r = 1/r;
447                                                                         /* bubble effect (and blackhole) */
448                                         st->from[i][j][0] = radius + (i-radius)*r;
449                                         st->from[i][j][1] = radius + (j-radius)*r;
450                                 }
451                         } else { /* not inside loop */
452                                 st->from[i][j][0] = i;
453                                 st->from[i][j][1] = j;
454                         }
455                 }
456         }
457
458         /* this is really just a quick hack to keep both the compability mode with all depths and still
459          * allow the custom optimized draw routines with the minimum amount of work */
460         if (0 != st->bpp_size) {
461                 convert(st);
462         }
463 }
464
465 #ifndef EXIT_FAILURE
466 # define EXIT_FAILURE -1
467 #endif
468
469 static void allocate_lense(struct state *st)
470 {
471         int i, j;
472         int s = ((0 != st->bpp_size) ? (st->buffer_map->bytes_per_line/st->bpp_size) : (2*st->radius+st->speed+2));
473         /* maybe this should be redone so that from[][][] is in one block;
474          * then pointers could be used instead of arrays in some places (and
475          * maybe give a speedup - maybe also consume less memory)
476          */
477         st->from = (int ***)malloc(s*sizeof(int **));
478         if (st->from == NULL) {
479                 perror("distort");
480                 exit(EXIT_FAILURE);
481         }
482         for (i = 0; i < s; i++) {
483                 st->from[i] = (int **)malloc((2*st->radius+st->speed+2) * sizeof(int *));
484                 if (st->from[i] == NULL) {
485                         perror("distort");
486                         exit(EXIT_FAILURE);
487                 }
488                 for (j = 0; j < s; j++) {
489                         st->from[i][j] = (int *)malloc(2 * sizeof(int));
490                         if (st->from[i][j] == NULL) {
491                                 perror("distort");
492                                 exit(EXIT_FAILURE);
493                         }
494                 }
495         }
496 }
497
498 /* from_array in an array containing precalculated from matrices,
499  * this is a double faced mem vs speed trade, it's faster, but eats
500  * _a lot_ of mem for large radius (is there a bug here? I can't see it)
501  */
502 static void init_round_lense(struct state *st)
503 {
504         int k;
505
506         if (st->effect == &swamp_thing) {
507                 st->from_array = (int ****)malloc((st->radius+1)*sizeof(int ***));
508                 for (k=0; k <= st->radius; k++) {
509                         allocate_lense(st);
510                         make_round_lense(st, st->radius, k);
511                         st->from_array[k] = st->from;
512                 }
513         } else { /* just allocate one from[][][] */
514                 allocate_lense(st);
515                 make_round_lense(st, st->radius,st->radius);
516         }
517 }
518
519 /* If fast_draw_8, fast_draw_16 or fast_draw_32 are to be used, the following properties
520  * of the src and dest XImages must hold (otherwise the generic, slooow, method provided
521  * by X is to be used):
522  *      src->byte_order == dest->byte_order
523  *      src->format == ZPixmap && dest->format == ZPixmap
524  *      src->depth == dest->depth == the depth the function in question asumes
525  * x and y is the coordinates in src from where to cut out the image from,
526  * distort_matrix is a precalculated array of how to distort the matrix
527  */
528
529 static void fast_draw_8(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
530 {
531         CARD8 *u = (CARD8 *)dest->data;
532         CARD8 *t = (CARD8 *)src->data + x + y*src->bytes_per_line/sizeof(CARD8);
533
534         while (u < (CARD8 *)(dest->data + sizeof(CARD8)*dest->height
535                                 *dest->bytes_per_line/sizeof(CARD8))) {
536                 *u++ = t[*distort_matrix++];
537         }
538 }
539
540 static void fast_draw_16(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
541 {
542         CARD16 *u = (CARD16 *)dest->data;
543         CARD16 *t = (CARD16 *)src->data + x + y*src->bytes_per_line/sizeof(CARD16);
544
545         while (u < (CARD16 *)(dest->data + sizeof(CARD16)*dest->height
546                                 *dest->bytes_per_line/sizeof(CARD16))) {
547                 *u++ = t[*distort_matrix++];
548         }
549 }
550
551 static void fast_draw_32(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
552 {
553         CARD32 *u = (CARD32 *)dest->data;
554         CARD32 *t = (CARD32 *)src->data + x + y*src->bytes_per_line/sizeof(CARD32);
555
556         while (u < (CARD32 *)(dest->data + sizeof(CARD32)*dest->height
557                                 *dest->bytes_per_line/sizeof(CARD32))) {
558                 *u++ = t[*distort_matrix++];
559         }
560 }
561
562 static void generic_draw(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
563 {
564         int i, j;
565         for (i = 0; i < dest->width; i++)
566                 for (j = 0; j < dest->height; j++)
567                         if (st->from[i][j][0] + x >= 0 &&
568                                         st->from[i][j][0] + x < src->width &&
569                                         st->from[i][j][1] + y >= 0 &&
570                                         st->from[i][j][1] + y < src->height)
571                                 XPutPixel(dest, i, j,
572                                                 XGetPixel(src,
573                                                         st->from[i][j][0] + x,
574                                                         st->from[i][j][1] + y));
575 }
576
577 /* generate an XImage of from[][][] and draw it on the screen */
578 static void plain_draw(struct state *st, int k)
579 {
580         if (st->xy_coo[k].x+2*st->radius+st->speed+2 > st->orig_map->width ||
581                         st->xy_coo[k].y+2*st->radius+st->speed+2 > st->orig_map->height)
582                 return;
583
584         st->draw_routine(st, st->orig_map, st->buffer_map, st->xy_coo[k].x, st->xy_coo[k].y, st->fast_from);
585
586 # ifdef HAVE_XSHM_EXTENSION
587         if (st->use_shm)
588                 XShmPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
589                                 2*st->radius+st->speed+2, 2*st->radius+st->speed+2, False);
590         else
591
592         if (!st->use_shm)
593 # endif
594                 XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
595                                 2*st->radius+st->speed+2, 2*st->radius+st->speed+2);
596
597 }
598
599
600 /* generate an XImage from the reflect algoritm submitted by
601  * Randy Zack <randy@acucorp.com>
602  * draw really got too big and ugly so I split it up
603  * it should be possible to use the from[][] to speed it up
604  * (once I figure out the algorithm used :)
605  */
606 static void reflect_draw(struct state *st, int k)
607 {
608         int i, j;
609         int     cx, cy;
610         int     ly, lysq, lx, ny, dist, rsq = st->radius * st->radius;
611
612         cx = cy = st->radius;
613         if (st->xy_coo[k].ymove > 0)
614                 cy += st->speed;
615         if (st->xy_coo[k].xmove > 0)
616                 cx += st->speed;
617
618         for(i = 0 ; i < 2*st->radius+st->speed+2; i++) {
619                 ly = i - cy;
620                 lysq = ly * ly;
621                 ny = st->xy_coo[k].y + i;
622                 if (ny >= st->orig_map->height) ny = st->orig_map->height-1;
623                 for(j = 0 ; j < 2*st->radius+st->speed+2 ; j++) {
624                         lx = j - cx;
625                         dist = lx * lx + lysq;
626                         if (dist > rsq ||
627                                 ly < -st->radius || ly > st->radius ||
628                                 lx < -st->radius || lx > st->radius)
629                                 XPutPixel( st->buffer_map, j, i,
630                                                    XGetPixel( st->orig_map, st->xy_coo[k].x + j, ny ));
631                         else if (dist == 0)
632                                 XPutPixel( st->buffer_map, j, i, st->black_pixel );
633                         else {
634                                 int     x = st->xy_coo[k].x + cx + (lx * rsq / dist);
635                                 int     y = st->xy_coo[k].y + cy + (ly * rsq / dist);
636                                 if (x < 0 || x >= st->xgwa.width ||
637                                         y < 0 || y >= st->xgwa.height)
638                                         XPutPixel( st->buffer_map, j, i, st->black_pixel );
639                                 else
640                                         XPutPixel( st->buffer_map, j, i,
641                                                            XGetPixel( st->orig_map, x, y ));
642                         }
643                 }
644         }
645
646         XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
647                         2*st->radius+st->speed+2, 2*st->radius+st->speed+2);
648 }
649
650 /* create a new, random coordinate, that won't interfer with any other
651  * coordinates, as the drawing routines would be significantly slowed
652  * down if they were to handle serveral layers of distortions
653  */
654 static void new_rnd_coo(struct state *st, int k)
655 {
656         int i;
657
658         st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
659         st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
660         
661         for (i = 0; i < st->number; i++) {
662                 if (i != k) {
663                         if ((abs(st->xy_coo[k].x - st->xy_coo[i].x) <= 2*st->radius+st->speed+2)
664                          && (abs(st->xy_coo[k].y - st->xy_coo[i].y) <= 2*st->radius+st->speed+2)) {
665                                 st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
666                                 st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
667                                 i=-1; /* ugly */
668                         } 
669                 }
670         }
671 }
672
673 /* move lens and handle bounces with walls and other lenses */
674 static void move_lense(struct state *st, int k)
675 {
676         int i;
677
678         if (st->xy_coo[k].x + 2*st->radius + st->speed + 2 >= st->xgwa.width)
679                 st->xy_coo[k].xmove = -abs(st->xy_coo[k].xmove);
680         if (st->xy_coo[k].x <= st->speed) 
681                 st->xy_coo[k].xmove = abs(st->xy_coo[k].xmove);
682         if (st->xy_coo[k].y + 2*st->radius + st->speed + 2 >= st->xgwa.height)
683                 st->xy_coo[k].ymove = -abs(st->xy_coo[k].ymove);
684         if (st->xy_coo[k].y <= st->speed)
685                 st->xy_coo[k].ymove = abs(st->xy_coo[k].ymove);
686
687         st->xy_coo[k].x = st->xy_coo[k].x + st->xy_coo[k].xmove;
688         st->xy_coo[k].y = st->xy_coo[k].y + st->xy_coo[k].ymove;
689
690         /* bounce against othe lenses */
691         for (i = 0; i < st->number; i++) {
692                 if ((i != k)
693                 
694 /* This commented test is for rectangular lenses (not currently used) and
695  * the one used is for circular ones
696                 && (abs(xy_coo[k].x - xy_coo[i].x) <= 2*radius)
697                 && (abs(xy_coo[k].y - xy_coo[i].y) <= 2*radius)) { */
698
699                 && ((st->xy_coo[k].x - st->xy_coo[i].x)*(st->xy_coo[k].x - st->xy_coo[i].x)
700                   + (st->xy_coo[k].y - st->xy_coo[i].y)*(st->xy_coo[k].y - st->xy_coo[i].y)
701                         <= 2*st->radius*2*st->radius)) {
702
703                         int x, y;
704                         x = st->xy_coo[k].xmove;
705                         y = st->xy_coo[k].ymove;
706                         st->xy_coo[k].xmove = st->xy_coo[i].xmove;
707                         st->xy_coo[k].ymove = st->xy_coo[i].ymove;
708                         st->xy_coo[i].xmove = x;
709                         st->xy_coo[i].ymove = y;
710                 }
711         }
712
713 }
714
715 /* make xy_coo[k] grow/shrink */
716 static void swamp_thing(struct state *st, int k)
717 {
718         if (st->xy_coo[k].r >= st->radius)
719                 st->xy_coo[k].r_change = -abs(st->xy_coo[k].r_change);
720         
721         if (st->xy_coo[k].r <= 0) {
722                 st->from = st->from_array[0];
723                 st->draw(st,k); 
724                 st->xy_coo[k].r_change = abs(st->xy_coo[k].r_change);
725                 new_rnd_coo(st,k);
726                 st->xy_coo[k].r=st->xy_coo[k].r_change;
727                 return;
728         }
729
730         st->xy_coo[k].r = st->xy_coo[k].r + st->xy_coo[k].r_change;
731
732         if (st->xy_coo[k].r >= st->radius)
733                 st->xy_coo[k].r = st->radius;
734         if (st->xy_coo[k].r <= 0)
735                 st->xy_coo[k].r=0;
736
737         st->from = st->from_array[st->xy_coo[k].r];
738 }
739
740
741 static unsigned long
742 distort_draw (Display *dpy, Window window, void *closure)
743 {
744   struct state *st = (struct state *) closure;
745   int k;
746
747   if (st->img_loader)   /* still loading */
748     {
749       st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0, 0);
750       if (! st->img_loader)  /* just finished */
751         distort_finish_loading (st);
752       return st->delay;
753     }
754
755   for (k = 0; k < st->number; k++) {
756     st->effect(st,k);
757     st->draw(st,k);
758   }
759   return st->delay;
760 }
761
762 static void
763 distort_reshape (Display *dpy, Window window, void *closure, 
764                  unsigned int w, unsigned int h)
765 {
766 }
767
768 static Bool
769 distort_event (Display *dpy, Window window, void *closure, XEvent *event)
770 {
771   return False;
772 }
773
774 static void
775 distort_free (Display *dpy, Window window, void *closure)
776 {
777   struct state *st = (struct state *) closure;
778   XFreeGC (st->dpy, st->gc);
779   if (st->orig_map) XDestroyImage (st->orig_map);
780   if (st->buffer_map) XDestroyImage (st->buffer_map);
781   if (st->from) free (st->from);
782   if (st->fast_from) free (st->fast_from);
783   if (st->from_array) free (st->from_array);
784   free (st);
785 }
786
787
788 \f
789
790 static const char *distort_defaults [] = {
791         "*dontClearRoot:                True",
792         "*background:                   Black",
793 #ifdef __sgi    /* really, HAVE_READ_DISPLAY_EXTENSION */
794         "*visualID:                     Best",
795 #endif
796
797         "*delay:                        20000",
798         "*radius:                       0",
799         "*speed:                        0",
800         "*number:                       0",
801         "*slow:                         False",
802         "*vortex:                       False",
803         "*magnify:                      False",
804         "*reflect:                      False",
805         "*blackhole:            False",
806         "*effect:                   none",
807 #ifdef HAVE_XSHM_EXTENSION
808         "*useSHM:                       False",         /* xshm turns out not to help. */
809 #endif /* HAVE_XSHM_EXTENSION */
810         0
811 };
812
813 static XrmOptionDescRec distort_options [] = {
814   { "-delay",     ".delay",       XrmoptionSepArg, 0 },
815   { "-radius",    ".radius",      XrmoptionSepArg, 0 },
816   { "-speed",     ".speed",       XrmoptionSepArg, 0 },
817   { "-number",    ".number",      XrmoptionSepArg, 0 },
818
819   { "-effect",    ".effect",      XrmoptionSepArg, 0 },
820   { "-swamp",     ".effect",      XrmoptionNoArg, "swamp"  },
821   { "-bounce",    ".effect",      XrmoptionNoArg, "bounce" },
822
823   { "-reflect",   ".reflect",     XrmoptionNoArg, "True" },
824   { "-vortex",    ".vortex",      XrmoptionNoArg, "True" },
825   { "-magnify",   ".magnify",     XrmoptionNoArg, "True" },
826   { "-blackhole", ".blackhole",   XrmoptionNoArg, "True" },
827   { "-slow",      ".slow",        XrmoptionNoArg, "True" },
828 #ifdef HAVE_XSHM_EXTENSION
829   { "-shm",       ".useSHM",      XrmoptionNoArg, "True" },
830   { "-no-shm",    ".useSHM",      XrmoptionNoArg, "False" },
831 #endif /* HAVE_XSHM_EXTENSION */
832   { 0, 0, 0, 0 }
833 };
834
835 XSCREENSAVER_MODULE ("Distort", distort)