1 /* epicycle --- The motion of a body with epicycles, as in the pre-Copernican
4 * Copyright (c) 1998 James Youngman <jay@gnu.org>
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that
9 * copyright notice and this permission notice appear in supporting
10 * documentation. No representations are made about the suitability of this
11 * software for any purpose. It is provided "as is" without express or
15 /* Standard C headers; screenhack.h assumes that these have already
16 * been included if required -- for example, it defines M_PI if not
23 #include "screenhack.h"
26 /* MIT-SHM headers omitted; this screenhack doesn't use it */
30 /*********************************************************/
31 /******************** MAGIC CONSTANTS ********************/
32 /*********************************************************/
33 #define MIN_RADIUS (5) /* smallest allowable circle radius */
34 #define FILL_PROPORTION (0.9) /* proportion of screen to fill by scaling. */
35 /*********************************************************/
36 /***************** END OF MAGIC CONSTANTS ****************/
37 /*********************************************************/
41 #define FULLCIRCLE (2.0 * M_PI) /* radians in a circle. */
44 /* Name of the Screensaver hack */
45 char *progclass="Epicycle";
47 /* Some of these resource values here are hand-tuned to give a
48 * pleasing variety of interesting shapes. These are not the only
49 * good settings, but you may find you need to change some as a group
50 * to get pleasing figures.
66 "*timestepCoarseFactor: 1.0", /* no option for this resource. */
67 "*divisorPoisson: 0.4",
68 "*sizeFactorMin: 1.05",
69 "*sizeFactorMax: 2.05",
73 /* options passed to this program */
74 XrmOptionDescRec options [] = {
75 { "-color0", ".color0", XrmoptionSepArg, 0 },
76 { "-colors", ".colors", XrmoptionSepArg, 0 },
77 { "-colours", ".colors", XrmoptionSepArg, 0 },
78 { "-foreground", ".foreground", XrmoptionSepArg, 0 },
79 { "-delay", ".delay", XrmoptionSepArg, 0 },
80 { "-holdtime", ".holdtime", XrmoptionSepArg, 0 },
81 { "-linewidth", ".lineWidth", XrmoptionSepArg, 0 },
82 { "-min_circles", ".minCircles", XrmoptionSepArg, 0 },
83 { "-max_circles", ".maxCircles", XrmoptionSepArg, 0 },
84 { "-min_speed", ".minSpeed", XrmoptionSepArg, 0 },
85 { "-max_speed", ".maxSpeed", XrmoptionSepArg, 0 },
86 { "-harmonics", ".harmonics", XrmoptionSepArg, 0 },
87 { "-timestep", ".timestep", XrmoptionSepArg, 0 },
88 { "-divisor_poisson",".divisorPoisson",XrmoptionSepArg, 0 },
89 { "-size_factor_min", ".sizeFactorMin", XrmoptionSepArg, 0 },
90 { "-size_factor_max", ".sizeFactorMax", XrmoptionSepArg, 0 },
98 static int width, height;
99 static int x_offset, y_offset;
100 static int unit_pixels;
101 static unsigned long bg;
102 static Colormap cmap;
103 static int restart = 0;
105 static double wdot_max;
106 static XColor *colors = NULL;
107 static int ncolors = 2;
108 static int color_shift_pos=0; /* how far we are towards that. */
109 static double colour_cycle_rate = 1.0;
110 static int harmonics = 8;
111 static double divisorPoisson = 0.4;
112 static double sizeFactorMin = 1.05;
113 static double sizeFactorMax = 2.05;
114 static int minCircles;
115 static int maxCircles;
117 /* Each circle is centred on a point on the rim of another circle.
121 long radius; /* in pixels */
122 double w; /* position (radians ccw from x-axis) */
123 double initial_w; /* starting position */
124 double wdot; /* rotation rate (change in w per iteration) */
127 struct tagCircle *pchild;
129 typedef struct tagCircle Circle;
132 struct tagBody /* a body that moves on a system of circles. */
134 int x_origin, y_origin;
137 int current_color; /* pixel index into colors[] */
138 Circle *epicycles; /* system of circles on which it moves. */
139 struct tagBody *next; /* next in list. */
141 typedef struct tagBody Body;
144 /* Determine the GCD of two numbers using Euclid's method. The other
145 * possible algorighm is Stein's method, but it's probably only going
146 * to be much faster on machines with no divide instruction, like the
147 * ARM and the Z80. The former is very fast anyway and the latter
148 * probably won't run X clients; in any case, this calculation is not
149 * the bulk of the computational expense of the program. I originally
150 * tried using Stein's method, but I wanted to remove the gotos. Not
151 * wanting to introduce possible bugs, I plumped for Euclid's method
152 * instead. Lastly, Euclid's algorithm is preferred to the
153 * generalisation for N inputs.
155 * See Knuth, section 4.5.2.
158 gcd(int u, int v) /* Euclid's Method */
160 /* If either operand of % is negative, the sign of the result is
161 * implementation-defined. See section 6.3.5 "Multiplicative
162 * Operators" of the ANSI C Standard (page 46 [LEFT HAND PAGE!] of
163 * "Annotated C Standard", Osborne, ISBN 0-07-881952-0).
178 /* Determine the Lowest Common Multiple of two integers, using
179 * Euclid's Proposition 34, as explained in Knuth's The Art of
180 * Computer Programming, Vol 2, section 4.5.2.
185 return u / gcd(u,v) * v;
189 random_radius(double scale)
193 r = frand(scale) * unit_pixels/2; /* for frand() see utils/yarandom.h */
206 while (frand(1.0) < divisorPoisson && divisor <= harmonics)
210 sign = (frand(1.0) < 0.5) ? +1 : -1;
211 return sign * divisor;
218 fprintf(stderr, "Failed to allocate memory!\n");
223 /* Construct a circle or die.
226 new_circle(double scale)
228 Circle *p = malloc(sizeof(Circle));
230 p->radius = random_radius(scale);
231 p->w = p->initial_w = 0.0;
232 p->divisor = random_divisor();
233 p->wdot = wdot_max / p->divisor;
239 static void delete_circle(Circle *p)
245 delete_circle_chain(Circle *p)
249 Circle *q = p->pchild;
256 new_circle_chain(void)
259 double scale = 1.0, factor;
262 /* Parent circles are larger than their children by a factor of at
263 * least FACTOR_MIN and at most FACTOR_MAX.
265 factor = sizeFactorMin + frand(sizeFactorMax - sizeFactorMin);
267 /* There are between minCircles and maxCircles in each figure.
269 n = minCircles + rand() % (maxCircles - minCircles);
274 Circle *p = new_circle(scale);
284 assign_random_common_w(Circle *p)
286 double w_common = frand(FULLCIRCLE); /* anywhere on the circle */
289 p->initial_w = w_common;
297 Body *p = malloc(sizeof(Body));
300 p->epicycles = new_circle_chain();
301 p->current_color = 0; /* ?? start them all on different colors? */
304 p->old_x = p->old_y = 0;
305 p->x_origin = p->y_origin = 0;
307 /* Start all the epicycles at the same w value to make it easier to
308 * figure out at what T value the cycle is closed. We don't just fix
309 * the initial W value because that makes all the patterns tend to
310 * be symmetrical about the X axis.
312 assign_random_common_w(p->epicycles);
319 delete_circle_chain(p->epicycles);
325 draw_body(Body *pb, GC gc)
327 XDrawLine(dpy, window, gc, pb->old_x, pb->old_y, pb->x, pb->y);
331 compute_divisor_lcm(Circle *p)
337 l = lcm(l, p->divisor);
346 * Calculate the position for the body at time T. We work in double
347 * rather than int to avoid the cumulative errors that would be caused
348 * by the rounding implicit in an assignment to int.
351 move_body(Body *pb, double t)
362 for (p=pb->epicycles; NULL != p; p=p->pchild)
364 /* angular pos = initial_pos + time * angular speed */
365 /* but this is an angular position, so modulo FULLCIRCLE. */
366 p->w = fmod(p->initial_w + (t * p->wdot), FULLCIRCLE);
368 x += (p->radius * cos(p->w));
369 y += (p->radius * sin(p->w));
377 colour_init(XWindowAttributes *pxgwa)
382 int H = random() % 360; /* colour choice from attraction.c. */
385 double V = frand(0.25) + 0.75;
390 unsigned long valuemask = 0L;
393 /* Free any already allocated colors...
397 free_colors(dpy, cmap, colors, ncolors);
402 ncolors = get_integer_resource ("colors", "Colors");
403 if (0 == ncolors) /* English spelling? */
404 ncolors = get_integer_resource ("colours", "Colors");
414 colors = (XColor *) malloc(sizeof(*colors) * (ncolors+1));
418 make_smooth_colormap (dpy, pxgwa->visual, cmap, colors, &ncolors,
420 False, /* not writable */
421 True); /* verbose (complain about failure) */
432 bg = get_pixel_resource ("background", "Background", dpy, cmap);
434 /* Set the line width
436 gcv.line_width = get_integer_resource ("lineWidth", "Integer");
439 valuemask |= GCLineWidth;
441 gcv.join_style = JoinRound;
442 gcv.cap_style = CapRound;
444 valuemask |= (GCCapStyle | GCJoinStyle);
448 /* Set the drawing function.
450 gcv.function = GXcopy;
451 valuemask |= GCFunction;
453 /* Set the foreground.
456 fg = get_pixel_resource ("foreground", "Foreground", dpy, cmap);
458 fg = bg ^ get_pixel_resource (("color0"), "Foreground", dpy, cmap);
460 valuemask |= GCForeground;
462 /* Actually create the GC.
464 color0 = XCreateGC (dpy, window, valuemask, &gcv);
470 /* check_events(); originally from XScreensaver: hacks/maze.c,
471 * but now quite heavily modified.
473 * Reaction to events:-
475 * Mouse 1 -- new figure }
476 * 2 -- new figure }-- ignored when running on root window.
479 * Window resized or exposed -- new figure.
480 * Window iconised -- wait until it's re-mapped, then start a new figure.
483 check_events (void) /* X event handler [ rhess ] */
488 while (unmapped || XPending(dpy))
495 switch (e.xbutton.button)
510 case ConfigureNotify:
515 printf("unmapped!\n");
517 restart = 1; /* restart with new fig. when re-mapped. */
521 if (0 == e.xexpose.count)
523 /* We can get several expose events in the queue.
524 * Only the last one has a zero count. We eat
525 * events in this function so as to avoid restarting
526 * the screensaver many times in quick succession.
530 /* If we had been unmapped and are now waiting to be re-mapped,
531 * indicate that we condition we are waiting for is now met.
534 printf("re-mapped!\n");
539 screenhack_handle_event(dpy, &e);
543 /* If we're unmapped, don't return to the caller. This
544 * prevents us wasting CPU, calculating new positions for
545 * things that will never be plotted. This is a real CPU
558 XWindowAttributes xgwa;
561 XGetWindowAttributes (dpy, window, &xgwa);
562 cmap = xgwa.colormap;
565 height = xgwa.height;
566 x_offset = width / 2;
567 y_offset = height / 2;
568 unit_pixels = width < height ? width : height;
571 static Bool done = False;
579 root = get_boolean_resource("root", "Boolean");
583 XSelectInput(dpy, window, ExposureMask);
587 XWindowAttributes xgwa;
588 XGetWindowAttributes (dpy, window, &xgwa);
589 XSelectInput (dpy, window,
590 xgwa.your_event_mask | ExposureMask |
591 ButtonPressMask |StructureNotifyMask);
596 color_step(Body *pb, double frac)
600 int newshift = ncolors * fmod(frac * colour_cycle_rate, 1.0);
601 if (newshift != color_shift_pos)
603 pb->current_color = newshift;
604 XSetForeground (dpy, color0, colors[pb->current_color].pixel);
605 color_shift_pos = newshift;
612 distance(long x1, long y1, long x2, long y2)
618 return dx*dx + dy*dy;
622 static int poisson_irand(double p)
625 while (fabs(frand(1.0)) < p)
627 return r < 1 ? 1 : r;
632 precalculate_figure(Body *pb,
633 double xtime, double step,
634 int *x_max, int *y_max,
635 int *x_min, int *y_min)
639 move_body(pb, 0.0); /* move once to avoid initial line from origin */
640 *x_min = *x_max = pb->x;
641 *y_min = *y_max = pb->y;
643 for (t=0.0; t<xtime; t += step)
645 move_body(pb, t); /* move once to avoid initial line from origin */
657 static int i_max(int a, int b)
659 return (a>b) ? a : b;
662 static void rescale_circles(Body *pb,
663 int x_max, int y_max,
664 int x_min, int y_min)
666 double xscale, yscale, scale;
674 x_max = i_max(x_max, -x_min);
675 y_max = i_max(y_max, -y_min);
689 if (xscale < yscale) /* wider than tall */
690 scale = xscale; /* ensure width fits onscreen */
692 scale = yscale; /* ensure height fits onscreen */
695 scale *= FILL_PROPORTION; /* only fill FILL_PROPORTION of screen */
696 if (scale < 1.0) /* only reduce, don't enlarge. */
699 for (p=pb->epicycles; p; p=p->pchild)
706 printf("enlarge by x%.2f skipped...\n", scale);
711 /* angular speeds of the circles are harmonics of a fundamental
712 * value. That should please the Pythagoreans among you... :-)
715 random_wdot_max(void)
717 /* Maximum and minimum values for the choice of wdot_max. Possible
718 * epicycle speeds vary from wdot_max to (wdot_max * harmonics).
720 double minspeed, maxspeed;
721 minspeed = get_float_resource("minSpeed", "Double");
722 maxspeed = get_float_resource("maxSpeed", "Double");
723 return harmonics * (minspeed + FULLCIRCLE * frand(maxspeed-minspeed));
726 /* this is the function called for your screensaver */
728 screenhack(Display *disp, Window win)
732 double t, timestep, circle, xtime, timestep_coarse;
735 int xmax, xmin, ymax, ymin;
736 int holdtime = get_integer_resource ("holdtime", "Integer");
743 XClearWindow(dpy, window);
746 delay = get_integer_resource ("delay", "Integer");
747 harmonics = get_integer_resource("harmonics", "Integer");
748 divisorPoisson = get_float_resource("divisorPoisson", "Double");
750 timestep = get_float_resource("timestep", "Double");
751 timestep_coarse = timestep *
752 get_float_resource("timestepCoarseFactor", "Double");
754 sizeFactorMin = get_float_resource("sizeFactorMin", "Double");
755 sizeFactorMax = get_float_resource("sizeFactorMax", "Double");
757 minCircles = get_integer_resource ("minCircles", "Integer");
758 maxCircles = get_integer_resource ("maxCircles", "Integer");
760 xtime = 0; /* is this right? */
763 setup(); /* do this inside the loop to cope with any window resizing */
766 /* Flush any outstanding events; this has the side effect of
767 * reducing the number of "false restarts"; resdtarts caused by
768 * one event (e.g. ConfigureNotify) followed by another
773 wdot_max = random_wdot_max();
781 pb->x_origin = pb->x = x_offset;
782 pb->y_origin = pb->y = y_offset;
787 erase_full_window(dpy, window);
792 precalculate_figure(pb, xtime, timestep_coarse,
793 &xmax, &ymax, &xmin, &ymin);
795 rescale_circles(pb, xmax, ymax, xmin, ymin);
797 move_body(pb, 0.0); /* move once to avoid initial line from origin */
798 move_body(pb, 0.0); /* move once to avoid initial line from origin */
801 t = 0.0; /* start at time zero. */
803 l = compute_divisor_lcm(pb->epicycles);
805 colour_cycle_rate = fabs(l);
807 xtime = fabs(l * circle / wdot_max);
809 if (colors) /* (colors==NULL) if mono_p */
810 XSetForeground (dpy, color0, colors[pb->current_color].pixel);
814 color_step(pb, t/xtime );
815 draw_body(pb, color0);
819 /* Check if the figure is complete...*/
826 sleep(holdtime); /* show complete figure for a bit. */
828 restart = 1; /* begin new figure. */