1 /* -*- Mode: C; tab-width: 2 -*- */
2 /* glcells --- Cells growing on your screen */
5 * Cells growing on your screen
7 * Copyright (c) 2007 by Matthias Toussaint
9 * Permission to use, copy, modify, and distribute this software and its
10 * documentation for any purpose and without fee is hereby granted,
11 * provided that the above copyright notice appear in all copies and that
12 * both that copyright notice and this permission notice appear in
13 * supporting documentation.
15 * This file is provided AS IS with no warranties of any kind. The author
16 * shall have no liability with respect to the infringement of copyrights,
17 * trade secrets or any patents by this file or any part thereof. In no
18 * event will the author be liable for any lost revenue or profits or
19 * other special, indirect and consequential damages.
21 * 2007: Written by Matthias Toussaint
23 * 0.2 Bugfixes (threading) and code cleanup by Jamie Zawinski
24 * Window scaling bug + performance bug in tick()
27 #include <sys/time.h> /* gettimeofday */
29 #include "xlockmore.h"
32 /**********************************
34 **********************************/
36 #define INDEX_OFFSET 100000
37 #define NUM_CELL_SHAPES 10
39 #define refresh_glcells 0
40 #define glcells_handle_event 0
42 #define DEF_DELAY "20000"
43 #define DEF_MAXCELLS "800"
44 #define DEF_RADIUS "40"
46 #define DEF_QUALITY "3"
47 #define DEF_KEEPOLD "False"
48 #define DEF_MINFOOD "5"
49 #define DEF_MAXFOOD "20"
50 #define DEF_DIVIDEAGE "20"
51 #define DEF_MINDIST "1.4"
52 #define DEF_PAUSE "50"
54 #define DEFAULTS "*delay: 30000 \n" \
55 "*showFPS: False \n" \
56 "*wireframe: False \n" \
59 #define countof(x) (sizeof((x))/sizeof((*x)))
61 #define USE_VERTEX_ARRAY
65 /**********************************
67 **********************************/
69 typedef struct /* a 3-D vector */
71 double x, y, z; /* 3-D coordinates (we don't need w here) */
74 typedef struct /* a triangle (indexes of vertexes in some list) */
76 int i[3]; /* the three indexes for the triangle corners */
87 typedef struct /* an 3-D object without normal vectors */
89 Vector *vertex; /* the vertexes */
90 Triangle *triangle; /* triangle list */
91 int num_vertex; /* number of vertexes */
92 int num_triangle; /* number of triangles */
95 typedef struct /* an 3-D object with smooth normal vectors */
97 Vector *vertex; /* the vertexes */
98 Vector *normal; /* the vertex normal vectors */
99 Triangle *triangle; /* triangle list */
100 int num_vertex; /* number of vertexes */
101 int num_triangle; /* number of triangles */
104 typedef struct /* Cell */
106 double x, y; /* position */
107 double vx, vy; /* movement vector */
108 int age; /* cells age */
109 double min_dist; /* minimum distance to other cells */
110 int energy; /* health */
111 double rotation; /* random rot, so they don't look all the same */
112 double radius; /* current size of cell */
113 double growth; /* current growth rate. might be <1.0 while dividing,
114 >1.0 when finished dividing and food is available
115 and 1.0 when grown up */
118 typedef struct /* hacks state */
120 GLXContext *glx_context;
121 int width, height; /* current size of viewport */
122 double screen_scale; /* we scale content with window size */
123 int num_cells; /* current number of cell in list */
124 Cell *cell; /* array of cells */
126 GLfloat color[4]; /* current cell color */
127 double radius; /* cell radius */
128 int move_dist; /* min distance from neighbours for forking */
129 int max_cells; /* maximum number of cells */
130 int num_seeds; /* number of initial seeds */
131 int keep_old_cells; /* draw dead cells? */
132 int divide_age; /* min age for division */
133 /* display lists for the cell stages */
134 int cell_list[NUM_CELL_SHAPES];
136 int minfood; /* minimum amount of food per area unit */
137 int maxfood; /* maximum amount of food per area unit */
138 int pause; /* pause at end (all cells dead) */
140 int wire; /* draw wireframe? */
141 Object *sphere; /* the raw undisturbed sphere */
142 double *disturbance; /* disturbance values for the vertexes */
143 int *food; /* our petri dish (e.g. screen) */
144 GLubyte *texture; /* texture data for nucleus */
145 GLuint texture_name; /* texture name for binding */
148 /**********************************
150 **********************************/
152 static State *sstate = NULL;
154 static XrmOptionDescRec opts[] = {
155 { "-maxcells", ".maxcells", XrmoptionSepArg, 0 },
156 { "-radius", ".radius", XrmoptionSepArg, 0 },
157 { "-seeds", ".seeds", XrmoptionSepArg, 0 },
158 { "-quality", ".quality", XrmoptionSepArg, 0 },
159 { "-minfood", ".minfood", XrmoptionSepArg, 0 },
160 { "-maxfood", ".maxfood", XrmoptionSepArg, 0 },
161 { "-divideage", ".divideage", XrmoptionSepArg, 0 },
162 { "-mindist", ".mindist", XrmoptionSepArg, 0 },
163 { "-pause", ".pause", XrmoptionSepArg, 0 },
164 { "-keepold", ".keepold", XrmoptionNoArg, "True" }
167 static int s_maxcells;
170 static int s_quality;
171 static int s_minfood;
172 static int s_maxfood;
173 static int s_divideage;
175 static float s_min_dist;
176 static Bool s_keepold;
178 static argtype vars[] = {
179 {&s_maxcells, "maxcells", "Max Cells", DEF_MAXCELLS, t_Int},
180 {&s_radius, "radius", "Radius", DEF_RADIUS, t_Int},
181 {&s_seeds, "seeds", "Seeds", DEF_SEEDS, t_Int},
182 {&s_quality, "quality", "Quality", DEF_QUALITY, t_Int},
183 {&s_minfood, "minfood", "Min Food", DEF_MINFOOD, t_Int},
184 {&s_maxfood, "maxfood", "Max Food", DEF_MAXFOOD, t_Int},
185 {&s_pause, "pause", "Pause at end", DEF_PAUSE, t_Int},
186 {&s_divideage, "divideage", "Age for duplication (Ticks)", DEF_DIVIDEAGE, t_Int},
187 {&s_min_dist, "mindist", "Minimum prefered distance to other cells", DEF_MINDIST, t_Float},
188 {&s_keepold, "keepold", "Keep old cells", DEF_KEEPOLD, t_Bool}
191 /**********************************
193 **********************************/
196 static int render( State *st );
197 /* create initial cells and fill petri dish with food */
198 static void create_cells( State * );
199 /* do one animation step */
200 static void tick( State *st );
201 /* draw a single cell */
202 static void draw_cell( State *st, int shape );
203 /* draw cells nucleus */
204 static void draw_nucleus( State *st );
205 /* return randum number in the interval min-max */
206 static int random_interval( int min, int max );
207 /* retunr random number in the interval 0-max */
208 static int random_max( int max );
209 /* create display list for given disturbance weighting factor */
210 static int create_list( State *st, double fac );
211 /* return length of vector */
212 static double vector_length( Vector * );
213 /* normalize vector */
214 static void vector_normalize( Vector * );
216 static void vector_add( Vector *a, Vector *b );
218 static void vector_sub( Vector *a, Vector *b );
220 static void vector_mul( Vector *a, double fac );
221 /* a.x = a.y = a.z = 0 */
222 static void vector_clear( Vector *a );
223 /* return crossproduct a*b in out */
224 static void vector_crossprod( Vector *a, Vector *b, Vector *out );
225 /* return 1 if vectors are equal (epsilon compare) otherwise 0 */
226 static int vector_compare( Vector *a, Vector *b );
227 /* compute normal vector of given triangle and return in out */
228 static void triangle_normal( Vector *a, Vector *b, Vector *c, Vector *out );
229 /* take an Object and create an ObjectSmooth out of it */
230 static ObjectSmooth *create_ObjectSmooth( Object * );
231 /* Subdivide the Object once (assuming it's supposed to be a shpere */
232 static Object *subdivide( Object *obj );
234 static void free_Object( Object * );
235 /* free an ObjectSmooth */
236 static void free_ObjectSmooth( ObjectSmooth * );
237 /* scale an Object. return pointer to the object */
238 /*static Object *scale_Object( Object *obj, double scale );*/
239 /* create a perfect sphere refining with divisions */
240 static Object *create_sphere( State *st, int divisions );
241 /* make a copy of the given Object */
242 static Object *clone_Object( Object * );
243 /* return 1 if cell is capable to divide */
244 static int can_divide( State *st, Cell *cell );
245 static VertexArray *array_from_ObjectSmooth( ObjectSmooth * );
246 static void create_nucleus_texture( State *st );
248 ENTRYPOINT ModeSpecOpt glcells_opts = { countof(opts), opts, countof(vars), vars,
252 /**********************************
254 **********************************/
255 /* create random numbers
257 static inline int random_interval( int min, int max )
261 return min+(random()%n);
264 static inline int random_max( int max )
273 static inline void vector_add( Vector *a, Vector *b )
281 static inline void vector_sub( Vector *a, Vector *b )
289 static inline void vector_mul( Vector *a, double v )
297 static inline void vector_clear( Vector *vec )
299 vec->x = vec->y = vec->z = 0;
302 /* return vector length */
303 static inline double vector_length( Vector *vec )
305 return sqrt( vec->x*vec->x + vec->y*vec->y + vec->z*vec->z );
308 /* normalize vector */
309 static inline void vector_normalize( Vector *vec )
311 double len = vector_length( vec );
314 vector_mul( vec, 1.0 / len );
319 static inline void vector_crossprod( Vector *a, Vector *b, Vector *out )
321 out->x = a->y*b->z - a->z*b->y;
322 out->y = a->z*b->x - a->x*b->z;
323 out->z = a->x*b->y - a->y*b->x;
326 /* epsilon compare of two vectors */
327 static inline int vector_compare( Vector *a, Vector *b )
329 const double epsilon = 0.0000001;
332 vector_sub( &delta, b );
333 if (fabs(delta.x) < epsilon &&
334 fabs(delta.y) < epsilon &&
335 fabs(delta.z) < epsilon) {
342 /* check if given cell is capable of dividing
343 needs space, must be old enough, grown up and healthy
345 static inline int can_divide( State *st, Cell *cell )
347 if (cell->min_dist > st->move_dist &&
348 cell->age >= st->divide_age &&
349 cell->radius > 0.99 * st->radius &&
357 /**********************************
359 **********************************/
361 /* compute normal vector of given
362 triangle spanned by the points a, b, c
364 static void triangle_normal( Vector *a, Vector *b, Vector *c, Vector *out )
369 vector_sub( &v1, b );
370 vector_sub( &v2, c );
371 vector_crossprod( &v1, &v2, out );
375 static void free_Object( Object *obj )
378 free( obj->triangle );
382 static void free_ObjectSmooth( ObjectSmooth *obj )
385 free( obj->triangle );
390 /* scale the given Object */
392 static Object *scale_Object( Object *obj, double scale )
396 for (v=0; v<obj->num_vertex; ++v) {
397 vector_mul( &obj->vertex[v], scale );
404 /* create a copy of the given Object */
405 static Object *clone_Object( Object *obj )
408 Object *ret = (Object *) malloc( sizeof( Object ) );
411 (Vector *) malloc( obj->num_vertex*sizeof(Vector) );
413 (Triangle *) malloc( obj->num_triangle*sizeof(Triangle) );
414 ret->num_vertex = obj->num_vertex;
415 ret->num_triangle = obj->num_triangle;
417 memcpy( ret->vertex, obj->vertex,
418 obj->num_vertex*sizeof(Vector) );
419 memcpy( ret->triangle, obj->triangle,
420 obj->num_triangle*sizeof(Triangle) );
425 static VertexArray *array_from_ObjectSmooth( ObjectSmooth *obj )
428 VertexArray *array = (VertexArray *) malloc( sizeof( VertexArray ) );
430 array->vertex = (float *) malloc( 3*sizeof(float)*obj->num_vertex );
431 array->normal = (float *) malloc( 3*sizeof(float)*obj->num_vertex );
432 array->index = (unsigned *) malloc( 3*sizeof(unsigned)*obj->num_triangle );
433 array->num_index = obj->num_triangle*3;
435 for (i=0, j=0; i<obj->num_vertex; ++i) {
436 array->vertex[j] = obj->vertex[i].x;
437 array->normal[j++] = obj->normal[i].x;
438 array->vertex[j] = obj->vertex[i].y;
439 array->normal[j++] = obj->normal[i].y;
440 array->vertex[j] = obj->vertex[i].z;
441 array->normal[j++] = obj->normal[i].z;
444 for (i=0, j=0; i<obj->num_triangle; ++i) {
445 array->index[j++] = obj->triangle[i].i[0];
446 array->index[j++] = obj->triangle[i].i[1];
447 array->index[j++] = obj->triangle[i].i[2];
453 /* create a smoothed version of the given Object
454 by computing average normal vectors for the vertexes
456 static ObjectSmooth *create_ObjectSmooth( Object *obj )
460 (Vector *) malloc( obj->num_triangle*sizeof(Vector) );
462 (ObjectSmooth *) malloc( sizeof( ObjectSmooth ) );
464 /* fill in vertexes and triangles */
465 ret->num_vertex = obj->num_vertex;
466 ret->num_triangle = obj->num_triangle;
468 (Vector *) malloc( obj->num_vertex * sizeof( Vector ) );
470 (Vector *) malloc( obj->num_vertex * sizeof( Vector ) );
472 (Triangle *) malloc( obj->num_triangle * sizeof( Triangle ) );
474 for (v=0; v<obj->num_vertex; ++v) {
475 ret->vertex[v] = obj->vertex[v];
478 for (t=0; t<obj->num_triangle; ++t) {
479 ret->triangle[t] = obj->triangle[t];
482 /* create normals (triangles) */
483 for (t=0; t<ret->num_triangle; ++t) {
484 triangle_normal( &ret->vertex[ret->triangle[t].i[0]],
485 &ret->vertex[ret->triangle[t].i[1]],
486 &ret->vertex[ret->triangle[t].i[2]],
490 /* create normals (vertex) by averaging triangle
493 for (v=0; v<ret->num_vertex; ++v) {
494 vector_clear( &ret->normal[v] );
495 for (t=0; t<ret->num_triangle; ++t) {
496 for (i=0; i<3; ++i) {
497 if (ret->triangle[t].i[i] == v) {
498 vector_add( &ret->normal[v], &t_normal[t] );
502 /* as we have only a half sphere we force the
503 normals at the bortder to be perpendicular to z.
504 the simple algorithm above makes an error here.
506 if (fabs(ret->vertex[v].z) < 0.0001) {
507 ret->normal[v].z = 0.0;
510 vector_normalize( &ret->normal[v] );
518 /* subdivide the triangles of the object once
519 The order of this algorithm is probably something like O(n^42) :)
520 but I can't think of something smarter at the moment
522 static Object *subdivide( Object *obj )
524 /* create for worst case (which I dont't know) */
526 int index_list[1000];
527 int index_cnt, index_found;
528 Object *tmp = (Object *)malloc( sizeof(Object) );
529 Object *ret = (Object *)malloc( sizeof(Object) );
533 (Vector *)malloc( 100*obj->num_vertex*sizeof( Vector ) );
535 (Triangle *)malloc( 4*obj->num_triangle*sizeof( Triangle ) );
537 tmp->num_triangle = 0;
539 (Vector *)malloc( 100*obj->num_vertex*sizeof( Vector ) );
541 (Triangle *)malloc( 4*obj->num_triangle*sizeof( Triangle ) );
543 ret->num_triangle = 0;
545 fprintf( stderr, "in v=%d t=%d\n",
546 obj->num_vertex, obj->num_triangle );
548 /* for each triangle create 3 new vertexes and the 4
549 corresponding triangles
551 for (t=0; t<obj->num_triangle; ++t) {
552 /* copy the three original vertexes */
553 for (i=0; i<3; ++i) {
554 tmp->vertex[tmp->num_vertex++] =
555 obj->vertex[obj->triangle[t].i[i]];
559 tmp->vertex[tmp->num_vertex] =
560 obj->vertex[obj->triangle[t].i[0]];
561 vector_add( &tmp->vertex[tmp->num_vertex],
562 &obj->vertex[obj->triangle[t].i[1]] );
563 vector_mul( &tmp->vertex[tmp->num_vertex++], 0.5 );
565 tmp->vertex[tmp->num_vertex] =
566 obj->vertex[obj->triangle[t].i[1]];
567 vector_add( &tmp->vertex[tmp->num_vertex],
568 &obj->vertex[obj->triangle[t].i[2]] );
569 vector_mul( &tmp->vertex[tmp->num_vertex++], 0.5 );
571 tmp->vertex[tmp->num_vertex] =
572 obj->vertex[obj->triangle[t].i[2]];
573 vector_add( &tmp->vertex[tmp->num_vertex],
574 &obj->vertex[obj->triangle[t].i[0]] );
575 vector_mul( &tmp->vertex[tmp->num_vertex++], 0.5 );
577 /* create triangles */
578 start = tmp->num_vertex-6;
580 tmp->triangle[tmp->num_triangle].i[0] = start;
581 tmp->triangle[tmp->num_triangle].i[1] = start+3;
582 tmp->triangle[tmp->num_triangle++].i[2] = start+5;
584 tmp->triangle[tmp->num_triangle].i[0] = start+3;
585 tmp->triangle[tmp->num_triangle].i[1] = start+1;
586 tmp->triangle[tmp->num_triangle++].i[2] = start+4;
588 tmp->triangle[tmp->num_triangle].i[0] = start+5;
589 tmp->triangle[tmp->num_triangle].i[1] = start+4;
590 tmp->triangle[tmp->num_triangle++].i[2] = start+2;
592 tmp->triangle[tmp->num_triangle].i[0] = start+3;
593 tmp->triangle[tmp->num_triangle].i[1] = start+4;
594 tmp->triangle[tmp->num_triangle++].i[2] = start+5;
597 /* compress object eliminating double vertexes
598 (welcome to the not so smart section)
600 /* copy original triangle list */
601 for (t=0; t<tmp->num_triangle; ++t) {
602 ret->triangle[t] = tmp->triangle[t];
604 ret->num_triangle = tmp->num_triangle;
606 /* copy unique vertexes and correct triangle list */
607 for (v=0; v<tmp->num_vertex; ++v) {
608 /* create list of vertexes that are the same */
610 for (i=0; i<tmp->num_vertex; ++i) {
611 /* check if i and v are the same
612 first in the list is the smallest index
614 if (vector_compare( &tmp->vertex[v], &tmp->vertex[i] )) {
615 index_list[index_cnt++] = i;
619 /* check if vertex unknown so far */
621 for (i=0; i<ret->num_vertex; ++i) {
622 if (vector_compare( &ret->vertex[i],
623 &tmp->vertex[index_list[0]] )) {
630 ret->vertex[ret->num_vertex] = tmp->vertex[index_list[0]];
633 (we add an offset to the index, so we can tell them apart)
635 for (t=0; t<ret->num_triangle; ++t) {
636 for (i=0; i<index_cnt; ++i) {
637 if (ret->triangle[t].i[0] == index_list[i]) {
638 ret->triangle[t].i[0] = ret->num_vertex+INDEX_OFFSET;
640 if (ret->triangle[t].i[1] == index_list[i]) {
641 ret->triangle[t].i[1] = ret->num_vertex+INDEX_OFFSET;
643 if (ret->triangle[t].i[2] == index_list[i]) {
644 ret->triangle[t].i[2] = ret->num_vertex+INDEX_OFFSET;
654 /* correct index offset */
655 for (t=0; t<ret->num_triangle; ++t) {
656 ret->triangle[t].i[0] -= INDEX_OFFSET;
657 ret->triangle[t].i[1] -= INDEX_OFFSET;
658 ret->triangle[t].i[2] -= INDEX_OFFSET;
661 /* normalize vertexes */
662 for (v=0; v<ret->num_vertex; ++v) {
663 vector_normalize( &ret->vertex[v] );
666 fprintf( stderr, "out v=%d t=%d\n",
667 ret->num_vertex, ret->num_triangle );
669 /* shrink the arrays by cloning */
670 c_ret = clone_Object( ret );
676 static int render( State *st )
679 struct timeval tv1, tv2;
682 GLfloat LightAmbient[]= { 0.1f, 0.1f, 0.1f, 1.0f };
683 GLfloat LightPosition[]= { -20.0f, -10.0f, -100.0f, 0.0f };
687 if (0 == st->food) return 0;
689 gettimeofday( &tv1, NULL );
691 /* life goes on... */
694 gettimeofday( &tv2, NULL );
695 usec = (tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec);
696 fprintf( stderr, "tick %d\n", usec );
697 gettimeofday( &tv1, NULL );
700 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
701 glDepthFunc(GL_LESS);
702 glEnable(GL_DEPTH_TEST);
703 glLightfv( GL_LIGHT0, GL_AMBIENT, LightAmbient );
704 glLightfv( GL_LIGHT0, GL_DIFFUSE, st->color );
705 glLightfv( GL_LIGHT0, GL_POSITION, LightPosition );
707 /* prepare lighting vs. wireframe */
709 glEnable( GL_LIGHT0 );
710 glEnable( GL_LIGHTING );
711 glEnable( GL_NORMALIZE );
712 glPolygonMode( GL_FRONT, GL_FILL );
714 glPolygonMode( GL_FRONT, GL_LINE );
717 /* draw the dead cells if choosen */
718 if (st->keep_old_cells) {
719 for (b=0; b<st->num_cells; ++b) {
720 if (st->cell[b].energy <= 0) {
723 glTranslatef( st->cell[b].x, st->cell[b].y, 0.0 );
724 glRotatef( st->cell[b].rotation, 0.0, 0.0, 1.0 );
725 glScalef( st->cell[b].radius, st->cell[b].radius, st->cell[b].radius );
732 /* draw the living cells */
733 for (b=0; b<st->num_cells; ++b) {
734 if (st->cell[b].energy >0) {
735 double fac = (double)st->cell[b].energy / 50.0;
737 if (fac < 0.0) fac = 0.0;
738 if (fac > 1.0) fac = 1.0;
740 shape = (int)(9.0*fac);
742 /*glColor3f( fac, fac, fac );*/
745 glTranslatef( st->cell[b].x, st->cell[b].y, 0.0 );
746 glRotatef( st->cell[b].rotation, 0.0, 0.0, 1.0 );
747 glScalef( st->cell[b].radius, st->cell[b].radius, st->cell[b].radius );
748 draw_cell( st, 9-shape );
753 /* draw cell nuclei */
756 glDisable( GL_LIGHT0 );
757 glDisable( GL_LIGHTING );
759 glEnable( GL_BLEND );
760 glDisable( GL_DEPTH_TEST );
761 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
762 glEnable( GL_TEXTURE_2D );
763 glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
764 glBindTexture( GL_TEXTURE_2D, st->texture_name );
766 for (b=0; b<st->num_cells; ++b) {
767 if (st->cell[b].energy>0 || st->keep_old_cells) {
769 glTranslatef( st->cell[b].x, st->cell[b].y, 0.0 );
770 glScalef( st->cell[b].radius, st->cell[b].radius, st->cell[b].radius );
776 glDisable( GL_TEXTURE_2D );
777 glDisable( GL_BLEND );
781 gettimeofday( &tv2, NULL );
782 usec = (tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec);
783 fprintf( stderr, "OpenGL %d\n", usec );
785 return num_paint * st->cell_polys;
788 /* this creates the initial subdivided half-dodecaedron */
789 static Object *create_sphere( State *st, int divisions )
792 int num_triangle = 10;
794 double a, aStep = (double)M_PI / 3.0;
796 int vi[30] = { 0, 7, 1, 1, 7, 2, 2, 8, 3, 3, 8, 4, 4, 6, 5,
797 5, 6, 0, 0, 6, 7, 2, 7, 8, 4, 8, 6, 6, 8, 7 };
798 Object *obj = (Object *)malloc( sizeof( Object ) );
800 obj->vertex = (Vector *)malloc( num_vertex*sizeof( Vector ) );
802 (Triangle *)malloc( num_triangle*sizeof( Triangle ) );
803 obj->num_vertex = num_vertex;
804 obj->num_triangle = num_triangle;
806 /* create vertexes for dodecaedron */
808 for (v=0; v<6; ++v) {
809 obj->vertex[v].x = sin( a );
810 obj->vertex[v].y = -cos( a );
811 obj->vertex[v].z = 0.0;
816 a = -60.0/180.0*(double)M_PI;
817 e = 58.2825/180.0 * (double)M_PI;
819 obj->vertex[v].x = sin( a )*cos( e );
820 obj->vertex[v].y = -cos( a )*cos( e );
821 obj->vertex[v].z = -sin( e );
826 /* create triangles */
827 for (t=0; t<obj->num_triangle; ++t) {
828 obj->triangle[t].i[0] = vi[3*t];
829 obj->triangle[t].i[1] = vi[3*t+1];
830 obj->triangle[t].i[2] = vi[3*t+2];
833 /* subdivide as specified */
834 for (i=0; i<divisions; ++i) {
835 Object *newObj = subdivide( obj );
840 st->cell_polys = obj->num_triangle;
845 static int create_list( State *st, double fac )
848 Object *obj = clone_Object( st->sphere );
849 ObjectSmooth *smooth;
850 #ifdef USE_VERTEX_ARRAY
851 VertexArray *vertex_array;
853 int list = glGenLists(1);
855 /* apply wrinckle factor */
856 for (v=0; v<obj->num_vertex; ++v) {
857 vector_mul( &obj->vertex[v], 1.0+fac*st->disturbance[v] );
860 /* compute normals */
861 smooth = create_ObjectSmooth( obj );
864 /* Create display list */
865 glNewList( list, GL_COMPILE );
866 #ifdef USE_VERTEX_ARRAY
867 vertex_array = array_from_ObjectSmooth( smooth );
868 glEnableClientState( GL_VERTEX_ARRAY );
869 glEnableClientState( GL_NORMAL_ARRAY );
870 glVertexPointer( 3, GL_FLOAT, 0, vertex_array->vertex );
871 glNormalPointer( GL_FLOAT, 0, vertex_array->normal );
872 glDrawElements( GL_TRIANGLES, vertex_array->num_index,
873 GL_UNSIGNED_INT, vertex_array->index );
874 free( vertex_array );
876 glBegin( GL_TRIANGLES );
878 for (t=0; t<smooth->num_triangle; ++t) {
879 for (i=0; i<3; ++i) {
880 glNormal3f( smooth->normal[smooth->triangle[t].i[i]].x,
881 smooth->normal[smooth->triangle[t].i[i]].y,
882 smooth->normal[smooth->triangle[t].i[i]].z );
883 glVertex3f( smooth->vertex[smooth->triangle[t].i[i]].x,
884 smooth->vertex[smooth->triangle[t].i[i]].y,
885 smooth->vertex[smooth->triangle[t].i[i]].z );
893 free_ObjectSmooth( smooth );
898 static void draw_cell( State *st, int shape )
900 if (-1 == st->cell_list[shape]) {
901 st->cell_list[shape] = create_list( st, (double)shape/10.0 );
904 glCallList( st->cell_list[shape] );
907 static void create_nucleus_texture( State *st )
913 st->texture = (GLubyte *) malloc( 4*TEX_SIZE*TEX_SIZE );
915 for (y=0; y<TEX_SIZE; ++y) {
916 for (x=0; x<TEX_SIZE; ++x) {
917 float r2 = ((x-w2)*(x-w2)+(y-w2)*(y-w2));
918 float v = 120.0 * expf( -(r2) / s );
919 st->texture[4*(x+y*TEX_SIZE)] = (GLubyte)0;
920 st->texture[4*(x+y*TEX_SIZE)+1] = (GLubyte)0;
921 st->texture[4*(x+y*TEX_SIZE)+2] = (GLubyte)0;
922 st->texture[4*(x+y*TEX_SIZE)+3] = (GLubyte)v;
926 glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
927 glGenTextures( 1, &st->texture_name );
928 glBindTexture( GL_TEXTURE_2D, st->texture_name );
930 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
931 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
932 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
933 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
934 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, TEX_SIZE, TEX_SIZE, 0,
935 GL_RGBA, GL_UNSIGNED_BYTE, st->texture );
938 static void draw_nucleus( State *st )
940 if (-1 == st->nucleus_list) {
943 st->nucleus_list = glGenLists( 1 );
944 glNewList( st->nucleus_list, GL_COMPILE );
946 glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -r, -r, z );
947 glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -r, r, z );
948 glTexCoord2f( 1.0f, 1.0f ); glVertex3f( r, r, z );
949 glTexCoord2f( 1.0f, 0.0f ); glVertex3f( r, -r, z );
954 glCallList( st->nucleus_list );
957 static void create_cells( State *st )
959 int border = (int)(200.0 * st->screen_scale);
961 int w = st->width-2*border;
962 int h = st->height-2*border;
964 st->color[0] = 0.5 + random_max( 1000 ) * 0.0005;
965 st->color[1] = 0.5 + random_max( 1000 ) * 0.0005;
966 st->color[2] = 0.5 + random_max( 1000 ) * 0.0005;
969 /* allocate if startup */
971 st->cell = (Cell *) malloc( st->max_cells * sizeof(Cell));
974 /* fill the screen with random food for our little critters */
975 foodcnt = (st->width*st->height)/16;
976 for (i=0; i<foodcnt; ++i) {
977 st->food[i] = random_interval( st->minfood, st->maxfood );
980 /* create the requested seed-cells */
981 st->num_cells = st->num_seeds;
983 for (i=0; i<st->num_cells; ++i) {
984 st->cell[i].x = border + random_max( w );
985 st->cell[i].y = border + random_max( h );
986 st->cell[i].vx = 0.0;
987 st->cell[i].vy = 0.0;
988 st->cell[i].age = random_max( 0x0f );
989 st->cell[i].min_dist = 500.0;
990 st->cell[i].energy = random_interval( 5, 5+0x3f );
991 st->cell[i].rotation = ((double)random()/(double)RAND_MAX)*360.0;
992 st->cell[i].radius = st->radius;
993 st->cell[i].growth = 1.0;
997 /* all this is rather expensive :( */
998 static void tick( State *st )
1000 int new_num_cells, num_cells=0;
1002 int x, y, w4=st->width/4, h4=st->height/4, offset;
1006 const double check_dist = 0.75*st->move_dist;
1007 const double grow_dist = 0.75*st->radius;
1008 const double adult_radius = st->radius;
1010 /* find number of cells capable of division
1011 and count living cells
1013 for (b=0; b<st->num_cells; ++b) {
1014 if (st->cell[b].energy > 0) num_living++;
1015 if (can_divide( st, &st->cell[b] )) num_cells++;
1017 new_num_cells = st->num_cells + num_cells;
1019 /* end of simulation ? */
1020 if (0 == num_living || new_num_cells >= st->max_cells) {
1021 if (st->pause_counter > 0) st->pause_counter--;
1022 if (st->pause_counter > 0) return;
1024 st->pause_counter = st->pause;
1025 } else if (num_cells) { /* any fertile candidates ? */
1026 for (b=0, j=st->num_cells; b<st->num_cells; ++b) {
1027 if (can_divide( st, &st->cell[b] )) {
1028 st->cell[b].vx = random_interval( -50, 50 ) * 0.01;
1029 st->cell[b].vy = random_interval( -50, 50 ) * 0.01;
1030 st->cell[b].age = random_max( 0x0f );
1031 /* half energy for both plus some bonus for forking */
1032 st->cell[b].energy =
1033 st->cell[b].energy/2 + random_max( 0x0f );
1034 /* forking makes me shrink */
1035 st->cell[b].growth = 0.995;
1037 /* this one initially goes into the oposite direction */
1038 st->cell[j].vx = -st->cell[b].vx;
1039 st->cell[j].vy = -st->cell[b].vy;
1041 st->cell[j].x = st->cell[b].x;
1042 st->cell[j].y = st->cell[b].y;
1043 st->cell[j].age = random_max( 0x0f );
1044 st->cell[j].energy = (st->cell[b].energy);
1045 st->cell[j].rotation =
1046 ((double)random()/(double)RAND_MAX)*360.0;
1047 st->cell[j].growth = st->cell[b].growth;
1048 st->cell[j].radius = st->cell[b].radius;
1051 st->cell[b].vx = 0.0;
1052 st->cell[b].vy = 0.0;
1056 st->num_cells = new_num_cells;
1059 /* for each find a direction to escape */
1060 if (st->num_cells > 1) {
1061 for (b=0; b<st->num_cells; ++b) {
1062 if (st->cell[b].energy > 0) {
1067 /* grow or shrink */
1068 st->cell[b].radius *= st->cell[b].growth;
1069 /* find closest neighbour */
1070 min_dist = 100000.0;
1072 for (j=0; j<st->num_cells; ++j) {
1074 const double dx = st->cell[b].x - st->cell[j].x;
1075 const double dy = st->cell[b].y - st->cell[j].y;
1077 if (fabs(dx) < check_dist || fabs(dy) < check_dist) {
1078 const double dist = dx*dx+dy*dy;
1079 /*const double dist = sqrt( dx*dx+dy*dy );*/
1080 if (dist<min_dist) {
1087 /* escape step is away from closest normalized with distance */
1088 vx = st->cell[b].x - st->cell[min_index].x;
1089 vy = st->cell[b].y - st->cell[min_index].y;
1090 len = sqrt( vx*vx + vy*vy );
1092 st->cell[b].vx = vx/len;
1093 st->cell[b].vy = vy/len;
1095 st->cell[b].min_dist = len;
1096 /* if not adult (radius too small) */
1097 if (st->cell[b].radius < adult_radius) {
1098 /* if too small 60% stop shrinking */
1099 if (st->cell[b].radius < adult_radius * 0.6) {
1100 st->cell[b].growth = 1.0;
1102 /* at safe distance we start growing again */
1103 if (len > grow_dist) {
1104 if (st->cell[b].energy > 30) {
1105 st->cell[b].growth = 1.005;
1108 } else { /* else keep size */
1109 st->cell[b].growth = 1.0;
1114 st->cell[0].min_dist = 2*st->move_dist;
1117 /* now move em, snack and burn energy */
1118 for (b=0; b<st->num_cells; ++b) {
1119 /* if still alive */
1120 if (st->cell[b].energy > 0) {
1121 /* agility depends on amount of energy */
1122 double fac = (double)st->cell[b].energy / 50.0;
1123 if (fac < 0.0) fac = 0.0;
1124 if (fac > 1.0) fac = 1.0;
1126 st->cell[b].x += fac*(2.0 -
1127 (4.0*(double)random() / (double)RAND_MAX) +
1129 st->cell[b].y += fac*(2.0 -
1130 (4.0*(double)random() / (double)RAND_MAX) +
1133 /* get older and burn energy */
1134 if (st->cell[b].energy > 0) {
1136 st->cell[b].energy--;
1140 x = ((int)st->cell[b].x)/4;
1141 if (x<0) x=0; if (x>=w4) x = w4-1;
1142 y = ((int)st->cell[b].y)/4;
1143 if (y<0) y=0; if (y>=h4) y = h4-1;
1147 /* don't eat if already satisfied */
1148 if (st->cell[b].energy < 100 &&
1149 st->food[offset] > 0) {
1151 st->cell[b].energy++;
1152 /* if you are hungry, eat more */
1153 if (st->cell[b].energy < 50 &&
1154 st->food[offset] > 0) {
1156 st->cell[b].energy++;
1164 reshape_glcells( ModeInfo *mi, int width, int height )
1166 State *st = &sstate[MI_SCREEN(mi)];
1167 st->height = height;
1169 st->screen_scale = (double)width / 1600.0;
1171 st->radius = s_radius;
1172 if (st->radius < 5) st->radius = 5;
1173 if (st->radius > 200) st->radius = 200;
1174 st->radius *= st->screen_scale;
1176 st->move_dist = s_min_dist;
1177 if (st->move_dist < 1.0) st->move_dist = 1.0;
1178 if (st->move_dist > 3.0) st->move_dist = 3.0;
1179 st->move_dist *= st->radius;
1181 glViewport (0, 0, (GLint) width, (GLint) height);
1183 glMatrixMode(GL_PROJECTION);
1185 glOrtho( 0, width, height, 0, 200, 0 );
1186 glMatrixMode(GL_MODELVIEW);
1189 if (st->food) free( st->food );
1190 st->food = (int *)malloc( ((width*height)/16)*sizeof(int) );
1196 init_glcells( ModeInfo *mi )
1203 calloc( MI_NUM_SCREENS(mi), sizeof(State) );
1205 fprintf( stderr, "%s: out of memory\n", progname );
1209 st = &sstate[MI_SCREEN(mi)];
1211 st->glx_context = init_GL(mi);
1214 st->wire = MI_IS_WIREFRAME(mi);
1217 st->max_cells = s_maxcells;;
1218 if (st->max_cells < 50) st->max_cells = 50;
1219 if (st->max_cells > 10000) st->max_cells = 10000;
1221 st->pause = s_pause;
1222 if (st->pause < 0) st->pause = 0;
1223 if (st->pause > 400) st->pause = 400;
1224 st->pause_counter = st->pause;
1226 st->radius = s_radius;
1227 if (st->radius < 5) st->radius = 5;
1228 if (st->radius > 200) st->radius = 200;
1230 divisions = s_quality;
1231 if (divisions < 0) divisions = 0;
1232 if (divisions > 5) divisions = 5;
1234 st->num_seeds = s_seeds;
1235 if (st->num_seeds < 1) st->num_seeds = 1;
1236 if (st->num_seeds > 16) st->num_seeds = 16;
1238 st->minfood = s_minfood;
1239 if (st->minfood < 0) st->minfood = 0;
1240 if (st->minfood > 1000) st->minfood = 1000;
1242 st->maxfood = s_maxfood;
1243 if (st->maxfood < 0) st->maxfood = 0;
1244 if (st->maxfood > 1000) st->maxfood = 1000;
1246 if (st->maxfood < st->minfood) st->maxfood = st->minfood+1;
1248 st->keep_old_cells = s_keepold;
1250 st->divide_age = s_divideage;
1251 if (st->divide_age < 1) st->divide_age = 1;
1252 if (st->divide_age > 1000) st->divide_age = 1000;
1254 st->move_dist = s_min_dist;
1255 if (st->move_dist < 1.0) st->move_dist = 1.0;
1256 if (st->move_dist > 3.0) st->move_dist = 3.0;
1257 st->move_dist *= st->radius;
1259 for (i=0; i<NUM_CELL_SHAPES; ++i) st->cell_list[i] = -1;
1260 st->nucleus_list = -1;
1263 st->sphere = create_sphere( st, divisions );
1265 (double *) malloc( st->sphere->num_vertex*sizeof(double) );
1266 for (i=0; i<st->sphere->num_vertex; ++i) {
1267 st->disturbance[i] =
1268 0.05-((double)random()/(double)RAND_MAX*0.1);
1271 create_nucleus_texture( st );
1273 reshape_glcells (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
1277 draw_glcells( ModeInfo *mi )
1279 State *st = &sstate[MI_SCREEN(mi)];
1280 Display *dpy = MI_DISPLAY(mi);
1281 Window window = MI_WINDOW(mi);
1283 if (!st->glx_context) return;
1285 glXMakeCurrent( MI_DISPLAY(mi), MI_WINDOW(mi),
1286 *(st->glx_context) );
1288 mi->polygon_count = render( st );
1290 if (mi->fps_p) do_fps (mi);
1293 glXSwapBuffers( dpy, window );
1297 release_glcells( ModeInfo *mi )
1300 State *st = &sstate[MI_SCREEN(mi)];
1302 /* nuke everything before exit */
1303 if (st->sphere) free_Object( st->sphere );
1304 if (st->food) free( st->food );
1305 for (i=0; i<NUM_CELL_SHAPES; ++i) {
1306 if (st->cell_list[i] != -1) {
1307 glDeleteLists( st->cell_list[i], 1 );
1310 if (st->cell) free( st->cell );
1311 free( st->disturbance );
1312 glDeleteTextures( 1, &st->texture_name );
1313 free( st->texture );
1316 XSCREENSAVER_MODULE( "GLCells", glcells )