Lorenz attractor demo (John Fay)
[freeglut] / progs / demos / Lorenz / lorenz.c
1 /*
2  * Lorenz Strange Attractor
3  *
4  * Written by John F. Fay in honor of the "freeglut" 2.0.0 release in July 2003
5  *
6  * What it does:
7  *  This program starts with two particles right next to each other.  The particles
8  *  move through a three-dimensional phase space governed by the following equations:
9  *       dx/dt = sigma * ( y - x )
10  *       dy/dt = r * x - y + x * z
11  *       dz/dt = x * y + b * z
12  *  These are the Lorenz equations and define the "Lorenz Attractor."  Any two particles
13  *  arbitrarily close together will move apart as time increases, but their tracks are
14  *  confined within a region of the space.
15  *
16  * Commands:
17  *  Arrow keys:  Rotate the view
18  *  PgUp, PgDn:  Zoom in and out
19  *  Mouse click:  Center on the nearest point on a particle trajectory
20  *
21  *  'r'/'R':  Reset the simulation
22  *  'm'/'M':  Modify the Lorenz parameters (in the text window)
23  *  's'/'S':  Stop (the advancement in time)
24  *  'g'/'G':  Go
25  *  <spacebar>:  Single-step
26  *  <Escape>:  Quit
27  */
28
29 /* Include Files */
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>
34 #include <time.h>
35 #include <GL/freeglut.h>
36
37
38 /************************************** Defined Constants ***************************************/
39 /* Number of points to draw in the curves */
40 #define NUM_POINTS    512
41
42 /* Angle to rotate when the user presses an arrow key */
43 #define ROTATION_ANGLE  5.0
44
45 /* Amount to scale bu when the user presses PgUp or PgDn */
46 #define SCALE_FACTOR     0.8
47
48
49 /*************************************** Global Variables ***************************************/
50 /* Lorenz Attractor variables */
51 double s0 = 10.0, r0 = 28.0, b0 = 8.0/3.0 ;   /* Default Lorenz attactor parameters */
52 double time_step = 0.03 ;                     /* Time step in the simulation */
53 double sigma = 10.0, r = 28.0, b = 8.0/3.0 ;  /* Lorenz attactor parameters */
54 double red_position[NUM_POINTS][3] ;          /* Path of the red point */
55 double grn_position[NUM_POINTS][3] ;          /* Path of the green point */
56 int array_index ;                             /* Position in *_position arrays of most recent point */
57 double distance = 0.0 ;                       /* Distance between the two points */
58
59 /* GLUT variables */
60 double yaw = 0.0, pit = 0.0 ;                 /* Euler angles of the viewing rotation */
61 double scale = 1.0 ;                          /* Scale factor */
62 double xcen = 0.0, ycen = 0.0, zcen = 0.0 ;   /* Coordinates of the point looked at */
63
64 int animate = 1 ;                             /* 0 - stop, 1 = go, 2 = single-step */
65
66
67 /******************************************* Functions ******************************************/
68
69 /* The Lorenz Attractor */
70 void calc_deriv ( double position[3], double deriv[3] )
71 {
72   /* Calculate the Lorenz attractor derivatives */
73   deriv[0] = sigma * ( position[1] - position[0] ) ;
74   deriv[1] = ( r + position[2] ) * position[0] - position[1] ;
75   deriv[2] = -position[0] * position[1] - b * position[2] ;
76 }
77
78 void advance_in_time ( double time_step, double position[3], double new_position[3] )
79 {
80   /* Move a point along the Lorenz attractor */
81   double deriv0[3], deriv1[3], deriv2[3], deriv3[3] ;
82   int i ;
83   memcpy ( new_position, position, 3 * sizeof(double) ) ;  /* Save the present values */
84
85   /* First pass in a Fourth-Order Runge-Kutta integration method */
86   calc_deriv ( position, deriv0 ) ;
87   for ( i = 0; i < 3; i++ )
88     new_position[i] = position[i] + 0.5 * time_step * deriv0[i] ;
89
90   /* Second pass */
91   calc_deriv ( new_position, deriv1 ) ;
92   for ( i = 0; i < 3; i++ )
93     new_position[i] = position[i] + 0.5 * time_step * deriv1[i] ;
94
95   /* Third pass */
96   calc_deriv ( position, deriv2 ) ;
97   for ( i = 0; i < 3; i++ )
98     new_position[i] = position[i] + time_step * deriv2[i] ;
99
100   /* Second pass */
101   calc_deriv ( new_position, deriv3 ) ;
102   for ( i = 0; i < 3; i++ )
103     new_position[i] = position[i] + 0.1666666666666666667 * time_step *
104                       ( deriv0[i] + 2.0 * ( deriv1[i] + deriv2[i] ) + deriv3[i] ) ;
105 }
106
107 /* GLUT callbacks */
108
109 void key_cb ( unsigned char key, int x, int y )
110 {
111   int i ;
112   char inputline [ 80 ] ;
113
114   switch ( key )
115   {
116   case 'r' :  case 'R' :  /* Reset the simulation */
117     /* Reset the Lorenz parameters */
118     sigma = s0 ;
119     b = b0 ;
120     r = r0 ;
121     /* Set an initial position */
122     red_position[0][0] = (double)rand() / (double)RAND_MAX ;
123     red_position[0][1] = (double)rand() / (double)RAND_MAX ;
124     red_position[0][2] = (double)rand() / (double)RAND_MAX ;
125     grn_position[0][0] = (double)rand() / (double)RAND_MAX ;
126     grn_position[0][1] = (double)rand() / (double)RAND_MAX ;
127     grn_position[0][2] = (double)rand() / (double)RAND_MAX ;
128     array_index = 0 ;
129     /* Initialize the arrays */
130     for ( i = 1; i < NUM_POINTS; i++ )
131     {
132       memcpy ( red_position[i], red_position[0], 3 * sizeof(double) ) ;
133       memcpy ( grn_position[i], grn_position[0], 3 * sizeof(double) ) ;
134     }
135
136     break ;
137
138   case 'm' :  case 'M' :  /* Modify the Lorenz parameters */
139     printf ( "Please enter new value for <sigma> (default %lf, currently %lf): ", s0, sigma ) ;
140     fgets ( inputline, 79, stdin ) ;
141     sscanf ( inputline, "%lf", &sigma ) ;
142
143     printf ( "Please enter new value for <b> (default %lf, currently %lf): ", b0, b ) ;
144     fgets ( inputline, 79, stdin ) ;
145     sscanf ( inputline, "%lf", &b ) ;
146
147     printf ( "Please enter new value for <r> (default %lf, currently %lf): ", r0, r ) ;
148     fgets ( inputline, 79, stdin ) ;
149     sscanf ( inputline, "%lf", &r ) ;
150
151     break ;
152
153   case 's' :  case 'S' :  /* Stop the animation */
154     animate = 0 ;
155     break ;
156
157   case 'g' :  case 'G' :  /* Start the animation */
158     animate = 1 ;
159     break ;
160
161   case ' ' :  /* Spacebar:  Single step */
162     animate = 2 ;
163     break ;
164
165   case 27 :  /* Escape key */
166     glutLeaveMainLoop () ;
167     break ;
168   }
169 }
170
171 void special_cb ( int key, int x, int y )
172 {
173   switch ( key )
174   {
175   case GLUT_KEY_UP :  /* Rotate up a little */
176     glRotated ( ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
177     break ;
178
179   case GLUT_KEY_DOWN :  /* Rotate down a little */
180     glRotated ( -ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
181     break ;
182
183   case GLUT_KEY_LEFT :  /* Rotate left a little */
184     glRotated ( ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
185     break ;
186
187   case GLUT_KEY_RIGHT :  /* Rotate right a little */
188     glRotated ( -ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
189     break ;
190
191   case GLUT_KEY_PAGE_UP :  /* Zoom in a little */
192     glScaled ( 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR ) ;
193     break ;
194
195   case GLUT_KEY_PAGE_DOWN :  /* Zoom out a little */
196     glScaled ( SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR ) ;
197     break ;
198   }
199
200   glutPostRedisplay () ;
201 }
202
203 void mouse_cb ( int button, int updown, int x, int y )
204 {
205   if ( updown == GLUT_DOWN )
206   {
207     double dist = 1.0e20 ;  /* A very large number */
208     (void) dist; /* what's this all about? */
209   }
210 }
211
212 void draw_curve ( int index, double position [ NUM_POINTS ][3] )
213 {
214   int i = index ;
215
216   glBegin ( GL_LINE_STRIP ) ;
217   do
218   {
219     i = ( i == NUM_POINTS-1 ) ? 0 : i + 1 ;
220     glVertex3dv ( position[i] ) ;
221   }
222   while ( i != index ) ;
223
224   glEnd () ;
225 }
226
227 void display_cb ( void )
228 {
229   char string [ 80 ] ;
230
231   glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;
232
233   glColor3d ( 1.0, 1.0, 1.0 ) ;  /* White */
234   /* Draw some axes */
235   glBegin ( GL_LINES ) ;
236   glVertex3d ( 0.0, 0.0, 0.0 ) ;
237   glVertex3d ( 2.0, 0.0, 0.0 ) ;
238   glVertex3d ( 0.0, 0.0, 0.0 ) ;
239   glVertex3d ( 0.0, 1.0, 0.0 ) ;
240   glVertex3d ( 0.0, 0.0, 0.0 ) ;
241   glVertex3d ( 0.0, 0.0, 1.0 ) ;
242   glEnd () ;
243
244   glColor3d ( 1.0, 0.0, 0.0 ) ;  /* Red */
245   draw_curve ( array_index, red_position ) ;
246
247   glColor3d ( 0.0, 1.0, 0.0 ) ;  /* Green */
248   draw_curve ( array_index, grn_position ) ;
249
250   /* Print the distance between the two points */
251   glColor3d ( 1.0, 1.0, 1.0 ) ;  /* White */
252   sprintf ( string, "Distance: %10.6lf", distance ) ;
253   glRasterPos2i ( 10, 10 ) ;
254   glutBitmapString ( GLUT_BITMAP_HELVETICA_12, string ) ;
255
256   glutSwapBuffers();
257 }
258
259 void reshape_cb ( int width, int height )
260 {
261   float ar;
262   glViewport ( 0, 0, width, height ) ;
263   glMatrixMode ( GL_PROJECTION ) ;
264   glLoadIdentity () ;
265   ar = (float) width / (float) height ;
266   glFrustum ( -ar, ar, -1.0, 1.0, 10.0, 100.0 ) ;
267   glMatrixMode ( GL_MODELVIEW ) ;
268   glLoadIdentity () ;
269   xcen = 0.0 ;
270   ycen = 0.0 ;
271   zcen = 0.0 ;
272   glTranslated ( xcen, ycen, zcen - 50.0 ) ;
273 }
274
275
276 void timer_cb ( int value )
277 {
278   /* Function called at regular intervals to update the positions of the points */
279   double deltax, deltay, deltaz ;
280   int new_index = array_index + 1 ;
281
282   /* Set the next timed callback */
283   glutTimerFunc ( 30, timer_cb, 0 ) ;
284
285   if ( animate > 0 )
286   {
287     if ( new_index == NUM_POINTS ) new_index = 0 ;
288     advance_in_time ( time_step, red_position[array_index], red_position[new_index] ) ;
289     advance_in_time ( time_step, grn_position[array_index], grn_position[new_index] ) ;
290     array_index = new_index ;
291
292     deltax = red_position[array_index][0] - grn_position[array_index][0] ;
293     deltay = red_position[array_index][1] - grn_position[array_index][1] ;
294     deltaz = red_position[array_index][2] - grn_position[array_index][2] ;
295     distance = sqrt ( deltax * deltax + deltay * deltay + deltaz * deltaz ) ;
296
297     if ( animate == 2 ) animate = 0 ;
298   }
299
300   glutPostRedisplay () ;
301 }
302
303
304
305 /* The Main Program */
306
307 int main ( int argc, char *argv[] )
308 {
309   int pargc = argc ;
310
311   /* Initialize the random number generator */
312   srand ( 1023 ) ;
313
314   /* Set up the OpenGL parameters */
315   /*  glDrawBuffer ( GL_BACK ) ;*/
316   glEnable ( GL_DEPTH_TEST ) ;
317   glClearColor ( 0.0, 0.0, 0.0, 0.0 ) ;
318   glClearDepth ( 1.0 ) ;
319
320   /* Initialize GLUT */
321   glutInitWindowSize ( 600, 600 ) ;
322   glutInit ( &pargc, argv ) ;
323   glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ) ;
324
325   /* Create the window */
326   glutCreateWindow ( "Lorenz Attractor" ) ;
327   glutKeyboardFunc ( key_cb ) ;
328   glutMouseFunc ( mouse_cb ) ;
329   glutSpecialFunc ( special_cb ) ;
330   glutDisplayFunc ( display_cb ) ;
331   glutReshapeFunc ( reshape_cb ) ;
332   glutTimerFunc ( 30, timer_cb, 0 ) ;
333
334   /* Initialize the attractor:  The easiest way is to call the keyboard callback with an
335    * argument of 'r' for Reset.
336    */
337   key_cb ( 'r', 0, 0 ) ;
338
339   /* Enter the GLUT main loop */
340   glutMainLoop () ;
341
342   return 0;
343 }
344