fluid simulation - department of computer scienceanima/408/notes/gas/fluids.pdf · combination of...

22
Fluid Simulation Copyright © 2004-15, Tyson Brochu and Howard Hamilton, University of Regina Textbook Reference for this page: Computer Animation: Algorithms and Techniques by Rick Parent (Chapter 5.3) Müller, Matthais et al. Particle-Based Fluid Simulation for Interactive Applications. Procedings of the Eurographics/SIGGRAPH Symposium on Computer Animation. Pages 154 – 159. 2003. http://portal.acm.org/ft_gateway.cfm?id=846298&type=pdf& coll=portal&dl=ACM&CFID=20929726&CFTOKEN=4786 4297 Stam, Jos. Real-Time Fluid Dynamics for Games. Proceedings of the Game Developer Conference. March 2003. http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/GD C03.pdf Other references: go to http://www2.cs.uregina.ca/~anima/408/Notes/References.htm Background for Fluid Simulaton: Computational Fluid Dynamics can be thought of as a combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain numerical solutions to the continuous equations used in Fluid Mechanics. CFD is generally used in engineering applications for the accurate physical simulation of fluids. In fluid dynamics, the Navier-Stokes equations relate fluid velocity, density, energy, temperature and other properties to each other. These fluid properties are usually functions of location in

Upload: others

Post on 22-Mar-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

Fluid Simulation

Copyright © 2004-15, Tyson Brochu and Howard Hamilton, University of Regina Textbook Reference for this page: Computer Animation:

Algorithms and Techniques by Rick Parent (Chapter 5.3) Müller, Matthais et al. Particle-Based Fluid Simulation for

Interactive Applications. Procedings of the Eurographics/SIGGRAPH Symposium on Computer Animation. Pages 154 – 159. 2003. http://portal.acm.org/ft_gateway.cfm?id=846298&type=pdf&coll=portal&dl=ACM&CFID=20929726&CFTOKEN=47864297

Stam, Jos. Real-Time Fluid Dynamics for Games. Proceedings of the Game Developer Conference. March 2003. http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/GDC03.pdf

Other references: go to http://www2.cs.uregina.ca/~anima/408/Notes/References.htm

Background for Fluid Simulaton: Computational Fluid Dynamics can be thought of as a combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain numerical solutions to the continuous equations used in Fluid Mechanics. CFD is generally used in engineering applications for the accurate physical simulation of fluids. In fluid dynamics, the Navier-Stokes equations relate fluid velocity, density, energy, temperature and other properties to each other. These fluid properties are usually functions of location in

Page 2: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

the simulation domain. The NS equations define the rules for the behavior of fluids such as liquids and gases. They are usually partial differential equations (PDEs). In general, they are fairly complicated, and not analytically solvable. Numerical methods are needed to estimate solutions for the system of equations. This is where the “Computational” part of CFD comes in. (Side note: Solving these equations numerically was one of the goals John von Neumann cited for developing his programmable computer.) How do we estimate numerical solutions to the Navier-Stokes equations? The main idea is that the functions for velocity, density, pressure, etc. are continuous, two- or three-dimensional functions, but we will represent them as discrete values in space. In other words, we “discretize” the functions involved. We sample the values of the functions at several points, and work with these sample values, instead of using the continuous functions. CFD and Computer Animation Realistic modeling and animation of fluids is one of the most challenging problems in Computer Animation. Until recently, animators had to create fluids manually using implicit surfaces, textures, sprites, particle systems, etc. This is tedious, and does not guarantee good results. So why not apply tried and true CFD techniques, originally used for the physical simulation of fluids, to building convincing animated models of fluids? The animator should be able to set a few parameters, specify a general flow, and let the animation system create a good model. Since the simulation is physically accurate, the results should look realistic. This method of animation is appealing, since it saves the animator time, and is guaranteed to produce physically accurate results.

Page 3: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

Grid-based solutions Using a computational grid to perform CFD calculations is called the Eulerian approach to CFD. The functions involved (density, velocity, etc.) are sampled at regularly spaced points. These regular samples form a square or cubic grid in two or three dimensions. A real function has a value at every point in the space in question, but our estimated function has the same value for all points in the interior of one grid cell. This is the same approach described for modeling gases. One of the things we wish to accomplish is to compute partial derivatives of functions with respect to different coordinates. For example, given a 2D grid, we may want to know how the density of the fluid increases along the x-dimension, ignoring the y-dimension. Taking the partial derivative of the density function will give us this information. We’ll pause here to offer a very brief introduction to multivariable calculus, and more specifically, partial derivatives. In single variable calculus, functions relate one variable, called the independent variable, to another, called the dependent variable. They have the form:

)(xfy = where: y is the dependent variable x is the independent variable f(x) is a function of x We can then differentiate the function:

)(' xfdxdy

=

Page 4: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

If we have a function of two or more independent variables, we must specify which variable we are differentiating with respect to. We call this finding the partial derivative with respect to a variable. We treat the other variables as constants, then differentiate as though it were a function of one variable. For example, suppose we take a function of two variables:

yxeyxyxf 3),( 2 +=

Then the partial derivative with respect to x is:

yexyyxxf 32),( +=∂∂

Here we treat y and ey as constants, and differentiate with respect to x. Note the special notation for partial derivatives:

),( yxxf∂∂

This is similar to the )(x

dxdf notation in single variable calculus, but

this new notation indicates that f is a function of multiple variables, and we are taking the derivative with respect to one of them, x. Sometimes the same derivative is written:

),( yxf x If fluid dynamics, we will often have a function defined over an area or volume. For example, we may have a density function, which is a function of area coordinates x and y. Given a point (x, y) in space, the function tells us the density of fluid at that point. Note that this is a multivariable function, since it is based on two coordinates, so we can take partial derivatives. Taking the partial derivative with respect to x tells us how the density changes as we

Page 5: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

move in the x direction. If xf (x, y) is positive at a certain point, then the function ),( yxf increases as we move in the positive x direction past this point. To compute partial derivatives numerically, we calculate the difference in sampled values divided by the distance between grid cells. For example, consider a small grid and a function F(x, y). The value of F is computed at the centre point of each cell. Assume the dimensions of one cell are H x H, for some constant H. In other words, the length of one side of a cell is H.

y 1 2 3 4 5 6

6 F = 1

F = 3

F = 4 F = 5 F =

3 F = 2

5

F = 1

F = 2

F = 5 F = 6 F =

5 F = 2

4 F = 2

F = 4

F = 6 F = 7 F =

6 F = 4

3 F = 3

F = 5

F = 7

F = 10

F = 7

F = 5

2 F = 2

F = 2

F = 5 F = 8 F =

6 F = 4

1 F = 1

F = 1

F = 4 F = 6 F =

7 F = 3

x

We will specify grid cells using the notation [c, r], where c is the column number of the cell, and r is the row number. The cell in row 4, column 2 is then specified by [2, 4]. This is different than the standard way we think about indexing 2D arrays, which would

Page 6: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

be [r, c]. It is closer to the standard way to reference Cartesian coordinates, (x, y). Suppose we want to know the value of the partial derivative of F with respect to x at some point (x, y). Now suppose that after some calculations, we find the point (x, y) lies in the cell in row 4, column 2. The value of x

F∂

∂ can be estimated by the change in F divided the change in x:

12

12

xxFF

xF

−−

≈∂∂

The cell to the left of [2, 4] is [1, 4], which has F = 2. The cell to the right is [3, 4], which has F = 6. So the value of F changes from 2 to 6 over the length of two grid cells. Since we are looking at coordinates along a horizontal line, the y-coordinate remains constant, and the x value changes by 2H. Thus the derivative with respect to x at cell [2, 4] is:

12

12

xxFF

xF

−−

≈∂∂ =

HH2

226=

The constant H specifies the size of a grid cell. If H = 10 in our example, then the area of one cell would be 100. With this value, the partial derivative computed above becomes:

12

12

xxFF

xF

−−

≈∂∂ = 2.0

204

226

==−H

We will also be dealing with derivatives with respect to time, t. Most of the functions we use will change as time progresses. To represent this, we can write them as parametrized functions, f(x, y, t), where the parameter t is time. We can then write the partial derivative with respect to time as:

Page 7: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

),,( tyxtf∂∂

These derivatives will not usually be estimated directly from the function values, but instead will be determined by other elements of the simulation. For example, the partial derivative of a velocity function v with respect to time is acceleration.

),,(),,( tyxt

tyx∂∂

=va

However, we will usually compute acceleration based on physical forces, not by differentiating v. With this approach, the derivatives of functions with respect to time cause the changes in function values, not the other way around. For example, the acceleration causes the change in velocity. Stam’s “Real-Time Fluid Dynamics” (See http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/GDC03.pdf) Jos Stam developed a grid-based method of fluid simulation with special emphasis on the modeling of smoke. The method is described here with respect to two dimensions, but it can be extended to three. It consists of two main functions defined over a 2D area – the density function, ρ, and the velocity function, u. The density function refers to the density (colour or transparency) of the smoke, mist, or other type of suspended particles (henceforth we will simply refer to smoke). The velocity function refers to the velocity of the fluid (say the air or water) that contains the smoke. It is assumed that the fluid itself has a constant density, which can thus be ignored, when working with the velocity. It is also assumed that the smoke is carried along with the fluid, and that its

Page 8: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

density (when doing mass-related calculations) is negligible with respect to the fluid’s density and can be ignored. The density function, ρ(x, y), tells us the density of smoke at a point (x, y) in 2D space. In mathematical terms, it is a scalar field, meaning it has a single value for each point in space. For example, ρ(5, 14) = 26 means that at the point (5, 14), the function has the value 26. Another example of a scalar field is a terrain map showing height. Given a point on the map, the height of the ground at that point can be determined. The example function F in the grid in the previous section is another example of a scalar field. The density of the smoke will be used to determine the color or transparency properties of the corresponding spot in the animation. The velocity field u(x, y), on the other hand, is a vector field, meaning that for each point in space, the function u returns a vector. For example: u(5, 14) = 4,2 . An example of a vector field is a map showing ocean currents. At each (x, y) point in the ocean, the velocity of the current can be determined.

Page 9: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

We are actually interested in versions of these functions with a third parameter, the time t. These functions are ρ(x, y, t) and v(x, y, t). Stam’s model uses two equations from the set of Navier-Stokes equations to relate density to velocity:

( )

( ) ),,(),,(),,(),,(),,(

),,(),,(),,(),,(),,(

2

2

tyxStyxatyxtyxtyxt

tyxtyxvtyxtyxtyxt

+∇+∇•−=∂∂

+∇+∇•−=∂∂

uu

fuuuu

ρρ

To avoid confusion with array index k, we have replaced the standard coefficient of diffusion k with the letter a. These equations tell us how the velocity of a fluid and the density of the smoke in it change over time. Roughly, we can think of the density field moving according to the velocity field (bottom equation), and the velocity field evolving over time (top equation). In our system, the visualization of the fluid will be based on the density field and the dense areas will be shown as more opaque. This provides a quick and easy visualization, and looks “smoky”. Both the density and velocity functions will be represented by 2D arrays in our system. The values at array locations are the values of the functions ρ(x, y, t) and u(x, y, t) at the current time at cell centers, as described in the previous section. The continuous functions are broken up into discrete values over an area. In our model, we will also consider discrete instants in time, broken up over time steps. As the simulation advances, the fluid function values change over these time steps. We first describe the motion of the density field through a velocity field. For now, we can assume the velocity field does not change. The bottom equation tells us that any change in the density field is

Page 10: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

due to three causes, represented by the three terms on the right-hand side of the equation. The terms represent change due to movement, diffusion, and sources of new matter, respectively. We will show the x, y and t parameters explicitly.

( ) ),,(),,(),,(),,(),,( 2 tyxStyxatyxtyxtyxt

+∇+∇•−=∂∂ uu ρρ

change = movement + diffusion + sources in density The addition of sources of new matter is handled easily. In our system, the user can add sources of density and velocity interactively, so the S value at any array location can be set manually. The ρ value at that array location can then be adjusted based on this S value. Diffusion is modeled by the exchange of density values among adjacent cells. In reality, the amount of material diffused is based on the velocity of the fluid, as described for animating gases. However, Stam’s model ignores this and assume that the material flows into adjacent areas at some constant rate. The user can specify this rate to change the visual characteristics of the fluid. To represent the flow of material into a cell, we could say that a certain fraction c of a cell’s material flows out to its four nearest neighbors in each time interval. Thus, each of these neighboring cells will get c/4 of this cell’s material. The fraction of this cell’s material that remains in it is (1 – c). Since all cells are the same size, the mass of material is equivalently measured by its density. If 0ρ (i, j), is the old density of cell (i, j), then we can calculate its new density using this formula:

[ ])1,()1,(),1(),1()4/(),()1(),( 00000 ++−+++−+−= jijijijicjicji ρρρρρρ HAMILTON

Page 11: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

where: ρ = density at the current time step at a given array location ρ0 = density at the previous time step at a given location i, j = array subscripts of the cell being examined c = coefficient of diffusion

Here, ),1(0 ji −ρ is the density of material in the neighboring cell to the left of cell (i, j). This formula is equivalent to:

[ ]),(4)1,()1,(),1(),1()4/(),(),( 000000 jijijijijicjiji ρρρρρρρ ⋅−++−+++−+=

HAMILTON We could also define a new constant a = c/4, which would range from 0 to ¼. This would give the formula:

[ ]),(4)1,()1,(),1(),1(),(),( 000000 jijijijijiajiji ρρρρρρρ ⋅−++−+++−+=

STAM where: ρ = density at the current time step at a given array location ρ0 = density at the previous time step at a given location i, j = array subscripts of the cell being examined a = coefficient of diffusion Stam does not specify the range for a, although he notes that values over 0.5 give unsatisfactory results. His definition for a = κ Δt / h2, where κ is the coefficient of diffusion, Δt is the length of the time step, and h is the width or height of a cell. Assuming that time is incremented by 1, and the size of the cells is 1x1, we can ignore these latter factors.

Here we break from our previous convention of explicitly specifying all three independent variables, such as in the expression ρ(x, y, t). This new form represents a function of space and time as two functions of space only, each at a specific, constant time. We also use array indices to specify locations in space, as opposed to (x, y) coordinates. The following illustration shows this approach to simulating diffusion:

Page 12: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

This method is straightforward and would be easy to code. We need to keep two arrays – one representing the density at the current time, dens2[][], and the other representing density at the previous time, dens1[][]. The current density of a cell can then be calculated from the densities of cells at the previous time:

dens2[i][j] = dens1[i][j] + a * ( dens1[i-1][j] + dens1[i+1][j] + dens1[i][j-1] + dens1[i][j+1] – 4 * dens1[i][j] );

As the simulation advances by one time step, the two arrays can be swapped, so at the next time step, the current data stored in dens2[][] should be used as the data for the previous time and dens1 should be used to record new values. This is more efficient than copying the whole new array into the old array, as was done in the gas simulation. According to Stam, this method is numerically unstable. It does not accurately model diffusion into any cells beyond the immediately adjacent cells. If the chosen time step is large enough, fluid from one cell should diffuse over several cells, but this method does not do this properly. Also, any computational errors will propagate unchecked as the simulation progresses. Instead, Stam defined a different method for modeling the effect of diffusion, which he claims is stable. The general idea of this method is to find a set of densities ρ which, when diffused backwards in time, yields the set of densities at the last time step, ρ0. The density for a cell at the previous time step is given by:

Page 13: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

[ ]),(4)1,()1,(),1(),1(),(),(0 jijijijijiajiji ρρρρρρρ ⋅−++−+++−−=

However, in Stam’s model, we know the density at the previous time step, and we want to find the density at the current time step. Solving for ρ(i, j), we get:

[ ]),(4),()]1,()1,(),1(),1([),(0 jiajijijijijiaji ρρρρρρρ ⋅−−=++−+++−+

),()41()]1,()1,(),1(),1([),(0 jiajijijijiaji ρρρρρρ +=++−+++−+ [ ]

ajijijijiaji

ji41

)1,()1,(),1(),1(),(),( 0

+++−+++−+

=ρρρρρ

ρ

So the current density of the cell is based on its density at the previous time and the current density of its neighbors. Obviously we cannot simply code this directly, since a cell’s density would be based on its neighbors, whose densities may not have been updated yet. Consider applying the formula to the first cell at a given time step. None of the other cells have had their density values updated yet, so each of the cell’s neighbors still has the density value from last time. This will lead to an inaccurate new value for the first cell. To fix this, we apply a technique called Gauss-Seidel relaxation. Basically, we apply the formula to each cell exactly as described above, knowing that the new values will not be correct. Then we repeat this process a number of times. Each successive repetition provides a better estimate to the actual values. A rough outline of the process is given below. Here, N is the number of cells along one dimension, dens[][] is the current density function, and prev_dens[][] is the density function at the previous time. The choice of 20 iterations has been found to provide reasonably good accuracy for our purposes, but it can be replaced with any other constant, or a termination condition based on change in successive guesses. for (k = 1 to 20) { for (i = 1 to N) { for (j = 1 to N) {

dens[i][j] = (prev_dens[i][j] + a * (dens[i-1][j] + dens[i+1][j] + dens[i][j-1] + dens[i][j+1])) / (1+4*a)

} } } Now that we have accounted for diffusion, we wish to move densities according to the velocity field. The velocity array represents vectors at the centre of each grid cell. We could imagine that the centre point of the cell is a particle of fluid, and it follows the corresponding velocity vector to the next time step. We could then assign the density value of the cell where the particle started to the new particle location.

Page 14: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

The problem with this method is that the new location of the particle will probably not correspond with the centre of another cell, so determining the new density values becomes problematic. To get around this, we again apply the idea of solving backwards in time. We still treat the center of a cell as a particle. Let’s call our cell Ci. We trace this particle from the centre of Ci backwards along the velocity vector associated with the given cell. This will give us the location of the particle at the previous time step, somewhere in another cell, Cj. The density function value at this location can be determined by interpolating from adjacent cells around Cj, based on the particle’s position within the cell. Note that in this interpolation, we will use the density values at the previous time step. This interpolated density becomes the new density of cell Ci. These three steps - add sources, diffuse, and move - model the change in density for the fluid. They are applied in this order at each step in Stam’s system. An easy implementation would be to build three functions, each of which would act over the density array, adding or subtracting the necessary density changes to the cells. The algorithm for diffusion shown above hints at the structure of such a function. We will now turn our attention to modeling the evolution of the velocity field, u(x, y, t). Recall that the top Navier-Stokes equations was:

( ) ),,(),,(),,(),,(),,( 2 tyxtyxvtyxtyxtyxt

fuuuu+∇+∇•−=

∂∂

We can interpret this equation as follows: change in velocity over time is due to addition of forces, viscous diffusion and self-advection, each represented by a term on the right hand side of the equation. The addition of forces is controlled by the user, just like the addition of density sources. Viscous diffusion refers to the effect of friction, which minimizes differences in velocities between neighboring areas of fluid. Self-advection means that the velocity field is moved along itself. Note the similarity between these terms and the terms accounting for the density change. In fact, we can use many of the same functions developed earlier to account for these terms. The easiest way to take advantage of the similarities is to treat the vector function u as two 2D arrays. One array stores the vector x components, the other stores the vector y components. The methods for determining density addition, diffusion and movement all deal with a scalar valued 2D array. The vector arrays are now broken down into scalar arrays, so the functions originally used for density can be applied to the scalar velocity arrays. To calculate viscous diffusion, for example, we pass the diffusion function the x-coordinate array, then the y-coordinate array. We can do the same for the movement (advection) function.

Page 15: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

In dealing with the velocity field, we would like to enforce incompressibility. Mathematically, this means that the divergence of the velocity field should be zero. To understand this, we need to know a little vector calculus. Suppose we have a vector field F(x, y). We can define F as ),(),,( 21 yxyx FF , which means that at a given point (x0, y0), the vector returned by the vector field is determined by the functions F1(x0, y0) and F2(x0, y0). For example, if

xyyxyx cos),( 31 +=F

22 ),( xyeyx y −=F

Then the vector at a point (x0, y0) would be:

200000

30

0,cos yxexyyx y −+

The divergence of a vector field F is represented as F•∇ . The symbol ∇ is called the

del operator, and can be thought of as yx ∂∂

∂∂ , in two dimensions. Note that this is

shorthand for an operator, not a real vector. We write it as a vector because it is used in conjunction with vector operations such as the cross and dot product to produce different operators. The divergence of a 2D vector field is formally defined as:

),(),( 21 yxy

yxx ∂

∂+

∂∂ FF

But this is (symbolically) the same as taking the dot product of ∇ and F:

),(),(

),(),(

),(),,(,),(

21

21

21

yxy

yxx

yxy

yxx

yxyxyx

yx

∂∂

+∂∂

=

⋅∂∂

+⋅∂∂

=

•∂∂

∂∂

=•∇

FF

FF

FFF

If we represent the velocity vector u be as vu, , where u and v are scalar functions of x and y, then the divergence of u is:

),(),(),( yxyvyx

xuyx

∂∂

+∂∂

=•∇ u

Page 16: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

In the previous section, we showed how partial derivatives with respect to distance could be estimated in a grid-based method. This will allow us to compute the divergence of u at each cell. As mentioned earlier, the divergence of a velocity field for an incompressible fluid should be zero. We would like to somehow force u•∇ to be zero. To achieve this, we will make use of a mathematical result called Hodge decomposition. Simply stated, this says that every velocity field is the sum of an incompressible field and a gradient field. A gradient field is written q∇ where q is some scalar function. The gradient is a vector field with vectors pointing in the direction of greatest increase or decrease of the function q. Again, if we treat ∇ as a symbolic vector, and assume q is a function of x and y, then:

yq

xqq

qyx

q

∂∂

∂∂

=∇

⋅∂∂

∂∂

=∇

,

,

According to Hodge decomposition, we can write our current velocity vector field, u, as: q∇+= wu (A) where: w is an incompressible vector field

q∇ is the gradient of some function If we can compute q, then we can just subtract q∇ from u to achieve a new incompressible vector field, w: q∇−= uw Taking the divergence, •∇ , of both sides of the equation,

qq

2

2

∇+•∇=•∇

∇−•∇=•∇

wuuw

q2∇=•∇ u since 0=•∇ w Since we know what u is, we can calculate u•∇ , then solve for q. This form of equation is called a Poisson equation, and can be solved using the same Gauss-Seidel relaxation technique used in the density diffusion step. We iteratively make guesses for the value of q that satisfies the equation. Once q is known, we can subtract q∇ from u to get an incompressible vector field, w. Enforcing incompressibility is done after the velocity field is diffused or advected.

Page 17: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

The general algorithm for this whole method is:

1. Get user input for sources of fluid (smoke) and forces 2. Update velocity

a. Add new forces b. Enforce incompressibility c. Diffuse velocity d. Enforce incompressibility e. Advect velocity along itself

3. Update Density a. Add sources of fluid b. Diffuse density c. Move density

Boundary conditions should also be enforced throughout the simulation. A simple way to do this is to maintain a one-cell buffer around the perimeter of the simulation area. No fluid should enter this buffer, so we set the vertical velocity to zero at the top and bottom, and the horizontal velocity to zero at the sides. We keep track of the buffer cells so that if some density does happen to cross over, it can be accounted for and moved back into the proper area.

Page 18: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

Another approach: Particle-based solutions In general, particle-based CFD methods are called Lagrangian methods. Instead of sampling discrete values in grid cells, we store the function values at points called particles. The particles each have attributes such as velocity, mass, density, and temperature. These attributes are really the values of continuous functions at a specific point in space and time. As with the grid method, we can use these values to compute derivatives and solve equations. The main advantage of this method over the grid-based solution is that the absence of a computational grid allows the simulated fluid to exist in an unspecified environment – the particles can just flow anywhere. Simple implementation of a particle-based fluid An easy way to create a particle-based fluid is to generate a particle system, then explicitly define global force fields which act on the fluid – e.g. turbulence, vortex, gravity, etc. This is an ad hoc way to simulate the forces that really act on a fluid. An example of such a system is the smoke generator in Maya. It is just a particle system with some pre-defined force fields. At render time, the particles are replaced with animated sprites to simulate the appearance of smoke. The problem with this is that it does not use any physical laws (like the NS equations), so the behavior is completely defined by the animator. This means the animator is responsible for the realism of the smoke behavior. We would rather have a system where

Page 19: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

the animator can specify some general characteristics and the physically accurate behavior will be generated automatically. Smoothed Particle Hydrodynamics (SPH) (This is written as “Smooth Particle Hydrodynamics” in some literature.) SPH was originally developed by computational astrophysicists to model the movement of galaxies. It is a specific branch of Lagrangian CFD. It defines a method for using the discrete values stored in the particles to solve the fluid dynamics equations. It is an interpolative method – function quantities are only defined at particle points, but the values of the functions can be computed anywhere in space through interpolation. For instance, each particle has a velocity attribute, but these are discrete values of a continuous velocity function. The value of some scalar function A: Rn → R at a location r is interpolated by using the values associated with particles close to r:

( ) ( )∑ −⋅⋅=j

jj

jj hrrW

AmrA ,

ρ (1)

Mass, density and the scalar A are all defined at each nearby particle j. rj is the location of particle j, and r is the point in space at which we want to compute A. W is a weighting function affecting radius h. W and h are defined below. Dividing by density approximates an averaging effect. Using this method, we can compute the value of the function A at any point r, but in practice we are only concerned with calculating functions at particle points. Therefore, we will usually encounter the formula for a given particle i:

( ) ∑≠

−⋅=ij

jij

jji hrrW

AmrA ),(

ρ (2)

The gradient of A is then given by:

( ) ∑≠

−∇⋅⋅=∇ij

jij

jji hrrW

AmrA ),(

ρ (3)

This second formula is important, since it transfers the work of calculating the spatial derivatives of A (which comprise its gradient vector, A∇ ) to calculating the spatial

Page 20: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

derivatives of W. Since W is a function of our own choosing, we can easily compute W∇ analytically, without having to compute them numerically.

We can also calculate the “Laplace operator” of a function A using a similar method:

( ) ∑≠

−∇⋅⋅=∇ij

jij

jji hrrW

AmrA ),(22

ρ (4)

We’ll skip the mathematical explanation of why this holds, but it’s an important result since the NS equations often deal with gradients and Laplaces of functions. The Smoothing Kernel (W) and the Core Radius (h) The function W(r- rj) is called the “weighting function”, or the “smoothing kernel”. It determines how much particle j should contribute to the final value of A. W is a function of the distance from r to rj, and a predefined variable h. The variable h represents the maximum distance at which a particle will affect A. In other words, the distance from r to rj must be less than h for particle j to have an effect on A. h is called the “core radius.” The choice of smoothing kernel has a major impact on the model. For example, if we choose a W(r, h) function that is negative for small r and positive for large r, it can be used to simulate an attractive-repulsive force. i.e. objects push away from each other when close, and move towards each other when far away. The value for h can be constant, but many implementations of SPH will assign each particle its own h value. In effect, this assigns a distance at which the particle is affected by a neighbor. This “per particle h value” can then be made adaptive, varying with time so that each particle is influenced by a set number of neighbors. Building an SPH model We now have a way to compute the functions and derivatives of functions at the particle locations. The task now is to use these methods in conjunction with the Navier-Stokes equations to create a fluid model. Two important equations from Navier-Stokes are:

0=•∇⋅+∂∂ vρρ

t (5)

vvv 2∇⋅++−∇=

∇•+∂∂ µρρ gP

tv (6)

Page 21: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

Equation (5) guarantees the conservation of mass in the fluid. Since SPH is a particle-based system, where each particle has a constant mass, this equation can be omitted. Equation (6) is the conservation of momentum equation. The left-hand side says that density and velocity are advected along the velocity field. Since our particles move through space and define the velocity and density field on their own, this term can be

condensed to

DtDvρ , where

DtDv is the “substantial derivative” of velocity – the change

in velocity of the particles over time. The right hand side of (6) says that the change in velocity is due to pressure P, external forces g, and viscosity, v2∇⋅µ . The main functions we wish to compute are the density, pressure, viscosity and velocity. The velocity of the particles is the most important function from a computer graphics point of view, but according to fluid dynamics, velocity is dependent on the other attributes, so they must be calculated first. To calculate the change in velocity (acceleration) in SPH, we consider the forces due to pressure and viscosity, as well as any external forces acting on the fluid.

Force = pressure force + viscosity force + external force

We then apply Newton’s second law of motion, acceleration = massforce , to determine the

motion of the particles. Density is the easiest function to compute. Substituting density for A into (2), we obtain:

( ) ∑≠

−⋅=ij

jiji hrrWmr ),(ρ

We can use the densities of particles to calculate a scalar pressure function. A simple way is to use the ideal gas state equation, which states that the pressure, P, is directly proportional to the density. So ρkP = for some constant k. In our system, we will want to model fluids that maintain a constant density at rest. To do this, we set ( )0ρρ −= kP , where k = some constant, and 0ρ = density of the fluid at rest. This will cause the fluid to flow into areas of low pressure, and out of areas with high pressure. The force due to pressure is calculated between pairs of particles using their pressure values and the vector separating their positions. A simple way to do this is to estimate

P∇ by our weighting method above. P∇ represents the direction and magnitude of the greatest change in P at a given point. We can think of negative P∇ as a contributing force, since the fluid should move away from areas of high pressure (i.e. in the direction opposite from the greatest change in pressure).

Page 22: Fluid Simulation - Department of Computer Scienceanima/408/Notes/Gas/Fluids.pdf · combination of Fluid Mechanics and Numerical Analysis. The objective of CFD techniques is to obtain

Viscosity is a function of the velocity field – particles tend to match velocity with their neighbors. The force between pairs of particles is based on the difference in their velocity vectors. This force is usually scaled by a user-defined constant, or by a variable related to the speed of sound in the fluid. External forces like gravity and wind can be added independently. The magnitude of an external force on a particle is proportional to the particle’s density attribute. For instance, the thermal buoyancy force, which causes hot gas to rise, is directly proportional to the density of the gas. Acceleration can now be computed as a sum of the forces, and applied to the velocities of the particles. The velocities then move the particles through space. Various methods for moving the particles can be applied. The so-called Leap-Frog scheme is popular. The general idea is that the velocity is calculated at intervals midway between time steps. The position is then updated using this velocity. So for one time step, ∆ t, the particle moves according to its velocity halfway through the time step. The position update procedure looks something like this:

x(i+1) = x(i) + v(i + ½) * ∆ t

where: x(n) = position at time n v(n) = velocity at time n ∆ t = time step