From http://www.jwz.org/xscreensaver/xscreensaver-5.35.tar.gz
[xscreensaver] / hacks / glx / engine.c
1 /*
2  * engine.c - GL representation of a 4 stroke engine
3  *
4  * version 2.00
5  *
6  * Copyright (C) 2001 Ben Buxton (bb@cactii.net)
7  * modified by Ed Beroset (beroset@mindspring.com)
8  *  new to 2.0 version is:
9  *  - command line argument to specify number of cylinders
10  *  - command line argument to specify included angle of engine
11  *  - removed broken command line argument to specify rotation speed
12  *  - included crankshaft shapes and firing orders for real engines
13  *    verified using the Bosch _Automotive Handbook_, 5th edition, pp 402,403
14  *
15  * Permission to use, copy, modify, distribute, and sell this software and its
16  * documentation for any purpose is hereby granted without fee, provided that
17  * the above copyright notice appear in all copies and that both that
18  * copyright notice and this permission notice appear in supporting
19  * documentation.  No representations are made about the suitability of this
20  * software for any purpose.  It is provided "as is" without express or
21  * implied warranty.
22  */
23
24 #ifdef STANDALONE
25 #define DEFAULTS        "*delay:           30000        \n" \
26                         "*showFPS:         False        \n" \
27                         "*suppressRotationAnimation: True\n" \
28         "*titleFont:  -*-helvetica-medium-r-normal-*-*-180-*-*-*-*-*-*\n" \
29
30 # define refresh_engine 0
31 # include "xlockmore.h"              /* from the xscreensaver distribution */
32 #else  /* !STANDALONE */
33 # include "xlock.h"                  /* from the xlockmore distribution */
34 #endif /* !STANDALONE */
35
36 #include "texfont.h"
37 #include "rotator.h"
38 #include "gltrackball.h"
39
40 /* lifted from lament.c */
41 #define RAND(n) ((long) ((random() & 0x7fffffff) % ((long) (n))))
42 #define RANDSIGN() ((random() & 1) ? 1 : -1)
43
44
45 #ifdef USE_GL
46
47 #define DEF_ENGINE "(none)"
48 #define DEF_TITLES "False"
49 #define DEF_SPIN   "True"
50 #define DEF_MOVE   "True"
51
52 #undef countof
53 #define countof(x) (sizeof((x))/sizeof((*x)))
54
55 static char *which_engine;
56 static int move;
57 static int spin;
58 static Bool do_titles;
59
60 static XrmOptionDescRec opts[] = {
61   {"-engine",  ".engine.engine", XrmoptionSepArg, DEF_ENGINE },
62   {"-move",    ".engine.move",   XrmoptionNoArg, "True"  },
63   {"+move",    ".engine.move",   XrmoptionNoArg, "False" },
64   {"-spin",    ".engine.spin",   XrmoptionNoArg, "True"  },
65   {"+spin",    ".engine.spin",   XrmoptionNoArg, "False" },
66   { "-titles", ".engine.titles", XrmoptionNoArg, "True"  },
67   { "+titles", ".engine.titles", XrmoptionNoArg, "False" },
68 };
69
70 static argtype vars[] = {
71   {&which_engine, "engine", "Engine", DEF_ENGINE, t_String},
72   {&move,         "move",   "Move",   DEF_MOVE,   t_Bool},
73   {&spin,         "spin",   "Spin",   DEF_SPIN,   t_Bool},
74   {&do_titles,    "titles", "Titles", DEF_TITLES, t_Bool},
75 };
76
77 ENTRYPOINT ModeSpecOpt engine_opts = {countof(opts), opts, countof(vars), vars, NULL};
78
79 #ifdef USE_MODULES
80 ModStruct   engine_description =
81 {"engine", "init_engine", "draw_engine", "release_engine",
82  "draw_engine", "init_engine", NULL, &engine_opts,
83  1000, 1, 2, 1, 4, 1.0, "",
84  "A four stroke engine", 0, NULL};
85
86 #endif
87
88 /* these defines are used to provide symbolic means
89  * by which to refer to various portions or multiples
90  * of a cyle in degrees
91  */
92 #define HALFREV 180
93 #define ONEREV 360
94 #define TWOREV 720
95
96 #define MOVE_MULT 0.05
97
98 #define RAND_RANGE(min, max) ((min) + (max - min) * f_rand())
99
100
101 typedef struct {
102   GLXContext *glx_context;
103   Window window;
104   GLfloat x, y, z; /* position */
105   GLfloat dx, dy, dz; /* position */
106   GLfloat an1, an2, an3; /* internal angle */
107   GLfloat nx, ny, nz; /* spin vector */
108   GLfloat a; /* spin angle */
109   GLfloat da; /* spin speed */
110   rotator *rot;
111   trackball_state *trackball;
112   Bool button_down_p;
113   texture_font_data *font_data;
114   char *engine_name;
115   int engineType;
116   int movepaused;
117
118   float crankOffset;
119   float crankWidth;
120
121   int win_w, win_h;
122
123   float sin_table[TWOREV];
124   float cos_table[TWOREV];
125   float tan_table[TWOREV];
126
127   GLfloat boom_red[4];
128   GLfloat boom_lpos[4];
129   GLfloat boom_d, boom_wd;
130   int boom_time;
131
132   GLfloat viewer[3], lookat[3];
133
134   int display_a;
135   GLfloat ln[730], yp[730], ang[730];
136   int ln_init;
137   int lastPlug;
138
139   GLuint shaft_list, piston_list;
140   int shaft_polys, piston_polys;
141
142 } Engine;
143
144 static Engine *engine = NULL;
145
146 static const GLfloat lightpos[] = {7.0, 7.0, 12, 1.0};
147 static const GLfloat light_sp[] = {0.8, 0.8, 0.8, 0.5};
148 static const GLfloat red[] = {1.0, 0, 0, 1.0};
149 static const GLfloat green[] = {0.0, 1, 0, 1.0};
150 static const GLfloat blue[] = {0, 0, 1, 1.0};
151 static const GLfloat white[] = {1.0, 1, 1, 1.0};
152 static const GLfloat yellow_t[] = {1, 1, 0, 0.4};
153
154 static GLvoid normal(GLfloat [], GLfloat [], GLfloat [], 
155                   GLfloat *, GLfloat *, GLfloat *);
156
157 /* 
158  * this table represents both the firing order and included angle of engine.
159  * To simplify things, we always number from 0 starting at the flywheel and 
160  * moving down the crankshaft toward the back of the engine.  This doesn't
161  * always match manufacturer's schemes.  For example, the Porsche 911 engine
162  * is a flat six with the following configuration (Porsche's numbering):
163  *
164  *    3  2  1
165  *  |=            firing order is 1-6-2-4-3-5 in this diagram
166  *     6  5  4
167  *
168  * We renumber these using our scheme but preserve the effective firing order:
169  *
170  *   0  2  4
171  * |=             firing order is 4-1-2-5-0-3 in this diagram
172  *    1  3  5
173  *
174  * To avoid going completely insane, we also reorder these so the newly 
175  * renumbered cylinder 0 is always first: 0-3-4-1-2-5
176  *   
177  * For a flat 6, the included angle is 180 degrees (0 would be a inline
178  * engine).  Because these are all four-stroke engines, each piston goes
179  * through 720 degrees of rotation for each time the spark plug sparks,
180  * so in this case, we would use the following angles:
181  *
182  * cylinder     firing order     angle
183  * --------     ------------     -----
184  *    0               0             0
185  *    1               3           360
186  *    2               4           240
187  *    3               1           600
188  *    4               2           480
189  *    5               5           120
190  *
191  */
192
193 typedef struct 
194 {
195     int cylinders;
196     int includedAngle;
197     int pistonAngle[12];  /* twelve cylinders should suffice... */
198     int speed;          /*  step size in degrees for engine speed */
199     const char *engineName;  /* currently unused */
200 } engine_type;
201
202 static const engine_type engines[] = {
203     { 3,   0, { 0, 240, 480,   0,   0,   0,
204                 0,   0,   0,   0,   0,   0 }, 12,
205      "Honda Insight" },
206     { 4,   0, { 0, 180, 540, 360,   0,   0,
207                 0,   0,   0,   0,   0,   0 }, 12,
208      "BMW M3" },
209     { 4, 180, { 0, 360, 180, 540,   0,   0,
210                 0,   0,   0,   0,   0,   0 }, 12,
211      "VW Beetle" },
212     { 5,   0, { 0, 576, 144, 432, 288,   0,
213                 0,   0,   0,   0,   0,   0 }, 12,
214      "Audi Quattro" },
215     { 6,   0, { 0, 240, 480, 120, 600, 360,
216                 0,   0,   0,   0,   0,   0 }, 12,
217      "BMW M5" },
218     { 6,  90, { 0, 360, 480, 120, 240, 600,
219                 0,   0,   0,   0,   0,   0 }, 12,
220      "Subaru XT" },
221     { 6, 180, { 0, 360, 240, 600, 480, 120,
222                 0,   0,   0,   0,   0,   0 }, 12,
223      "Porsche 911" },
224     { 8,  90, { 0, 450,  90, 180, 270, 360,
225               540, 630,   0,   0,   0,   0 }, 15,
226      "Corvette Z06" },
227     {10,  90, { 0,  72, 432, 504, 288, 360,
228               144, 216, 576, 648,   0,   0 }, 12,
229      "Dodge Viper" },
230     {12,  60, { 0, 300, 240, 540, 480,  60,
231               120, 420, 600, 180, 360, 660 }, 12,
232      "Jaguar XKE" },
233 };
234
235 /* this define is just a little shorter way of referring to members of the 
236  * table above
237  */
238 #define ENG engines[e->engineType]
239
240 /* given a number of cylinders and an included angle, finds matching engine */
241 static int
242 find_engine(char *name)
243 {
244   unsigned int i;
245   char *s;
246
247   if (!name || !*name || !strcasecmp (name, "(none)"))
248     return (random() % countof(engines));
249
250   for (s = name; *s; s++)
251     if (*s == '-' || *s == '_') *s = ' ';
252
253   for (i = 0; i < countof(engines); i++) {
254     if (!strcasecmp(name, engines[i].engineName))
255       return i;
256   }
257
258   fprintf (stderr, "%s: unknown engine type \"%s\"\n", progname, name);
259   fprintf (stderr, "%s: available models are:\n", progname);
260   for (i = 0; i < countof(engines); i++) {
261     fprintf (stderr, "\t %-13s (%d cylinders",
262              engines[i].engineName, engines[i].cylinders);
263     if (engines[i].includedAngle == 0)
264       fprintf (stderr, ")\n");
265     else if (engines[i].includedAngle == 180)
266       fprintf (stderr, ", flat)\n");
267     else
268       fprintf (stderr, ", V)\n");
269   }
270   exit(1);
271 }
272
273 /* we use trig tables to speed things up - 200 calls to sin()
274  in one frame can be a bit harsh..
275 */
276
277 static void make_tables(Engine *e)
278 {
279   int i;
280   float f;
281
282   f = ONEREV / (M_PI * 2);
283   for (i = 0 ; i < TWOREV ; i++) {
284     e->sin_table[i] = sin(i/f);
285   }
286   for (i = 0 ; i < TWOREV ; i++) {
287     e->cos_table[i] = cos(i/f);
288   }
289   for (i = 0 ; i < TWOREV ; i++) {
290     e->tan_table[i] = tan(i/f);
291   }
292 }
293
294 /* if inner and outer are the same, we draw a cylinder, not a tube */
295 /* for a tube, endcaps is 0 (none), 1 (left), 2 (right) or 3(both) */
296 /* angle is how far around the axis to go (up to 360) */
297
298 static int cylinder (Engine *e, GLfloat x, GLfloat y, GLfloat z, 
299     float length, float outer, float inner, int endcaps, int sang, int eang)
300 {
301   int polys = 0;
302   int a; /* current angle around cylinder */
303   int b = 0; /* previous */
304   int angle, norm, step, sangle;
305   float z1, y1, z2, y2, ex=0;
306   float Z1, Y1, Z2, Y2, xl;
307   GLfloat y2c[TWOREV], z2c[TWOREV];
308   int nsegs, tube = 0;
309
310   glPushMatrix();
311   nsegs = outer*(MAX(e->win_w, e->win_h)/200);
312   nsegs = MAX(nsegs, 6);
313   nsegs = MAX(nsegs, 40);
314   if (nsegs % 2)
315      nsegs += 1;
316   sangle = sang;
317   angle = eang;
318   z1 = e->cos_table[sangle]*outer+z; y1 = e->sin_table[sangle] * outer+y;
319   Z1 = e->cos_table[sangle] * inner+z; Y1 = e->sin_table[sangle]*inner+y ; 
320   Z2 = z;
321   Y2 = y;
322   xl = x + length;
323   if (inner < outer && endcaps < 3) tube = 1;
324   step = ONEREV/nsegs;
325
326   glBegin(GL_QUADS);
327   for (a = sangle ; a <= angle || b <= angle ; a+= step) {
328     y2=outer*(float)e->sin_table[a]+y;
329     z2=outer*(float)e->cos_table[a]+z;
330     if (endcaps) {
331        y2c[a] = y2;
332        z2c[a] = z2; /* cache for later */
333     }
334     if (tube) {
335       Y2=inner*(float)e->sin_table[a]+y;
336       Z2=inner*(float)e->cos_table[a]+z;
337     }
338     glNormal3f(0, y1, z1);
339     glVertex3f(x,y1,z1);
340     glVertex3f(xl,y1,z1);
341     glNormal3f(0, y2, z2);
342     glVertex3f(xl,y2,z2);
343     glVertex3f(x,y2,z2);
344     polys++;
345     if (a == sangle && angle - sangle < ONEREV) {
346       if (tube)
347         glVertex3f(x, Y1, Z1);
348       else
349         glVertex3f(x, y, z);
350       glVertex3f(x, y1, z1);
351       glVertex3f(xl, y1, z1);
352       if (tube)
353         glVertex3f(xl, Z1, Z1);
354       else
355         glVertex3f(xl, y, z);
356       polys++;
357     }
358     if (tube) {
359       if (endcaps != 1) {
360         glNormal3f(-1, 0, 0); /* left end */
361         glVertex3f(x, y1, z1);
362         glVertex3f(x, y2, z2);
363         glVertex3f(x, Y2, Z2);
364         glVertex3f(x, Y1, Z1);
365         polys++;
366       }
367
368       glNormal3f(0, -Y1, -Z1); /* inner surface */
369       glVertex3f(x, Y1, Z1);
370       glVertex3f(xl, Y1, Z1);
371       glNormal3f(0, -Y2, -Z2);
372       glVertex3f(xl, Y2, Z2);
373       glVertex3f(x, Y2, Z2);
374       polys++;
375
376       if (endcaps != 2) {
377         glNormal3f(1, 0, 0); /* right end */
378         glVertex3f(xl, y1, z1);
379         glVertex3f(xl, y2, z2);
380         glVertex3f(xl, Y2, Z2);
381         glVertex3f(xl, Y1, Z1);
382         polys++;
383       }
384     }
385
386     z1=z2; y1=y2;
387     Z1=Z2; Y1=Y2;
388     b = a;
389   }
390   glEnd();
391
392   if (angle - sangle < ONEREV) {
393     GLfloat nx, ny, nz;
394     GLfloat v1[3], v2[3], v3[3];
395     v1[0] = x; v1[1] = y; v1[2] = z;
396     v2[0] = x; v2[1] = y1; v2[2] = z1;
397     v3[0] = xl; v3[1] = y1; v3[2] = z1;
398     normal(&v2[0], &v1[0], &v3[0], &nx, &ny, &nz);
399     glBegin(GL_QUADS);
400     glNormal3f(nx, ny, nz);
401     glVertex3f(x, y, z);
402     glVertex3f(x, y1, z1);
403     glVertex3f(xl, y1, z1);
404     glVertex3f(xl, y, z);
405     polys++;
406     glEnd();
407   }
408   if (endcaps) {
409     GLfloat end, start;
410     if (tube) {
411       if (endcaps == 1) {
412         end = 0;
413         start = 0;
414       } else if (endcaps == 2) {
415         start = end = length+0.01;
416       } else {
417         end = length+0.02; start = -0.01;
418       }
419       norm = (ex == length+0.01) ? -1 : 1;
420     } else  {
421       end = length;
422       start = 0;
423       norm = -1;
424     }
425
426     for(ex = start ; ex <= end ; ex += length) {
427       z1 = outer*e->cos_table[sangle]+z;
428       y1 = y+e->sin_table[sangle]*outer;
429       step = ONEREV/nsegs;
430       glBegin(GL_TRIANGLES);
431       b = 0;
432       for (a = sangle ; a <= angle || b <= angle; a+= step) {
433           glNormal3f(norm, 0, 0);
434           glVertex3f(x+ex,y, z);
435           glVertex3f(x+ex,y1,z1);
436           glVertex3f(x+ex,y2c[a],z2c[a]);
437           polys++;
438         y1 = y2c[a]; z1 = z2c[a];
439         b = a;
440       }
441       if (!tube) norm = 1;
442       glEnd();
443     }
444   }
445   glPopMatrix();
446   return polys;
447 }
448
449 /* this is just a convenience function to make a solid rod */
450 static int rod (Engine *e, GLfloat x, GLfloat y, GLfloat z, float length, float diameter)
451 {
452     return cylinder(e, x, y, z, length, diameter, diameter, 3, 0, ONEREV);
453 }
454
455 static GLvoid normal(GLfloat v1[], GLfloat v2[], GLfloat v3[], 
456                   GLfloat *nx, GLfloat *ny, GLfloat *nz)
457 {
458    GLfloat x, y, z, X, Y, Z;
459
460    x = v2[0]-v1[0];
461    y = v2[1]-v1[1];
462    z = v2[2]-v1[2];
463    X = v3[0]-v1[0];
464    Y = v3[1]-v1[1];
465    Z = v3[2]-v1[2];
466
467    *nx = Y*z - Z*y;
468    *ny = Z*x - X*z;
469    *nz = X*y - Y*x;
470
471
472
473
474
475 static int Rect(GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLfloat h,
476             GLfloat t)
477 {
478   int polys = 0;
479   GLfloat yh;
480   GLfloat xw;
481   GLfloat zt;
482
483   yh = y+h; xw = x+w; zt = z - t;
484
485   glBegin(GL_QUADS); /* front */
486     glNormal3f(0, 0, 1);
487     glVertex3f(x, y, z);
488     glVertex3f(x, yh, z);
489     glVertex3f(xw, yh, z);
490     glVertex3f(xw, y, z);
491     polys++;
492   /* back */
493     glNormal3f(0, 0, -1);
494     glVertex3f(x, y, zt);
495     glVertex3f(x, yh, zt);
496     glVertex3f(xw, yh, zt);
497     glVertex3f(xw, y, zt);
498     polys++;
499   /* top */
500     glNormal3f(0, 1, 0);
501     glVertex3f(x, yh, z);
502     glVertex3f(x, yh, zt);
503     glVertex3f(xw, yh, zt);
504     glVertex3f(xw, yh, z);
505     polys++;
506   /* bottom */
507     glNormal3f(0, -1, 0);
508     glVertex3f(x, y, z);
509     glVertex3f(x, y, zt);
510     glVertex3f(xw, y, zt);
511     glVertex3f(xw, y, z);
512     polys++;
513   /* left */
514     glNormal3f(-1, 0, 0);
515     glVertex3f(x, y, z);
516     glVertex3f(x, y, zt);
517     glVertex3f(x, yh, zt);
518     glVertex3f(x, yh, z);
519     polys++;
520   /* right */
521     glNormal3f(1, 0, 0);
522     glVertex3f(xw, y, z);
523     glVertex3f(xw, y, zt);
524     glVertex3f(xw, yh, zt);
525     glVertex3f(xw, yh, z);
526     polys++;
527   glEnd();
528   return polys;
529 }
530
531 static int makepiston(Engine *e)
532 {
533   int polys = 0;
534   GLfloat colour[] = {0.6, 0.6, 0.6, 1.0};
535   
536   /* if (e->piston_list) glDeleteLists(1, e->piston_list); */
537   if (! e->piston_list) e->piston_list = glGenLists(1);
538   glNewList(e->piston_list, GL_COMPILE);
539   glRotatef(90, 0, 0, 1);
540   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colour);
541   glMaterialfv(GL_FRONT, GL_SPECULAR, colour);
542   glMateriali(GL_FRONT, GL_SHININESS, 20);
543   polys += cylinder(e, 0, 0, 0, 2, 1, 0.7, 2, 0, ONEREV); /* body */
544   colour[0] = colour[1] = colour[2] = 0.2;
545   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colour);
546   polys += cylinder(e, 1.6, 0, 0, 0.1, 1.05, 1.05, 0, 0, ONEREV); /* ring */
547   polys += cylinder(e, 1.8, 0, 0, 0.1, 1.05, 1.05, 0, 0, ONEREV); /* ring */
548   glEndList();
549   return polys;
550 }
551
552 static int CrankBit(Engine *e, GLfloat x)
553 {
554   int polys = 0;
555   polys += Rect(x, -1.4, 0.5, 0.2, 1.8, 1);
556   polys += cylinder(e, x, -0.5, 0, 0.2, 2, 2, 1, 60, 120);
557   return polys;
558 }
559
560 static int boom(Engine *e, GLfloat x, GLfloat y, int s)
561 {
562   int polys = 0;
563   int flameOut = 720/ENG.speed/ENG.cylinders;
564
565   if (e->boom_time == 0 && s) {
566     e->boom_red[0] = e->boom_red[1] = 0;
567     e->boom_d = 0.05;
568     e->boom_time++;
569     glEnable(GL_LIGHT1); 
570   } else if (e->boom_time == 0 && !s) {
571     return polys;
572   } else if (e->boom_time >= 8 && e->boom_time < flameOut && !s) {
573     e->boom_time++;
574     e->boom_red[0] -= 0.2; e->boom_red[1] -= 0.1;
575     e->boom_d-= 0.04;
576   } else if (e->boom_time >= flameOut) {
577     e->boom_time = 0;
578     glDisable(GL_LIGHT1);
579     return polys;
580   } else {
581     e->boom_red[0] += 0.2; e->boom_red[1] += 0.1;
582     e->boom_d += 0.04;
583     e->boom_time++;
584   }
585   e->boom_lpos[0] = x-e->boom_d; e->boom_lpos[1] = y;
586   glLightfv(GL_LIGHT1, GL_POSITION, e->boom_lpos);
587   glLightfv(GL_LIGHT1, GL_DIFFUSE, e->boom_red);
588   glLightfv(GL_LIGHT1, GL_SPECULAR, e->boom_red);
589   glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 1.3);
590   glLighti(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 0);
591
592   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, e->boom_red);
593   e->boom_wd = e->boom_d*3;
594   if (e->boom_wd > 0.7) e->boom_wd = 0.7;
595   glEnable(GL_BLEND);
596   glDepthMask(GL_FALSE);
597   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
598   polys += rod(e, x, y, 0, e->boom_d, e->boom_wd);
599   glDepthMask(GL_TRUE);
600   glDisable(GL_BLEND);
601   return polys;
602 }
603
604 static int display(ModeInfo *mi)
605 {
606  Engine *e = &engine[MI_SCREEN(mi)];
607   int polys = 0;
608   GLfloat zb, yb;
609   float rightSide;
610   int half;
611   int sides;
612   int j, b;
613
614   glEnable(GL_LIGHTING);
615   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
616   glLoadIdentity();
617   gluLookAt(e->viewer[0], e->viewer[1], e->viewer[2], 
618             e->lookat[0], e->lookat[1], e->lookat[2], 
619             0.0, 1.0, 0.0);
620   glPushMatrix();
621
622 # ifdef HAVE_MOBILE     /* Keep it the same relative size when rotated. */
623   {
624     GLfloat h = MI_HEIGHT(mi) / (GLfloat) MI_WIDTH(mi);
625     int o = (int) current_device_rotation();
626     if (o != 0 && o != 180 && o != -180)
627       glScalef (1/h, 1/h, 1/h);
628   }
629 # endif
630
631   glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
632   glLightfv(GL_LIGHT0, GL_SPECULAR, light_sp);
633   glLightfv(GL_LIGHT0, GL_DIFFUSE, light_sp);
634
635   if (move) {
636     double x, y, z;
637     get_position (e->rot, &x, &y, &z, !e->button_down_p);
638     glTranslatef(x*16-9, y*14-7, z*16-10);
639   }
640
641   if (spin) {
642     double x, y, z;
643
644     gltrackball_rotate (e->trackball);
645
646     get_rotation(e->rot, &x, &y, &z, !e->button_down_p);
647     glRotatef(x*ONEREV, 1.0, 0.0, 0.0);
648     glRotatef(y*ONEREV, 0.0, 1.0, 0.0);
649     glRotatef(x*ONEREV, 0.0, 0.0, 1.0);
650   }
651
652 /* So the rotation appears around the centre of the engine */
653   glTranslatef(-5, 0, 0); 
654
655 /* crankshaft */
656   glPushMatrix();
657   glRotatef(e->display_a, 1, 0, 0);
658   glCallList(e->shaft_list);
659   polys += e->shaft_polys;
660   glPopMatrix();
661
662   /* init the ln[] matrix for speed */
663   if (e->ln_init == 0) {
664     for (e->ln_init = 0 ; e->ln_init < countof(e->sin_table) ; e->ln_init++) {
665       zb = e->sin_table[e->ln_init];
666       yb = e->cos_table[e->ln_init];
667       /* y ordinate of piston */
668       e->yp[e->ln_init] = yb + sqrt(25 - (zb*zb)); 
669       /* length of rod */
670       e->ln[e->ln_init] = sqrt(zb*zb + (yb-e->yp[e->ln_init])*(yb-e->yp[e->ln_init])); 
671       /* angle of connecting rod */
672       e->ang[e->ln_init] = asin(zb/5)*57; 
673       e->ang[e->ln_init] *= -1;
674     }
675   }
676
677   glPushMatrix();
678   sides = (ENG.includedAngle == 0) ? 1 : 2;
679   for (half = 0; half < sides; half++, glRotatef(ENG.includedAngle,1,0,0))
680   {
681     /* pistons */
682       /* glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white); */
683       for (j = 0; j < ENG.cylinders; j += sides)
684       {
685         b = (e->display_a + ENG.pistonAngle[j+half]) % ONEREV;
686         glPushMatrix();
687         glTranslatef(e->crankWidth/2 + e->crankOffset*(j+half), e->yp[b]-0.3, 0);
688         glCallList(e->piston_list);
689         polys += e->piston_polys;
690         glPopMatrix();
691       }
692     /* spark plugs */
693       glPushMatrix();
694       glRotatef(90, 0, 0, 1); 
695       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red);
696       for (j = 0; j < ENG.cylinders; j += sides) 
697       {
698         polys += cylinder(e, 8.5, -e->crankWidth/2-e->crankOffset*(j+half), 0, 
699             0.5, 0.4, 0.3, 1, 0, ONEREV); 
700       }
701       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white);
702       for (j = 0; j < ENG.cylinders; j += sides)
703       {
704         polys += rod(e, 8, -e->crankWidth/2-e->crankOffset*(j+half), 0, 0.5, 0.2); 
705         polys += rod(e, 9, -e->crankWidth/2-e->crankOffset*(j+half), 0, 1, 0.15); 
706       }   
707
708      /* rod */
709       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
710       for (j = 0; j < ENG.cylinders; j += sides)
711       {
712           b = (e->display_a+HALFREV+ENG.pistonAngle[j+half]) % TWOREV; 
713           glPushMatrix();
714           glRotatef(e->ang[b], 0, 1, 0);
715           polys += rod(e, 
716               -e->cos_table[b],
717               -e->crankWidth/2-e->crankOffset*(j+half),
718               -e->sin_table[b], 
719               e->ln[b], 0.2);
720           glPopMatrix();
721       }
722       glPopMatrix();
723
724         /* engine block */
725       glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, yellow_t);
726       glEnable(GL_BLEND);
727       glDepthMask(GL_FALSE);
728       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
729       rightSide = (sides > 1) ? 0 : 1.6;
730     /* left plate */
731       polys += Rect(-e->crankWidth/2, -0.5,  1, 0.2, 9, 2);
732     /* right plate */
733       polys += Rect(0.3+e->crankOffset*ENG.cylinders-rightSide, -0.5, 1, 0.2, 9, 2);
734     /* head plate */
735       polys += Rect(-e->crankWidth/2+0.2, 8.3, 1, 
736             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 2);
737     /* front rail */
738       polys += Rect(-e->crankWidth/2+0.2, 3, 1, 
739             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 0.2);
740     /* back rail */
741       polys += Rect(-e->crankWidth/2+0.2, 3, -1+0.2, 
742             e->crankWidth/2+0.1+e->crankOffset*ENG.cylinders-rightSide, 0.2, 0.2);
743     /* plates between cylinders */
744       for (j=0; j < ENG.cylinders - (sides == 1); j += sides)
745         polys += Rect(0.4+e->crankWidth+e->crankOffset*(j-half), 3, 1, 1, 5.3, 2);
746       glDepthMask(GL_TRUE);
747   }
748   glPopMatrix();
749
750         /* see which of our plugs should fire now, if any */
751   for (j = 0; j < ENG.cylinders; j++)
752   {
753     if (0 == ((e->display_a + ENG.pistonAngle[j]) % TWOREV))
754     {
755         glPushMatrix();
756         if (j & 1) 
757             glRotatef(ENG.includedAngle,1,0,0);
758         glRotatef(90, 0, 0, 1); 
759         polys += boom(e, 8, -e->crankWidth/2-e->crankOffset*j, 1); 
760         e->lastPlug = j;
761         glPopMatrix();
762     }
763   }
764
765   if (e->lastPlug != j)
766   {
767     /* this code causes the last plug explosion to dim gradually */
768     if (e->lastPlug & 1) 
769       glRotatef(ENG.includedAngle, 1, 0, 0);
770     glRotatef(90, 0, 0, 1); 
771     polys += boom(e, 8, -e->crankWidth/2-e->crankOffset*e->lastPlug, 0); 
772   }
773   glDisable(GL_BLEND);
774
775   e->display_a += ENG.speed; 
776   if (e->display_a >= TWOREV) 
777     e->display_a = 0;
778   glPopMatrix();
779   glFlush();
780   return polys;
781 }
782
783 static int makeshaft (Engine *e)
784 {
785   int polys = 0;
786   int j;
787   float crankThick = 0.2;
788   float crankDiam = 0.3;
789
790   /* if (e->shaft_list) glDeleteLists(1, e->shaft_list); */
791   if (! e->shaft_list) e->shaft_list = glGenLists(1);
792   glNewList(e->shaft_list, GL_COMPILE);
793
794   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
795   /* draw the flywheel */
796   polys += cylinder(e, -2.5, 0, 0, 1, 3, 2.5, 0, 0, ONEREV);
797   polys += Rect(-2, -0.3, 2.8, 0.5, 0.6, 5.6);
798   polys += Rect(-2, -2.8, 0.3, 0.5, 5.6, 0.6);
799
800   /* now make each of the shaft bits between the cranks, 
801    * starting from the flywheel end which is at X-coord 0. 
802    * the first cranskhaft bit is always 2 units long 
803    */
804   polys += rod(e, -2, 0, 0, 2, crankDiam);
805
806   /* Each crank is crankWidth units wide and the total width of a
807    * cylinder assembly is 3.3 units. For inline engines, there is just
808    * a single crank per cylinder width.  For other engine
809    * configurations, there is a crank between each pair of adjacent
810    * cylinders on one side of the engine, so the crankOffset length is
811    * halved.
812    */
813   e->crankOffset = 3.3;
814   if (ENG.includedAngle != 0)
815     e->crankOffset /= 2;
816   for (j = 0; j < ENG.cylinders - 1; j++)
817     polys += rod(e,
818         e->crankWidth - crankThick + e->crankOffset*j, 0, 0, 
819         e->crankOffset - e->crankWidth + 2 * crankThick, crankDiam);
820   /* the last bit connects to the engine wall on the non-flywheel end */
821   polys += rod(e, e->crankWidth - crankThick + e->crankOffset*j, 0, 0, 0.9, crankDiam);
822
823
824   for (j = 0; j < ENG.cylinders; j++)
825   {
826     glPushMatrix();
827     if (j & 1)
828         glRotatef(HALFREV+ENG.pistonAngle[j]+ENG.includedAngle,1,0,0);
829     else
830         glRotatef(HALFREV+ENG.pistonAngle[j],1,0,0);
831     /* draw wrist pin */
832     glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue);
833     polys += rod(e, e->crankOffset*j, -1.0, 0.0, e->crankWidth, crankDiam);
834     glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
835     /* draw right part of crank */
836     polys += CrankBit(e, e->crankOffset*j); 
837     /* draw left part of crank */
838     polys += CrankBit(e, e->crankWidth-crankThick+e->crankOffset*j);
839     glPopMatrix();
840   }
841   glEndList();
842   return polys;
843 }
844
845
846 ENTRYPOINT void reshape_engine(ModeInfo *mi, int width, int height)
847 {
848  Engine *e = &engine[MI_SCREEN(mi)];
849  glViewport(0,0,(GLint)width, (GLint) height);
850  glMatrixMode(GL_PROJECTION);
851  glLoadIdentity();
852 /* glFrustum(-1.0,1.0,-1.0,1.0,1.5,70.0);*/
853  gluPerspective(40.0,((GLdouble)width)/height,1.5,70.0);
854  glMatrixMode(GL_MODELVIEW);
855  e->win_h = height; 
856  e->win_w = width;
857 }
858
859
860 ENTRYPOINT void init_engine(ModeInfo *mi)
861 {
862   int screen = MI_SCREEN(mi);
863   Engine *e;
864
865  if (engine == NULL) {
866    if ((engine = (Engine *) calloc(MI_NUM_SCREENS(mi),
867                                         sizeof(Engine))) == NULL)
868           return;
869  }
870  e = &engine[screen];
871  e->window = MI_WINDOW(mi);
872
873  e->x = e->y = e->z = e->a = e->an1 = e->nx = e->ny = e->nz = 
874  e->dx = e->dy = e->dz = e->da = 0;
875
876  if (move) {
877    e->dx = (float)(random() % 1000)/30000;
878    e->dy = (float)(random() % 1000)/30000;
879    e->dz = (float)(random() % 1000)/30000;
880  } else {
881   e->viewer[0] = 0; e->viewer[1] = 2; e->viewer[2] = 18;
882   e->lookat[0] = 0; e->lookat[1] = 0; e->lookat[2] = 0; 
883
884  }
885  if (spin) {
886    e->da = (float)(random() % 1000)/125 - 4;
887    e->nx = (float)(random() % 100) / 100;
888    e->ny = (float)(random() % 100) / 100;
889    e->nz = (float)(random() % 100) / 100;
890  }
891
892  {
893    double spin_speed = 0.5;
894    double wander_speed = 0.01;
895
896  e->crankWidth = 1.5;
897  e->boom_red[3] = 0.9;
898  e->boom_lpos[3] = 1;
899
900  e->viewer[2] = 30;
901
902  e->rot = make_rotator (spin ? spin_speed : 0,
903                         spin ? spin_speed : 0,
904                         spin ? spin_speed : 0,
905                         1.0,
906                         move ? wander_speed : 0,
907                         True);
908
909     e->trackball = gltrackball_init (True);
910  }
911
912  if (!e->glx_context &&   /* re-initting breaks print_texture_label */
913      (e->glx_context = init_GL(mi)) != NULL) {
914       reshape_engine(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
915  } else {
916      MI_CLEARWINDOW(mi);
917  }
918  glShadeModel(GL_SMOOTH);
919  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
920  glEnable(GL_DEPTH_TEST);
921  glEnable(GL_LIGHTING);
922  glEnable(GL_LIGHT0);
923  glEnable(GL_NORMALIZE);
924  make_tables(e);
925  e->engineType = find_engine(which_engine);
926
927  if (!e->engine_name)
928    e->engine_name = malloc(200);
929  sprintf (e->engine_name,
930           "%s\n%s%d%s",
931           engines[e->engineType].engineName,
932           (engines[e->engineType].includedAngle == 0 ? "" :
933            engines[e->engineType].includedAngle == 180 ? "Flat " : "V"),
934           engines[e->engineType].cylinders,
935           (engines[e->engineType].includedAngle == 0 ? " Cylinder" : "")
936           );
937
938  e->shaft_polys = makeshaft(e);
939  e->piston_polys = makepiston(e);
940
941  if (!e->font_data)
942    e->font_data = load_texture_font (mi->dpy, "titleFont");
943 }
944
945 ENTRYPOINT Bool
946 engine_handle_event (ModeInfo *mi, XEvent *event)
947 {
948    Engine *e = &engine[MI_SCREEN(mi)];
949
950    if (event->xany.type == ButtonPress &&
951        event->xbutton.button == Button1)
952    {
953        return True;
954    }
955    else if (event->xany.type == ButtonRelease &&
956             event->xbutton.button == Button1) {
957        e->movepaused = 0;
958    }
959
960   if (gltrackball_event_handler (event, e->trackball,
961                                  MI_WIDTH (mi), MI_HEIGHT (mi),
962                                  &e->button_down_p))
963     return True;
964   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
965     {
966       which_engine = NULL; /* randomize */
967       init_engine(mi);
968       return True;
969     }
970
971   return False;
972 }
973
974 ENTRYPOINT void draw_engine(ModeInfo *mi)
975 {
976   Engine *e = &engine[MI_SCREEN(mi)];
977   Window w = MI_WINDOW(mi);
978   Display *disp = MI_DISPLAY(mi);
979
980   if (!e->glx_context)
981     return;
982
983   glXMakeCurrent(disp, w, *(e->glx_context));
984
985
986   mi->polygon_count = display(mi);
987
988   glColor3f (1, 1, 0);
989   if (do_titles)
990       print_texture_label (mi->dpy, e->font_data,
991                            mi->xgwa.width, mi->xgwa.height,
992                            1, e->engine_name);
993
994   if(mi->fps_p) do_fps(mi);
995   glFinish(); 
996   glXSwapBuffers(disp, w);
997 }
998
999 ENTRYPOINT void
1000 release_engine(ModeInfo *mi) 
1001 {
1002   if (engine != NULL) {
1003    (void) free((void *) engine);
1004    engine = NULL;
1005   }
1006   FreeAllGL(mi);
1007 }
1008
1009 XSCREENSAVER_MODULE ("Engine", engine)
1010
1011 #endif