From http://www.jwz.org/xscreensaver/xscreensaver-5.38.tar.gz
[xscreensaver] / hacks / strange.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* strange --- strange attractors */
3
4 #if 0
5 static const char sccsid[] = "@(#)strange.c     5.00 2000/11/01 xlockmore";
6 #endif
7
8 /*-
9 * Copyright (c) 1997 by Massimino Pascal <Pascal.Massimon@ens.fr>
10 *
11 * Permission to use, copy, modify, and distribute this software and its
12 * documentation for any purpose and without fee is hereby granted,
13 * provided that the above copyright notice appear in all copies and that
14 * both that copyright notice and this permission notice appear in
15 * supporting documentation.
16 *
17 * This file is provided AS IS with no warranties of any kind.  The author
18 * shall have no liability with respect to the infringement of copyrights,
19 * trade secrets or any patents by this file or any part thereof.  In no
20 * event will the author be liable for any lost revenue or profits or
21 * other special, indirect and consequential damages.
22 *
23 * Revision History:
24 * 10-Apr-2017: dmo2118@gmail.com: Enhancements for accumulator mode:
25 *              Performance tuning, varying colors, fixed wobbliness.
26 *              New options: point size, zoom, brightness, motion blur.
27 * 08-Apr-2017: dmo2118@gmail.com: Merged with current xlockmore strange.c.
28 *              Also resurrected the -curve parameter from XScreenSaver 2.31.
29 *              Multi-monitor fixes.
30 *              More allocation checks.
31 * 13-Apr-2010: Added useAccumulator, VARY_SPEED_TO_AVOID_BOREDOM.
32 * 22-Dec-2004: TDA: Replace Gauss_Rand with a real Gaussian.
33 * 01-Nov-2000: Allocation checks
34 * 30-Jul-1998: sineswiper@resonatorsoft.com: added curve factor (discovered
35 *              while experimenting with the Gauss_Rand function).
36 * 10-May-1997: jwz AT jwz.org: turned into a standalone program.
37 *              Made it render into an offscreen bitmap and then copy
38 *              that onto the screen, to reduce flicker.
39 *
40 * strange attractors are not so hard to find...
41 */
42
43 /* Be sure to try:
44 * ./strange -points 500000 -delay 0 -point-size 3
45 * ./strange -points 500000 -delay 0 -point-size 2 -curve 5 -zoom 1.5 -brightness 0.75
46 */
47
48 /* TODO: Can anything be done about the overflow with -point-size 32? */
49
50 #ifdef STANDALONE
51 # define MODE_strange
52 # define DEFAULTS       "*delay: 10000 \n" \
53                                         "*ncolors: 100 \n" \
54                                         "*fpsSolid: True \n" \
55                                         "*ignoreRotation: True \n" \
56                                         "*useSHM: True \n" \
57                                         "*useThreads: True \n" \
58                                     "*lowrez: True \n" \
59
60 # define SMOOTH_COLORS
61 # define release_strange 0
62 # define reshape_strange 0
63 # define strange_handle_event 0
64 # include "xlockmore.h"         /* from the xscreensaver distribution */
65 #else /* !STANDALONE */
66 # include "xlock.h"             /* from the xlockmore distribution */
67 # define ENTRYPOINT
68 #endif /* !STANDALONE */
69
70 #include <errno.h>
71 #include "pow2.h"
72 #include "thread_util.h"
73 #include "xshm.h"
74
75 #ifdef HAVE_INTTYPES_H
76 # include <inttypes.h>
77 #endif
78
79 #ifdef MODE_strange
80 #define DEF_CURVE       "10"
81 #define DEF_POINTS      "5500"
82 #define DEF_POINT_SIZE  "1"
83 #define DEF_ZOOM        "0.9" /* approx. 1 / 1.1 */
84 #define DEF_BRIGHTNESS  "1.0"
85 #define DEF_MOTION_BLUR "3.0" /* Formerly MERGE_FRAMES, but it's IIR now. */
86
87 static int curve;
88 static int points;
89 static int pointSize;
90 static float zoom;
91 static float brightness;
92 static float motionBlur;
93
94 static XrmOptionDescRec opts[] =
95 {
96                 {"-curve",        ".strange.curve",      XrmoptionSepArg, 0},
97                 {"-points",       ".strange.points",     XrmoptionSepArg, 0},
98                 {"-point-size",   ".strange.pointSize",  XrmoptionSepArg, 0},
99                 {"-zoom",         ".strange.zoom",       XrmoptionSepArg, 0},
100                 {"-brightness",   ".strange.brightness", XrmoptionSepArg, 0},
101                 {"-motion-blur",  ".strange.motionBlur", XrmoptionSepArg, 0},
102                 THREAD_OPTIONS
103 };
104 static argtype vars[] =
105 {
106                 {&curve,      "curve",      "Curve",      DEF_CURVE,       t_Int},
107                 {&points,     "points",     "Points",     DEF_POINTS,      t_Int},
108                 {&pointSize,  "pointSize",  "PointSize",  DEF_POINT_SIZE,  t_Int},
109                 {&zoom,       "zoom",       "Zoom",       DEF_ZOOM,        t_Float},
110                 {&brightness, "brightness", "Brightness", DEF_BRIGHTNESS,  t_Float},
111                 {&motionBlur, "motionBlur", "MotionBlur", DEF_MOTION_BLUR, t_Float},
112 };
113 static OptionStruct desc[] =
114 {
115                 {"-curve", "set the curve factor of the attractors"},
116                 {"-points", "change the number of points/iterations each frame"},
117                 {"-point-size", "change the size of individual points"},
118                 {"-zoom", "zoom in or out"},
119                 {"-brightness", "adjust the brightness for accumulator mode"},
120                 {"-motion-blur", "adds motion blur"},
121 };
122 ENTRYPOINT ModeSpecOpt strange_opts =
123 {sizeof opts / sizeof opts[0], opts,
124 sizeof vars / sizeof vars[0], vars, desc};
125
126 #ifdef USE_MODULES
127 ModStruct   strange_description =
128 {"strange", "init_strange", "draw_strange", (char *) NULL,
129 "init_strange", "init_strange", "free_strange", &strange_opts,
130 10000, 1, 1, 1, 64, 1.0, "",
131 "Shows strange attractors", 0, NULL};
132 #endif
133
134 #ifdef HAVE_JWXYZ
135 # define NO_DBUF
136 #endif
137
138 typedef float DBL;
139 typedef int PRM;
140
141 #define UNIT_BITS 12
142 #define UNIT (1<<UNIT_BITS)
143 #define UNIT2 (1<<14)
144 #define COLOR_BITS 16
145 /* #define UNIT2 (3140*UNIT/1000) */
146
147 #define SKIP_FIRST      100
148 #define DBL_To_PRM(x)  (PRM)( (DBL)(UNIT)*(x) )
149
150
151 #define DO_FOLD(a) (a)<0 ? -A->Fold[ (-(a))&(UNIT2-1) ] : A->Fold[ (a)&(UNIT2-1) ]
152
153 #if 0
154 #define DO_FOLD(a) (a)<-UNIT2 ? -A->Fold[(-(a))%UNIT2] : (a)<0 ? -A->Fold[ -(a) ] :\
155 (a)>UNIT2 ? A->Fold[ (a)%UNIT2 ] : A->Fold[ (a) ]
156 #define DO_FOLD(a) DBL_To_PRM( sin( (DBL)(a)/UNIT ) )
157 #define DO_FOLD(a) (a)<0 ? DBL_To_PRM( exp( 16.0*(a)/UNIT2 ) )-1.0 : \
158 DBL_To_PRM( 1.0-exp( -16.0*(a)/UNIT2 ) )
159 #endif
160
161 /* useAccumulator performs two functions:
162 * If it is defined, then support for the accumulator will be compiled.
163 * It is also the condition for which the accumulator renderer will engage.
164 */
165 #define useAccumulator (A->Max_Pt > 6000)
166 #define ACC_GAMMA 10.0
167 #define DEF_NUM_COLS 150
168 /* Extra options: */
169 #define VARY_SPEED_TO_AVOID_BOREDOM
170 /*#define AUTO_ZOOM*/ /* Works funny, but try it with -curve 5. */
171
172 /******************************************************************/
173
174 #define MAX_PRM 3*5
175
176 #if defined(__BIGGEST_ALIGNMENT__) \
177         && (defined(__GNUC__) \
178          && (__GNUC__ == 4 && __GNUC_MINOR__ >= 4 || __GNUC__ >= 5) \
179         || defined(__clang__))
180 # define ALIGNED __attribute__((aligned(__BIGGEST_ALIGNMENT__)))
181 # define ALIGN_HINT(ptr) __builtin_assume_aligned((ptr), __BIGGEST_ALIGNMENT__)
182 #else
183 # define ALIGNED
184 # define ALIGN_HINT(ptr) (ptr)
185 # ifndef __BIGGEST_ALIGNMENT__
186 #  define __BIGGEST_ALIGNMENT__ (sizeof(void *))
187 # endif
188 #endif
189
190
191 #ifdef HAVE_INTTYPES_H
192 typedef uint16_t ALIGNED PIXEL0;
193 typedef uint32_t PIXEL0X;
194 typedef uint32_t ALIGNED PIXEL1;
195 #else
196 typedef unsigned short ALIGNED PIXEL0;
197 typedef unsigned long PIXEL0X;
198 typedef unsigned long ALIGNED PIXEL1;
199 #endif
200
201 static const union {
202 #ifdef HAVE_INTTYPES_H
203         uint16_t signature;
204         uint8_t bytes[2];
205 #else
206         unsigned short signature;
207         unsigned char bytes[2];
208 #endif
209 } byte_order_union = {MSBFirst};
210
211 #define LOCAL_BYTE_ORDER byte_order_union.bytes[1]
212
213 typedef struct _ATTRACTOR {
214         DBL         Prm1[MAX_PRM], Prm2[MAX_PRM];
215         PRM         Prm[MAX_PRM], *Fold;
216         void        (*Iterate) (const struct _ATTRACTOR *, PRM, PRM, PRM *, PRM *);
217         void       *Buffer1, *Buffer2; /* Either XPoint or XRectangle. */
218         int         Cur_Pt, Max_Pt;
219         int         Col, Count, Speed;
220         int         Width, Height;
221         Pixmap      dbuf;       /* jwz */
222         GC          dbuf_gc;
223         #ifdef useAccumulator
224                 int visualClass;
225                 size_t alignedWidth;
226                 unsigned long rMask, gMask, bMask;
227                 unsigned rShift, gShift, bShift;
228                 PIXEL0 blurFac; /* == 0 when no motion blur is taking place. */
229                 double colorFac;
230                 XColor *palette;
231                 unsigned numCols;
232                 unsigned long *cols;
233                 XImage *accImage;
234                 XShmSegmentInfo shmInfo;
235                 struct _THREAD **threads;
236                 struct threadpool pool;
237         #endif
238 } ATTRACTOR;
239
240 static ATTRACTOR *Root = (ATTRACTOR *) NULL;
241
242 #ifdef useAccumulator
243 typedef struct _THREAD {
244         const ATTRACTOR *Attractor;
245         unsigned long Rnd;
246         size_t y0, y1, y2;
247
248         PIXEL0 **accMap;
249         PIXEL0 *bloomRows;
250         PIXEL1 *colorRow;
251         PIXEL0 *motionBlur;
252
253         PRM xmin, xmax, ymin, ymax;
254         unsigned pixelCount;
255 } THREAD;
256 #endif
257
258 static DBL  Amp_Prm[MAX_PRM] =
259 {
260         1.0, 3.5, 3.5, 2.5, 4.7,
261         1.0, 3.5, 3.6, 2.5, 4.7,
262         1.0, 1.5, 2.2, 2.1, 3.5
263 };
264 static DBL  Mid_Prm[MAX_PRM] =
265 {
266         0.0, 1.5, 0.0, .5, 1.5,
267         0.0, 1.5, 0.0, .5, 1.5,
268         0.0, 1.5, -1.0, -.5, 2.5,
269 };
270
271 #if 0
272
273 static inline uint64_t frq(void)
274 {
275         return 1000000;
276 }
277
278 static inline uint64_t tick(void)
279 {
280         struct timeval tv;
281         gettimeofday(&tv, NULL);
282         return tv.tv_sec * frq() + tv.tv_usec;
283 }
284
285 #endif
286
287 static      DBL
288 Old_Gauss_Rand(DBL c, DBL A, DBL S)
289 {
290         DBL         y,z;
291
292         y = (DBL) LRAND() / MAXRAND;
293         z = curve / 10;
294         y = A * (z - exp(-y * y * S)) / (z - exp(-S));
295         if (NRAND(2))
296                 return (c + y);
297         else
298                 return (c - y);
299 }
300
301 #if 0
302 /* dmo2118: seems to be responsible for lots of boring-looking rings */
303
304 /* I don't know that it makes a difference, but this one actually *is*
305    a Gaussian.  [TDA] */
306
307 /* Generate Gaussian random number: mean c, "amplitude" A (actually
308    A is 3*standard deviation).  'S' is unused.  */
309
310 /* Note this generates a pair of gaussian variables, so it saves one
311    to give out next time it's called */
312
313 static double
314 Gauss_Rand(DBL c, DBL A, DBL S)
315 {
316         static double d;
317         static Bool ready = 0;
318         if(ready) {
319                 ready = 0;
320                 return c + A/3 * d;
321         } else {
322                 double x, y, w;
323                 do {
324                         x = 2.0 * (double)LRAND() / MAXRAND - 1.0;
325                         y = 2.0 * (double)LRAND() / MAXRAND - 1.0;
326                         w = x*x + y*y;
327                 } while(w >= 1.0);
328
329                 w = sqrt((-2 * log(w))/w);
330                 ready = 1;
331                 d =          x * w;
332                 return c + A/3 * y * w;
333         }
334 }
335 #endif
336
337 static void
338 Random_Prm(DBL * Prm)
339 {
340         int         i;
341
342         for (i = 0; i < MAX_PRM; ++i) {
343 #if 0
344                 if (curve == 10)
345                         Prm[i] = Gauss_Rand (Mid_Prm[i], Amp_Prm[i], 4.0);
346                 else
347 #endif
348                         Prm[i] = Old_Gauss_Rand (Mid_Prm[i], Amp_Prm[i], 4.0);
349         }
350 }
351
352 /***************************************************************/
353
354   /* 2 examples of non-linear map */
355
356 static void
357 Iterate_X2(const ATTRACTOR * A, PRM x, PRM y, PRM * xo, PRM * yo)
358 {
359         PRM         xx, yy, xy, x2y, y2x, Tmp;
360
361         xx = (x * x) >> UNIT_BITS;
362         x2y = (xx * y) >> UNIT_BITS;
363         yy = (y * y) >> UNIT_BITS;
364         y2x = (yy * x) >> UNIT_BITS;
365         xy = (x * y) >> UNIT_BITS;
366
367         Tmp = A->Prm[1] * xx + A->Prm[2] * xy + A->Prm[3] * yy + A->Prm[4] * x2y;
368         Tmp = A->Prm[0] - y + (Tmp >> UNIT_BITS);
369         *xo = DO_FOLD(Tmp);
370         Tmp = A->Prm[6] * xx + A->Prm[7] * xy + A->Prm[8] * yy + A->Prm[9] * y2x;
371         Tmp = A->Prm[5] + x + (Tmp >> UNIT_BITS);
372         *yo = DO_FOLD(Tmp);
373 }
374
375 static void
376 Iterate_X3(const ATTRACTOR * A, PRM x, PRM y, PRM * xo, PRM * yo)
377 {
378         PRM         xx, yy, xy, x2y, y2x, Tmp_x, Tmp_y, Tmp_z;
379
380         xx = (x * x) >> UNIT_BITS;
381         x2y = (xx * y) >> UNIT_BITS;
382         yy = (y * y) >> UNIT_BITS;
383         y2x = (yy * x) >> UNIT_BITS;
384         xy = (x * y) >> UNIT_BITS;
385
386         Tmp_x = A->Prm[1] * xx + A->Prm[2] * xy + A->Prm[3] * yy + A->Prm[4] * x2y;
387         Tmp_x = A->Prm[0] - y + (Tmp_x >> UNIT_BITS);
388         Tmp_x = DO_FOLD(Tmp_x);
389
390         Tmp_y = A->Prm[6] * xx + A->Prm[7] * xy + A->Prm[8] * yy + A->Prm[9] * y2x;
391         Tmp_y = A->Prm[5] + x + (Tmp_y >> UNIT_BITS);
392
393         Tmp_y = DO_FOLD(Tmp_y);
394
395         Tmp_z = A->Prm[11] * xx + A->Prm[12] * xy + A->Prm[13] * yy + A->Prm[14] * y2x;
396         Tmp_z = A->Prm[10] + x + (Tmp_z >> UNIT_BITS);
397         Tmp_z = UNIT + ((Tmp_z * Tmp_z) >> UNIT_BITS);
398
399         /* Can happen with -curve 9. */
400         if (!Tmp_z)
401                 Tmp_z = 1;
402
403 #ifdef HAVE_INTTYPES_H
404         {
405                 uint64_t Tmp_z1 = (1 << 30) / Tmp_z;
406                 *xo = (Tmp_x * Tmp_z1) >> (30 - UNIT_BITS);
407                 *yo = (Tmp_y * Tmp_z1) >> (30 - UNIT_BITS);
408         }
409 #else
410         *xo = (Tmp_x * UNIT) / Tmp_z;
411         *yo = (Tmp_y * UNIT) / Tmp_z;
412 #endif
413 }
414
415 static void (*Funcs[2]) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *) = {
416         Iterate_X2, Iterate_X3
417 };
418
419 /***************************************************************/
420
421 ENTRYPOINT void
422 free_strange(ModeInfo *mi)
423 {
424         Display *display = MI_DISPLAY(mi);
425         ATTRACTOR  *A = &Root[MI_SCREEN(mi)];
426
427         if (A->Buffer1 != NULL) {
428                 free(A->Buffer1);
429                 A->Buffer1 = (XPoint *) NULL;
430         }
431         if (A->Buffer2 != NULL) {
432                 free(A->Buffer2);
433                 A->Buffer2 = (XPoint *) NULL;
434         }
435         if (A->dbuf) {
436                 XFreePixmap(display, A->dbuf);
437                 A->dbuf = None;
438         }
439         if (A->dbuf_gc) {
440                 XFreeGC(display, A->dbuf_gc);
441                 A->dbuf_gc = None;
442         }
443         if (A->Fold != NULL) {
444                 free(A->Fold);
445                 A->Fold = (PRM *) NULL;
446         }
447
448 #ifdef useAccumulator
449         if (useAccumulator) {
450                 if (A->pool.count) {
451                         threadpool_destroy (&A->pool);
452                         A->pool.count = 0;
453                 }
454
455                 free (A->threads);
456                 A->threads = NULL;
457
458                 if (A->accImage) {
459                         destroy_xshm_image (display, A->accImage, &A->shmInfo);
460                         A->accImage = NULL;
461                 }
462
463                 free (A->palette);
464                 A->palette = NULL;
465
466                 if (A->cols) {
467                         if (A->visualClass != TrueColor && A->numCols > 2)
468                                 XFreeColors (display, MI_COLORMAP(mi), A->cols, A->numCols, 0);
469                         free (A->cols);
470                         A->cols = NULL;
471                 }
472         }
473 #endif
474 }
475
476 /* NRAND() is also in use; making three PRNGs in total here. */
477
478 /* ISO/IEC 9899 suggests this one. Doesn't require 64-bit math. */
479 #define GOODRND(seed) ((seed) = (((seed) * 1103515245 + 12345) & 0x7fffffff))
480 #define GOODRND_BITS 31
481
482 /* Extremely cheap entropy: this is often a single LEA instruction. */
483 #define CHEAPRND(seed) ((seed) = (seed) * 5)
484
485 static void
486 init_draw (const ATTRACTOR *A, PRM *x, PRM *y,
487            PRM *xmin, PRM *ymin, PRM *xmax, PRM *ymax, unsigned long *rnd)
488 {
489         int         n;
490         PRM         xo, yo;
491
492         *xmin = UNIT;
493         *ymin = UNIT;
494         *xmax = -UNIT;
495         *ymax = -UNIT;
496
497         *x = *y = DBL_To_PRM(.0);
498         for (n = SKIP_FIRST; n; --n) {
499                 (*A->Iterate) (A, *x, *y, &xo, &yo);
500
501 #ifdef AUTO_ZOOM
502                 if (xo > *xmax)
503                         *xmax = xo;
504                 if (xo < *xmin)
505                         *xmin = xo;
506                 if (yo > *ymax)
507                         *ymax = yo;
508                 if (yo < *ymin)
509                         *ymin = yo;
510 #endif
511
512                 /* Can't use NRAND(), because that modifies global state in a
513                  * thread-unsafe way.
514                  */
515                 *x = xo + (GOODRND(*rnd) >> (GOODRND_BITS - 3)) - 4;
516                 *y = yo + (GOODRND(*rnd) >> (GOODRND_BITS - 3)) - 4;
517         }
518 }
519
520 static void
521 recalc_scale (const ATTRACTOR *A, PRM xmin, PRM ymin, PRM xmax, PRM ymax,
522               DBL *Lx, DBL *Ly, PRM *mx, PRM *my)
523 {
524 #ifndef AUTO_ZOOM
525         xmin = -UNIT;
526         ymin = -UNIT;
527         xmax = UNIT;
528         ymax = UNIT;
529 #endif
530
531         *Lx = zoom * (DBL) A->Width / (xmax - xmin);
532         *Ly = -zoom * (DBL) A->Height / (ymax - ymin);
533         *mx = A->Width/2 - (xmax + xmin) * *Lx / 2;
534         *my = A->Height/2 - (ymax + ymin) * *Ly / 2;
535 }
536
537 #ifdef useAccumulator
538
539 static void
540 thread_destroy (void *Self_Raw)
541 {
542         THREAD     *T = (THREAD *)Self_Raw;
543
544         aligned_free (T->accMap[0]);
545         (void) free((void *) T->accMap);
546         aligned_free (T->bloomRows);
547         aligned_free (T->colorRow);
548         aligned_free (T->motionBlur);
549 }
550
551 static int
552 thread_create (void *Self_Raw, struct threadpool *pool, unsigned id)
553 {
554         THREAD     *T = (THREAD *)Self_Raw;
555         int         i;
556         const ATTRACTOR *A = GET_PARENT_OBJ(ATTRACTOR, pool, pool);
557
558         memset (T, 0, sizeof(*T));
559
560         T->Attractor = A;
561         A->threads[id] = T;
562
563         T->Rnd = random();
564
565         /* The gap between y0 and y1 is to preheat the box blur. */
566         T->y1 = A->Height * id / pool->count;
567         T->y2 = A->Height * (id + 1) / pool->count;
568         T->y0 = T->y1 < pointSize ? 0 : T->y1 - pointSize;
569
570         T->accMap = (PIXEL0**)calloc(A->Height,sizeof(PIXEL0*));
571         if (!T->accMap) {
572                 thread_destroy (T);
573                 return ENOMEM;
574         }
575         T->accMap[0] = NULL;
576         if (aligned_malloc ((void **)&T->accMap[0], __BIGGEST_ALIGNMENT__,
577                 A->alignedWidth * A->Height * sizeof(PIXEL0))) {
578                 thread_destroy (T);
579                 return ENOMEM;
580         }
581         for (i=0;i<A->Height;i++)
582                 T->accMap[i] = T->accMap[0] + A->alignedWidth * i;
583
584         if (aligned_malloc ((void **)&T->bloomRows, __BIGGEST_ALIGNMENT__,
585                 A->alignedWidth * (pointSize + 2) * sizeof(*T->bloomRows))) {
586                 thread_destroy (T);
587                 return ENOMEM;
588         }
589         if (aligned_malloc ((void **)&T->colorRow, __BIGGEST_ALIGNMENT__,
590                 A->alignedWidth * sizeof(*T->colorRow))) {
591                 thread_destroy (T);
592                 return ENOMEM;
593         }
594         if (A->blurFac) {
595                 if (aligned_malloc ((void **)&T->motionBlur, __BIGGEST_ALIGNMENT__,
596                         A->alignedWidth * (T->y2 - T->y1) * sizeof(*T->motionBlur))) {
597                         thread_destroy (T);
598                         return ENOMEM;
599                 }
600
601                 memset (T->motionBlur, 0, A->alignedWidth * (T->y2 - T->y1) * sizeof(*T->motionBlur));
602         }
603
604         return 0;
605 }
606
607 static void
608 points_thread (void *Self_Raw)
609 {
610         /* Restricts viewable area to 2^(32-L_Bits). */
611         const unsigned L_Bits = 19; /* Max. image size: 8192x8192. */
612
613         THREAD     *T = (THREAD *)Self_Raw;
614         const ATTRACTOR *A = T->Attractor;
615         int         n;
616         PRM         x, y, xo, yo;
617         DBL         Lx, Ly;
618         PRM         iLx, iLy, cx, cy;
619         void        (*Iterate) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *);
620         unsigned    Rnd;
621         PRM         xmax, xmin, ymax, ymin;
622
623         Iterate = A->Iterate;
624
625         if (useAccumulator) {
626                 memset (T->accMap[0], 0, sizeof(PIXEL0) * A->alignedWidth * A->Height);
627         }
628
629         /* Using CHEAPRND() by itself occasionally gets stuck at 0 mod 8, so seed it
630          * from GOODRND().
631          */
632         init_draw (A, &x, &y, &xmin, &ymin, &xmax, &ymax, &T->Rnd);
633         recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);
634
635         Rnd = GOODRND(T->Rnd);
636
637         iLx = Lx * (1 << L_Bits);
638         iLy = Ly * (1 << L_Bits);
639         if (!iLx) /* Can happen with small windows. */
640                 iLx = 1;
641         if (!iLy)
642                 iLy = 1;
643
644         for (n = T->Attractor->Max_Pt / A->pool.count; n; --n) {
645                 unsigned mx,my;
646                 (*Iterate) (T->Attractor, x, y, &xo, &yo);
647                 mx = ((iLx * x) >> L_Bits) + cx;
648                 my = ((iLy * y) >> L_Bits) + cy;
649                 /* Fun trick: making m[x|y] unsigned means we can skip mx<0 && my<0. */
650                 if (mx<A->Width && my<A->Height)
651                         T->accMap[my][mx]++;
652
653                 #ifdef AUTO_ZOOM
654                 if (xo > xmax)
655                         xmax = xo;
656                 if (xo < xmin)
657                         xmin = xo;
658                 if (yo > ymax)
659                         ymax = yo;
660                 if (yo < ymin)
661                         ymin = yo;
662
663                 if (!(n & 0xfff)) {
664                         recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);
665                 }
666                 #endif
667
668                 /* Skimp on the randomness. */
669                 x = xo + (CHEAPRND(Rnd) >> (sizeof(Rnd) * 8 - 3)) - 4;
670                 y = yo + (CHEAPRND(Rnd) >> (sizeof(Rnd) * 8 - 3)) - 4;
671         }
672 }
673
674 static void
675 rasterize_thread (void *Self_Raw)
676 {
677         THREAD     *T = (THREAD *)Self_Raw;
678         const ATTRACTOR *A = T->Attractor;
679         unsigned    i, j, k;
680         PRM         xmax = 0, xmin = A->Width, ymax = 0, ymin = A->Height;
681         unsigned long colorScale =
682                 (double)A->Width * A->Height
683                 * (1 << COLOR_BITS) * brightness
684                 * A->colorFac
685                 * (zoom * zoom) / (0.9 * 0.9)
686                 / 640.0 / 480.0
687                 / (pointSize * pointSize)
688                 * 800000.0
689                 / (float)A->Max_Pt
690                 * (float)A->numCols/256;
691         #ifdef VARY_SPEED_TO_AVOID_BOREDOM
692         unsigned    pixelCount = 0;
693         #endif
694         PIXEL0     *motionBlurRow = T->motionBlur;
695         void       *outRow = (char *)A->accImage->data
696                              + A->accImage->bytes_per_line * T->y1;
697
698         /* Clang needs these for loop-vectorizing; A->Width doesn't work. */
699         unsigned    w = A->Width, aw = A->alignedWidth;
700
701         if (A->numCols == 2) /* Brighter for monochrome. */
702                 colorScale *= 4;
703
704         /* bloomRows: row ring buffer, bloom accumulator, in that order. */
705         memset (T->bloomRows, 0, (pointSize + 1) * aw * sizeof(*T->bloomRows));
706
707         /* This code is highly amenable to auto-vectorization; on GCC use -O3 to get
708          * that. On x86-32, also add -msse2.
709          */
710         for (j=T->y0;j<T->y2;j++) {
711                 Bool has_col = False;
712                 int accum = 0;
713
714                 PIXEL0 *bloomRow =
715                         ALIGN_HINT(T->bloomRows + A->alignedWidth * (j % pointSize));
716                 PIXEL0 *accumRow =
717                         ALIGN_HINT(T->bloomRows + A->alignedWidth * pointSize);
718                 PIXEL1 *colRow = T->colorRow;
719
720                 /* Moderately fast bloom.  */
721
722                 for (i=0;i<aw;i++) {
723                         accumRow[i] -= bloomRow[i];
724                         bloomRow[i] = 0;
725                 }
726
727                 for (k=0;k<A->pool.count;k++) {
728                         const PIXEL0 *inRow = ALIGN_HINT(A->threads[k]->accMap[j]);
729                         for (i=0;i<aw;i++) {
730                                 /* Lots of last-level cache misses. Such is life. */
731                                 bloomRow[i] += inRow[i];
732                         }
733                 }
734
735                 /* Hardware prefetching works better going forwards than going backwards.
736                  * Since this blurs/blooms/convolves in-place, it expands points to the
737                  * right instead of to the left.
738                  */
739                 for (i=0;i<pointSize-1;i++)
740                         accum += bloomRow[i];
741
742                 for (i=0;i<aw;i++) {
743                         PIXEL0 oldBloom = bloomRow[i];
744
745                         /* alignedWidth has extra padding for this one line. */
746                         accum += bloomRow[i+pointSize-1];
747
748                         bloomRow[i] = accum;
749                         accumRow[i] += accum;
750                         accum -= oldBloom;
751                 }
752
753                 if (j>=T->y1) {
754                         PIXEL0 *accumRow1 = A->blurFac ? motionBlurRow : accumRow;
755                         PIXEL0 blurFac = A->blurFac;
756
757                         if (blurFac) {
758                                 /* TODO: Do I vectorize OK? */
759                                 if (blurFac == 0x8000) {
760                                         /* Optimization for the default. */
761                                         for (i=0;i<aw;i++)
762                                                 motionBlurRow[i] = (motionBlurRow[i] >> 1) + accumRow[i];
763                                 } else {
764                                         for (i=0;i<aw;i++)
765                                                 motionBlurRow[i] = (PIXEL0)(((PIXEL0X)motionBlurRow[i] * blurFac) >> 16) + accumRow[i];
766                                 }
767
768                                 motionBlurRow += aw;
769                         }
770
771                         for (i=0;i<aw;i++) {
772                                 unsigned col = (accumRow1[i] * colorScale) >> COLOR_BITS;
773                                 if (col>A->numCols-1) {
774                                         col = A->numCols-1;
775                                 }
776                                 #ifdef VARY_SPEED_TO_AVOID_BOREDOM
777                                 if (col>0) {
778                                         if (col<A->numCols-1)  /* we don't count maxxed out pixels */
779                                                 pixelCount++;
780                                         if (i > xmax)
781                                                 xmax = i;
782                                         if (i < xmin)
783                                                 xmin = i;
784                                         has_col = True;
785                                 }
786                                 #endif
787                                 colRow[i] = A->cols[col];
788                         }
789
790                         #ifdef VARY_SPEED_TO_AVOID_BOREDOM
791                         if (has_col) {
792                                 if (j > ymax)
793                                         ymax = j;
794                                 if (j < ymin)
795                                         ymin = j;
796                         }
797                         #endif
798
799 #if 0
800                         for (i=0;i<aw;i++) {
801                                 if (MI_NPIXELS(mi) < 2)
802                                         XSetForeground(display, gc, MI_WHITE_PIXEL(mi));
803                                 else
804                                         /*XSetForeground(display, gc, MI_PIXEL(mi, A->Col % MI_NPIXELS(mi)));*/
805                                         XSetForeground(display, gc, cols[col].pixel);
806
807                                 if (A->dbuf != None) {
808                                         XSetForeground(display, A->dbuf_gc, cols[col].pixel);
809                                         XDrawPoint(display, A->dbuf, A->dbuf_gc, i, j);
810                                 } else {
811                                         XSetForeground(display, gc, cols[col].pixel);
812                                         XDrawPoint(display, window, gc, i, j);
813                                 }
814                         }
815 #endif
816
817                         if (A->accImage->bits_per_pixel==32 &&
818                                 A->accImage->byte_order==LOCAL_BYTE_ORDER) {
819                                 for (i=0;i<aw;i++)
820                                         ((uint32_t *)outRow)[i] = colRow[i];
821                         } else if (A->accImage->bits_per_pixel==16 &&
822                                 A->accImage->byte_order==LOCAL_BYTE_ORDER) {
823                                 for (i=0;i<aw;i++)
824                                         ((uint16_t *)outRow)[i] = colRow[i];
825                         } else if (A->accImage->bits_per_pixel==8) {
826                                 for (i=0;i<aw;i++)
827                                         ((uint8_t *)outRow)[i] = colRow[i];
828                         } else {
829                                 for (i=0;i<w;i++)
830                                         XPutPixel (A->accImage, i, j, colRow[i]);
831                         }
832
833                         outRow = (char *)outRow + A->accImage->bytes_per_line;
834                 }
835         }
836
837         /*
838         uint64_t dt = 0;
839         uint64_t t0 = tick();
840         dt += tick() - t0;
841
842         printf("B %g\t(%d,%d)\t%dx%d\t%d\n", 1000.0 * dt / frq(),
843                 xmin, ymin, xmax - xmin, ymax - ymin, pixelCount);
844         */
845
846         T->xmax = xmax;
847         T->xmin = xmin;
848         T->ymax = ymax;
849         T->ymin = ymin;
850         T->pixelCount = pixelCount;
851 }
852
853 static void
854 ramp_color (const XColor *color_in, XColor *color_out, unsigned i, unsigned n)
855 {
856         float li;
857         #define MINBLUE 1
858         #define FULLBLUE 128
859         #define LOW_COLOR(c) ((c)*li/FULLBLUE)
860         #define HIGH_COLOR(c) ((65535-(c))*(li-FULLBLUE)/(256-FULLBLUE)+(c))
861         li = MINBLUE
862                 + (255.0-MINBLUE) * log(1.0 + ACC_GAMMA*(float)i/n)
863                 / log(1.0 + ACC_GAMMA);
864         if (li<FULLBLUE) {
865                 color_out->red = LOW_COLOR(color_in->red);
866                 color_out->green = LOW_COLOR(color_in->green);
867                 color_out->blue = LOW_COLOR(color_in->blue);
868         } else {
869                 color_out->red = HIGH_COLOR(color_in->red);
870                 color_out->green = HIGH_COLOR(color_in->green);
871                 color_out->blue = HIGH_COLOR(color_in->blue);
872         }
873 }
874
875 #endif
876
877 static void
878 draw_points (Display *display, Drawable d, GC gc, const void *Buf,
879              unsigned Count)
880 {
881         if (pointSize == 1)
882                 XDrawPoints(display, d, gc, (XPoint *)Buf, Count, CoordModeOrigin);
883         else
884                 XFillRectangles(display, d, gc, (XRectangle *)Buf, Count);
885 }
886
887 ENTRYPOINT void
888 draw_strange(ModeInfo * mi)
889 {
890         int         i, j, n, Cur_Pt;
891         PRM         x, y, xo, yo;
892         DBL         u;
893         void       *Buf;
894         Display    *display = MI_DISPLAY(mi);
895         Window      window = MI_WINDOW(mi);
896         GC          gc = MI_GC(mi);
897         DBL         Lx, Ly;
898         void        (*Iterate) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *);
899         PRM         xmin, xmax, ymin, ymax;
900         ATTRACTOR  *A;
901         unsigned long Rnd = random();
902         int         cx, cy;
903
904         if (Root == NULL)
905                 return;
906         A = &Root[MI_SCREEN(mi)];
907         if (A->Fold == NULL)
908                 return;
909
910         Cur_Pt = A->Cur_Pt;
911         Iterate = A->Iterate;
912
913         u = (DBL) (A->Count) / 40000.0;
914         for (j = MAX_PRM - 1; j >= 0; --j)
915                 A->Prm[j] = DBL_To_PRM((1.0 - u) * A->Prm1[j] + u * A->Prm2[j]);
916
917         /* We collect the accumulation of the orbits in the 2d int array field. */
918
919         init_draw (A, &x, &y, &xmin, &ymin, &xmax, &ymax, &Rnd);
920         recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);
921
922         A->Cur_Pt = 0;
923
924         xmax = 0;
925         xmin = A->Width;
926         ymax = 0;
927         ymin = A->Height;
928
929         MI_IS_DRAWN(mi) = True;
930
931         #ifdef useAccumulator
932         if (useAccumulator) {
933                 int pixelCount = 0;
934
935                 threadpool_run (&A->pool, points_thread);
936
937                 if (A->visualClass == TrueColor) {
938                         XColor *src_color = &A->palette[A->Col % MI_NPIXELS(mi)];
939
940                         for (i=0;i<A->numCols;i++) {
941                                 XColor color;
942                                 ramp_color (src_color, &color, i, A->numCols);
943                                 A->cols[i] =
944                                         ((((unsigned long)color.red   << 16) >> A->rShift) & A->rMask) |
945                                         ((((unsigned long)color.green << 16) >> A->gShift) & A->gMask) |
946                                         ((((unsigned long)color.blue  << 16) >> A->bShift) & A->bMask);
947                         }
948                 }
949                 threadpool_wait (&A->pool);
950
951                 threadpool_run(&A->pool, rasterize_thread);
952                 threadpool_wait(&A->pool);
953
954                 for (i=0; i!=A->pool.count; ++i) {
955                         THREAD *T = A->threads[i];
956                         if (T->xmax > xmax)
957                                 xmax = T->xmax;
958                         if (T->xmin < xmin)
959                                 xmin = T->xmin;
960                         if (T->ymax > ymax)
961                                 ymax = T->ymax;
962                         if (T->ymin < ymin)
963                                 ymin = T->ymin;
964                         pixelCount += T->pixelCount;
965                 }
966
967                 put_xshm_image (display, A->dbuf != None ? A->dbuf : window,
968                                 A->dbuf != None ? A->dbuf_gc : gc, A->accImage,
969                                 0, 0, 0, 0, A->accImage->width, A->accImage->height,
970                                 &A->shmInfo);
971
972                 if (A->dbuf != None) {
973                         XCopyArea(display, A->dbuf, window, gc, 0, 0, A->Width, A->Height, 0, 0);
974                 }
975                 #ifdef VARY_SPEED_TO_AVOID_BOREDOM
976                         /* Increase the rate of change of the parameters if the attractor has become visually boring. */
977                         if ((xmax - xmin < Lx * DBL_To_PRM(.2)) && (ymax - ymin < Ly * DBL_To_PRM(.2))) {
978                                 A->Speed *= 1.25;
979                         } else if (pixelCount>0 && pixelCount<A->Width*A->Height/1000) {
980                                 A->Speed *= 1.25;  /* A->Count = 1000; */
981                         } else {
982                                 A->Speed = 4; /* reset to normal/default */
983                         }
984                         if (A->Speed > 32)
985                                 A->Speed = 32;
986                         A->Count += A->Speed;
987                         if (A->Count >= 1000) {
988                                 for (i = MAX_PRM - 1; i >= 0; --i)
989                                         A->Prm1[i] = A->Prm2[i];
990                                 Random_Prm(A->Prm2);
991                                 A->Count = 0;
992                         }
993                 #endif
994         } else {
995         #endif
996         for (n = 0; n != A->Max_Pt; ++n) {
997                 int x1, y1;
998                 (*Iterate) (A, x, y, &xo, &yo);
999                 x1 = (int) (Lx * x) + cx;
1000                 y1 = (int) (Ly * y) + cy;
1001                 if (pointSize == 1) {
1002                         XPoint *Buf = &((XPoint *)A->Buffer2)[n];
1003                         Buf->x = x1;
1004                         Buf->y = y1;
1005                 } else {
1006                         XRectangle *Buf = &((XRectangle *)A->Buffer2)[n];
1007                         /* Position matches bloom in accumulator mode. */
1008                         Buf->x = x1 - pointSize + 1;
1009                         Buf->y = y1;
1010                         Buf->width = pointSize;
1011                         Buf->height = pointSize;
1012                 }
1013
1014                 if (x1 > xmax)
1015                         xmax = x1;
1016                 if (x1 < xmin)
1017                         xmin = x1;
1018                 if (y1 > ymax)
1019                         ymax = y1;
1020                 if (y1 < ymin)
1021                         ymin = y1;
1022
1023                 A->Cur_Pt++;
1024                 /* (void) fprintf( stderr, "X,Y: %d %d    ", Buf->x, Buf->y ); */
1025                 x = xo + NRAND(8) - 4;
1026                 y = yo + NRAND(8) - 4;
1027         }
1028
1029         XSetForeground(display, gc, MI_BLACK_PIXEL(mi));
1030
1031         if (A->dbuf != None) {          /* jwz */
1032                 XSetForeground(display, A->dbuf_gc, 0);
1033 /* XDrawPoints(display, A->dbuf, A->dbuf_gc, A->Buffer1,
1034   Cur_Pt,CoordModeOrigin); */
1035                 XFillRectangle(display, A->dbuf, A->dbuf_gc, 0, 0, A->Width, A->Height);
1036         } else {
1037                 draw_points(display, window, gc, A->Buffer1, Cur_Pt);
1038         }
1039
1040         if (MI_NPIXELS(mi) <= 2)
1041                 XSetForeground(display, gc, MI_WHITE_PIXEL(mi));
1042         else
1043                 XSetForeground(display, gc, MI_PIXEL(mi, A->Col % MI_NPIXELS(mi)));
1044
1045         if (A->dbuf != None) {
1046                 XSetForeground(display, A->dbuf_gc, 1);
1047                 draw_points(display, A->dbuf, A->dbuf_gc, A->Buffer2, A->Cur_Pt);
1048                 XCopyPlane(display, A->dbuf, window, gc, 0, 0, A->Width, A->Height, 0, 0, 1);
1049         } else
1050                 draw_points(display, window, gc, A->Buffer2, A->Cur_Pt);
1051
1052         #ifdef useAccumulator
1053         }
1054         #endif
1055
1056         Buf = A->Buffer1;
1057         A->Buffer1 = A->Buffer2;
1058         A->Buffer2 = Buf;
1059
1060         if ((xmax - xmin < Lx * DBL_To_PRM(.2)) && (ymax - ymin < Ly * DBL_To_PRM(.2)))
1061                 A->Count += 4 * A->Speed;
1062         else
1063                 A->Count += A->Speed;
1064         if (A->Count >= 1000) {
1065                 for (i = MAX_PRM - 1; i >= 0; --i)
1066                         A->Prm1[i] = A->Prm2[i];
1067                 Random_Prm(A->Prm2);
1068                 A->Count = 0;
1069         }
1070         A->Col++;
1071 #ifdef STANDALONE
1072     mi->recursion_depth = A->Count;
1073 #endif
1074 }
1075
1076
1077 /***************************************************************/
1078
1079 ENTRYPOINT void
1080 init_strange(ModeInfo * mi)
1081 {
1082         Display    *display = MI_DISPLAY(mi);
1083 #ifndef NO_DBUF
1084         GC          gc = MI_GC(mi);
1085 #endif
1086         ATTRACTOR  *Attractor;
1087         size_t      pointStructSize =
1088                 pointSize == 1 ? sizeof (XPoint) : sizeof (XRectangle);
1089
1090         if (curve <= 0) curve = 10;
1091
1092         MI_INIT (mi, Root);
1093         Attractor = &Root[MI_SCREEN(mi)];
1094
1095         if (Attractor->Fold == NULL) {
1096                 int         i;
1097
1098                 if ((Attractor->Fold = (PRM *) calloc(UNIT2 + 1,
1099                                 sizeof (PRM))) == NULL) {
1100                         free_strange(mi);
1101                         return;
1102                 }
1103                 for (i = 0; i <= UNIT2; ++i) {
1104                         DBL         x;
1105
1106                         /* x = ( DBL )(i)/UNIT2; */
1107                         /* x = sin( M_PI/2.0*x ); */
1108                         /* x = sqrt( x ); */
1109                         /* x = x*x; */
1110                         /* x = x*(1.0-x)*4.0; */
1111                         x = (DBL) (i) / UNIT;
1112                         x = sin(x);
1113                         Attractor->Fold[i] = DBL_To_PRM(x);
1114                 }
1115         }
1116
1117         Attractor->Max_Pt = points;
1118
1119         if (Attractor->Buffer1 == NULL)
1120                 if ((Attractor->Buffer1 = calloc(Attractor->Max_Pt,
1121                                 pointStructSize)) == NULL) {
1122                         free_strange(mi);
1123                         return;
1124                 }
1125         if (Attractor->Buffer2 == NULL)
1126                 if ((Attractor->Buffer2 = calloc(Attractor->Max_Pt,
1127                                 pointStructSize)) == NULL) {
1128                         free_strange(mi);
1129                         return;
1130                 }
1131
1132         Attractor->Width = MI_WIDTH(mi);
1133         Attractor->Height = MI_HEIGHT(mi);
1134         Attractor->Cur_Pt = 0;
1135         Attractor->Count = 0;
1136         Attractor->Col = NRAND(MI_NPIXELS(mi));
1137         Attractor->Speed = 4;
1138
1139         Attractor->Iterate = Funcs[NRAND(2)];
1140         if (curve < 10) /* Avoid boring Iterate_X2. */
1141                 Attractor->Iterate = Iterate_X3;
1142
1143         Random_Prm(Attractor->Prm1);
1144         Random_Prm(Attractor->Prm2);
1145 #ifndef NO_DBUF
1146         if (Attractor->dbuf != None)
1147                 XFreePixmap(display, Attractor->dbuf);
1148         #ifdef useAccumulator
1149         #define A Attractor
1150         if (useAccumulator)
1151         {
1152                 Attractor->dbuf = None;
1153         }
1154         else
1155         #undef A
1156         #endif
1157         {
1158                 Attractor->dbuf = XCreatePixmap (display, MI_WINDOW(mi),
1159                         Attractor->Width, Attractor->Height,
1160                         /* useAccumulator ? MI_DEPTH(mi) : */ 1);
1161         }
1162         /* Allocation checked */
1163         if (Attractor->dbuf != None) {
1164                 XGCValues   gcv;
1165
1166                 gcv.foreground = 0;
1167                 gcv.background = 0;
1168 #ifndef HAVE_JWXYZ
1169                 gcv.graphics_exposures = False;
1170 #endif /* HAVE_JWXYZ */
1171                 gcv.function = GXcopy;
1172
1173                 if (Attractor->dbuf_gc != None)
1174                         XFreeGC(display, Attractor->dbuf_gc);
1175
1176                 if ((Attractor->dbuf_gc = XCreateGC(display, Attractor->dbuf,
1177 #ifndef HAVE_JWXYZ
1178                                 GCGraphicsExposures |
1179 #endif /* HAVE_JWXYZ */
1180                                GCFunction | GCForeground | GCBackground,
1181                                 &gcv)) == None) {
1182                         XFreePixmap(display, Attractor->dbuf);
1183                         Attractor->dbuf = None;
1184                 } else {
1185                         XFillRectangle(display, Attractor->dbuf, Attractor->dbuf_gc,
1186                                 0, 0, Attractor->Width, Attractor->Height);
1187                         XSetBackground(display, gc, MI_BLACK_PIXEL(mi));
1188                         XSetFunction(display, gc, GXcopy);
1189                 }
1190         }
1191 #endif
1192
1193
1194 #ifdef useAccumulator
1195         #define A Attractor
1196         if (useAccumulator) {
1197                 static const struct threadpool_class threadClass = {
1198                         sizeof(THREAD),
1199                         thread_create,
1200                         thread_destroy
1201                 };
1202                 Screen *screen = MI_SCREENPTR(mi);
1203                 int i;
1204                 unsigned maxThreads, threadCount;
1205                 unsigned bpp = visual_pixmap_depth (screen, MI_VISUAL(mi));
1206                 size_t threadAlign1 = 8 * thread_memory_alignment(display) - 1;
1207                 if (A->cols) {
1208                         if (A->visualClass != TrueColor && A->numCols > 2)
1209                                 XFreeColors (display, MI_COLORMAP(mi), A->cols, A->numCols, 0);
1210                         free (A->cols);
1211                 }
1212                 if (MI_NPIXELS(mi) <= 2) {
1213                         A->numCols = 2;
1214                         A->visualClass = StaticColor;
1215                 } else {
1216                         A->numCols = DEF_NUM_COLS;
1217                         A->visualClass = visual_class(screen, MI_VISUAL(mi));
1218                 }
1219
1220                 A->cols = calloc (A->numCols,sizeof(*A->cols));
1221                 if (!A->cols) {
1222                         free_strange(mi);
1223                         return;
1224                 }
1225
1226                 if (A->visualClass == TrueColor) {
1227                         /* Rebuilds ramp every frame. No need for XAllocColor. */
1228                         /* TODO: This could also include PseudoColor. */
1229                         visual_rgb_masks (screen, MI_VISUAL(mi),
1230                                 &A->rMask, &A->gMask, &A->bMask);
1231                         A->rShift = 31 - i_log2 (A->rMask);
1232                         A->gShift = 31 - i_log2 (A->gMask);
1233                         A->bShift = 31 - i_log2 (A->bMask);
1234
1235                         free (A->palette);
1236                         A->palette = malloc(MI_NPIXELS(mi) * sizeof(XColor));
1237                         if (!A->palette) {
1238                                 free_strange (mi);
1239                                 return;
1240                         }
1241
1242                         for (i=0;i<MI_NPIXELS(mi);i++)
1243                                 A->palette[i].pixel = MI_PIXEL(mi,i);
1244
1245                         XQueryColors (display, MI_COLORMAP(mi), A->palette, MI_NPIXELS(mi));
1246                 } else if (A->numCols == 2) {
1247                         A->cols[0] = MI_BLACK_PIXEL (mi);
1248                         A->cols[1] = MI_WHITE_PIXEL (mi);
1249                 } else {
1250                         /* No changing colors, unfortunately. */
1251                         XColor color;
1252
1253                         color.pixel = MI_PIXEL(mi,NRAND(MI_NPIXELS(mi)));
1254                         XQueryColor (display, MI_COLORMAP(mi), &color);
1255
1256                         for (;;) {
1257                                 for (i=0;i<A->numCols;i++) {
1258                                         XColor out_color;
1259                                         ramp_color (&color, &out_color, i, A->numCols);
1260                                         if (!XAllocColor (display, MI_COLORMAP(mi), &out_color))
1261                                                 break;
1262                                         A->cols[i] = out_color.pixel;
1263                                         /*
1264                                         if (!XAllocColor(MI_DISPLAY(mi), cmap, &cols[i])) {
1265                                         if (!XAllocColor(display, cmap, &cols[i])) {
1266                                                 cols[i].pixel = WhitePixel (display, DefaultScreen (display));
1267                                                 cols[i].red = cols[i].green = cols[i].blue = 0xFFFF;
1268                                         }
1269                                         */
1270                                 }
1271
1272                                 if (i==A->numCols)
1273                                         break;
1274
1275                                 XFreeColors (display, MI_COLORMAP(mi), A->cols, i, 0);
1276                                 A->numCols = A->numCols * 11 / 12;
1277                                 if (A->numCols < 2) {
1278                                         A->numCols = 0;
1279                                         free_strange (mi);
1280                                         abort();
1281                                         return;
1282                                 }
1283                         }
1284                 }
1285
1286                 /* Add slack for horizontal blur, then round up to the platform's SIMD
1287                  * alignment.
1288                  */
1289                 A->alignedWidth =
1290                         (((A->Width + pointSize) * sizeof(PIXEL0) + (__BIGGEST_ALIGNMENT__ - 1)) &
1291                                 ~(__BIGGEST_ALIGNMENT__ - 1)) / sizeof(PIXEL0);
1292
1293                 if (A->accImage)
1294                         destroy_xshm_image (display, A->accImage, &A->shmInfo);
1295                 A->accImage = create_xshm_image(display, MI_VISUAL(mi),
1296                         MI_DEPTH(mi), ZPixmap, &A->shmInfo,
1297                         ((A->alignedWidth * bpp + threadAlign1) & ~threadAlign1) / bpp,
1298                         A->Height);
1299
1300                 A->blurFac = (PIXEL0)(65536 * (motionBlur - 1) / (motionBlur + 1));
1301                 A->colorFac = 2 / (motionBlur + 1);
1302
1303                 /* Don't overdose on threads. */
1304                 threadCount = hardware_concurrency (display);
1305                 maxThreads = A->Height / (pointSize * 4);
1306                 if (maxThreads < 1)
1307                         maxThreads = 1;
1308                 if (threadCount > maxThreads)
1309                         threadCount = maxThreads;
1310
1311                 if (A->threads)
1312                         free (A->threads);
1313                 A->threads = malloc (threadCount * sizeof(*A->threads));
1314                 if (!A->threads) {
1315                         free_strange (mi);
1316                         return;
1317                 }
1318
1319                 if (A->pool.count)
1320                         threadpool_destroy (&A->pool);
1321                 if (threadpool_create (&A->pool, &threadClass, display, threadCount)) {
1322                         A->pool.count = 0;
1323                         free_strange (mi);
1324                         return;
1325                 }
1326         }
1327         #undef A
1328 #endif
1329         MI_CLEARWINDOW(mi);
1330
1331         /* Do not want any exposure events from XCopyPlane */
1332         XSetGraphicsExposures(display, MI_GC(mi), False);
1333 }
1334
1335 /***************************************************************/
1336
1337 #ifdef STANDALONE
1338 XSCREENSAVER_MODULE ("Strange", strange)
1339 #endif
1340
1341 #endif /* MODE_strange */