From http://www.jwz.org/xscreensaver/xscreensaver-5.22.tar.gz
[xscreensaver] / hacks / abstractile.c
1 /*
2  * Copyright (c) 2004-2009 Steve Sundstrom
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or
10  * implied warranty.
11  */
12
13 #include "screenhack.h"
14 #include "colors.h"
15 #include "hsv.h"
16 #include <stdio.h>
17 #include <math.h>
18 #include <sys/time.h>
19 /*#include <sys/utsname.h>*/
20
21 #define DEBUGFILE       "/tmp/abstractile.dbg"
22
23 #define MODE_CREATE             0   /* init, create, then finish sleep */
24 #define MODE_ERASE              1   /* erase, then reset colors */
25 #define MODE_DRAW               2
26
27 #define DIR_NONE                0
28 #define DIR_UP                  1
29 #define DIR_DOWN                2
30 #define DIR_LEFT                3
31 #define DIR_RIGHT               4
32
33 #define LINE_FORCE              1
34 #define LINE_NEW                2
35 #define LINE_BRIN               3
36 #define LINE_BROUT              4
37
38 #define PT_UL                   0
39 #define PT_MP                   1
40 #define PT_LR                   2
41 #define PT_NL                   3
42
43 #define D3D_NONE                0
44 #define D3D_BLOCK               1
45 #define D3D_NEON                2
46 #define D3D_TILED               3
47
48 #define TILE_RANDOM             0
49 #define TILE_FLAT               1
50 #define TILE_THIN               2
51 #define TILE_OUTLINE            3
52 #define TILE_BLOCK              4
53 #define TILE_NEON               5
54 #define TILE_TILED              6
55
56 #define BASECOLORS              30
57 #define SHADES                  12
58 #define MAXCOLORS               40
59 #define LAYERS                  4
60 #define PATTERNS                40
61 #define SHAPES                  18
62 #define DRAWORDERS              40
63 #define COLORMAPS               20
64 #define WAVES                   6
65 #define STRETCHES               8
66
67 struct lineStruct {
68     unsigned int x, y, len, obj, color, ndol;
69     int deo;
70     Bool hv;
71 };
72
73 struct gridStruct {
74     unsigned int line, hl, hr, vu, vd, dhl, dhr, dvu, dvd;
75 };
76
77 /* basically the same as global variables, but used to keep them in a bucket
78    and pass them around easier like the original C++ implementation */
79 struct state {
80   /* window values */
81   Display *display;
82   Window window;
83   XWindowAttributes xgwa;
84   GC fgc, bgc;
85   XColor colors[255];
86
87   /* memory values */
88   struct lineStruct *dline, *eline;
89   struct gridStruct *grid;
90   unsigned int *zlist, *fdol;
91   Bool *odi;
92     /* draw, erase, fill, init, line, object, z indexes */
93   unsigned int di, ei, fi, ii, bi, li, eli, oi, zi;
94   /* size variables */
95   unsigned int gridx, gridy, gridn;                     /* grid size */
96   int lwid, bwid, swid;/* line width, background width, shadow width */
97   int narray, max_wxh;
98   int elwid, elpu, egridx, egridy; /* for now */
99   /* fill variables */
100   int bnratio;                 /* ratio of branch lines to new lines */
101   int maxlen;                              /* maximum length of line */
102   int forcemax;                  /* make line be max possible length */
103   int olen;                           /* open length set by findopen */
104   int bln;          /* blocking line number set by findopen, -1=edge */
105   /* color variables */
106   int ncolors;                        /* number of colors for screen */
107   int shades;
108   int rco[MAXCOLORS];           /* random ordering of colors for deo */
109   int cmap;
110   int layers;
111   Bool newcols;      /* can we create new colormaps with each screen */
112   /* draw variables */
113   int dmap, emap;  /* pattern by which line draw order is determined */
114   int dvar, evar;             /* random number added to .deo to vary */
115   int ddir, edir;      /* draw/erase in forward direction or reverse */
116   int lpu;            /* lines drawn per update used to adjust speed */
117   int d3d;
118   int round;
119   int outline;
120   /* layered draw variables */
121   int pattern[LAYERS], shape[LAYERS], mix[LAYERS];
122   int csw[LAYERS], wsx[LAYERS], wsy[LAYERS], sec[LAYERS];
123   int cs1[LAYERS], cs2[LAYERS], cs3[LAYERS]; int cs4[LAYERS];
124   int wave[LAYERS], waveh[LAYERS], wavel[LAYERS];
125   int rx1[LAYERS], rx2[LAYERS], rx3[LAYERS];
126   int ry1[LAYERS], ry2[LAYERS], ry3[LAYERS];
127   /* misc variables */
128   int mode, sleep, speed, tile, dialog;
129   Bool grid_full, resized;
130   struct timeval time;
131 };
132
133 static int
134 _min(int a, int b)
135 {
136   if (a<=b)
137     return(a);
138   return(b);
139 }
140
141 static int
142 _max(int a, int b)
143 {
144   if (a>=b)
145     return(a);
146   return(b);
147 }
148
149 static int
150 _dist(struct state *st, int x1, int x2, int y1, int y2, int s)
151 {
152   double xd=x1-x2;
153   double yd=y1-y2;
154   switch(s) {
155     case 0:
156       return((int)sqrt(xd*xd+yd*yd));
157     case 1:
158       return((int)sqrt(xd*xd*st->cs1[0]*2+yd*yd));
159     case 2:
160       return((int)sqrt(xd*xd+yd*yd*st->cs2[0]*2));
161     default:
162       return((int)sqrt(xd*xd*st->cs1[0]/st->cs2[0]+yd*yd*st->cs3[0]/st->cs4[0]));
163   }
164 }
165
166 static int
167 _wave(struct state *st, int x, int h, int l, int wave)
168 {
169   l+=1;
170   switch(wave) {
171     case 0:                                         /* cos wave*/
172       return((int)(cos((double)x*M_PI/l)*h));
173     case 1:                                      /* double wave*/
174     case 2:                                      /* double wave*/
175       return((int)(cos((double)x*M_PI/l)*h)+(int)(sin((double)x*M_PI/l/st->cs1[1])*h));
176     case 3:                                         /* zig zag */
177       return(abs((x%(l*2)-l))*h/l);
178     case 4:                                   /* giant zig zag */
179       return(abs((x%(l*4)-l*2))*h*3/l);
180     case 5:                                        /* sawtooth */
181       return((x%(l))*h/l);
182     default:                                        /* no wave */
183       return(0);
184   }
185 }
186
187 static int
188 _triangle(struct state *st, int x, int y, int rx, int ry, int t)
189 {
190   switch(t) {
191     case 1:
192       return(_min(_min(x+y+rx-(st->gridx/2),st->gridx-x+y),(st->gridy-y+(ry/2))*3/2));
193     case 2:
194       return(_min(_min(x-rx,y-ry),(rx+ry-x-y)*2/3));
195     case 3:
196       return(_min(_min(st->gridx-x-rx,y-ry),(rx+ry-st->gridx+x-y)*2/3));
197     case 4:
198       return(_min(_min(x-rx,st->gridy-y-ry),(rx+ry-x-st->gridy+y)*2/3));
199   }
200   return(_min(_min(st->gridx-x-rx,st->gridy-y-ry),(rx+ry-st->gridx+x-st->gridy+y)*2/3));
201 }
202
203 static void
204 _init_zlist(struct state *st)
205 {
206   unsigned int tmp, y, z;
207
208   st->gridx=st->xgwa.width/st->lwid;
209   st->gridy=st->xgwa.height/st->lwid;
210   st->gridn=st->gridx*st->gridy;
211   /* clear grid */
212   for (z=0; z<st->gridn; z++) {
213     st->grid[z].line=st->grid[z].hl=st->grid[z].hr=st->grid[z].vu=st->grid[z].vd=st->grid[z].dhl=st->grid[z].dhr=st->grid[z].dvu=st->grid[z].dvd=0;
214     st->zlist[z]=z;
215   }
216   /* rather than pull x,y points randomly and wait to hit final empy cells a
217      list of all points is created and mixed so empty cells do get hit last */
218   for (z=0; z<st->gridn; z++) {
219     y=random()%st->gridn;
220     tmp=st->zlist[y];
221     st->zlist[y]=st->zlist[z];
222     st->zlist[z]=tmp;
223   }
224 }
225
226 static void
227 make_color_ramp_rgb (Screen *screen, Visual *visual, Colormap cmap,
228     int r1, int g1, int b1,  int r2, int g2, int b2,
229     XColor *colors, int *ncolorsP, Bool closed_p)
230 {
231     int h1, h2;
232     double s1, s2, v1, v2;
233     rgb_to_hsv(r1, g1, b1, &h1, &s1, &v1);
234     rgb_to_hsv(r2, g2, b2, &h2, &s2, &v2);
235     make_color_ramp(screen, visual, cmap, h1, s1, v1, h2, s2, v2,
236         colors, ncolorsP, False, True, 0);
237 }
238
239
240 static void
241 _init_colors(struct state *st)
242 {
243   int col[BASECOLORS];
244   int c1, c2, c3, h1, h2, h3;
245   int r1, g1, b1, r2, g2, b2, r3, g3, b3;
246   double s1, s2, s3, v1, v2, v3;
247   XColor tmp_col1[16], tmp_col2[16], tmp_col3[16];
248
249   unsigned short basecol[BASECOLORS][3]={
250     /* 0  dgray */    {0x3333,0x3333,0x3333},
251     /* 1  dbrown */   {0x6666,0x3333,0x0000},
252     /* 2  dred */     {0x9999,0x0000,0x0000},
253     /* 3  orange */   {0xFFFF,0x6666,0x0000},
254     /* 4  gold */     {0xFFFF,0xCCCC,0x0000},
255     /* 5  olive */    {0x6666,0x6666,0x0000},
256     /* 6  ivy */      {0x0000,0x6666,0x0000},
257     /* 7  dgreen */   {0x0000,0x9999,0x0000},
258     /* 8  bluegray */ {0x3333,0x6666,0x6666},
259     /* 9  dblue */    {0x0000,0x0000,0x9999},
260     /* 10 blue */     {0x3333,0x3333,0xFFFF},
261     /* 11 dpurple */  {0x6666,0x0000,0xCCCC},
262     /* 12 purple */   {0x6666,0x3333,0xFFFF},
263     /* 13 violet */   {0x9999,0x3333,0x9999},
264     /* 14 magenta */  {0xCCCC,0x3333,0xCCCC},
265     /* lights */
266     /* 15 gray */     {0x3333,0x3333,0x3333},
267     /* 16 brown */    {0x9999,0x6666,0x3333},
268     /* 17 tan */      {0xCCCC,0x9999,0x3333},
269     /* 18 red */      {0xFFFF,0x0000,0x0000},
270     /* 19 lorange */  {0xFFFF,0x9999,0x0000},
271     /* 20 yellow */   {0xFFFF,0xFFFF,0x0000},
272     /* 21 lolive */   {0x9999,0x9999,0x0000},
273     /* 22 green */    {0x3333,0xCCCC,0x0000},
274     /* 23 lgreen */   {0x3333,0xFFFF,0x3333},
275     /* 24 cyan */     {0x0000,0xCCCC,0xCCCC},
276     /* 25 sky */      {0x3333,0xFFFF,0xFFFF},
277     /* 26 marine */   {0x3333,0x6666,0xFFFF},
278     /* 27 lblue */    {0x3333,0xCCCC,0xFFFF},
279     /* 28 lpurple */  {0x9999,0x9999,0xFFFF},
280     /* 29 pink */     {0xFFFF,0x9999,0xFFFF}};
281
282   if (st->d3d) {
283     st->shades = (st->d3d==D3D_TILED) ? 5 : st->lwid/2+1;
284     st->ncolors=4+random()%4;
285     if (st->cmap>0) {                      /* tint the basecolors a bit */
286       for (c1=0; c1<BASECOLORS; c1++)
287         for (c2=0; c2<2; c2++)
288           if (!basecol[c1][c2]) {
289             basecol[c1][c2]+=random()%16000;
290           } else if (basecol[c1][c2]==0xFFFF) {
291             basecol[c1][c2]-=random()%16000;
292           } else {
293             basecol[c1][c2]-=8000;
294             basecol[c1][c2]+=random()%16000;
295           }
296     }
297     switch(st->cmap%4) {
298       case 0:                                            /* all */
299         for (c1=0; c1<st->ncolors; c1++)
300           col[c1]=random()%BASECOLORS;
301         break;
302       case 1:                                          /* darks */
303         for (c1=0; c1<st->ncolors; c1++)
304           col[c1]=random()%15;
305         break;
306       case 2:                                   /* semi consecutive darks */
307         col[0]=random()%15;
308         for (c1=1; c1<st->ncolors; c1++)
309           col[c1]=(col[c1-1]+1+random()%2)%15;
310         break;
311       case 3:                                   /* consecutive darks */
312         col[0]=random()%(15-st->ncolors);
313         for (c1=1; c1<st->ncolors; c1++)
314           col[c1]=col[c1-1]+1;
315         break;
316     }
317     for (c1=0; c1<st->ncolors; c1++) {
318       /* adjust colors already set */
319       for (h1=c1*st->shades-1; h1>=0; h1--)
320         st->colors[h1+st->shades]=st->colors[h1];
321       make_color_ramp_rgb(st->xgwa.screen, st->xgwa.visual, st->xgwa.colormap,
322         basecol[col[c1]][0], basecol[col[c1]][1], basecol[col[c1]][2],
323         0xFFFF, 0xFFFF, 0xFFFF, st->colors, &st->shades,
324         False);
325     }
326     return;
327   }
328   /* not 3d */
329   st->shades=1;
330   if (st->cmap%2) {                                  /* basecolors */
331     if (random()%3) {
332       c1=random()%15;
333       c2=(c1+3+(random()%5))%15;
334       c3=(c2+3+(random()%5))%15;
335     } else {
336       c1=random()%BASECOLORS;
337       c2=(c1+5+(random()%10))%BASECOLORS;
338       c3=(c2+5+(random()%10))%BASECOLORS;
339     }
340     r1=basecol[c1][0];
341     g1=basecol[c1][1];
342     b1=basecol[c1][2];
343     r2=basecol[c2][0];
344     g2=basecol[c2][1];
345     b2=basecol[c2][2];
346     r3=basecol[c3][0];
347     g3=basecol[c3][1];
348     b3=basecol[c3][2];
349   } else {                                             /* random rgb's */
350     r1=random()%65535;
351     g1=random()%65535;
352     b1=random()%65535;
353     r2=(r1+16384+random()%32768)%65535;
354     g2=(g1+16384+random()%32768)%65535;
355     b2=(b1+16384+random()%32768)%65535;
356     r3=(r2+16384+random()%32768)%65535;
357     g3=(g2+16384+random()%32768)%65535;
358     b3=(b2+16384+random()%32768)%65535;
359  }
360  switch(st->cmap) {
361     case 0:                           /* make_color_ramp color->color */
362     case 1:
363     case 2:                           /* make_color_ramp color->white */
364     case 3:
365       st->ncolors=5+random()%5;
366       if (st->cmap>1)
367         r2=g2=b2=0xFFFF;
368       make_color_ramp_rgb(st->xgwa.screen, st->xgwa.visual, st->xgwa.colormap,
369         r1, g1, b1, r2, g2, b2,
370         st->colors, &st->ncolors, random()%2);
371       break;
372     case 4:                                /* 3 color make_color_loop */
373     case 5:
374     case 6:
375     case 7:
376       st->ncolors=8+random()%12;
377       rgb_to_hsv(r1, g1, b1, &h1, &s1, &v1);
378       rgb_to_hsv(r2, g2, b2, &h2, &s2, &v2);
379       rgb_to_hsv(r3, g3, b3, &h3, &s3, &v3);
380
381       make_color_loop(st->xgwa.screen, st->xgwa.visual, st->xgwa.colormap,
382         h1, s1, v1, h2, s2, v2, h3, s3, v3,
383         st->colors, &st->ncolors, True, False);
384       break;
385     case 8:                                            /* random smooth */
386     case 9:
387       st->ncolors=(random()%4)*6+12;
388       make_smooth_colormap (st->xgwa.screen, st->xgwa.visual,
389         st->xgwa.colormap, st->colors, &st->ncolors,
390         True, False, True);
391       break;
392     case 10:                                                 /* rainbow */
393       st->ncolors=(random()%4)*6+12;
394       make_uniform_colormap (st->xgwa.screen, st->xgwa.visual,
395         st->xgwa.colormap, st->colors, &st->ncolors,
396         True, False, True);
397       break;
398     case 11:                                     /* dark to light blend */
399     case 12:
400     case 13:
401     case 14:
402       st->ncolors=7;
403       make_color_ramp_rgb(st->xgwa.screen, st->xgwa.visual,  st->xgwa.colormap,
404         r1, g1, b1, 0xFFFF, 0xFFFF, 0xFFFF,
405         tmp_col1, &st->ncolors, False);
406       make_color_ramp_rgb(st->xgwa.screen, st->xgwa.visual,  st->xgwa.colormap,
407         r2, g2, b2, 0xFFFF, 0xFFFF, 0xFFFF,
408         tmp_col2, &st->ncolors, False);
409       if (st->cmap<13) {
410         for(c1=0; c1<=4; c1++) {
411            st->colors[c1*2]=tmp_col1[c1];
412            st->colors[c1*2+1]=tmp_col2[c1];
413         }
414         st->ncolors=10;
415       } else {
416         make_color_ramp_rgb(st->xgwa.screen, st->xgwa.visual,  st->xgwa.colormap,
417           r3, g3, b3, 0xFFFF, 0xFFFF, 0xFFFF,
418           tmp_col3, &st->ncolors, False);
419         for(c1=0; c1<=4; c1++) {
420            st->colors[c1*3]=tmp_col1[c1];
421            st->colors[c1*3+1]=tmp_col2[c1];
422            st->colors[c1*3+2]=tmp_col3[c1];
423         }
424         st->ncolors=15;
425       }
426       break;
427     default:                                                  /* random */
428       st->ncolors=(random()%4)*6+12;
429       make_random_colormap (st->xgwa.screen, st->xgwa.visual,
430         st->xgwa.colormap, st->colors, &st->ncolors,
431         False, True, False, True);
432       break;
433   }
434
435   /* set random color order for drawing and erasing */
436   for (c1=0; c1<MAXCOLORS; c1++)
437     st->rco[c1]=c1;
438   for (c1=0; c1<MAXCOLORS; c1++) {
439     c3=random()%MAXCOLORS;
440     c2=st->rco[c1];
441     st->rco[c1]=st->rco[c3];
442     st->rco[c3]=c2;
443   }
444 }
445
446 static int _comparedeo(const void *i, const void *j)
447 {
448         struct lineStruct *h1, *h2;
449
450         h1=(struct lineStruct *)i;
451         h2=(struct lineStruct *)j;
452         if (h1->deo > h2->deo)
453                 return(1);
454         if (h1->deo < h2->deo)
455                 return(-1);
456         return(0);
457 }
458
459 static int
460 _hv(struct state *st, int x, int y, int d1, int d2, int pn, Bool de)
461 {
462   int v1, v2, r;
463
464   switch (d1) {
465     case 0:
466       v1 = (de) ? st->egridx-x : st->gridx-x;
467       break;
468     case 1:
469       v1 = y;
470       break;
471     case 2:
472       v1 = x;
473       break;
474     default:
475       v1 = (de) ? st->egridy-y : st->gridy-y;
476       break;
477   }
478   switch (d2) {
479     case 0:
480       v2 = (de) ? st->egridx-x : st->gridx-x;
481       break;
482     case 1:
483       v2 = y;
484       break;
485     case 2:
486       v2 = x;
487       break;
488     default:
489       v2 = (de) ? st->egridy-y : st->gridy-y;
490       break;
491   }
492   r = (de) ? (st->dline[st->li].hv) ? (v1+10000)*pn : (v2+10000)*-pn :
493     (st->eline[st->li].hv) ? (v1+10000)*pn : (v2+10000)*-pn;
494   return(r);
495 }
496         
497 static int
498 _getdeo(struct state *st, int x, int y, int map, int de)
499 {
500   int cr;
501   switch(map) {
502     case 0:                                        /* horizontal one side */
503       return(x);
504     case 1:                                          /* vertical one side */
505       return(y);
506     case 2:                                        /* horizontal two side */
507       return(_min(x,st->gridx-x)+1);
508     case 3:                                          /* vertical two side */
509       return(_min(y,st->gridy-y)+1);
510     case 4:                                                     /* square */
511       return(_max(abs(x-st->rx3[de]),abs(y-st->ry3[de]))+1);
512     case 5:                                                /* two squares */
513       return(_min(_max(abs(x-(st->rx3[de]/2)),abs(y-st->ry3[de])),_max(abs(x-(st->gridx-(st->rx2[de]/2))),abs(y-st->ry2[de])))+1);
514     case 6:                                       /* horizontal rectangle */
515       return(_max(abs(x-st->rx3[de]),abs(y-(st->ry3[de]))*st->cs1[de])+1);
516     case 7:                                         /* vertical rectangle */
517       return(_max(abs(x-st->rx3[de])*st->cs1[de],abs(y-(st->ry3[de])))+1);
518     case 8:                                                    /* + cross */
519       return(_min(abs(x-st->rx3[de]),abs(y-(st->ry3[de])))+1);
520     case 9:                                                   /* diagonal */
521       return((x*3/4+y)+1);
522     case 10:                                         /* opposite diagonal */
523       return((x*3/4+st->gridy-y)+1);
524     case 11:                                                   /* diamond */
525       return((abs(x-st->rx3[de])+abs(y-st->ry3[de]))/2+1);
526     case 12:                                              /* two diamonds */
527       return(_min(abs(x-(st->rx3[de]/2))+abs(y-st->ry3[de]),abs(x-(st->gridx-(st->rx2[de]/2)))+abs(y-st->ry2[de]))/2+1);
528     case 13:                                                    /* circle */
529       return(_dist(st,x,st->rx3[de],y,st->ry3[de],0)+1);
530     case 14:                                        /* horizontal ellipse */
531       return(_dist(st,x,st->rx3[de],y,st->ry3[de],1)+1);
532     case 15:                                          /* vertical ellipse */
533       return(_dist(st,x,st->rx3[de],y,st->ry3[de],2)+1);
534     case 16:                                               /* two circles */
535       return(_min(_dist(st,x,st->rx3[de]/2,y,st->ry3[de],0),_dist(st,x,st->gridx-(st->rx2[de]/2),y,st->ry2[de],0))+1);
536     case 17:                                  /* horizontal straight wave */
537       return(x+_wave(st,st->gridy+y,st->csw[0]*st->cs1[0],st->csw[0]*st->cs2[0],st->wave[de]));
538     case 18:                                    /* vertical straight wave */
539       return(y+_wave(st,st->gridx+x,st->csw[0]*st->cs1[0],st->csw[0]*st->cs2[0],st->wave[de]));
540     case 19:                                     /* horizontal wavey wave */
541       return(x+_wave(st,st->gridy+y+((x/5)*st->edir),st->csw[de]*st->cs1[de],st->csw[de]*st->cs2[de],st->wave[de])+1);
542     case 20:                                       /* vertical wavey wave */
543       return(y+_wave(st,st->gridx+x+((y/5)*st->edir),st->csw[de]*st->cs1[de],st->csw[de]*st->cs2[de],st->wave[de])+1);
544 /* no d3d for 21,22 */
545     case 21:                                  /* simultaneous directional */
546       return(_hv(st,x,y,st->cs1[0]%2,st->cs2[0]%2,1,de));
547     case 22:                                       /* reverse directional */
548       return(_hv(st,x,y,st->cs1[0]%2,st->cs2[0]%2,-1,de));
549     case 23:                                                    /* length */
550       if (de)
551         return(st->dline[st->li].len*1000+random()%5000);
552       else
553         return(st->eline[st->li].len*1000+random()%5000);
554     case 24:                                                    /* object */
555     case 25:
556     case 26:
557     case 27:
558       if (de)
559         return(st->dline[st->li].obj*100);
560       else
561         return(st->eline[st->li].obj*100);
562     default:                                                     /* color */
563       cr = (de) ? st->dline[st->li].color : st->eline[st->li].color;
564       if (map<34) cr=st->rco[cr];
565       if ((map%6<4) || (de))  {                               /* by color */
566         cr*=1000;
567         cr+=random()%1000;
568       } else if (map%6==4) {                      /* by color horizontaly */
569         cr*=st->gridx;
570         cr+=(x+random()%(st->gridx/2));
571       } else {                                     /* by color vertically */
572         cr*=st->gridy;
573         cr+=(y+random()%(st->gridy/2));
574       }
575       return(cr);
576   }
577   return(1);
578 }
579
580 static void
581 _init_screen(struct state *st)
582 {
583   int nstr, x;
584   struct lineStruct *tmp;
585
586   /* malloc memory in case of resize */
587   if (st->resized) {
588     st->max_wxh=st->xgwa.width*st->xgwa.height;
589     if (st->dline!=NULL)
590       free(st->dline);
591     if (st->eline!=NULL)
592       free(st->eline);
593     if (st->grid!=NULL)
594       free(st->grid);
595     if (st->zlist!=NULL)
596       free(st->zlist);
597     if (st->fdol!=NULL)
598       free(st->fdol);
599     if (st->odi!=NULL)
600       free(st->odi);
601     st->narray = (st->xgwa.width+1)*(st->xgwa.height+1)/4+1;
602     st->dline = calloc(st->narray, sizeof(struct lineStruct));
603     st->eline = calloc(st->narray, sizeof(struct lineStruct));
604     st->grid = calloc(st->narray, sizeof(struct gridStruct));
605     st->zlist = calloc(st->narray, sizeof(unsigned int));
606     st->fdol = calloc(st->narray, sizeof(unsigned int));
607     st->odi = calloc(st->narray, sizeof(Bool));
608     if ((st->dline == NULL) || (st->eline == NULL) ||
609       (st->grid == NULL) || (st->zlist == NULL) ||
610       (st->fdol == NULL) || (st->odi == NULL)) {
611       fprintf(stderr, "not enough memory\n");
612       exit(1);
613     }
614     st->dialog = (st->xgwa.width<500) ? 1 : 0;
615     st->resized=False;
616   }
617   if (st->ii) {
618     /* swap st->dline and st->eline pointers to resort and erase */
619     tmp=st->eline;
620     st->eline=st->dline;
621     st->dline=tmp;
622     st->eli=st->li;
623     st->elwid=st->lwid;
624     st->elpu=st->lpu;
625     st->egridx=st->gridx;
626     st->egridy=st->gridy;
627
628     /* create new erase order */
629     for (st->li=1; st->li<=st->eli; st->li++)
630       st->eline[st->li].deo=(_getdeo(st,st->eline[st->li].x,st->eline[st->li].y,st->emap,0) + (random()%st->evar) + (random()%st->evar))*st->edir;
631     qsort(st->eline, st->eli+1, sizeof(struct lineStruct), _comparedeo);
632   }
633   st->ii++;
634
635   /* clear arrays and other counters */
636   st->di=st->ei=st->fi=st->li=st->oi=st->zi=0;
637   st->grid_full=False;
638   /* li starts from 1 */
639   st->dline[0].x=st->dline[0].y=st->dline[0].len=0;
640   /* to keep it first after sorting so di is never null */
641   st->dline[0].deo=-999999999;
642
643   /* set random screen variables */
644   st->lwid = (st->ii==1) ? 3 : 2+((random()%6)%4);
645   st->d3d = ((st->tile==TILE_FLAT) || (st->tile==TILE_THIN) ||
646     (st->tile==TILE_OUTLINE)) ? D3D_NONE :
647     (st->tile==TILE_BLOCK) ? D3D_BLOCK :
648     (st->tile==TILE_NEON) ? D3D_NEON :
649     (st->tile==TILE_TILED) ? D3D_TILED :
650     /* force TILE_D3D on first screen to properly load all shades */
651     ((st->ii==1) && (!st->newcols)) ? D3D_TILED : (random()%5)%4;
652 /* st->d3d=D3D_BLOCK; st->lwid=2; */
653   st->outline = (st->tile==TILE_OUTLINE) ? 1 :
654      ((st->tile!=TILE_RANDOM) || (random()%5)) ? 0 : 1;
655   st->round = (st->d3d==D3D_NEON) ? 1 :
656     ((st->d3d==D3D_BLOCK) || (st->outline) || (random()%6)) ? 0 : 1;
657   if ((st->d3d) || (st->outline) || (st->round))
658     st->lwid+=2;
659   if ((!st->d3d) && (!st->round) && (!st->outline) && (st->lwid>3))
660     st->lwid-=2;
661   if (st->d3d==D3D_TILED)
662     st->lwid++;
663   if (st->tile==TILE_THIN)
664     st->lwid=2;
665
666   _init_zlist(st);
667
668   st->maxlen=(st->lwid>6) ? 2+(random()%4) :
669                 (st->lwid>4) ? 2+(random()%8)%6 :
670                 (st->lwid>2) ? 2+(random()%12)%8 : 2+(random()%15)%10;
671   st->bnratio = 4+(random()%4)+(random()%4);
672   st->forcemax = (random()%6) ? 0 : 1;
673
674   if ((st->ii==1) || (st->newcols))
675     _init_colors(st);
676
677   st->dmap = (st->emap+5+(random()%5))%DRAWORDERS;
678
679   st->dmap=20+random()%20;
680
681   st->dvar = (st->dmap>22) ? 100 : 10+(st->csw[0]*(random()%5));
682   st->ddir= (random()%2) ? 1 : -1;
683
684   st->emap = (st->dmap+10+(random()%10))%20;
685   st->evar = (st->emap>22) ? 100 : 10+(st->csw[0]*(random()%5));
686   st->edir= (random()%2) ? 1 : -1;
687
688   st->layers= (random()%2) ? 2 : (random()%2) ? 1 : (random()%2) ? 3 : 4;
689   st->cmap=(st->cmap+5+(random()%10))%COLORMAPS;
690
691   for (x=0; x<LAYERS; x++) {
692     st->pattern[x]=random()%PATTERNS;
693     st->shape[x]=random()%SHAPES;
694     st->mix[x]=random()%20;
695     nstr = (st->lwid==2) ? 20+random()%12 :
696       (st->lwid==3) ? 16+random()%8 :
697       (st->lwid==4) ? 12+random()%6 :
698       (st->lwid==5) ? 10+random()%5 :
699       (st->lwid==6) ? 8+random()%4 :
700         5+random()%5;
701     st->csw[x] = _max(5,st->gridy/nstr);
702     st->wsx[x] = (st->wsx[x]+3+(random()%3))%STRETCHES;
703     st->wsy[x] = (st->wsy[x]+3+(random()%3))%STRETCHES;
704     st->sec[x] = random()%5;
705     if ((!st->dialog) && (st->sec[x]<2)) st->csw[x]/=2;
706     st->cs1[x] = (st->dialog) ? 1+random()%3 : 2+random()%5;
707     st->cs2[x] = (st->dialog) ? 1+random()%3 : 2+random()%5;
708     st->cs3[x] = (st->dialog) ? 1+random()%3 : 2+random()%5;
709     st->cs4[x] = (st->dialog) ? 1+random()%3 : 2+random()%5;
710     st->wave[x]=random()%WAVES;
711     st->wavel[x]=st->csw[x]*(2+random()%6);
712     st->waveh[x]=st->csw[x]*(1+random()%3);
713     st->rx1[x]=(st->gridx/10+random()%(st->gridx*8/10));
714     st->ry1[x]=(st->gridy/10+random()%(st->gridy*8/10));
715     st->rx2[x]=(st->gridx*2/10+random()%(st->gridx*6/10));
716     st->ry2[x]=(st->gridy*2/10+random()%(st->gridy*6/10));
717     st->rx3[x]=(st->gridx*3/10+random()%(st->gridx*4/10));
718     st->ry3[x]=(st->gridy*3/10+random()%(st->gridy*4/10));
719   }
720 }
721
722 static int
723 _shape(struct state *st, int x, int y, int rx, int ry, int n)
724 {
725   switch(st->shape[n]) {
726     case 0:                                        /* square/rectangle */
727     case 1:
728     case 2:
729       return(1+_max(abs(x-rx)*st->cs1[n]/st->cs2[n],abs(y-ry)*st->cs3[n]/st->cs4[n]));
730     case 3:                                                 /* diamond */
731     case 4:
732       return(1+(abs(x-rx)*st->cs1[n]/st->cs2[n]+abs(y-ry)*st->cs3[n]/st->cs4[n]));
733     case 5:                                            /* 8 point star */
734       return(1+_min(_max(abs(x-rx),abs(y-ry))*3/2,abs(x-rx)+abs(y-ry)));
735     case 6:                                             /* circle/oval */
736     case 7:
737     case 8:
738       return(1+_dist(st,x,rx,y,ry,st->cs1[n]));
739     case 9:                                       /* black hole circle */
740       return(1+(st->gridx*st->gridy/(1+(_dist(st,x,rx,y,ry,st->cs2[n])))));
741     case 10:                                                   /* sun */
742       return(1+_min(abs(x-rx)*st->gridx/(abs(y-ry)+1),abs(y-ry)*st->gridx/(abs(x-rx)+1)));
743     case 11:                             /* 2 circles+inverted circle */
744       return(1+(_dist(st,x,rx,y,ry,st->cs1[n])*_dist(st,x,(rx*3)%st->gridx,y,(ry*5)%st->gridy,st->cs1[n])/(1+_dist(st,x,(rx*4)%st->gridx,y,(ry*7)%st->gridy,st->cs1[n]))));
745     case 12:                                                   /* star */
746       return(1+(int)sqrt(abs((x-rx)*(y-ry))));
747     case 13:                                       /* centered ellipse */
748       return(1+_dist(st,x,rx,y,ry,0)+_dist(st,x,st->gridx-rx,y,st->gridy-ry,0));
749     default:                                               /* triangle */
750       return(1+_triangle(st,x,y,rx,ry,st->cs4[n]));
751   }
752   return(1+_triangle(st,x,y,rx,ry,st->cs4[n]));
753 }
754
755 static int
756 _pattern(struct state *st, int x, int y, int n)
757 {
758   int v=0, ox;
759   ox=x;
760   switch(st->wsx[n]) {
761     case 0:                                             /* slants */
762       x+=y/(1+st->cs4[n]);
763       break;
764     case 1:
765       x+=(st->gridy-y)/(1+st->cs4[n]);
766       break;
767     case 2:                                             /* curves */
768       x+=_wave(st,y,st->gridx/(1+st->cs1[n]),st->gridy,0);
769       break;
770     case 3:
771       x+=_wave(st,st->gridy-y,st->gridy/(1+st->cs1[n]),st->gridy,0);
772       break;
773     case 4:                                           /* U curves */
774       x+=_wave(st,y,st->cs1[n]*st->csw[n]/2,st->gridy*2/M_PI,0);
775       break;
776     case 5:
777       x-=_wave(st,y,st->cs1[n]*st->csw[n]/2,st->gridy*2/M_PI,0);
778       break;
779   }
780   switch(st->wsy[0]) {
781     case 0:                                          /* slants */
782       y+=ox/(1+st->cs1[n]);
783       break;
784     case 1:
785       y+=(st->gridx-ox)/(1+st->cs1[n]);
786       break;
787     case 2:                                           /* curves */
788       y+=_wave(st,ox,st->gridx/(1+st->cs1[n]),st->gridx,0);
789       break;
790     case 3:
791       y+=_wave(st,st->gridx-ox,st->gridx/(1+st->cs1[n]),st->gridx,0);
792       break;
793     case 4:                                         /* U curves */
794       y+=_wave(st,ox,st->cs1[n]*st->csw[n]/2,st->gridy*2/M_PI,0);
795       break;
796     case 5:
797       y-=_wave(st,ox,st->cs1[n]*st->csw[n]/2,st->gridy*2/M_PI,0);
798       break;
799   }
800   switch(st->pattern[n]) {
801     case 0:                                          /* horizontal stripes */
802       v=y;
803       break;
804     case 1:                                            /* vertical stripes */
805       v=x;
806       break;
807     case 2:                                            /* diagonal stripes */
808       v=(x+(y*st->cs1[n]/st->cs2[n]));
809       break;
810     case 3:                                    /* reverse diagonal stripes */
811       v=(x-(y*st->cs1[n]/st->cs2[n]));
812       break;
813     case 4:                                                /* checkerboard */
814       v=(y/st->csw[n]*3+x/st->csw[n])*st->csw[n];
815       break;
816     case 5:                                       /* diagonal checkerboard */
817       v=((x+y)/2/st->csw[n]+(x+st->gridy-y)/2/st->csw[n]*3)*st->csw[n];
818       break;
819     case 6:                                                     /* + cross */
820       v=st->gridx+(_min(abs(x-st->rx3[n]),abs(y-st->ry3[n]))*2);
821       break;
822     case 7:                                              /* double + cross */
823       v=_min(_min(abs(x-st->rx2[n]),abs(y-st->ry2[n])),_min(abs(x-st->rx1[n]),abs(y-st->ry1[n])))*2;
824       break;
825     case 8:                                                     /* X cross */
826       v=st->gridx+(_min(abs(x-st->rx3[n])*st->cs1[n]/st->cs2[n]+abs(y-st->ry2[n])*st->cs3[n]/st->cs4[n],abs(x-st->rx3[n])*st->cs1[n]/st->cs2[n]-abs(y-st->ry3[n])*st->cs3[n]/st->cs4[n])*2);
827       break;
828     case 9:                                              /* double X cross */
829       v=_min(_min(abs(x-st->rx2[n])+abs(y-st->ry2[n]),abs(x-st->rx2[n])-abs(y-st->ry2[n])),_min(abs(x-st->rx1[n])+abs(y-st->ry1[n]),abs(x-st->rx1[n])-abs(y-st->ry1[n])))*2;
830       break;
831     case 10:                                   /* horizontal stripes/waves */
832       v=st->gridy+(y+_wave(st,x,st->waveh[n],st->wavel[n],st->wave[n]));
833       break;
834     case 11:                                     /* vertical stripes/waves */
835       v=st->gridx+(x+_wave(st,y,st->waveh[n],st->wavel[n],st->wave[n]));
836       break;
837     case 12:                                     /* diagonal stripes/waves */
838       v=st->gridx+(x+(y*st->cs1[n]/st->cs2[n])+_wave(st,x,st->waveh[n],st->wavel[n],st->wave[n]));
839       break;
840     case 13:                                     /* diagonal stripes/waves */
841       v=st->gridx+(x-(y*st->cs1[n]/st->cs2[n])+_wave(st,y,st->waveh[n],st->wavel[n],st->wave[n]));
842       break;
843     case 14:                                    /* horizontal spikey waves */
844       v=y+(st->csw[n]*st->cs4[n]/st->cs3[n])+_wave(st,x+((y/st->cs3[n])*st->edir),st->csw[n]/2*st->cs1[n]/st->cs2[n],st->csw[n]/2*st->cs2[n]/st->cs1[n],st->wave[n]);
845       break;
846     case 15:                                      /* vertical spikey waves */
847       v=x+(st->csw[n]*st->cs1[n]/st->cs2[n])+_wave(st,y+((x/st->cs3[n])*st->edir),st->csw[n]/2*st->cs1[n]/st->cs2[n],st->csw[n]/2*st->cs3[n]/st->cs4[n],st->wave[n]);
848       break;
849     case 16:                                    /* big slanted hwaves */
850       v=st->gridy-y-(x*st->cs1[n]/st->cs3[n])+(st->csw[n]*st->cs1[n]*st->cs2[n]) +_wave(st,x,st->csw[n]/3*st->cs1[n]*st->cs2[n],st->csw[n]/3*st->cs3[n]*st->cs2[n],st->wave[n]);
851       break;
852     case 17:                                    /* big slanted vwaves */
853       v=x-(y*st->cs1[n]/st->cs3[n])+(st->csw[n]*st->cs1[n]*st->cs2[n]) +_wave(st,y, st->csw[n]/3*st->cs1[n]*st->cs2[n], st->csw[n]/3*st->cs3[n]*st->cs2[n], st->wave[n]);
854       break;
855     case 18:                                          /* double hwave */
856       v=y+(y+st->csw[n]*st->cs3[n])+_wave(st,x,st->csw[n]/3*st->cs3[n],st->csw[n]/3*st->cs2[n],st->wave[n])+_wave(st,x,st->csw[n]/3*st->cs4[n],st->csw[n]/3*st->cs1[n]*3/2,st->wave[n]);
857       break;
858     case 19:                                          /* double vwave */
859       v=x+(x+st->csw[n]*st->cs1[n])+_wave(st,y,st->csw[n]/3*st->cs1[n],st->csw[n]/3*st->cs3[n],st->wave[n])+_wave(st,y,st->csw[n]/3*st->cs2[n],st->csw[n]/3*st->cs4[n]*3/2,st->wave[n]);
860       break;
861     case 20:                                                  /* one shape */
862     case 21:
863     case 22:
864       v=_shape(st,x, y, st->rx3[n], st->ry3[n], n);
865       break;
866     case 23:                                                 /* two shapes */
867     case 24:
868     case 25:
869       v=_min(_shape(st,x, y, st->rx1[n], st->ry1[n], n),_shape(st,x, y, st->rx2[n], st->ry2[n], n));
870       break;
871     case 26:                                       /* two shapes opposites */
872     case 27:
873       v=_min(_shape(st,x, y, st->rx2[n], st->ry2[n], n),_shape(st,x, y, st->gridx-st->rx2[n], st->gridy-st->rx2[n], n));
874       break;
875     case 28:                                     /* two shape checkerboard */
876     case 29:
877       v=((_shape(st,x, y, st->rx1[n], st->ry1[n], n)/st->csw[n])+(_shape(st,x, y, st->rx2[n], st->ry2[n], n)/st->csw[n]))*st->csw[n];
878       break;
879     case 30:                                             /* two shape blob */
880     case 31:
881       v=(_shape(st,x, y, st->rx1[n], st->ry1[n], n)+_shape(st,x, y, st->rx2[n], st->ry2[n], n))/2;
882       break;
883     case 32:                                    /* inverted two shape blob */
884     case 33:
885       v=(_shape(st,x, y, st->rx1[n], st->ry1[n], n)+_shape(st,st->gridx-x, st->gridy-y, st->rx1[n], st->ry1[n], n))/2;
886       break;
887     case 34:                                               /* three shapes */
888     case 35:
889       v=_min(_shape(st,x, y, st->rx3[n], st->ry3[n], n),_min(_shape(st,x, y, st->rx1[n], st->ry1[n], n),_shape(st,x, y, st->rx2[n], st->ry2[n], n)));
890       break;
891     case 36:                                           /* three shape blob */
892     case 37:
893       v=(_shape(st,x, y, st->rx1[n], st->ry1[n], n)+_shape(st,x, y, st->rx2[n], st->ry2[n], n)+_shape(st,x, y, st->rx3[n], st->ry3[n], n))/3;
894       break;
895     case 38:                                                  /* 4 shapes */    
896       v=(_min(_shape(st,x, y, st->rx2[n], st->ry2[n], n),_shape(st,x, y, st->gridx-st->rx2[n], st->gridy-st->ry2[n], n)),_min(_shape(st,x, y, st->gridx-st->rx2[n], st->ry2[n], n),_shape(st,x, y, st->rx2[n], st->gridy-st->ry2[n], n)));
897       break;
898     case 39:                                            /* four rainbows */
899       v=(_min(_shape(st,x, y, st->gridx-st->rx2[n]/2, st->csw[n], n),_shape(st,x, y, st->csw[n], st->ry2[n]/2, n)),_min(_shape(st,x, y, st->rx2[n]/2, st->gridy-st->csw[n], n),_shape(st,x, y, st->gridx-st->csw[n], st->gridy-(st->ry2[n]/2), n)));
900       break;
901   }
902   /* stretch or contract stripe */
903   switch(st->sec[n]) {
904     case 0:
905       v=(int)sqrt((int)sqrt(abs(v)*st->gridx)*st->gridx);
906       break;
907     case 1:
908       v=((int)pow(v,2)/st->gridx);
909       break;
910   }
911   return (abs(v));
912 }
913
914 static int
915 _getcolor(struct state *st, int x, int y)
916 {
917   int n, cv[LAYERS];
918
919   for (n=0; n<st->layers; n++) {
920     cv[n]=_pattern(st,x,y,n);
921                   /* first wave/shape */
922     cv[0] = (!n) ? cv[0]/st->csw[0] :
923                     /* checkerboard+1 */
924       (st->mix[n]<5) ? (cv[0]*st->csw[0]+cv[n])/st->csw[n] :
925                /* checkerboard+ncol/2 */
926       (st->mix[n]<12) ? cv[0]+(cv[n]/st->csw[n]*st->ncolors/2) :
927                            /* add mix */
928       (st->mix[n]<16) ? cv[0]+(cv[n]/st->csw[n]) :
929                       /* subtract mix */
930       (st->mix[n]<18) ? cv[0]-(cv[n]/st->csw[n]) :
931                   /* r to l morph mix */
932       (st->mix[n]==18) ? ((cv[0]*x)+(cv[n]*(st->gridx-x)/st->csw[n]))/st->gridx :
933                   /* u to d morph mix */
934       ((cv[0]*y)+(cv[n]*(st->gridy-y)/st->csw[n]))/st->gridy;
935   }
936   return(cv[0]);
937 }
938
939 /* return value=line direction
940    st->olen=open space to edge or next blocking line
941    st->bln=blocking line number or -1 if edge blocks */
942 static int
943 _findopen(struct state *st, int x, int y, int z)
944 {
945   int dir, od[4], no=0;
946
947   if (((st->grid[z].hl) || (st->grid[z].hr)) &&
948     ((st->grid[z].vu) || (st->grid[z].vd)))
949     return(DIR_NONE);
950   if ((z>st->gridx) && (!st->grid[z].hl) && (!st->grid[z].hr) &&
951     (!st->grid[z-st->gridx].line)) {
952     od[no]=DIR_UP;
953     no++;
954   }
955   if ((z<st->gridn-st->gridx) && (!st->grid[z].hl) &&
956     (!st->grid[z].hr) && (!st->grid[z+st->gridx].line)) {
957     od[no]=DIR_DOWN;
958     no++;
959   }
960   if ((x) && (!st->grid[z].hl) && (!st->grid[z].hr) &&
961     (!st->grid[z-1].line)) {
962     od[no]=DIR_LEFT;
963     no++;
964   }
965   if (((z+1)%st->gridx) && (!st->grid[z].hl) && (!st->grid[z].hr) &&
966     (!st->grid[z+1].line)) {
967     od[no]=DIR_RIGHT;
968     no++;
969   }
970   if (!no)
971     return(DIR_NONE);
972   dir=od[random()%no];
973   st->olen=st->bln=0;
974   while ((st->olen<=st->maxlen) && (!st->bln)) {
975     st->olen++;
976     if (dir==DIR_UP)
977       st->bln = (y-st->olen<0) ? -1 :
978         st->grid[z-(st->olen*st->gridx)].line;
979     if (dir==DIR_DOWN)
980       st->bln = (y+st->olen>=st->gridy) ? -1 :
981         st->grid[z+(st->olen*st->gridx)].line;
982     if (dir==DIR_LEFT)
983       st->bln = (x-st->olen<0) ? -1 :
984         st->grid[z-st->olen].line;
985     if (dir==DIR_RIGHT)
986       st->bln = (x+st->olen>=st->gridx) ? -1 :
987         st->grid[z+st->olen].line;
988   }
989   st->olen--;
990   return(dir);
991 }
992
993 static void
994 _fillgrid(struct state *st)
995 {
996   unsigned int gridc, n, add;
997
998   gridc=st->gridx*st->dline[st->li].y+st->dline[st->li].x;
999   add = (st->dline[st->li].hv) ? 1 : st->gridx;
1000   for (n=0;  n<=st->dline[st->li].len; n++) {
1001     if (n)
1002       gridc+=add;
1003     if (!st->grid[gridc].line) {
1004       st->fi++;
1005       st->grid[gridc].line=st->li;
1006     }
1007     if (st->dline[st->li].hv) {
1008       if (n)
1009         st->grid[gridc].hr=st->li;
1010       if (n<st->dline[st->li].len)
1011         st->grid[gridc].hl=st->li;
1012     } else {
1013       if (n)
1014         st->grid[gridc].vd=st->li;
1015       if (n<st->dline[st->li].len)
1016         st->grid[gridc].vu=st->li;
1017     }
1018     if (st->fi>=st->gridn) {
1019       st->grid_full=True;
1020       return;
1021     }
1022   }
1023 }
1024
1025 static void
1026 _newline(struct state *st)
1027 {
1028   int bl, bz, dir, lt, x, y, z;
1029
1030   bl=0;
1031   z=st->zlist[st->zi];
1032   x=z%st->gridx;
1033   y=z/st->gridx;
1034   st->zi++;
1035   dir=_findopen(st,x,y,z);
1036
1037   if (!st->grid[z].line) {
1038   /* this is an empty space, make a new line unless nothing is open around it */
1039     if (dir==DIR_NONE) {
1040       /* nothing is open, force a len 1 branch in any direction */
1041       lt=LINE_FORCE;
1042       while ((dir==DIR_NONE) ||
1043         ((dir==DIR_UP) && (!y)) ||
1044         ((dir==DIR_DOWN) && (y+1==st->gridy)) ||
1045         ((dir==DIR_LEFT) && (!x)) ||
1046         ((dir==DIR_RIGHT) && (x+1==st->gridx))) {
1047           dir=random()%4;
1048       }
1049       bz = (dir==DIR_UP) ? z-st->gridx : (dir==DIR_DOWN) ? z+st->gridx : (dir==DIR_LEFT) ? z-1 : z+1;
1050       bl = st->grid[bz].line;
1051     } else if ((st->bnratio>1) && (st->bln>0) &&
1052       (st->olen<st->maxlen) && (random()%st->bnratio)) {
1053       /* branch into blocking line */
1054       lt=LINE_BRIN;
1055       bl = st->bln;
1056     } else {
1057       /* make a new line and new object */
1058       lt=LINE_NEW;
1059       st->oi++;
1060     }
1061   } else {
1062     /* this is a filled space, make a branch unless nothing is open around it */
1063     if (dir==DIR_NONE)
1064       return;
1065     /* make a branch out of this line */
1066     lt=LINE_BROUT;
1067     bl=st->grid[z].line;
1068   }
1069   st->li++;
1070   st->dline[st->li].len = (lt==LINE_FORCE) ? 1 :  (lt==LINE_BRIN) ?
1071     st->olen+1 : (!st->forcemax) ? st->olen : 1+random()%st->olen;
1072   st->dline[st->li].x=x;
1073   if (dir==DIR_LEFT)
1074     st->dline[st->li].x-=st->dline[st->li].len;
1075   st->dline[st->li].y=y;
1076   if (dir==DIR_UP)
1077     st->dline[st->li].y-=st->dline[st->li].len;
1078   st->dline[st->li].hv = ((dir==DIR_LEFT) || (dir==DIR_RIGHT)) ?
1079     True : False;
1080   st->dline[st->li].obj = (lt==LINE_NEW) ? st->oi :
1081     st->dline[bl].obj;
1082   st->dline[st->li].color = (lt==LINE_NEW) ?
1083     (_getcolor(st,x,y))%st->ncolors : st->dline[bl].color;
1084   st->dline[st->li].deo=(_getdeo(st,x,y,st->dmap,1) +
1085     (random()%st->dvar) + (random()%st->dvar))*st->ddir;
1086   st->dline[st->li].ndol=0;
1087   _fillgrid(st);
1088 }
1089
1090 static void
1091 _create_screen(struct state *st)
1092 {
1093   while(!st->grid_full)
1094     _newline(st);
1095   qsort(st->dline, st->li+1, sizeof(struct lineStruct), _comparedeo);
1096 /*st->lpu=st->li/20/((6-st->speed)*3);
1097   Used to use a computed lpu, lines per update to control draw speed
1098   draw 1/lpu of the lines before each XSync which takes a split second
1099   the higher the lpu, the quicker the screen draws.  This worked somewhat
1100   after the 4->5 update, however with the Mac updating so much more slowly,
1101   values tuned for it draw the screen in a blink on Linux.  Therefore we
1102   draw 1/200th of the screen with each update and sleep, if necessary */
1103   st->lpu = (st->dialog) ? st->li/50 : st->li/200;
1104   if (!st->lpu) st->lpu = 1;
1105   st->bi=1;
1106   st->mode=MODE_ERASE;
1107 }
1108
1109 static void
1110 _fill_outline(struct state *st, int di)
1111 {
1112   int x, y, h, w;
1113
1114   if (!di)
1115     return;
1116   x=st->dline[di].x*st->lwid+1;
1117   y=st->dline[di].y*st->lwid+1;
1118   if (st->dline[di].hv) {
1119     w=(st->dline[di].len+1)*st->lwid-3;
1120     h=st->lwid-3;
1121   } else {
1122     w=st->lwid-3;
1123     h=(st->dline[di].len+1)*st->lwid-3;
1124   }
1125   XFillRectangle (st->display, st->window, st->bgc, x, y, w, h);
1126 }
1127
1128 static void
1129 _XFillRectangle(struct state *st, int di, int adj)
1130 {
1131   int a, b, x, y, w, h;
1132
1133   x=st->dline[di].x*st->lwid;
1134   y=st->dline[di].y*st->lwid;
1135   if (st->dline[di].hv) {
1136     w=(st->dline[di].len+1)*st->lwid-1;
1137     h=st->lwid-1;
1138   } else {
1139     w=st->lwid-1;
1140     h=(st->dline[di].len+1)*st->lwid-1;
1141   }
1142   switch (st->d3d) {
1143     case D3D_NEON:
1144       x+=adj;
1145       y+=adj;
1146       w-=adj*2;
1147       h-=adj*2;
1148     break;
1149     case D3D_BLOCK:
1150       x+=adj;
1151       y+=adj;
1152       w-=st->lwid/2-1;
1153       h-=st->lwid/2-1;
1154     break;
1155   }
1156   if (!st->round) {
1157     XFillRectangle(st->display, st->window, st->fgc, x, y, w, h);
1158   } else {
1159     if (h<st->lwid) {                                   /* horizontal */
1160       a=(h-1)/2;
1161       for (b=0; b<=a; b++)
1162         XFillRectangle(st->display, st->window, st->fgc,
1163           x+b, y+a-b, w-b*2, h-((a-b)*2));
1164     } else {                                               /* vertical */
1165       a=(w-1)/2;
1166       for (b=0; b<=a; b++)
1167         XFillRectangle(st->display, st->window, st->fgc,
1168           x+a-b, y+b, w-((a-b)*2), h-b*2);
1169     }
1170   }
1171 }
1172
1173 static void
1174 _XFillTriangle(struct state *st, int color, int x1, int y1, int x2, int y2,
1175   int x3, int y3)
1176 {
1177   XPoint points[3];
1178
1179   points[0].x=x1;
1180   points[0].y=y1;
1181   points[1].x=x2;
1182   points[1].y=y2;
1183   points[2].x=x3;
1184   points[2].y=y3;
1185   XSetForeground(st->display, st->fgc, st->colors[color].pixel);
1186   XFillPolygon (st->display, st->window, st->fgc, points, 3, Convex,
1187       CoordModeOrigin);
1188 }
1189
1190 static void
1191 _XFillPolygon4(struct state *st, int color, int x1, int y1, int x2, int y2,
1192   int x3, int y3, int x4, int y4)
1193 {
1194   XPoint points[4];
1195
1196   points[0].x=x1;
1197   points[0].y=y1;
1198   points[1].x=x2;
1199   points[1].y=y2;
1200   points[2].x=x3;
1201   points[2].y=y3;
1202   points[3].x=x4;
1203   points[3].y=y4;
1204   XSetForeground(st->display, st->fgc, st->colors[color].pixel);
1205   XFillPolygon (st->display, st->window, st->fgc, points, 4, Convex,
1206       CoordModeOrigin);
1207 }
1208
1209 static void
1210 _draw_tiled(struct state *st, int color)
1211 {
1212   int a, c, d, x, y, z, m1, m2, lr, nl, w, h;
1213   a = (st->dline[st->di].hv) ? 1 : st->gridx;
1214   z = st->dline[st->di].y*st->gridx+st->dline[st->di].x;
1215   m1 = (st->lwid-1)/2;
1216   m2 = st->lwid/2;
1217   lr = st->lwid-1;
1218   nl = st->lwid;
1219
1220   /* draw tiles one grid cell at a time */
1221   for (c=0; c<=st->dline[st->di].len; c++) {
1222     if (st->dline[st->di].hv) {
1223       x = (st->dline[st->di].x+c)*st->lwid;
1224       y = st->dline[st->di].y*st->lwid;
1225       if (c)
1226         st->grid[z].dhr=st->di;
1227       if (c<st->dline[st->di].len)
1228         st->grid[z].dhl=st->di;
1229     } else {
1230       x = st->dline[st->di].x*st->lwid;
1231       y = (st->dline[st->di].y+c)*st->lwid;
1232       if (c)
1233         st->grid[z].dvd=st->di;
1234       if (c<st->dline[st->di].len)
1235         st->grid[z].dvu=st->di;
1236     }
1237     d=0;
1238     if (st->grid[z].dhl)
1239       d+=8;
1240     if (st->grid[z].dhr)
1241       d+=4;
1242     if (st->grid[z].dvu)
1243       d+=2;
1244     if (st->grid[z].dvd)
1245       d++;
1246     /* draw line base */
1247     switch (d) {
1248       case 1:
1249       case 2:                                    /* vertical */
1250       case 3:
1251       case 5:
1252       case 6:
1253       case 7:
1254       case 11:
1255       case 15:
1256         h = ((d==1) || (d==5)) ? lr : nl;
1257         XSetForeground(st->display, st->fgc,
1258           st->colors[color].pixel);
1259         XFillRectangle (st->display, st->window, st->fgc,
1260           x, y, m2, h);
1261         XSetForeground(st->display, st->fgc,
1262            st->colors[color+3].pixel);
1263         XFillRectangle (st->display, st->window, st->fgc,
1264           x+m2, y, m1, h);
1265         break;
1266       case 4:
1267       case 8:                                     /* horizontal */
1268       case 9:
1269       case 10:
1270       case 12:
1271       case 13:
1272       case 14:
1273         w = (d==4) ? lr : nl;
1274         XSetForeground(st->display, st->fgc,
1275           st->colors[color+1].pixel);
1276         XFillRectangle (st->display, st->window, st->fgc,
1277           x, y, w, m2);
1278         XSetForeground(st->display, st->fgc,
1279            st->colors[color+2].pixel);
1280         XFillRectangle (st->display, st->window, st->fgc,
1281           x, y+m2, w, m1);
1282         break;
1283     }
1284     /* draw angles */
1285     switch(d) {
1286       case 1:                                      /* bottom end ^ */
1287         _XFillTriangle(st,color+2, x, y+lr, x+lr, y+lr, x+m2, y+m2);
1288         break;
1289       case 2:                                       /* top end \/ */
1290         _XFillTriangle(st,color+1, x, y, x+lr, y, x+m2, y+m2);
1291         break;
1292       case 4:                                       /* right end < */
1293         _XFillTriangle(st,color+3, x+lr, y, x+lr, y+lr, x+m2, y+m2);
1294         break;
1295       case 5:                                        /* LR corner */
1296         _XFillTriangle(st,color+1, x, y+m2, x+m2, y+m2, x, y);
1297         _XFillPolygon4(st,color+2, x, y+m2, x+m2, y+m2, x+lr, y+lr, x, y+lr);
1298         break;
1299       case 6:                                        /* UR corner */
1300         _XFillPolygon4(st,color+1, x, y+m2, x+m2, y+m2, x+lr, y, x, y);
1301         _XFillTriangle(st,color+2, x, y+m2, x+m2, y+m2, x, y+lr);
1302         break;
1303       case 7:                                        /* T > into line */
1304         _XFillTriangle(st,color+1, x, y+m2, x+m2, y+m2, x, y);
1305         _XFillTriangle(st,color+2, x, y+m2, x+m2, y+m2, x, y+lr);
1306         break;
1307       case 8:                                       /* left end > */
1308         _XFillTriangle(st,color, x, y, x, y+lr, x+m2, y+m2);
1309         break;
1310       case 9:                                       /* LL corner */
1311         _XFillPolygon4(st,color, x+m2, y, x+m2, y+m2, x, y+lr, x, y);
1312         _XFillTriangle(st,color+3, x+m2, y, x+m2, y+m2, x+lr, y);
1313         break;
1314       case 10:                                      /* UL corner */
1315         _XFillPolygon4(st,color, x+m2, y+nl, x+m2, y+m2, x, y, x, y+nl);
1316         _XFillPolygon4(st,color+3, x+m2, y+nl, x+m2, y+m2, x+lr, y+lr, x+lr, y+nl);
1317         break;
1318       case 11:                                       /* T < into line */
1319         _XFillPolygon4(st,color+1, x+nl, y+m2, x+m2, y+m2, x+lr, y, x+nl, y);
1320         _XFillPolygon4(st,color+2, x+nl, y+m2, x+m2, y+m2, x+lr, y+lr, x+nl, y+lr);
1321         break;
1322       case 13:                                        /* T \/ into line */
1323         _XFillTriangle(st,color, x+m2, y, x+m2, y+m2, x, y);
1324         _XFillTriangle(st,color+3, x+m2, y, x+m2, y+m2, x+lr, y);
1325         break;
1326       case 14:                                        /* T ^ into line */
1327         _XFillPolygon4(st,color, x+m2, y+nl, x+m2, y+m2, x, y+lr, x, y+nl);
1328         _XFillPolygon4(st,color+3, x+m2, y+nl, x+m2, y+m2, x+lr, y+lr, x+lr, y+nl);
1329         break;
1330       case 15:                                        /* X intersection */
1331         _XFillTriangle(st,color+1, x, y+m2, x+m2, y+m2, x, y);
1332         _XFillTriangle(st,color+2, x, y+m2, x+m2, y+m2, x, y+lr);
1333         _XFillPolygon4(st,color+1, x+nl, y+m2, x+m2, y+m2, x+lr, y, x+nl, y);
1334         _XFillPolygon4(st,color+2, x+nl, y+m2, x+m2, y+m2, x+lr, y+lr, x+nl, y+lr);
1335         break;
1336     }
1337     z+=a;
1338   }
1339 }
1340
1341 static long
1342 _mselapsed(struct state *st)
1343 {
1344   struct timeval t;
1345   gettimeofday(&t, NULL);
1346   t.tv_sec -= st->time.tv_sec;
1347   t.tv_usec -= st->time.tv_usec;
1348   return ((long)t.tv_sec*1000000+t.tv_usec);
1349 }
1350
1351 static void
1352 _draw_lines(struct state *st)
1353 {
1354   int n, z, a, color, sh, di;
1355   if (st->bi==1)
1356     for (a=0; a<=st->oi; a++)
1357       st->fdol[a]=0;
1358
1359   for (st->di=st->bi; st->di<_min(st->li+1,st->bi+st->lpu); st->di++) {
1360     color=(st->dline[st->di].color%st->ncolors)*st->shades;
1361     XSetForeground(st->display, st->fgc, st->colors[color].pixel);
1362
1363     switch (st->d3d) {
1364       case D3D_NEON:
1365         st->dline[st->di].ndol=st->fdol[st->dline[st->di].obj];
1366         st->fdol[st->dline[st->di].obj]=st->di;
1367         for (sh=0; sh<st->lwid/2; sh++) {
1368           XSetForeground(st->display, st->fgc,
1369             st->colors[color+sh].pixel);
1370           di=st->di;
1371           while(di>0) {
1372             _XFillRectangle(st,di,sh);
1373             di=st->dline[di].ndol;
1374           }
1375         }
1376         break;
1377       case D3D_BLOCK:
1378         st->dline[st->di].ndol=st->fdol[st->dline[st->di].obj];
1379         st->fdol[st->dline[st->di].obj]=st->di;
1380         for (sh=0; sh<st->lwid/2; sh++) {
1381           XSetForeground(st->display, st->fgc,
1382             st->colors[color+(st->lwid/2)-sh-1].pixel);
1383           di=st->di;
1384           while(di>0) {
1385             _XFillRectangle(st,di,sh);
1386             di=st->dline[di].ndol;
1387           }
1388         }
1389         break;
1390       case D3D_TILED:
1391         _draw_tiled(st,color);
1392         break;
1393       default:               /* D3D_NONE */
1394         _XFillRectangle(st,st->di,0);
1395         if (st->outline) {
1396           _fill_outline(st, st->di);
1397           z=st->dline[st->di].y*st->gridx+st->dline[st->di].x;
1398           a = (st->dline[st->di].hv) ? 1 : st->gridx;
1399           for (n=0; n<=st->dline[st->di].len; n++) {
1400             _fill_outline(st, st->grid[z].dhl);
1401             _fill_outline(st, st->grid[z].dhr);
1402             _fill_outline(st, st->grid[z].dvu);
1403             _fill_outline(st, st->grid[z].dvd);
1404             if (st->dline[st->di].hv) {
1405               if (n)
1406                 st->grid[z].dhr=st->di;
1407               if (n<st->dline[st->di].len)
1408                 st->grid[z].dhl=st->di;
1409             } else {
1410               if (n)
1411                 st->grid[z].dvd=st->di;
1412               if (n<st->dline[st->di].len)
1413                 st->grid[z].dvu=st->di;
1414             }
1415             z+=a;
1416           }
1417         }
1418         break;
1419     }
1420   }
1421   if (st->di>st->li) {
1422       st->bi=1;
1423       st->mode=MODE_CREATE;
1424   } else {
1425       st->bi+=st->lpu;
1426   }
1427 }
1428
1429 static void
1430 _erase_lines(struct state *st)
1431 {
1432   if (!st->ii)
1433     return;
1434   for (st->di=st->bi; st->di<_min(st->eli+1,st->bi+st->elpu); st->di++) {
1435     if (st->eline[st->di].hv) {
1436       XFillRectangle (st->display, st->window, st->bgc,
1437       st->eline[st->di].x*st->elwid,
1438       st->eline[st->di].y*st->elwid,
1439       (st->eline[st->di].len+1)*st->elwid, st->elwid);
1440     } else {
1441       XFillRectangle (st->display, st->window, st->bgc,
1442       st->eline[st->di].x*st->elwid,
1443       st->eline[st->di].y*st->elwid,
1444       st->elwid, (st->eline[st->di].len+1)*st->elwid);
1445     }
1446     if (st->di==st->eli) /* clear just in case */
1447       XFillRectangle(st->display, st->window, st->bgc, 0, 0,
1448         st->xgwa.width, st->xgwa.height);
1449   }
1450   if (st->di>st->eli) {
1451       st->bi=1;
1452       if (st->resized) {
1453          st->mode=MODE_CREATE;
1454       } else {
1455          st->mode=MODE_DRAW;
1456       }
1457   } else {
1458       st->bi+=st->elpu;
1459   }
1460 }
1461
1462 static void *
1463 abstractile_init(Display *display, Window window)
1464 {
1465   struct state *st = (struct state *) calloc (1, sizeof(*st));
1466   XGCValues gcv;
1467 /*  struct utsname os;*/
1468
1469   char *tile = get_string_resource(display, "tile", "Tile");
1470   if      (tile && !strcmp(tile, "random")) st->tile = TILE_RANDOM;
1471   else if (tile && !strcmp(tile, "flat")) st->tile = TILE_FLAT;
1472   else if (tile && !strcmp(tile, "thin")) st->tile = TILE_THIN;
1473   else if (tile && !strcmp(tile, "outline")) st->tile = TILE_OUTLINE;
1474   else if (tile && !strcmp(tile, "block")) st->tile = TILE_BLOCK;
1475   else if (tile && !strcmp(tile, "neon")) st->tile = TILE_NEON;
1476   else if (tile && !strcmp(tile, "tiled")) st->tile = TILE_TILED;
1477   else {
1478     if (tile && *tile && !!strcmp(tile, "random"))
1479       fprintf(stderr, "%s: unknown tile option %s\n", progname, tile);
1480     st->tile = TILE_RANDOM;
1481   }
1482
1483   st->speed = get_integer_resource(display, "speed", "Integer");
1484   if (st->speed < 0) st->speed = 0;
1485   if (st->speed > 5) st->speed = 5;
1486   st->sleep = get_integer_resource(display, "sleep", "Integer");
1487   if (st->sleep < 0) st->sleep = 0;
1488   if (st->sleep > 60) st->sleep = 60;
1489
1490   st->display=display;
1491   st->window=window;
1492
1493   /* get screen size and create Graphics Contexts */
1494   XGetWindowAttributes (display, window, &st->xgwa);
1495   gcv.foreground = get_pixel_resource(display, st->xgwa.colormap,
1496       "foreground", "Foreground");
1497   st->fgc = XCreateGC (display, window, GCForeground, &gcv);
1498   gcv.foreground = get_pixel_resource(display, st->xgwa.colormap,
1499       "background", "Background");
1500   st->bgc = XCreateGC (display, window, GCForeground, &gcv);
1501
1502 /* Um, no. This is obscene. -jwz.
1503   uname(&os);
1504   st->newcols=((!strcmp(os.sysname,"Linux")) || (!strcmp(os.sysname,"Darwin")))
1505       ? True : False;
1506 */
1507   st->newcols=False;
1508
1509   st->mode=MODE_CREATE;
1510   st->ii=0;
1511   st->resized=True;
1512   return st;
1513 }
1514
1515 static unsigned long
1516 abstractile_draw (Display *dpy, Window window, void *closure)
1517 {
1518   struct state *st = (struct state *) closure;
1519   int mse, usleep;
1520
1521   gettimeofday(&st->time, NULL);
1522
1523   /* If the window is too small, do nothing, sorry! */
1524   if (st->xgwa.width > 20 && st->xgwa.height > 20) {
1525     switch (st->mode) {
1526     case MODE_CREATE:
1527       _init_screen(st);
1528       _create_screen(st);
1529       break;
1530     case MODE_ERASE:
1531       _erase_lines(st);
1532       break;
1533     case MODE_DRAW:
1534       _draw_lines(st);
1535       break;
1536     }
1537   }
1538   mse=_mselapsed(st);
1539   usleep = ((!st->ii) && (st->mode==MODE_CREATE)) ?  0 :
1540       (st->mode==MODE_CREATE) ?  st->sleep*1000000-mse :
1541       /* speed=0-5, goal is 10,8,6,4,2,0 sec normal and 5,4,3,2,1,0 dialog */
1542       (5-st->speed)*(2-st->dialog)*100000/st->lpu-mse;
1543   if (usleep>=0)
1544       return usleep;
1545   return 0;
1546 }
1547
1548 static void
1549 abstractile_reshape (Display *dpy, Window window, void *closure,
1550                  unsigned int w, unsigned int h)
1551 {
1552   struct state *st = (struct state *) closure;
1553   st->xgwa.width = w;
1554   st->xgwa.height = h;
1555   if (w*h>st->max_wxh)
1556     st->resized=True;
1557 }
1558
1559 static Bool
1560 abstractile_event (Display *dpy, Window window, void *closure, XEvent *event)
1561 {
1562   return False;
1563 }
1564
1565 static void
1566 abstractile_free (Display *dpy, Window window, void *closure)
1567 {
1568   struct state *st = (struct state *) closure;
1569   free (st);
1570 }
1571
1572 static const char *abstractile_defaults [] = {
1573   ".background:    black",
1574   ".foreground:    white",
1575   "*fpsSolid:      true",
1576   "*sleep:             3",
1577   "*speed:             3",
1578   "*tile:         random",
1579   0
1580 };
1581
1582 static XrmOptionDescRec abstractile_options [] = {
1583   { "-sleep",  ".sleep",  XrmoptionSepArg, 0 },
1584   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
1585   { "-tile",   ".tile",   XrmoptionSepArg, 0 },
1586   { 0, 0, 0, 0 }
1587 };
1588
1589 XSCREENSAVER_MODULE ("Abstractile", abstractile)