http://ftp.x.org/contrib/applications/xscreensaver-2.17.tar.gz
[xscreensaver] / hacks / xlyap.c
1 /* Lyap - calculate and display Lyapunov exponents */
2
3 /* Written by Ron Record (rr@sco) 03 Sep 1991 */
4
5 /* The idea here is to calculate the Lyapunov exponent for a periodically
6  * forced logistic map (later i added several other nonlinear maps of the unit
7  * interval). In order to turn the 1-dimensional parameter space of the
8  * logistic map into a 2-dimensional parameter space, select two parameter
9  * values ('a' and 'b') then alternate the iterations of the logistic map using
10  * first 'a' then 'b' as the parameter. This program accepts an argument to
11  * specify a forcing function, so instead of just alternating 'a' and 'b', you
12  * can use 'a' as the parameter for say 6 iterations, then 'b' for 6 iterations
13  * and so on. An interesting forcing function to look at is abbabaab (the
14  * Morse-Thue sequence, an aperiodic self-similar, self-generating sequence).
15  * Anyway, step through all the values of 'a' and 'b' in the ranges you want,
16  * calculating the Lyapunov exponent for each pair of values. The exponent
17  * is calculated by iterating out a ways (specified by the variable "settle")
18  * then on subsequent iterations calculating an average of the logarithm of
19  * the absolute value of the derivative at that point. Points in parameter
20  * space with a negative Lyapunov exponent are colored one way (using the
21  * value of the exponent to index into a color map) while points with a
22  * non-negative exponent are colored differently.
23  *
24  * The algorithm was taken from the September 1991 Scientific American article
25  * by A. K. Dewdney who gives credit to Mario Markus of the Max Planck Institute
26  * for its creation. Additional information and ideas were gleaned from the
27  * discussion on alt.fractals involving Stephen Hall, Ed Kubaitis, Dave Platt
28  * and Baback Moghaddam. Assistance with colormaps and spinning color wheels
29  * and X was gleaned from Hiram Clawson. Rubber banding code was adapted from
30  * an existing Mandelbrot program written by Stacey Campbell.
31  */
32
33 #define LYAP_PATCHLEVEL 4
34 #define LYAP_VERSION "#(@) lyap 2.3 2/20/92"
35
36 #include <assert.h>
37 #include <math.h>
38
39 #include "screenhack.h"
40 #include "yarandom.h"
41 #include "hsv.h"
42 #include "vroot.h"
43
44 #include <X11/cursorfont.h> 
45 #include <X11/Xutil.h> 
46
47 char *progclass = "XLyap";
48
49 char *defaults [] = {
50   "XLyap.background:    black",         /* to placate SGI */
51   "*randomize:          false",
52   "*builtin:            -1",
53   "*minColor:           1",
54   "*maxColor:           256",
55   "*dwell:              50",
56   "*useLog:             false",
57   "*colorExponent:      1.0",
58   "*colorOffset:        0",
59   "*randomForce:        ",              /* 0.5 */
60   "*settle:             50",
61   "*minA:               2.0",
62   "*minB:               2.0",
63   "*wheels:             7",
64   "*function:           10101010",
65   "*forcingFunction:    abbabaab",
66   "*bRange:             ",              /* 2.0 */
67   "*startX:             0.65",
68   "*mapIndex:           ",              /* 0 */
69   "*outputFile:         ",
70   "*beNegative:         false",
71   "*rgbMax:             65000",
72   "*spinLength:         256",
73   "*show:               false",
74   "*aRange:             ",              /* 2.0 */
75   0
76 };
77
78 XrmOptionDescRec options [] = {
79   { "-randomize", ".randomize", XrmoptionNoArg, "true" },
80   { "-builtin",   ".builtin",   XrmoptionSepArg, 0 },
81   { "-C", ".minColor",          XrmoptionSepArg, 0 },   /* n */
82   { "-D", ".dwell",             XrmoptionSepArg, 0 },   /* n */
83   { "-L", ".useLog",            XrmoptionNoArg, "true" },
84   { "-M", ".colorExponent",     XrmoptionSepArg, 0 },   /* r */
85   { "-O", ".colorOffset",       XrmoptionSepArg, 0 },   /* n */
86   { "-R", ".randomForce",       XrmoptionSepArg, 0 },   /* p */
87   { "-S", ".settle",            XrmoptionSepArg, 0 },   /* n */
88   { "-a", ".minA",              XrmoptionSepArg, 0 },   /* r */
89   { "-b", ".minB",              XrmoptionSepArg, 0 },   /* n */
90   { "-c", ".wheels",            XrmoptionSepArg, 0 },   /* n */
91   { "-F", ".function",          XrmoptionSepArg, 0 },   /* 10101010 */
92   { "-f", ".forcingFunction",   XrmoptionSepArg, 0 },   /* abbabaab */
93   { "-h", ".bRange",            XrmoptionSepArg, 0 },   /* r */
94   { "-i", ".startX",            XrmoptionSepArg, 0 },   /* r */
95   { "-m", ".mapIndex",          XrmoptionSepArg, 0 },   /* n */
96   { "-o", ".outputFile",        XrmoptionSepArg, 0 },   /* filename */
97   { "-p", ".beNegative",        XrmoptionNoArg, "true" },
98   { "-r", ".rgbMax",            XrmoptionSepArg, 0 },   /* n */
99   { "-s", ".spinLength",        XrmoptionSepArg, 0 },   /* n */
100   { "-v", ".show",              XrmoptionNoArg, "true" },
101   { "-w", ".aRange",            XrmoptionSepArg, 0 },   /* r */
102   { 0, 0, 0, 0 }
103 };
104
105
106 #define ABS(a)  (((a)<0) ? (0-(a)) : (a) )
107 #define Min(x,y) ((x < y)?x:y)
108 #define Max(x,y) ((x > y)?x:y)
109
110 #ifdef SIXTEEN_COLORS
111 #define MAXPOINTS  128
112 #ifdef BIGMEM
113 #define MAXFRAMES 4
114 #else
115 #define MAXFRAMES 2
116 #endif
117 #define MAXCOLOR 16
118 static int maxcolor=16, startcolor=0, color_offset=0, mincolindex=1;
119 static int dwell=50, settle=25;
120 static int width=128, height=128, xposition=128, yposition=128;
121 #else
122 #define MAXPOINTS  256
123 #ifdef BIGMEM
124 #define MAXFRAMES 8
125 #else
126 #define MAXFRAMES 2
127 #endif
128 #define MAXCOLOR 256
129 static int maxcolor=256, startcolor=17, color_offset=96, mincolindex=33;
130 static int dwell=100, settle=50;
131 static int width=256, height=256;
132 #endif
133
134 #ifndef TRUE
135 #define TRUE 1
136 #define FALSE 0
137 #endif
138
139 static int screen;
140 static Display* dpy;
141 static Visual *visual;
142
143 static unsigned long foreground, background;
144
145 static Window canvas;
146
147 typedef struct {
148         int x, y;
149 } xy_t;
150
151 typedef struct {
152         int start_x, start_y;
153         int last_x, last_y;
154         } rubber_band_data_t;
155
156 typedef struct {
157         Cursor band_cursor;
158         double p_min, p_max, q_min, q_max;
159         rubber_band_data_t rubber_band;
160         } image_data_t;
161
162 typedef struct points_t {
163         XPoint data[MAXCOLOR][MAXPOINTS];
164         int npoints[MAXCOLOR];
165         } points_t;
166
167 static points_t Points;
168 static image_data_t rubber_data;
169
170 #ifndef TRUE
171 #define TRUE 1
172 #define FALSE 0
173 #endif
174
175 static GC Data_GC[MAXCOLOR], RubberGC;
176
177 #define MAXINDEX 64
178 #define FUNCMAXINDEX 16
179 #define MAXWHEELS 7
180 #define NUMMAPS 5
181
182 typedef double (*PFD)(double,double);
183
184 static double logistic(double,double), circle(double,double), leftlog(double,double), rightlog(double,double), doublelog(double,double);
185 static double dlogistic(double,double), dcircle(double,double), dleftlog(double,double), drightlog(double,double), ddoublelog(double,double);
186 static PFD map, deriv;
187 static PFD Maps[NUMMAPS] = { logistic, circle, leftlog, rightlog, doublelog };
188 static PFD Derivs[NUMMAPS] = { dlogistic, dcircle, dleftlog, drightlog, ddoublelog };
189
190 static int aflag=0, bflag=0, wflag=0, hflag=0, Rflag=0;
191 static double pmins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
192 static double pmaxs[NUMMAPS] = { 4.0, 1.0, 6.75, 6.75, 16.0 };
193 static double amins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
194 static double aranges[NUMMAPS] = { 2.0, 1.0, 6.75, 6.75, 16.0 };
195 static double bmins[NUMMAPS] = { 2.0, 0.0, 0.0, 0.0, 0.0 };
196 static double branges[NUMMAPS] = { 2.0, 1.0, 6.75, 6.75, 16.0 };
197
198 static int   forcing[MAXINDEX] = { 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
199                         0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
200                         0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1 };
201 static int   Forcing[FUNCMAXINDEX] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
202
203 static int   maxindex = MAXINDEX;
204 static int   funcmaxindex = FUNCMAXINDEX;
205 static double   min_a=2.0, min_b=2.0, a_range=2.0, b_range=2.0, minlyap=1.0;
206 static double  max_a=4.0, max_b=4.0;
207 static double  start_x=0.65, lyapunov, a_inc, b_inc, a, b;
208 static int      numcolors=16, numfreecols, displayplanes, lowrange;
209 static xy_t     point;
210 static Pixmap  pixmap;
211 static Colormap cmap;
212 static XColor   Colors[MAXCOLOR];
213 static double  *exponents[MAXFRAMES];
214 static double  a_minimums[MAXFRAMES], b_minimums[MAXFRAMES];
215 static double  a_maximums[MAXFRAMES], b_maximums[MAXFRAMES];
216 static double  minexp, maxexp, prob=0.5;
217 static int     expind[MAXFRAMES]={0}, resized[MAXFRAMES]={0};
218 static int      numwheels=MAXWHEELS, force=0, Force=0, negative=1;
219 static int     rgb_max=65000, nostart=1, stripe_interval=7;
220 static int      save=1, show=0, useprod=1, spinlength=256, savefile=0;
221 static int      maxframe=0, frame=0, dorecalc=0, mapindex=0, run=1;
222 static char     *outname="lyap.out";
223
224
225 const char * const version = LYAP_VERSION;
226
227 static void resize(void);
228 static void redisplay(Window w, XExposeEvent *event);
229 static void Spin(Window w);
230 static void show_defaults(void);
231 static void StartRubberBand(Window w, image_data_t *data, XEvent *event);
232 static void TrackRubberBand(Window w, image_data_t *data, XEvent *event);
233 static void EndRubberBand(Window w, image_data_t *data, XEvent *event);
234 static void CreateXorGC(void);
235 static void InitBuffer(void);
236 static void BufferPoint(Display *display, Window window, int color,
237                         int x, int y);
238 static void FlushBuffer(void);
239 static void init_canvas(void);
240 static void init_data(void);
241 static void init_color(void);
242 static void parseargs(void);
243 static void Clear(void);
244 static void setupmem(void);
245 static void main_event(void);
246 static int complyap(void);
247 static void Getkey(XKeyEvent *event);
248 static int sendpoint(double expo);
249 static void save_to_file(void);
250 static void setforcing(void);
251 static void check_params(int mapnum, int parnum);
252 static void usage(void);
253 static void Destroy_frame(void);
254 static void freemem(void);
255 static void Redraw(void);
256 static void redraw(double *exparray, int index, int cont);
257 static void recalc(void);
258 static void SetupCorners(XPoint *corners, image_data_t *data);
259 static void set_new_params(Window w, image_data_t *data);
260 static void go_down(void);
261 static void go_back(void);
262 static void go_init(void);
263 static void jumpwin(void);
264 static void print_help(void);
265 static void print_values(void);
266
267
268 void
269 screenhack (Display *d, Window window)
270 {
271   XWindowAttributes xgwa;
272   int builtin = -1;
273   dpy = d;
274   XGetWindowAttributes (dpy, window, &xgwa);
275   width = xgwa.width;
276   height = xgwa.height;
277   visual = xgwa.visual;
278   cmap = xgwa.colormap;
279
280   parseargs();
281
282   if (get_boolean_resource("randomize", "Boolean"))
283     builtin = random() % 22;
284   else {
285     char *s = get_string_resource("builtin", "Integer");
286     if (s && *s)
287       builtin = atoi(s);
288     if (s) free (s);
289   }
290     
291   if (builtin >= 0)
292     {
293       char *ff = 0;
294       switch (builtin) {
295       case 0:
296         min_a = 3.75; aflag++;
297         min_b = 3.299999; bflag++;
298         a_range = 0.05; wflag++;
299         b_range = 0.05; hflag++;
300         dwell = 200;
301         settle = 100;
302         ff = "abaabbaaabbb";
303         break;
304
305       case 1:
306         min_a = 3.8; aflag++;
307         min_b = 3.2; bflag++;
308         b_range = .05; hflag++;
309         a_range = .05; wflag++;
310         ff = "bbbbbaaaaa";
311         break;
312
313       case 2:
314         min_a =  3.4; aflag++;
315         min_b =  3.04; bflag++;
316         a_range =  .5; wflag++;
317         b_range =  .5; hflag++;
318         ff = "abbbbbbbbb";
319         settle = 500;
320         dwell = 1000;
321         break;
322
323       case 3:
324         min_a = 3.5; aflag++;
325         min_b = 3.0; bflag++;
326         a_range = 0.2; wflag++;
327         b_range = 0.2; hflag++;
328         dwell = 600;
329         settle = 300;
330         ff = "aaabbbab";
331         break;
332
333       case 4:
334         min_a = 3.55667; aflag++;
335         min_b = 3.2; bflag++;
336         b_range = .05; hflag++;
337         a_range = .05; wflag++;
338         ff = "bbbbbaaaaa";
339         break;
340
341       case 5:
342         min_a = 3.79; aflag++;
343         min_b = 3.22; bflag++;
344         b_range = .02999; hflag++;
345         a_range = .02999; wflag++;
346         ff = "bbbbbaaaaa";
347         break;
348
349       case 6:
350         min_a = 3.7999; aflag++;
351         min_b = 3.299999; bflag++;
352         a_range = 0.2; wflag++;
353         b_range = 0.2; hflag++;
354         dwell = 300;
355         settle = 150;
356         ff = "abaabbaaabbb";
357         break;
358
359       case 7:
360         min_a = 3.89; aflag++;
361         min_b = 3.22; bflag++;
362         b_range = .028; hflag++;
363         a_range = .02999; wflag++;
364         ff = "bbbbbaaaaa";
365         settle = 600;
366         dwell = 1000;
367         break;
368
369       case 8:
370         min_a = 3.2; aflag++;
371         min_b = 3.7; bflag++;
372         a_range = 0.05; wflag++;
373         b_range = .005; hflag++;
374         ff = "abbbbaa";
375         break;
376
377       case 9:
378         ff = "aaaaaabbbbbb";
379         mapindex = 1;
380         dwell =  400;
381         settle =  200;
382         minlyap = maxexp = ABS(-0.85);
383         minexp = -1.0 * minlyap;
384         break;
385
386       case 10:
387         ff = "aaaaaabbbbbb";
388         mapindex = 1;
389         dwell =  400;
390         settle = 200;
391         minlyap = maxexp = ABS(-0.85);
392         minexp = -1.0 * minlyap;
393         break;
394
395       case 11:
396         mapindex = 1;
397         dwell =  400;
398         settle = 200;
399         minlyap = maxexp = ABS(-0.85);
400         minexp = -1.0 * minlyap;
401         break;
402
403       case 12:
404         ff = "abbb";
405         mapindex = 1;
406         dwell =  400;
407         settle = 200;
408         minlyap = maxexp = ABS(-0.85);
409         minexp = -1.0 * minlyap;
410         break;
411
412       case 13:
413         ff = "abbabaab";
414         mapindex = 1;
415         dwell =  400;
416         settle = 200;
417         minlyap = maxexp = ABS(-0.85);
418         minexp = -1.0 * minlyap;
419         break;
420
421       case 14:
422         ff = "abbabaab";
423         dwell =  800;
424         settle = 200;
425         minlyap = maxexp = ABS(-0.85);
426         minexp = -1.0 * minlyap;
427         /* ####  -x 0.05 */
428         min_a = 3.91; aflag++;
429         a_range =  0.0899999999; wflag++;
430         min_b =  3.28; bflag++;
431         b_range =  0.35; hflag++;
432         break;
433
434       case 15:
435         ff = "aaaaaabbbbbb";
436         dwell =  400;
437         settle = 200;
438         minlyap = maxexp = ABS(-0.85);
439         minexp = -1.0 * minlyap;
440         break;
441
442       case 16:
443         dwell =  400;
444         settle = 200;
445         minlyap = maxexp = ABS(-0.85);
446         minexp = -1.0 * minlyap;
447         break;
448
449       case 17:
450         ff = "abbb";
451         dwell =  400;
452         settle = 200;
453         minlyap = maxexp = ABS(-0.85);
454         minexp = -1.0 * minlyap;
455         break;
456
457       case 18:
458         ff = "abbabaab";
459         dwell =  400;
460         settle = 200;
461         minlyap = maxexp = ABS(-0.85);
462         minexp = -1.0 * minlyap;
463         break;
464
465       case 19:
466         mapindex = 2;
467         ff = "aaaaaabbbbbb";
468         dwell =  400;
469         settle = 200;
470         minlyap = maxexp = ABS(-0.85);
471         minexp = -1.0 * minlyap;
472         break;
473
474       case 20:
475         mapindex = 2;
476         dwell =  400;
477         settle = 200;
478         minlyap = maxexp = ABS(-0.85);
479         minexp = -1.0 * minlyap;
480         break;
481
482       case 21:
483         mapindex = 2;
484         ff = "abbb";
485         dwell =  400;
486         settle = 200;
487         minlyap = maxexp = ABS(-0.85);
488         minexp = -1.0 * minlyap;
489         break;
490
491       case 22:
492         mapindex = 2;
493         ff = "abbabaab";
494         dwell =  400;
495         settle = 200;
496         minlyap = maxexp = ABS(-0.85);
497         minexp = -1.0 * minlyap;
498         break;
499       }
500
501       if (ff) {
502         char *ch;
503         int bindex = 0;
504         maxindex = strlen(ff);
505         if (maxindex > MAXINDEX)
506           usage();
507         ch = ff;
508         force++;
509         while (bindex < maxindex) {
510           if (*ch == 'a')
511             forcing[bindex++] = 0;
512           else if (*ch == 'b')
513             forcing[bindex++] = 1;
514           else
515             usage();
516           ch++;
517         }
518       }
519     }
520
521   screen = DefaultScreen(dpy);
522   background = BlackPixel(dpy, screen);
523   setupmem();
524   init_data();
525   if (displayplanes > 1)
526     foreground = startcolor;
527   else
528     foreground = WhitePixel(dpy, screen);
529
530   /*
531   * Create the window to display the Lyapunov exponents
532   */
533   canvas = window;
534   init_canvas();
535
536   if (window != DefaultRootWindow(dpy))
537     XSelectInput(dpy,canvas,KeyPressMask|ButtonPressMask|ButtonMotionMask|
538                  ButtonReleaseMask|ExposureMask|StructureNotifyMask);
539   if (displayplanes > 1) {
540     init_color();
541   } else {
542     XQueryColors(dpy, DefaultColormap(dpy, DefaultScreen(dpy)),
543         Colors, numcolors);
544   }
545   pixmap = XCreatePixmap(dpy, DefaultRootWindow(dpy),
546                          width, height, DefaultDepth(dpy, screen));
547   rubber_data.band_cursor = XCreateFontCursor(dpy, XC_hand2);
548   CreateXorGC();
549   Clear();
550   for(;;)
551       main_event();
552 }
553
554 static void
555 main_event(void)
556 {
557   int n;
558   XEvent event;
559
560   if (complyap() == TRUE)
561       run=0;
562   n = XEventsQueued(dpy, QueuedAfterFlush);
563   while (n--) {
564           XNextEvent(dpy, &event);
565             switch(event.type)
566             {
567             case KeyPress:
568     Getkey(&event.xkey);
569     break;
570             case Expose:
571     redisplay(canvas, &event.xexpose);
572           break;
573             case ConfigureNotify:
574     resize();
575           break;
576             case ButtonPress:
577     StartRubberBand(canvas, &rubber_data, &event);
578           break;
579             case MotionNotify:
580     TrackRubberBand(canvas, &rubber_data, &event);
581           break;
582             case ButtonRelease:
583     EndRubberBand(canvas, &rubber_data, &event);
584           break;
585             }
586         }
587 }
588
589 /* complyap() is the guts of the program. This is where the Lyapunov exponent
590  * is calculated. For each iteration (past some large number of iterations)
591  * calculate the logarithm of the absolute value of the derivative at that
592  * point. Then average them over some large number of iterations. Some small
593  * speed up is achieved by utilizing the fact that log(a*b) = log(a) + log(b).
594  */
595 static int
596 complyap(void)
597 {
598   register i, bindex;
599   double total, prod, x, r;
600
601   if (!run)
602     return TRUE;
603   a += a_inc;
604   if (a >= max_a)
605     if (sendpoint(lyapunov) == TRUE)
606       return FALSE;
607     else {
608       FlushBuffer();
609       if (savefile)
610         save_to_file();
611       return TRUE;
612     }
613   if (b >= max_b) {
614     FlushBuffer();
615     if (savefile)
616       save_to_file();
617     return TRUE;
618   }
619   prod = 1.0;
620   total = 0.0;
621   bindex = 0;
622   x = start_x;
623   r = (forcing[bindex]) ? b : a;
624 #ifdef MAPS
625   findex = 0;
626   map = Maps[Forcing[findex]];
627 #endif
628   for (i=0;i<settle;i++) {     /* Here's where we let the thing */
629     x = (*map)(x, r);    /* "settle down". There is usually */
630     if (++bindex >= maxindex) { /* some initial "noise" in the */
631       bindex = 0;    /* iterations. How can we optimize */
632       if (Rflag)      /* the value of settle ??? */
633           setforcing();
634     }
635     r = (forcing[bindex]) ? b : a;
636 #ifdef MAPS
637     if (++findex >= funcmaxindex)
638       findex = 0;
639     map = Maps[Forcing[findex]];
640 #endif
641   }
642 #ifdef MAPS
643   deriv = Derivs[Forcing[findex]];
644 #endif
645   if (useprod) {      /* using log(a*b) */
646     for (i=0;i<dwell;i++) {
647       x = (*map)(x, r);
648       prod *= ABS((*deriv)(x, r));
649       /* we need to prevent overflow and underflow */
650       if ((prod > 1.0e12) || (prod < 1.0e-12)) {
651         total += log(prod);
652         prod = 1.0;
653       }
654       if (++bindex >= maxindex) {
655         bindex = 0;
656         if (Rflag)
657           setforcing();
658       }
659       r = (forcing[bindex]) ? b : a;
660 #ifdef MAPS
661       if (++findex >= funcmaxindex)
662         findex = 0;
663       map = Maps[Forcing[findex]];
664       deriv = Derivs[Forcing[findex]];
665 #endif
666     }
667     total += log(prod);
668     lyapunov = (total * M_LOG2E) / (double)dwell;
669   }
670   else {        /* use log(a) + log(b) */
671     for (i=0;i<dwell;i++) {
672       x = (*map)(x, r);
673       total += log(ABS((*deriv)(x, r)));
674       if (++bindex >= maxindex) {
675         bindex = 0;
676         if (Rflag)
677           setforcing();
678       }
679       r = (forcing[bindex]) ? b : a;
680 #ifdef MAPS
681       if (++findex >= funcmaxindex)
682         findex = 0;
683       map = Maps[Forcing[findex]];
684       deriv = Derivs[Forcing[findex]];
685 #endif
686     }
687     lyapunov = (total * M_LOG2E) / (double)dwell;
688   }
689   if (sendpoint(lyapunov) == TRUE)
690     return FALSE;
691   else {
692     FlushBuffer();
693     if (savefile)
694       save_to_file();
695     return TRUE;
696   }
697 }
698
699 static double
700 logistic(double x, double r)        /* the familiar logistic map */
701 {
702   return(r * x * (1.0 - x));
703 }
704
705 static double
706 dlogistic(double x, double r)       /* the derivative of logistic map */
707 {
708   return(r - (2.0 * r * x));
709 }
710
711 static double
712 circle(double x, double r)        /* sin() hump or sorta like the circle map */
713 {
714   return(r * sin(M_PI * x));
715 }
716
717 static double
718 dcircle(double x, double r)       /* derivative of the "sin() hump" */
719 {
720   return(r * M_PI * cos(M_PI * x));
721 }
722
723 static double
724 leftlog(double x, double r)       /* left skewed logistic */
725 {
726   double d;
727
728   d = 1.0 - x;
729   return(r * x * d * d);
730 }
731
732 static double
733 dleftlog(double x, double r)    /* derivative of the left skewed logistic */
734 {
735   return(r * (1.0 - (4.0 * x) + (3.0 * x * x)));
736 }
737
738 static double
739 rightlog(double x, double r)    /* right skewed logistic */
740 {
741   return(r * x * x * (1.0 - x));
742 }
743
744 static double
745 drightlog(double x, double r)    /* derivative of the right skewed logistic */
746 {
747   return(r * ((2.0 * x) - (3.0 * x * x)));
748 }
749
750 static double
751 doublelog(double x, double r)    /* double logistic */
752 {
753   double d;
754
755   d = 1.0 - x;
756   return(r * x * x * d * d);
757 }
758
759 static double
760 ddoublelog(double x, double r)   /* derivative of the double logistic */
761 {
762   double d;
763
764   d = x * x;
765   return(r * ((2.0 * x) - (6.0 * d) + (4.0 * x * d)));
766 }
767
768 static void
769 init_data(void)
770 {
771   numcolors = XDisplayCells(dpy, XDefaultScreen(dpy));
772   displayplanes = DisplayPlanes(dpy, XDefaultScreen(dpy));
773   if (numcolors > maxcolor)
774     numcolors = maxcolor;
775   numfreecols = numcolors - mincolindex;
776   lowrange = mincolindex - startcolor;
777   a_inc = a_range / (double)width;
778   b_inc = b_range / (double)height;
779   point.x = -1;
780   point.y = 0;
781   a = rubber_data.p_min = min_a;
782   b = rubber_data.q_min = min_b;
783   rubber_data.p_max = max_a;
784   rubber_data.q_max = max_b;
785   if (show)
786     show_defaults();
787   InitBuffer();
788   ya_rand_init(0);
789 }
790
791 static void
792 init_canvas(void)
793 {
794   static int i;
795
796   /*
797   * create default, writable, graphics contexts for the canvas.
798   */
799         for (i=0; i<maxcolor; i++) {
800             Data_GC[i] = XCreateGC(dpy, DefaultRootWindow(dpy),
801                 (unsigned long) NULL, (XGCValues *) NULL);
802             /* set the background to black */
803             XSetBackground(dpy,Data_GC[i],BlackPixel(dpy,XDefaultScreen(dpy)));
804             /* set the foreground of the ith context to i */
805             XSetForeground(dpy, Data_GC[i], i);
806         }
807         if (displayplanes == 1) {
808             XSetForeground(dpy,Data_GC[0],BlackPixel(dpy,XDefaultScreen(dpy)));
809             XSetForeground(dpy,Data_GC[1],WhitePixel(dpy,XDefaultScreen(dpy)));
810         }
811 }
812
813 #if 0
814 static void
815 hls2rgb(int hue_light_sat[3],
816         int rgb[3])             /*      Each in range [0..65535]        */
817 {
818   unsigned short r, g, b;
819   hsv_to_rgb((int) (hue_light_sat[0] / 10),             /* 0-3600 -> 0-360 */
820              (int) ((hue_light_sat[2]/1000.0) * 64435), /* 0-1000 -> 0-65535 */
821              (int) ((hue_light_sat[1]/1000.0) * 64435), /* 0-1000 -> 0-65535 */
822              &r, &g, &b);
823   rgb[0] = r;
824   rgb[1] = g;
825   rgb[2] = b;
826 }
827 #endif /* 0 */
828
829
830 static void
831 init_color(void)
832 {
833 #if 1
834
835   int i;
836   XColor colors[256];
837   int ncolors = maxcolor;
838   Bool writable = False;
839   make_smooth_colormap(dpy, visual, cmap,
840                         colors, &ncolors, True, &writable, True);
841
842   for (i = 0; i < maxcolor; i++)
843     XSetForeground(dpy, Data_GC[i],
844                    colors[((int) ((i / ((float)maxcolor)) * ncolors))].pixel);
845
846 #else
847   static int i, j, colgap, leg, step;
848   static Visual *visual;
849   Colormap def_cmap;
850   int hls[3], rgb[3];
851
852   def_cmap = DefaultColormap(dpy, DefaultScreen(dpy));
853   for (i=0; i<numcolors; i++) {
854     Colors[i].pixel = i;
855     Colors[i].flags = DoRed|DoGreen|DoBlue;
856   }
857
858   /* Try to write into a new color map */
859   visual = DefaultVisual(dpy, DefaultScreen(dpy));
860   cmap = XCreateColormap(dpy, canvas, visual, AllocAll);
861   XQueryColors(dpy, def_cmap, Colors, numcolors);
862   if (mincolindex)
863     colgap = rgb_max / mincolindex;
864   else
865     colgap = rgb_max;
866   hls[0] = 50;  /* Hue in low range */
867   hls[2] = 1000;  /* Fully saturated */
868   for (i=startcolor; i<lowrange + startcolor; i++) {
869     hls[1] = 1000L * (i-startcolor) / lowrange;
870     hls2rgb(hls, rgb);
871     Colors[i].red = rgb[0];
872     Colors[i].green = rgb[1];
873     Colors[i].blue = rgb[2];
874   }
875   colgap = rgb_max / numcolors;
876   if (numwheels == 0)
877     XQueryColors(dpy, def_cmap, Colors, numcolors);
878   else if (numwheels == 1) {
879     colgap = 2*rgb_max/(numcolors - color_offset);
880     for (i=mincolindex; i<(numcolors/2); i++) {
881       Colors[i].blue = 0;
882       Colors[i].green=((i+color_offset)*colgap);
883       Colors[i].red=((i+color_offset)*colgap);
884     }
885     for (i=(numcolors/2); i<(numcolors); i++) {
886       Colors[i].blue = 0;
887       Colors[i].green=(((numcolors-i)+color_offset)*colgap);
888       Colors[i].red=(((numcolors-i)+color_offset)*colgap);
889     }
890   }
891   else if (numwheels == 2) {
892           hls[0] = 800; /* Hue in mid range */
893           hls[2] = 1000;  /* Fully saturated */
894           for (i=startcolor; i<lowrange + startcolor; i++) {
895       hls[1] = 1000L * (i-startcolor) / lowrange;
896       hls2rgb(hls, rgb);
897       Colors[i].red = rgb[0];
898       Colors[i].green = rgb[1];
899       Colors[i].blue = rgb[2];
900           }
901     for (i=mincolindex; i<(numcolors/2); i++) {
902       Colors[i].blue = rgb_max;
903       Colors[i].green = 0;
904       Colors[i].red=(i*2*rgb_max/numcolors);
905     }
906     for (i=(numcolors/2); i<numcolors; i++) {
907       Colors[i].blue = rgb_max;
908       Colors[i].green = 0;
909       Colors[i].red=((numcolors - i)*2*rgb_max/numcolors);
910     }
911   }
912   else if (numwheels == 3) {
913           hls[0] = 800; /* Hue in mid range */
914           hls[2] = 1000;  /* Fully saturated */
915           for (i=startcolor; i<lowrange + startcolor; i++) {
916       hls[1] = 1000L * (i-startcolor) / lowrange;
917       hls2rgb(hls, rgb);
918       Colors[i].red = rgb[0];
919       Colors[i].green = rgb[1];
920       Colors[i].blue = rgb[2];
921           }
922     colgap = 4*rgb_max/numcolors;
923     for (i=mincolindex; i<(numcolors/4); i++) {
924       Colors[i].blue = rgb_max;
925       Colors[i].green = 0;
926       Colors[i].red=(i*colgap);
927     }
928     for (i=(numcolors/4); i<(numcolors/2); i++) {
929       Colors[i].red = rgb_max;
930       Colors[i].green = 0;
931       Colors[i].blue=((numcolors/2) - i) * colgap;
932     }
933     for (i=(numcolors/2); i<(0.75*numcolors); i++) {
934       Colors[i].red = rgb_max;
935       Colors[i].blue=(i * colgap);
936       Colors[i].green = 0;
937     }
938     for (i=(0.75*numcolors); i<numcolors; i++) {
939       Colors[i].blue = rgb_max;
940       Colors[i].green = 0;
941       Colors[i].red=(numcolors-i)*colgap;
942     }
943   }
944   else if (numwheels == 4) {
945           hls[0] = 800; /* Hue in mid range */
946           hls[2] = 1000;  /* Fully saturated */
947           for (i=startcolor; i<lowrange + startcolor; i++) {
948       hls[1] = 1000L * (i-startcolor) / lowrange;
949       hls2rgb(hls, rgb);
950       Colors[i].red = rgb[0];
951       Colors[i].green = rgb[1];
952       Colors[i].blue = rgb[2];
953           }
954     colgap = numwheels * rgb_max / numcolors;
955     for (i=mincolindex; i<(numcolors/numwheels); i++) {
956       Colors[i].blue = rgb_max;
957       Colors[i].green = 0;
958       Colors[i].red=(i*colgap);
959     }
960     for (i=(numcolors/numwheels); i<(2*numcolors/numwheels); i++) {
961       Colors[i].red = rgb_max;
962       Colors[i].green = 0;
963       Colors[i].blue=((2*numcolors/numwheels) - i) * colgap;
964     }
965     for (i=(2*numcolors/numwheels); i<numcolors; i++) {
966       Colors[i].red = rgb_max;
967       Colors[i].green=(i - (2*numcolors/numwheels)) * colgap;
968       Colors[i].blue = 0;
969     }
970   }
971   else if (numwheels == 5) {
972     hls[1] = 700; /* Lightness in midrange */
973     hls[2] = 1000;  /* Fully saturated */
974     for (i=mincolindex; i<numcolors; i++) {
975       hls[0] = 3600L * i / numcolors;
976       hls2rgb(hls, rgb);
977       Colors[i].red = rgb[0];
978       Colors[i].green = rgb[1];
979       Colors[i].blue = rgb[2];
980     }
981     for (i=mincolindex; i<numcolors; i+=stripe_interval) {
982       hls[0] = 3600L * i / numcolors;
983       hls2rgb(hls, rgb);
984       Colors[i].red = rgb[0] / 2;
985       Colors[i].green = rgb[1] / 2;
986       Colors[i].blue = rgb[2] / 2;
987     }
988   }
989   else if (numwheels == 6) {
990       hls[0] = 800; /* Hue in mid range */
991       hls[2] = 1000;  /* Fully saturated */
992       for (i=startcolor; i<lowrange + startcolor; i++) {
993     hls[1] = 1000L * (i-startcolor) / lowrange;
994     hls2rgb(hls, rgb);
995     Colors[i].red = rgb[0];
996     Colors[i].green = rgb[1];
997     Colors[i].blue = rgb[2];
998       }
999       step = numfreecols / 3;
1000       leg = step+mincolindex;
1001       for (i = mincolindex; i < leg; ++i)
1002       {
1003     Colors[i].pixel = i;
1004     Colors[i].red = fabs(65535 - (double)i / step * 65535.0);
1005     Colors[i].blue = (double)i / step * 65535.0;
1006     Colors[i].green = 0;
1007     Colors[i].flags = DoRed | DoGreen | DoBlue;
1008       }
1009       for (j = 0, i = leg, leg += step; i < leg; ++i, ++j)
1010       {
1011     Colors[i].pixel = i;
1012     Colors[i].red = (double)j / step * 65535.0;
1013     Colors[i].blue = 65535;
1014     Colors[i].green = Colors[i].red;
1015     Colors[i].flags = DoRed | DoGreen | DoBlue;
1016       }
1017       for (j = 0, i = leg, leg += step; i < leg; ++i, ++j)
1018       {
1019     Colors[i].pixel = i;
1020     Colors[i].red = 65535;
1021     Colors[i].blue = fabs(65535 - (double)j / step * 65535.0);
1022     Colors[i].green = Colors[i].blue;
1023     Colors[i].flags = DoRed | DoGreen | DoBlue;
1024       }
1025   }
1026   else if (numwheels == MAXWHEELS) {  /* rainbow palette */
1027     hls[1] = 500; /* Lightness in midrange */
1028     hls[2] = 1000;  /* Fully saturated */
1029     for (i=mincolindex; i<numcolors; i++) {
1030       hls[0] = 3600L * i / numcolors;
1031       hls2rgb(hls, rgb);
1032       Colors[i].red = rgb[0];
1033       Colors[i].green = rgb[1];
1034       Colors[i].blue = rgb[2];
1035     }
1036   }
1037   XStoreColors(dpy, cmap, Colors, numcolors);
1038
1039   XSetWindowColormap(dpy, canvas, cmap);
1040 #endif
1041 }
1042
1043 static void
1044 parseargs()
1045 {
1046   static int i;
1047   int bindex=0, findex;
1048   char *s, *ch;
1049
1050   map = Maps[0];
1051   deriv = Derivs[0];
1052   maxexp=minlyap; minexp= -1.0 * minlyap;
1053
1054   mincolindex = get_integer_resource("minColor", "Integer");
1055   dwell = get_integer_resource("dwell", "Integer");
1056 #ifdef MAPS
1057   {
1058     char *optarg = get_string_resource("function", "String");
1059     funcmaxindex = strlen(optarg);
1060     if (funcmaxindex > FUNCMAXINDEX)
1061       usage();
1062     ch = optarg;
1063     Force++;
1064     for (findex=0;findex<funcmaxindex;findex++) {
1065       Forcing[findex] = (int)(*ch++ - '0');;
1066       if (Forcing[findex] >= NUMMAPS)
1067         usage();
1068     }
1069   }
1070 #endif
1071   if (get_boolean_resource("useLog", "Boolean"))
1072     useprod=0;
1073
1074   minlyap=ABS(get_float_resource("colorExponent", "Float"));
1075   maxexp=minlyap;
1076   minexp= -1.0 * minlyap;
1077
1078   color_offset = get_integer_resource("colorOffset", "Integer");
1079
1080   maxcolor=ABS(get_integer_resource("maxColor", "Integer"));
1081   if ((maxcolor - startcolor) <= 0)
1082     startcolor = 0;
1083   if ((maxcolor - mincolindex) <= 0) {
1084     mincolindex = 1;
1085     color_offset = 0;
1086   }
1087
1088   s = get_string_resource("randomForce", "Float");
1089   if (s && *s) {
1090     prob=atof(s); Rflag++; setforcing();
1091   }
1092
1093   settle = get_integer_resource("settle", "Integer");
1094
1095   s = get_string_resource("minA", "Float");
1096   if (s && *s) {
1097     min_a = atof(s);
1098     aflag++;
1099   }
1100   
1101   s = get_string_resource("minB", "Float");
1102   if (s && *s) {
1103     min_b=atof(s); bflag++;
1104   }
1105   
1106   numwheels = get_integer_resource("wheels", "Integer");
1107
1108   s = get_string_resource("forcingFunction", "String");
1109   if (s && *s) {
1110     maxindex = strlen(s);
1111     if (maxindex > MAXINDEX)
1112       usage();
1113     ch = s;
1114     force++;
1115     while (bindex < maxindex) {
1116       if (*ch == 'a')
1117         forcing[bindex++] = 0;
1118       else if (*ch == 'b')
1119         forcing[bindex++] = 1;
1120       else
1121         usage();
1122       ch++;
1123     }
1124   }
1125
1126   s = get_string_resource("bRange", "Float");
1127   if (s && *s) {
1128     b_range = atof(s);
1129     hflag++;
1130   }
1131
1132   start_x = get_float_resource("startX", "Float");
1133
1134   s = get_string_resource("mapIndex", "Integer");
1135   if (s && *s) {
1136     mapindex=atoi(s);
1137     if ((mapindex >= NUMMAPS) || (mapindex < 0))
1138       usage();
1139     map = Maps[mapindex];
1140     deriv = Derivs[mapindex];
1141     if (!aflag)
1142       min_a = amins[mapindex];
1143     if (!wflag)
1144       a_range = aranges[mapindex];
1145     if (!bflag)
1146       min_b = bmins[mapindex];
1147     if (!hflag)
1148       b_range = branges[mapindex];
1149     if (!Force)
1150       for (i=0;i<FUNCMAXINDEX;i++)
1151         Forcing[i] = mapindex;
1152   }
1153
1154   outname = get_string_resource("outputFile", "Integer");
1155
1156   if (get_boolean_resource("beNegative", "Boolean"))
1157     negative--;
1158
1159   rgb_max = get_integer_resource("rgbMax", "Integer");
1160   spinlength = get_integer_resource("spinLength", "Integer");
1161   show = get_boolean_resource("show", "Boolean");
1162
1163   s = get_string_resource("aRange", "Float");
1164   if (s && *s) {
1165     a_range = atof(s); wflag++;
1166   }
1167
1168   max_a = min_a + a_range;
1169   max_b = min_b + b_range;
1170
1171   a_minimums[0] = min_a; b_minimums[0] = min_b;
1172   a_maximums[0] = max_a; b_maximums[0] = max_b;
1173
1174   if (Force)
1175     if (maxindex == funcmaxindex)
1176       for (findex=0;findex<funcmaxindex;findex++)
1177         check_params(Forcing[findex],forcing[findex]);
1178     else
1179       fprintf(stderr, "Warning! Unable to check parameters\n");
1180   else
1181     check_params(mapindex,2);
1182 }
1183
1184 static void
1185 check_params(int mapnum, int parnum)
1186 {
1187
1188   if (parnum != 1) {
1189       if ((max_a > pmaxs[mapnum]) || (min_a < pmins[mapnum])) {
1190     fprintf(stderr, "Warning! Parameter 'a' out of range.\n");
1191     fprintf(stderr, "You have requested a range of (%f,%f).\n",
1192       min_a,max_a);
1193     fprintf(stderr, "Valid range is (%f,%f).\n",
1194       pmins[mapnum],pmaxs[mapnum]);
1195       }
1196   }
1197   if (parnum != 0) {
1198       if ((max_b > pmaxs[mapnum]) || (min_b < pmins[mapnum])) {
1199     fprintf(stderr, "Warning! Parameter 'b' out of range.\n");
1200     fprintf(stderr, "You have requested a range of (%f,%f).\n",
1201       min_b,max_b);
1202     fprintf(stderr, "Valid range is (%f,%f).\n",
1203       pmins[mapnum],pmaxs[mapnum]);
1204       }
1205   }
1206 }
1207
1208 static void
1209 usage(void)
1210 {
1211     fprintf(stderr,"lyap [-BLs][-W#][-H#][-a#][-b#][-w#][-h#][-x xstart]\n");
1212     fprintf(stderr,"\t[-M#][-S#][-D#][-f string][-r#][-O#][-C#][-c#][-m#]\n");
1213 #ifdef MAPS
1214     fprintf(stderr,"\t[-F string]\n");
1215 #endif
1216     fprintf(stderr,"\tWhere: -C# specifies the minimum color index\n");
1217     fprintf(stderr,"\t       -r# specifies the maxzimum rgb value\n");
1218     fprintf(stderr,"\t       -u displays this message\n");
1219     fprintf(stderr,"\t       -a# specifies the minimum horizontal parameter\n");
1220     fprintf(stderr,"\t       -b# specifies the minimum vertical parameter\n");
1221     fprintf(stderr,"\t       -w# specifies the horizontal parameter range\n");
1222     fprintf(stderr,"\t       -h# specifies the vertical parameter range\n");
1223     fprintf(stderr,"\t       -D# specifies the dwell\n");
1224     fprintf(stderr,"\t       -S# specifies the settle\n");
1225     fprintf(stderr,"\t       -H# specifies the initial window height\n");
1226     fprintf(stderr,"\t       -W# specifies the initial window width\n");
1227     fprintf(stderr,"\t       -O# specifies the color offset\n");
1228     fprintf(stderr,"\t       -c# specifies the desired color wheel\n");
1229     fprintf(stderr,"\t       -m# specifies the desired map (0-4)\n");
1230     fprintf(stderr,"\t       -f aabbb specifies a forcing function of 00111\n");
1231 #ifdef MAPS
1232     fprintf(stderr,"\t       -F 00111 specifies the function forcing function\n");
1233 #endif
1234     fprintf(stderr,"\t       -L indicates use log(x)+log(y) rather than log(xy)\n");
1235     fprintf(stderr,"\tDuring display :\n");
1236     fprintf(stderr,"\t     Use the mouse to zoom in on an area\n");
1237     fprintf(stderr,"\t     e or E recalculates color indices\n");
1238     fprintf(stderr,"\t     f or F saves exponents to a file\n");
1239     fprintf(stderr,"\t     KJmn increase/decrease minimum negative exponent\n");
1240     fprintf(stderr,"\t     r or R redraws\n");
1241     fprintf(stderr,"\t     s or S spins the colorwheel\n");
1242     fprintf(stderr,"\t     w or W changes the color wheel\n");
1243     fprintf(stderr,"\t     x or X clears the window\n");
1244     fprintf(stderr,"\t     q or Q exits\n");
1245     exit(1);
1246 }
1247
1248 static void
1249 Cycle_frames(void)
1250 {
1251   static int i;
1252   for (i=0;i<=maxframe;i++)
1253     redraw(exponents[i], expind[i], 1);
1254 }
1255
1256 static void
1257 Spin(Window w)
1258 {
1259   static int i, j;
1260   long tmpxcolor;
1261
1262   if (displayplanes > 1) {
1263     for (j=0;j<spinlength;j++) {
1264       tmpxcolor = Colors[mincolindex].pixel;
1265       for (i=mincolindex;i<numcolors-1;i++)
1266         Colors[i].pixel = Colors[i+1].pixel;
1267       Colors[numcolors-1].pixel = tmpxcolor;
1268       XStoreColors(dpy, cmap, Colors, numcolors);
1269     }
1270     for (j=0;j<spinlength;j++) {
1271       tmpxcolor = Colors[numcolors-1].pixel;
1272       for (i=numcolors-1;i>mincolindex;i--)
1273         Colors[i].pixel = Colors[i-1].pixel;
1274       Colors[mincolindex].pixel = tmpxcolor;
1275       XStoreColors(dpy, cmap, Colors, numcolors);
1276     }
1277   }
1278 }
1279
1280 static void
1281 Getkey(XKeyEvent *event)
1282 {
1283   unsigned char key;
1284   static int i;
1285   if (XLookupString(event, (char *)&key, sizeof(key), (KeySym *)0,
1286             (XComposeStatus *) 0) > 0)
1287     switch (key) {
1288   case '<': dwell /= 2; if (dwell < 1) dwell = 1; break;
1289   case '>': dwell *= 2; break;
1290   case '[': settle /= 2; if (settle < 1) settle = 1; break;
1291   case ']': settle *= 2; break;
1292   case 'd': go_down(); break;
1293   case 'D': FlushBuffer(); break;
1294   case 'e':
1295   case 'E': FlushBuffer();
1296       dorecalc = (!dorecalc);
1297       if (dorecalc)
1298       recalc();
1299       else {
1300       maxexp = minlyap; minexp = -1.0 * minlyap;
1301       }
1302       redraw(exponents[frame], expind[frame], 1);
1303       break;
1304   case 'f':
1305   case 'F': save_to_file(); break;
1306   case 'i': if (stripe_interval > 0) {
1307       stripe_interval--;
1308         if (displayplanes > 1) {
1309             init_color();
1310         }
1311       }
1312       break;
1313   case 'I': stripe_interval++;
1314       if (displayplanes > 1) {
1315         init_color();
1316       }
1317       break;
1318   case 'K': if (minlyap > 0.05)
1319       minlyap -= 0.05;
1320        break;
1321   case 'J': minlyap += 0.05;
1322        break;
1323   case 'm': mapindex++;
1324                   if (mapindex >= NUMMAPS)
1325                         mapindex=0;
1326                   map = Maps[mapindex];
1327                   deriv = Derivs[mapindex];
1328       if (!aflag)
1329                         min_a = amins[mapindex];
1330                   if (!wflag)
1331                         a_range = aranges[mapindex];
1332                   if (!bflag)
1333                         min_b = bmins[mapindex];
1334                   if (!hflag)
1335                         b_range = branges[mapindex];
1336                   if (!Force)
1337                         for (i=0;i<FUNCMAXINDEX;i++)
1338                              Forcing[i] = mapindex;
1339             max_a = min_a + a_range;
1340             max_b = min_b + b_range;
1341             a_minimums[0] = min_a; b_minimums[0] = min_b;
1342             a_maximums[0] = max_a; b_maximums[0] = max_b;
1343             a_inc = a_range / (double)width;
1344             b_inc = b_range / (double)height;
1345             point.x = -1;
1346             point.y = 0;
1347             a = rubber_data.p_min = min_a;
1348             b = rubber_data.q_min = min_b;
1349             rubber_data.p_max = max_a;
1350             rubber_data.q_max = max_b;
1351                   Clear();
1352                   break;
1353   case 'M': if (minlyap > 0.005)
1354       minlyap -= 0.005;
1355        break;
1356   case 'N': minlyap += 0.005;
1357        break;
1358   case 'p':
1359   case 'P': negative = (!negative);
1360       FlushBuffer(); redraw(exponents[frame], expind[frame], 1);
1361       break;
1362   case 'r': FlushBuffer(); redraw(exponents[frame], expind[frame], 1);
1363       break;
1364   case 'R': FlushBuffer(); Redraw(); break;
1365   case 's':
1366        spinlength=spinlength/2;
1367   case 'S': if (displayplanes > 1)
1368       Spin(canvas);
1369        spinlength=spinlength*2; break;
1370   case 'u': go_back(); break;
1371   case 'U': go_init(); break;
1372   case 'v':
1373   case 'V': print_values(); break;
1374   case 'W': if (numwheels < MAXWHEELS)
1375       numwheels++;
1376        else
1377       numwheels = 0;
1378        if (displayplanes > 1) {
1379         init_color();
1380        }
1381        break;
1382   case 'w': if (numwheels > 0)
1383       numwheels--;
1384        else
1385       numwheels = MAXWHEELS;
1386        if (displayplanes > 1) {
1387         init_color();
1388        }
1389        break;
1390   case 'x': Clear(); break;
1391   case 'X': Destroy_frame(); break;
1392   case 'z': Cycle_frames(); redraw(exponents[frame], expind[frame], 1);
1393       break;
1394   case 'Z': while (!XPending(dpy)) Cycle_frames();
1395       redraw(exponents[frame], expind[frame], 1); break;
1396   case 'q':
1397   case 'Q': exit(0); break;
1398   case '?':
1399   case 'h':
1400   case 'H': print_help(); break;
1401   default:  break;
1402   }
1403 }
1404
1405 /* Here's where we index into a color map. After the Lyapunov exponent is
1406  * calculated, it is used to determine what color to use for that point.
1407  * I suppose there are a lot of ways to do this. I used the following :
1408  * if it's non-negative then there's a reserved area at the lower range
1409  * of the color map that i index into. The ratio of some "minimum exponent
1410  * value" and the calculated value is used as a ratio of how high to index
1411  * into this reserved range. Usually these colors are dark red (see init_color).
1412  * If the exponent is negative, the same ratio (expo/minlyap) is used to index
1413  * into the remaining portion of the colormap (which is usually some light
1414  * shades of color or a rainbow wheel). The coloring scheme can actually make
1415  * a great deal of difference in the quality of the picture. Different colormaps
1416  * bring out different details of the dynamics while different indexing
1417  * algorithms also greatly effect what details are seen. Play around with this.
1418  */
1419 static int
1420 sendpoint(double expo)
1421 {
1422   static int index;
1423   static double tmpexpo;
1424
1425   point.x++;
1426   tmpexpo = (negative) ? expo : -1.0 * expo;
1427   if (tmpexpo > 0) {
1428     if (displayplanes >1) {
1429         index = (int)(tmpexpo*lowrange/maxexp);
1430         index = (index % lowrange) + startcolor;
1431     }
1432     else
1433         index = 0;
1434   }
1435   else {
1436     if (displayplanes >1) {
1437         index = (int)(tmpexpo*numfreecols/minexp);
1438         index = (index % numfreecols) + mincolindex;
1439     }
1440     else
1441         index = 1;
1442   }
1443     BufferPoint(dpy, canvas, index, point.x, point.y);
1444   if (save)
1445     exponents[frame][expind[frame]++] = expo;
1446   if (point.x >= width) {
1447     point.y++;
1448     point.x = 0;
1449     if (save) {
1450       b += b_inc;
1451       a = min_a;
1452     }
1453     if (point.y >= height)
1454       return FALSE;
1455     else
1456       return TRUE;
1457   }
1458   return TRUE;
1459 }
1460
1461 static void
1462 redisplay (Window w, XExposeEvent *event)
1463 {
1464   /*
1465   * Extract the exposed area from the event and copy
1466   * from the saved pixmap to the window.
1467   */
1468   XCopyArea(dpy, pixmap, canvas, Data_GC[0],
1469            event->x, event->y, event->width, event->height,
1470            event->x, event->y);
1471 }
1472
1473 static void
1474 resize(void)
1475 {
1476   Window r;
1477   int n, x, y;
1478   unsigned int bw, d, new_w, new_h;
1479
1480   XGetGeometry(dpy,canvas,&r,&x,&y,&new_w,&new_h,&bw,&d);
1481   if ((new_w == width) && (new_h == height))
1482     return;
1483   width = new_w; height = new_h;
1484   XClearWindow(dpy, canvas);
1485   if (pixmap)
1486     XFreePixmap(dpy, pixmap);
1487   pixmap = XCreatePixmap(dpy, DefaultRootWindow(dpy),
1488       width, height, DefaultDepth(dpy, screen));
1489   a_inc = a_range / (double)width;
1490   b_inc = b_range / (double)height;
1491   point.x = -1;
1492   point.y = 0;
1493   run = 1;
1494   a = rubber_data.p_min = min_a;
1495   b = rubber_data.q_min = min_b;
1496   rubber_data.p_max = max_a;
1497   rubber_data.q_max = max_b;
1498   freemem();
1499   setupmem();
1500         for (n=0;n<MAXFRAMES;n++)
1501     if ((n <= maxframe) && (n != frame))
1502         resized[n] = 1;
1503   InitBuffer();
1504   Clear();
1505   Redraw();
1506 }
1507
1508 static void
1509 redraw(double *exparray, int index, int cont)
1510 {
1511   static int i;
1512   static int x_sav, y_sav;
1513
1514   x_sav = point.x;
1515   y_sav = point.y;
1516
1517   point.x = -1;
1518   point.y = 0;
1519
1520   save=0;
1521   for (i=0;i<index;i++)
1522     sendpoint(exparray[i]);
1523   save=1;
1524
1525   if (cont) {
1526     point.x = x_sav;
1527     point.y = y_sav;
1528   }
1529   else {
1530     a = point.x * a_inc + min_a;
1531     b = point.y * b_inc + min_b;
1532   }
1533   FlushBuffer();
1534 }
1535
1536 static void
1537 Redraw(void)
1538 {
1539   FlushBuffer();
1540         point.x = -1;
1541         point.y = 0;
1542   run = 1;
1543         a = min_a;
1544         b = min_b;
1545   expind[frame] = 0;
1546   resized[frame] = 0;
1547 }
1548
1549 /* Store color pics in PPM format and monochrome in PGM */
1550 static void
1551 save_to_file(void)
1552 {
1553   FILE *outfile;
1554   unsigned char c;
1555   XImage *ximage;
1556   static int i,j;
1557   struct Colormap {
1558     unsigned char red;
1559     unsigned char green;
1560     unsigned char blue;
1561   };
1562   struct Colormap *colormap=NULL;
1563
1564   if (colormap)
1565     free(colormap);
1566   if ((colormap=
1567     (struct Colormap *)malloc(sizeof(struct Colormap)*maxcolor))
1568       == NULL) {
1569     fprintf(stderr,"Error malloc'ing colormap array\n");
1570     exit(-1);
1571   }
1572   outfile = fopen(outname,"w");
1573   if(!outfile) {
1574     perror(outname);
1575     exit(-1);
1576   }
1577
1578   ximage=XGetImage(dpy, pixmap, 0, 0, width, height, AllPlanes, XYPixmap);
1579
1580   if (displayplanes > 1) {
1581     for (i=0;i<maxcolor;i++) {
1582       colormap[i].red=(unsigned char)(Colors[i].red >> 8);
1583       colormap[i].green=(unsigned char)(Colors[i].green >> 8);
1584       colormap[i].blue =(unsigned char)(Colors[i].blue >> 8);
1585     }
1586     fprintf(outfile,"P%d %d %d\n",6,width,height);
1587   }
1588   else
1589     fprintf(outfile,"P%d %d %d\n",5,width,height);
1590   fprintf(outfile,"# settle=%d  dwell=%d start_x=%f\n",settle,dwell,
1591         start_x);
1592   fprintf(outfile,"# min_a=%f  a_rng=%f  max_a=%f\n",min_a,a_range,max_a);
1593   fprintf(outfile,"# min_b=%f  b_rng=%f  max_b=%f\n",min_b,b_range,max_b);
1594   if (Rflag)
1595     fprintf(outfile,"# pseudo-random forcing\n");
1596   else if (force) {
1597     fprintf(outfile,"# periodic forcing=");
1598     for (i=0;i<maxindex;i++) {
1599       fprintf(outfile,"%d",forcing[i]);
1600     }
1601     fprintf(outfile,"\n");
1602   }
1603   else
1604     fprintf(outfile,"# periodic forcing=01\n");
1605   if (Force) {
1606     fprintf(outfile,"# function forcing=");
1607     for (i=0;i<funcmaxindex;i++) {
1608       fprintf(outfile,"%d",Forcing[i]);
1609     }
1610     fprintf(outfile,"\n");
1611   }
1612   fprintf(outfile,"%d\n",numcolors-1);
1613
1614   for (j=0;j<height;j++)
1615       for (i=0;i<width;i++) {
1616     c = (unsigned char)XGetPixel(ximage,i,j);
1617     if (displayplanes > 1)
1618         fwrite((char *)&colormap[c],sizeof colormap[0],1,outfile);
1619     else
1620         fwrite((char *)&c,sizeof c,1,outfile);
1621       }
1622   fclose(outfile);
1623 }
1624
1625 static void
1626 recalc(void)
1627 {
1628   static int i, x, y;
1629
1630   minexp = maxexp = 0.0;
1631   x = y = 0;
1632   for (i=0;i<expind[frame];i++) {
1633     if (exponents[frame][i] < minexp)
1634       minexp = exponents[frame][i];
1635     if (exponents[frame][i] > maxexp)
1636       maxexp = exponents[frame][i];
1637   }
1638 }
1639
1640 static void
1641 Clear(void)
1642 {
1643       XClearWindow(dpy, canvas);
1644   XCopyArea(dpy, canvas, pixmap, Data_GC[0],
1645             0, 0, width, height, 0, 0);
1646   InitBuffer();
1647 }
1648
1649 static void
1650 show_defaults(void)
1651 {
1652
1653   printf("Width=%d  Height=%d  numcolors=%d  settle=%d  dwell=%d\n",
1654     width,height,numcolors,settle,dwell);
1655   printf("min_a=%f  a_range=%f  max_a=%f\n", min_a,a_range,max_a);
1656   printf("min_b=%f  b_range=%f  max_b=%f\n", min_b,b_range,max_b);
1657   printf("minlyap=%f  minexp=%f  maxexp=%f\n", minlyap,minexp,maxexp);
1658   exit(0);
1659 }
1660
1661 static void
1662 CreateXorGC(void)
1663 {
1664   XGCValues values;
1665
1666   values.foreground = foreground;
1667   values.line_style = LineSolid;
1668   values.function = GXxor;
1669   RubberGC = XCreateGC(dpy, DefaultRootWindow(dpy),
1670         GCForeground | GCBackground | GCFunction | GCLineStyle, &values);
1671 }
1672
1673 static void
1674 StartRubberBand(Window w, image_data_t *data, XEvent *event)
1675 {
1676   XPoint corners[5];
1677
1678   nostart = 0;
1679   data->rubber_band.last_x = data->rubber_band.start_x = event->xbutton.x;
1680   data->rubber_band.last_y = data->rubber_band.start_y = event->xbutton.y;
1681   SetupCorners(corners, data);
1682   XDrawLines(dpy, canvas, RubberGC,
1683       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1684 }
1685
1686 static void
1687 SetupCorners(XPoint *corners, image_data_t *data)
1688 {
1689   corners[0].x = data->rubber_band.start_x;
1690   corners[0].y = data->rubber_band.start_y;
1691   corners[1].x = data->rubber_band.start_x;
1692   corners[1].y = data->rubber_band.last_y;
1693   corners[2].x = data->rubber_band.last_x;
1694   corners[2].y = data->rubber_band.last_y;
1695   corners[3].x = data->rubber_band.last_x;
1696   corners[3].y = data->rubber_band.start_y;
1697   corners[4] = corners[0];
1698 }
1699
1700 static void
1701 TrackRubberBand(Window w, image_data_t *data, XEvent *event)
1702 {
1703   XPoint corners[5];
1704   int xdiff, ydiff;
1705
1706   if (nostart)
1707     return;
1708   SetupCorners(corners, data);
1709   XDrawLines(dpy, canvas, RubberGC,
1710       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1711   ydiff = event->xbutton.y - data->rubber_band.start_y;
1712   xdiff = event->xbutton.x - data->rubber_band.start_x;
1713   data->rubber_band.last_x = data->rubber_band.start_x + xdiff;
1714   data->rubber_band.last_y = data->rubber_band.start_y + ydiff;
1715   if (data->rubber_band.last_y < data->rubber_band.start_y ||
1716       data->rubber_band.last_x < data->rubber_band.start_x)
1717   {
1718     data->rubber_band.last_y = data->rubber_band.start_y;
1719     data->rubber_band.last_x = data->rubber_band.start_x;
1720   }
1721   SetupCorners(corners, data);
1722   XDrawLines(dpy, canvas, RubberGC,
1723       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1724 }
1725
1726 static void
1727 EndRubberBand(Window w, image_data_t *data, XEvent *event)
1728 {
1729   XPoint corners[5];
1730   XPoint top, bot;
1731   double delta, diff;
1732
1733   nostart = 1;
1734   SetupCorners(corners, data);
1735   XDrawLines(dpy, canvas, RubberGC,
1736       corners, sizeof(corners) / sizeof(corners[0]), CoordModeOrigin);
1737   if (data->rubber_band.start_x >= data->rubber_band.last_x ||
1738       data->rubber_band.start_y >= data->rubber_band.last_y)
1739     return;
1740   top.x = data->rubber_band.start_x;
1741   bot.x = data->rubber_band.last_x;
1742   top.y = data->rubber_band.start_y;
1743   bot.y = data->rubber_band.last_y;
1744   diff = data->q_max - data->q_min;
1745   delta = (double)top.y / (double)height;
1746   data->q_min += diff * delta;
1747   delta = (double)(height - bot.y) / (double)height;
1748   data->q_max -= diff * delta;
1749   diff = data->p_max - data->p_min;
1750   delta = (double)top.x / (double)width;
1751   data->p_min += diff * delta;
1752   delta = (double)(width - bot.x) / (double)width;
1753   data->p_max -= diff * delta;
1754   fflush(stdout);
1755   set_new_params(w, data);
1756 }
1757
1758 static void
1759 set_new_params(Window w, image_data_t *data)
1760 {
1761   frame = (maxframe + 1) % MAXFRAMES;
1762   if (frame > maxframe)
1763     maxframe = frame;
1764   a_range = data->p_max - data->p_min;
1765   b_range = data->q_max - data->q_min;
1766         a_minimums[frame] = min_a = data->p_min;
1767         b_minimums[frame] = min_b = data->q_min;
1768         a_inc = a_range / (double)width;
1769         b_inc = b_range / (double)height;
1770         point.x = -1;
1771         point.y = 0;
1772   run = 1;
1773         a = min_a;
1774         b = min_b;
1775         a_maximums[frame] = max_a = data->p_max;
1776         b_maximums[frame] = max_b = data->q_max;
1777   expind[frame] = 0;;
1778   Clear();
1779 }
1780
1781 static void
1782 go_down(void)
1783 {
1784   frame++;
1785   if (frame > maxframe)
1786     frame = 0;
1787   jumpwin();
1788 }
1789
1790 static void
1791 go_back(void)
1792 {
1793   frame--;
1794   if (frame < 0)
1795     frame = maxframe;
1796   jumpwin();
1797 }
1798
1799 static void
1800 jumpwin(void)
1801 {
1802   rubber_data.p_min = min_a = a_minimums[frame];
1803   rubber_data.q_min = min_b = b_minimums[frame];
1804   rubber_data.p_max = max_a = a_maximums[frame];
1805   rubber_data.q_max = max_b = b_maximums[frame];
1806   a_range = max_a - min_a;
1807   b_range = max_b - min_b;
1808         a_inc = a_range / (double)width;
1809         b_inc = b_range / (double)height;
1810         point.x = -1;
1811         point.y = 0;
1812         a = min_a;
1813         b = min_b;
1814   Clear();
1815   if (resized[frame])
1816     Redraw();
1817   else
1818     redraw(exponents[frame], expind[frame], 0);
1819 }
1820
1821 static void
1822 go_init(void)
1823 {
1824   frame = 0;
1825   jumpwin();
1826 }
1827
1828 static void
1829 Destroy_frame(void)
1830 {
1831   static int i;
1832
1833   for (i=frame; i<maxframe; i++) {
1834     exponents[frame] = exponents[frame+1];
1835     expind[frame] = expind[frame+1];
1836     a_minimums[frame] = a_minimums[frame+1];
1837     b_minimums[frame] = b_minimums[frame+1];
1838     a_maximums[frame] = a_maximums[frame+1];
1839     b_maximums[frame] = b_maximums[frame+1];
1840   }
1841   maxframe--;
1842   go_back();
1843 }
1844
1845 static void
1846 InitBuffer(void)
1847 {
1848   int i;
1849
1850   for (i = 0 ; i < maxcolor; ++i)
1851     Points.npoints[i] = 0;
1852 }
1853
1854 static void
1855 BufferPoint(Display *display, Window window, int color, int x, int y)
1856 {
1857   if (Points.npoints[color] == MAXPOINTS)
1858   {
1859     XDrawPoints(display, window, Data_GC[color],
1860         Points.data[color], Points.npoints[color], CoordModeOrigin);
1861     XDrawPoints(display, pixmap, Data_GC[color],
1862         Points.data[color], Points.npoints[color], CoordModeOrigin);
1863     Points.npoints[color] = 0;
1864   }
1865   Points.data[color][Points.npoints[color]].x = x;
1866   Points.data[color][Points.npoints[color]].y = y;
1867   ++Points.npoints[color];
1868 }
1869
1870 static void
1871 FlushBuffer(void)
1872 {
1873   int color;
1874
1875   for (color = 0; color < maxcolor; ++color)
1876     if (Points.npoints[color])
1877     {
1878         XDrawPoints(dpy, canvas, Data_GC[color],
1879           Points.data[color], Points.npoints[color],
1880           CoordModeOrigin);
1881         XDrawPoints(dpy, pixmap, Data_GC[color],
1882           Points.data[color], Points.npoints[color],
1883           CoordModeOrigin);
1884         Points.npoints[color] = 0;
1885     }
1886 }
1887
1888 static void
1889 print_help(void)
1890 {
1891     printf("During run-time, interactive control can be exerted via : \n");
1892     printf("Mouse buttons allow rubber-banding of a zoom box\n");
1893     printf("< halves the 'dwell', > doubles the 'dwell'\n");
1894     printf("[ halves the 'settle', ] doubles the 'settle'\n");
1895     printf("D flushes the drawing buffer\n");
1896     printf("e or E recalculates color indices\n");
1897     printf("f or F saves exponents to a file\n");
1898     printf("h or H or ? displays this message\n");
1899     printf("i decrements, I increments the stripe interval\n");
1900     printf("KJMN increase/decrease minimum negative exponent\n");
1901     printf("m increments the map index, changing maps\n");
1902     printf("p or P reverses the colormap for negative/positive exponents\n");
1903     printf("r redraws without recalculating\n");
1904     printf("R redraws, recalculating with new dwell and settle values\n");
1905     printf("s or S spins the colorwheel\n");
1906     printf("u pops back up to the last zoom\n");
1907     printf("U pops back up to the first picture\n");
1908     printf("v or V displays the values of various settings\n");
1909     printf("w decrements, W increments the color wheel index\n");
1910     printf("x or X clears the window\n");
1911     printf("q or Q exits\n");
1912 }
1913
1914 static void
1915 print_values(void)
1916 {
1917     static int i;
1918
1919     printf("\nminlyap=%f minexp=%f maxexp=%f\n",minlyap,minexp,maxexp);
1920     printf("width=%d height=%d\n",width,height);
1921     printf("settle=%d  dwell=%d start_x=%f\n",settle,dwell, start_x);
1922     printf("min_a=%f  a_rng=%f  max_a=%f\n",min_a,a_range,max_a);
1923     printf("min_b=%f  b_rng=%f  max_b=%f\n",min_b,b_range,max_b);
1924     if (Rflag)
1925   printf("pseudo-random forcing\n");
1926     else if (force) {
1927   printf("periodic forcing=");
1928   for (i=0;i<maxindex;i++)
1929     printf("%d",forcing[i]);
1930   printf("\n");
1931     }
1932     else
1933   printf("periodic forcing=01\n");
1934     if (Force) {
1935   printf("function forcing=");
1936   for (i=0;i<funcmaxindex;i++) {
1937     printf("%d",Forcing[i]);
1938   }
1939   printf("\n");
1940     }
1941     printf("numcolors=%d\n",numcolors-1);
1942 }
1943
1944 static void
1945 freemem(void)
1946 {
1947   static int i;
1948
1949         for (i=0;i<MAXFRAMES;i++)
1950                 free(exponents[i]);
1951 }
1952
1953 static void
1954 setupmem(void)
1955 {
1956   static int i;
1957
1958         for (i=0;i<MAXFRAMES;i++) {
1959                 if((exponents[i]=
1960                     (double *)malloc(sizeof(double)*width*height))==NULL){
1961                     fprintf(stderr,"Error malloc'ing exponent array.\n");
1962                     exit(-1);
1963                 }
1964         }
1965 }
1966
1967 static void
1968 setforcing(void)
1969 {
1970   static int i;
1971   for (i=0;i<MAXINDEX;i++)
1972     forcing[i] = (ya_random() > prob) ? 0 : 1;
1973 }