summaryrefslogtreecommitdiffstats
path: root/hacks/strange.c
blob: 89e9a3bc455cc677c291913a9666728abca01b51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
/* -*- Mode: C; tab-width: 4 -*- */
/* strange --- strange attractors */

#if 0
static const char sccsid[] = "@(#)strange.c	5.00 2000/11/01 xlockmore";
#endif

/*-
* Copyright (c) 1997 by Massimino Pascal <Pascal.Massimon@ens.fr>
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation.
*
* This file is provided AS IS with no warranties of any kind.  The author
* shall have no liability with respect to the infringement of copyrights,
* trade secrets or any patents by this file or any part thereof.  In no
* event will the author be liable for any lost revenue or profits or
* other special, indirect and consequential damages.
*
* Revision History:
* 10-Apr-2017: dmo2118@gmail.com: Enhancements for accumulator mode:
*              Performance tuning, varying colors, fixed wobbliness.
*              New options: point size, zoom, brightness, motion blur.
* 08-Apr-2017: dmo2118@gmail.com: Merged with current xlockmore strange.c.
*              Also resurrected the -curve parameter from XScreenSaver 2.31.
*              Multi-monitor fixes.
*              More allocation checks.
* 13-Apr-2010: Added useAccumulator, VARY_SPEED_TO_AVOID_BOREDOM.
* 22-Dec-2004: TDA: Replace Gauss_Rand with a real Gaussian.
* 01-Nov-2000: Allocation checks
* 30-Jul-1998: sineswiper@resonatorsoft.com: added curve factor (discovered
*              while experimenting with the Gauss_Rand function).
* 10-May-1997: jwz AT jwz.org: turned into a standalone program.
*              Made it render into an offscreen bitmap and then copy
*              that onto the screen, to reduce flicker.
*
* strange attractors are not so hard to find...
*/

/* Be sure to try:
* ./strange -points 500000 -delay 0 -point-size 3
* ./strange -points 500000 -delay 0 -point-size 2 -curve 5 -zoom 1.5 -brightness 0.75
*/

/* TODO: Can anything be done about the overflow with -point-size 32? */

#ifdef STANDALONE
# define MODE_strange
# define DEFAULTS	"*delay: 10000 \n" \
					"*ncolors: 100 \n" \
					"*fpsSolid: True \n" \
					"*ignoreRotation: True \n" \
					"*useSHM: True \n" \
					"*useThreads: True \n" \
				    "*lowrez: True \n" \

# define SMOOTH_COLORS
# define release_strange 0
# define reshape_strange 0
# define strange_handle_event 0
# include "xlockmore.h"		/* from the xscreensaver distribution */
#else /* !STANDALONE */
# include "xlock.h"		/* from the xlockmore distribution */
# define ENTRYPOINT
#endif /* !STANDALONE */

#include <errno.h>
#include "pow2.h"
#include "thread_util.h"
#include "xshm.h"

#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif

#ifdef MODE_strange
#define DEF_CURVE       "10"
#define DEF_POINTS      "5500"
#define DEF_POINT_SIZE  "1"
#define DEF_ZOOM        "0.9" /* approx. 1 / 1.1 */
#define DEF_BRIGHTNESS  "1.0"
#define DEF_MOTION_BLUR "3.0" /* Formerly MERGE_FRAMES, but it's IIR now. */

static int curve;
static int points;
static int pointSize;
static float zoom;
static float brightness;
static float motionBlur;

static XrmOptionDescRec opts[] =
{
		{"-curve",        ".strange.curve",      XrmoptionSepArg, 0},
		{"-points",       ".strange.points",     XrmoptionSepArg, 0},
		{"-point-size",   ".strange.pointSize",  XrmoptionSepArg, 0},
		{"-zoom",         ".strange.zoom",       XrmoptionSepArg, 0},
		{"-brightness",   ".strange.brightness", XrmoptionSepArg, 0},
		{"-motion-blur",  ".strange.motionBlur", XrmoptionSepArg, 0},
		THREAD_OPTIONS
};
static argtype vars[] =
{
		{&curve,      "curve",      "Curve",      DEF_CURVE,       t_Int},
		{&points,     "points",     "Points",     DEF_POINTS,      t_Int},
		{&pointSize,  "pointSize",  "PointSize",  DEF_POINT_SIZE,  t_Int},
		{&zoom,       "zoom",       "Zoom",       DEF_ZOOM,        t_Float},
		{&brightness, "brightness", "Brightness", DEF_BRIGHTNESS,  t_Float},
		{&motionBlur, "motionBlur", "MotionBlur", DEF_MOTION_BLUR, t_Float},
};
static OptionStruct desc[] =
{
		{"-curve", "set the curve factor of the attractors"},
		{"-points", "change the number of points/iterations each frame"},
		{"-point-size", "change the size of individual points"},
		{"-zoom", "zoom in or out"},
		{"-brightness", "adjust the brightness for accumulator mode"},
		{"-motion-blur", "adds motion blur"},
};
ENTRYPOINT ModeSpecOpt strange_opts =
{sizeof opts / sizeof opts[0], opts,
sizeof vars / sizeof vars[0], vars, desc};

#ifdef USE_MODULES
ModStruct   strange_description =
{"strange", "init_strange", "draw_strange", (char *) NULL,
"init_strange", "init_strange", "free_strange", &strange_opts,
10000, 1, 1, 1, 64, 1.0, "",
"Shows strange attractors", 0, NULL};
#endif

#ifdef HAVE_JWXYZ
# define NO_DBUF
#endif

typedef float DBL;
typedef int PRM;

#define UNIT_BITS 12
#define UNIT (1<<UNIT_BITS)
#define UNIT2 (1<<14)
#define COLOR_BITS 16
/* #define UNIT2 (3140*UNIT/1000) */

#define SKIP_FIRST      100
#define DBL_To_PRM(x)  (PRM)( (DBL)(UNIT)*(x) )


#define DO_FOLD(a) (a)<0 ? -A->Fold[ (-(a))&(UNIT2-1) ] : A->Fold[ (a)&(UNIT2-1) ]

#if 0
#define DO_FOLD(a) (a)<-UNIT2 ? -A->Fold[(-(a))%UNIT2] : (a)<0 ? -A->Fold[ -(a) ] :\
(a)>UNIT2 ? A->Fold[ (a)%UNIT2 ] : A->Fold[ (a) ]
#define DO_FOLD(a) DBL_To_PRM( sin( (DBL)(a)/UNIT ) )
#define DO_FOLD(a) (a)<0 ? DBL_To_PRM( exp( 16.0*(a)/UNIT2 ) )-1.0 : \
DBL_To_PRM( 1.0-exp( -16.0*(a)/UNIT2 ) )
#endif

/* useAccumulator performs two functions:
* If it is defined, then support for the accumulator will be compiled.
* It is also the condition for which the accumulator renderer will engage.
*/
#define useAccumulator (A->Max_Pt > 6000)
#define ACC_GAMMA 10.0
#define DEF_NUM_COLS 150
/* Extra options: */
#define VARY_SPEED_TO_AVOID_BOREDOM
/*#define AUTO_ZOOM*/ /* Works funny, but try it with -curve 5. */

/******************************************************************/

#define MAX_PRM 3*5

#if defined(__BIGGEST_ALIGNMENT__) \
	&& (defined(__GNUC__) \
	 && (__GNUC__ == 4 && __GNUC_MINOR__ >= 4 || __GNUC__ >= 5) \
	|| defined(__clang__))
# define ALIGNED __attribute__((aligned(__BIGGEST_ALIGNMENT__)))
# define ALIGN_HINT(ptr) __builtin_assume_aligned((ptr), __BIGGEST_ALIGNMENT__)
#else
# define ALIGNED
# define ALIGN_HINT(ptr) (ptr)
# ifndef __BIGGEST_ALIGNMENT__
#  define __BIGGEST_ALIGNMENT__ (sizeof(void *))
# endif
#endif


#ifdef HAVE_INTTYPES_H
typedef uint16_t ALIGNED PIXEL0;
typedef uint32_t PIXEL0X;
typedef uint32_t ALIGNED PIXEL1;
#else
typedef unsigned short ALIGNED PIXEL0;
typedef unsigned long PIXEL0X;
typedef unsigned long ALIGNED PIXEL1;
#endif

static const union {
#ifdef HAVE_INTTYPES_H
	uint16_t signature;
	uint8_t bytes[2];
#else
	unsigned short signature;
	unsigned char bytes[2];
#endif
} byte_order_union = {MSBFirst};

#define LOCAL_BYTE_ORDER byte_order_union.bytes[1]

typedef struct _ATTRACTOR {
	DBL         Prm1[MAX_PRM], Prm2[MAX_PRM];
	PRM         Prm[MAX_PRM], *Fold;
	void        (*Iterate) (const struct _ATTRACTOR *, PRM, PRM, PRM *, PRM *);
	void       *Buffer1, *Buffer2; /* Either XPoint or XRectangle. */
	int         Cur_Pt, Max_Pt;
	int         Col, Count, Speed;
	int         Width, Height;
	Pixmap      dbuf;	/* jwz */
	GC          dbuf_gc;
	#ifdef useAccumulator
		int visualClass;
		size_t alignedWidth;
		unsigned long rMask, gMask, bMask;
		unsigned rShift, gShift, bShift;
		PIXEL0 blurFac; /* == 0 when no motion blur is taking place. */
		double colorFac;
		XColor *palette;
		unsigned numCols;
		unsigned long *cols;
		XImage *accImage;
		XShmSegmentInfo shmInfo;
		struct _THREAD **threads;
		struct threadpool pool;
	#endif
} ATTRACTOR;

static ATTRACTOR *Root = (ATTRACTOR *) NULL;

#ifdef useAccumulator
typedef struct _THREAD {
	const ATTRACTOR *Attractor;
	unsigned long Rnd;
	size_t y0, y1, y2;

	PIXEL0 **accMap;
	PIXEL0 *bloomRows;
	PIXEL1 *colorRow;
	PIXEL0 *motionBlur;

	PRM xmin, xmax, ymin, ymax;
	unsigned pixelCount;
} THREAD;
#endif

static DBL  Amp_Prm[MAX_PRM] =
{
	1.0, 3.5, 3.5, 2.5, 4.7,
	1.0, 3.5, 3.6, 2.5, 4.7,
	1.0, 1.5, 2.2, 2.1, 3.5
};
static DBL  Mid_Prm[MAX_PRM] =
{
	0.0, 1.5, 0.0, .5, 1.5,
	0.0, 1.5, 0.0, .5, 1.5,
	0.0, 1.5, -1.0, -.5, 2.5,
};

#if 0

static inline uint64_t frq(void)
{
	return 1000000;
}

static inline uint64_t tick(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec * frq() + tv.tv_usec;
}

#endif

static      DBL
Old_Gauss_Rand(DBL c, DBL A, DBL S)
{
	DBL         y,z;

	y = (DBL) LRAND() / MAXRAND;
	z = curve / 10;
  	y = A * (z - exp(-y * y * S)) / (z - exp(-S));
	if (NRAND(2))
		return (c + y);
	else
		return (c - y);
}

#if 0
/* dmo2118: seems to be responsible for lots of boring-looking rings */

/* I don't know that it makes a difference, but this one actually *is*
   a Gaussian.  [TDA] */

/* Generate Gaussian random number: mean c, "amplitude" A (actually
   A is 3*standard deviation).  'S' is unused.  */

/* Note this generates a pair of gaussian variables, so it saves one
   to give out next time it's called */

static double
Gauss_Rand(DBL c, DBL A, DBL S)
{
	static double d;
	static Bool ready = 0;
	if(ready) {
		ready = 0;
		return c + A/3 * d;
	} else {
		double x, y, w;
		do {
			x = 2.0 * (double)LRAND() / MAXRAND - 1.0;
			y = 2.0 * (double)LRAND() / MAXRAND - 1.0;
			w = x*x + y*y;
		} while(w >= 1.0);

		w = sqrt((-2 * log(w))/w);
		ready = 1;
		d =          x * w;
		return c + A/3 * y * w;
	}
}
#endif

static void
Random_Prm(DBL * Prm)
{
	int         i;

	for (i = 0; i < MAX_PRM; ++i) {
#if 0
		if (curve == 10)
			Prm[i] = Gauss_Rand (Mid_Prm[i], Amp_Prm[i], 4.0);
		else
#endif
			Prm[i] = Old_Gauss_Rand (Mid_Prm[i], Amp_Prm[i], 4.0);
	}
}

/***************************************************************/

  /* 2 examples of non-linear map */

static void
Iterate_X2(const ATTRACTOR * A, PRM x, PRM y, PRM * xo, PRM * yo)
{
	PRM         xx, yy, xy, x2y, y2x, Tmp;

	xx = (x * x) >> UNIT_BITS;
	x2y = (xx * y) >> UNIT_BITS;
	yy = (y * y) >> UNIT_BITS;
	y2x = (yy * x) >> UNIT_BITS;
	xy = (x * y) >> UNIT_BITS;

	Tmp = A->Prm[1] * xx + A->Prm[2] * xy + A->Prm[3] * yy + A->Prm[4] * x2y;
	Tmp = A->Prm[0] - y + (Tmp >> UNIT_BITS);
	*xo = DO_FOLD(Tmp);
	Tmp = A->Prm[6] * xx + A->Prm[7] * xy + A->Prm[8] * yy + A->Prm[9] * y2x;
	Tmp = A->Prm[5] + x + (Tmp >> UNIT_BITS);
	*yo = DO_FOLD(Tmp);
}

static void
Iterate_X3(const ATTRACTOR * A, PRM x, PRM y, PRM * xo, PRM * yo)
{
	PRM         xx, yy, xy, x2y, y2x, Tmp_x, Tmp_y, Tmp_z;

	xx = (x * x) >> UNIT_BITS;
	x2y = (xx * y) >> UNIT_BITS;
	yy = (y * y) >> UNIT_BITS;
	y2x = (yy * x) >> UNIT_BITS;
	xy = (x * y) >> UNIT_BITS;

	Tmp_x = A->Prm[1] * xx + A->Prm[2] * xy + A->Prm[3] * yy + A->Prm[4] * x2y;
	Tmp_x = A->Prm[0] - y + (Tmp_x >> UNIT_BITS);
	Tmp_x = DO_FOLD(Tmp_x);

	Tmp_y = A->Prm[6] * xx + A->Prm[7] * xy + A->Prm[8] * yy + A->Prm[9] * y2x;
	Tmp_y = A->Prm[5] + x + (Tmp_y >> UNIT_BITS);

	Tmp_y = DO_FOLD(Tmp_y);

	Tmp_z = A->Prm[11] * xx + A->Prm[12] * xy + A->Prm[13] * yy + A->Prm[14] * y2x;
	Tmp_z = A->Prm[10] + x + (Tmp_z >> UNIT_BITS);
	Tmp_z = UNIT + ((Tmp_z * Tmp_z) >> UNIT_BITS);

	/* Can happen with -curve 9. */
	if (!Tmp_z)
		Tmp_z = 1;

#ifdef HAVE_INTTYPES_H
	{
		uint64_t Tmp_z1 = (1 << 30) / Tmp_z;
		*xo = (Tmp_x * Tmp_z1) >> (30 - UNIT_BITS);
		*yo = (Tmp_y * Tmp_z1) >> (30 - UNIT_BITS);
	}
#else
	*xo = (Tmp_x * UNIT) / Tmp_z;
	*yo = (Tmp_y * UNIT) / Tmp_z;
#endif
}

static void (*Funcs[2]) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *) = {
	Iterate_X2, Iterate_X3
};

/***************************************************************/

ENTRYPOINT void
free_strange(ModeInfo *mi)
{
	Display *display = MI_DISPLAY(mi);
	ATTRACTOR  *A = &Root[MI_SCREEN(mi)];

	if (A->Buffer1 != NULL) {
		free(A->Buffer1);
		A->Buffer1 = (XPoint *) NULL;
	}
	if (A->Buffer2 != NULL) {
		free(A->Buffer2);
		A->Buffer2 = (XPoint *) NULL;
	}
	if (A->dbuf) {
		XFreePixmap(display, A->dbuf);
		A->dbuf = None;
	}
	if (A->dbuf_gc) {
		XFreeGC(display, A->dbuf_gc);
		A->dbuf_gc = None;
	}
	if (A->Fold != NULL) {
		free(A->Fold);
		A->Fold = (PRM *) NULL;
	}

#ifdef useAccumulator
	if (useAccumulator) {
		if (A->pool.count) {
			threadpool_destroy (&A->pool);
			A->pool.count = 0;
		}

		free (A->threads);
		A->threads = NULL;

		if (A->accImage) {
			destroy_xshm_image (display, A->accImage, &A->shmInfo);
			A->accImage = NULL;
		}

		free (A->palette);
		A->palette = NULL;

		if (A->cols) {
			if (A->visualClass != TrueColor && A->numCols > 2)
				XFreeColors (display, MI_COLORMAP(mi), A->cols, A->numCols, 0);
			free (A->cols);
			A->cols = NULL;
		}
	}
#endif
}

/* NRAND() is also in use; making three PRNGs in total here. */

/* ISO/IEC 9899 suggests this one. Doesn't require 64-bit math. */
#define GOODRND(seed) ((seed) = (((seed) * 1103515245 + 12345) & 0x7fffffff))
#define GOODRND_BITS 31

/* Extremely cheap entropy: this is often a single LEA instruction. */
#define CHEAPRND(seed) ((seed) = (seed) * 5)

static void
init_draw (const ATTRACTOR *A, PRM *x, PRM *y,
           PRM *xmin, PRM *ymin, PRM *xmax, PRM *ymax, unsigned long *rnd)
{
	int         n;
	PRM         xo, yo;

	*xmin = UNIT;
	*ymin = UNIT;
	*xmax = -UNIT;
	*ymax = -UNIT;

	*x = *y = DBL_To_PRM(.0);
	for (n = SKIP_FIRST; n; --n) {
		(*A->Iterate) (A, *x, *y, &xo, &yo);

#ifdef AUTO_ZOOM
		if (xo > *xmax)
			*xmax = xo;
		if (xo < *xmin)
			*xmin = xo;
		if (yo > *ymax)
			*ymax = yo;
		if (yo < *ymin)
			*ymin = yo;
#endif

		/* Can't use NRAND(), because that modifies global state in a
		 * thread-unsafe way.
		 */
		*x = xo + (GOODRND(*rnd) >> (GOODRND_BITS - 3)) - 4;
		*y = yo + (GOODRND(*rnd) >> (GOODRND_BITS - 3)) - 4;
	}
}

static void
recalc_scale (const ATTRACTOR *A, PRM xmin, PRM ymin, PRM xmax, PRM ymax,
              DBL *Lx, DBL *Ly, PRM *mx, PRM *my)
{
#ifndef AUTO_ZOOM
	xmin = -UNIT;
	ymin = -UNIT;
	xmax = UNIT;
	ymax = UNIT;
#endif

	*Lx = zoom * (DBL) A->Width / (xmax - xmin);
	*Ly = -zoom * (DBL) A->Height / (ymax - ymin);
	*mx = A->Width/2 - (xmax + xmin) * *Lx / 2;
	*my = A->Height/2 - (ymax + ymin) * *Ly / 2;
}

#ifdef useAccumulator

static void
thread_destroy (void *Self_Raw)
{
	THREAD     *T = (THREAD *)Self_Raw;

	aligned_free (T->accMap[0]);
	(void) free((void *) T->accMap);
	aligned_free (T->bloomRows);
	aligned_free (T->colorRow);
	aligned_free (T->motionBlur);
}

static int
thread_create (void *Self_Raw, struct threadpool *pool, unsigned id)
{
	THREAD     *T = (THREAD *)Self_Raw;
	int         i;
	const ATTRACTOR *A = GET_PARENT_OBJ(ATTRACTOR, pool, pool);

	memset (T, 0, sizeof(*T));

	T->Attractor = A;
	A->threads[id] = T;

	T->Rnd = random();

	/* The gap between y0 and y1 is to preheat the box blur. */
	T->y1 = A->Height * id / pool->count;
	T->y2 = A->Height * (id + 1) / pool->count;
	T->y0 = T->y1 < pointSize ? 0 : T->y1 - pointSize;

	T->accMap = (PIXEL0**)calloc(A->Height,sizeof(PIXEL0*));
	if (!T->accMap) {
		thread_destroy (T);
		return ENOMEM;
	}
	T->accMap[0] = NULL;
	if (aligned_malloc ((void **)&T->accMap[0], __BIGGEST_ALIGNMENT__,
		A->alignedWidth * A->Height * sizeof(PIXEL0))) {
		thread_destroy (T);
		return ENOMEM;
	}
	for (i=0;i<A->Height;i++)
		T->accMap[i] = T->accMap[0] + A->alignedWidth * i;

	if (aligned_malloc ((void **)&T->bloomRows, __BIGGEST_ALIGNMENT__,
		A->alignedWidth * (pointSize + 2) * sizeof(*T->bloomRows))) {
		thread_destroy (T);
		return ENOMEM;
	}
	if (aligned_malloc ((void **)&T->colorRow, __BIGGEST_ALIGNMENT__,
		A->alignedWidth * sizeof(*T->colorRow))) {
		thread_destroy (T);
		return ENOMEM;
	}
	if (A->blurFac) {
		if (aligned_malloc ((void **)&T->motionBlur, __BIGGEST_ALIGNMENT__,
			A->alignedWidth * (T->y2 - T->y1) * sizeof(*T->motionBlur))) {
			thread_destroy (T);
			return ENOMEM;
		}

		memset (T->motionBlur, 0, A->alignedWidth * (T->y2 - T->y1) * sizeof(*T->motionBlur));
	}

	return 0;
}

static void
points_thread (void *Self_Raw)
{
	/* Restricts viewable area to 2^(32-L_Bits). */
	const unsigned L_Bits = 19; /* Max. image size: 8192x8192. */

	THREAD     *T = (THREAD *)Self_Raw;
	const ATTRACTOR *A = T->Attractor;
	int         n;
	PRM         x, y, xo, yo;
	DBL         Lx, Ly;
	PRM         iLx, iLy, cx, cy;
	void        (*Iterate) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *);
	unsigned    Rnd;
	PRM         xmax, xmin, ymax, ymin;

	Iterate = A->Iterate;

	if (useAccumulator) {
		memset (T->accMap[0], 0, sizeof(PIXEL0) * A->alignedWidth * A->Height);
	}

	/* Using CHEAPRND() by itself occasionally gets stuck at 0 mod 8, so seed it
	 * from GOODRND().
	 */
	init_draw (A, &x, &y, &xmin, &ymin, &xmax, &ymax, &T->Rnd);
	recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);

	Rnd = GOODRND(T->Rnd);

	iLx = Lx * (1 << L_Bits);
	iLy = Ly * (1 << L_Bits);
	if (!iLx) /* Can happen with small windows. */
		iLx = 1;
	if (!iLy)
		iLy = 1;

	for (n = T->Attractor->Max_Pt / A->pool.count; n; --n) {
		unsigned mx,my;
		(*Iterate) (T->Attractor, x, y, &xo, &yo);
		mx = ((iLx * x) >> L_Bits) + cx;
		my = ((iLy * y) >> L_Bits) + cy;
		/* Fun trick: making m[x|y] unsigned means we can skip mx<0 && my<0. */
		if (mx<A->Width && my<A->Height)
			T->accMap[my][mx]++;

		#ifdef AUTO_ZOOM
		if (xo > xmax)
			xmax = xo;
		if (xo < xmin)
			xmin = xo;
		if (yo > ymax)
			ymax = yo;
		if (yo < ymin)
			ymin = yo;

		if (!(n & 0xfff)) {
			recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);
		}
		#endif

		/* Skimp on the randomness. */
		x = xo + (CHEAPRND(Rnd) >> (sizeof(Rnd) * 8 - 3)) - 4;
		y = yo + (CHEAPRND(Rnd) >> (sizeof(Rnd) * 8 - 3)) - 4;
	}
}

static void
rasterize_thread (void *Self_Raw)
{
	THREAD     *T = (THREAD *)Self_Raw;
	const ATTRACTOR *A = T->Attractor;
	unsigned    i, j, k;
	PRM         xmax = 0, xmin = A->Width, ymax = 0, ymin = A->Height;
	unsigned long colorScale =
		(double)A->Width * A->Height
		* (1 << COLOR_BITS) * brightness
		* A->colorFac
		* (zoom * zoom) / (0.9 * 0.9)
		/ 640.0 / 480.0
		/ (pointSize * pointSize)
		* 800000.0
		/ (float)A->Max_Pt
		* (float)A->numCols/256;
	#ifdef VARY_SPEED_TO_AVOID_BOREDOM
	unsigned    pixelCount = 0;
	#endif
	PIXEL0     *motionBlurRow = T->motionBlur;
	void       *outRow = (char *)A->accImage->data
	                     + A->accImage->bytes_per_line * T->y1;

	/* Clang needs these for loop-vectorizing; A->Width doesn't work. */
	unsigned    w = A->Width, aw = A->alignedWidth;

	if (A->numCols == 2) /* Brighter for monochrome. */
		colorScale *= 4;

	/* bloomRows: row ring buffer, bloom accumulator, in that order. */
	memset (T->bloomRows, 0, (pointSize + 1) * aw * sizeof(*T->bloomRows));

	/* This code is highly amenable to auto-vectorization; on GCC use -O3 to get
	 * that. On x86-32, also add -msse2.
	 */
	for (j=T->y0;j<T->y2;j++) {
		Bool has_col = False;
		int accum = 0;

		PIXEL0 *bloomRow =
			ALIGN_HINT(T->bloomRows + A->alignedWidth * (j % pointSize));
		PIXEL0 *accumRow =
			ALIGN_HINT(T->bloomRows + A->alignedWidth * pointSize);
		PIXEL1 *colRow = T->colorRow;

		/* Moderately fast bloom.  */

		for (i=0;i<aw;i++) {
			accumRow[i] -= bloomRow[i];
			bloomRow[i] = 0;
		}

		for (k=0;k<A->pool.count;k++) {
			const PIXEL0 *inRow = ALIGN_HINT(A->threads[k]->accMap[j]);
			for (i=0;i<aw;i++) {
				/* Lots of last-level cache misses. Such is life. */
				bloomRow[i] += inRow[i];
			}
		}

		/* Hardware prefetching works better going forwards than going backwards.
		 * Since this blurs/blooms/convolves in-place, it expands points to the
		 * right instead of to the left.
		 */
		for (i=0;i<pointSize-1;i++)
			accum += bloomRow[i];

		for (i=0;i<aw;i++) {
			PIXEL0 oldBloom = bloomRow[i];

			/* alignedWidth has extra padding for this one line. */
			accum += bloomRow[i+pointSize-1];

			bloomRow[i] = accum;
			accumRow[i] += accum;
			accum -= oldBloom;
		}

		if (j>=T->y1) {
			PIXEL0 *accumRow1 = A->blurFac ? motionBlurRow : accumRow;
			PIXEL0 blurFac = A->blurFac;

			if (blurFac) {
				/* TODO: Do I vectorize OK? */
				if (blurFac == 0x8000) {
					/* Optimization for the default. */
					for (i=0;i<aw;i++)
						motionBlurRow[i] = (motionBlurRow[i] >> 1) + accumRow[i];
				} else {
					for (i=0;i<aw;i++)
						motionBlurRow[i] = (PIXEL0)(((PIXEL0X)motionBlurRow[i] * blurFac) >> 16) + accumRow[i];
				}

				motionBlurRow += aw;
			}

			for (i=0;i<aw;i++) {
				unsigned col = (accumRow1[i] * colorScale) >> COLOR_BITS;
				if (col>A->numCols-1) {
					col = A->numCols-1;
				}
				#ifdef VARY_SPEED_TO_AVOID_BOREDOM
				if (col>0) {
					if (col<A->numCols-1)  /* we don't count maxxed out pixels */
						pixelCount++;
					if (i > xmax)
						xmax = i;
					if (i < xmin)
						xmin = i;
					has_col = True;
				}
				#endif
				colRow[i] = A->cols[col];
			}

			#ifdef VARY_SPEED_TO_AVOID_BOREDOM
			if (has_col) {
				if (j > ymax)
					ymax = j;
				if (j < ymin)
					ymin = j;
			}
			#endif

#if 0
			for (i=0;i<aw;i++) {
				if (MI_NPIXELS(mi) < 2)
					XSetForeground(display, gc, MI_WHITE_PIXEL(mi));
				else
					/*XSetForeground(display, gc, MI_PIXEL(mi, A->Col % MI_NPIXELS(mi)));*/
					XSetForeground(display, gc, cols[col].pixel);

				if (A->dbuf != None) {
					XSetForeground(display, A->dbuf_gc, cols[col].pixel);
					XDrawPoint(display, A->dbuf, A->dbuf_gc, i, j);
				} else {
					XSetForeground(display, gc, cols[col].pixel);
					XDrawPoint(display, window, gc, i, j);
				}
			}
#endif

			if (A->accImage->bits_per_pixel==32 &&
				A->accImage->byte_order==LOCAL_BYTE_ORDER) {
				for (i=0;i<aw;i++)
					((uint32_t *)outRow)[i] = colRow[i];
			} else if (A->accImage->bits_per_pixel==16 &&
				A->accImage->byte_order==LOCAL_BYTE_ORDER) {
				for (i=0;i<aw;i++)
					((uint16_t *)outRow)[i] = colRow[i];
			} else if (A->accImage->bits_per_pixel==8) {
				for (i=0;i<aw;i++)
					((uint8_t *)outRow)[i] = colRow[i];
			} else {
				for (i=0;i<w;i++)
					XPutPixel (A->accImage, i, j, colRow[i]);
			}

			outRow = (char *)outRow + A->accImage->bytes_per_line;
		}
	}

	/*
	uint64_t dt = 0;
	uint64_t t0 = tick();
	dt += tick() - t0;

	printf("B %g\t(%d,%d)\t%dx%d\t%d\n", 1000.0 * dt / frq(),
		xmin, ymin, xmax - xmin, ymax - ymin, pixelCount);
	*/

	T->xmax = xmax;
	T->xmin = xmin;
	T->ymax = ymax;
	T->ymin = ymin;
	T->pixelCount = pixelCount;
}

static void
ramp_color (const XColor *color_in, XColor *color_out, unsigned i, unsigned n)
{
	float li;
	#define MINBLUE 1
	#define FULLBLUE 128
	#define LOW_COLOR(c) ((c)*li/FULLBLUE)
	#define HIGH_COLOR(c) ((65535-(c))*(li-FULLBLUE)/(256-FULLBLUE)+(c))
	li = MINBLUE
		+ (255.0-MINBLUE) * log(1.0 + ACC_GAMMA*(float)i/n)
		/ log(1.0 + ACC_GAMMA);
	if (li<FULLBLUE) {
		color_out->red = LOW_COLOR(color_in->red);
		color_out->green = LOW_COLOR(color_in->green);
		color_out->blue = LOW_COLOR(color_in->blue);
	} else {
		color_out->red = HIGH_COLOR(color_in->red);
		color_out->green = HIGH_COLOR(color_in->green);
		color_out->blue = HIGH_COLOR(color_in->blue);
	}
}

#endif

static void
draw_points (Display *display, Drawable d, GC gc, const void *Buf,
             unsigned Count)
{
	if (pointSize == 1)
		XDrawPoints(display, d, gc, (XPoint *)Buf, Count, CoordModeOrigin);
	else
		XFillRectangles(display, d, gc, (XRectangle *)Buf, Count);
}

ENTRYPOINT void
draw_strange(ModeInfo * mi)
{
	int         i, j, n, Cur_Pt;
	PRM         x, y, xo, yo;
	DBL         u;
	void       *Buf;
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	GC          gc = MI_GC(mi);
	DBL         Lx, Ly;
	void        (*Iterate) (const ATTRACTOR *, PRM, PRM, PRM *, PRM *);
	PRM         xmin, xmax, ymin, ymax;
	ATTRACTOR  *A;
	unsigned long Rnd = random();
	int         cx, cy;

	if (Root == NULL)
		return;
	A = &Root[MI_SCREEN(mi)];
	if (A->Fold == NULL)
		return;

	Cur_Pt = A->Cur_Pt;
	Iterate = A->Iterate;

	u = (DBL) (A->Count) / 40000.0;
	for (j = MAX_PRM - 1; j >= 0; --j)
		A->Prm[j] = DBL_To_PRM((1.0 - u) * A->Prm1[j] + u * A->Prm2[j]);

	/* We collect the accumulation of the orbits in the 2d int array field. */

	init_draw (A, &x, &y, &xmin, &ymin, &xmax, &ymax, &Rnd);
	recalc_scale (A, xmin, ymin, xmax, ymax, &Lx, &Ly, &cx, &cy);

	A->Cur_Pt = 0;

	xmax = 0;
	xmin = A->Width;
	ymax = 0;
	ymin = A->Height;

	MI_IS_DRAWN(mi) = True;

	#ifdef useAccumulator
	if (useAccumulator) {
		int pixelCount = 0;

		threadpool_run (&A->pool, points_thread);

		if (A->visualClass == TrueColor) {
			XColor *src_color = &A->palette[A->Col % MI_NPIXELS(mi)];

			for (i=0;i<A->numCols;i++) {
				XColor color;
				ramp_color (src_color, &color, i, A->numCols);
				A->cols[i] =
					((((unsigned long)color.red   << 16) >> A->rShift) & A->rMask) |
					((((unsigned long)color.green << 16) >> A->gShift) & A->gMask) |
					((((unsigned long)color.blue  << 16) >> A->bShift) & A->bMask);
			}
		}
		threadpool_wait (&A->pool);

		threadpool_run(&A->pool, rasterize_thread);
		threadpool_wait(&A->pool);

		for (i=0; i!=A->pool.count; ++i) {
			THREAD *T = A->threads[i];
			if (T->xmax > xmax)
				xmax = T->xmax;
			if (T->xmin < xmin)
				xmin = T->xmin;
			if (T->ymax > ymax)
				ymax = T->ymax;
			if (T->ymin < ymin)
				ymin = T->ymin;
			pixelCount += T->pixelCount;
		}

		put_xshm_image (display, A->dbuf != None ? A->dbuf : window,
		                A->dbuf != None ? A->dbuf_gc : gc, A->accImage,
		                0, 0, 0, 0, A->accImage->width, A->accImage->height,
		                &A->shmInfo);

		if (A->dbuf != None) {
			XCopyArea(display, A->dbuf, window, gc, 0, 0, A->Width, A->Height, 0, 0);
		}
		#ifdef VARY_SPEED_TO_AVOID_BOREDOM
			/* Increase the rate of change of the parameters if the attractor has become visually boring. */
			if ((xmax - xmin < Lx * DBL_To_PRM(.2)) && (ymax - ymin < Ly * DBL_To_PRM(.2))) {
				A->Speed *= 1.25;
			} else if (pixelCount>0 && pixelCount<A->Width*A->Height/1000) {
				A->Speed *= 1.25;  /* A->Count = 1000; */
			} else {
				A->Speed = 4; /* reset to normal/default */
			}
			if (A->Speed > 32)
				A->Speed = 32;
			A->Count += A->Speed;
			if (A->Count >= 1000) {
				for (i = MAX_PRM - 1; i >= 0; --i)
					A->Prm1[i] = A->Prm2[i];
				Random_Prm(A->Prm2);
				A->Count = 0;
			}
		#endif
	} else {
	#endif
	for (n = 0; n != A->Max_Pt; ++n) {
		int x1, y1;
		(*Iterate) (A, x, y, &xo, &yo);
		x1 = (int) (Lx * x) + cx;
		y1 = (int) (Ly * y) + cy;
		if (pointSize == 1) {
			XPoint *Buf = &((XPoint *)A->Buffer2)[n];
			Buf->x = x1;
			Buf->y = y1;
		} else {
			XRectangle *Buf = &((XRectangle *)A->Buffer2)[n];
			/* Position matches bloom in accumulator mode. */
			Buf->x = x1 - pointSize + 1;
			Buf->y = y1;
			Buf->width = pointSize;
			Buf->height = pointSize;
		}

		if (x1 > xmax)
			xmax = x1;
		if (x1 < xmin)
			xmin = x1;
		if (y1 > ymax)
			ymax = y1;
		if (y1 < ymin)
			ymin = y1;

		A->Cur_Pt++;
		/* (void) fprintf( stderr, "X,Y: %d %d    ", Buf->x, Buf->y ); */
		x = xo + NRAND(8) - 4;
		y = yo + NRAND(8) - 4;
	}

	XSetForeground(display, gc, MI_BLACK_PIXEL(mi));

	if (A->dbuf != None) {		/* jwz */
		XSetForeground(display, A->dbuf_gc, 0);
/* XDrawPoints(display, A->dbuf, A->dbuf_gc, A->Buffer1,
  Cur_Pt,CoordModeOrigin); */
		XFillRectangle(display, A->dbuf, A->dbuf_gc, 0, 0, A->Width, A->Height);
	} else {
		draw_points(display, window, gc, A->Buffer1, Cur_Pt);
	}

	if (MI_NPIXELS(mi) <= 2)
		XSetForeground(display, gc, MI_WHITE_PIXEL(mi));
	else
		XSetForeground(display, gc, MI_PIXEL(mi, A->Col % MI_NPIXELS(mi)));

	if (A->dbuf != None) {
		XSetForeground(display, A->dbuf_gc, 1);
		draw_points(display, A->dbuf, A->dbuf_gc, A->Buffer2, A->Cur_Pt);
		XCopyPlane(display, A->dbuf, window, gc, 0, 0, A->Width, A->Height, 0, 0, 1);
	} else
		draw_points(display, window, gc, A->Buffer2, A->Cur_Pt);

	#ifdef useAccumulator
	}
	#endif

	Buf = A->Buffer1;
	A->Buffer1 = A->Buffer2;
	A->Buffer2 = Buf;

	if ((xmax - xmin < Lx * DBL_To_PRM(.2)) && (ymax - ymin < Ly * DBL_To_PRM(.2)))
		A->Count += 4 * A->Speed;
	else
		A->Count += A->Speed;
	if (A->Count >= 1000) {
		for (i = MAX_PRM - 1; i >= 0; --i)
			A->Prm1[i] = A->Prm2[i];
		Random_Prm(A->Prm2);
		A->Count = 0;
	}
	A->Col++;
#ifdef STANDALONE
    mi->recursion_depth = A->Count;
#endif
}


/***************************************************************/

ENTRYPOINT void
init_strange(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
#ifndef NO_DBUF
	GC          gc = MI_GC(mi);
#endif
	ATTRACTOR  *Attractor;
	size_t      pointStructSize =
		pointSize == 1 ? sizeof (XPoint) : sizeof (XRectangle);

	if (curve <= 0) curve = 10;

	MI_INIT (mi, Root);
	Attractor = &Root[MI_SCREEN(mi)];

	if (Attractor->Fold == NULL) {
		int         i;

		if ((Attractor->Fold = (PRM *) calloc(UNIT2 + 1,
				sizeof (PRM))) == NULL) {
			free_strange(mi);
			return;
		}
		for (i = 0; i <= UNIT2; ++i) {
			DBL         x;

			/* x = ( DBL )(i)/UNIT2; */
			/* x = sin( M_PI/2.0*x ); */
			/* x = sqrt( x ); */
			/* x = x*x; */
			/* x = x*(1.0-x)*4.0; */
			x = (DBL) (i) / UNIT;
			x = sin(x);
			Attractor->Fold[i] = DBL_To_PRM(x);
		}
	}

	Attractor->Max_Pt = points;

	if (Attractor->Buffer1 == NULL)
		if ((Attractor->Buffer1 = calloc(Attractor->Max_Pt,
				pointStructSize)) == NULL) {
			free_strange(mi);
			return;
		}
	if (Attractor->Buffer2 == NULL)
		if ((Attractor->Buffer2 = calloc(Attractor->Max_Pt,
				pointStructSize)) == NULL) {
			free_strange(mi);
			return;
		}

	Attractor->Width = MI_WIDTH(mi);
	Attractor->Height = MI_HEIGHT(mi);
	Attractor->Cur_Pt = 0;
	Attractor->Count = 0;
	Attractor->Col = NRAND(MI_NPIXELS(mi));
	Attractor->Speed = 4;

	Attractor->Iterate = Funcs[NRAND(2)];
	if (curve < 10) /* Avoid boring Iterate_X2. */
		Attractor->Iterate = Iterate_X3;

	Random_Prm(Attractor->Prm1);
	Random_Prm(Attractor->Prm2);
#ifndef NO_DBUF
	if (Attractor->dbuf != None)
		XFreePixmap(display, Attractor->dbuf);
	#ifdef useAccumulator
	#define A Attractor
	if (useAccumulator)
	{
		Attractor->dbuf = None;
	}
	else
	#undef A
	#endif
	{
		Attractor->dbuf = XCreatePixmap (display, MI_WINDOW(mi),
			Attractor->Width, Attractor->Height,
			/* useAccumulator ? MI_DEPTH(mi) : */ 1);
	}
	/* Allocation checked */
	if (Attractor->dbuf != None) {
		XGCValues   gcv;

		gcv.foreground = 0;
		gcv.background = 0;
#ifndef HAVE_JWXYZ
		gcv.graphics_exposures = False;
#endif /* HAVE_JWXYZ */
		gcv.function = GXcopy;

		if (Attractor->dbuf_gc != None)
			XFreeGC(display, Attractor->dbuf_gc);

		if ((Attractor->dbuf_gc = XCreateGC(display, Attractor->dbuf,
#ifndef HAVE_JWXYZ
				GCGraphicsExposures |
#endif /* HAVE_JWXYZ */
                               GCFunction | GCForeground | GCBackground,
				&gcv)) == None) {
			XFreePixmap(display, Attractor->dbuf);
			Attractor->dbuf = None;
		} else {
			XFillRectangle(display, Attractor->dbuf, Attractor->dbuf_gc,
				0, 0, Attractor->Width, Attractor->Height);
			XSetBackground(display, gc, MI_BLACK_PIXEL(mi));
			XSetFunction(display, gc, GXcopy);
		}
	}
#endif


#ifdef useAccumulator
	#define A Attractor
	if (useAccumulator) {
		static const struct threadpool_class threadClass = {
			sizeof(THREAD),
			thread_create,
			thread_destroy
		};
		Screen *screen = MI_SCREENPTR(mi);
		int i;
		unsigned maxThreads, threadCount;
		unsigned bpp = visual_pixmap_depth (screen, MI_VISUAL(mi));
		size_t threadAlign1 = 8 * thread_memory_alignment(display) - 1;
		if (A->cols) {
			if (A->visualClass != TrueColor && A->numCols > 2)
				XFreeColors (display, MI_COLORMAP(mi), A->cols, A->numCols, 0);
			free (A->cols);
		}
		if (MI_NPIXELS(mi) <= 2) {
			A->numCols = 2;
			A->visualClass = StaticColor;
		} else {
			A->numCols = DEF_NUM_COLS;
			A->visualClass = visual_class(screen, MI_VISUAL(mi));
		}

		A->cols = calloc (A->numCols,sizeof(*A->cols));
		if (!A->cols) {
			free_strange(mi);
			return;
		}

		if (A->visualClass == TrueColor) {
			/* Rebuilds ramp every frame. No need for XAllocColor. */
			/* TODO: This could also include PseudoColor. */
			visual_rgb_masks (screen, MI_VISUAL(mi),
				&A->rMask, &A->gMask, &A->bMask);
			A->rShift = 31 - i_log2 (A->rMask);
			A->gShift = 31 - i_log2 (A->gMask);
			A->bShift = 31 - i_log2 (A->bMask);

			free (A->palette);
			A->palette = malloc(MI_NPIXELS(mi) * sizeof(XColor));
			if (!A->palette) {
				free_strange (mi);
				return;
			}

			for (i=0;i<MI_NPIXELS(mi);i++)
				A->palette[i].pixel = MI_PIXEL(mi,i);

			XQueryColors (display, MI_COLORMAP(mi), A->palette, MI_NPIXELS(mi));
		} else if (A->numCols == 2) {
			A->cols[0] = MI_BLACK_PIXEL (mi);
			A->cols[1] = MI_WHITE_PIXEL (mi);
		} else {
			/* No changing colors, unfortunately. */
			XColor color;

			color.pixel = MI_PIXEL(mi,NRAND(MI_NPIXELS(mi)));
			XQueryColor (display, MI_COLORMAP(mi), &color);

			for (;;) {
				for (i=0;i<A->numCols;i++) {
					XColor out_color;
					ramp_color (&color, &out_color, i, A->numCols);
					if (!XAllocColor (display, MI_COLORMAP(mi), &out_color))
						break;
					A->cols[i] = out_color.pixel;
					/*
					if (!XAllocColor(MI_DISPLAY(mi), cmap, &cols[i])) {
					if (!XAllocColor(display, cmap, &cols[i])) {
						cols[i].pixel = WhitePixel (display, DefaultScreen (display));
						cols[i].red = cols[i].green = cols[i].blue = 0xFFFF;
					}
					*/
				}

				if (i==A->numCols)
					break;

				XFreeColors (display, MI_COLORMAP(mi), A->cols, i, 0);
				A->numCols = A->numCols * 11 / 12;
				if (A->numCols < 2) {
					A->numCols = 0;
					free_strange (mi);
					abort();
					return;
				}
			}
		}

		/* Add slack for horizontal blur, then round up to the platform's SIMD
		 * alignment.
		 */
		A->alignedWidth =
			(((A->Width + pointSize) * sizeof(PIXEL0) + (__BIGGEST_ALIGNMENT__ - 1)) &
				~(__BIGGEST_ALIGNMENT__ - 1)) / sizeof(PIXEL0);

		if (A->accImage)
			destroy_xshm_image (display, A->accImage, &A->shmInfo);
		A->accImage = create_xshm_image(display, MI_VISUAL(mi),
			MI_DEPTH(mi), ZPixmap, &A->shmInfo,
			((A->alignedWidth * bpp + threadAlign1) & ~threadAlign1) / bpp,
			A->Height);

		A->blurFac = (PIXEL0)(65536 * (motionBlur - 1) / (motionBlur + 1));
		A->colorFac = 2 / (motionBlur + 1);

		/* Don't overdose on threads. */
		threadCount = hardware_concurrency (display);
		maxThreads = A->Height / (pointSize * 4);
		if (maxThreads < 1)
			maxThreads = 1;
		if (threadCount > maxThreads)
			threadCount = maxThreads;

		if (A->threads)
			free (A->threads);
		A->threads = malloc (threadCount * sizeof(*A->threads));
		if (!A->threads) {
			free_strange (mi);
			return;
		}

		if (A->pool.count)
			threadpool_destroy (&A->pool);
		if (threadpool_create (&A->pool, &threadClass, display, threadCount)) {
			A->pool.count = 0;
			free_strange (mi);
			return;
		}
	}
	#undef A
#endif
	MI_CLEARWINDOW(mi);

	/* Do not want any exposure events from XCopyPlane */
	XSetGraphicsExposures(display, MI_GC(mi), False);
}

/***************************************************************/

#ifdef STANDALONE
XSCREENSAVER_MODULE ("Strange", strange)
#endif

#endif /* MODE_strange */