5b26950a42003ec13f5942520c34e25fab7fae5f
[xscreensaver] / hacks / shadebobs.c
1 /* shadebobs, Copyright (c) 1999 Shane Smit <blackend@inconnect.com>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or
9  * implied warranty.
10  *
11  * Module - "shadebobs.c"
12  *
13  * Description:
14  *  There are two little shading circles (bobs) that zip around the screen.
15  *  one of them shades up towards white, and the other shades down toward
16  *  black.
17  *  This keeps the screen in color balance at a chosen color.
18  *
19  *  Its kinda like 'The Force'
20  *   There is a light side, a dark side, and it keeps the world in balance.
21  *
22  * [05/23/99] - Shane Smit: Creation
23  * [05/26/99] - Shane Smit: Port to C/screenhack for use with XScreenSaver
24  * [06/11/99] - Shane Smit: Stopped trying to rape the palette.
25  * [06/20/99] - jwz: cleaned up ximage handling, gave resoources short names,
26  *                introduced delay, made it restart after N iterations.
27  * [06/21/99] - Shane Smit: Modified default values slightly, color changes
28  *                on cycle, and the extents of the sinus pattern change in
29  *                real-time.
30  * [06/22/99] - Shane Smit: Fixed delay to be fast and use little CPU :).
31  * [09/17/99] - Shane Smit: Made all calculations based on the size of the
32  *                window. Thus, it'll look the same at 100x100 as it does at
33  *                1600x1200 ( Only smaller :).
34  * [04/24/00] - Shane Smit: Revamped entire source code:
35  *                Shade Bob movement is calculated very differently.
36  *                Base color can be any color now.
37  */
38
39
40 #include <math.h>
41 #include "screenhack.h"
42
43 /* #define VERBOSE */
44
45 static const char *shadebobs_defaults [] = {
46   ".background: black",
47   ".foreground: white",
48   "*fpsSolid:   true",
49   "*degrees:  0",       /* default: Automatic degree calculation */
50   "*color:    random",
51   "*count:    4",
52   "*cycles:   10",
53   "*ncolors:  64",    /* changing this doesn't work particularly well */
54   "*delay:    10000",
55   0
56 };
57
58 static XrmOptionDescRec shadebobs_options [] = {
59   { "-degrees", ".degrees", XrmoptionSepArg, 0 },
60   { "-color",   ".color",   XrmoptionSepArg, 0 },
61   { "-ncolors", ".ncolors", XrmoptionSepArg, 0 },
62   { "-count",   ".count",   XrmoptionSepArg, 0 },
63   { "-delay",   ".delay",   XrmoptionSepArg, 0 },
64   { "-cycles",  ".cycles",  XrmoptionSepArg, 0 },
65   { 0, 0, 0, 0 }
66 };
67
68 /* Ahem. Chocolate is a flavor; not a food. Thank you */
69
70
71 typedef struct
72 {
73         signed char *anDeltaMap;
74         double nAngle, nAngleDelta, nAngleInc;
75         double nPosX, nPosY;
76 } SShadeBob;
77
78 struct state {
79   Display *dpy;
80   Window window;
81   unsigned short iDegreeCount;
82   double *anSinTable, *anCosTable;
83   unsigned short iWinWidth, iWinHeight;
84   unsigned short iWinCenterX, iWinCenterY;
85   char *sColor;
86   unsigned char iBobRadius, iBobDiameter; 
87   unsigned char iVelocity;
88
89   unsigned long *aiColorVals;
90   signed short iColorCount;
91   int cycles;
92   XImage *pImage;
93   unsigned char nShadeBobCount, iShadeBob;
94   SShadeBob *aShadeBobs;
95   GC gc;
96   int delay;
97   int draw_i;
98 };
99
100 #define RANDOM() ((int) (random() & 0X7FFFFFFFL))
101
102
103
104 static void ResetShadeBob( struct state *st, SShadeBob *pShadeBob )
105 {
106         pShadeBob->nPosX = RANDOM() % st->iWinWidth;
107         pShadeBob->nPosY = RANDOM() % st->iWinHeight;
108         pShadeBob->nAngle = RANDOM() % st->iDegreeCount;
109         pShadeBob->nAngleDelta = ( RANDOM() % st->iDegreeCount ) - ( st->iDegreeCount / 2.0F );
110         pShadeBob->nAngleInc = pShadeBob->nAngleDelta / 50.0F; 
111         if( pShadeBob->nAngleInc == 0.0F )      
112                 pShadeBob->nAngleInc = ( pShadeBob->nAngleDelta > 0.0F ) ? 0.0001F : -0.0001F;
113 }
114
115
116 static void InitShadeBob( struct state *st, SShadeBob *pShadeBob, Bool bDark )
117 {
118         double nDelta;
119         int iWidth, iHeight;
120
121         if( ( pShadeBob->anDeltaMap = calloc( st->iBobDiameter * st->iBobDiameter, sizeof(char) ) ) == NULL )
122         {
123                 fprintf( stderr, "%s: Could not allocate Delta Map!\n", progname );
124                 return;
125         }
126
127         for( iHeight=-st->iBobRadius; iHeight<st->iBobRadius; iHeight++ )
128                 for( iWidth=-st->iBobRadius; iWidth<st->iBobRadius; iWidth++ )
129                 {
130                         nDelta = 9 - ( ( sqrt( pow( iWidth+0.5, 2 ) + pow( iHeight+0.5, 2 ) ) / st->iBobRadius ) * 8 );
131                         if( nDelta < 0 )  nDelta = 0;
132                         if( bDark ) nDelta = -nDelta;
133                         pShadeBob->anDeltaMap[ ( iWidth + st->iBobRadius ) * st->iBobDiameter + iHeight + st->iBobRadius ] = (char)nDelta;
134                 }
135   
136         ResetShadeBob( st, pShadeBob );
137 }
138
139
140 /* A delta is calculated, and the shadebob turns at an increment.  When the delta
141  * falls to 0, a new delta and increment are calculated. */
142 static void MoveShadeBob( struct state *st, SShadeBob *pShadeBob )
143 {
144         pShadeBob->nAngle          += pShadeBob->nAngleInc;
145         pShadeBob->nAngleDelta -= pShadeBob->nAngleInc;
146
147         if( pShadeBob->nAngle >= st->iDegreeCount )     pShadeBob->nAngle -= st->iDegreeCount;
148         else if( pShadeBob->nAngle < 0 )                pShadeBob->nAngle += st->iDegreeCount;
149         
150         if( ( pShadeBob->nAngleInc>0.0F  && pShadeBob->nAngleDelta<pShadeBob->nAngleInc ) ||
151             ( pShadeBob->nAngleInc<=0.0F && pShadeBob->nAngleDelta>pShadeBob->nAngleInc ) )
152         {
153                 pShadeBob->nAngleDelta = ( RANDOM() % st->iDegreeCount ) - ( st->iDegreeCount / 2.0F );
154                 pShadeBob->nAngleInc = pShadeBob->nAngleDelta / 50.0F;
155                 if( pShadeBob->nAngleInc == 0.0F )
156                         pShadeBob->nAngleInc = ( pShadeBob->nAngleDelta > 0.0F ) ? 0.0001F : -0.0001F;
157         }
158         
159         pShadeBob->nPosX = ( st->anSinTable[ (int)pShadeBob->nAngle ] * st->iVelocity ) + pShadeBob->nPosX;
160         pShadeBob->nPosY = ( st->anCosTable[ (int)pShadeBob->nAngle ] * st->iVelocity ) + pShadeBob->nPosY;
161
162         /* This wraps it around the screen. */
163         if( pShadeBob->nPosX >= st->iWinWidth ) pShadeBob->nPosX -= st->iWinWidth;
164         else if( pShadeBob->nPosX < 0 )         pShadeBob->nPosX += st->iWinWidth;
165         
166         if( pShadeBob->nPosY >= st->iWinHeight )        pShadeBob->nPosY -= st->iWinHeight;
167         else if( pShadeBob->nPosY < 0 )                 pShadeBob->nPosY += st->iWinHeight;
168 }
169
170
171 static void Execute( struct state *st, SShadeBob *pShadeBob )
172 {
173         unsigned long iColor;
174         short iColorVal;
175         int iPixelX, iPixelY;
176         unsigned int iWidth, iHeight;
177
178         MoveShadeBob( st, pShadeBob );
179         
180         for( iHeight=0; iHeight<st->iBobDiameter; iHeight++ )
181         {
182                 iPixelY = pShadeBob->nPosY + iHeight;
183                 if( iPixelY >= st->iWinHeight ) iPixelY -= st->iWinHeight;
184
185                 for( iWidth=0; iWidth<st->iBobDiameter; iWidth++ )
186                 {
187                         iPixelX = pShadeBob->nPosX + iWidth;
188                         if( iPixelX >= st->iWinWidth )  iPixelX -= st->iWinWidth;
189
190                         iColor = XGetPixel( st->pImage, iPixelX, iPixelY );
191
192                         /*  FIXME: Here is a loop I'd love to take out. */
193                         for( iColorVal=0; iColorVal<st->iColorCount; iColorVal++ )
194                                 if( st->aiColorVals[ iColorVal ] == iColor )
195                                         break;
196
197                         iColorVal += pShadeBob->anDeltaMap[ iWidth * st->iBobDiameter + iHeight ];
198                         if( iColorVal >= st->iColorCount ) iColorVal = st->iColorCount - 1;
199                         if( iColorVal < 0 )                        iColorVal = 0;
200
201                         XPutPixel( st->pImage, iPixelX, iPixelY, st->aiColorVals[ iColorVal ] );
202                 }
203         }
204
205         /* FIXME: if it's next to the top or left sides of screen this will break. However, it's not noticable. */
206         XPutImage( st->dpy, st->window, st->gc, st->pImage,
207              pShadeBob->nPosX, pShadeBob->nPosY, pShadeBob->nPosX, pShadeBob->nPosY, st->iBobDiameter, st->iBobDiameter );
208 }
209
210
211 static void CreateTables( struct state *st, unsigned int nDegrees )
212 {
213         double nRadian;
214         unsigned int iDegree;
215         st->anSinTable = calloc( nDegrees, sizeof(double) );
216         st->anCosTable = calloc( nDegrees, sizeof(double) );
217
218         for( iDegree=0; iDegree<nDegrees; iDegree++ )
219         {
220                 nRadian = ( (double)(2*iDegree) / (double)nDegrees ) * M_PI;
221                 st->anSinTable[ iDegree ] = sin( nRadian );
222                 st->anCosTable[ iDegree ] = cos( nRadian );
223         }
224 }
225
226
227 static unsigned long * SetPalette(struct state *st )
228 {
229         XWindowAttributes XWinAttribs;
230         XColor Color, *aColors;
231         signed short iColor;
232         float nHalfColors;
233         
234         XGetWindowAttributes( st->dpy, st->window, &XWinAttribs );
235         
236         Color.red =   RANDOM() % 0xFFFF;
237         Color.green = RANDOM() % 0xFFFF;
238         Color.blue =  RANDOM() % 0xFFFF;
239
240         if( strcasecmp( st->sColor, "random" ) && !XParseColor( st->dpy, XWinAttribs.colormap, st->sColor, &Color ) )
241                 fprintf( stderr, "%s: color %s not found in database. Choosing to random...\n", progname, st->sColor );
242
243 #ifdef VERBOSE
244         printf( "%s: Base color (RGB): <%d, %d, %d>\n", progname, Color.red, Color.green, Color.blue );
245 #endif  /*  VERBOSE */
246
247         st->iColorCount = get_integer_resource(st->dpy,  "ncolors", "Integer" );
248         if( st->iColorCount <   2 )     st->iColorCount = 2;
249         if( st->iColorCount > 255 )     st->iColorCount = 255;
250
251         aColors    = calloc( st->iColorCount, sizeof(XColor) );
252         st->aiColorVals = calloc( st->iColorCount, sizeof(unsigned long) );
253         
254         for( iColor=0; iColor<st->iColorCount; iColor++ )
255         {
256                 nHalfColors = st->iColorCount / 2.0F;
257                 /* Black -> Base Color */
258                 if( iColor < (st->iColorCount/2) )
259                 {
260                         aColors[ iColor ].red   = ( Color.red   / nHalfColors ) * iColor;
261                         aColors[ iColor ].green = ( Color.green / nHalfColors ) * iColor;
262                         aColors[ iColor ].blue  = ( Color.blue  / nHalfColors ) * iColor;
263                 }
264                 /* Base Color -> White */
265                 else
266                 {
267                         aColors[ iColor ].red   = ( ( ( 0xFFFF - Color.red )   / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.red;
268                         aColors[ iColor ].green = ( ( ( 0xFFFF - Color.green ) / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.green;
269                         aColors[ iColor ].blue  = ( ( ( 0xFFFF - Color.blue )  / nHalfColors ) * ( iColor - nHalfColors ) ) + Color.blue;
270                 }
271
272                 if( !XAllocColor( st->dpy, XWinAttribs.colormap, &aColors[ iColor ] ) )
273                 {
274                         /* start all over with less colors */   
275                         XFreeColors( st->dpy, XWinAttribs.colormap, st->aiColorVals, iColor, 0 );
276                         free( aColors );
277                         free( st->aiColorVals );
278                         st->iColorCount--;
279                         aColors     = calloc( st->iColorCount, sizeof(XColor) );
280                         st->aiColorVals = calloc( st->iColorCount, sizeof(unsigned long) );
281                         iColor = -1;
282                 }
283                 else
284                         st->aiColorVals[ iColor ] = aColors[ iColor ].pixel;
285         }
286
287         free( aColors );
288
289         XSetWindowBackground( st->dpy, st->window, st->aiColorVals[ 0 ] );
290
291         return st->aiColorVals;
292 }
293
294
295 static void Initialize( struct state *st )
296 {
297         XGCValues gcValues;
298         XWindowAttributes XWinAttribs;
299         int iBitsPerPixel;
300
301         /* Create the Image for drawing */
302         XGetWindowAttributes( st->dpy, st->window, &XWinAttribs );
303
304         /* Find the preferred bits-per-pixel. (jwz) */
305         {
306                 int i, pfvc = 0;
307                 XPixmapFormatValues *pfv = XListPixmapFormats( st->dpy, &pfvc );
308                 for( i=0; i<pfvc; i++ )
309                         if( pfv[ i ].depth == XWinAttribs.depth )
310                         {
311                                 iBitsPerPixel = pfv[ i ].bits_per_pixel;
312                                 break;
313                         }
314                 if( pfv )
315                         XFree (pfv);
316         }
317
318         /*  Create the GC. */
319         st->gc = XCreateGC( st->dpy, st->window, 0, &gcValues );
320
321         st->pImage = XCreateImage( st->dpy, XWinAttribs.visual, XWinAttribs.depth, ZPixmap, 0, NULL,
322                                                           XWinAttribs.width, XWinAttribs.height, 8 /*BitmapPad( st->dpy )*/, 0 );
323         st->pImage->data = calloc((st->pImage)->bytes_per_line, (st->pImage)->height);
324
325         st->iWinWidth = XWinAttribs.width;
326         st->iWinHeight = XWinAttribs.height;
327
328         /*  These are precalculations used in Execute(). */
329         st->iBobDiameter = ( ( st->iWinWidth < st->iWinHeight ) ? st->iWinWidth : st->iWinHeight ) / 25;
330         st->iBobRadius = st->iBobDiameter / 2;
331 #ifdef VERBOSE
332         printf( "%s: Bob Diameter = %d\n", progname, st->iBobDiameter );
333 #endif
334
335         st->iWinCenterX = ( XWinAttribs.width / 2 ) - st->iBobRadius;
336         st->iWinCenterY = ( XWinAttribs.height / 2 ) - st->iBobRadius;
337
338         st->iVelocity = ( ( st->iWinWidth < st->iWinHeight ) ? st->iWinWidth : st->iWinHeight ) / 150;
339         
340         /*  Create the Sin and Cosine lookup tables. */
341         st->iDegreeCount = get_integer_resource(st->dpy,  "degrees", "Integer" );
342         if(      st->iDegreeCount == 0   ) st->iDegreeCount = ( XWinAttribs.width / 6 ) + 400;
343         else if( st->iDegreeCount < 90   ) st->iDegreeCount = 90;
344         else if( st->iDegreeCount > 5400 ) st->iDegreeCount = 5400;
345         CreateTables( st, st->iDegreeCount );
346 #ifdef VERBOSE
347         printf( "%s: Using a %d degree circle.\n", progname );
348 #endif /* VERBOSE */
349   
350         /*  Get the base color. */
351         st->sColor = get_string_resource(st->dpy,  "color", "Color" );
352 }
353
354
355 static void *
356 shadebobs_init (Display *dpy, Window window)
357 {
358   struct state *st = (struct state *) calloc (1, sizeof(*st));
359
360 #ifdef VERBOSE
361         time_t nTime = time( NULL );
362         unsigned short iFrame = 0;
363 #endif  /*  VERBOSE */
364
365   st->dpy = dpy;
366   st->window = window;
367
368         st->nShadeBobCount = get_integer_resource(st->dpy,  "count", "Integer" );
369         if( st->nShadeBobCount > 64 ) st->nShadeBobCount = 64;
370         if( st->nShadeBobCount <  1 ) st->nShadeBobCount = 1;
371
372         if( ( st->aShadeBobs = calloc( st->nShadeBobCount, sizeof(SShadeBob) ) ) == NULL )
373         {
374                 fprintf( stderr, "%s: Could not allocate %d ShadeBobs\n", progname, st->nShadeBobCount );
375                 abort();
376         }
377 #ifdef VERBOSE 
378         printf( "%s: Allocated %d ShadeBobs\n", progname, st->nShadeBobCount );
379 #endif  /*  VERBOSE */
380
381         Initialize( st );
382
383         for( st->iShadeBob=0; st->iShadeBob<st->nShadeBobCount; st->iShadeBob++ )
384                 InitShadeBob( st, &st->aShadeBobs[ st->iShadeBob ], st->iShadeBob % 2 );
385
386         st->delay = get_integer_resource(st->dpy,  "delay", "Integer" );
387         st->cycles = get_integer_resource(st->dpy,  "cycles", "Integer" ) * st->iDegreeCount;
388
389         st->draw_i = 99999999;
390         return st;
391 }
392
393 static unsigned long
394 shadebobs_draw (Display *dpy, Window window, void *closure)
395 {
396   struct state *st = (struct state *) closure;
397
398   if( st->draw_i++ >= st->cycles )
399     {
400       XWindowAttributes XWinAttribs;
401       XGetWindowAttributes( st->dpy, st->window, &XWinAttribs );
402
403       st->draw_i = 0;
404 #if 0
405       memset( st->pImage->data, 0, st->pImage->bytes_per_line * st->pImage->height );
406 #else
407       {
408         /* fill the image with the actual value of the black pixel, not 0. */
409         unsigned long black = BlackPixelOfScreen (XWinAttribs.screen);
410         int x, y;
411         for (y = 0; y < XWinAttribs.height; y++)
412           for (x = 0; x < XWinAttribs.width; x++)
413             XPutPixel (st->pImage, x, y, black);
414       }
415 #endif
416
417       for( st->iShadeBob=0; st->iShadeBob<st->nShadeBobCount; st->iShadeBob++ )
418         ResetShadeBob( st, &st->aShadeBobs[ st->iShadeBob ] );
419       XFreeColors( st->dpy, XWinAttribs.colormap, st->aiColorVals, st->iColorCount, 0 );
420       free( st->aiColorVals );
421       st->aiColorVals = SetPalette( st );
422       XClearWindow( st->dpy, st->window );
423     }
424
425   for( st->iShadeBob=0; st->iShadeBob<st->nShadeBobCount; st->iShadeBob++ )
426     Execute( st, &st->aShadeBobs[ st->iShadeBob ] );
427
428 #ifdef VERBOSE
429   iFrame++;
430   if( nTime - time( NULL ) )
431     {
432       printf( "%s: %d FPS\n", progname, iFrame );
433       nTime = time( NULL );
434       iFrame = 0;
435     }
436 #endif  /*  VERBOSE */
437
438   return st->delay;
439 }
440
441 static void
442 shadebobs_reshape (Display *dpy, Window window, void *closure, 
443                  unsigned int w, unsigned int h)
444 {
445 }
446
447 static Bool
448 shadebobs_event (Display *dpy, Window window, void *closure, XEvent *event)
449 {
450   return False;
451 }
452
453 static void
454 shadebobs_free (Display *dpy, Window window, void *closure)
455 {
456   struct state *st = (struct state *) closure;
457         free( st->anSinTable );
458         free( st->anCosTable );
459         /* free( st->pImage->data ); */
460         XDestroyImage( st->pImage );
461         for( st->iShadeBob=0; st->iShadeBob<st->nShadeBobCount; st->iShadeBob++ )
462                 free( st->aShadeBobs[ st->iShadeBob ].anDeltaMap );
463         free( st->aShadeBobs );
464         free( st->aiColorVals );
465 }
466
467
468 XSCREENSAVER_MODULE ("ShadeBobs", shadebobs)
469
470 /* End of Module - "shadebobs.c" */
471
472 /* vim: ts=4
473  */