From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / glx / glforestfire.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* fire --- 3D fire or rain landscape */
3
4 #if 0
5 static const char sccsid[] = "@(#)fire.c        5.02 2001/09/26 xlockmore";
6 #endif
7
8 /* Copyright (c) E. Lassauge, 2001. */
9
10 /*
11  * Permission to use, copy, modify, and distribute this software and its
12  * documentation for any purpose and without fee is hereby granted,
13  * provided that the above copyright notice appear in all copies and that
14  * both that copyright notice and this permission notice appear in
15  * supporting documentation.
16  *
17  * This file is provided AS IS with no warranties of any kind.  The author
18  * shall have no liability with respect to the infringement of copyrights,
19  * trade secrets or any patents by this file or any part thereof.  In no
20  * event will the author be liable for any lost revenue or profits or
21  * other special, indirect and consequential damages.
22  *
23  * The original code for this mode was written by David Bucciarelli 
24  * (tech.hmw@plus.it) and could be found in the demo package 
25  * of Mesa (Mesa-3.2/3Dfx/demos/). This mode is the result of the merge of
26  * two of the David's demos (fire and rain).
27  *
28  * Eric Lassauge  (October-10-2000) <lassauge@users.sourceforge.net>
29  *                                  http://lassauge.free.fr/linux.html
30  *
31  * REVISION HISTORY:
32  *
33  * E.Lassauge - 26-Sep-2001:
34  *      - add wander option and code 
35  *      - cleanups for xscreensaver
36  *
37  * E.Lassauge - 09-Mar-2001:
38  *      - get rid of my framerate options to use showfps
39  *
40  * E.Lassauge - 12-Jan-2001:
41  *      - add rain particules, selected if count=0 (no fire means rain !)
42  *
43  * E.Lassauge - 28-Nov-2000:
44  *      - modified release part to add freeing of GL objects
45  *
46  * E.Lassauge - 14-Nov-2000:
47  *      - use new common xpm_to_ximage function
48  *
49  * E.Lassauge - 25-Oct-2000:
50  *      - add the trees (with a new resource '-trees')
51  *      - corrected handling of color (textured vs untextured)
52  *      - corrected handling of endiannes for the xpm files
53  *      - inverted ground pixmap file
54  *      - use malloc-ed tree array
55  *
56  * TSchmidt - 23-Oct-2000:
57  *      - added size option like used in sproingies mode
58  *
59  * E.Lassauge - 13-Oct-2000:
60  *      - when trackmouse and window is iconified (login screen): stop tracking
61  *      - add pure GLX handling of framerate display (erased GLUT stuff)
62  *      - made count a per screen variable and update it only if framemode
63  *      - changes for no_texture an wireframe modes
64  *      - change no_texture color for the ground
65  *      - add freeing of texture image
66  *      - misc comments and little tweakings
67  *
68  * TODO:
69  *      - perhaps use a user supplied xpm for ground image (or a whatever image
70  *        file using ImageMagick ?)
71  *      - random number of trees ? change trees at change_fire ?
72  *      - fix wireframe mode: it's too CPU intensive.
73  *      - look how we can get the Wheel events (Button4&5).
74  */
75
76
77 #ifdef STANDALONE       /* xscreensaver mode */
78 #define DEFAULTS "*delay:     10000 \n" \
79                 "*count:        800 \n" \
80                 "*size:           0 \n" \
81                 "*showFPS:    False \n" \
82                 "*wireframe:  False \n" \
83
84 # define refresh_fire 0
85 #define MODE_fire
86 #include "xlockmore.h"          /* from the xscreensaver distribution */
87 #include "gltrackball.h"
88 #else                           /* !STANDALONE */
89 #include "xlock.h"              /* from the xlockmore distribution */
90 #include "visgl.h"
91 #endif                          /* !STANDALONE */
92
93 #ifdef MODE_fire
94
95 #define MINSIZE 32
96
97 #if defined( USE_XPM ) || defined( USE_XPMINC ) || defined(STANDALONE)
98 /* USE_XPM & USE_XPMINC in xlock mode ; HAVE_XPM in xscreensaver mode */
99 #include "xpm-ximage.h"
100 #define I_HAVE_XPM
101
102 #ifdef STANDALONE
103 #include "../images/ground.xpm"
104 #include "../images/tree.xpm"
105 #else /* !STANDALONE */
106 #include "pixmaps/ground.xpm"
107 #include "pixmaps/tree.xpm"
108 #endif /* !STANDALONE */
109 #endif /* HAVE_XPM */
110
111 /* vector utility macros */
112 #define vinit(a,i,j,k) {\
113   (a)[0]=i;\
114   (a)[1]=j;\
115   (a)[2]=k;\
116 }
117
118 #define vinit4(a,i,j,k,w) {\
119   (a)[0]=i;\
120   (a)[1]=j;\
121   (a)[2]=k;\
122   (a)[3]=w;\
123 }
124
125 #define vadds(a,dt,b) {\
126   (a)[0]+=(dt)*(b)[0];\
127   (a)[1]+=(dt)*(b)[1];\
128   (a)[2]+=(dt)*(b)[2];\
129 }
130
131 #define vequ(a,b) {\
132   (a)[0]=(b)[0];\
133   (a)[1]=(b)[1];\
134   (a)[2]=(b)[2];\
135 }
136
137 #define vinter(a,dt,b,c) {\
138   (a)[0]=(dt)*(b)[0]+(1.0-dt)*(c)[0];\
139   (a)[1]=(dt)*(b)[1]+(1.0-dt)*(c)[1];\
140   (a)[2]=(dt)*(b)[2]+(1.0-dt)*(c)[2];\
141 }
142
143 #define clamp(a)        ((a) < 0.0 ? 0.0 : ((a) < 1.0 ? (a) : 1.0))
144
145 #define vclamp(v) {\
146   (v)[0]=clamp((v)[0]);\
147   (v)[1]=clamp((v)[1]);\
148   (v)[2]=clamp((v)[2]);\
149 }
150
151 /* Manage option vars */
152 #define DEF_TEXTURE     "True"
153 #define DEF_FOG         "False"
154 #define DEF_SHADOWS     "True"
155 #define DEF_FRAMERATE   "False"
156 #define DEF_WANDER      "True"
157 #define DEF_TREES       "5"
158 #define MAX_TREES       20
159 static Bool do_texture;
160 static Bool do_fog;
161 static Bool do_shadows;
162 static Bool do_wander;
163 static int num_trees;
164 static XFontStruct *mode_font = None;
165
166 static XrmOptionDescRec opts[] = {
167     {"-texture", ".fire.texture", XrmoptionNoArg, "on"},
168     {"+texture", ".fire.texture", XrmoptionNoArg, "off"},
169     {"-fog", ".fire.fog", XrmoptionNoArg, "on"},
170     {"+fog", ".fire.fog", XrmoptionNoArg, "off"},
171     {"-shadows", ".fire.shadows", XrmoptionNoArg, "on"},
172     {"+shadows", ".fire.shadows", XrmoptionNoArg, "off"},
173     {"-wander", ".fire.wander", XrmoptionNoArg, "on"},
174     {"+wander", ".fire.wander", XrmoptionNoArg, "off"},
175     {"-trees", ".fire.trees", XrmoptionSepArg, 0},
176     {"-rain", ".fire.count", XrmoptionNoArg, "0"},
177
178 };
179
180 static argtype vars[] = {
181     {&do_texture,    "texture",    "Texture",    DEF_TEXTURE,    t_Bool},
182     {&do_fog,        "fog",        "Fog",        DEF_FOG,        t_Bool},
183     {&do_shadows,    "shadows",    "Shadows",    DEF_SHADOWS,    t_Bool},
184     {&do_wander,     "wander",     "Wander",     DEF_WANDER,     t_Bool},
185     {&num_trees,     "trees",      "Trees",      DEF_TREES,      t_Int},
186 };
187
188 static OptionStruct desc[] = {
189     {"-/+texture", "turn on/off texturing"},
190     {"-/+fog", "turn on/off fog"},
191     {"-/+shadows", "turn on/off shadows"},
192     {"-/+wander", "turn on/off wandering"},
193     {"-trees num", "number of trees (0 disables)"},
194 };
195
196 ENTRYPOINT ModeSpecOpt fire_opts =
197  { sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc };
198
199 #ifdef USE_MODULES
200 ModStruct fire_description =
201     { "fire", "init_fire", "draw_fire", "release_fire",
202     "draw_fire", "change_fire", (char *) NULL, &fire_opts,
203     10000, 800, 1, 400, 64, 1.0, "",
204     "Shows a 3D fire-like image", 0, NULL
205 };
206 #endif /* USE_MODULES */
207
208 /* misc defines */
209 #define TREEINR         2.5     /* tree min distance */
210 #define TREEOUTR        8.0     /* tree max distance */
211 #define FRAME           50      /* frame count interval */
212 #define DIMP            20.0    /* dimension of ground */
213 #define DIMTP           16.0    /* dimension of ground texture */
214
215 #define RIDCOL          0.4     /* factor for color blending */
216
217 #define AGRAV           -9.8    /* gravity */
218
219 #define NUMPART         7500    /* rain particles */
220
221 /* fire particle struct */
222 typedef struct {
223     int age;
224     float p[3][3];
225     float v[3];
226     float c[3][4];
227 } part;
228
229 /* rain particle struct */
230 typedef struct {
231     float age;
232     float acc[3];
233     float vel[3];
234     float pos[3];
235     float partLength;
236     float oldpos[3];
237 } rain;
238
239 /* colors */
240 static const GLfloat black[3]    = { 0.0, 0.0, 0.0 }; /* shadow color */
241 static const GLfloat partcol1[3] = { 1.0, 0.2, 0.0 }; /* initial color: red-ish */
242 static const GLfloat partcol2[3] = { 1.0, 1.0, 0.0 }; /* blending color: yellow-ish */
243 static const GLfloat fogcolor[4] = { 0.9, 0.9, 1.0, 1.0 };
244
245 /* ground */
246 static const float q[4][3] = {
247     {-DIMP, 0.0, -DIMP},
248     {DIMP, 0.0, -DIMP},
249     {DIMP, 0.0, DIMP},
250     {-DIMP, 0.0, DIMP}
251 };
252
253 /* ground texture */
254 static const float qt[4][2] = {
255     {-DIMTP, -DIMTP},
256     {DIMTP, -DIMTP},
257     {DIMTP, DIMTP},
258     {-DIMTP, DIMTP}
259 };
260
261 /* default values for observer */
262 static const float DEF_OBS[3] = { 2.0f, 1.0f, 0.0f };
263 #define DEV_V           0.0
264 #define DEF_ALPHA       -90.0
265 #define DEF_BETA        90.0
266
267 /* tree struct */
268 typedef struct {
269     float x,y,z;
270 } treestruct;
271
272 /* the mode struct, contains all per screen variables */
273 typedef struct {
274     GLint WIDTH, HEIGHT;        /* display dimensions */
275     GLXContext *glx_context;
276
277     int np;                     /* number of fire particles : set it through 'count' resource */
278     float eject_r;              /* emission radius */
279     float dt, maxage, eject_vy, eject_vl;
280     float ridtri;               /* fire particle size */
281     Bool shadows;               /* misc booleans: set them through specific resources */
282     Bool fog;
283
284     part *p;                    /* fire particles array */
285     rain *r;                    /* rain particles array */
286
287     XImage *gtexture;           /* ground texture image bits */
288     XImage *ttexture;           /* tree texture image bits */
289     GLuint groundid;            /* ground texture id: GL world */
290     GLuint treeid;              /* tree texture id: GL world */
291     GLuint fontbase;            /* fontbase id: GL world */
292
293     int   num_trees;            /* number of trees: set it through 'trees' resource */
294     treestruct *treepos;        /* trees positions: float treepos[num_trees][3] */
295
296     float min[3];               /* raining area */
297     float max[3];
298
299     float obs[3];               /* observer coordinates */
300     float dir[3];               /* view direction */
301     float v;                    /* observer velocity */
302     float alpha;                /* observer angles */
303     float beta;
304
305     trackball_state *trackball;
306     Bool button_down_p;
307     int frame;
308
309 } firestruct;
310
311 /* array of firestruct indexed by screen number */
312 static firestruct *fire = (firestruct *) NULL;
313
314 /*
315  *-----------------------------------------------------------------------------
316  *-----------------------------------------------------------------------------
317  *    Misc funcs.
318  *-----------------------------------------------------------------------------
319  *-----------------------------------------------------------------------------
320  */
321
322 /* utility function for the rain particles */
323 static float gettimerain(void)
324 {
325 #if 0
326   /* Oh yeah, *that's* portable!  WTF. */
327   /* 
328    * I really thought clock() was standard ... EL
329    * I found this on the net:
330    * The clock() function conforms to ISO/IEC 9899:1990 (``ISO C89'') 
331    * */
332
333   static clock_t told= (clock_t)0;
334   clock_t tnew,ris;
335
336   tnew=clock();
337
338   ris=tnew-told;
339
340   told=tnew;
341
342   return (0.0125 + ris/(float)CLOCKS_PER_SEC);
343 #else
344   return 0.0150;
345 #endif
346 }
347
348 /* my RAND */
349 static float vrnd(void)
350 {
351     return ((float) LRAND() / (float) MAXRAND);
352 }
353
354 /* initialise new fire particle */
355 static void setnewpart(firestruct * fs, part * p)
356 {
357     float a, vi[3];
358     const float *c;
359
360     p->age = 0;
361
362     a = vrnd() * M_PI * 2.0;
363
364     vinit(vi, sin(a) * fs->eject_r * vrnd(), 0.15, cos(a) * fs->eject_r * vrnd());
365     vinit(p->p[0], vi[0] + vrnd() * fs->ridtri, vi[1] + vrnd() * fs->ridtri, vi[2] + vrnd() * fs->ridtri);
366     vinit(p->p[1], vi[0] + vrnd() * fs->ridtri, vi[1] + vrnd() * fs->ridtri, vi[2] + vrnd() * fs->ridtri);
367     vinit(p->p[2], vi[0] + vrnd() * fs->ridtri, vi[1] + vrnd() * fs->ridtri, vi[2] + vrnd() * fs->ridtri);
368
369     vinit(p->v, vi[0] * fs->eject_vl / (fs->eject_r / 2),
370           vrnd() * fs->eject_vy + fs->eject_vy / 2,
371           vi[2] * fs->eject_vl / (fs->eject_r / 2));
372
373     c = partcol1;
374
375     vinit4(p->c[0], c[0] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
376            c[1] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
377            c[2] * ((1.0 - RIDCOL) + vrnd() * RIDCOL), 1.0);
378     vinit4(p->c[1], c[0] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
379            c[1] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
380            c[2] * ((1.0 - RIDCOL) + vrnd() * RIDCOL), 1.0);
381     vinit4(p->c[2], c[0] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
382            c[1] * ((1.0 - RIDCOL) + vrnd() * RIDCOL),
383            c[2] * ((1.0 - RIDCOL) + vrnd() * RIDCOL), 1.0);
384 }
385
386 /* initialise new rain particle */
387 static void setnewrain(firestruct * fs, rain * r)
388 {
389     r->age=0.0f;
390
391     vinit(r->acc,0.0f,-0.98f,0.0f);
392     vinit(r->vel,0.0f,0.0f,0.0f);
393     
394     r->partLength=0.2f;
395
396     vinit(r->oldpos,fs->min[0]+(fs->max[0]-fs->min[0])*vrnd(),
397                     fs->max[1]+0.2f*fs->max[1]*vrnd(),
398                     fs->min[2]+(fs->max[2]-fs->min[2])*vrnd());
399     vequ(r->pos,r->oldpos);
400     vadds(r->oldpos,-(r->partLength),r->vel);
401
402     r->pos[1]=(fs->max[1]-fs->min[1])*vrnd()+fs->min[1];
403     r->oldpos[1]=r->pos[1]-r->partLength*r->vel[1];
404 }
405
406 /* set fire particle values */
407 static void setpart(firestruct * fs, part * p)
408 {
409     float fact;
410
411     if (p->p[0][1] < 0.1) {
412         setnewpart(fs, p);
413         return;
414     }
415
416     p->v[1] += AGRAV * fs->dt;
417
418     vadds(p->p[0], fs->dt, p->v);
419     vadds(p->p[1], fs->dt, p->v);
420     vadds(p->p[2], fs->dt, p->v);
421
422     p->age++;
423
424     if ((p->age) > fs->maxage) {
425         vequ(p->c[0], partcol2);
426         vequ(p->c[1], partcol2);
427         vequ(p->c[2], partcol2);
428     } else {
429         fact = 1.0 / fs->maxage;
430         vadds(p->c[0], fact, partcol2);
431         vclamp(p->c[0]);
432         p->c[0][3] = fact * (fs->maxage - p->age);
433
434         vadds(p->c[1], fact, partcol2);
435         vclamp(p->c[1]);
436         p->c[1][3] = fact * (fs->maxage - p->age);
437
438         vadds(p->c[2], fact, partcol2);
439         vclamp(p->c[2]);
440         p->c[2][3] = fact * (fs->maxage - p->age);
441     }
442 }
443
444 /* set rain particle values */
445 static void setpartrain(firestruct * fs, rain * r, float dt)
446 {
447     r->age += dt;
448
449     vadds(r->vel,dt,r->acc);
450     vadds(r->pos,dt,r->vel);
451
452     if(r->pos[0]<fs->min[0])
453         r->pos[0]=fs->max[0]-(fs->min[0]-r->pos[0]);
454     if(r->pos[2]<fs->min[2])
455         r->pos[2]=fs->max[2]-(fs->min[2]-r->pos[2]);
456
457     if(r->pos[0]>fs->max[0])
458         r->pos[0]=fs->min[0]+(r->pos[0]-fs->max[0]);
459     if(r->pos[2]>fs->max[2])
460         r->pos[2]=fs->min[2]+(r->pos[2]-fs->max[2]);
461
462     vequ(r->oldpos,r->pos);
463     vadds(r->oldpos,-(r->partLength),r->vel);
464     if(r->pos[1]<fs->min[1])
465         setnewrain(fs, r);
466 }
467
468 /* draw a tree */
469 static int drawtree(float x, float y, float z)
470 {
471     int polys = 0;
472     glBegin(GL_QUADS);
473     glTexCoord2f(0.0,0.0);
474     glVertex3f(x-1.5,y+0.0,z);
475
476     glTexCoord2f(1.0,0.0);
477     glVertex3f(x+1.5,y+0.0,z);
478
479     glTexCoord2f(1.0,1.0);
480     glVertex3f(x+1.5,y+3.0,z);
481
482     glTexCoord2f(0.0,1.0);
483     glVertex3f(x-1.5,y+3.0,z);
484     polys++;
485
486
487     glTexCoord2f(0.0,0.0);
488     glVertex3f(x,y+0.0,z-1.5);
489
490     glTexCoord2f(1.0,0.0);
491     glVertex3f(x,y+0.0,z+1.5);
492
493     glTexCoord2f(1.0,1.0);
494     glVertex3f(x,y+3.0,z+1.5);
495
496     glTexCoord2f(0.0,1.0);
497     glVertex3f(x,y+3.0,z-1.5);
498     polys++;
499
500     glEnd();
501
502     return polys;
503 }
504
505 /* calculate observer position : modified only if trackmouse is used */
506 static void calcposobs(firestruct * fs)
507 {
508     fs->dir[0] = sin(fs->alpha * M_PI / 180.0);
509     fs->dir[2] =
510         cos(fs->alpha * M_PI / 180.0) * sin(fs->beta * M_PI / 180.0);
511     fs->dir[1] = cos(fs->beta * M_PI / 180.0);
512
513     fs->obs[0] += fs->v * fs->dir[0];
514     fs->obs[1] += fs->v * fs->dir[1];
515     fs->obs[2] += fs->v * fs->dir[2];
516
517     if (!fs->np)
518     {
519         vinit(fs->min,fs->obs[0]-7.0f,-0.2f,fs->obs[2]-7.0f);
520         vinit(fs->max,fs->obs[0]+7.0f,8.0f,fs->obs[2]+7.0f);
521     }
522 }
523
524
525 /* initialise textures */
526 static void inittextures(ModeInfo * mi)
527 {
528     firestruct *fs = &fire[MI_SCREEN(mi)];
529
530 #if defined( I_HAVE_XPM )
531     if (do_texture) {
532
533         glGenTextures(1, &fs->groundid);
534 #ifdef HAVE_GLBINDTEXTURE
535         glBindTexture(GL_TEXTURE_2D, fs->groundid);
536 #endif /* HAVE_GLBINDTEXTURE */
537
538         if ((fs->gtexture = xpm_to_ximage(MI_DISPLAY(mi), MI_VISUAL(mi),
539                          MI_COLORMAP(mi), ground)) == None) {
540             (void) fprintf(stderr, "Error reading the ground texture.\n");
541             glDeleteTextures(1, &fs->groundid);
542             do_texture = False;
543             fs->groundid = 0;
544             fs->treeid   = 0;
545             return;
546         }
547
548         glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
549     clear_gl_error();
550         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
551                  fs->gtexture->width, fs->gtexture->height, 0,
552                  GL_RGBA,
553                  /* GL_UNSIGNED_BYTE, */
554                  GL_UNSIGNED_INT_8_8_8_8_REV,
555                  fs->gtexture->data);
556     check_gl_error("texture");
557
558         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
559         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
560
561         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
562         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
563
564         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
565
566         if (fs->num_trees)
567         {
568             glGenTextures(1, &fs->treeid);
569 #ifdef HAVE_GLBINDTEXTURE
570             glBindTexture(GL_TEXTURE_2D,fs->treeid);
571 #endif /* HAVE_GLBINDTEXTURE */
572             if ((fs->ttexture = xpm_to_ximage(MI_DISPLAY(mi), MI_VISUAL(mi),
573                          MI_COLORMAP(mi), tree)) == None) {
574               (void)fprintf(stderr,"Error reading tree texture.\n");
575               glDeleteTextures(1, &fs->treeid);
576               fs->treeid    = 0;
577               fs->num_trees = 0; 
578               return;
579             }
580
581         clear_gl_error();
582             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
583                      fs->ttexture->width, fs->ttexture->height, 0,
584                      GL_RGBA,
585                      /* GL_UNSIGNED_BYTE, */
586                      GL_UNSIGNED_INT_8_8_8_8_REV,
587                      fs->ttexture->data);
588         check_gl_error("texture");
589
590             glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
591             glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
592
593             glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
594             glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
595
596             glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
597         }
598     }
599     else
600     {
601         fs->groundid = 0;       /* default textures */
602         fs->treeid   = 0;
603     }
604 #else /* !I_HAVE_XPM */
605   do_texture = False;
606   fs->groundid = 0;       /* default textures */
607   fs->treeid = 0;
608 #endif /* !I_HAVE_XPM */
609 }
610
611 /* init tree array and positions */
612 static Bool inittree(ModeInfo * mi)
613 {
614     firestruct *fs = &fire[MI_SCREEN(mi)];
615     int i;
616     float dist;
617
618     /* allocate treepos array */
619     if ((fs->treepos = (treestruct *) malloc(fs->num_trees *
620                                         sizeof(treestruct))) == NULL) {
621                 return False;
622     }
623     /* initialise positions */
624     for(i=0;i<fs->num_trees;i++) {
625       do {
626         fs->treepos[i].x =vrnd()*TREEOUTR*2.0-TREEOUTR;
627         fs->treepos[i].y =0.0;
628         fs->treepos[i].z =vrnd()*TREEOUTR*2.0-TREEOUTR;
629         dist = sqrt(fs->treepos[i].x * fs->treepos[i].x +
630                     fs->treepos[i].z * fs->treepos[i].z);
631       } while((dist<TREEINR) || (dist>TREEOUTR));
632     }
633         return True;
634 }
635
636 /*
637  *-----------------------------------------------------------------------------
638  *-----------------------------------------------------------------------------
639  *    GL funcs.
640  *-----------------------------------------------------------------------------
641  *-----------------------------------------------------------------------------
642  */
643
644 ENTRYPOINT void reshape_fire(ModeInfo * mi, int width, int height)
645 {
646
647     firestruct *fs = &fire[MI_SCREEN(mi)];
648     int size = MI_SIZE(mi);
649
650     /* Viewport is specified size if size >= MINSIZE && size < screensize */
651     if (size <= 1) {
652         fs->WIDTH = MI_WIDTH(mi);
653         fs->HEIGHT = MI_HEIGHT(mi);
654     } else if (size < MINSIZE) {
655         fs->WIDTH = MINSIZE;
656         fs->HEIGHT = MINSIZE;
657     } else {
658         fs->WIDTH = (size > MI_WIDTH(mi)) ? MI_WIDTH(mi) : size;
659         fs->HEIGHT = (size > MI_HEIGHT(mi)) ? MI_HEIGHT(mi) : size;
660     }
661     glViewport((MI_WIDTH(mi) - fs->WIDTH) / 2, (MI_HEIGHT(mi) - fs->HEIGHT) / 2, fs->WIDTH, fs->HEIGHT);
662     glMatrixMode(GL_PROJECTION);
663     glLoadIdentity();
664     gluPerspective(70.0, fs->WIDTH / (float) fs->HEIGHT, 0.1, 30.0);
665
666     glMatrixMode(GL_MODELVIEW);
667
668 }
669
670 static void DrawFire(ModeInfo * mi)
671 {
672     int j;
673     firestruct *fs = &fire[MI_SCREEN(mi)];
674     Bool wire = MI_IS_WIREFRAME(mi);
675
676     mi->polygon_count = 0;
677
678     if (do_wander && !fs->button_down_p)
679     {
680         GLfloat x, y, z;
681
682 #       define SINOID(SCALE,SIZE) \
683         ((((1 + sin((fs->frame * (SCALE)) / 2 * M_PI)) / 2.0) * (SIZE)) - (SIZE)/2)
684
685         x = SINOID(0.031, 0.85);
686         y = SINOID(0.017, 0.25);
687         z = SINOID(0.023, 0.85);
688         fs->frame++;
689         fs->obs[0] = x + DEF_OBS[0];
690         fs->obs[1] = y + DEF_OBS[1];
691         fs->obs[2] = z + DEF_OBS[2];
692         fs->dir[1] = y;
693         fs->dir[2] = z;
694     }
695
696     glEnable(GL_DEPTH_TEST);
697
698     if (fs->fog)
699         glEnable(GL_FOG);
700     else
701         glDisable(GL_FOG);
702
703     glDepthMask(GL_TRUE);
704     glClearColor(0.5, 0.5, 0.8, 1.0);   /* sky in the distance */
705     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
706
707     glPushMatrix();
708
709     calcposobs(fs);
710
711     gltrackball_rotate (fs->trackball);
712
713     gluLookAt(fs->obs[0], fs->obs[1], fs->obs[2],
714               fs->obs[0] + fs->dir[0], 
715               fs->obs[1] + fs->dir[1],
716               fs->obs[2] + fs->dir[2],
717               0.0, 1.0, 0.0);
718
719     glEnable(GL_TEXTURE_2D);
720
721     /* draw ground using the computed texture */
722     if (do_texture) {
723         glColor4f(1.0,1.0,1.0,1.0);     /* white to get texture in it's true color */
724 #ifdef HAVE_GLBINDTEXTURE
725         glBindTexture(GL_TEXTURE_2D, fs->groundid);
726 #endif /* HAVE_GLBINDTEXTURE */
727     }
728     else
729         glColor4f(0.54, 0.27, 0.07, 1.0);       /* untextured ground color */
730     glBegin(GL_QUADS);
731     glTexCoord2fv(qt[0]);
732     glVertex3fv(q[0]);
733     glTexCoord2fv(qt[1]);
734     glVertex3fv(q[1]);
735     glTexCoord2fv(qt[2]);
736     glVertex3fv(q[2]);
737     glTexCoord2fv(qt[3]);
738     glVertex3fv(q[3]);
739     mi->polygon_count++;
740     glEnd();
741
742     glAlphaFunc(GL_GEQUAL, 0.9);
743     if (fs->num_trees)
744     {
745         /* here do_texture IS True - and color used is white */
746         glEnable(GL_ALPHA_TEST);
747 #ifdef HAVE_GLBINDTEXTURE
748         glBindTexture(GL_TEXTURE_2D,fs->treeid);
749 #endif /* HAVE_GLBINDTEXTURE */
750         for(j=0;j<fs->num_trees;j++)
751       mi->polygon_count += drawtree(fs->treepos[j].x ,fs->treepos[j].y ,fs->treepos[j].z );
752         glDisable(GL_ALPHA_TEST);
753     }
754     glDisable(GL_TEXTURE_2D);
755     glDepthMask(GL_FALSE);
756
757     if (fs->shadows) {
758         /* draw shadows with black color */
759         glBegin(wire ? GL_LINE_STRIP : GL_TRIANGLES);
760         for (j = 0; j < fs->np; j++) {
761             glColor4f(black[0], black[1], black[2], fs->p[j].c[0][3]);
762             glVertex3f(fs->p[j].p[0][0], 0.1, fs->p[j].p[0][2]);
763
764             glColor4f(black[0], black[1], black[2], fs->p[j].c[1][3]);
765             glVertex3f(fs->p[j].p[1][0], 0.1, fs->p[j].p[1][2]);
766
767             glColor4f(black[0], black[1], black[2], fs->p[j].c[2][3]);
768             glVertex3f(fs->p[j].p[2][0], 0.1, fs->p[j].p[2][2]);
769         mi->polygon_count++;
770         }
771         glEnd();
772     }
773
774     glBegin(wire ? GL_LINE_STRIP : GL_TRIANGLES);
775     for (j = 0; j < fs->np; j++) {
776         /* draw particles: colors are computed in setpart */
777         glColor4fv(fs->p[j].c[0]);
778         glVertex3fv(fs->p[j].p[0]);
779
780         glColor4fv(fs->p[j].c[1]);
781         glVertex3fv(fs->p[j].p[1]);
782
783         glColor4fv(fs->p[j].c[2]);
784         glVertex3fv(fs->p[j].p[2]);
785     mi->polygon_count++;
786
787         setpart(fs, &fs->p[j]);
788     }
789     glEnd();
790
791     /* draw rain particles if no fire particles */
792     if (!fs->np)
793     {
794         float timeused = gettimerain();
795         glDisable(GL_TEXTURE_2D);
796         glShadeModel(GL_SMOOTH);
797         glBegin(GL_LINES);
798         for (j = 0; j < NUMPART; j++) {
799             glColor4f(0.7f,0.95f,1.0f,0.0f);
800             glVertex3fv(fs->r[j].oldpos);
801             glColor4f(0.3f,0.7f,1.0f,1.0f);
802             glVertex3fv(fs->r[j].pos);
803             setpartrain(fs, &fs->r[j],timeused);
804         mi->polygon_count++;
805         }
806         glEnd();
807         glShadeModel(GL_FLAT);
808     }
809
810     glDisable(GL_TEXTURE_2D);
811     glDisable(GL_ALPHA_TEST);
812     glDisable(GL_DEPTH_TEST);
813     glDisable(GL_FOG);
814
815     /* manage framerate display */
816     if (MI_IS_FPS(mi)) do_fps (mi);
817     glPopMatrix();
818 }
819
820
821 static Bool Init(ModeInfo * mi)
822 {
823     int i;
824     firestruct *fs = &fire[MI_SCREEN(mi)];
825
826     /* default settings */
827     fs->eject_r = 0.1 + NRAND(10) * 0.03;
828     fs->dt = 0.015;
829     fs->eject_vy = 4;
830     fs->eject_vl = 1;
831     fs->ridtri = 0.1 + NRAND(10) * 0.005;
832     fs->maxage = 1.0 / fs->dt;
833     vinit(fs->obs, DEF_OBS[0], DEF_OBS[1], DEF_OBS[2]);
834     fs->v = 0.0;
835     fs->alpha = DEF_ALPHA;
836     fs->beta = DEF_BETA;
837
838     /* initialise texture stuff */
839     if (do_texture)
840         inittextures(mi);
841     else
842     {
843         fs->ttexture = (XImage*) NULL;
844         fs->gtexture = (XImage*) NULL;
845     }
846
847     if (MI_IS_DEBUG(mi)) {
848         (void) fprintf(stderr,
849                        "%s:\n\tnum_part=%d\n\ttrees=%d\n\tfog=%s\n\tshadows=%s\n\teject_r=%.3f\n\tridtri=%.3f\n",
850                        MI_NAME(mi),
851                        fs->np,
852                        fs->num_trees,
853                        fs->fog ? "on" : "off",
854                        fs->shadows ? "on" : "off",
855                        fs->eject_r, fs->ridtri);
856     }
857
858     /* initialise particles and trees */
859     for (i = 0; i < fs->np; i++) {
860         setnewpart(fs, &(fs->p[i]));
861     }
862
863     if (fs->num_trees)
864         if (!inittree(mi)) {
865                 return False;
866         }
867
868     /* if no fire particles then initialise rain particles */
869     if (!fs->np)
870     {
871         vinit(fs->min,-7.0f,-0.2f,-7.0f);
872         vinit(fs->max,7.0f,8.0f,7.0f);
873         for (i = 0; i < NUMPART; i++) {
874             setnewrain(fs, &(fs->r[i]));
875         }
876     }
877     
878     return True;
879 }
880
881 /*
882  *-----------------------------------------------------------------------------
883  *-----------------------------------------------------------------------------
884  *    Xlock hooks.
885  *-----------------------------------------------------------------------------
886  *-----------------------------------------------------------------------------
887  */
888
889
890 static void
891 free_fire(firestruct *fs)
892 {
893         if (mode_font != None && fs->fontbase != None) {
894                 glDeleteLists(fs->fontbase, mode_font->max_char_or_byte2 -
895                         mode_font->min_char_or_byte2 + 1);
896                 fs->fontbase = None;
897         }
898
899         if (fs->p != NULL) {
900                 (void) free((void *) fs->p);
901                 fs->p = (part *) NULL;
902         }
903         if (fs->r != NULL) {
904                 (void) free((void *) fs->r);
905                 fs->r = (rain *) NULL;
906         }
907         if (fs->treepos != NULL) {
908                 (void) free((void *) fs->treepos);
909                 fs->treepos = (treestruct *) NULL;
910         }
911         if (fs->ttexture != None) {
912                 glDeleteTextures(1, &fs->treeid);
913                 XDestroyImage(fs->ttexture);
914                 fs->ttexture = None;
915         }
916         if (fs->gtexture != None) {
917                 glDeleteTextures(1, &fs->groundid);
918                 XDestroyImage(fs->gtexture);
919                 fs->gtexture = None;
920         }
921 }
922
923 /*
924  *-----------------------------------------------------------------------------
925  *    Initialize fire.  Called each time the window changes.
926  *-----------------------------------------------------------------------------
927  */
928
929 ENTRYPOINT void
930 init_fire(ModeInfo * mi)
931 {
932     firestruct *fs;
933
934     MI_INIT (mi, fire, 0);
935     fs = &fire[MI_SCREEN(mi)];
936     fs->np = MI_COUNT(mi);
937     fs->fog = do_fog;
938     fs->shadows = do_shadows;
939     /* initialise fire particles if any */
940     if ((fs->np)&&(fs->p == NULL)) {
941         if ((fs->p = (part *) calloc(fs->np, sizeof(part))) == NULL) {
942             free_fire(fs);
943             return;
944         }
945     }
946     else if (fs->r == NULL) {
947         /* initialise rain particles if no fire particles */
948         if ((fs->r = (rain *) calloc(NUMPART, sizeof(part))) == NULL) {
949             free_fire(fs);
950             return;
951         }
952     }
953
954     /* check tree number */
955     if (do_texture)
956         fs->num_trees = (num_trees<MAX_TREES)?num_trees:MAX_TREES;
957     else
958         fs->num_trees = 0;
959
960     fs->trackball = gltrackball_init (False);
961
962     /* xlock GL stuff */
963     if ((fs->glx_context = init_GL(mi)) != NULL) {
964
965 #ifndef STANDALONE
966         Reshape(mi); /* xlock mode */
967 #else
968         reshape_fire(mi,MI_WIDTH(mi),MI_HEIGHT(mi)); /* xscreensaver mode */
969 #endif
970         glDrawBuffer(GL_BACK);
971         if (!Init(mi)) {
972                 free_fire(fs);
973                 return;
974         }
975     } else {
976         MI_CLEARWINDOW(mi);
977     }
978 }
979
980 /*
981  *-----------------------------------------------------------------------------
982  *    Called by the mainline code periodically to update the display.
983  *-----------------------------------------------------------------------------
984  */
985 ENTRYPOINT void draw_fire(ModeInfo * mi)
986 {
987     firestruct *fs = &fire[MI_SCREEN(mi)];
988
989     Display *display = MI_DISPLAY(mi);
990     Window window = MI_WINDOW(mi);
991
992     MI_IS_DRAWN(mi) = True;
993
994     if (!fs->glx_context)
995         return;
996
997     glXMakeCurrent(display, window, *(fs->glx_context));
998
999     glShadeModel(GL_FLAT);
1000     glEnable(GL_DEPTH_TEST);
1001
1002     /* makes particles blend with background */
1003     if (!MI_IS_WIREFRAME(mi)||(!fs->np))
1004     {
1005         glEnable(GL_BLEND);
1006         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1007     }
1008
1009     /* fog stuff */
1010     glEnable(GL_FOG);
1011     glFogi(GL_FOG_MODE, GL_EXP);
1012     glFogfv(GL_FOG_COLOR, fogcolor);
1013     glFogf(GL_FOG_DENSITY, 0.03);
1014     glHint(GL_FOG_HINT, GL_NICEST);
1015
1016     glPushMatrix();
1017     glRotatef(current_device_rotation(), 0, 0, 1);
1018     DrawFire(mi);
1019     glPopMatrix();
1020 #ifndef STANDALONE
1021     Reshape(mi); /* xlock mode */
1022 #else
1023     reshape_fire(mi,MI_WIDTH(mi),MI_HEIGHT(mi)); /* xscreensaver mode */
1024 #endif
1025
1026     glFinish();
1027     glXSwapBuffers(display, window);
1028 }
1029
1030
1031 /*
1032  *-----------------------------------------------------------------------------
1033  *    The display is being taken away from us.  Free up malloc'ed
1034  *      memory and X resources that we've alloc'ed.  Only called
1035  *      once, we must zap everything for every screen.
1036  *-----------------------------------------------------------------------------
1037  */
1038
1039 ENTRYPOINT void release_fire(ModeInfo * mi)
1040 {
1041     if (fire != NULL) {
1042     int screen;
1043         for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
1044                 free_fire(&fire[screen]);
1045         (void) free((void *) fire);
1046         fire = (firestruct *) NULL;
1047     }
1048     if (mode_font != None)
1049     {
1050         /* only free-ed when there are no more screens used */
1051         XFreeFont(MI_DISPLAY(mi), mode_font);
1052         mode_font = None;
1053     }
1054     FreeAllGL(mi);
1055 }
1056
1057 ENTRYPOINT Bool
1058 fire_handle_event (ModeInfo *mi, XEvent *event)
1059 {
1060   firestruct *fs = &fire[MI_SCREEN(mi)];
1061
1062   if (gltrackball_event_handler (event, fs->trackball,
1063                                  MI_WIDTH (mi), MI_HEIGHT (mi),
1064                                  &fs->button_down_p))
1065     return True;
1066
1067   return False;
1068 }
1069
1070
1071 #ifndef STANDALONE
1072 ENTRYPOINT void change_fire(ModeInfo * mi)
1073 {
1074     firestruct *fs = &fire[MI_SCREEN(mi)];
1075
1076     if (!fs->glx_context)
1077         return;
1078
1079     glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(fs->glx_context));
1080
1081     /* if available, randomly change some values */
1082     if (do_fog)
1083         fs->fog = LRAND() & 1;
1084     if (do_shadows)
1085         fs->shadows = LRAND() & 1;
1086     /* reset observer position */
1087     frame = 0;
1088     vinit(fs->obs, DEF_OBS[0], DEF_OBS[1], DEF_OBS[2]);
1089     fs->v = 0.0;
1090     /* particle randomisation */
1091     fs->eject_r = 0.1 + NRAND(10) * 0.03;
1092     fs->ridtri = 0.1 + NRAND(10) * 0.005;
1093
1094     if (MI_IS_DEBUG(mi)) {
1095         (void) fprintf(stderr,
1096                        "%s:\n\tnum_part=%d\n\ttrees=%d\n\tfog=%s\n\tshadows=%s\n\teject_r=%.3f\n\tridtri=%.3f\n",
1097                        MI_NAME(mi),
1098                        fs->np,
1099                        fs->num_trees,
1100                        fs->fog ? "on" : "off",
1101                        fs->shadows ? "on" : "off",
1102                        fs->eject_r, fs->ridtri);
1103     }
1104 }
1105 #endif /* !STANDALONE */
1106
1107 XSCREENSAVER_MODULE_2 ("GLForestFire", glforestfire, fire)
1108
1109 #endif /* MODE_fire */