Advertisement
backstreetimrul

fluid.c 2

Jul 26th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 14.26 KB | None | 0 0
  1. // Usage: Drag with the mouse to add smoke to the fluid. This will also move a "rotor" that disturbs
  2. //        the velocity field at the mouse location. Press the indicated keys to change options
  3. //--------------------------------------------------------------------------------------------------
  4. #include <rfftw.h>              //the numerical simulation FFTW library
  5. #include <GL/glut.h>            //the GLUT graphics library
  6. #include <stdio.h>              //for printing the help text
  7. #include<math.h>
  8.  
  9.  
  10. //--- SIMULATION PARAMETERS ------------------------------------------------------------------------
  11. const int DIM = 50;             //size of simulation grid
  12. double dt = 0.4;                //simulation time step
  13. float visc = 0.001;             //fluid viscosity
  14. fftw_real *vx, *vy;             //(vx,vy)   = velocity field at the current moment
  15. fftw_real *vx0, *vy0;           //(vx0,vy0) = velocity field at the previous moment
  16. fftw_real *fx, *fy;             //(fx,fy)   = user-controlled simulation forces, steered with the mouse
  17. fftw_real *rho, *rho0;          //smoke density at the current (rho) and previous (rho0) moment
  18. rfftwnd_plan plan_rc, plan_cr;  //simulation domain discretization
  19.  
  20.  
  21. //--- VISUALIZATION PARAMETERS ---------------------------------------------------------------------
  22. int   winWidth, winHeight;      //size of the graphics window, in pixels
  23. int   color_dir = 0;            //use direction color-coding or not
  24. float vec_scale = 1000;         //scaling of hedgehogs
  25. int   draw_smoke = 0;           //draw the smoke or not
  26. int   draw_vecs = 1;            //draw the vector field or not
  27. const int COLOR_BLACKWHITE=0;   //different types of color mapping: black-and-white, rainbow, banded
  28. const int COLOR_RAINBOW=1;
  29. const int COLOR_BANDS=2;
  30. int   scalar_col = 0;           //method for scalar coloring
  31. int   frozen = 0;               //toggles on/off the animation
  32.  
  33.  
  34. //------ SIMULATION CODE STARTS HERE -----------------------------------------------------------------
  35.  
  36. //init_simulation: Initialize simulation data structures as a function of the grid size 'n'.
  37. //                 Although the simulation takes place on a 2D grid, we allocate all data structures as 1D arrays,
  38. //                 for compatibility with the FFTW numerical library.
  39. void init_simulation(int n)
  40. {
  41.     int i; size_t dim;
  42.  
  43.     dim     = n*2*(n/2+1)*sizeof(fftw_real);        //Allocate data structures
  44.     vx       = (fftw_real*) malloc(dim);
  45.     vy       = (fftw_real*) malloc(dim);
  46.     vx0      = (fftw_real*) malloc(dim);
  47.     vy0      = (fftw_real*) malloc(dim);
  48.     dim     = n * n * sizeof(fftw_real);
  49.     fx      = (fftw_real*) malloc(dim);
  50.     fy      = (fftw_real*) malloc(dim);
  51.     rho     = (fftw_real*) malloc(dim);
  52.     rho0    = (fftw_real*) malloc(dim);
  53.     plan_rc = rfftw2d_create_plan(n, n, FFTW_REAL_TO_COMPLEX, FFTW_IN_PLACE);
  54.     plan_cr = rfftw2d_create_plan(n, n, FFTW_COMPLEX_TO_REAL, FFTW_IN_PLACE);
  55.  
  56.     for (i = 0; i < n * n; i++)                      //Initialize data structures to 0
  57.     { vx[i] = vy[i] = vx0[i] = vy0[i] = fx[i] = fy[i] = rho[i] = rho0[i] = 0.0f; }
  58. }
  59.  
  60.  
  61. //FFT: Execute the Fast Fourier Transform on the dataset 'vx'.
  62. //     'dirfection' indicates if we do the direct (1) or inverse (-1) Fourier Transform
  63. void FFT(int direction,void* vx)
  64. {
  65.     if(direction==1) rfftwnd_one_real_to_complex(plan_rc,(fftw_real*)vx,(fftw_complex*)vx);
  66.     else             rfftwnd_one_complex_to_real(plan_cr,(fftw_complex*)vx,(fftw_real*)vx);
  67. }
  68.  
  69. int clamp(float x)
  70. { return ((x)>=0.0?((int)(x)):(-((int)(1-(x))))); }
  71.  
  72. //solve: Solve (compute) one step of the fluid flow simulation
  73. void solve(int n, fftw_real* vx, fftw_real* vy, fftw_real* vx0, fftw_real* vy0, fftw_real visc, fftw_real dt)
  74. {
  75.     fftw_real x, y, x0, y0, f, r, U[2], V[2], s, t;
  76.     int i, j, i0, j0, i1, j1;
  77.  
  78.     for (i=0;i<n*n;i++)
  79.     { vx[i] += dt*vx0[i]; vx0[i] = vx[i]; vy[i] += dt*vy0[i]; vy0[i] = vy[i]; }
  80.  
  81.     for ( x=0.5f/n,i=0 ; i<n ; i++,x+=1.0f/n )
  82.        for ( y=0.5f/n,j=0 ; j<n ; j++,y+=1.0f/n )
  83.        {
  84.           x0 = n*(x-dt*vx0[i+n*j])-0.5f;
  85.           y0 = n*(y-dt*vy0[i+n*j])-0.5f;
  86.           i0 = clamp(x0); s = x0-i0;
  87.           i0 = (n+(i0%n))%n;
  88.           i1 = (i0+1)%n;
  89.           j0 = clamp(y0); t = y0-j0;
  90.           j0 = (n+(j0%n))%n;
  91.           j1 = (j0+1)%n;
  92.           vx[i+n*j] = (1-s)*((1-t)*vx0[i0+n*j0]+t*vx0[i0+n*j1])+s*((1-t)*vx0[i1+n*j0]+t*vx0[i1+n*j1]);
  93.           vy[i+n*j] = (1-s)*((1-t)*vy0[i0+n*j0]+t*vy0[i0+n*j1])+s*((1-t)*vy0[i1+n*j0]+t*vy0[i1+n*j1]);
  94.        }
  95.  
  96.     for(i=0; i<n; i++)
  97.       for(j=0; j<n; j++)
  98.       {  vx0[i+(n+2)*j] = vx[i+n*j]; vy0[i+(n+2)*j] = vy[i+n*j]; }
  99.  
  100.     FFT(1,vx0);
  101.     FFT(1,vy0);
  102.  
  103.     for (i=0;i<=n;i+=2)
  104.     {
  105.        x = 0.5f*i;
  106.        for (j=0;j<n;j++)
  107.        {
  108.           y = j<=n/2 ? (fftw_real)j : (fftw_real)j-n;
  109.           r = x*x+y*y;
  110.           if ( r==0.0f ) continue;
  111.           f = (fftw_real)exp(-r*dt*visc);
  112.           U[0] = vx0[i  +(n+2)*j]; V[0] = vy0[i  +(n+2)*j];
  113.           U[1] = vx0[i+1+(n+2)*j]; V[1] = vy0[i+1+(n+2)*j];
  114.  
  115.           vx0[i  +(n+2)*j] = f*((1-x*x/r)*U[0]     -x*y/r *V[0]);
  116.           vx0[i+1+(n+2)*j] = f*((1-x*x/r)*U[1]     -x*y/r *V[1]);
  117.           vy0[i+  (n+2)*j] = f*(  -y*x/r *U[0] + (1-y*y/r)*V[0]);
  118.           vy0[i+1+(n+2)*j] = f*(  -y*x/r *U[1] + (1-y*y/r)*V[1]);
  119.        }
  120.     }
  121.  
  122.     FFT(-1,vx0);
  123.     FFT(-1,vy0);
  124.  
  125.     f = 1.0/(n*n);
  126.     for (i=0;i<n;i++)
  127.        for (j=0;j<n;j++)
  128.        { vx[i+n*j] = f*vx0[i+(n+2)*j]; vy[i+n*j] = f*vy0[i+(n+2)*j]; }
  129. }
  130.  
  131.  
  132. // diffuse_matter: This function diffuses matter that has been placed in the velocity field. It's almost identical to the
  133. // velocity diffusion step in the function above. The input matter densities are in rho0 and the result is written into rho.
  134. void diffuse_matter(int n, fftw_real *vx, fftw_real *vy, fftw_real *rho, fftw_real *rho0, fftw_real dt)
  135. {
  136.     fftw_real x, y, x0, y0, s, t;
  137.     int i, j, i0, j0, i1, j1;
  138.  
  139.     for ( x=0.5f/n,i=0 ; i<n ; i++,x+=1.0f/n )
  140.         for ( y=0.5f/n,j=0 ; j<n ; j++,y+=1.0f/n )
  141.         {
  142.             x0 = n*(x-dt*vx[i+n*j])-0.5f;
  143.             y0 = n*(y-dt*vy[i+n*j])-0.5f;
  144.             i0 = clamp(x0);
  145.             s = x0-i0;
  146.             i0 = (n+(i0%n))%n;
  147.             i1 = (i0+1)%n;
  148.             j0 = clamp(y0);
  149.             t = y0-j0;
  150.             j0 = (n+(j0%n))%n;
  151.             j1 = (j0+1)%n;
  152.             rho[i+n*j] = (1-s)*((1-t)*rho0[i0+n*j0]+t*rho0[i0+n*j1])+s*((1-t)*rho0[i1+n*j0]+t*rho0[i1+n*j1]);
  153.         }
  154. }
  155.  
  156. //set_forces: copy user-controlled forces to the force vectors that are sent to the solver.
  157. //            Also dampen forces and matter density to get a stable simulation.
  158. void set_forces(void)
  159. {
  160.     int i;
  161.     for (i = 0; i < DIM * DIM; i++)
  162.     {
  163.         rho0[i]  = 0.995 * rho[i];
  164.         fx[i] *= 0.85;
  165.         fy[i] *= 0.85;
  166.         vx0[i]    = fx[i];
  167.         vy0[i]    = fy[i];
  168.     }
  169. }
  170.  
  171.  
  172. //do_one_simulation_step: Do one complete cycle of the simulation:
  173. //      - set_forces:
  174. //      - solve:            read forces from the user
  175. //      - diffuse_matter:   compute a new set of velocities
  176. //      - gluPostRedisplay: draw a new visualization frame
  177. void do_one_simulation_step(void)
  178. {
  179.     if (!frozen)
  180.     {
  181.       set_forces();
  182.       solve(DIM, vx, vy, vx0, vy0, visc, dt);
  183.       diffuse_matter(DIM, vx, vy, rho, rho0, dt);
  184.       glutPostRedisplay();
  185.     }
  186. }
  187.  
  188.  
  189. //------ VISUALIZATION CODE STARTS HERE -----------------------------------------------------------------
  190.  
  191.  
  192. //rainbow: Implements a color palette, mapping the scalar 'value' to a rainbow color RGB
  193. void rainbow(float value,float* R,float* G,float* B)
  194. {
  195.    const float dx=0.8;
  196.    if (value<0) value=0; if (value>1) value=1;
  197.    value = (6-2*dx)*value+dx;
  198.    *R = max(0.0,(3-fabs(value-4)-fabs(value-5))/2);
  199.    *G = max(0.0,(4-fabs(value-2)-fabs(value-4))/2);
  200.    *B = max(0.0,(3-fabs(value-1)-fabs(value-2))/2);
  201. }
  202.  
  203. //set_colormap: Sets three different types of colormaps
  204. void set_colormap(float vy)
  205. {
  206.    float R,G,B;
  207.  
  208.    if (scalar_col==COLOR_BLACKWHITE)
  209.        R = G = B = vy;
  210.    else if (scalar_col==COLOR_RAINBOW)
  211.        rainbow(vy,&R,&G,&B);
  212.    else if (scalar_col==COLOR_BANDS)
  213.        {
  214.           const int NLEVELS = 7;
  215.           vy *= NLEVELS; vy = (int)(vy); vy/= NLEVELS;
  216.           rainbow(vy,&R,&G,&B);
  217.        }
  218.    glColor3f(R,G,B);
  219. }
  220.  
  221.  
  222. //direction_to_color: Set the current color by mapping a direction vector (x,y), using
  223. //                    the color mapping method 'method'. If method==1, map the vector direction
  224. //                    using a rainbow colormap. If method==0, simply use the white color
  225. void direction_to_color(float x, float y, int method)
  226. {
  227.     float r,g,b,f;
  228.     if (method)
  229.     {
  230.       f = atan2(y,x) / 3.1415927 + 1;
  231.       r = f;
  232.       if(r > 1) r = 2 - r;
  233.       g = f + .66667;
  234.       if(g > 2) g -= 2;
  235.       if(g > 1) g = 2 - g;
  236.       b = f + 2 * .66667;
  237.       if(b > 2) b -= 2;
  238.       if(b > 1) b = 2 - b;
  239.     }
  240.     else
  241.     { r = g = b = 1; }
  242.     glColor3f(r,g,b);
  243. }
  244.  
  245. void colorbar()
  246. {
  247.     glBegin(GL_QUADS);
  248.     glColor3f(1.0, 0.0, 0.0);
  249.     glVertex2f(600, 200);
  250.     glVertex2f(650, 200);
  251.     glColor3f(0.0, 0.0, 1.0);
  252.     glVertex2f(650, 400);
  253.     glVertex2f(600, 400);
  254.     glEnd();
  255.     glFlush();
  256. }
  257.  
  258. //visualize: This is the main visualization function
  259. void visualize(void)
  260. {
  261.     colorbar();
  262.     /***
  263.     glBegin(GL_QUADS);
  264.     glColor3f(1.0,0.0,0.0);
  265.     glVertex2f(600,200);
  266.     glVertex2f(650,200);
  267.     glColor3f(0.0,0.0,1.0);
  268.     glVertex2f(650,400);
  269.     glVertex2f(600,400);
  270.     glEnd();
  271.     glFlush();
  272.     ***/
  273.    
  274.  
  275.  
  276.  
  277.     int i, j, idx;
  278.     fftw_real  wn = (fftw_real)(winWidth - 300) / (fftw_real)(DIM + 1);   // Grid cell width
  279.     fftw_real  hn = (fftw_real)winHeight / (fftw_real)(DIM + 1);  // Grid cell heigh    printf(winWidth);
  280.  
  281.  
  282.     if (draw_smoke)
  283.     {
  284.         int idx0, idx1, idx2, idx3;
  285.         double px0, py0, px1, py1, px2, py2, px3, py3;
  286.         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  287.        
  288.  
  289.         glBegin(GL_TRIANGLES);
  290.         for (j = 0; j < DIM - 1; j++)            //draw smoke
  291.         {
  292.            
  293.             for (i = 0; i < DIM - 1; i++)
  294.             {
  295.                
  296.                 px0 = wn + (fftw_real)i * wn;
  297.                 py0 = hn + (fftw_real)j * hn;
  298.                 idx0 = (j * DIM) + i;
  299.  
  300.  
  301.                 px1 = wn + (fftw_real)i * wn;
  302.                 py1 = hn + (fftw_real)(j + 1) * hn;
  303.                 idx1 = ((j + 1) * DIM) + i;
  304.                 px2 = wn + (fftw_real)(i + 1) * wn;
  305.                 py2 = hn + (fftw_real)(j + 1) * hn;
  306.                 idx2 = ((j + 1) * DIM) + (i + 1);
  307.  
  308.  
  309.                 px3 = wn + (fftw_real)(i + 1) * wn;
  310.                 py3 = hn + (fftw_real)j * hn;
  311.                 idx3 = (j * DIM) + (i + 1);
  312.  
  313.                 set_colormap(rho[idx0]);    
  314.                                             glVertex2f(px0, py0);
  315.                 set_colormap(rho[idx1]);  
  316.                                             glVertex2f(px1, py1);
  317.                 set_colormap(rho[idx2]);    
  318.                                             glVertex2f(px2, py2);
  319.  
  320.  
  321.                 set_colormap(rho[idx0]);    
  322.                                             glVertex2f(px0, py0);
  323.                 set_colormap(rho[idx2]);    
  324.                                             glVertex2f(px2, py2);
  325.                 set_colormap(rho[idx3]);    
  326.                                             glVertex2f(px3, py3);
  327.    
  328.             }
  329.         }
  330.         glEnd();
  331.     }
  332.  
  333.     if (draw_vecs)
  334.     {
  335.         glBegin(GL_LINES);              //draw velocities
  336.         for (i = 0; i < DIM; i++)
  337.             for (j = 0; j < DIM; j++)
  338.             {
  339.                 idx = (j * DIM) + i;
  340.                 direction_to_color(vx[idx],vy[idx],color_dir);
  341.                 glVertex2f(wn + (fftw_real)i * wn, hn + (fftw_real)j * hn);
  342.                 glVertex2f((wn + (fftw_real)i * wn) + vec_scale * vx[idx], (hn + (fftw_real)j * hn) + vec_scale * vy[idx]);
  343.             }
  344.         glEnd();
  345.     }
  346. }
  347.  
  348.  
  349. //------ INTERACTION CODE STARTS HERE -----------------------------------------------------------------
  350.  
  351. //display: Handle window redrawing events. Simply delegates to visualize().
  352. void display(void)
  353. {
  354.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  355.     glMatrixMode(GL_MODELVIEW);
  356.     glLoadIdentity();
  357.     visualize();
  358.  
  359.     glFlush();
  360.     glutSwapBuffers();
  361. }
  362.  
  363. //reshape: Handle window resizing (reshaping) events
  364. void reshape(int w, int h)
  365. {
  366.     glViewport(0.0f, 0.0f, (GLfloat)w, (GLfloat)h);
  367.     glMatrixMode(GL_PROJECTION);
  368.     glLoadIdentity();
  369.     gluOrtho2D(0.0, (GLdouble)w, 0.0, (GLdouble)h);
  370.     winWidth = w; winHeight = h;
  371. }
  372.  
  373. //keyboard: Handle key presses
  374. void keyboard(unsigned char key, int x, int y)
  375. {
  376.     switch (key)
  377.     {
  378.       case 't': dt -= 0.001; break;
  379.       case 'T': dt += 0.001; break;
  380.       case 'c': color_dir = 1 - color_dir; break;
  381.       case 'S': vec_scale *= 1.2; break;
  382.       case 's': vec_scale *= 0.8; break;
  383.       case 'V': visc *= 5; break;
  384.       case 'vy': visc *= 0.2; break;
  385.       case 'x': draw_smoke = 1 - draw_smoke;
  386.             if (draw_smoke==0) draw_vecs = 1; break;
  387.       case 'y': draw_vecs = 1 - draw_vecs;
  388.             if (draw_vecs==0) draw_smoke = 1; break;
  389.       case 'm': scalar_col++; if (scalar_col>COLOR_BANDS) scalar_col=COLOR_BLACKWHITE; break;
  390.       case 'a': frozen = 1-frozen; break;
  391.       case 'q': exit(0);
  392.     }
  393. }
  394.  
  395.  
  396.  
  397. // drag: When the user drags with the mouse, add a force that corresponds to the direction of the mouse
  398. //       cursor movement. Also inject some new matter into the field at the mouse location.
  399. void drag(int mx, int my)
  400. {
  401.     int xi,yi,X,Y; double  dx, dy, len;
  402.     static int lmx=0,lmy=0;             //remembers last mouse location
  403.  
  404.     // Compute the array index that corresponds to the cursor location
  405.     xi = (int)clamp((double)(DIM + 1) * ((double)mx / (double)winWidth));
  406.     yi = (int)clamp((double)(DIM + 1) * ((double)(winHeight - my) / (double)winHeight));
  407.  
  408.     X = xi; Y = yi;
  409.  
  410.     if (X > (DIM - 1))  X = DIM - 1; if (Y > (DIM - 1))  Y = DIM - 1;
  411.     if (X < 0) X = 0; if (Y < 0) Y = 0;
  412.  
  413.     // Add force at the cursor location
  414.     my = winHeight - my;
  415.     dx = mx - lmx; dy = my - lmy;
  416.     len = sqrt(dx * dx + dy * dy);
  417.     if (len != 0.0) {  dx *= 0.1 / len; dy *= 0.1 / len; }
  418.     fx[Y * DIM + X] += dx;
  419.     fy[Y * DIM + X] += dy;
  420.     rho[Y * DIM + X] = 10.0f;
  421.     lmx = mx; lmy = my;
  422. }
  423.  
  424.  
  425. //main: The main program
  426. int main(int argc, char **argv)
  427. {
  428.     printf("Fluid Flow Simulation and Visualization\n");
  429.     printf("=======================================\n");
  430.     printf("Click and drag the mouse to steer the flow!\n");
  431.     printf("T/t:   increase/decrease simulation timestep\n");
  432.     printf
  433.     ("S/s:   increase/decrease hedgehog scaling\n");
  434.     printf("c:     toggle direction coloring on/off\n");
  435.     printf("V/vy:   increase decrease fluid viscosity\n");
  436.     printf("x:     toggle drawing matter on/off\n");
  437.     printf("y:     toggle drawing hedgehogs on/off\n");
  438.     printf("m:     toggle thru scalar coloring\n");
  439.     printf("a:     toggle the animation on/off\n");
  440.     printf("q:     quit\n\n");
  441.  
  442.     glutInit(&argc, argv);
  443.     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
  444.     //glutInitWindowSize(500,500);
  445.     glutInitWindowSize(800, 500);
  446.     glutCreateWindow("Real-time smoke simulation and visualization");
  447.     glutDisplayFunc(display);
  448.     glutReshapeFunc(reshape);
  449.     glutIdleFunc(do_one_simulation_step);
  450.     glutKeyboardFunc(keyboard);
  451.     glutMotionFunc(drag);
  452.  
  453.  
  454.     init_simulation(DIM);   //initialize the simulation data structures
  455.     glutMainLoop();         //calls do_one_simulation_step, keyboard, display, drag, reshape
  456.     return 0;
  457. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement