From http://www.jwz.org/xscreensaver/xscreensaver-5.18.tar.gz
[xscreensaver] / hacks / apollonian.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* apollonian --- Apollonian Circles */
3
4 #if 0
5 static const char sccsid[] = "@(#)apollonian.c  5.02 2001/07/01 xlockmore";
6 #endif
7
8 /*-
9  * Copyright (c) 2000, 2001 by Allan R. Wilks <allan@research.att.com>.
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  * radius r = 1 / c (curvature)
24  *
25  * Descartes Circle Theorem: (a, b, c, d are curvatures of tangential circles)
26  * Let a, b, c, d be the curvatures of for mutually (externally) tangent
27  * circles in the plane.  Then
28  * a^2 + b^2 + c^2 + d^2 = (a + b + c + d)^2 / 2
29  *
30  * Complex Descartes Theorem:  If the oriented curvatues and (complex) centers
31  * of an oriented Descrates configuration in the plane are a, b, c, d and
32  * w, x, y, z respectively, then
33  * a^2*w^2 + b^2*x^2 + c^2*y^2 + d^2*z^2 = (aw + bx + cy + dz)^2 / 2
34  * In addition these quantities satisfy
35  * a^2*w + b^2*x + c^2*y + d^2*z = (aw + bx + cy + dz)(a + b + c + d) /  2
36  *
37  * Enumerate root integer Descartes quadruples (a,b,c,d) satisfying the
38  * Descartes condition:
39  *      2(a^2+b^2+c^2+d^2) = (a+b+c+d)^2
40  * i.e., quadruples for which no application of the "pollinate" operator
41  *      z <- 2(a+b+c+d) - 3*z,
42  * where z is in {a,b,c,d}, gives a quad of strictly smaller sum.  This
43  * is equivalent to the condition:
44  *      sum(a,b,c,d) >= 2*max(a,b,c,d)
45  * which, because of the Descartes condition, is equivalent to
46  *      sum(a^2,b^2,c^2,d^2) >= 2*max(a,b,c,d)^2
47  *
48  *
49  * Todo:
50  * Add a small font
51  *
52  * Revision History:
53  * 25-Jun-2001: Converted from C and Postscript code by David Bagley 
54  *              Original code by Allan R. Wilks <allan@research.att.com>.
55  *
56  * From Circle Math Science News April 21, 2001 VOL. 254-255
57  * http://www.sciencenews.org/20010421/toc.asp
58  * Apollonian Circle Packings Assorted papers from Ronald L Graham,
59  * Jeffrey Lagarias, Colin Mallows, Allan Wilks, Catherine Yan
60  *      http://front.math.ucdavis.edu/math.NT/0009113
61  *      http://front.math.ucdavis.edu/math.MG/0101066
62  *      http://front.math.ucdavis.edu/math.MG/0010298
63  *      http://front.math.ucdavis.edu/math.MG/0010302
64  *      http://front.math.ucdavis.edu/math.MG/0010324
65  */
66
67 #ifdef STANDALONE
68 # define MODE_apollonian
69 # define DEFAULTS       "*delay:   1000000 \n" \
70                                         "*count:   64      \n" \
71                                         "*cycles:  20      \n" \
72                                         "*ncolors: 64      \n" \
73                                         "*fpsTop: true     \n" \
74                                         "*fpsSolid: true   \n" \
75
76 # define refresh_apollonian 0
77 # define apollonian_handle_event 0
78 # include "xlockmore.h"         /* in xscreensaver distribution */
79 # include "erase.h"
80 #else /* STANDALONE */
81 # include "xlock.h"             /* in xlockmore distribution */
82 #endif /* STANDALONE */
83
84 #ifdef MODE_apollonian
85
86 #define DEF_ALTGEOM  "True"
87 #define DEF_LABEL  "True"
88
89 static Bool altgeom;
90 static Bool label;
91
92 static XrmOptionDescRec opts[] =
93 {
94         {"-altgeom", ".apollonian.altgeom", XrmoptionNoArg, "on"},
95         {"+altgeom", ".apollonian.altgeom", XrmoptionNoArg, "off"},
96         {"-label", ".apollonian.label", XrmoptionNoArg, "on"},
97         {"+label", ".apollonian.label", XrmoptionNoArg, "off"},
98 };
99 static argtype vars[] =
100 {
101         {&altgeom, "altgeom", "AltGeom", DEF_ALTGEOM, t_Bool},
102         {&label,   "label",   "Label",   DEF_LABEL,   t_Bool},
103 };
104 static OptionStruct desc[] =
105 {
106         {"-/+altgeom", "turn on/off alternate geometries (off euclidean space, on includes spherical and hyperbolic)"},
107         {"-/+label", "turn on/off alternate space and number labeling"},
108 };
109
110 ENTRYPOINT ModeSpecOpt apollonian_opts =
111 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
112
113 #ifdef DOFONT
114 extern XFontStruct *getFont(Display * display);
115 #endif
116
117 #ifdef USE_MODULES
118 ModStruct   apollonian_description =
119 {"apollonian", "init_apollonian", "draw_apollonian", "release_apollonian",
120  "init_apollonian", "init_apollonian", (char *) NULL, &apollonian_opts,
121  1000000, 64, 20, 1, 64, 1.0, "",
122  "Shows Apollonian Circles", 0, NULL};
123
124 #endif
125
126 typedef struct {
127         int a, b, c, d;
128 } apollonian_quadruple;
129
130 typedef struct {
131         double e;       /* euclidean bend */
132         double s;       /* spherical bend */
133         double h;       /* hyperbolic bend */
134         double x, y;    /* euclidean bend times euclidean position */
135 } circle;
136 enum space {
137   euclidean = 0, spherical, hyperbolic
138 };
139
140 static const char * space_string[] = {
141   "euclidean",
142   "spherical",
143   "hyperbolic"
144 };
145
146 /*
147 Generate Apollonian packing starting with a quadruple of circles.
148 The four input lines each contain the 5-tuple (e,s,h,x,y) representing
149 the circle with radius 1/e and center (x/e,y/e).  The s and h is propagated
150 like e, x and y, but can differ from e so as to represent different
151 geometries, spherical and hyperbolic, respectively.  The "standard" picture,
152 for example (-1, 2, 2, 3), can be labeled for the three geometries.
153 Origins of circles z1, z2, z3, z4
154 a * z1 = 0
155 b * z2 = (a+b)/a
156 c * z3 = (q123 + a * i)^2/(a*(a+b)) where q123 = sqrt(a*b+a*c+b*c)
157 d * z4 = (q124 + a * i)^2/(a*(a+b)) where q124 = q123 - a - b
158 If (e,x,y) represents the Euclidean circle (1/e,x/e,y/e) (so that e is
159 the label in the standard picture) then the "spherical label" is
160 (e^2+x^2+y^2-1)/(2*e) (an integer!)  and the "hyperbolic label", is 
161 calulated by h + s = e.
162 */
163 static circle examples[][4] = {
164 { /* double semi-bounded */
165         { 0, 0, 0,   0,  1},
166         { 0, 0, 0,   0, -1},
167         { 1, 1, 1,  -1,  0},
168         { 1, 1, 1,   1,  0}
169 },
170 #if 0
171 { /* standard */
172         {-1, 0, -1,   0,  0},
173         { 2, 1,  1,   1,  0},
174         { 2, 1,  1,  -1,  0},
175         { 3, 2,  1,   0,  2}
176 },
177 { /* next simplest */
178         {-2, -1, -1,   0.0,  0},
179         { 3,  2,  1,   0.5,  0},
180         { 6,  3,  3,  -2.0,  0},
181         { 7,  4,  3,  -1.5,  2}
182 },
183 { /*  */
184         {-3, -2, -1,         0.0,  0},
185         { 4,  3,  1,   1.0 / 3.0,  0},
186         {12,  7,  5,        -3.0,  0},
187         {13,  8,  5,  -8.0 / 3.0,  2}
188 },
189 { /* Mickey */
190         {-3, -2, -1,         0.0,  0},
191         { 5,  4,  1,   2.0 / 3.0,  0},
192         { 8,  5,  3,  -4.0 / 3.0, -1},
193         { 8,  5,  3,  -4.0 / 3.0,  1}
194 },
195 { /*  */
196         {-4, -3, -1,   0.00,  0},
197         { 5,  4,  1,   0.25,  0},
198         {20, 13,  7,  -4.00,  0},
199         {21, 14,  7,  -3.75,  2}
200 },
201 { /* Mickey2 */
202         {-4, -2, -2,    0.0,  0},
203         { 8,  4,  4,    1.0,  0},
204         { 9,  5,  4,  -0.75, -1},
205         { 9,  5,  4,  -0.75,  1}
206 },
207 { /* Mickey3 */
208         {-5,  -4, -1,   0.0,  0},
209         { 7,   6,  1,   0.4,  0},
210         {18,  13,  5,  -2.4, -1},
211         {18,  13,  5,  -2.4,  1}
212 },
213 { /*  */
214         {-6, -5, -1,          0.0,  0},
215         { 7,  6,  1,    1.0 / 6.0,  0},
216         {42, 31, 11,         -6.0,  0},
217         {43, 32, 11,  -35.0 / 6.0,  2}
218 },
219 { /*  */
220         {-6, -3, -3,         0.0,  0},
221         {10,  5,  5,   2.0 / 3.0,  0},
222         {15,  8,  7,        -1.5,  0},
223         {19, 10,  9,  -5.0 / 6.0,  2}
224 },
225 { /* asymmetric */
226         {-6, -5, -1,           0.0,  0.0},
227         {11, 10,  1,     5.0 / 6.0,  0.0},
228         {14, 11,  3,  -16.0 / 15.0, -0.8},
229         {15, 12,  3,          -0.9,  1.2} 
230 },
231 #endif
232 /* Non integer stuff */
233 #define DELTA 2.154700538 /* ((3+2*sqrt(3))/3) */
234 { /* 3 fold symmetric bounded (x, y calculated later) */
235         {   -1,    -1,    -1,   0.0,  0.0},
236         {DELTA, DELTA, DELTA,   1.0,  0.0},
237         {DELTA, DELTA, DELTA,   1.0, -1.0},
238         {DELTA, DELTA, DELTA,  -1.0,  1.0} 
239 },
240 { /* semi-bounded (x, y calculated later) */
241 #define ALPHA 2.618033989 /* ((3+sqrt(5))/2) */
242         {              1.0,               1.0,               1.0,   0,  0},
243         {              0.0,               0.0,               0.0,   0, -1},
244         {1.0/(ALPHA*ALPHA), 1.0/(ALPHA*ALPHA), 1.0/(ALPHA*ALPHA),  -1,  0},
245         {        1.0/ALPHA,         1.0/ALPHA,         1.0/ALPHA,  -1,  0}
246 },
247 { /* unbounded (x, y calculated later) */
248 /* #define PHI 1.618033989 *//* ((1+sqrt(5))/2) */
249 #define BETA 2.890053638 /* (PHI+sqrt(PHI)) */
250         {                 1.0,                  1.0,                  1.0,  0,  0},
251         {1.0/(BETA*BETA*BETA), 1.0/(BETA*BETA*BETA), 1.0/(BETA*BETA*BETA),  1,  0},
252         {     1.0/(BETA*BETA),      1.0/(BETA*BETA),      1.0/(BETA*BETA),  1,  0},
253         {            1.0/BETA,             1.0/BETA,             1.0/BETA,  1,  0}
254 }
255 };
256
257 #define PREDEF_CIRCLE_GAMES  (sizeof (examples) / (4 * sizeof (circle)))
258
259 #if 0
260 Euclidean
261 0, 0, 1, 1
262 -1, 2, 2, 3
263 -2, 3, 6, 7
264 -3, 5, 8, 8
265 -4, 8, 9, 9
266 -3, 4, 12, 13
267 -6, 11, 14, 15
268  -5, 7, 18, 18
269  -6, 10, 15, 19
270  -7, 12, 17, 20
271  -4, 5, 20, 21
272  -9, 18, 19, 22
273  -8, 13, 21, 24
274 Spherical
275 0, 1, 1, 2
276  -1, 2, 3, 4
277  -2, 4, 5, 5
278  -2, 3, 7, 8
279 Hyperbolic
280 -1, 1, 1, 1
281  0, 0, 1, 3
282  -2, 3, 5, 6
283  -3, 6, 6, 7
284 #endif
285
286 typedef struct {
287         int         size;
288         XPoint      offset;
289         int         geometry;
290         circle      c1, c2, c3, c4;
291         int         color_offset;
292         int         count;
293         Bool        label, altgeom;
294         apollonian_quadruple  *quad;
295 #ifdef DOFONT
296         XFontStruct *font;
297 #endif
298         int         time;
299         int         game;
300 #ifdef STANDALONE
301   eraser_state *eraser;
302 #endif
303 } apollonianstruct;
304
305 static apollonianstruct *apollonians = (apollonianstruct *) NULL;
306
307 #define FONT_HEIGHT 19
308 #define FONT_WIDTH 15
309 #define FONT_LENGTH 20
310 #define MAX_CHAR 10
311 #define K       2.15470053837925152902  /* 1+2/sqrt(3) */
312 #define MAXBEND 100 /* Do not want configurable by user since it will take too
313         much time if increased. */
314
315 static int
316 gcd(int a, int b)
317 {
318         int r;
319
320         while (b) {
321                 r = a % b;
322                 a = b;
323                 b = r;
324         }
325         return a;
326 }
327
328 static int
329 isqrt(int n)
330 {
331         int y;
332
333         if (n < 0)
334                 return -1;
335         y = (int) (sqrt((double) n) + 0.5);
336         return ((n == y*y) ? y : -1);
337 }
338
339 static void
340 dquad(int n, apollonian_quadruple *quad)
341 {
342         int a, b, c, d;
343         int counter = 0, B, C;
344         
345         for (a = 0; a < MAXBEND; a++) {
346                 B = (int) (K * a);
347                 for (b = a + 1; b <= B; b++) {
348                         C = (int) (((a + b) * (a + b)) / (4.0 * (b - a)));
349                         for (c = b; c <= C; c++) {
350                                 d = isqrt(b*c-a*(b+c));
351                                 if (d >= 0 && (gcd(a,gcd(b,c)) <= 1)) {
352                                         quad[counter].a = -a;
353                                         quad[counter].b = b;
354                                         quad[counter].c = c;
355                                         quad[counter].d = -a+b+c-2*d;
356                                         if (++counter >= n) {
357                                                 return;
358                                         }
359                                 }
360                         }
361                 }
362         }
363         (void) printf("found only %d below maximum bend of %d\n",
364                 counter, MAXBEND);
365         for (; counter < n; counter++) {
366                 quad[counter].a = -1; 
367                 quad[counter].b = 2;
368                 quad[counter].c = 2;
369                 quad[counter].d = 3;
370         }
371         return;
372 }
373
374 /*
375  * Given a Descartes quadruple of bends (a,b,c,d), with a<0, find a
376  * quadruple of circles, represented by (bend,bend*x,bend*y), such
377  * that the circles have the given bends and the bends times the
378  * centers are integers.
379  *
380  * This just performs an exaustive search, assuming that the outer
381  * circle has center in the unit square.
382  *
383  * It is always sufficient to look in {(x,y):0<=y<=x<=1/2} for the
384  * center of the outer circle, but this may not lead to a packing
385  * that can be labelled with integer spherical and hyperbolic labels.
386  * To effect the smaller search, replace FOR(a) with
387  *
388  *      for (pa = ea/2; pa <= 0; pa++) for (qa = pa; qa <= 0; qa++)
389  */
390
391 #define For(v,l,h)      for (v = l; v <= h; v++)
392 #define FOR(z)          For(p##z,lop##z,hip##z) For(q##z,loq##z,hiq##z)
393 #define H(z)            ((e##z*e##z+p##z*p##z+q##z*q##z)%2)
394 #define UNIT(z)         ((abs(e##z)-1)*(abs(e##z)-1) >= p##z*p##z+q##z*q##z)
395 #define T(z,w)          is_tangent(e##z,p##z,q##z,e##w,p##w,q##w)
396 #define LO(r,z)         lo##r##z = iceil(e##z*(r##a+1),ea)-1
397 #define HI(r,z)         hi##r##z = iflor(e##z*(r##a-1),ea)-1
398 #define B(z)            LO(p,z); HI(p,z); LO(q,z); HI(q,z)
399
400 static int
401 is_quad(int a, int b, int c, int d)
402 {
403         int s;
404
405         s = a+b+c+d;
406         return 2*(a*a+b*b+c*c+d*d) == s*s;
407 }
408
409 static Bool
410 is_tangent(int e1, int p1, int q1, int e2, int p2, int q2)
411 {
412         int dx, dy, s;
413
414         dx = p1*e2 - p2*e1;
415         dy = q1*e2 - q2*e1;
416         s = e1 + e2;
417         return dx*dx + dy*dy == s*s;
418 }
419
420 static int
421 iflor(int a, int b)
422 {
423         int q;
424
425         if (b == 0) {
426                 (void) printf("iflor: b = 0\n");
427                 return 0;
428         }
429         if (a%b == 0)
430                 return a/b;
431         q = abs(a)/abs(b);
432         return ((a<0)^(b<0)) ? -q-1 : q;
433 }
434
435 static int
436 iceil(int a, int b)
437 {
438         int q;
439
440         if (b == 0) {
441                 (void) printf("iceil: b = 0\n");
442                 return 0;
443         }
444         if (a%b == 0)
445                 return a/b;
446         q = abs(a)/abs(b);
447         return ((a<0)^(b<0)) ? -q : 1+q;
448 }
449
450 static double
451 geom(int geometry, int e, int p, int q)
452 {
453         int g = (geometry == spherical) ? -1 :
454                 (geometry == hyperbolic) ? 1 : 0;
455
456         if (g)
457                 return (e*e + (1.0 - p*p - q*q) * g) / (2.0*e);
458         (void) printf("geom: g = 0\n");
459         return e;
460 }
461
462 static void
463 cquad(circle *c1, circle *c2, circle *c3, circle *c4)
464 {
465         int ea, eb, ec, ed;
466         int pa, pb, pc, pd;
467         int qa, qb, qc, qd;
468         int lopa, lopb, lopc, lopd;
469         int hipa, hipb, hipc, hipd;
470         int loqa, loqb, loqc, loqd;
471         int hiqa, hiqb, hiqc, hiqd;
472
473         ea = (int) c1->e;
474         eb = (int) c2->e;
475         ec = (int) c3->e;
476         ed = (int) c4->e;
477         if (ea >= 0)
478                 (void) printf("ea = %d\n", ea);
479         if (!is_quad(ea,eb,ec,ed))
480                 (void) printf("Error not quad %d %d %d %d\n", ea, eb, ec, ed);
481         lopa = loqa = ea;
482         hipa = hiqa = 0;
483         FOR(a) {
484                 B(b); B(c); B(d);
485                 if (H(a) && UNIT(a)) FOR(b) {
486                         if (H(b) && T(a,b)) FOR(c) {
487                                 if (H(c) && T(a,c) && T(b,c)) FOR(d) {
488                                   if (H(d) && T(a,d) && T(b,d) && T(c,d)) {
489                                     c1->s = geom(spherical, ea, pa, qa);
490                                     c1->h = geom(hyperbolic, ea, pa, qa);
491                                     c2->s = geom(spherical, eb, pb, qb);
492                                     c2->h = geom(hyperbolic, eb, pb, qb);
493                                     c3->s = geom(spherical, ec, pc, qc);
494                                     c3->h = geom(hyperbolic, ec, pc, qc);
495                                     c4->s = geom(spherical, ed, pd, qd);
496                                     c4->h = geom(hyperbolic, ed, pd, qd);
497                                   }
498                                 }
499                         }
500                 }
501         }
502 }
503
504 static void
505 p(ModeInfo *mi, circle c)
506 {
507         apollonianstruct *cp = &apollonians[MI_SCREEN(mi)];
508         char string[10];
509         double g, e;
510         int g_width;
511
512 #ifdef DEBUG
513         (void) printf("c.e=%g c.s=%g c.h=%g  c.x=%g c.y=%g\n",
514                 c.e, c.s, c.h, c.x, c.y);
515 #endif
516         g = (cp->geometry == spherical) ? c.s : (cp->geometry == hyperbolic) ?
517                 c.h : c.e;
518         if (c.e < 0.0) {
519                 if (g < 0.0)
520                         g = -g;
521                 if (MI_NPIXELS(mi) <= 2)
522                         XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
523                                 MI_WHITE_PIXEL(mi));
524                 else
525                         XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
526                                 MI_PIXEL(mi, ((int) ((g + cp->color_offset) *
527                                         g)) % MI_NPIXELS(mi)));
528                 XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
529                         ((int) (cp->size * (-cp->c1.e) * (c.x - 1.0) /
530                                 (-2.0 * c.e) + cp->size / 2.0 + cp->offset.x)),
531                         ((int) (cp->size * (-cp->c1.e) * (c.y - 1.0) /
532                                 (-2.0 * c.e) + cp->size / 2.0 + cp->offset.y)),
533                         (int) (cp->c1.e * cp->size / c.e),
534                         (int) (cp->c1.e * cp->size / c.e), 0, 23040);
535                 if (!cp->label) {
536 #ifdef DEBUG
537                         (void) printf("%g\n", -g);
538 #endif
539                         return;
540                 }
541                 (void) sprintf(string, "%g", (g == 0.0) ? 0 : -g);
542                 if (cp->size >= 10 * FONT_WIDTH) {
543                   /* hard code these to corners */
544                   XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
545                         ((int) (cp->size * c.x / (2.0 * c.e))) + cp->offset.x,
546                         ((int) (cp->size * c.y / (2.0 * c.e))) + FONT_HEIGHT,
547                         string, (g == 0.0) ? 1 : ((g < 10.0) ? 2 :
548                                 ((g < 100.0) ? 3 : 4)));
549                 }
550                 if (cp->altgeom && MI_HEIGHT(mi) >= 30 * FONT_WIDTH) {
551                   XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
552                         ((int) (cp->size * c.x / (2.0 * c.e) + cp->offset.x)),
553                         ((int) (cp->size * c.y / (2.0 * c.e) + MI_HEIGHT(mi) -
554                         FONT_HEIGHT / 2)), (char *) space_string[cp->geometry],
555                         strlen(space_string[cp->geometry]));
556                 }
557                 return;
558         }
559         if (MI_NPIXELS(mi) <= 2)
560                 XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_WHITE_PIXEL(mi));
561         else
562                 XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
563                         MI_PIXEL(mi, ((int) ((g + cp->color_offset) * g)) %
564                                 MI_NPIXELS(mi)));
565         if (c.e == 0.0) {
566                 if (c.x == 0.0 && c.y != 0.0) {
567                         XDrawLine(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
568                                 0, (int) ((c.y + 1.0) * cp->size / 2.0 + cp->offset.y),
569                                 MI_WIDTH(mi),
570                                 (int) ((c.y + 1.0) * cp->size / 2.0 + cp->offset.y));
571                 } else if (c.y == 0.0 && c.x != 0.0) {
572                         XDrawLine(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
573                                 (int) ((c.x + 1.0) * cp->size / 2.0 + cp->offset.x), 0,
574                                 (int) ((c.x + 1.0) * cp->size / 2.0 + cp->offset.x),
575                                 MI_HEIGHT(mi));
576                 }
577                 return;
578         }
579         e = (cp->c1.e >= 0.0) ? 1.0 : -cp->c1.e;
580         XFillArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
581                 ((int) (cp->size * e * (c.x - 1.0) / (2.0 * c.e) +
582                         cp->size / 2.0 + cp->offset.x)),
583                 ((int) (cp->size * e * (c.y - 1.0) / (2.0 * c.e) +
584                         cp->size / 2.0 + cp->offset.y)),
585                 (int) (e * cp->size / c.e), (int) (e * cp->size / c.e),
586                 0, 23040);
587         if (!cp->label) {
588 #ifdef DEBUG
589                 (void) printf("%g\n", g);
590 #endif
591                 return;
592         }
593         if (MI_NPIXELS(mi) <= 2)
594                 XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_BLACK_PIXEL(mi));
595         else
596                 XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
597                         MI_PIXEL(mi, ((int) ((g + cp->color_offset) * g) +
598                                 MI_NPIXELS(mi) / 2) % MI_NPIXELS(mi)));
599         g_width = (g < 10.0) ? 1: ((g < 100.0) ? 2 : 3);
600         if (c.e < e * cp->size / (FONT_LENGTH + 5 * g_width) && g < 1000.0) {
601                 (void) sprintf(string, "%g", g);
602                 XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
603                         ((int) (cp->size * e * c.x / (2.0 * c.e) +
604                                 cp->size / 2.0 + cp->offset.x)) -
605                                 g_width * FONT_WIDTH / 2,
606                         ((int) (cp->size * e * c.y / (2.0 * c.e) +
607                                 cp->size / 2.0 + cp->offset.y)) +
608                                 FONT_HEIGHT / 2,
609                         string, g_width);
610         }
611 }
612
613 #define BIG 7
614 static void
615 f(ModeInfo *mi, circle c1, circle c2, circle c3, circle c4, int depth)
616 {
617         apollonianstruct *cp = &apollonians[MI_SCREEN(mi)];
618         int e = (int) ((cp->c1.e >= 0.0) ? 1.0 : -cp->c1.e);
619         circle c;
620
621         if (depth > mi->recursion_depth) mi->recursion_depth = depth;
622
623         c.e = 2*(c1.e+c2.e+c3.e) - c4.e;
624         c.s = 2*(c1.s+c2.s+c3.s) - c4.s;
625         c.h = 2*(c1.h+c2.h+c3.h) - c4.h;
626         c.x = 2*(c1.x+c2.x+c3.x) - c4.x;
627         c.y = 2*(c1.y+c2.y+c3.y) - c4.y;
628         if (c.e == 0 ||
629             c.e > cp->size * e || c.x / c.e > BIG || c.y / c.e > BIG ||
630             c.x / c.e < -BIG || c.y / c.e < -BIG)
631                 return;
632         p(mi, c);
633         f(mi, c2, c3, c, c1, depth+1);
634         f(mi, c1, c3, c, c2, depth+1);
635         f(mi, c1, c2, c, c3, depth+1);
636 }
637
638 ENTRYPOINT void
639 free_apollonian (Display *display, apollonianstruct *cp)
640 {
641         if (cp->quad != NULL) {
642                 (void) free((void *) cp->quad);
643                 cp->quad = (apollonian_quadruple *) NULL;
644         }
645 #ifdef DOFONT
646         if (cp->gc != None) {
647                 XFreeGC(display, cp->gc);
648                 cp->gc = None;
649         }
650         if (cp->font != None) {
651                 XFreeFont(display, cp->font);
652                 cp->font = None;
653         }
654 #endif
655 }
656
657 #ifndef DEBUG
658 static void
659 randomize_c(int randomize, circle * c)
660 {
661   if (randomize / 2) {
662     double temp;
663
664     temp = c->x;
665     c->x = c->y;
666     c->y = temp;
667   }
668   if (randomize % 2) {
669     c->x = -c->x;
670     c->y = -c->y;
671   }
672 }
673 #endif
674
675 ENTRYPOINT void
676 init_apollonian (ModeInfo * mi)
677 {
678         apollonianstruct *cp;
679         int i;
680
681         if (apollonians == NULL) {
682                 if ((apollonians = (apollonianstruct *) calloc(MI_NUM_SCREENS(mi),
683                                              sizeof (apollonianstruct))) == NULL)
684                         return;
685         }
686         cp = &apollonians[MI_SCREEN(mi)];
687
688         cp->size = MAX(MIN(MI_WIDTH(mi), MI_HEIGHT(mi)) - 1, 1);
689         cp->offset.x = (MI_WIDTH(mi) - cp->size) / 2;
690         cp->offset.y = (MI_HEIGHT(mi) - cp->size) / 2;
691         cp->color_offset = NRAND(MI_NPIXELS(mi));
692
693 #ifdef DOFONT
694         if (cp->font == None) {
695                 if ((cp->font = getFont(MI_DISPLAY(mi))) == None)
696                         return False;
697         }
698 #endif
699         cp->label = label;
700         cp->altgeom = cp->label && altgeom;
701
702         if (cp->quad == NULL) {
703                 cp->count = ABS(MI_COUNT(mi));
704                 if ((cp->quad = (apollonian_quadruple *) malloc(cp->count *
705                         sizeof (apollonian_quadruple))) == NULL) {
706                         return;
707                 }
708                 dquad(cp->count, cp->quad);
709         }
710         cp->game = NRAND(PREDEF_CIRCLE_GAMES + cp->count);
711         cp->geometry = (cp->game && cp->altgeom) ? NRAND(3) : 0;
712
713         if (cp->game < PREDEF_CIRCLE_GAMES) {   
714                 cp->c1 = examples[cp->game][0];
715                 cp->c2 = examples[cp->game][1];
716                 cp->c3 = examples[cp->game][2];
717                 cp->c4 = examples[cp->game][3];
718                 /* do not label non int */
719                 cp->label = cp->label && (cp->c4.e == (int) cp->c4.e);
720         } else { /* uses results of dquad, all int */
721                 i = cp->game - PREDEF_CIRCLE_GAMES;
722                 cp->c1.e = cp->quad[i].a;
723                 cp->c2.e = cp->quad[i].b;
724                 cp->c3.e = cp->quad[i].c;
725                 cp->c4.e = cp->quad[i].d;
726                 if (cp->geometry)
727                         cquad(&(cp->c1), &(cp->c2), &(cp->c3), &(cp->c4));
728         }
729         cp->time = 0;
730 #ifndef STANDALONE
731         MI_CLEARWINDOW(mi);
732 #endif
733         if (cp->game != 0) {
734                 double q123;
735
736                 if (cp->c1.e == 0.0 || cp->c1.e == -cp->c2.e)
737                         return;
738                 cp->c1.x = 0.0;
739                 cp->c1.y = 0.0;
740                 cp->c2.x = -(cp->c1.e + cp->c2.e) / cp->c1.e;
741                 cp->c2.y = 0;
742                 q123 = sqrt(cp->c1.e * cp->c2.e + cp->c1.e * cp->c3.e +
743                         cp->c2.e * cp->c3.e);
744 #ifdef DEBUG
745                 (void) printf("q123 = %g, ", q123);
746 #endif
747                 cp->c3.x = (cp->c1.e * cp->c1.e - q123 * q123) / (cp->c1.e *
748                         (cp->c1.e + cp->c2.e));
749                 cp->c3.y = -2.0 * q123 / (cp->c1.e + cp->c2.e);
750                 q123 = -cp->c1.e - cp->c2.e + q123;
751                 cp->c4.x = (cp->c1.e * cp->c1.e - q123 * q123) / (cp->c1.e *
752                         (cp->c1.e + cp->c2.e));
753                 cp->c4.y = -2.0 * q123 / (cp->c1.e + cp->c2.e);
754 #ifdef DEBUG
755                 (void) printf("q124 = %g\n", q123);
756                 (void) printf("%g %g %g %g %g %g %g %g\n",
757                         cp->c1.x, cp->c1.y, cp->c2.x, cp->c2.y,
758                         cp->c3.x, cp->c3.y, cp->c4.x, cp->c4.y);
759 #endif
760         }
761 #ifndef DEBUG
762         if (LRAND() & 1) {
763                 cp->c3.y = -cp->c3.y;
764                 cp->c4.y = -cp->c4.y;
765         }
766         i = NRAND(4);
767         randomize_c(i, &(cp->c1));
768         randomize_c(i, &(cp->c2));
769         randomize_c(i, &(cp->c3));
770         randomize_c(i, &(cp->c4));
771 #endif 
772
773     mi->recursion_depth = -1;
774 }
775
776 ENTRYPOINT void
777 draw_apollonian (ModeInfo * mi)
778 {
779         apollonianstruct *cp;
780
781         if (apollonians == NULL)
782                 return;
783         cp = &apollonians[MI_SCREEN(mi)];
784
785 #ifdef STANDALONE
786     if (cp->eraser) {
787       cp->eraser = erase_window (MI_DISPLAY(mi), MI_WINDOW(mi), cp->eraser);
788       return;
789     }
790 #endif
791
792         MI_IS_DRAWN(mi) = True;
793
794         if (cp->time < 5) {
795                 switch (cp->time) {
796                 case 0:
797                         p(mi, cp->c1);
798                         p(mi, cp->c2);
799                         p(mi, cp->c3);
800                         p(mi, cp->c4);
801                         break;
802                 case 1:
803                         f(mi, cp->c1, cp->c2, cp->c3, cp->c4, 0);
804                         break;
805                 case 2:
806                         f(mi, cp->c1, cp->c2, cp->c4, cp->c3, 0);
807                         break;
808                 case 3:
809                         f(mi, cp->c1, cp->c3, cp->c4, cp->c2, 0);
810                         break;
811                 case 4:
812                         f(mi, cp->c2, cp->c3, cp->c4, cp->c1, 0);
813                 }
814         }
815         if (++cp->time > MI_CYCLES(mi))
816       {
817 #ifdef STANDALONE
818         cp->eraser = erase_window (MI_DISPLAY(mi), MI_WINDOW(mi), cp->eraser);
819 #endif /* STANDALONE */
820                 init_apollonian(mi);
821       }
822 }
823
824 ENTRYPOINT void
825 reshape_apollonian(ModeInfo * mi, int width, int height)
826 {
827   XClearWindow (MI_DISPLAY (mi), MI_WINDOW(mi));
828   init_apollonian (mi);
829 }
830
831 ENTRYPOINT void
832 release_apollonian (ModeInfo * mi)
833 {
834         if (apollonians != NULL) {
835                 int         screen;
836
837                 for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
838                         free_apollonian(MI_DISPLAY(mi), &apollonians[screen]);
839                 (void) free((void *) apollonians);
840                 apollonians = (apollonianstruct *) NULL;
841         }
842 }
843
844 XSCREENSAVER_MODULE ("Apollonian", apollonian)
845
846 #endif /* MODE_apollonian */