1 /* twang, twist around screen bits, v1.3
2 * by Dan Bornstein, danfuzz@milk.com
3 * Copyright (c) 2003 Dan Bornstein. All rights reserved.
5 * Permission to use, copy, modify, distribute, and sell this software and its
6 * documentation for any purpose is hereby granted without fee, provided that
7 * the above copyright notice appear in all copies and that both that
8 * copyright notice and this permission notice appear in supporting
9 * documentation. No representations are made about the suitability of this
10 * software for any purpose. It is provided "as is" without express or
13 * See the included man page for more details.
17 #include "screenhack.h"
22 /* random float in the range (-1..1) */
23 #define RAND_FLOAT_PM1 \
24 (((FLOAT) ((random() >> 8) & 0xffff)) / ((FLOAT) 0x10000) * 2 - 1)
26 /* random float in the range (0..1) */
27 #define RAND_FLOAT_01 \
28 (((FLOAT) ((random() >> 8) & 0xffff)) / ((FLOAT) 0x10000))
33 int x; /* x coordinate of the center of the tile */
34 int y; /* y coordinate of the center of the tile */
35 FLOAT angle; /* angle of the tile (-pi..pi) */
36 FLOAT zoom; /* log of the zoom of the tile (-1..1) */
37 FLOAT vAngle; /* angular velocity (-pi/4..pi/4) */
38 FLOAT vZoom; /* zoomular velocity (-0.25..0.25) */
47 int delay; /* delay (usec) between iterations */
48 int duration; /* time (sec) before loading new image */
49 int maxColumns; /* the maximum number of columns of tiles */
50 int maxRows; /* the maximum number of rows of tiles */
51 int tileSize; /* the size (width and height) of a tile */
52 int borderWidth; /* the width of the border around each tile */
53 FLOAT eventChance; /* the chance, per iteration, of an interesting event happening */
54 FLOAT friction; /* friction: the fraction (0..1) by which velocity decreased per iteration */
55 FLOAT springiness; /* springiness: the fraction (0..1) of the orientation that turns into velocity towards the center */
56 FLOAT transference; /* transference: the fraction (0..1) of the orientations of orthogonal neighbors that turns into velocity (in the same direction as the orientation) */
57 int windowWidth; /* width and height of the window */
59 Screen *screen; /* the screen to draw on */
60 XImage *sourceImage; /* image source of stuff to draw */
61 XImage *workImage; /* work area image, used when rendering */
63 GC backgroundGC; /* GC for the background color */
64 GC foregroundGC; /* GC for the foreground color */
65 GC borderGC; /* GC for the border color */
66 unsigned long backgroundPixel; /* background color as a pixel value */
67 unsigned long borderPixel; /* border color as a pixel value */
69 Tile *tiles; /* array of tiles (left->right, top->bottom, row major) */
70 int rows; /* number of rows of tiles */
71 int columns; /* number of columns of tiles */
73 Tile **sortedTiles; /* array of tile pointers, sorted by zoom */
74 int tileCount; /* total number of tiles */
77 async_load_state *img_loader;
80 XShmSegmentInfo shmInfo;
84 #define TILE_AT(col,row) (&st->tiles[(row) * st->columns + (col)])
86 #define MAX_VANGLE (M_PI / 4.0)
87 #define MAX_VZOOM 0.25
89 #define RAND_ANGLE (RAND_FLOAT_PM1 * M_PI)
90 #define RAND_ZOOM (RAND_FLOAT_PM1)
91 #define RAND_VANGLE (RAND_FLOAT_PM1 * MAX_VANGLE)
92 #define RAND_VZOOM (RAND_FLOAT_PM1 * MAX_VZOOM)
100 /* grab the source image */
102 grabImage_start (struct state *st, XWindowAttributes *xwa)
104 /* On MacOS X11, XGetImage on a Window often gets an inexplicable BadMatch,
105 possibly due to the window manager having occluded something? It seems
106 nondeterministic. Loading the image into a pixmap instead fixes it. */
107 if (st->pm) XFreePixmap (st->dpy, st->pm);
108 st->pm = XCreatePixmap (st->dpy, st->window,
109 xwa->width, xwa->height, xwa->depth);
111 st->start_time = time ((time_t *) 0);
112 st->img_loader = load_image_async_simple (0, xwa->screen, st->window,
117 grabImage_done (struct state *st)
119 XWindowAttributes xwa;
120 XGetWindowAttributes (st->dpy, st->window, &xwa);
122 st->start_time = time ((time_t *) 0);
123 if (st->sourceImage) XDestroyImage (st->sourceImage);
124 st->sourceImage = XGetImage (st->dpy, st->pm, 0, 0,
125 st->windowWidth, st->windowHeight,
128 if (st->workImage) destroy_xshm_image (st->dpy, st->workImage,
131 st->workImage = create_xshm_image (st->dpy, xwa.visual, xwa.depth,
132 ZPixmap, &st->shmInfo,
133 st->windowWidth, st->windowHeight);
136 /* set up the system */
137 static void setup (struct state *st)
139 XWindowAttributes xgwa;
142 XGetWindowAttributes (st->dpy, st->window, &xgwa);
144 st->screen = xgwa.screen;
145 st->windowWidth = xgwa.width;
146 st->windowHeight = xgwa.height;
148 gcv.line_width = st->borderWidth;
149 gcv.foreground = get_pixel_resource (st->dpy, xgwa.colormap,
150 "borderColor", "BorderColor");
151 st->borderPixel = gcv.foreground;
152 st->borderGC = XCreateGC (st->dpy, st->window, GCForeground | GCLineWidth,
155 gcv.foreground = get_pixel_resource (st->dpy, xgwa.colormap,
156 "background", "Background");
157 st->backgroundPixel = gcv.foreground;
158 st->backgroundGC = XCreateGC (st->dpy, st->window, GCForeground, &gcv);
160 gcv.foreground = get_pixel_resource (st->dpy, xgwa.colormap,
161 "foreground", "Foreground");
162 st->foregroundGC = XCreateGC (st->dpy, st->window, GCForeground, &gcv);
164 grabImage_start (st, &xgwa);
173 /* event: randomize all the angular velocities */
174 static void randomizeAllAngularVelocities (struct state *st)
179 for (r = 0; r < st->rows; r++)
181 for (c = 0; c < st->columns; c++)
183 TILE_AT (c, r)->vAngle = RAND_VANGLE;
188 /* event: randomize all the zoomular velocities */
189 static void randomizeAllZoomularVelocities (struct state *st)
194 for (r = 0; r < st->rows; r++)
196 for (c = 0; c < st->columns; c++)
198 TILE_AT (c, r)->vZoom = RAND_VZOOM;
203 /* event: randomize all the velocities */
204 static void randomizeAllVelocities (struct state *st)
206 randomizeAllAngularVelocities (st);
207 randomizeAllZoomularVelocities (st);
210 /* event: randomize all the angular orientations */
211 static void randomizeAllAngularOrientations (struct state *st)
216 for (r = 0; r < st->rows; r++)
218 for (c = 0; c < st->columns; c++)
220 TILE_AT (c, r)->angle = RAND_ANGLE;
225 /* event: randomize all the zoomular orientations */
226 static void randomizeAllZoomularOrientations (struct state *st)
231 for (r = 0; r < st->rows; r++)
233 for (c = 0; c < st->columns; c++)
235 TILE_AT (c, r)->zoom = RAND_ZOOM;
240 /* event: randomize all the orientations */
241 static void randomizeAllOrientations (struct state *st)
243 randomizeAllAngularOrientations (st);
244 randomizeAllZoomularOrientations (st);
247 /* event: randomize everything */
248 static void randomizeEverything (struct state *st)
250 randomizeAllVelocities (st);
251 randomizeAllOrientations (st);
254 /* event: pick one tile and randomize all its stats */
255 static void randomizeOneTile (struct state *st)
257 int c = RAND_FLOAT_01 * st->columns;
258 int r = RAND_FLOAT_01 * st->rows;
260 Tile *t = TILE_AT (c, r);
261 t->angle = RAND_ANGLE;
263 t->vAngle = RAND_VANGLE;
264 t->vZoom = RAND_VZOOM;
267 /* event: pick one row and randomize everything about each of its tiles */
268 static void randomizeOneRow (struct state *st)
271 int r = RAND_FLOAT_01 * st->rows;
273 for (c = 0; c < st->columns; c++)
275 Tile *t = TILE_AT (c, r);
276 t->angle = RAND_ANGLE;
278 t->vAngle = RAND_VANGLE;
279 t->vZoom = RAND_VZOOM;
283 /* event: pick one column and randomize everything about each of its tiles */
284 static void randomizeOneColumn (struct state *st)
286 int c = RAND_FLOAT_01 * st->columns;
289 for (r = 0; r < st->rows; r++)
291 Tile *t = TILE_AT (c, r);
292 t->angle = RAND_ANGLE;
294 t->vAngle = RAND_VANGLE;
295 t->vZoom = RAND_VZOOM;
299 /* do model event processing */
300 static void modelEvents (struct state *st)
304 if (RAND_FLOAT_01 > st->eventChance)
309 which = RAND_FLOAT_01 * 10;
313 case 0: randomizeAllAngularVelocities (st); break;
314 case 1: randomizeAllZoomularVelocities (st); break;
315 case 2: randomizeAllVelocities (st); break;
316 case 3: randomizeAllAngularOrientations (st); break;
317 case 4: randomizeAllZoomularOrientations (st); break;
318 case 5: randomizeAllOrientations (st); break;
319 case 6: randomizeEverything (st); break;
320 case 7: randomizeOneTile (st); break;
321 case 8: randomizeOneColumn (st); break;
322 case 9: randomizeOneRow (st); break;
326 /* update the model for one iteration */
327 static void updateModel (struct state *st)
332 /* for each tile, decrease its velocities according to the friction,
333 * and increase them based on its current orientation and the orientations
334 * of its orthogonal neighbors */
335 for (r = 0; r < st->rows; r++)
337 for (c = 0; c < st->columns; c++)
339 Tile *t = TILE_AT (c, r);
342 FLOAT va = t->vAngle;
345 va -= t->angle * st->springiness;
346 vz -= t->zoom * st->springiness;
350 Tile *t2 = TILE_AT (c - 1, r);
351 va += (t2->angle - a) * st->transference;
352 vz += (t2->zoom - z) * st->transference;
355 if (c < (st->columns - 1))
357 Tile *t2 = TILE_AT (c + 1, r);
358 va += (t2->angle - a) * st->transference;
359 vz += (t2->zoom - z) * st->transference;
364 Tile *t2 = TILE_AT (c, r - 1);
365 va += (t2->angle - a) * st->transference;
366 vz += (t2->zoom - z) * st->transference;
369 if (r < (st->rows - 1))
371 Tile *t2 = TILE_AT (c, r + 1);
372 va += (t2->angle - a) * st->transference;
373 vz += (t2->zoom - z) * st->transference;
376 va *= (1.0 - st->friction);
377 vz *= (1.0 - st->friction);
379 if (va > MAX_VANGLE) va = MAX_VANGLE;
380 else if (va < -MAX_VANGLE) va = -MAX_VANGLE;
383 if (vz > MAX_VZOOM) vz = MAX_VZOOM;
384 else if (vz < -MAX_VZOOM) vz = -MAX_VZOOM;
389 /* for each tile, update its orientation based on its velocities */
390 for (r = 0; r < st->rows; r++)
392 for (c = 0; c < st->columns; c++)
394 Tile *t = TILE_AT (c, r);
395 FLOAT a = t->angle + t->vAngle;
396 FLOAT z = t->zoom + t->vZoom;
398 if (a > M_PI) a = M_PI;
399 else if (a < -M_PI) a = -M_PI;
402 if (z > 1.0) z = 1.0;
403 else if (z < -1.0) z = -1.0;
409 /* the comparator to us to sort the tiles (used immediately below); it'd
410 * sure be nice if C allowed inner functions (or jeebus-forbid *real
412 static int sortTilesComparator (const void *v1, const void *v2)
414 Tile *t1 = *(Tile **) v1;
415 Tile *t2 = *(Tile **) v2;
417 if (t1->zoom < t2->zoom)
422 if (t1->zoom > t2->zoom)
430 /* sort the tiles in sortedTiles by zoom */
431 static void sortTiles (struct state *st)
433 qsort (st->sortedTiles, st->tileCount, sizeof (Tile *), sortTilesComparator);
436 /* render the given tile */
437 static void renderTile (struct state *st, Tile *t)
439 /* note: the zoom as stored per tile is log-based (centered on 0, with
440 * 0 being no zoom, but the range for zoom-as-drawn is 0.4..2.5,
441 * hence the alteration of t->zoom, below */
448 FLOAT zoom = pow (2.5, t->zoom);
449 FLOAT ang = -t->angle;
450 FLOAT sinAng = sin (ang);
451 FLOAT cosAng = cos (ang);
453 FLOAT innerBorder = (st->tileSize - st->borderWidth) / 2.0;
454 FLOAT outerBorder = innerBorder + st->borderWidth;
456 int maxCoord = outerBorder * zoom * (fabs (sinAng) + fabs (cosAng));
457 int minX = tx - maxCoord;
458 int maxX = tx + maxCoord;
459 int minY = ty - maxCoord;
460 int maxY = ty + maxCoord;
464 if (minX < 0) minX = 0;
465 if (maxX > st->windowWidth) maxX = st->windowWidth;
466 if (minY < 0) minY = 0;
467 if (maxY > st->windowHeight) maxY = st->windowHeight;
472 for (y = minY, prey = y - ty; y < maxY; y++, prey++)
474 FLOAT prex = minX - tx;
475 FLOAT srcx = prex * cosAng - prey * sinAng;
476 FLOAT srcy = prex * sinAng + prey * cosAng;
480 x++, srcx += cosAng, srcy += sinAng)
482 if ((srcx < -innerBorder) || (srcx >= innerBorder) ||
483 (srcy < -innerBorder) || (srcy >= innerBorder))
485 if ((srcx < -outerBorder) || (srcx >= outerBorder) ||
486 (srcy < -outerBorder) || (srcy >= outerBorder))
490 XPutPixel (st->workImage, x, y, st->borderPixel);
495 XGetPixel (st->sourceImage, srcx + tx, srcy + ty);
496 XPutPixel (st->workImage, x, y, p);
502 /* render and display the current model */
503 static void renderFrame (struct state *st)
507 /* This assumes black is zero. */
508 memset (st->workImage->data, 0,
509 st->workImage->bytes_per_line * st->workImage->height);
513 for (n = 0; n < st->tileCount; n++)
515 renderTile (st, st->sortedTiles[n]);
518 put_xshm_image (st->dpy, st->window, st->backgroundGC, st->workImage, 0, 0, 0, 0,
519 st->windowWidth, st->windowHeight, &st->shmInfo);
522 /* set up the model */
523 static void setupModel (struct state *st)
528 int leftX; /* x of the center of the top-left tile */
529 int topY; /* y of the center of the top-left tile */
531 if (st->tileSize > (st->windowWidth / 2))
533 st->tileSize = st->windowWidth / 2;
536 if (st->tileSize > (st->windowHeight / 2))
538 st->tileSize = st->windowHeight / 2;
541 st->columns = st->tileSize ? st->windowWidth / st->tileSize : 0;
542 st->rows = st->tileSize ? st->windowHeight / st->tileSize : 0;
544 if ((st->maxColumns != 0) && (st->columns > st->maxColumns))
546 st->columns = st->maxColumns;
549 if ((st->maxRows != 0) && (st->rows > st->maxRows))
551 st->rows = st->maxRows;
554 st->tileCount = st->rows * st->columns;
556 leftX = (st->windowWidth - (st->columns * st->tileSize) + st->tileSize) / 2;
557 topY = (st->windowHeight - (st->rows * st->tileSize) + st->tileSize) / 2;
559 if (st->tileCount < 1) st->tileCount = 1;
560 st->tiles = calloc (st->tileCount, sizeof (Tile));
561 st->sortedTiles = calloc (st->tileCount, sizeof (Tile *));
563 for (r = 0; r < st->rows; r++)
565 for (c = 0; c < st->columns; c++)
567 Tile *t = TILE_AT (c, r);
568 t->x = leftX + c * st->tileSize;
569 t->y = topY + r * st->tileSize;
570 st->sortedTiles[c + r * st->columns] = t;
574 randomizeEverything (st);
577 /* do one iteration */
580 twang_draw (Display *dpy, Window window, void *closure)
582 struct state *st = (struct state *) closure;
584 if (st->img_loader) /* still loading */
586 st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0, 0);
587 if (! st->img_loader) { /* just finished */
593 if (!st->img_loader &&
594 st->start_time + st->duration < time ((time_t *) 0)) {
595 XWindowAttributes xgwa;
596 XGetWindowAttributes (st->dpy, st->window, &xgwa);
597 grabImage_start (st, &xgwa);
609 twang_reshape (Display *dpy, Window window, void *closure,
610 unsigned int w, unsigned int h)
615 twang_event (Display *dpy, Window window, void *closure, XEvent *event)
617 struct state *st = (struct state *) closure;
618 if (screenhack_event_helper (dpy, window, event))
627 twang_free (Display *dpy, Window window, void *closure)
629 struct state *st = (struct state *) closure;
630 if (st->pm) XFreePixmap (dpy, st->pm);
636 /* main and options and stuff */
638 /* initialize the user-specifiable params */
639 static void initParams (struct state *st)
643 st->borderWidth = get_integer_resource (st->dpy, "borderWidth", "Integer");
644 if (st->borderWidth < 0)
646 fprintf (stderr, "error: border width must be at least 0\n");
650 st->delay = get_integer_resource (st->dpy, "delay", "Delay");
653 fprintf (stderr, "error: delay must be at least 0\n");
657 st->duration = get_integer_resource (st->dpy, "duration", "Seconds");
658 if (st->duration < 1) st->duration = 1;
660 st->eventChance = get_float_resource (st->dpy, "eventChance", "Double");
661 if ((st->eventChance < 0.0) || (st->eventChance > 1.0))
663 fprintf (stderr, "error: eventChance must be in the range 0..1\n");
667 st->friction = get_float_resource (st->dpy, "friction", "Double");
668 if ((st->friction < 0.0) || (st->friction > 1.0))
670 fprintf (stderr, "error: friction must be in the range 0..1\n");
674 st->maxColumns = get_integer_resource (st->dpy, "maxColumns", "Integer");
675 if (st->maxColumns < 0)
677 fprintf (stderr, "error: max columns must be at least 0\n");
681 st->maxRows = get_integer_resource (st->dpy, "maxRows", "Integer");
684 fprintf (stderr, "error: max rows must be at least 0\n");
688 st->springiness = get_float_resource (st->dpy, "springiness", "Double");
689 if ((st->springiness < 0.0) || (st->springiness > 1.0))
691 fprintf (stderr, "error: springiness must be in the range 0..1\n");
695 st->tileSize = get_integer_resource (st->dpy, "tileSize", "Integer");
696 if (st->tileSize < 1)
698 fprintf (stderr, "error: tile size must be at least 1\n");
702 st->transference = get_float_resource (st->dpy, "transference", "Double");
703 if ((st->transference < 0.0) || (st->transference > 1.0))
705 fprintf (stderr, "error: transference must be in the range 0..1\n");
716 twang_init (Display *dpy, Window win)
718 struct state *st = (struct state *) calloc (1, sizeof(*st));
730 static const char *twang_defaults [] = {
731 ".background: black",
732 ".foreground: white",
733 "*borderColor: blue",
737 "*eventChance: 0.01",
743 "*transference: 0.025",
744 #ifdef HAVE_XSHM_EXTENSION
750 "*ignoreRotation: True",
751 "*rotateImages: True",
756 static XrmOptionDescRec twang_options [] = {
757 { "-border-color", ".borderColor", XrmoptionSepArg, 0 },
758 { "-border-width", ".borderWidth", XrmoptionSepArg, 0 },
759 { "-delay", ".delay", XrmoptionSepArg, 0 },
760 { "-duration", ".duration", XrmoptionSepArg, 0 },
761 { "-event-chance", ".eventChance", XrmoptionSepArg, 0 },
762 { "-friction", ".friction", XrmoptionSepArg, 0 },
763 { "-max-columns", ".maxColumns", XrmoptionSepArg, 0 },
764 { "-max-rows", ".maxRows", XrmoptionSepArg, 0 },
765 { "-springiness", ".springiness", XrmoptionSepArg, 0 },
766 { "-tile-size", ".tileSize", XrmoptionSepArg, 0 },
767 { "-transference", ".transference", XrmoptionSepArg, 0 },
768 { "-shm", ".useSHM", XrmoptionNoArg, "True" },
769 { "-no-shm", ".useSHM", XrmoptionNoArg, "False" },
774 XSCREENSAVER_MODULE ("Twang", twang)