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