Advertisement
backstreetimrul

fluid.c 1

Jul 25th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 14.48 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.  
  219.    glColor3f(R,G,B);
  220. }
  221.  
  222.  
  223. //direction_to_color: Set the current color by mapping a direction vector (x,y), using
  224. //                    the color mapping method 'method'. If method==1, map the vector direction
  225. //                    using a rainbow colormap. If method==0, simply use the white color
  226. void direction_to_color(float x, float y, int method)
  227. {
  228.     float r,g,b,f;
  229.     if (method)
  230.     {
  231.       f = atan2(y,x) / 3.1415927 + 1;
  232.       r = f;
  233.       if(r > 1) r = 2 - r;
  234.       g = f + .66667;
  235.       if(g > 2) g -= 2;
  236.       if(g > 1) g = 2 - g;
  237.       b = f + 2 * .66667;
  238.       if(b > 2) b -= 2;
  239.       if(b > 1) b = 2 - b;
  240.     }
  241.     else
  242.     { r = g = b = 1; }
  243.     glColor3f(r,g,b);
  244. }
  245.  
  246. //visualize: This is the main visualization function
  247. void visualize(void)
  248. {
  249.    
  250.  
  251.     int i, j, idx;
  252.     fftw_real  wn = (fftw_real)(winWidth - 300) / (fftw_real)(DIM + 1);   // Grid cell width
  253.     fftw_real  hn = (fftw_real)winHeight / (fftw_real)(DIM + 1);  // Grid cell heigh
  254.  
  255.    
  256.     if (draw_smoke)
  257.     {
  258.         int idx0, idx1, idx2, idx3;
  259.         double px0, py0, px1, py1, px2, py2, px3, py3;
  260.         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  261.         glBegin(GL_TRIANGLES);
  262.        
  263.         for (j = 0; j < DIM - 1; j++)            //draw smoke
  264.         {
  265.            
  266.             for (i = 0; i < DIM - 1; i++)
  267.             {
  268.                 px0 = wn + (fftw_real)i * wn;
  269.                 py0 = hn + (fftw_real)j * hn;
  270.                 idx0 = (j * DIM) + i;
  271.  
  272.  
  273.                 px1 = wn + (fftw_real)i * wn;
  274.                 py1 = hn + (fftw_real)(j + 1) * hn;
  275.                 idx1 = ((j + 1) * DIM) + i;
  276.  
  277.  
  278.                 px2 = wn + (fftw_real)(i + 1) * wn;
  279.                 py2 = hn + (fftw_real)(j + 1) * hn;
  280.                 idx2 = ((j + 1) * DIM) + (i + 1);
  281.  
  282.  
  283.                 px3 = wn + (fftw_real)(i + 1) * wn;
  284.                 py3 = hn + (fftw_real)j * hn;
  285.                 idx3 = (j * DIM) + (i + 1);
  286.  
  287.  
  288.                 set_colormap(rho[idx0]);    glVertex2f(px0, py0);
  289.                 set_colormap(rho[idx1]);    glVertex2f(px1, py1);
  290.                 set_colormap(rho[idx2]);    glVertex2f(px2, py2);
  291.  
  292.  
  293.                 set_colormap(rho[idx0]);    glVertex2f(px0, py0);
  294.                 set_colormap(rho[idx2]);    glVertex2f(px2, py2);
  295.                 set_colormap(rho[idx3]);    glVertex2f(px3, py3);
  296.  
  297.                
  298.             }
  299.         }
  300.         glEnd();
  301.  
  302.         /***
  303.         glBegin(GL_QUADS);
  304.         glColor3f(1.0,0.0,0.0); ///----------------
  305.         glVertex2f(-1.,0.5); //two floats value
  306.         glVertex2f(-1.0,-0.5); //two floats value
  307.         glColor3f(0.0,0.0,1.0); ///----------------
  308.         glVertex2f(0.0,-0.5); //two floats value
  309.         glVertex2f(0.0,0.5); //two floats value
  310.         glEnd();
  311.         glFlush();
  312.  
  313.         ***/
  314.        
  315.  
  316.        
  317.  
  318.     }
  319.  
  320.     if (draw_vecs)
  321.     {
  322.         glBegin(GL_LINES);              //draw velocities
  323.         for (i = 0; i < DIM; i++)
  324.             for (j = 0; j < DIM; j++)
  325.             {
  326.                 idx = (j * DIM) + i;
  327.                 direction_to_color(vx[idx],vy[idx],color_dir);
  328.                 glVertex2f(wn + (fftw_real)i * wn, hn + (fftw_real)j * hn);
  329.                 glVertex2f((wn + (fftw_real)i * wn) + vec_scale * vx[idx], (hn + (fftw_real)j * hn) + vec_scale * vy[idx]);
  330.             }
  331.         glEnd();
  332.     }
  333. }
  334.  
  335.  
  336. //------ INTERACTION CODE STARTS HERE -----------------------------------------------------------------
  337.  
  338. //display: Handle window redrawing events. Simply delegates to visualize().
  339. void display(void)
  340. {
  341.     //printf("Hello");
  342.     /***
  343.     glBegin(GL_QUADS);
  344.     glColor3f(1.0, 0.0, 0.0); ///----------------
  345.     glVertex2f(0.6, 0.3); //two floats value
  346.     glVertex2f(0.6, -0.3); //two floats value
  347.     glColor3f(0.0, 0.0, 1.0); ///----------------
  348.     glVertex2f(0.9, -0.3); //two floats value
  349.     glVertex2f(0.9, 0.3); //two floats value
  350.     glEnd();
  351.     glFlush();
  352.     ***/
  353.  
  354.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  355.     glMatrixMode(GL_MODELVIEW);
  356.     glLoadIdentity();
  357.     visualize();
  358.  
  359.     //rainbow(0.8, 0, 1, 1);
  360.     //set_colormap(1);
  361.    
  362.  
  363.  
  364.     glFlush();
  365.     glutSwapBuffers();
  366. }
  367.  
  368. //reshape: Handle window resizing (reshaping) events
  369. void reshape(int w, int h)
  370. {
  371.     glViewport(0.0f, 0.0f, (GLfloat)w, (GLfloat)h);
  372.     glMatrixMode(GL_PROJECTION);
  373.     glLoadIdentity();
  374.     gluOrtho2D(0.0, (GLdouble)w, 0.0, (GLdouble)h);
  375.     winWidth = w; winHeight = h;
  376. }
  377.  
  378. //keyboard: Handle key presses
  379. void keyboard(unsigned char key, int x, int y)
  380. {
  381.     switch (key)
  382.     {
  383.       case 't': dt -= 0.001; break;
  384.       case 'T': dt += 0.001; break;
  385.       case 'c': color_dir = 1 - color_dir; break;
  386.       case 'S': vec_scale *= 1.2; break;
  387.       case 's': vec_scale *= 0.8; break;
  388.       case 'V': visc *= 5; break;
  389.       case 'vy': visc *= 0.2; break;
  390.       case 'x': draw_smoke = 1 - draw_smoke;
  391.             if (draw_smoke==0) draw_vecs = 1; break;
  392.       case 'y': draw_vecs = 1 - draw_vecs;
  393.             if (draw_vecs==0) draw_smoke = 1; break;
  394.       case 'm': scalar_col++; if (scalar_col>COLOR_BANDS) scalar_col=COLOR_BLACKWHITE; break;
  395.       case 'a': frozen = 1-frozen; break;
  396.       case 'q': exit(0);
  397.     }
  398. }
  399.  
  400.  
  401.  
  402. // drag: When the user drags with the mouse, add a force that corresponds to the direction of the mouse
  403. //       cursor movement. Also inject some new matter into the field at the mouse location.
  404. void drag(int mx, int my)
  405. {
  406.     int xi,yi,X,Y; double  dx, dy, len;
  407.     static int lmx=0,lmy=0;             //remembers last mouse location
  408.  
  409.     // Compute the array index that corresponds to the cursor location
  410.     xi = (int)clamp((double)(DIM + 1) * ((double)mx / (double)winWidth));
  411.     yi = (int)clamp((double)(DIM + 1) * ((double)(winHeight - my) / (double)winHeight));
  412.  
  413.     X = xi; Y = yi;
  414.  
  415.     if (X > (DIM - 1))  X = DIM - 1; if (Y > (DIM - 1))  Y = DIM - 1;
  416.     if (X < 0) X = 0; if (Y < 0) Y = 0;
  417.  
  418.     // Add force at the cursor location
  419.     my = winHeight - my;
  420.     dx = mx - lmx; dy = my - lmy;
  421.     len = sqrt(dx * dx + dy * dy);
  422.     if (len != 0.0) {  dx *= 0.1 / len; dy *= 0.1 / len; }
  423.     fx[Y * DIM + X] += dx;
  424.     fy[Y * DIM + X] += dy;
  425.     rho[Y * DIM + X] = 10.0f;
  426.     lmx = mx; lmy = my;
  427. }
  428.  
  429.  
  430. //main: The main program
  431. int main(int argc, char **argv)
  432. {
  433.     printf("Fluid Flow Simulation and Visualization\n");
  434.     printf("=======================================\n");
  435.     printf("Click and drag the mouse to steer the flow!\n");
  436.     printf("T/t:   increase/decrease simulation timestep\n");
  437.     printf
  438.     ("S/s:   increase/decrease hedgehog scaling\n");
  439.     printf("c:     toggle direction coloring on/off\n");
  440.     printf("V/vy:   increase decrease fluid viscosity\n");
  441.     printf("x:     toggle drawing matter on/off\n");
  442.     printf("y:     toggle drawing hedgehogs on/off\n");
  443.     printf("m:     toggle thru scalar coloring\n");
  444.     printf("a:     toggle the animation on/off\n");
  445.     printf("q:     quit\n\n");
  446.  
  447.     glutInit(&argc, argv);
  448.     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
  449.     //glutInitWindowSize(500,500);
  450.     glutInitWindowSize(800, 500);
  451.     glutCreateWindow("Real-time smoke simulation and visualization");
  452.     glutDisplayFunc(display);
  453.     glutReshapeFunc(reshape);
  454.     glutIdleFunc(do_one_simulation_step);
  455.     glutKeyboardFunc(keyboard);
  456.     glutMotionFunc(drag);
  457.  
  458.  
  459.     init_simulation(DIM);   //initialize the simulation data structures
  460.     glutMainLoop();         //calls do_one_simulation_step, keyboard, display, drag, reshape
  461.     return 0;
  462. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement