From http://www.jwz.org/xscreensaver/xscreensaver-5.38.tar.gz
[xscreensaver] / hacks / glx / flipflop.c
1 /* flipflop, Copyright (c) 2003 Kevin Ogden <kogden1@hotmail.com>
2  *                     (c) 2006 Sergio GutiĆ©rrez "Sergut" <sergut@gmail.com>
3  *                     (c) 2008 Andrew Galante <a.drew7@gmail.com>
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and its
6  * documentation for any purpose is hereby granted without fee, provided that
7  * the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation.  No representations are made about the suitability of this
10  * software for any purpose.  It is provided "as is" without express or
11  * implied warranty.
12  *
13  *
14  * 2003 Kevin Odgen                  First version
15  * 2006 Sergio GutiĆ©rrez "Sergut"    Made several parameters dynamic and selectable
16  *                                   from the command line: size of the board, 
17  *                                   rotation speed and number of free squares; also
18  *                                   added the "sticks" mode.
19  * 2008 Andrew Galante               Added -textured option: textures the board with
20  *                                   an image which gets scrambled as the tiles move
21  *
22  */
23
24 #define DEF_MODE  "tiles" /* Default mode (options: "tiles", "sticks") */
25 #define DEF_SIZEX   "9"     /* Default width of the board */
26 #define DEF_SIZEY   "9"     /* Default length of the board */
27
28 #define DEF_BOARD_SIZE     "0"     /* "0" means "no value selected by user". It is changed */ 
29 #define DEF_NUMSQUARES     "0"     /* in function init_flipflop() to its correct value (that */ 
30 #define DEF_FREESQUARES    "0"     /* is a function of the size of the board and the mode)*/
31
32 #define DEF_SPIN           "0.1"   /* Default angular velocity: PI/10 rads/s    */
33
34 #define DEF_TEXTURED       "False" /* Default: do not grab an image for texturing */
35
36 #define DEF_STICK_THICK   54       /* Thickness for the sticks mode (over 100)  */
37 #define DEF_STICK_RATIO   80       /* Ratio of sticks/total squares (over 100)  */
38 #define DEF_TILE_THICK     4       /* Thickness for the tiles mode (over 100)   */
39 #define DEF_TILE_RATIO    95       /* Ratio of tiles/total squares (over 100)   */
40
41 #ifdef STANDALONE
42 #define DEFAULTS       "*delay:     20000     \n" \
43                        "*showFPS:   False     \n" \
44                        "*wireframe: False     \n"
45
46 # define release_flipflop 0
47 # include "xlockmore.h"
48
49 #else
50 # include "xlock.h"
51 #endif /* STANDALONE */
52
53 #ifdef USE_GL
54
55 #include "gltrackball.h"
56
57 #undef countof
58 #define countof(x) (sizeof((x))/sizeof((*x)))
59
60 static XrmOptionDescRec opts[] = {
61     {"-sticks",         ".mode",            XrmoptionNoArg,  "sticks"},
62     {"-tiles",          ".mode",            XrmoptionNoArg,  "tiles" },
63     {"-mode",           ".mode",            XrmoptionSepArg, 0       },
64     {"-size",           ".size",            XrmoptionSepArg, 0       },
65     {"-size-x",         ".sizex",           XrmoptionSepArg, 0       },
66     {"-size-y",         ".sizey",           XrmoptionSepArg, 0       },
67     {"-count",          ".numsquares",      XrmoptionSepArg, 0       },
68     {"-free",           ".freesquares",     XrmoptionSepArg, 0       },
69     {"-spin",           ".spin",            XrmoptionSepArg, 0       },
70     {"-texture",        ".textured",        XrmoptionNoArg,  "True"  },
71     {"+texture",        ".textured",        XrmoptionNoArg,  "False" },
72 };
73
74 static int wire, clearbits;
75 static int board_x_size, board_y_size, board_avg_size;
76 static int numsquares, freesquares;
77 static float half_thick;
78 static float spin;
79 static char* flipflopmode_str="tiles";
80 static int textured;
81
82 static argtype vars[] = {
83     { &flipflopmode_str, "mode",        "Mode",     DEF_MODE,  t_String},
84     { &board_avg_size,   "size",        "Integer",  DEF_BOARD_SIZE,     t_Int},
85     { &board_x_size,     "sizex",       "Integer",  DEF_SIZEX,   t_Int},
86     { &board_y_size,     "sizey",       "Integer",  DEF_SIZEY,   t_Int},
87     { &numsquares,       "numsquares",  "Integer",  DEF_NUMSQUARES,     t_Int},
88     { &freesquares,      "freesquares", "Integer",  DEF_NUMSQUARES,     t_Int},
89     { &spin,             "spin",        "Float",    DEF_SPIN,           t_Float},
90     { &textured,         "textured",    "Bool",     DEF_TEXTURED,       t_Bool},
91 };
92
93 ENTRYPOINT ModeSpecOpt flipflop_opts = {countof(opts), opts, countof(vars), vars, NULL};
94
95 #ifdef USE_MODULES
96 ModStruct   flipflop_description =
97     {"flipflop", "init_flipflop", "draw_flipflop", NULL,
98      "draw_flipflop", "init_flipflop", "free_flipflop", &flipflop_opts,
99      1000, 1, 2, 1, 4, 1.0, "",
100      "Flipflop", 0, NULL};
101
102 #endif /* USE_MODULES */
103
104 typedef struct {
105     /* array specifying which squares are where (to avoid collisions) */
106     /* -1 means empty otherwise integer represents square index 0 - n-1 */
107         /* occupied[x*board_y_size+y] is the tile [x][y] (i.e. that starts at column x and row y)*/
108     int *occupied; /* size: size_x * size_y */
109     /* an array of xpositions of the squares */
110     int *xpos; /* size: numsquares */
111     /* array of y positions of the squares */
112     int *ypos; /* size: numsquares */
113     /* integer representing the direction of movement of a square */
114     int *direction; /* 0 not, 1 x+, 2 y+, 3 x-, 4 y-*/ /* size: numsquares */
115     /* angle of moving square (during a flip) */
116     float *angle; /* size: numsquares */
117     /* array of colors for a square (RGB) */
118     /* eg. color[ 3*3 + 0 ] is the red   component of square 3 */
119     /* eg. color[ 4*3 + 1 ] is the green component of square 4 */
120     /* eg. color[ 5*3 + 2 ] is the blue  component of square 5 */
121     /*            ^-- n is the number of square */
122     float *color; /* size: numsquares * 3 */
123     /* array of texcoords for each square */
124     /* tex[ n*4 + 0 ] is x texture coordinate of square n's left side */
125     /* tex[ n*4 + 1 ] is y texture coordinate of square n's top side */
126     /* tex[ n*4 + 2 ] is x texture coordinate of square n's right side */
127     /* tex[ n*4 + 3 ] is y texture coordinate of square n's bottom side */
128     float *tex; /* size: numsquares * 4 */
129 } randsheet;
130
131 typedef struct {
132     GLXContext *glx_context;
133     Window window;
134     trackball_state *trackball;
135     Bool button_down_p;
136
137     randsheet *sheet;
138
139     float theta;      /* angle of rotation of the board                */
140     float flipspeed;  /* amount of flip;  1 is a entire flip           */
141     float reldist;    /* relative distace of camera from center        */
142     float energy;     /* likelyhood that a square will attempt to move */
143
144     /* texture rectangle */
145     float tex_x;
146     float tex_y;
147     float tex_width;
148     float tex_height;
149
150     /* id of texture in use */
151     GLuint texid;
152
153     Bool mipmap;
154     Bool got_texture;
155
156     GLfloat anisotropic;
157
158 } Flipflopcreen;
159
160 static Flipflopcreen *qs = NULL;
161
162 #include "grab-ximage.h"
163
164 static void randsheet_create( randsheet *rs );
165 static void randsheet_initialize( randsheet *rs );
166 static void randsheet_free( randsheet *rs );
167 static int  randsheet_new_move( randsheet* rs );
168 static void randsheet_move( randsheet *rs, float rot );
169 static int randsheet_draw( randsheet *rs );
170 static void setup_lights(void);
171 static int drawBoard(Flipflopcreen *);
172 static int display(ModeInfo *mi);
173 static int draw_sheet(float *tex);
174
175
176 /* configure lighting */
177 static void
178 setup_lights(void)
179 {
180     /*   GLfloat position0[] = { board_avg_size*0.5, board_avg_size*0.1, board_avg_size*0.5, 1.0 }; */
181
182     /*   GLfloat position0[] = { -board_avg_size*0.5, 0.2*board_avg_size, -board_avg_size*0.5, 1.0 }; */
183     GLfloat position0[4];
184     position0[0] = 0;
185     position0[1] = board_avg_size*0.3;
186     position0[2] = 0;
187     position0[3] = 1;
188
189     if (wire) return;
190
191     glEnable(GL_LIGHTING);
192     glLightfv(GL_LIGHT0, GL_POSITION, position0);
193     glEnable(GL_LIGHT0);
194 }
195
196 static void get_texture(ModeInfo *);
197
198
199 ENTRYPOINT Bool
200 flipflop_handle_event (ModeInfo *mi, XEvent *event)
201 {
202     Flipflopcreen *c = &qs[MI_SCREEN(mi)];
203
204   if (gltrackball_event_handler (event, c->trackball,
205                                  MI_WIDTH (mi), MI_HEIGHT (mi),
206                                  &c->button_down_p))
207     return True;
208   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
209     {
210       if (!textured || c->got_texture)
211         {
212           textured = 1;
213           c->got_texture = False;
214           get_texture (mi);
215           return True;
216         }
217     }
218
219     return False;
220 }
221
222 /* draw board */
223 static int
224 drawBoard(Flipflopcreen *c)
225 {
226     int i;
227     for( i=0; i < (c->energy) ; i++ ) {
228         randsheet_new_move( c->sheet );
229         }
230     randsheet_move( c->sheet, c->flipspeed * 3.14159 );
231     return randsheet_draw( c->sheet );
232 }
233
234
235 static int
236 display(ModeInfo *mi)
237 {
238     Flipflopcreen *c = &qs[MI_SCREEN(mi)];
239     GLfloat amb[] = { 0.8, 0.8, 0.8, 1.0 };
240     int polys = 0;
241
242
243     glClear(clearbits);
244     glMatrixMode(GL_MODELVIEW);
245     glLoadIdentity();
246     glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.2);
247     glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.15/board_avg_size );
248     glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.15/board_avg_size );
249     glLightfv(GL_LIGHT0, GL_AMBIENT, amb);
250
251
252     glRotatef(current_device_rotation(), 0, 0, 1);
253
254     /** setup perspectif */
255     glTranslatef(0.0, 0.0, -c->reldist*board_avg_size);
256     glRotatef(22.5, 1.0, 0.0, 0.0);  
257     gltrackball_rotate (c->trackball);
258     glRotatef(c->theta*100, 0.0, 1.0, 0.0);
259     glTranslatef(-0.5*board_x_size, 0.0, -0.5*board_y_size); /* Center the board */
260
261     /* set texture */
262     if(textured)
263       glBindTexture(GL_TEXTURE_2D, c->texid);
264
265 # ifdef HAVE_MOBILE     /* Keep it the same relative size when rotated. */
266     {
267       GLfloat h = MI_HEIGHT(mi) / (GLfloat) MI_WIDTH(mi);
268       int o = (int) current_device_rotation();
269       if (o != 0 && o != 180 && o != -180)
270         glScalef (1/h, 1/h, 1/h);
271     }
272 # endif
273
274     polys = drawBoard(c);
275
276     if (!c->button_down_p) {
277         c->theta += .01 * spin;
278     }
279
280     return polys;
281 }
282
283 ENTRYPOINT void
284 reshape_flipflop(ModeInfo *mi, int width, int height)
285 {
286   GLfloat h = (GLfloat) height / (GLfloat) width;
287   int y = 0;
288
289   if (width > height * 5) {   /* tiny window: show middle */
290     height = width * 9/16;
291     y = -height/2;
292     h = height / (GLfloat) width;
293   }
294
295   glViewport(0,y, width, height);
296   glMatrixMode(GL_PROJECTION);
297   glLoadIdentity();
298   gluPerspective(45, 1/h, 1.0, 300.0);
299   glMatrixMode(GL_MODELVIEW);
300 }
301
302 static void
303 image_loaded_cb (const char *filename, XRectangle *geometry,
304                  int image_width, int image_height, 
305                  int texture_width, int texture_height,
306                  void *closure)
307 {
308     Flipflopcreen *c = (Flipflopcreen *)closure;
309     int i, j;
310     int index = 0;
311     randsheet *rs = c->sheet;
312
313     c->tex_x = (float)geometry->x / (float)texture_width;
314     c->tex_y = (float)geometry->y / (float)texture_height;
315     c->tex_width = (float)geometry->width / (float)texture_width; 
316     c->tex_height = (float)geometry->height / (float)texture_height;
317
318     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
319     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
320         (c->mipmap ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR));
321
322     if(c->anisotropic >= 1)
323         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, c->anisotropic);
324
325     glEnable(GL_TEXTURE_2D);
326     glEnable(GL_BLEND);
327     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
328
329     for(i = 0; i < board_x_size && index < numsquares; i++)
330         for(j = 0; j < board_y_size && index < numsquares; j++)
331         {
332             /* arrange squares to form loaded image */
333             rs->tex[ index*4 + 0 ] = c->tex_x + c->tex_width  / board_x_size * (i + 0);
334             rs->tex[ index*4 + 1 ] = c->tex_y + c->tex_height / board_y_size * (j + 1);
335             rs->tex[ index*4 + 2 ] = c->tex_x + c->tex_width  / board_x_size * (i + 1);
336             rs->tex[ index*4 + 3 ] = c->tex_y + c->tex_height / board_y_size * (j + 0);
337             rs->color[ index*3 + 0 ] = 1;
338             rs->color[ index*3 + 1 ] = 1;
339             rs->color[ index*3 + 2 ] = 1;
340             index++;
341         }
342
343     c->got_texture = True;
344 }
345
346 static void
347 get_texture(ModeInfo *modeinfo)
348 {
349     Flipflopcreen *c = &qs[MI_SCREEN(modeinfo)];
350
351     c->got_texture = False;
352     c->mipmap = True;
353     load_texture_async (modeinfo->xgwa.screen, modeinfo->window,
354                       *c->glx_context, 0, 0, c->mipmap, c->texid,
355                       image_loaded_cb, c);
356 }
357
358 ENTRYPOINT void
359 init_flipflop(ModeInfo *mi)
360 {
361     int screen; 
362     Flipflopcreen *c;
363
364     if (MI_IS_WIREFRAME(mi)) textured = 0;
365
366     /* Set all constants to their correct values */
367     if (board_avg_size != 0) {  /* general size specified by user */
368         board_x_size = board_avg_size;
369         board_y_size = board_avg_size;
370     } else {
371         board_avg_size = (board_x_size + board_y_size) / 2;
372     }
373     if ((numsquares == 0) && (freesquares != 0)) {
374         numsquares = board_x_size * board_y_size - freesquares; 
375     }
376     if (strcmp(flipflopmode_str, "tiles")) {
377       textured = 0;  /* textures look dumb in stick mode */
378         half_thick = 1.0 * DEF_STICK_THICK / 100.0; 
379         if (numsquares == 0) {  /* No value defined by user */
380             numsquares = board_x_size * board_y_size * DEF_STICK_RATIO / 100;
381         }
382     } else {
383         half_thick = 1.0 * DEF_TILE_THICK / 100.0; 
384         if (numsquares == 0) {  /* No value defined by user */
385             numsquares = board_x_size * board_y_size * DEF_TILE_RATIO/ 100;;
386         }
387     }
388     if (board_avg_size < 2) {
389         fprintf (stderr,"%s: the board must be at least 2x2.\n", progname);
390         exit(1);
391     }
392     if ((board_x_size < 1) || (board_y_size < 1) ||     (numsquares < 1)) {
393         fprintf (stderr,"%s: the number of elements ('-count') and the dimensions of the board ('-size-x', '-size-y') must be positive integers.\n", progname);
394         exit(1);
395     }
396     if (board_x_size * board_y_size <= numsquares) {
397         fprintf (stderr,"%s: the number of elements ('-count') that you specified is too big \n for the dimensions of the board ('-size-x', '-size-y'). Nothing will move.\n", progname);
398     }
399
400     screen = MI_SCREEN(mi);
401     wire = MI_IS_WIREFRAME(mi);
402
403     MI_INIT(mi, qs);
404
405     c = &qs[screen];
406     c->window = MI_WINDOW(mi);
407     c->trackball = gltrackball_init (False);
408
409     c->flipspeed = 0.03;
410     c->reldist = 1;
411     c->energy = 40;
412
413     if((c->glx_context = init_GL(mi)))
414         reshape_flipflop(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
415     else
416         MI_CLEARWINDOW(mi);
417
418         /* At this point, all the constants have already been set, */
419         /* so we can create the board */
420     c->sheet = (randsheet*) malloc(sizeof(randsheet)); 
421     randsheet_create( c->sheet ); 
422
423     clearbits = GL_COLOR_BUFFER_BIT;
424
425     glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
426     glEnable(GL_COLOR_MATERIAL);
427     setup_lights();
428
429     glEnable(GL_DEPTH_TEST);
430     clearbits |= GL_DEPTH_BUFFER_BIT;
431     glEnable(GL_CULL_FACE);
432     glCullFace(GL_BACK);
433
434     randsheet_initialize( c->sheet );
435     if( textured ){
436         /* check for anisotropic filtering */
437         if(strstr((char *)glGetString(GL_EXTENSIONS),
438             "GL_EXT_texture_filter_anisotropic"))
439             glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &c->anisotropic);
440         else
441             c->anisotropic = 0;
442
443         /* allocate a new texture and get it */
444         glGenTextures(1, &c->texid);
445         get_texture(mi);
446     }
447 }
448
449 ENTRYPOINT void
450 draw_flipflop(ModeInfo *mi)
451 {
452     Flipflopcreen *c = &qs[MI_SCREEN(mi)];
453     Window w = MI_WINDOW(mi);
454     Display *disp = MI_DISPLAY(mi);
455
456     if(!c->glx_context || (textured && !c->got_texture))
457         return;
458
459     glXMakeCurrent(disp, w, *(c->glx_context));
460
461     mi->polygon_count = display(mi);
462
463     if(mi->fps_p){
464         do_fps(mi);
465     }
466
467     glFinish();
468     glXSwapBuffers(disp, w);
469
470
471 }
472
473 ENTRYPOINT void
474 free_flipflop(ModeInfo *mi)
475 {
476   Flipflopcreen *c = &qs[MI_SCREEN(mi)];
477   if (c->sheet) {
478     randsheet_free(c->sheet);
479     free (c->sheet);
480   }
481 }
482
483 /*** ADDED RANDSHEET FUNCTIONS ***/
484
485 static int
486 draw_sheet(float *tex)
487 {
488     int polys = 0;
489     glBegin( wire ? GL_LINE_LOOP : GL_QUADS );
490
491     glNormal3f( 0, -1, 0 );
492     glTexCoord2f(tex[0], tex[3]);
493     glVertex3f( half_thick,  -half_thick,  half_thick );
494     glTexCoord2f(tex[2], tex[3]);
495     glVertex3f( 1-half_thick,   -half_thick, half_thick );
496     glTexCoord2f(tex[2], tex[1]);
497     glVertex3f( 1-half_thick, -half_thick,  1-half_thick);
498     glTexCoord2f(tex[0], tex[1]);
499     glVertex3f( half_thick, -half_thick, 1-half_thick );
500     polys++;
501
502     if (wire) { glEnd(); glBegin (GL_LINE_LOOP); }
503
504     /* back */
505     glNormal3f( 0, 1, 0 );
506     glTexCoord2f(tex[0], tex[1]);
507     glVertex3f( half_thick, half_thick, 1-half_thick );
508     glTexCoord2f(tex[2], tex[1]);
509     glVertex3f( 1-half_thick, half_thick,  1-half_thick);
510     glTexCoord2f(tex[2], tex[3]);
511     glVertex3f( 1-half_thick,   half_thick, half_thick );
512     glTexCoord2f(tex[0], tex[3]);
513     glVertex3f( half_thick,  half_thick,  half_thick );
514     polys++;
515
516     if (wire) { glEnd(); return polys; }
517
518     /* 4 edges!!! weee.... */
519     glNormal3f( 0, 0, -1 );
520     glTexCoord2f(tex[0], tex[3]);
521     glVertex3f( half_thick, half_thick, half_thick );
522     glTexCoord2f(tex[2], tex[3]);
523     glVertex3f( 1-half_thick, half_thick, half_thick );
524     glTexCoord2f(tex[2], tex[3]);
525     glVertex3f( 1-half_thick, -half_thick, half_thick );
526     glTexCoord2f(tex[0], tex[3]);
527     glVertex3f( half_thick, -half_thick, half_thick );
528     polys++;
529     glNormal3f( 0, 0, 1 );
530     glTexCoord2f(tex[0], tex[1]);
531     glVertex3f( half_thick, half_thick, 1-half_thick );
532     glTexCoord2f(tex[0], tex[1]);
533     glVertex3f( half_thick, -half_thick, 1-half_thick );
534     glTexCoord2f(tex[2], tex[1]);
535     glVertex3f( 1-half_thick, -half_thick, 1-half_thick );
536     glTexCoord2f(tex[2], tex[1]);
537     glVertex3f( 1-half_thick, half_thick, 1-half_thick );
538     polys++;
539     glNormal3f( 1, 0, 0 );
540     glTexCoord2f(tex[2], tex[1]);
541     glVertex3f( 1-half_thick, half_thick, 1-half_thick );
542     glTexCoord2f(tex[2], tex[1]);
543     glVertex3f( 1-half_thick, -half_thick, 1-half_thick );
544     glTexCoord2f(tex[2], tex[3]);
545     glVertex3f( 1-half_thick, -half_thick, half_thick );
546     glTexCoord2f(tex[2], tex[3]);
547     glVertex3f( 1-half_thick, half_thick, half_thick );
548     polys++;
549     glNormal3f( -1, 0, 0 );
550     glTexCoord2f(tex[0], tex[1]);
551     glVertex3f( half_thick, half_thick, 1-half_thick );
552     glTexCoord2f(tex[0], tex[3]);
553     glVertex3f( half_thick, half_thick, half_thick );
554     glTexCoord2f(tex[0], tex[3]);
555     glVertex3f( half_thick, -half_thick, half_thick );
556     glTexCoord2f(tex[0], tex[1]);
557     glVertex3f( half_thick, -half_thick, 1-half_thick );
558     polys++;
559     glEnd();
560
561     return polys;
562 }
563
564 /* Reserve memory for the randsheet */
565 static void
566 randsheet_create( randsheet *rs )
567 {
568         rs -> occupied  = (int*) malloc(board_x_size*board_y_size * sizeof(int));
569         rs -> xpos      = (int*) malloc(numsquares * sizeof(int));
570         rs -> ypos      = (int*) malloc(numsquares * sizeof(int));
571         rs -> direction = (int*) malloc(numsquares * sizeof(int));
572         rs -> angle     = (float*) malloc(numsquares * sizeof(float));
573         rs -> color     = (float*) malloc(numsquares*3 * sizeof(float));
574         rs -> tex       = (float*) malloc(numsquares*4 * sizeof(float));
575 }
576
577 /* Free reserved memory for the randsheet */
578 static void
579 randsheet_free( randsheet *rs )
580 {
581         free(rs->occupied);
582         free(rs->xpos);
583         free(rs->ypos);
584         free(rs->direction);
585         free(rs->angle);
586         free(rs->color);
587         free(rs->tex);
588 }
589
590 static void
591 randsheet_initialize( randsheet *rs )
592 {
593     int i, j, index;
594     index = 0;
595     /* put the moving sheets on the board */
596     for( i = 0; i < board_x_size; i++ )
597         {
598             for( j = 0; j < board_y_size; j++ )
599                 {
600                     /* initially fill up a corner with the moving squares */
601                     if( index < numsquares )
602                         {
603                             rs->occupied[ i * board_y_size + j ] = index;
604                             rs->xpos[ index ] = i;
605                             rs->ypos[ index ] = j;
606                                                         /* have the square colors start out as a pattern */
607                                                         rs->color[ index*3 + 0 ] = ((i+j)%3 == 0)||((i+j+1)%3 == 0);
608                                                         rs->color[ index*3 + 1 ] = ((i+j+1)%3 == 0);
609                                                         rs->color[ index*3 + 2 ] = ((i+j+2)%3 == 0);
610                             index++;
611                         }
612                     /* leave everything else empty*/
613                     else
614                         {
615                             rs->occupied[ i * board_y_size + j ] = -1;
616                         }
617                 }
618         }
619     /* initially everything is at rest */
620     for( i=0; i<numsquares; i++ )
621         {
622             rs->direction[ i ] = 0;
623             rs->angle[ i ] = 0;
624         }
625 }
626
627 /* Pick and random square and direction and try to move it. */
628 /* May not actually move anything, just attempt a random move. */
629 /* Returns true if move was sucessful. */
630 /* This could probably be implemented faster in a dequeue */
631 /* to avoid trying to move a square which is already moving */
632 /* but speed is most likely bottlenecked by rendering anyway... */
633 static int
634 randsheet_new_move( randsheet* rs )
635 {
636     int i, j;
637     int num, dir;
638     /* pick a random square */
639     num = random( ) % numsquares;
640     i = rs->xpos[ num ];
641     j = rs->ypos[ num ];
642     /* pick a random direction */
643     dir = ( random( )% 4 ) + 1;
644
645     if( rs->direction[ num ] == 0 )
646         {
647             switch( dir )
648                 {
649                 case 1:
650                     /* move up in x */
651                     if( ( i + 1 ) < board_x_size )
652                         {
653                             if( rs->occupied[ (i + 1) * board_y_size + j ] == -1 )
654                                 {
655                                     rs->direction[ num ] = dir;
656                                     rs->occupied[ (i + 1) * board_y_size + j ] = num;
657                                     rs->occupied[ i * board_y_size + j ] = -1;
658                                     return 1;
659                                 }
660                         }
661                     return 0;
662                     break;
663                 case 2:
664                     /* move up in y */
665                     if( ( j + 1 ) < board_y_size )
666                         {
667                             if( rs->occupied[ i * board_y_size + (j + 1) ] == -1 )
668                                 {
669                                     rs->direction[ num ] = dir;
670                                     rs->occupied[ i * board_y_size + (j + 1) ] = num;
671                                     rs->occupied[ i * board_y_size + j ] = -1;
672                                     return 1;
673                                 }
674                         }
675                     return 0;
676                     break;
677                 case 3:
678                     /* move down in x */
679                     if( ( i - 1 ) >= 0 )
680                         {
681                             if( rs->occupied[ (i - 1) * board_y_size + j ] == -1 )
682                                 {
683                                     rs->direction[ num ] = dir;
684                                     rs->occupied[ (i - 1) * board_y_size + j ] = num;
685                                     rs->occupied[ i * board_y_size + j ] = -1;
686                                     return 1;
687                                 }
688                         }
689                     return 0;
690                     break;
691                 case 4:
692                     /* move down in y */
693                     if( ( j - 1 ) >= 0 )
694                         {
695                             if( rs->occupied[ i * board_y_size + (j - 1) ] == -1 )
696                                 {
697                                     rs->direction[ num ] = dir;
698                                     rs->occupied[ i * board_y_size + (j - 1) ] = num;
699                                     rs->occupied[ i * board_y_size + j ] = -1;
700                                     return 1;
701                                 }
702                         }
703                     return 0;
704                     break;
705                 default:
706                     break;
707                 }
708         }
709     return 0;
710 }
711
712 /*   move a single frame.  */
713 /*   Pass in the angle in rads the square rotates in a frame. */
714 static void
715 randsheet_move( randsheet *rs, float rot )
716 {
717     int index;
718     float tmp;
719     for( index = 0 ; index < numsquares; index++ )
720         {
721             switch( rs->direction[ index ] )
722                 {
723                 case 0:
724                     /* not moving */
725                     break;
726                 case 1:
727                     /* move up in x */
728                     if( textured && rs->angle[ index ] == 0 )
729                         {
730                             tmp = rs->tex[ index * 4 + 0 ];
731                             rs->tex[ index * 4 + 0 ] = rs->tex[ index * 4 + 2 ];
732                             rs->tex[ index * 4 + 2 ] = tmp;
733                         }
734                     rs->angle[ index ] += rot;
735                     /* check to see if we have finished moving */
736                     if( rs->angle[ index ] >= M_PI  )
737                         {
738                             rs->xpos[ index ] += 1;
739                             rs->direction[ index ] = 0;
740                             rs->angle[ index ] = 0;
741                         }
742                     break;
743                 case 2:
744                     /* move up in y */
745                     if( textured && rs->angle[ index ] == 0 )
746                         {
747                             tmp = rs->tex[ index * 4 + 1 ];
748                             rs->tex[ index * 4 + 1 ] = rs->tex[ index * 4 + 3 ];
749                             rs->tex[ index * 4 + 3 ] = tmp;
750                         }
751                     rs->angle[ index ] += rot;
752                     /* check to see if we have finished moving */
753                     if( rs->angle[ index ] >= M_PI  )
754                         {
755                             rs->ypos[ index ] += 1;
756                             rs->direction[ index ] = 0;
757                             rs->angle[ index ] = 0;
758                         }
759                     break;
760                 case 3:
761                     /* down in x */
762                     rs->angle[ index ] += rot;
763                     /* check to see if we have finished moving */
764                     if( rs->angle[ index ] >= M_PI  )
765                         {
766                             rs->xpos[ index ] -= 1;
767                             rs->direction[ index ] = 0;
768                             rs->angle[ index ] = 0;
769                             if( textured )
770                             {
771                                                             tmp = rs->tex[ index * 4 + 0 ];
772                                                             rs->tex[ index * 4 + 0 ] = rs->tex[ index * 4 + 2 ];
773                                                             rs->tex[ index * 4 + 2 ] = tmp;
774                             }
775                         }
776                     break;
777                 case 4:
778                     /* down in y */
779                     rs->angle[ index ] += rot;
780                     /* check to see if we have finished moving */
781                     if( rs->angle[ index ] >= M_PI  )
782                         {
783                             rs->ypos[ index ] -= 1;
784                             rs->direction[ index ] = 0;
785                             rs->angle[ index ] = 0;
786                             if( textured )
787                             {
788                                 tmp = rs->tex[ index * 4 + 1 ];
789                                 rs->tex[ index * 4 + 1 ] = rs->tex[ index * 4 + 3 ];
790                                 rs->tex[ index * 4 + 3 ] = tmp;
791                             }
792                         }
793                     break;
794                 default:
795                     break;
796                 }
797         }
798 }
799
800
801 /* draw all the moving squares  */
802 static int
803 randsheet_draw( randsheet *rs )
804 {
805     int i, j, polys = 0;
806     int index;
807
808     /* for all moving squares ... */
809     for( index = 0; index < numsquares; index++ )
810         {
811             /* set color */
812             glColor3f( rs->color[ index*3 + 0 ],
813                        rs->color[ index*3 + 1 ],
814                        rs->color[ index*3 + 2 ] );
815             /* find x and y position */
816             i = rs->xpos[ index ];
817             j = rs->ypos[ index ];
818             glPushMatrix();
819             switch( rs->direction[ index ] )
820                 {
821                 case 0:
822
823                     /* not moving */
824                     /* front */
825                     glTranslatef( i, 0, j );
826                     break;
827                 case 1:
828                     glTranslatef( i+1, 0, j );
829                     glRotatef( 180 - rs->angle[ index ]*180/M_PI, 0, 0, 1 );
830
831                     break;
832                 case 2:
833                     glTranslatef( i, 0, j+1 );
834                     glRotatef( 180 - rs->angle[ index ]*180/M_PI, -1, 0, 0 );
835
836                     break;
837                 case 3:
838                     glTranslatef( i, 0, j );
839                     glRotatef( rs->angle[ index ]*180/M_PI, 0, 0, 1 );
840                     break;
841                 case 4:
842                     glTranslatef( i, 0, j );
843                     glRotatef( rs->angle[ index ]*180/M_PI, -1, 0, 0 );
844                     break;
845                 default:
846                     break;
847                 }
848             polys += draw_sheet( rs->tex + index*4 );
849             glPopMatrix();
850
851         }
852     return polys;
853 }
854
855 /**** END RANDSHEET_BAK FUNCTIONS ***/
856
857 XSCREENSAVER_MODULE ("FlipFlop", flipflop)
858
859 #endif /* USE_GL */