http://ftp.x.org/contrib/applications/xscreensaver-3.24.tar.gz
[xscreensaver] / hacks / flow.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* flow --- flow of strange bees */
3
4 #if !defined( lint ) && !defined( SABER )
5 static const char sccsid[] = "@(#)flow.c 4.10 98/04/24 xlockmore";
6
7 #endif
8
9 /*-
10  * Copyright (c) 1996 by Tim Auckland <Tim.Auckland@Sun.COM>
11  * Portions added by Stephen Davies are Copyright (c) 2000 Stephen Davies
12  *
13  * Permission to use, copy, modify, and distribute this software and its
14  * documentation for any purpose and without fee is hereby granted,
15  * provided that the above copyright notice appear in all copies and that
16  * both that copyright notice and this permission notice appear in
17  * supporting documentation.
18  *
19  * This file is provided AS IS with no warranties of any kind.  The author
20  * shall have no liability with respect to the infringement of copyrights,
21  * trade secrets or any patents by this file or any part thereof.  In no
22  * event will the author be liable for any lost revenue or profits or
23  * other special, indirect and consequential damages.
24  *
25  * "flow" shows a variety of continuous phase-space flows around strange
26  * attractors.  It includes the well-known Lorentz mask (the "Butterfly"
27  * of chaos fame), two forms of Rossler's "Folded Band" and Poincare'
28  * sections of the "Birkhoff Bagel" and Duffing's forced occilator.
29  *
30  * Revision History:
31  * 21-Feb-00: Major hackage by Chalky (Stephen Davies, chalky@null.net)
32  *            Forced perspective mode, added 3d box around attractor which
33  *            involved coding 3d-planar-clipping against the view-frustrum
34  *            thingy. Also made view alternate between piggybacking on a 'bee'
35  *            to zooming around outside the attractor. Most bees slow down and
36  *            stop, to make the structure of the attractor more obvious.
37  * 31-Nov-98: [TDA] Added Duffing  (what a strange day that was :) DAB)
38  *   Duffing's forced oscillator has been added to the formula list and
39  *   the parameters section has been updated to display it in Poincare'
40  *   section.
41  * 30-Nov-98: [TDA] Added travelling perspective option
42  *   A more exciting point-of-view has been added to all autonomous flows.
43  *   This views the flow as seen by a particle moving with the flow.  In the
44  *   metaphor of the original code, I've attached a camera to one of the
45  *   trained bees!
46  * 30-Nov-98: [TDA] Much code cleanup.
47  * 09-Apr-97: [TDA] Ported to xlockmore-4
48  * 18-Jul-96: Adapted from swarm.c Copyright (c) 1991 by Patrick J. Naughton.
49  * 31-Aug-90: Adapted from xswarm by Jeff Butterworth. (butterwo@ncsc.org)
50  */
51
52 #ifdef STANDALONE
53 # define PROGCLASS      "Flow"
54 # define HACK_INIT      init_flow
55 # define HACK_DRAW      draw_flow
56 # define flow_opts      xlockmore_opts
57 # define DEFAULTS       "*delay:                1000 \n" \
58                                         "*count:                500 \n" \
59                                         "*cycles:               3000 \n" \
60                                         "*ncolors:              200 \n" \
61         "*rotate:         True \n" \
62         "*ride:           True \n" \
63         "*zoom:           True \n" \
64         "*allow2d:        True \n" \
65         "*box:            True \n" \
66         "*slow:           True \n" \
67         "*freeze:         True \n"
68 # define SMOOTH_COLORS
69 # include "xlockmore.h"         /* in xscreensaver distribution */
70 # include "erase.h"
71
72 #else /* STANDALONE */
73 # include "xlock.h"             /* in xlockmore distribution */
74 #endif /* STANDALONE */
75
76 XrmOptionDescRec flow_options[];
77 ModeSpecOpt flow_opts = { 7, flow_options, 0, NULL, NULL };
78
79 #ifdef USE_MODULES
80 ModStruct   flow_description = {
81         "flow", "init_flow", "draw_flow", "release_flow",
82         "refresh_flow", "init_flow", NULL, &flow_opts,
83         1000, 1024, 3000, 1, 64, 1.0, "",
84         "Shows dynamic strange attractors", 0, NULL
85 };
86
87 #endif
88
89 typedef struct {
90         double      x;
91         double      y;
92         double      z;
93 } dvector;
94
95 typedef struct {
96         double      a, b, c;
97 } Par;
98
99 /* Macros */
100 #define X(t,b)  (sp->p[t][b].x)
101 #define Y(t,b)  (sp->p[t][b].y)
102 #define Z(t,b)  (sp->p[t][b].z)
103 #define balance_rand(v) ((LRAND()/MAXRAND*(v))-((v)/2)) /* random around 0 */
104 #define SCALE_X(A) (sp->width/2+sp->width/sp->size*(A))
105 /*#define SCALE_Y(A) (sp->height/2+sp->height/sp->size*(A))*/
106 #define SCALE_Y(A) (sp->height/2+sp->width/sp->size*(A))
107
108 /* Mode of operation. Rotate, ride and zoom are mutually exclusive */
109 typedef enum {
110         FLOW_ROTATE = 1, /* Rotate around attractor */
111         FLOW_RIDE = 2,   /* Ride a trained bee */
112         FLOW_ZOOM = 4,   /* Zoom in and out */
113         FLOW_2D = 8,     /* Allow 2D attractors */
114         FLOW_BOX = 16,    /* Compute a box around the attractor */
115         FLOW_SLOW = 32,   /* Some bees are slower (and have antifreeze) */
116         FLOW_FREEZE = 64, /* Freeze some of the bees in action */
117 } FlowMode;
118
119 #define FLOW_DEFAULT (FLOW_ROTATE|FLOW_RIDE|FLOW_ZOOM|FLOW_2D|\
120                 FLOW_BOX|FLOW_SLOW|FLOW_FREEZE)
121
122 typedef struct {
123         int         width;
124         int         height;
125         int         count;
126         double      size;
127         
128         int         beecount;   /* number of bees */
129         XSegment   *csegs;          /* bee lines */
130         int        *cnsegs;
131         XSegment   *old_segs;   /* old bee lines */
132         int         nold_segs;
133         double      step;
134         double          slow;
135         double          slow_view;
136         dvector     centre;             /* centre */
137         dvector         range;
138         struct {
139                 double  depth;
140                 double  height;
141         }           view;
142         dvector         circle[2]; /* POV that circles around the scene */
143         dvector    *p[2];   /* bee positions x[time][bee#] */
144         struct {
145                 double  theta;
146                 double  dtheta;
147                 double  phi;
148                 double  dphi;
149         }           tumble;
150         dvector  (*ODE) (Par par, double x, double y, double z);
151         Par         par;
152         FlowMode                mode; /* Mode of operation */
153 } flowstruct;
154
155 static flowstruct *flows = NULL;
156
157 static dvector
158 Lorentz(Par par, double x, double y, double z)
159 {
160         dvector d;
161
162         d.x = par.a * (y - x);
163         d.y = x * (par.b - z) - y;
164         d.z = x * y - par.c * z;
165         return d;
166 }
167
168 static dvector
169 Rossler(Par par, double x, double y, double z)
170 {
171         dvector d;
172
173         d.x = -(y + par.a * z);
174         d.y = x + y * par.b;
175         d.z = par.c + z * (x - 5.7);
176         return d;
177 }
178
179 static dvector
180 RosslerCone(Par par, double x, double y, double z)
181 {
182         dvector d;
183
184         d.x = -(y + par.a * z);
185         d.y = x + y * par.b - z * z * par.c;
186         d.z = 0.2 + z * (x - 5.7);
187         return d;
188 }
189
190 static dvector
191 Birkhoff(Par par, double x, double y, double z)
192 {
193         dvector d;
194
195         d.x = -y + par.b * sin(z);
196         d.y = 0.7 * x + par.a * y * (0.1 - x * x);
197         d.z = par.c;
198         return d;
199 }
200
201 static dvector
202 Duffing(Par par, double x, double y, double z)
203 {
204         dvector d;
205
206         d.x = -par.a * x - y/2 - y * y * y/8 + par.b * cos(z);
207         d.y = 2*x;
208         d.z = par.c;
209         return d;
210 }
211
212 void init_clip(flowstruct *sp);
213
214 void
215 init_flow(ModeInfo * mi)
216 {
217         flowstruct *sp;
218         int         b;
219         double      beemult = 1;
220         static int  allocated = 0;
221
222         if (flows == NULL) {
223                 if ((flows = (flowstruct *) calloc(MI_NUM_SCREENS(mi),
224                                                sizeof (flowstruct))) == NULL)
225                         return;
226         }
227         sp = &flows[MI_SCREEN(mi)];
228
229         sp->count = 0;
230         sp->slow = 0.999;
231         sp->slow_view = 0.90;
232
233         sp->width = MI_WIDTH(mi);
234         sp->height = MI_HEIGHT(mi);
235
236         sp->tumble.theta = balance_rand(M_PI);
237         sp->tumble.phi = balance_rand(M_PI);
238         sp->tumble.dtheta = 0.002;
239         sp->tumble.dphi = 0.001;
240         sp->view.height = 0;
241         sp->view.depth = 0; /* no perspective view */
242         sp->mode = 0;
243    if (get_boolean_resource ("rotate", "Boolean")) sp->mode |= FLOW_ROTATE;
244    if (get_boolean_resource ("ride", "Boolean")) sp->mode |= FLOW_RIDE;
245    if (get_boolean_resource ("zoom", "Boolean")) sp->mode |= FLOW_ZOOM;
246    if (get_boolean_resource ("allow2d", "Boolean")) sp->mode |= FLOW_2D;
247    if (get_boolean_resource ("slow", "Boolean")) sp->mode |= FLOW_SLOW;
248    if (get_boolean_resource ("freeze", "Boolean")) sp->mode |= FLOW_FREEZE;
249    if (get_boolean_resource ("box", "Boolean")) sp->mode |= FLOW_BOX;
250
251         b = (sp->mode & FLOW_2D) ? 5 : 3;
252         b = NRAND(b);
253
254         /* If more than one of rotate, ride and zoom are set, choose one */
255         if (b < 3) {
256                 int num = 0, modes[3];
257
258                 if (sp->mode & FLOW_ROTATE) modes[num++] = FLOW_ROTATE;
259                 if (sp->mode & FLOW_RIDE) modes[num++] = FLOW_RIDE;
260                 if (sp->mode & FLOW_ZOOM) modes[num++] = FLOW_ZOOM;
261
262                 sp->mode &= ~(FLOW_ROTATE | FLOW_RIDE | FLOW_ZOOM);
263
264                 if (num) sp->mode |= modes[ NRAND(num) ];
265                 else sp->mode |= FLOW_ZOOM;
266         }
267         
268         switch (b) {
269         case 0:
270                 sp->view.depth = 10;
271                 sp->view.height = 0.2;
272                 beemult = 3;
273                 sp->ODE = Lorentz;
274                 sp->step = 0.02;
275                 sp->size = 60;
276                 sp->centre.x = 0;
277                 sp->centre.y = 0;
278                 sp->centre.z = 24;
279                 sp->range.x = 5;
280                 sp->range.y = 5;
281                 sp->range.z = 1;
282                 sp->par.a = 10 + balance_rand(5);
283                 sp->par.b = 28 + balance_rand(5);
284                 sp->par.c = 2 + balance_rand(1);
285                 break;
286         case 1:
287                 sp->view.depth = 10;
288                 sp->view.height = 0.1;
289                 beemult = 4;
290                 sp->ODE = Rossler;
291                 sp->step = 0.05;
292                 sp->size = 24;
293                 sp->centre.x = 0;
294                 sp->centre.y = 0;
295                 sp->centre.z = 3;
296                 sp->range.x = 4;
297                 sp->range.y = 4;
298                 sp->range.z = 7;
299                 sp->par.a = 2 + balance_rand(1);
300                 sp->par.b = 0.2 + balance_rand(0.1);
301                 sp->par.c = 0.2 + balance_rand(0.1);
302                 break;
303         case 2:
304                 sp->view.depth = 10;
305                 sp->view.height = 0.1;
306                 beemult = 3;
307                 sp->ODE = RosslerCone;
308                 sp->step = 0.05;
309                 sp->size = 24;
310                 sp->centre.x = 0;
311                 sp->centre.y = 0;
312                 sp->centre.z = 3;
313                 sp->range.x = 4;
314                 sp->range.y = 4;
315                 sp->range.z = 4;
316                 sp->par.a = 2;
317                 sp->par.b = 0.2;
318                 sp->par.c = 0.25 + balance_rand(0.09);
319                 break;
320         case 3:
321                 sp->ODE = Birkhoff;
322                 sp->step = 0.04;
323                 sp->size = 2.6;
324                 sp->centre.x = 0;
325                 sp->centre.y = 0;
326                 sp->centre.z = 0;
327                 sp->range.x = 3;
328                 sp->range.y = 4;
329                 sp->range.z = 0;
330                 sp->par.a = 10 + balance_rand(5);
331                 sp->par.b = 0.35 + balance_rand(0.25);
332                 sp->par.c = 1.57;
333                 sp->tumble.theta = 0;
334                 sp->tumble.phi = 0;
335                 sp->tumble.dtheta = 0;
336                 sp->tumble.dphi = 0;
337                 break;
338         case 4:
339         default:
340                 sp->ODE = Duffing;
341                 sp->step = 0.02;
342                 sp->size = 30;
343                 sp->centre.x = 0;
344                 sp->centre.y = 0;
345                 sp->centre.z = 0;
346                 sp->range.x = 20;
347                 sp->range.y = 20;
348                 sp->range.z = 0;
349                 sp->par.a = 0.2 + balance_rand(0.1);
350                 sp->par.b = 27.0 + balance_rand(3.0);
351                 sp->par.c = 1.33;
352                 sp->tumble.theta = 0;
353                 sp->tumble.phi = 0;
354                 sp->tumble.dtheta = -NRAND(2)*sp->par.c*sp->step;
355                 sp->tumble.dphi = 0;
356                 beemult = 0.5;
357                 break;
358         }
359
360         sp->view.depth *= 4;
361
362         sp->beecount = beemult * MI_COUNT(mi);
363         if (sp->beecount < 0)   /* random variations */ 
364                 sp->beecount = NRAND(-sp->beecount) + 1; /* Minimum 1 */
365
366         /* Clear the background. */
367         MI_CLEARWINDOW(mi);
368
369         if(!allocated || sp->beecount != allocated){ /* reallocate */
370                 if (sp->csegs != NULL) {
371                         (void) free((void *) sp->csegs);
372                         sp->csegs = NULL;
373                 }
374                 if (sp->cnsegs != NULL) {
375                         (void) free((void *) sp->cnsegs);
376                         sp->cnsegs = NULL;
377                 }
378                 if (sp->old_segs != NULL) {
379                         (void) free((void *) sp->old_segs);
380                         sp->old_segs = NULL;
381                 }
382                 if (sp->p[0] != NULL) {
383                         (void) free((void *) sp->p[0]);
384                         sp->p[0] = NULL;
385                 }
386                 if (sp->p[1] != NULL) {
387                         (void) free((void *) sp->p[1]);
388                         sp->p[1] = NULL;
389                 }
390                 allocated = sp->beecount;
391         }
392
393         /* Allocate memory. */
394
395         if (!sp->csegs) {
396                 sp->csegs = (XSegment *) malloc(sizeof (XSegment) * sp->beecount
397                                                 * MI_NPIXELS(mi));
398                 sp->cnsegs = (int *) malloc(sizeof (int) * MI_NPIXELS(mi));
399
400                 sp->old_segs = (XSegment *) malloc(sizeof (XSegment) * sp->beecount);
401                 sp->p[0] = (dvector *) malloc(sizeof (dvector) * sp->beecount);
402                 sp->p[1] = (dvector *) malloc(sizeof (dvector) * sp->beecount);
403         }
404
405         /* Initialize point positions, velocities, etc. */
406
407         for (b = 0; b < sp->beecount; b++) {
408                 X(1, b) = X(0, b) = balance_rand(sp->range.x);
409                 Y(1, b) = Y(0, b) = balance_rand(sp->range.y);
410                 Z(1, b) = Z(0, b) = balance_rand(sp->range.z);
411         }
412
413         init_clip(sp);
414
415 }
416
417 /* Clipping planes */
418 #define PLANES 5
419 static double plane_orig[][2][3] = {
420         /* X goes into screen, Y goes right, Z goes down(up?) */
421         /* {Normal}, {Point} */
422         { {1.0, 0, 0}, {0.01, 0, 0} },
423         { {1.0, 1.0, 0.0}, {0, 0, 0} },
424         { {1.0,-1.0, 0.0}, {0, 0, 0} },
425         { {1.0, 0.0, 1.0}, {0, 0, 0} },
426         { {1.0, 0.0,-1.0}, {0, 0, 0} }
427 };
428 static double plane[PLANES][2][3];
429 static double plane_d[PLANES];
430
431 #define BOX_P 32
432 #define BOX_L 36
433 #define MIN_BOX (3)
434 #define MAX_BOX (MIN_BOX + BOX_L)
435 /* Points that make up the box (normalized coordinates) */
436 static double box_orig[][3] = {
437         {1,1,1},   /* 0 */
438         {1,1,-1},  /* 1 */
439         {1,-1,-1}, /* 2 */
440         {1,-1,1},  /* 3 */
441         {-1,1,1},  /* 4 */
442         {-1,1,-1}, /* 5 */
443         {-1,-1,-1},/* 6 */
444         {-1,-1,1}, /* 7 */
445         {1, .8, .8},
446         {1, .8,-.8},
447         {1,-.8,-.8},
448         {1,-.8, .8},
449         { .8,1, .8},
450         { .8,1,-.8},
451         {-.8,1,-.8},
452         {-.8,1, .8},
453         { .8, .8,1},
454         { .8,-.8,1},
455         {-.8,-.8,1},
456         {-.8, .8,1},
457         {-1, .8, .8},
458         {-1, .8,-.8},
459         {-1,-.8,-.8},
460         {-1,-.8, .8},
461         { .8,-1, .8},
462         { .8,-1,-.8},
463         {-.8,-1,-.8},
464         {-.8,-1, .8},
465         { .8, .8,-1},
466         { .8,-.8,-1},
467         {-.8,-.8,-1},
468         {-.8, .8,-1}
469 };
470
471 /* Container for scaled box points */
472 static double box[BOX_P][3];
473
474 /* Lines connecting the box dots */
475 static double lines[0][2] = {
476         {0,1}, {1,2}, {2,3}, {3,0}, /* box */
477         {4,5}, {5,6}, {6,7}, {7,4},
478         {0,4}, {1,5}, {2,6}, {3,7},
479         {4+4,5+4}, {5+4,6+4}, {6+4,7+4}, {7+4,4+4},
480         {4+8,5+8}, {5+8,6+8}, {6+8,7+8}, {7+8,4+8},
481         {4+12,5+12}, {5+12,6+12}, {6+12,7+12}, {7+12,4+12},
482         {4+16,5+16}, {5+16,6+16}, {6+16,7+16}, {7+16,4+16},
483         {4+20,5+20}, {5+20,6+20}, {6+20,7+20}, {7+20,4+20},
484         {4+24,5+24}, {5+24,6+24}, {6+24,7+24}, {7+24,4+24},
485 };
486         
487 /* Boundaries of bees */
488 double xmin, xmax;
489 double ymin, ymax;
490 double zmin, zmax;
491
492 void init_clip(flowstruct *sp)
493 {
494         int i;
495
496         /* Scale the planes to the screen. I had to invert the projection
497          * algorithms so that when projected they would be right at the edge of the
498          * screen. */
499         double width = sp->size/sp->view.depth/2;
500         double height = sp->size/sp->view.depth/2*sp->view.height/sp->view.height;
501         for (i = 0; i < PLANES; i++) {
502                 /* Copy orig planes into planes, expanding <-> clippings */
503                 plane[i][0][0] = plane_orig[i][0][0];
504                 plane[i][0][1] = plane_orig[i][0][1] / width;
505                 plane[i][0][2] = plane_orig[i][0][2] / height;
506                 plane[i][1][0] = plane_orig[i][1][0];
507                 plane[i][1][1] = plane_orig[i][1][1];
508                 plane[i][1][2] = plane_orig[i][1][2];
509                 
510                 /* Calculate the 'd' part of 'ax + by + cz = d' */
511                 plane_d[i] = - plane[i][0][0] * plane[i][1][0];
512                 plane_d[i] -= plane[i][0][1] * plane[i][1][1];
513                 plane_d[i] -= plane[i][0][2] * plane[i][1][2];
514         }
515         xmin = X(0, i); xmax = X(0,i);
516         ymin = Y(0, i); ymax = Y(0,i);
517         zmin = Z(0, i); zmax = Z(0,i);
518 }
519
520 /* Scale the box defined above to fit around all points */
521 void create_box(flowstruct *sp)
522 {
523         int i = MAX_BOX;
524         double xmid, ymid, zmid;
525         double xsize, ysize, zsize;
526         double size;
527
528         /* Count every 5th point for speed.. */
529         for (; i < sp->beecount; i += 5) {
530                 if ( X(0,i) < xmin ) xmin = X(0, i);
531                 else if ( X(0,i) > xmax ) xmax = X(0, i);
532                 if ( Y(0,i) < ymin ) ymin = Y(0, i);
533                 else if ( Y(0,i) > ymax ) ymax = Y(0, i);
534                 if ( Z(0,i) < zmin ) zmin = Z(0, i);
535                 else if ( Z(0,i) > zmax ) zmax = Z(0, i);
536         }
537         xmid = (xmax+xmin)/2;
538         ymid = (ymax+ymin)/2;
539         zmid = (zmax+zmin)/2;
540         xsize = xmax - xmin;
541         ysize = ymax - ymin;
542         zsize = zmax - zmin;
543         size = xsize;
544         if (ysize> size) size = ysize;
545         if (zsize > size) size = zsize;
546         size /= 2;
547
548         /* Scale box */
549         for (i = 0; i < BOX_P; i++) {
550                 box[i][0] = box_orig[i][0] * size + xmid;
551                 box[i][1] = box_orig[i][1] * size + ymid;
552                 box[i][2] = box_orig[i][2] * size + zmid;
553         }
554
555 }
556
557 /* Returns true if point is infront of the plane (rather than behind) */
558 int infront_of(double x, double y, double z, int i)
559 {
560         double sum = plane[i][0][0]*x + plane[i][0][1]*y + plane[i][0][2]*z + plane_d[i];
561         return sum >= 0.0;
562 }
563
564 /* Returns true if line was behind a clip plane, or clips the line */
565 int clip(double *x1, double *y1, double *z1, double *x2, double *y2, double *z2)
566 {
567         int i;
568         for (i = 0; i < PLANES; i++) {
569                 double t;
570                 double x, y, z; /* Intersection point */
571                 double dx, dy, dz; /* line delta */
572                 int front1, front2;
573                 front1 = infront_of(*x1, *y1, *z1, i);
574                 front2 = infront_of(*x2, *y2, *z2, i);
575                 if (!front1 && !front2) return 1;
576                 if (front1 && front2) continue;
577
578                 dx = *x2 - *x1;
579                 dy = *y2 - *y1;
580                 dz = *z2 - *z1;
581
582                 /* Find t in line equation */
583                 t = ( plane_d[i] - 
584                                 plane[i][0][0]*(*x1) - plane[i][0][1]*(*y1) - plane[i][0][2]*(*z1) ) 
585                                 / 
586                         ( plane[i][0][0]*dx + plane[i][0][1]*dy + plane[i][0][2]*dz );
587
588                 x = *x1 + dx * t;
589                 y = *y1 + dy * t;
590                 z = *z1 + dz * t;
591                 /* Make point that was behind to be the intersect */
592                 if (front2) {
593                         *x1 = x;
594                         *y1 = y;
595                         *z1 = z;
596                 } else {
597                         *x2 = x;
598                         *y2 = y;
599                         *z2 = z;
600                 }
601         }
602         return 0;
603 }       
604
605
606 void
607 draw_flow(ModeInfo * mi)
608 {
609         Display    *display = MI_DISPLAY(mi);
610         Window      window = MI_WINDOW(mi);
611         GC          gc = MI_GC(mi);
612         flowstruct *sp = &flows[MI_SCREEN(mi)];
613         int         b, c, i;
614         int         col, ix;
615         int                     new_view = 0;
616         double      M[3][3]; /* transformation matrix */
617         double          step_view = sp->step;
618         double          step_bees = sp->step;
619         double          step_slow = sp->step;
620         double          pp, pc;
621
622         create_box(sp);
623
624         if(!sp->view.depth){ /* simple 3D tumble */
625                 double      sint, cost, sinp, cosp;
626                 sp->tumble.theta += sp->tumble.dtheta;
627                 sp->tumble.phi += sp->tumble.dphi;
628                 sint = sin(sp->tumble.theta);
629                 cost = cos(sp->tumble.theta);
630                 sinp = sin(sp->tumble.phi);
631                 cosp = cos(sp->tumble.phi);
632                 M[0][0]= cost; M[0][1]=-sint*cosp; M[0][2]= sint*sinp;
633                 M[1][0]= sint; M[1][1]= cost*cosp; M[1][2]=-cost*sinp;
634                 M[2][0]= 0;    M[2][1]= 0;         M[2][2]= 1;
635         } else { /* initialize matrix */
636                 M[0][0]= 0; M[0][1]= 0; M[0][2]= 0;
637                 M[1][0]= 0; M[1][1]= 0; M[1][2]= 0;
638                 M[2][0]= 0; M[2][1]= 0; M[2][2]= 0;
639
640         }
641
642         for (col = 0; col < MI_NPIXELS(mi); col++)
643                 sp->cnsegs[col] = 0;
644
645         MI_IS_DRAWN(mi) = True;
646
647         /* Calculate circling POV */
648         sp->circle[1] = sp->circle[0];
649         sp->circle[0].x = sp->size * 2 * sin(sp->count / 40.0) * (0.6 + 0.4 *cos(sp->count / 100.0));
650         sp->circle[0].y = sp->size * 2 * cos(sp->count / 40.0) * (0.6 + 0.4 *cos(sp->count / 100.0));
651         sp->circle[0].z = sp->size * 2 * sin(sp->count / 421.0);
652
653         if (sp->mode & FLOW_ROTATE)
654                 pp = 0;
655         else if (sp->mode & FLOW_RIDE)
656                 pp = 1;
657         else /* ZOOM */
658                 /* Bistable oscillator to switch between the trained bee and the circler */
659                 pp = -sin(sin(sin(cos(sp->count / 150.0)*M_PI/2)*M_PI/2)*M_PI/2) *0.5 + 0.5;
660         pc = 1 - pp;
661
662
663         /* Slow down or speed up the bees / view: */
664
665         /* exponentially accelerate towards zero */
666         sp->slow = sp->slow * 1.005 - 0.005; 
667         if (sp->slow < 0) sp->slow = 0;
668
669         sp->slow_view = sp->slow_view * 1.005 - 0.005;
670         if (sp->slow_view < 0) sp->slow_view = 0;
671
672         /* View speeds up, slow bees slow to half speed, and other bees will
673          * actually stop */
674         step_view = step_view * (1.01 - sp->slow_view * sp->slow_view) * 0.2;
675         step_slow = step_slow * (sp->slow + 0.5) / 2;
676         if (sp->mode & FLOW_SLOW)
677                 step_bees = step_bees * sp->slow;
678         else
679                 step_bees = step_slow;
680
681         /* <=- Bees -=> */
682         for (b = 0; b < sp->beecount; b++) {
683                 /* Calc if this bee is slow. Note normal bees are exempt from
684                  * calculations once they slow to half speed, so that they remain as
685                  * frozen lines rather than barely-visible points */
686                 int slow = ((b & 0x7) == 0);
687                 if ( !(sp->mode & FLOW_FREEZE) ) slow = 1;
688                 /* Age the arrays. */
689                 if (b < 2 || sp->slow > 0.5 || slow) {
690                         X(1, b) = X(0, b);
691                         Y(1, b) = Y(0, b);
692                         Z(1, b) = Z(0, b);
693
694                         /* 2nd order Kunge Kutta */
695                         {
696                                 dvector     k1, k2;
697                                 double          step;
698
699                                 if (b == 0 || b == 1) {
700                                         step = step_view;
701                                 } else if (slow) {
702                                         step = step_slow;
703                                 } else {
704                                         step = step_bees;
705                                 }
706                                 k1 = sp->ODE(sp->par, X(1, b), Y(1, b), Z(1, b));
707                                 k1.x *= step;
708                                 k1.y *= step;
709                                 k1.z *= step;
710                                 k2 = sp->ODE(sp->par, X(1, b) + k1.x, Y(1, b) + k1.y, Z(1, b) + k1.z);
711                                 k2.x *= step;
712                                 k2.y *= step;
713                                 k2.z *= step;
714                                 X(0, b) = X(1, b) + (k1.x + k2.x) / 2.0;
715                                 Y(0, b) = Y(1, b) + (k1.y + k2.y) / 2.0;
716                                 Z(0, b) = Z(1, b) + (k1.z + k2.z) / 2.0;
717                         }
718                 }
719
720
721                 /* Colour according to bee */
722                 col = b % (MI_NPIXELS(mi) - 1);
723                 ix = col * sp->beecount + sp->cnsegs[col];
724
725                 /* Fill the segment lists. */
726
727                 if(sp->view.depth) { /* perspective view has special points */
728                         if(b==0){ /* point of view */
729                                 sp->centre.x = X(0, b) * pp + sp->circle[0].x * pc;
730                                 sp->centre.y = Y(0, b) * pp + sp->circle[0].y * pc;
731                                 sp->centre.z = Z(0, b) * pp + sp->circle[0].z * pc;
732                                 /*printf("center: (%3.3f,%3.3f,%3.3f)\n",sp->centre.x, sp->centre.y, sp->centre.z);*/
733                         }else if(b==1){ /* neighbour: used to compute local axes */
734                                 double x[3], p[3], x2=0, xp=0, C[3][3];
735                                 int j;
736
737                                 /* forward */                           
738                                 x[0] = X(0, 0) - X(1, 0);
739                                 x[1] = Y(0, 0) - Y(1, 0);
740                                 x[2] = Z(0, 0) - Z(1, 0);
741                         
742                                 /* neighbour */
743                                 p[0] = X(0, 1) - X(1, 0);
744                                 p[1] = Y(0, 1) - Y(1, 0);
745                                 p[2] = Z(0, 1) - Z(1, 0);
746
747                                 for(i=0; i<3; i++){
748                                         x2+= x[i]*x[i];    /* X . X */
749                                         xp+= x[i]*p[i];    /* X . P */
750                                         M[0][i] = x[i];    /* X */
751                                 }
752
753                                 for(i=0; i<3; i++)               /* (X x P) x X */
754                                         M[1][i] = x2*p[i] - xp*x[i]; /* == (X . X) P - (X . P) X */
755                                 
756                                 M[2][0] =  x[1]*p[2] - x[2]*p[1]; /* X x P */
757                                 M[2][1] = -x[0]*p[2] + x[2]*p[0];
758                                 M[2][2] =  x[0]*p[1] - x[1]*p[0];
759
760                                 /* normalise axes */
761                                 for(j=0; j<3; j++){
762                                         double A=0;
763                                         for(i=0; i<3; i++) A+=M[j][i]*M[j][i]; /* sum squares */
764                                         A=sqrt(A);
765                                         for(i=0; i<3; i++) M[j][i]/=A;
766                                 }
767
768                                 X(0, 1)=X(0, 0)+M[1][0]; /* adjust neighbour */
769                                 Y(0, 1)=Y(0, 0)+M[1][1];
770                                 Z(0, 1)=Z(0, 0)+M[1][2];
771
772                                 /* Look at trained bee into C matrix */
773                                 /* forward */                           
774                                 x[0] = 0 - sp->circle[0].x;
775                                 x[1] = 0 - sp->circle[0].y;
776                                 x[2] = 0 - sp->circle[0].z;
777                         
778                                 /* neighbour */
779                                 p[0] = sp->circle[0].x - sp->circle[1].x;
780                                 p[1] = sp->circle[0].y - sp->circle[1].y;
781                                 p[2] = sp->circle[0].z - sp->circle[1].z;
782
783                                 for(i=0; i<3; i++){
784                                         x2+= x[i]*x[i];    /* X . X */
785                                         xp+= x[i]*p[i];    /* X . P */
786                                         C[0][i] = x[i];    /* X */
787                                 }
788
789                                 for(i=0; i<3; i++)               /* (X x P) x X */
790                                         C[1][i] = x2*p[i] - xp*x[i]; /* == (X . X) P - (X . P) X */
791                                 
792                                 C[2][0] =  x[1]*p[2] - x[2]*p[1]; /* X x P */
793                                 C[2][1] = -x[0]*p[2] + x[2]*p[0];
794                                 C[2][2] =  x[0]*p[1] - x[1]*p[0];
795
796                                 /* normalise axes */
797                                 for(j=0; j<3; j++){
798                                         double A=0;
799                                         for(i=0; i<3; i++) A+=C[j][i]*C[j][i]; /* sum squares */
800                                         A=sqrt(A);
801                                         for(i=0; i<3; i++) C[j][i]/=A;
802                                 }
803
804                                 /* Interpolate between Center and Trained Bee matrices */
805                                 /* This isn't very accurate and leads to weird transformations
806                                  * (shearing, etc), but it works. Besides, sometimes they look
807                                  * cool :) */
808                                 pp = pp * pp; /* Don't follow bee's direction until very close */
809                                 pc = 1 - pp;
810                                 for (i = 0; i < 3; i++)
811                                         for (j = 0; j < 3; j++)
812                                                 M[i][j] = M[i][j] * pp + C[i][j] * pc;
813                                 
814
815 #if 0  /* display local axes for testing */
816                                 X(1, b)=X(0, 0);
817                                 Y(1, b)=Y(0, 0);
818                                 Z(1, b)=Z(0, 0);
819                         }else if(b==2){
820                                 X(0, b)=X(0, 0)+0.5*M[0][0];
821                                 Y(0, b)=Y(0, 0)+0.5*M[0][1];
822                                 Z(0, b)=Z(0, 0)+0.5*M[0][2];
823                                 X(1, b)=X(0, 0);
824                                 Y(1, b)=Y(0, 0);
825                                 Z(1, b)=Z(0, 0);
826                         }else if(b==3){
827                                 X(0, b)=X(0, 0)+1.5*M[2][0];
828                                 Y(0, b)=Y(0, 0)+1.5*M[2][1];
829                                 Z(0, b)=Z(0, 0)+1.5*M[2][2];
830                                 X(1, b)=X(0, 0);
831                                 Y(1, b)=Y(0, 0);
832                                 Z(1, b)=Z(0, 0);
833 #endif
834                         /* Draw a box... */
835                         }
836                 }
837                         if (b >= MIN_BOX && b < MAX_BOX) {
838                                 int p1 = lines[b-MIN_BOX][0];
839                                 int p2 = lines[b-MIN_BOX][1];
840                                 X(0, b) = box[p1][0]; Y(0, b) = box[p1][1]; Z(0, b) = box[p1][2];
841                                 X(1, b) = box[p2][0]; Y(1, b) = box[p2][1]; Z(1, b) = box[p2][2];
842                         }
843                 
844                 
845 #if 0   /* Original code */
846                 for(i=0; i<2; i++){
847                         double x=X(i,b)-sp->centre.x;
848                         double y=Y(i,b)-sp->centre.y;
849                         double z=Z(i,b)-sp->centre.z;
850                         double X=M[0][0]*x + M[0][1]*y + M[0][2]*z;
851                         double Y=M[1][0]*x + M[1][1]*y + M[1][2]*z;
852                         double Z=M[2][0]*x + M[2][1]*y + M[2][2]*z+sp->view.height;
853                         double absx, absy;                              
854                         if(sp->view.depth){
855                                 if(X <= 0) break;
856                                 absx=SCALE_X(sp->view.depth*Y/X);
857                                 absy=SCALE_Y(sp->view.depth*Z/X);
858                                 if(absx < -sp->width || absx > 2*sp->width ||
859                                    absy < -sp->height || absy > 2*sp->height)
860                                         break;
861                         }else{
862                                 absx=SCALE_X(X);
863                                 absy=SCALE_Y(Y);
864                         }
865                         if(i){
866                                 sp->csegs[ix].x1 = (short) absx;
867                                 sp->csegs[ix].y1 = (short) absy;
868                         }else{
869                                 sp->csegs[ix].x2 = (short) absx;
870                                 sp->csegs[ix].y2 = (short) absy;
871                         }
872                 }
873                 if(i == 2) /* both assigned */
874                         sp->cnsegs[col]++;
875 #else   
876                 /* Chalky's code w/ clipping */
877                 if (b < ((sp->mode & FLOW_BOX) ? 2 : MAX_BOX))
878                         continue;
879                 do {
880                         double x1=X(0,b)-sp->centre.x;
881                         double y1=Y(0,b)-sp->centre.y;
882                         double z1=Z(0,b)-sp->centre.z;
883                         double X1=M[0][0]*x1 + M[0][1]*y1 + M[0][2]*z1;
884                         double Y1=M[1][0]*x1 + M[1][1]*y1 + M[1][2]*z1;
885                         double Z1=M[2][0]*x1 + M[2][1]*y1 + M[2][2]*z1+sp->view.height;
886                         double absx1, absy1;                            
887                         double x2=X(1,b)-sp->centre.x;
888                         double y2=Y(1,b)-sp->centre.y;
889                         double z2=Z(1,b)-sp->centre.z;
890                         double X2=M[0][0]*x2 + M[0][1]*y2 + M[0][2]*z2;
891                         double Y2=M[1][0]*x2 + M[1][1]*y2 + M[1][2]*z2;
892                         double Z2=M[2][0]*x2 + M[2][1]*y2 + M[2][2]*z2+sp->view.height;
893                         double absx2, absy2;                            
894                         if(sp->view.depth){
895                                 /* Need clipping if: is part of box, or close to viewer */
896                                 if ( (b >= MIN_BOX && b < MAX_BOX) || X1 <= 0.1 || X2 < 0.1) 
897                                         if (clip(&X1, &Y1, &Z1, &X2, &Y2, &Z2))
898                                                 break;
899                                 if (X1 <= 0 || X2 <= 0) break;
900                                 absx1=SCALE_X(sp->view.depth*Y1/X1);
901                                 absy1=SCALE_Y(sp->view.depth*Z1/X1);
902                                 if(absx1 < -sp->width || absx1 > 2*sp->width ||
903                                    absy1 < -sp->height || absy1 > 2*sp->height)
904                                         break;
905                                 absx2=SCALE_X(sp->view.depth*Y2/X2);
906                                 absy2=SCALE_Y(sp->view.depth*Z2/X2);
907                                 if(absx2 < -sp->width || absx2 > 2*sp->width ||
908                                    absy2 < -sp->height || absy2 > 2*sp->height)
909                                         break;
910                         }else{
911                                 absx1=SCALE_X(X1);
912                                 absy1=SCALE_Y(Y1);
913                                 absx2=SCALE_X(X2);
914                                 absy2=SCALE_Y(Y2);
915                         }
916
917                         sp->csegs[ix].x1 = (short) absx1;
918                         sp->csegs[ix].y1 = (short) absy1;
919                         sp->csegs[ix].x2 = (short) absx2;
920                         sp->csegs[ix].y2 = (short) absy2;
921
922                         sp->cnsegs[col]++;
923                 } while (0);
924 #endif
925         }
926
927         if (sp->count) { /* erase */
928                 XSetForeground(display, gc, MI_BLACK_PIXEL(mi));
929                 XDrawSegments(display, window, gc, sp->old_segs, sp->nold_segs);
930         }
931
932         if (MI_NPIXELS(mi) > 2){ /* render colour */
933                 for (col = 0; col < MI_NPIXELS(mi); col++)
934                         if (sp->cnsegs[col] > 0) {
935                                 XSetForeground(display, gc, MI_PIXEL(mi, col));
936                                 XDrawSegments(display, window, gc,
937                                               sp->csegs + col * sp->beecount, sp->cnsegs[col]);
938                         }
939         } else {                /* render mono */
940                 XSetForeground(display, gc, MI_WHITE_PIXEL(mi));
941                 XDrawSegments(display, window, gc,
942                                           sp->csegs + col * sp->beecount, sp->cnsegs[col]);
943         }
944
945         /* Copy to erase-list */
946         for (col = 0, c = 0; col < MI_NPIXELS(mi); col++)
947                 for (b = 0; b < sp->cnsegs[col]; b++)
948                         sp->old_segs[c++] = (sp->csegs + col * sp->beecount)[b];
949         sp->nold_segs = c;
950
951         if (++sp->count > MI_CYCLES(mi)) /* pick a new flow */
952                 init_flow(mi);
953
954         if (sp->count % (MI_CYCLES(mi)/4) == 0) { /* pick a new view */
955                 new_view = 0; /* change to 1 .. */
956         }
957
958         if (X(0, 0) < xmin*2 || X(0, 0) > xmax*2) new_view = 1;
959         if (Y(0, 0) < ymin*2 || Y(0, 0) > ymax*2) new_view = 1;
960         if (Z(0, 0) < zmin*2 || Z(0, 0) > zmax*2) new_view = 1;
961
962         if (new_view) {
963                 for (b = 0; b < 2; b++) {
964                         X(1, b) = X(0, b) = balance_rand(sp->range.x*4);
965                         Y(1, b) = Y(0, b) = balance_rand(sp->range.y*4);
966                         Z(1, b) = Z(0, b) = balance_rand(sp->range.z*4);
967                 }
968                 sp->slow_view = 0.90;
969         }
970 }
971
972 void
973 release_flow(ModeInfo * mi)
974 {
975         if (flows != NULL) {
976                 int         screen;
977
978                 for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++) {
979                         flowstruct *sp = &flows[screen];
980
981                         if (sp->csegs != NULL)
982                                 (void) free((void *) sp->csegs);
983                         if (sp->cnsegs != NULL)
984                                 (void) free((void *) sp->cnsegs);
985                         if (sp->old_segs != NULL)
986                                 (void) free((void *) sp->old_segs);
987                         if (sp->p[0] != NULL)
988                                 (void) free((void *) sp->p[0]);
989                         if (sp->p[1] != NULL)
990                                 (void) free((void *) sp->p[1]);
991                 }
992                 (void) free((void *) flows);
993                 flows = NULL;
994         }
995 }
996
997 void
998 refresh_flow(ModeInfo * mi)
999 {
1000         MI_CLEARWINDOW(mi);
1001 }
1002
1003 XrmOptionDescRec flow_options[] =
1004 {
1005         {"-rotate",  ".rotate", XrmoptionSepArg, 0},
1006         {"-ride",  ".ride", XrmoptionSepArg, 0},
1007         {"-zoom",  ".zoom", XrmoptionSepArg, 0},
1008         {"-box",  ".box", XrmoptionSepArg, 0},
1009         {"-slow",  ".slow", XrmoptionSepArg, 0},
1010         {"-freeze",  ".freeze", XrmoptionSepArg, 0},
1011         {"-allow2d",  ".allow2d", XrmoptionSepArg, 0},
1012   { 0, 0, 0, 0 }
1013 };
1014
1015 /*
1016 char*        defaults[] =
1017 {
1018         "*rotate:         True",
1019         "*ride:           True",
1020         "*zoom:           True",
1021         "*allow2d:        True",
1022         "*box:            True",
1023         "*slow:           True",
1024         "*freeze:         True",
1025   0
1026 };
1027         */