May 12, 2009 - effects, such as wind, the spreading of fire, and furthermore requires a fixed ... [KCR00] used textured splats for flame visualization, reducing the.
¨ ERLANGEN-NURNBERG ¨ FRIEDRICH-ALEXANDER-UNIVERSITAT ¨ INFORMATIK (MATHEMATISCHE MASCHINEN UND DATENVERARBEITUNG) INSTITUT FUR
Lehrstuhl f¨ur Informatik 10 (Systemsimulation)
Simulation and Visualization of Fire with the Lattice-Boltzmann Method Florian Rathgeber
Bachelor Thesis
Simulation and Visualization of Fire with the Lattice-Boltzmann Method Florian Rathgeber Bachelor Thesis
Aufgabensteller:
Prof. Dr. U. R¨ ude Prof. Dr. G. Zeng Betreuer: M.Sc. K. Iglberger Bearbeitungszeitraum: 03.01.2009 – 12.05.2009
Erkl¨ arung: Ich versichere, dass ich die Arbeit ohne fremde Hilfe und ohne Benutzung anderer als der angegebenen Quellen angefertigt habe und dass die Arbeit in gleicher oder ¨ahnlicher Form noch keiner anderen Pr¨ ufungsbeh¨orde vorgelegen hat und von dieser als Teil einer Pr¨ ufungsleistung angenommen wurde. Alle Ausf¨ uhrungen, die w¨ortlich oder sinngem¨aß u ¨bernommen wurden, sind als solche gekennzeichnet.
Erlangen, den 12.05.2009
.................................
Abstract The realistic depiction of fire is a challenge for the disciplines of computational simulation and visualization alike. As the phenomenon is not fully understood yet, finding a suitable model for the lifelike simulation of fire is difficult. Therefore, most approaches concentrate on the creation of realistic imagery rather than strict physical accuracy. This thesis attempts a physically motivated simulation and visualization of freely fed fire. The implementation is based on a model presented in the paper “Simulating Fire With Texture Splats” of Wei et al. Fire and smoke are represented by a cloud of particles that are advected by a velocity field computed with the Lattice-Boltzmann method (LBM). Combined with the Smagorinsky subgrid correction, the fluid simulation is stable even for turbulent flows. Additionally, the LBM provides an easy way to integrate second-order boundary conditions and obstacles in the flow. In this way, the interaction of the airflow with objects and environmental influences like wind can be modeled. A temperature field is added to control the creation of smoke from the fire and buoyancy-induced particle movements. Supplemented with an OpenGL 3D engine, the results can be immediately visualized in real-time with interactive frame rates, using billboards as particle representations.
Zusammenfassung Die realistische Darstellung von Feuer stellt sowohl f¨ ur die Disziplin der Computersimulation als auch der Visualisierung eine Herausforderung dar. Da das Ph¨anomen noch nicht v¨ollig verstanden ist, ist es schwierig ein geeignetes Modell f¨ ur die naturgetreue Simulation von Feuer zu finden. Deshalb konzentrieren sich die meisten Ans¨atze mehr auf die Erzeugung realistischen Bildmaterials als auf strikte physikalische Genauigkeit. Diese Arbeit macht den Versuch einer physikalisch motivierten Simulation und Visualisierung von offenem Feuer. Die Implementierung basiert auf einem Modell, das im Paper “Simulating Fire With Texture Splats” von Wei et al. vorgestellt wird. Feuer und Rauch werden durch eine Partikelwolke repr¨asentiert, die von einem mittels der Lattice-Boltzmann-Methode (LBM) berechneten Geschwindigkeitsfeld getragen wird. In Verbindung mit der Smagorinsky Subgitter-Korrektur bleibt die Fluidsimulation selbst f¨ ur turbulente Str¨omungen stabil. Außerdem erm¨oglicht die LBM die einfache Einbindung von Randbedingungen zweiter Ordnung und Hindernissen im Str¨omungsfeld. Auf diese Weise kann die Interaktion des Luftstroms mit Objekten und Umwelteinfl¨ ussen wie Wind modelliert werden. Ein zus¨atzliches Temperaturfeld kontrolliert die Raucherzeugung durch das Feuer und auftriebsbedingte Partikelbewegungen. Erg¨anzt durch eine 3D-Engine in OpenGL k¨onnen die Ergebnisse direkt in Echtzeit bei interaktiven Bildwiederholraten visualisiert werden, wobei Partikel durch sog. billboards dargestellt werden.
Acknowledgments
This thesis was partly written during my stay as an exchange student at the Tongji University Shanghai, China, in the winter semester 2008 / 2009. I was admitted as a participant to an exchange program organized by the Lehrstuhl f¨ ur Technische Elektronik of Prof. Dr. Dr. Robert Weigel at the Technische Fakult¨at and received financial support granted by the Dean of the Technische Fakult¨at. I want to thank my Chinese host university for accepting me, particularly Prof. Zhibiao Feng, who supported me in all the formalities, and Richard Rose, who was always available as a contact person in Erlangen. Further, I want to express my gratitude towards Zuowen Jiang, Zheng Li, and Yufan Qiu for assisting me in admistrative problems during my time at Tongji University. I would like to thank Prof. Dr. Guosun Zeng and Prof. Dr. Ulrich R¨ ude for offering this thesis to me. Dr. Nils Th¨ urey and Klaus Iglberger gave vital hints on how to develop the topic, many thanks for that. Special thanks go to Klaus Iglberger for his ongoing and very prompt support despite the long distance from Erlangen to Shanghai. Finally, I want to thank Thomas Heller, Martin Bauer, and Klaus Sembritzki for helping me out with some tedious C++ issues.
Notation Quantities with no physical units given are non-dimensional. Whenever necessary, a prime is used to distinguish a physical quantity from a corresponding non-dimensional lattice quantity. The notation follows [Th¨ u07]. fi f˜i fieq fi∗ wi C T ρ0 ρ ∆t0 ∆x0 µ0 ν0 λ ∆t ∆x ν τ ei g u0 u
particle distribution function particle distribution function in inverse direction of fi equilibrium distribution function particle distribution function in post collision state equilibrium weighting factor Smagorinsky constant temperature [K] fluid density [kg/m3 ] lattice fluid density physical time step size [s] physical cell size [m] dynamic viscosity [m Pa/s] kinematic viscosity [m2 /s] relaxation time [s] lattice time step lattice cell size lattice viscosity lattice relaxation time lattice velocity vector gravity acceleration vector [m/s2 ] physical fluid velocity [m/s] lattice fluid velocity
Abbreviations CFD Computational Fluid Dynamics D2Q9 Lattice-Boltzmann model in 2D with 9 velocity directions D2Q19 Lattice-Boltzmann model in 3D with 19 velocity directions LB Lattice-Boltzmann LBE Lattice-Boltzmann equation LBM Lattice-Boltzmann method LGCA Lattice Gas Cellular Automata NS Navier-Stokes Equations PDE partial differential equation
Contents 1 Introduction 1.1 A Brief Survey of the History of Fire Simulation . . . . . . . . . . . . . . . . . . . 1.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 The 2.1 2.2 2.3
Lattice-Boltzmann Method Introduction to the Lattice-Boltzmann Method . . . . . . . . Improved Stability with the Smagorinsky Turbulence Model Boundary Treatment . . . . . . . . . . . . . . . . . . . . . . 2.3.1 No-slip Boundary Conditions . . . . . . . . . . . . . 2.3.2 Acceleration Boundary Conditions . . . . . . . . . . 2.3.3 Inflow Boundary Conditions . . . . . . . . . . . . . . 2.3.4 Outflow Boundary Conditions . . . . . . . . . . . . . 2.4 Obstacles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.1 Cell-Boundary Aligned Obstacles . . . . . . . . . . . 2.4.2 Curved Boundaries . . . . . . . . . . . . . . . . . . .
3 Characteristics of Fire 3.1 A Physical Motivation 3.2 Categorization of Fire 3.3 The Color of Flame . . 3.4 Smoke . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
. . . . . . . . . .
. . . .
3 3 4
. . . . . . . . . .
5 5 9 10 10 10 10 12 12 12 13
. . . .
17 17 17 18 20
4 A Model of Freely Fed Fire 4.1 Overview of the Model . . . . . . . . . . . . 4.2 Evaluation . . . . . . . . . . . . . . . . . . . 4.3 Implementation Aspects . . . . . . . . . . . 4.3.1 Overview of the Implemented Classes 4.3.2 Particle System Main Loop . . . . . 4.3.3 Particles . . . . . . . . . . . . . . . . 4.3.4 Emission . . . . . . . . . . . . . . . . 4.3.5 Particle Update Step . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
21 21 21 22 22 23 23 23 25
5 Visualization 5.1 Irrlicht 3D Engine . . . . . . . . . . 5.2 Particles to the Screen . . . . . . . 5.3 Coloring . . . . . . . . . . . . . . . 5.4 Environment and Lighting . . . . . 5.5 Integration into the Particle System
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
29 29 30 31 32 33
6 Performance Aspects
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
35
XI
6.1
6.2 6.3
Lattice-Boltzmann Solver . . . . . . . . . . . . . . . . . . . 6.1.1 Performance Impact of the Smagorinsky Turbulence 6.1.2 Obstacle Boundary Conditions Compared . . . . . Particles and Rendering . . . . . . . . . . . . . . . . . . . Dynamic Lighting . . . . . . . . . . . . . . . . . . . . . . .
7 Examples And Results 7.1 The Scene Description . . . . . . . . . . . 7.2 Example Setups and Visual Results . . . . 7.2.1 Influence of Varying Sprite Number 7.2.2 Dynamic Lighting . . . . . . . . . . 7.2.3 Selected Example Scenes . . . . . . 7.2.4 Evaluation of the Results . . . . . .
. . . . per . . . . . .
. . . . . . . . . . Particle . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . . correction . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
. . . . . .
. . . . .
35 35 35 37 41
. . . . . .
43 43 44 44 45 45 48
8 Conclusion
49
Bibliography
51
XII
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
List of Figures 2.1 2.2 2.3 2.4 2.5 2.6 2.7
Discrete velocity directions for D2Q9 and D3Q19 models . . Stream and collide step . . . . . . . . . . . . . . . . . . . . . Bounce back boundary treatment . . . . . . . . . . . . . . . Obstacle with curved boundary in the LBM lattice . . . . . Intersection calculation of lattice link and sphere . . . . . . . Bounce back behavior depending on the position of the wall Pre- and post-moving state of an obstacle . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
3.1 3.2 3.3
CIE 1931 chromaticity diagram including the Planckian locus . . . . . . . . . . . 19 Black body color spectrum for 1000 - 16000K . . . . . . . . . . . . . . . . . . . . 19 Influences directing the movement of smoke particles . . . . . . . . . . . . . . . . 20
4.1 4.2
Intersection calculation of lattice link and sphere . . . . . . . . . . . . . . . . . . . 22 Composition of the particle movement vector . . . . . . . . . . . . . . . . . . . . . 25
6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9
LBM with and without Smagorinsky turbulence correction . . . . . Curved boundary obstacle for a sphere of radius 15 . . . . . . . . . Performance of different boundary conditions for obstacles . . . . . Computing time comparison of LBM, particle update and rendering Runtimes of a full simulation time step (1 sprite per particle) . . . . Runtimes of a full simulation time step (2 sprites per particle) . . . Runtimes of a full simulation time step (4 sprites per particle) . . . Runtimes of a full simulation time step (8 sprites per particle) . . . Rendering time comparison for dynamic lighting turned on and off .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
36 36 37 38 39 39 40 40 41
7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8
Simulation after 100 time steps for different numbers of sprites displayed A soccer ball shot through a campfire with and without dynamic lighting A campfire with strong wind from the side . . . . . . . . . . . . . . . . . Two soccer balls shot through a campfire from different sides . . . . . . . Three soccer balls shot through a campfire from different sides . . . . . . A teapot placed on a campfire . . . . . . . . . . . . . . . . . . . . . . . . A teapot placed on a stove inside a room . . . . . . . . . . . . . . . . . . A fire calmly burning in a fireplace . . . . . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
44 45 46 46 47 47 48 48
. . . . . . . . .
. . . . . . .
. . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
6 8 11 13 14 15 16
XIII
List of Figures
XIV
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
List of Algorithms 2.1 2.2
Basic algorithm of the Lattice-Boltzmann Method . . . . . . . . . . . . . . . . . . 9 Calculation of the delta value for lattice link intersection with the boundary . . . 15
4.1 4.2 4.3 4.4
Particle system main loop . . . . . . . . . . . . . . . . . Excerpt from the declaration of the class Particle . . . . Excerpt from the declaration of the class Emitter . . . . . Simplified implementation of the particle update method
5.1 5.2
A basic Irrlicht engine example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Visualization-enabled particle system main loop . . . . . . . . . . . . . . . . . . . 33
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
23 24 24 27
1
List of Algorithms
2
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
1 Introduction Fire is one of nature’s most exciting yet little understood phenomena that has been fascinating mankind since the earliest days, long before we had means to effectively create and control it. The dangerous and highly destructive nature of experiments involving fire has made scientific examination always difficult. Only with the upcoming of computer simulation it was possible to investigate fire free of danger and destruction and therefore at much lower cost. A primary goal of most fire simulations was not only to gain new physical and chemical insight, but also to create realistically looking flame visualizations. In this context, computer graphics developed methods rousing great interest in the film industry that very much appreciated these expanding possibilities of comparatively cheap yet highly flexible special effects. In the following, a short historical survey of approaches to simulate fire is given, followed by an overview of this thesis.
1.1 A Brief Survey of the History of Fire Simulation With different goals in mind, a variety of different methods have been developed and applied for simulation and visualization of fire. The first attempts were more visualization-oriented rather than targeting physical correctness. An early work is the particle-based system of Reeves [Ree83] used to model the “Genesis bomb” in the film Star Trek II: The Wrath of Khan. A two-level hierarchy of particle sources came to use, consisting at the first level of particles that were themselves particle systems forming the second level and representing the actual explosions. The realism of particle-based approaches largely depends on the number of particles involved, which in turn is limited by the computing power of the hardware, especially at this time. A different path was taken by Perlin and Hoffert [Per85, PH89], who employed an easy to implement noise-based method to model fire in two and three dimensions, where turbulent behavior was achieved by fractal perturbation. This approach lacks the possibility of easily integrating external effects, such as wind, the spreading of fire, and furthermore requires a fixed viewpoint position. More recently, King et al. [KCR00] used textured splats for flame visualization, reducing the computational complexity compared with particle systems as a comparable visual result can be achieved by a much smaller number of splats. The use of high-resolution textures provides a turbulent appearance of the fire as well as smooth boundaries. Their model, however, does not incorporate interaction with external influences like wind and temperature, leaving the animation rather static. The group around Ari Kaufman were the first to introduce the Lattice-Boltzmann Method for the computation of the flow velocity field advecting fire particles and incorporating the interactions with external wind forces and the environment. They accelerated the LBM using graphics hardware and in the work of Wei et al. [WLMK02] combined this approach with textured splats as basic display primitives to attain real-time rendering frame rates. Zhao et al. [ZWF+ 03] expanded this idea by fire front propagation on volumetric data sets. The necessity of creating an isosurface was eliminated by using an enhanced distance field generated by a shell
3
1. Introduction volume that stores density relations of the voxel neighborhood. This enables the fire front to directly propagate on a virtual surface related to a given isovalue.
1.2 Overview The foundation for this thesis lies in the idea of basing fire simulation on a Lattice-Boltzmanncalculated velocity field brought up by the Kaufman group. In particular, the model presented in the paper “Simulating Fire With Texture Splats” [WLMK02] is implemented as a particle system on top of a Lattice-Boltzmann solver. This central part is then combined with an OpenGL realtime visualization and a versatile configuration approach using a custom configuration file parser. First of all, the structure of this thesis subdivided into eight chapters is outlined. After this introductory chapter, the basics of the Lattice-Boltzmann Method will be recapitulated, along with the presentation of a Smagorinsky turbulence model for enhanced stability. Additionally, the implementation of different kinds of boundary conditions integrated into the Lattice-Boltzmann solver, including the accurate treatment of curved boundaries, will be explainded in detail. In Chapter 3, some physically motivated considerations for the modeling of fire will be given, covering smoke and the color of flame. Chapter 4 introduces the model of Wei et al. [WLMK02] for freely fed fire, followed by some details on the implementation of the particle system based on this model, the central part of the thesis. In the subsequent chapter, the real-time visualization in OpenGL based on the open source 3D engine Irrlicht is presented. Chapter 6 presents selected performance results, showing the impact of the different simulation components in terms of computational complexity. A brief overview of how to set up a scene for simulation will be given in Chapter 7, together with visual results for selected example setups. The last chapter will conclude the thesis and give an outlook on possible extensions.
4
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2 The Lattice-Boltzmann Method 2.1 Introduction to the Lattice-Boltzmann Method For more than a decade now, scientists and engineers have a new choice for the numerical simulation of fluids that has received constantly increasing attention, the Lattice-Boltzmann Method (LBM). Before that, the principal approach for the computation of the flow of incompressible fluids in Computational Fluid Dynamics (CFD) had been the numerical solution of the NavierStokes Equations (NS). This system of second-order partial differential equations (PDE) for an incompressible fluid consists of the momentum equation 1 ∂u0 + (u0 ∇)u0 = − ∇p + ν∇2 u0 ∂t ρ0
(2.1)
that ensures momentum conservation and the continuity equation ∇ · u0 = 0
(2.2)
that ensures mass conservation [WG00, p. 7]. The flow velocity u0 and the pressure p are the quantities of interest here, ∇ is the nabla operator, ρ0 is the constant mass density by the assumption of incompressibility, and ν is the kinematic shear viscosity. The latter two characterize the fluid under consideration. The NS equations can be discretized in space and time by well-known methods such as Finite Differences (FD), Finite Elements (FE), or Finite Volumes (FV). Difficulties arise through the non-linearity of the term (u0 ∇)u0 in the momentum equation, especially for turbulent flows, where the influence of this term gets strong. A substantially different, mesoscopic approach was introduced with the Lattice Gas Cellular Automata (LGCA) that were originally proposed by Hardy, de Pazzis and Pomeau in 1973 (HPPmodel). An in-depth coverage of the topic can be found in [WG00]. The simulation domain is divided into a lattice of uniform, discrete cells or lattice sites, where the fluid itself is discretized as particles. These can only reside at lattice sites, where each cell can host either one particle or be unpopulated, and propagate from cell to cell along associated lattice links. Collisions occurring when two or more particles propagate to the same cell in the same time step need to be resolved in a way that conserves mass and momentum. These interactions, involving an exchange of momentum between the colliding particles, are strictly local and only involve the cell where the collision actually happens. Macroscopic values such as density and velocity can be obtained by coarse graining, i.e. averaging over a large number of cells, hundreds or probably thousands. In 1986 Frisch, Hasslacher and Pomeau showed that their proposed hexagonal symmetric LGCA-model (FHP-model) in the macroscopic limit satisfies the Navier-Stokes equations1 , whereas the HPP-model does not due to insufficient isotropy. Still, the LGCA suffered from a number 1
The proof can also be found in [WG00]
5
2. The Lattice-Boltzmann Method
Figure 2.1: Discrete velocity directions for D2Q9 and D3Q19 models (image taken from Nils Th¨ urey [Th¨ u07])
of weaknesses, the most prominent being the statistical noise caused by the random particle movement. An approach to alleviate the problem was the introduction of continuous distribution functions instead of the discrete particles proposed by McNamara and Zanetti in 1988. This made coarse graining unnecessary and is regarded as the birth of the Lattice-Boltzmann Method. The calculation of the distribution functions is based on the Boltzmann Equation ∂f + u0 ∇f = Q ∂t
(2.3)
with f being the distribution function, u0 the velocity, and Q the collision integral. To adapt to the lattice, the velocity-space is discretized into a finite number of lattice velocities ui with associated distribution functions fi and the derivatives are approximated by finite differences. The collision integral is approximated by a single-relaxation-time kinetic model, a relaxation towards a Maxwellian equilibrium distribution, know as the Bhatnagar-Gross-Krook-approximation (BGK) [QdL92]. These transformations with all quantities non-dimensionalized finally result in the Lattice-Boltzmann Equation (LBE) 1 fi (x + ei ∆t, t + ∆t) − fi (x, t) = − (fi − fieq ) τ
(2.4)
with the discrete distribution values fi (x, t) at a lattice site x at time t, representing the fraction of particles moving in that particular direction, lattice velocities ci , time step ∆t, relaxation time τ and equilibrium distribution functions fieq . This linear and first-order equation forms the basis of the LBM. Several possibilities exist for the discretization of the velocity-space in two and three dimensions, the most popular ones being the D2Q9 model in two dimensions and the D3Q19 model in three dimensions. Both are multi-speed models, i.e. they comprise lattice velocities of different magnitudes that can be combined to corresponding sub-lattices. Refer to Figure 2.1 for an
6
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2. The Lattice-Boltzmann Method illustration of the velocity directions. The D3Q19 lattice velocities are defined as e0 = (0, 0, 0) e1,2 , e3,4 , e5,6 = (±1, 0, 0), (0, ±1, 0), (0, 0, ±1) e7,...,10 , e11,...,14 , e15,...,18 = (±1, ±1, 0), (±1, 0, ±1), (0, ±1, ±1). It is evident that there are three different particle velocities: Velocity√0 for the particles at rest, six directions with unit velocity 1, and twelve directions with velocity 2. Apart from the D3Q19 model, there are also the D3Q15 and D3Q27 models in three dimensions that introduce a fourth √ √ sub-lattice with eight velocities of magnitude 3. The D3Q15 model lacks the 2 sub-lattice in return. But as this gives no stability benefit despite the performance penalty and higher memory requirements of eight additional distribution functions for the D3Q27 model, whereas the D3Q15 model suffers from anisotropy effects far outweighing the performance gain from the smaller number of distribution functions, the D3Q19 model is the best choice for most practical purposes. The macroscopic quantities density and velocity relevant for CFD can be computed by summation over the particle distribution functions of a cell as ρ=
X
fi
u=
1X ei fi . ρ
(2.5)
Equilibrium distribution functions represent the stationary state of the fluid, which means that the distribution functions remain constant over time but not necessarily that the fluid is at rest. They solely depend on the macroscopic density and velocity and can be computed as 3 9 fieq = wi ρ[1 + 3ei · u − u2 + (ei · u)2 ] 2 2
(2.6)
where the equilibrium weighting factors wi give the equilibrium distribution functions for a resting fluid of unit density and for the D3Q19 model are given by wi = 1/3 wi = 1/18 wi = 1/36
for i = 0, for i = 1..6, for i = 7..18.
Usually, the LBE is split into two parts, representing the two steps of computation. One is the collision step that accounts for the collisions of particles in a cell by linear relaxing the distribution functions towards their equilibrium state: 1 fi∗ (x, t) = fi (x, t) − [fi (x, t) − ωfieq ]. τ
(2.7)
The other is the streaming step, where particles stream to adjacent cells according to their lattice velocities fi (x + ei ∆t, t + ∆t) = fi∗ (x, t). (2.8) In practice, the lattice cell size and time step are normalized as ∆x/∆t = 1 such that the streaming step is a simple copy operation. It can be performed in two different ways by going over
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
7
2. The Lattice-Boltzmann Method
Figure 2.2: Stream and collide step (image taken from Nils Th¨ urey [Th¨ u07])
all lattice cells and either pushing the distribution functions of the current cell to its neighbors or pulling those values from them respectively.
Splitting the LBE as above is referred to as the collide-stream order. Reversing the order to stream-collide as illustrated in Figure 2.2 is perfectly possible as well and numerical differences between the two are negligible. However, [Igl03] attributes the collide-stream order a slightly better overall performance. It is common to merge both steps in the implementation to require only a single sweep over all grid cells, where in case of the collide-stream order the streaming step directly pushes to the neighboring cells. As a consequence, the post-collision distribution values are never actually stored in the grid. Algorithm 2.1 shows the basic algorithm of the Lattice-Boltzmann Method.
8
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2. The Lattice-Boltzmann Method
1 2 3 4 5 6 7 8 9
setup () ; for ( int step = 0; step < maxSteps ; ++ step ) { collideStream () ; handleBoundaries () ; } Algorithm 2.1: Basic algorithm of the Lattice-Boltzmann Method
2.2 Improved Stability with the Smagorinsky Turbulence Model The Lattice-Boltzmann Method has a limited area of stability that imposes the restriction τ > 1/2 on the relaxation time τ , equal to limiting the collision frequency to ω < 2. Stability considerations for the LBM can be found in [WG00, Chapter 5.6] and [Suc01, Chapter 11.1]. The relaxation time τ is related to the kinematic shear viscosity as ν=
2τ − 1 . 6
(2.9)
As τ approaches 1/2, ν goes to zero and more and more turbulent flow results, corresponding to a high Reynolds number and leading to instability of the basic LBM. Wei et al. [WZF+ 03] explain this instability with the inability of the LBM to represent flow dynamics on scales smaller than the lattice spacing, disabling the possibility of energy transfer to these small scales. To alleviate the issue of the basic LBM becoming more and more unstable, the Smagorinsky sub-grid model as described in [HSCD96] and [Th¨ u07] is applied. Sub-grid model in this context does not refer to a grid refinement. Instead it accounts for small-scale physical effects that cannot be resolved on the ordinary lattice scale by the LBM anymore. This is done by adding a positive eddy viscosity to the kinematic shear viscosity before the collision step and in turn influencing the relaxation time τ , pushing it within safe bounds. Consequently, the single-relaxation-time scheme is given up by allowing a variation of the relaxation time over the lattice. For each cell, a number of local computations need to be done to determine the relaxation time modification, beginning with the non-equilibrium stress tensor X Πα,β = eiα eiβ (fi − fieq ), (2.10) i
where α and β run over the three spatial dimensions and i denotes the distribution function or lattice velocity respectively. The second variance of this tensor is given as Q = Πα,β Πα,β . Next, the intensity of the local stress tensor is computed as q p 1 2 2 ν + 18C Q − ν , S= 6C 2
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
(2.11)
(2.12)
9
2. The Lattice-Boltzmann Method and finally the modified relaxation time is given by 1 τs = 3(ν + C 2 S) + . 2
(2.13)
As S is evidently always positive, the local viscosity is increased proportional to the local stress tensor. Thus, the relaxation time grows alike and is effectively driven out of the critical region close to the basis value of 1/2.
2.3 Boundary Treatment One of the key advantages of the Lattice-Boltzmann Method is the straightforward implementation and natural treatment of boundary conditions. To support flexible setups, it is necessary to make use of this property and implement different kinds of boundary conditions, as explained in the following.
2.3.1 No-slip Boundary Conditions The most commonly used boundary conditions for LBM are the no-slip boundary conditions, representing a “sticky” wall, and characterized by a fluid velocity of zero at the boundary for the normal as well as the tangential component of the velocity. They are simply implemented as a bounce-back, meaning distribution values that would propagate to a no-slip boundary cell are reversed instead. From an implementation point of view, these values are copied to the distribution values of the inverse direction as depicted in Figure 2.3. Therefore this condition is often referred to as “bounce-back” boundary condition of the link bounce back kind that places the boundary at the midpoint between fluid and obstacle cell. In terms of implementation it requires altering the streaming step for every velocity direction i pointing towards a wall to f˜i (x + e˜i ∆t, t + ∆t) = fi∗ (x, t).
(2.14)
2.3.2 Acceleration Boundary Conditions A wall that is not at rest is implemented similar to the no-slip boundary conditions, but the velocity at the wall is set to a user defined value, the moving speed of the wall, instead of zero. The bounce-back is therefor augmented by a velocity-dependent term, resulting in a streaming step of f˜i (x + e˜i ∆t, t + ∆t) = fi∗ (x, t) + 6wi ρw e˜i · uw (2.15) where wi is the equilibrium distribution function weighting factor, ρw is the fluid density at the wall and uw is the moving speed of the wall. Frictional forces acted upon the fluid by the wall movement are modelled by this additional term.
2.3.3 Inflow Boundary Conditions Fluid flow entering the domain from outside can be modelled by setting the distribution functions of the inflow boundary cells to the equilibrium distribution values of unit density and a velocity
10
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2. The Lattice-Boltzmann Method
Figure 2.3: Bounce back boundary treatment (image taken from Nils Th¨ urey [Th¨ u07])
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
11
2. The Lattice-Boltzmann Method equal to that of the incoming flow specified by the user: 9 3 2 fi (x, t + ∆t) = wi 1 + 3ei · uin + (ei · uin ) − (uin · uin ) . 2 2
(2.16)
2.3.4 Outflow Boundary Conditions Using the same approach as for an inflow for an outflow boundary condition, where fluid flow is supposed to leave the domain, usually does not give the desired results as the outflow velocity is not known in advance and thus cannot be pre-defined. What is mostly desired is an outflow with the current velocity of the cell at the outflow boundary. Feichtinger et al. [FGD+ 07] suggest two different approaches for that. The first approach is the pressure boundary condition adapted from [Th¨ u07], where the outflow cells are assigned atmospheric pressure by using the reference density ρA = 1 and setting 9 3 eq eq 2 fi (x, t + ∆t) = fi (ρA , u) + f˜i (ρA , u) − f˜i (x, t) = 2wi 1 − (u · u) + (ei · u) − f˜i (x, t), 2 2 (2.17) where u = u(x, t) is the fluid velocity of boundary cell x at time t. The second approach is imposing a pressure gradient of zero at the boundary by not using a prescribed pressure value like that of the atmosphere, but the current pressure ρ of the cell: 3 9 2 fi (x, t + ∆t) = 2wi ρ − (u · u) + (ei · u) − f˜i (x, t) (2.18) 2 2 However, Feichtinger et al. [FGD+ 07] report that using this second pressure condition as outflow condition increases the overall domain density when combined with inflow conditions.
2.4 Obstacles The ease of treating boundary conditions in the Lattice-Boltzmann Method is paired with an equally straightforward way to cope with obstacles in the interior of the flow domain. Two possibilities are outlined in the following, a very simplistic one for box-shaped obstacles and a more elaborate one handling the curved boundaries of spherical obstacles.
2.4.1 Cell-Boundary Aligned Obstacles Obstacles in the flow can be easily handled as long as their bounds follow the lattice cell boundaries by simply defining the corresponding cells as no-slip boundary cells. A cuboid-shaped obstacle is the simplest conceivable case and can be defined by two opposite corner cells. Their indices delimit the volume to be occupied by the obstacle in the three lattice space dimensions. More complex shapes could be attained by combination of several of these “boxes”. The standard no-slip boundaries belong to the link bounce back conditions, where the wall is placed exactly halfway between fluid and boundary node. Though this assumption could be retained to approximate arbitrary shaped obstacles by the standard no-slip conditions, this “staircase approximation” as described above is not accurate. Figure 2.4(a) shows that for a curved boundary an error is introduced with every bounce back from a link where the wall is
12
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2. The Lattice-Boltzmann Method
(a) Error introduced by “staircase approximation”
(b) Lattice link intersections of a curved boundary
Figure 2.4: Obstacle with curved boundary in the LBM lattice (images taken from Klaus Iglberger [Igl05])
not placed exactly in between two nodes. Thus it is necessary to introduce an appropriate and accurate treatment for obstacles of more complex shape, for instance curved surfaces like those of spheres.
2.4.2 Curved Boundaries For obstacles of arbitrary shape, the intersection of the obstacle surface with the lattice link can be at an arbitrary distance between 0 and the link length from the fluid node under consideration. √ Note that for multispeed models lattice links can be of different lengths such as 1 and 2 for the D3Q19 model used. An accurate boundary treatment requires precisely calculating this distance that will be referred to as delta value of that particular lattice link or “fluid fraction”. As illustrated in Figure 2.4(b) it represents the fraction of the link length lying within the fluid domain and is computed as |xf − xw | , (2.19) ∆= |xf − xo | with xf being the fluid node and xo the boundary node associated with the link and xw being the intersection point with the surface. This fraction needs to be calculated for each lattice link intersecting the obstacle surface. Prerequisite for this calculation is to know the intersection point. An elementary deviation of this computation for a sphere is given in the following. We assume that all obstacle cells within the sphere radius that have a lattice link intersecting the surface have already been located. Picking one of these nodes as boundary o and denoting the center of the sphere c we get the difference vector as l = o − c. With e being the unit vector along the lattice link under consideration, we can write the intersection point as x = o + αe = c + l + αe with α the distance from o to the intersection point along e.
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
13
2. The Lattice-Boltzmann Method
α
b
e o
f
l
m
r c
Figure 2.5: Intersection calculation of lattice link and sphere
Putting x into the sphere equation |x − c| = r2 yields |x − c| = |l + αe| = (l1 + αe1 )2 + (l2 + αe2 )2 + (l3 + αe3 )2 = r2 , and rearranging α2 (e21 + e22 + e23 ) + 2α(l1 · e1 + l2 · e2 + l3 · e3 ) + (l12 + l22 + l32 ) = r2 . Noting that e is of unit length we can simplify this quadratic equation in α to α2 + α · 2(l · e) + (l · l − r2 ) = 0. Solving for α, we are only interested in the positive solution p α = (l · e)2 − l · l + r2 − l · e.
(2.20)
This calculation is illustrated in Figure 2.5, where o denotes the obstacle, f the fluid node,
14
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
2. The Lattice-Boltzmann Method
Figure 2.6: Bounce back behavior depending on the position of the wall along the lattice link (images taken from Klaus Iglberger [Igl05])
and c is the cell center. Looking at the right triangle formed by the slope of l, b = l · e for e of unit length and m2 = l · l − b2 by the √ Pythagorean theorem. Applying the same theorem to the right triangle over r, one gets α = r2 − m2 − b equal to Equation (2.20). As ∆ is defined as the fluid fraction, we still need to normalize α with the length of the link and then take the difference to 1: α ∆=1− . (2.21) |xf − xo | We end up with the same result as [Igl05], though the derivation differs slightly. An example implementation is given in Algorithm 2.2.
1 2 3 4 5 6
float calcDelta ( Vecf o , Vecf c , Vecf e , float r ) { Vecf l = o - c ; float b = normalize ( e ) * l ; float c = l * l - r * r ; return 1.0 - ( b + sqrt ( b * b - c ) ) / len ( e ) ; }
Algorithm 2.2: Calculation of the delta value for lattice link intersection with the boundary given the obstacle node o, sphere center c, lattice link e and radius r
Now we need to fit these delta values falling into a range of ]0, 1] into the bounce back scheme. Note that values of 0 do not occur as the wall would in this case lie at the fluid node, which is consequently treated as an obstacle node. Moving with lattice velocity, the particle distribution functions propagate by precisely the lattice spacing every time step. If they do not bounce back from a wall located at the midpoint between fluid and obstacle node, they will therefore come to rest either behind the fluid node or between the fluid and the obstacle node, depending whether the wall lies closer to the fluid or the obstacle node respectively, compared to the halfway bounce back. The different cases are illustrated in Figure 2.6. Either way, some kind of interpolation needs to be applied, as we need to know the distribution function of the fluid node pointing away from the obstacle surface. An overview and a comparison of the approach of Filippova and H¨anel (FH-model) using a fictitious distribution function and the approaches of Boudizi and Yu, both interpolation-based models, is presented in [KY08]. They point out that the FH and Boudizi models require a distinction of delta values below and above 1/2 and the FH-model furthermore the computationally fairly expensive collision with the fictitious distribution function. Taking this into consideration, the approach of Yu was chosen, involving two interpolation steps in the linear case, where Boudizi’s approach only requires one. Improved accuracy paired with higher computational expense by an interpolation of second order was not investigated.
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
15
2. The Lattice-Boltzmann Method
(a) Cell state modification for a moving boundary
(b) Cell states after obstacle movement
Figure 2.7: Pre- and post-moving state of an obstacle (images taken from Klaus Iglberger [Igl05])
Yu’s model can be formulated as f˜i (xf , t + ∆t) =
1 [(1 − ∆)fi (xf , t) + ∆fi (xo , t) + ∆f˜i (xf 0 , t) + 6wi ρw e˜i · uw ], 1+∆
(2.22)
where i denotes the lattice link in direction towards, ˜i in direction from the obstacle surface, xf is the fluid node, xo is the obstacle node associated by the lattice link, and xf 0 = xf + e˜i ∆t. Furthermore, wi is the equilibrium distribution value, ρw is the density at the obstacle surface, and uw the obstacle velocity. For an obstacle at rest, the last term in equation 2.22 can be skipped and the determination of the obstacle boundary cells and computation of delta values for links intersecting the surface needs only to be done once, e.g. during LBM setup phase. If the sphere is allowed to move, however, cells will need to turn from fluid cells to obstacle cells and vice versa, as shown in Figure 2.7. In other words, the determination of obstacle boundary cells and delta value calculation needs to be done for every time step, resulting in a significant additional computational effort.
16
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
3 Characteristics of Fire What actually happens when a flammable object catches fire and burns? Though this question is far too complex to answer in detail, a short overview of the scientific aspects is necessary to motivate a physically-based fire simulation. Nielsen and Madsen treat this matter more thoroughly in their Master’s thesis [NM99] that gives an overview of a variety of methods to model, animate, and visualize fire along with some physical background. Great parts of this chapter are loosely based on it.
3.1 A Physical Motivation Contrary to popular belief, it is not the wood itself burning in a campfire, but the fuel, i.e. sap and wood oils, contained in them and driven to the surface by heat. Burning is a rapid oxidation of a flammable object caused by high temperature. Having said that, we already mentioned the three ingredients of fire: fuel, oxygen, and heat. But what is fire? Facing this question, one instantaneously tends to fall back to describing its characteristics, the color, the shape, the heat, the greedy spreading, and connected dangers. We will not dare trying to answer this question, since the phenomenon of fire is far from being fully understood even by experts, but instead go through some general terms first, taken from [NM99]. The lowest temperature, where fuel vapor forms an ignitable mixture with air is called flash point. As soon as the vapor can sustain a burning flame for at least five seconds, the fire point is reached. At the critical temperature, a flammable liquid is irrevocably turned into vapor at atmospheric pressure. Self-sustained combustion is possible above the ignition temperature, depending on a multitude of conditions such as fuel concentration, air mixture, temperature of the ignition source, and many more.
3.2 Categorization of Fire Depending on external circumstances like supply of fuel and oxygen, fire develops differently and shows distinct visual characteristics. Based upon that, [NM99] try a categorization. A calm fire is for example that of a lit candle, undisturbed by wind and resulting in an almost static flame. It is classified as a diffusion flame, since a sufficient amount of oxygen needs to diffuse inwards to reach the burning zone. Supply of fuel and oxygen is controlled and the flame has no direct possibilities of spreading. The freely fed fire permeates the whole burning object and receives virtually unlimited fuel and oxygen. Vapor is advected by buoyancy forces and thus limits the flame spreading to the upward direction. In contrast, the motion of the flammable vapor of a pressure fed fire is mainly dictated by the fuel’s velocity vectors when leaving the pressure tank. For this kind of flame, oxygen is usually premixed with the fuel before ignition to obtain clean combustion with no soot being
17
3. Characteristics of Fire formed. In this way, the combustion process can be controlled to a certain extent, which applies to the temperature in particular. This type of control is for instance used in a Bunsen burner that can reach very high temperature regions. A violent fire is fed somewhat more irregularly, fuel is vaporized as available. It may spread to other flammable regions, but the spreading is mainly directed by advecting buoyancy forces if not strongly influenced by environmental circumstances such as wind. In this thesis, we are mainly concerned with freely or pressure fed fire, that are visually more interesting than a candle flame, yet fairly simple to model. The focus is put on the interaction with external wind fields rather than the spreading of fire, which will be omitted.
3.3 The Color of Flame In physics, light emitted solely due to an object’s high temperature is referred to as incandescence. The higher the temperature, the faster the Brownian motion of the atoms and therefore the higher the energy the electrons gain by more frequent collisions, enabling them to rise to a higher energy level, a quantum leap, and emitting photons when falling back to their respective base levels. This phenomenon is described as one of 15 causes of color in [Nas01]. As the object is heated, the incandescent light spectrum turns from black over red, orange, yellow and white to blue-white. The path taken in the chromaticity space of visible light depicted in Figure 3.1 is called Planckian Locus. This transition corresponds to an increase of energy of the light. What we perceive as “white” daylight is incandescent light emitted by the sun with a surface temperature of about 5700 . It appears white because it is a mixture of a high number of different wavelengths of the visible spectrum of light. Black body radiation is a special form of incandescence. A black body is an ideal absorber that neither reflects nor transmits any electromagnetic radiation. Specifically, no light is reflected, what makes the object appear black when cold, hence the name. But when heated, it emits a characteristic, temperature-dependent spectrum of incandescent light, the black body radiation, displayed in Figure 3.2 for a range of 1000 to 16000K. In the resulting black body table, every possible temperature, commonly measured in Kelvin, can be assigned a corresponding color. The other way round, the black body palette can also be used to determine an estimate of the flame temperature given its color. Of course this is an idealization. There is no real-world object with black body properties. Nevertheless, the color of a flame or a very hot object, imagine metalwork of a blacksmith just extracted from the forge, can give a rough temperature estimate. More specifically, one can assign a color temperature to any incandescent object by taking the temperature of a true black body emitter that best matches the color of the actual incandescent object. Soot remaining from incomplete combustion, mostly carbon, is responsible for the black body coloring of flames. This can be demonstrated by adjusting the oxygen supply vent of a Bunsen burner. The wider open, the more oxygen reaches the combustion zone, the hotter the flame, where the color, turning from yellow-orange to blue, serves as an indicator of the temperature. In zones of residue-free combustion, as for instance in the hottest part of the flame, the flame is even translucent as no soot is present there. Real-world flame colors are moreover influenced by spectral band emission of the burning material, the characteristic emission of an element given by the structure of its valence orbital. A widespread experiment in chemistry education at schools to demonstrate this phenomenon is the flame test of sodium, which gives a characteristic
18
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
3. Characteristics of Fire
Figure 3.1: CIE 1931 chromaticity diagram including the Planckian locus1
1800 K
4000 K
5500 K
8000 K
12.000 K
Figure 3.2: Black body color spectrum for 1000 - 16000K
16.000 K
2
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
19
3. Characteristics of Fire
convection
drag drag pressure
Thermal Buoyancy
pressure
(low pressure)
Figure 3.3: Influences directing the movement of smoke particles (Image taken from [NM99])
bright-yellow burning flame.
3.4 Smoke What we perceive as smoke is hot gas containing remains of incomplete combustion such as soot and tiny fragments of the burnt material. The color of the smoke particles themselves is mostly very dark to black, the color of rising smoke as a whole depends on its density and lighting conditions. This interaction with light according to [NM99] mainly consists of three components. One is scattering of light rays at particles, possibly happening multifold within the smoke cloud. The second is the albedo of this medium, the amount of light being refracted out of the cloud and thus emanating from its surface. Self shadowing is the third component to consider, resulting in the surface of the medium appearing brighter and the inside of the cloud subsequently getting darker. The smoke particle motion is according to Figure 3.3 mainly driven by the thermal buoyancy forces acting on the hot gas and advecting it faster than the surrounding cool air, causing turbulent drag forces at the interface resulting in the formation of eddies and pushing along the air above, know as convection. Beneath the rising gas a drop in pressure occurs, dragging in cooler air from the sides.
1 2
http://commons.wikimedia.org/wiki/File:PlanckianLocus.png, version of 16 Apr 2005 15:51 http://commons.wikimedia.org/wiki/File:Color_temperature_sRGB.svg, version of 13 Jan 2008 16:00
20
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
4 A Model of Freely Fed Fire 4.1 Overview of the Model The implementation presented in this chapter is based on the work of Wei et al. published in the paper “Simulating Fire with Texture Splats” [WLMK02]. They present a model of freely fed fire that is essentially a particle system. The particles represent the individual flames and are referred to as display primitives. They are advected by a Lattice-Boltzmann computed 3D velocity volume representing the airflow and incorporating boundary conditions and interaction with obstacles and environmental influences like wind fields. When inserted, each primitive is assigned a certain amount of fuel it consumes over its lifespan. As all the fuel is used up, the display primitive expires and is removed from the system. For the particle system they propose the following algorithm: 1. Inject new fire particles into the system with an initial texture and fuel value 2. Perform one step of the LBM solver to update the velocity vectors of the lattice 3. Move each fire particle according to the trilinearly interpolated velocity vector at the particle’s current position. Check for particles that leave the grid or have consumed all of their fuel and remove them from the system. 4. Compute the temperature of each particle with a linear temperature model and assign a color to the particle according to a black body color table. If the particle temperature falls below a certain threshold, convert it to a smoke particle and color it using a separate color table. Decrease the fuel value of each particle. 5. Render the particles
4.2 Evaluation As the authors state in [WLMK02], the presented model offers a physically-based description of the evolution of fire and its interaction with the environment. It claims by no means to be physically accurate and that is not the primary intention. The goal is computational efficiency to allow a visualization in real-time as described in the next chapter. All steps of the implementation and also the results should be regarded with this in mind. A limitation of the model is the absence of a feedback from the temperature field back into the LBM. In fact, this limitation is one of the LBM itself, as the D3Q19 is an isothermal model that cannot describe the energy transfer caused by temperature differences [WLMK04]. For a discussion of the problems involved refer to the book of Succi [Suc01, Chapter 14], where several thermodynamic Lattice-Boltzmann models are introduced. The author concludes that none of them is free from stability problems so far.
21
4. A Model of Freely Fed Fire
boost
ConfParser
ConfBlock
Irrlicht
confparser Vec ParticleSystem
LBM lbm
Grid
Particle Emitter particles
main_lbm
main_ps
Figure 4.1: Intersection calculation of lattice link and sphere
Consequently, temperature-induced buoyancy cannot be incorporated into the LBM computations. As a compromise, buoyancy forces will therefore be treated independently in the implementation, while they are omitted altogether in the model of Wei et al. For the temperatureindependent advecting velocity field of the LBM, however, it is necessary to explicitly prescribe inflow boundary conditions with fixed velocities as sources of the flow.
4.3 Implementation Aspects 4.3.1 Overview of the Implemented Classes The implementation is divided into namespaces and classes as shown in Figure 4.1. As the core component, the Lattice-Boltzmann fluid solver was designed completely independent of the fire simulation code. It is wrapped in the class LBM residing in the lbm namespace, can be used with both float and double data types, and implements all the features detailed in Chapter 2. The namespace confparser contains the two classes ConfParser and ConfBlock responsible for parsing parameter files containing the description of the scene to simulate. These are described in detail in Section 7.1. As the parser only turns the configuration file into a format the application can then query for parameter values but makes no assumption of its content, it can be used for other applications without modification. The main component of the fire simulation is the particle system organized in the classes ParticleSystem, Particle and Emitter in the namespace particles. ParticleSystem contains the main simulation loop, invoking the LBM solver and the visualization, that is separately presented in Chapter 5. Emitter and Particle are the data structures for the particle sources and the particles, respectively.
22
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
4. A Model of Freely Fed Fire
4.3.2 Particle System Main Loop All the components of the particle system are triggered from its main loop, defining the order of steps that need to be performed in every time step. We will first only concentrate on the control of particles, omitting the visualization for the moment. As shown in Algorithm 4.1, the three core parts are emitParticles(), where new particles enter the scene at defined inlets, calculation of the velocity field by calling the runStep() function of the LBM solver and updateParticles(), comprising the movement, exchange of temperature, and the check for the end of life of each particle. 1 2 3 4
setupLBM () ; s et u p Pa r t ic l e Sy s t em () ; for ( int step = 0; step < maxSteps ; ++ step ) {
5 6 7 8 9 10 11 12
emitParticles () ; solver . runStep () ; updateParticles () ; } Algorithm 4.1: Particle system main loop
4.3.3 Particles Fire is for modeling purposes abstracted by a cloud of particles characterized by the four properties type, i.e. fire or smoke, position in 3D space, temperature and lifetime, a measure for the remaining fuel. An excerpt from the class declaration is given in Algorithm 4.2. For construction, the latter three properties must be specified, the type is implicitly set to fire. The functions dist() returning the distance between the current and a given particle and updatePos() to move the particle by a given vector will be needed in the particle update step described later.
4.3.4 Emission New fire particles enter the scene at certain user-defined inlets constituting the sources of flame. These emitters are defined by a volume given by position and size, where new particles appear at random positions, a temperature that is set as initial temperature of newly created particles, a fuel value defining their lifespan and a list of particles emitted by this source. The class declaration of an emitter given in Algorithm 4.3 contains three further coefficients, emitThreshold, defining the maximum amount of particles that can be emitted per time step, fuelConsumption, a factor by which the emitter’s fuel is reduced with every emission, and lifetimeCoeff, a factor defining what fraction of the emitter’s current fuel value is assigned to each particle as initial lifetime. The actual emission step is a loop over all emitters, where each emits a random number of particles up to its given upper threshold. Those newly created particles are appended to the emitter’s particle list particles and assigned a random position in the emitter volume, initial temperature equal to the emitter temperature and lifetime according
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
23
4. A Model of Freely Fed Fire
1 2 3 4 5 6
class Particle { public : Particle ( const Vec3 < float >& Position , float Temperature , uint Lifetime ) ;
7 8 9 10 11 12 13 14 15 16 17 18
virtual ~ Particle () ; float dist ( Particle & particle ) ; void updatePos ( const Vec3 < float >& distance ) ; ... protected : Vec3 < float > position ; ParticleType type ; float temperature ; uint lifetime ;
19 20 21 22 23 24
}; Algorithm 4.2: Excerpt from the declaration of the class Particle
1 2 3
class Emitter { public :
4 5 6 7 8 9
Emitter ( Vec3 < float > Position , Vec3 < float > Size , float Temperature , int Fuel , int EmitThreshold , float FuelConsumption , float LifetimeCoeff ) ;
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
virtual ~ Emitter () {} protected : list < Particle > particles ; Vec3 < float > position ; Vec3 < float > size ; float temperature ; int fuel ; int emitThreshold ; float fuelConsumption ; float lifetimeCoeff ; }; Algorithm 4.3: Excerpt from the declaration of the class Emitter
24
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
4. A Model of Freely Fed Fire
ui+1,j+1
ui,j+1 (xi,yj+1)
up,res
(xi+1,yj+1)
v(Tp) u(xp,yp) (xp,yp)
ui,j
ui+1,j
(xi,yj)
(xi+1,yj)
Figure 4.2: Composition of the particle movement vector
to fuel * lifetimeCoeff. Each emission consumes part of the fuel supply that is therefore decreased, affecting the lifespan of future particles.
4.3.5 Particle Update Step Movement And Buoyancy To account for the buoyancy of the hot fire and smoke particles, an additional temperaturedependent force term is introduced, directed against gravity. The governing equation is taken from [WLMK04] as Fbuoyancy = Hg(Tk − Tamb ), (4.1) where g is the inverse gravity vector, H the coefficient of thermal expansion and Tamb the ambient temperature. The final particle movement is then given as the composition of this buoyancy force and the
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
25
4. A Model of Freely Fed Fire velocity computed by the LBM, illustrated in Figure 4.2. As the particles are not restricted to the lattice but can reside at arbitrary positions in the domain, the LBM velocity is trilinearly interpolated. Care needs to be taken at the boundaries of obstacles in the domain. Where the Lattice-Boltzmann computation directs the flow around the obstacle, this additional advection term could carry the particle inside the obstacle if not prevented by a collision detection. Temperature Model As the LBM is isothermal and cannot track temperature information, a simple linear heat equation is employed to approximate the particle temperature over time and the heat the particles radiate onto one another: X Tk (t) = αTk (t − 1) + β G(dkj )Tj (t − 1) (4.2) j6=k
where α is the heat conservation, β the transferability coefficient, dkj the distance between the display primitives k and j, G() a Gaussian filter to approximate the effect of diffusion and Tk (0) is the predefined initial temperature. This temperature information is needed to determine the color of a display primitive as described in Section 3.3 and decide when the fire particle turns into a smoke particle. Therefor Equation (4.2) needs to be evaluated for every particle in every time step, where the Gaussian distribution is tabulated at distinct samples over the whole range of possible distance values. Particles lying dense within the flame’s core are effectively kept at high temperature, whereas those towards the edge of the flame receive fewer irradiated heat and thus cool down faster. Eventually, the particle gets carried out of the core area and after cooling down below a given threshold, it is turned into a smoke particle. The Algorithm The begin of every update step is a check for particles that need to be removed from the scene either because they have exceeded their lifespan and used up all their fuel or because they have moved out of the simulation domain. Next, the particles are moved by a vector composed of the LBM velocity at the current particle position and the buoyancy force depending on the temperature. A collision test confirms that they will not end up in an obstacle. Otherwise, they are only moved by the velocity coming from the LBM. Afterwards, the temperature is computed with Equation (4.2). If it has fallen below the threshold temperature, the particle type is changed from fire to smoke. Finally, the particle’s lifetime is decreased. Algorithm 4.4 shows a simplified implementation.
26
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
4. A Model of Freely Fed Fire
1 2 3 4
void updateParticles () { // Go over all particles of all emitters for ( ParticleIterator p = particles . begin () ; p != particles . end () ; ++ p ) {
5 6 7 8 9 10
// Remove particles that have left the domain , exceeded their lifetime , or // cooled down to ambient temperature while ( outsideDomain ( p - > pos ) || p - > lifetime == 0 || p - > temp < ambTemp ) p = particles . erase ( p ) ;
11 12 13 14 15 16
// Move particle according to fluid velocity at current position Vec3 < float > v = solver . getVelocity ( p - > pos ) ; // Buoyancy force Vec3 < float > b = gravity * k * ( p - > temp - ambTemp ) ; // Resulting particle movement vector Vec3 < float > u = b + v ;
17 18 19 20 21 22
// Check whether buoyancy force would carry particle into an obstacle for ( ObstacleIterator o = obstacles . begin () ; o != obstacles . end () ; ++ o ) if ( o - > isPointInside ( p - > pos + u ) ) { u = v; break ; }
23 24 25 26 27
// Move the particle p - > updatePos ( u ) ; // Update temperature float tempExt = - gaussTable [0] * p - > temp ; // Add up temperature contributions of all other particles weighted by // distance for ( p2 = particles . begin () ; p2 != particles . end () ; ++ p2 ) tempExt += gaussTable [ p - > dist ( * p2 ) ] * p2 - > temp ; p - > temp = alpha * p - > temp + beta * tempExt ;
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// If temperature has fallen below threshold , convert to smoke particle if ( p - > temp < smokeTemp ) p - > type = SMOKE ; // Decrease particle lifetime p - > lifetime - -; } } Algorithm 4.4: Simplified implementation of the particle update method
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
27
4. A Model of Freely Fed Fire
28
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
5 Visualization In most cases, a fire simulation is targeted on producing visually pleasing and graphically rich imagery, and this work is no exception in this regard. The visualization is aimed at real-time frame rates, where the rendering is performed by the Irrlicht 3D engine. This chapter comprises an overview of this framework, the visualization and coloring of fire and smoke particles, and a word on modeling the surroundings.
5.1 Irrlicht 3D Engine On its official website, the author Nikolaus Gebhard describes Irrlicht as a cross-platform high performance realtime 3D engine with a powerful high level API for creating complete 3D and 2D applications like games or scientific visualization [Geb09]. Cross-platform means not only support for different operating systems, but also for different rendering engines, namely OpenGL, Direct3D 8.1 and 9.0, and two different software renderers. Further criteria for choosing this engine were the built-in support for a number of image and mesh formats, but most important the available library functions and that it is open source. Irrlicht holds, as most 3D engines do, everything that needs to be drawn in the screen as scene nodes of a hierarchical scene graph. The camera is a scene node as well. Simple primitives like boxes and spheres are readily available as objects in Irrlicht and can be pasted with a texture. More complex objects need to be loaded from a mesh file and can be placed freely in the scene. As the rendering is completely handled by the Irrlicht engine, the particle system needs to take care of populating the scene graph with all necessary objects at the right positions and with the right properties set. The API is quite well structured, has a steep learning curve, and a high level of abstraction, such that a working example can be developed with only a few lines of code. A demonstration is given by Algorithm 5.1 that is adapted from the “HelloWorld” tutorial on the Irrlicht website1 . The very heart of the engine is the IrrlichtDevice, that should only be created once with the graphics backend, desired resolution, color depth, and optionally further parameters specified. Having created that, one can access all components of the engine, most importantly the indispensable VideoDriver that is an interface to the system’s video driver, and the SceneManager that provides convenient methods for populating and modifying the scene graph. In the example, a mesh file is loaded and added to the scene after all the initialization is done. A texture is added to it and as there are no light sources in the scene, dynamic lighting is turned off such that the model is illuminated globally. For defining the point of view, a static camera is inserted afterwards with a fixed position and focus point. Then the main loop is started by calling the device’s run() method. In every loop iteration, the driver is instructed to begin the rendering process by calling beginScene(), then the scene manager draws everything contained in the scene graph and the video driver finishes the rendering. The loop only exits when the user 1
http://irrlicht.sourceforge.net/docu/example001.html
29
5. Visualization enforces it by closing the window or hitting Ctrl-C. There is not much going on in this static scene though, but the API reference2 documents the manifold possibilities at hand that were partly harnessed in this thesis. # include < irrlicht .h >
1 2 3 4
using namespace irr ; int main () { IrrlichtDevice * device = createDevice ( video :: EDT_OPENGL , dimension2d < u32 >(640 , 480) , 16 ) ;
5 6 7 8 9 10
if (! device ) throw " Could not create OpenGL device ! " ;
11 12 13 14 15 16
device - > setWindowCaption ( L " Hello World ! - Irrlicht Engine Demo " ) ; video :: IVideoDriver * driver = device - > getVideoDriver () ; scene :: ISceneManager * smgr = device - > getSceneManager () ;
17 18 19 20 21 22
scene :: IAnimatedMesh * mesh = smgr - > getMesh ( " mesh . obj " ) ; scene :: I A n i m a t e d M e s h S c e n e N o d e * node = smgr - > a d d A n i m a t e d M e s h S c e n e N o d e ( mesh ) ; if ( node ) { node - > setMaterialFlag ( EMF_LIGHTING , false ) ; node - > s et Ma te ri al Te xt ur e ( 0 , driver - > getTexture ( " texture . bmp " ) ) ; }
23 24 25 26 27
smgr - > a dd Ca me ra Sc en eN od e (0 , core :: vector3df (0 ,30 , -40) , core :: vector3df (0 ,5 ,0) ) ;
28 29 30 31 32 33
while ( device - > run () ) { driver - > beginScene ( true , true , video :: SColor (255 ,100 ,100 ,100) ) ; smgr - > drawAll () ; driver - > endScene () ; }
34 35 36 37 38 39
device - > drop () ; return 0; } Algorithm 5.1: A basic Irrlicht engine example
5.2 Particles to the Screen Particles as introduced in the previous chapter are abstract entities in the first place that somehow require a manifestation on the screen. They were chosen to be represented by billboards [AMHH08, p. 447], textured polygons always facing the viewer, and thus hiding their inherently 2
http://irrlicht.sourceforge.net/docu/index.html
30
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
5. Visualization two dimensional nature. Despite the polygon usually being a quadrilateral, they can be given any shape by setting the texture partly transparent. Billboards are a very common choice for particle applications, being easy to handle, very flexible in use, and at the same time cheap to render. They are very closely related to sprites [AMHH08, p. 445], images that can be moved around freely on the screen and usually are partly transparent, as for instance the mouse cursor. But while sprites purely live in the 2D screen space and their pixels are mapped 1:1 on screen pixels, billboards do have “real” positions in the 3D scene space and are rendered together with all the other objects of the scene graph. Sprites can overlap by putting them on different layers, but this kind of depth information is completely independent of the Z-buffer based depth calculations of a 3D scene. For further details, the interested reader is referred to the book “Real-time rendering” of Akenine-M¨oller et al. [AMHH08]. In the following, the terms sprite, billboard and display primitive will be used interchangeably, though still referring to a billboard in terms of implementation. As the particle update step is rather computationally expensive, a possible compromise is to perform the simulation with a smaller number of particles but add more display primitives for rendering. In other words, for each particle a predefined number of billboards is added to the scenegraph and distributed randomly in a small area around its center. Thus a visually dense fire representation can also be achieved with a limited amount of particles in the simulation. In terms of implementation, the Particle class is extended by a vector of billboards and takes care that when the particle is moved, the display primitives representing it are moved similarly. When a billboard is added as display primitive to the scene, it is assigned a random texture from a pool of 32 fire textures and keeps it until its lifetime expires. The texture adds turbulent appearance to the particles. At first thought one might be tempted to change the texture at every time step to increase the impression of turbulence, but this only creates a visual enhancement in case the texture series is continuous. Otherwise the result is just a messy-looking perturbation. To account for the typical shape of a flame, rather round-bodied at the base and get slimmer towards the tip, the size of the billboards is adapted with the lifetime of the particle. A method is provided to set the size of the display primitives as size = sizebase +
lifetime · sizevar lifetimeinit
in every time step.
5.3 Coloring To actually resemble a flame, the cloud of particles needs to be colored appropriately. As described in Section 3.3, flame color can be approximated by that of an incandescent black body. To this end, a black body color table is precomputed with color samples up to double the particles’ initial temperature in steps of 50K. During the update step, each display primitive gets assigned the tabulated color closest to its current temperature through a function provided by the Particle class. Precisely, the billboard polygon is colored, the texture itself is a grayscale image and contributes the structure and transparency by acting as a weighting factor for the color of the underlying polygon. The same grayscale values are set again as the alpha channel. The final flame color results from simply adding up all color values of all billboards contributing to the drawing of a particular pixel. This mode of color determination is called additive blending
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
31
5. Visualization [AMHH08, p. 139] and is given as c0 = α s cs + cd
(5.1)
where c0 is the resulting color value, cs is the color and αs the opacity of the current billboard referred to as source, and cd is the resulting color of the previous step referred to as destination. In Irrlicht this is achieved by setting the material type to EMT_TRANSPARENT_ADD_COLOR. Note, however, that the billboard texture’s grayscale value serves as αs and the polygon color as cs in the implementation of this Irrlicht material. From a physical point of view, this makes sense, as the light reaching the viewer is superimposed from all light emitters lying in direction of this ray. Intuitively, the denser the fire, the brighter it should appear. When a particle has turned to smoke, its color is not given by the black body palette anymore, but is set to a gray value dependent on the remaining lifespan. The color rendered to the screen is now determined by blending the texture colors weighted by their corresponding alpha or opacity values with the underlying billboards from back to front, given by a formula called the over operator [AMHH08, p. 136] defined as c0 = αs cs + (1 − αs )cd
(5.2)
with the same symbols as in Equation (5.1). This differentiation is due to the fact that smoke particles do not send out light by themselves, so additive blending would lead to a wrong visual appearance. On transition from a fire to a smoke particle, the material type is changed to EMT_TRANSPARENT_ALPHA_CHANNEL to enable this blending mode in Irrlicht. When approaching the end of their lifetime, smoke particles should slowly fade out instead of just vanishing from one moment to the other. An easy solution to that would be decreasing the overall opacity value of the billboard from time step to time step. Not supported by any material type available in Irrlicht, this behavior is approximated by gradually darkening the billboard polygon color so that it adapts the black background.
5.4 Environment and Lighting As a fire burning in the pure blackness of empty space looks somewhat out of place, a few possibilities are provided to make the scene look more lively. First of all, an obstacle placed into the domain, be it stationary of moving, can be set visible and pasted with a texture. It is not necessary to provide a corresponding mesh to the object, as only spheres and axis-aligned cuboids are supported, that can be drawn using built-in functions of Irrlicht. Secondly, any static mesh Irrlicht is capable of loading and handling can be placed at an arbitrary position into the scene, scaled if desired and a texture can be applied if the model has none. Irrlicht supports quite a number of file formats. Details on that can be found in the feature list of [Geb09]. Furthermore, planes of finite extension can be placed with an arbitrary orientation into the scene and again be supplied with a texture. Fire is most impressive in the dark, when it is the only light source available and illuminates the surroundings in warm color. This visual effect can be attained by dynamic lighting. When activated, every billboard representing a fire particle gets a light source attached on insertion, that is deleted again as the particle turns to smoke. The color of light coming from the flame core is modified by all the billboards it passes through on its way from the source to the surface it illuminates, resulting in a realistic tinge.
32
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
5. Visualization
5.5 Integration into the Particle System 1 2 3 4 5 6 7 8 9
setupLBM () ; s et u p Pa r t ic l e Sy s t em () ; setupIrrlicht () ; for ( int step = 0; device - > run () && step < maxSteps ; ++ step ) { emitParticles () ; driver - > beginScene () ; sceneManager - > drawAll () ; driver - > endScene () ;
10 11 12 13 14 15 16 17
solver . runStep () ; updateParticles () ; } Algorithm 5.2: Visualization-enabled particle system main loop
A number of changes are required to integrate the Irrlicht-based visualization into the particle system. First of all, the engine needs to be initialized with the graphics backend to use and the desired resolution similar to Algorithm 5.1. The Irrlicht main loop with the rendering of the scene graph objects is integrated into that of the particle system as demonstrated in Algorithm 5.2. Population of the scene graph by the static scene environment is done during setup already, while the billboards acting as display primitives are added during the particle emission step and are optionally equipped with light sources if dynamic lighting is enabled. They are moved, adapted in size and color, and removed again if the particle has left the domain or has consumed all its fuel.
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
33
5. Visualization
34
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
6 Performance Aspects This chapter contains a discussion of the performance impact of different components of the Lattice-Boltzmann fluid solver, the particle system, and the 3D visualization. All tests were performed on machines equipped with an Intel Core2 Duo 6400 dual core CPU, each core running at 2.13GHz, and having 2MB L2-cache at its disposal, 2GB of main memory and an nVIDIA GeForce 7300 series video card. The code was compiled with g++ 4.2.1, linking against Irrlicht 1.5.0 and Boost 1.37.0 libraries on an openSUSE Linux x86 64 operating system.
6.1 Lattice-Boltzmann Solver The performance of Lattice-Boltzmann implementations has been measured and evaluated in great detail at the Chair for System Simulation, and various approaches for optimization have been worked out in previous theses [Don04, Igl03, Hab06]. For this thesis, however, the goal was substantially different. Optimization was not an important issue, so no attempts of parallelizing or blocking the LBM implementation were carried out and hence no comparison is done. The figures presented in the following are therefore of interest in terms of performance relations rather than absolute values.
6.1.1 Performance Impact of the Smagorinsky Turbulence correction In what way the runtime and performance of the collide-stream step is influenced by activating the Smagorinsky turbulence correction is the first question we want to investigate. To this end, the well-known lid-driven cavity setup, where fluid in a closed cavity is set in motion by a continuous movement of the lid, was simulated with domain sizes of 203 up to 1203 . Figure 6.1(a) shows curves for the runtime of the collide-stream step and the full time step including boundary calculations for the Smagorinsky subgrid model turned on and off. The curves drift apart considerably between the collision with and without the turbulence correction, whereas the boundary calculations play almost no role in terms of computation time. Measuring the performance in millions of lattice cell updates per second (MLUP/s) reveals a significantly higher computational effort for the Smagorinsky-enhanced collision resulting in a performance penalty of almost 40% (see Figure 6.1(b)). This is mostly due to the evaluation of two square roots in the calculation of the local stress tensor, as illustrated in Equation (2.12).
6.1.2 Obstacle Boundary Conditions Compared Another aspect worth evaluating is the computational complexity involved in obstacle boundary calculations. As detailed in section 2.4, two different kinds were implemented: Simple cuboid shaped obstacles translating to no-slip boundaries, and spheres with curved boundaries that can optionally be moving. For a comparison, spheres with a radius between 5 and 50 lattice units were placed in the center of the 1203 lid-driven cavity setup from above as obstacle in
35
6. Performance Aspects
1600
2.5 Smagorinsky on, complete Smagorinsky on, collide-stream Smagorinsky off, complete Smagorinsky off, collide-stream
1400
2 1200
1.5 MLUP/s
Runtime [ms]
1000
800
1
600
400 0.5 Smagorinsky off, all cells Smagorinsky off, fluid cells Smagorinsky on, all cells Smagorinsky on, fluid cells
200
0
0 20
40
60 80 Domain size
100
(a) Runtime of a single LBM time step
120
20
40
60 80 Domain size
100
(b) Performance of the LBM implementation
Figure 6.1: LBM with and without Smagorinsky turbulence correction
(a) Staircase approximation...
(b) ...blended with the correct spherical shape
Figure 6.2: Curved boundary obstacle for a sphere of radius 15
36
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
120
6. Performance Aspects
120 moving boundary curved boundary staircase approximation
staircase approximation curved boundary moving boundary
7
100 6
5 MLUP/s
Runtime [ms]
80
60
4
3 40 2 20 1
0
0 0
5000 10000 15000 20000 25000 30000 35000 40000 Obstacle boundary cells
(a) Runtime of the obstacle boundary calculations
0
5000 10000 15000 20000 25000 30000 35000 40000 Obstacle boundary cells
(b) Performance of the obstacle boundary calculations
Figure 6.3: Performance of different boundary conditions for obstacles
staircase approximation and with curved boundary both stationary and moving with constant velocity. Figure 6.2(a) gives an idea of the staircase approximation of an obstacle of radius 15 that is blended with a sphere of the same radius to illustrate the approximation error (see Figure 6.2(b)). The results given in Figure 6.3 show that the curved boundary conditions are still comparatively computationally cheap, involving around double the number of computations of a no-slip boundary calculation. In contrast to that, using moving curved boundary obstacles has a considerable impact on performance, such that the cell update rate drops well below that of the collide-stream step. What causes this huge difference is the requirement to re-calculate the lattice link intersections with the obstacle surface in every time step, whereas for the stationary sphere this is done only once during the LBM setup phase. The computational effort scales with the number of cells inside the obstacle, that is cubic in the obstacle radius. In the other two cases it is only with the number of obstacle boundary cells, thus quadratic in the radius.
6.2 Particles and Rendering When looking at the performance of the particle system and the visualization, it is especially interesting to see what the individual components contribute to the overall computations of a full time step. In this way, parameters can be tuned to have the components interact in a way to get decent visual results in a reasonable amount of time. Keep in mind, that the set goal is to have visualization in real-time so that there is a hard upper bound for the runtime of a single time step. If the simulation is supposed to run at least at 20 frames per second, the total computing time may not exceed 50ms per time step. Firstly, let us look at the particle update and the visualization step in isolation. Figure 6.4 shows a comparison of the runtimes of the LBM time step with a grid size of 303 and 603 , the
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
37
6. Performance Aspects 1200 Rendering 2 sprites Update 2 sprites Rendering 1 sprite Update 1 sprite Update no sprites LBM 603 lattice LBM 303 lattice
1000
Runtime [ms]
800
600
400
200
0 0
500
1000
1500
2000 2500 3000 Number of particles
3500
4000
4500
5000
Figure 6.4: Computing time comparison of LBM, particle update and rendering
particle update step for no, one and two sprites per particle and the rendering for the latter two cases over the particle number. The LBM computations are completely independent of the particle system and show the expected constant computing times. On the other hand, particle update and rendering are not aware of the Lattice-Boltzmann voxel grid at all and thus their runtime is not dependent on the lattice dimensions. Instead they are directly related to the number of particles present in the simulation and the number of sprites representing each of them. The graph shows a quadratic dependence for the update time that can be explained by the necessary temperature calculation using Equation (4.2) that has a complexity of O(n2 ) as every particle interacts with each other particle. Due to the position, color, and size update for the sprites also done in this time step, there is an additional scaling with the number of sprites per particle. As expected, the rendering time shows a linear dependence on the total number of sprites to draw, the curves thus scale linearly with the sprites per particle. From Figure 6.4 one can further extract how the runtimes of the individual components compare to each other. An LBM time step for 303 cells is outstripped by the particle update in terms of computing time at a particle count of 1200, no matter if zero, one, or two sprites per particle are rendered and plays an increasingly insignificant role for high particle counts. This happens with rendering time for the same particle number for one sprite, whereas for two sprites per particle the break-even is already seen for a particle number of 900. In comparison the 603 cell LBM computations are by a factor of 8 more computationally expensive, breaking even with the “pure” particle update step at 3500, and at 3200 and 3000 particles with one and two sprites attached, respectively. The rendering times always stay below this bound for the particle counts under consideration. An attempt to get a better visualization of these computing time relations is made with Figures
38
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
6. Performance Aspects
900
100 Particle update LBM Rendering Particle emission
800
80 % of computation time
700
Runtime [ms]
600 500 400
60
40
300 20 200 100
0 0
0 0
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles Rendering Particle emission
(a) Runtimes summed up for one time step
Particle update LBM
(b) Runtimes set in relation to each other
Figure 6.5: Runtimes of a full simulation time step (1 sprite per particle)
1400
100 Particle update LBM Rendering Particle emission
1200
80 % of computation time
Runtime [ms]
1000
800
600
400
60
40
20
200 0 0 0 0
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles
(a) Runtimes summed up for one time step
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles Rendering Particle emission
Particle update LBM
(b) Runtimes set in relation to each other
Figure 6.6: Runtimes of a full simulation time step (2 sprites per particle)
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
39
6. Performance Aspects
1400
100 Particle update LBM Rendering Particle emission
1200
80 % of computation time
Runtime [ms]
1000
800
600
400
60
40
20
200 0 0 0 0
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles Rendering Particle emission
(a) Runtimes summed up for one time step
Particle update LBM
(b) Runtimes set in relation to each other
Figure 6.7: Runtimes of a full simulation time step (4 sprites per particle)
2500
100 Particle update LBM Rendering Particle emission 80 % of computation time
Runtime [ms]
2000
1500
1000
60
40
20 500 0 0 0 0
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles
(a) Runtimes summed up for one time step
500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Number of particles Rendering Particle emission
Particle update LBM
(b) Runtimes set in relation to each other
Figure 6.8: Runtimes of a full simulation time step (8 sprites per particle)
40
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
6. Performance Aspects 120 Dynamic lighting (8 Objects) Dynamic lighting (4 Objects) Dynamic lighting (2 Objects) Dynamic lighting (1 Object) No dynamic lighting
100
Rendering time [ms]
80
60
40
20
0 0
500
1000
1500
2000
2500 3000 Number of sprites
3500
4000
4500
5000
Figure 6.9: Rendering time comparison for dynamic lighting turned on and off
6.5, 6.6, 6.7 and 6.8. These four pairs of graphs show the composition of the total runtime of a simulation time step and the contributions to it by the four substeps weighted in percent, once more plotted against the total particle count. Figures were measured for a sprite number of one, two, four, and eight per particle and the emission of particles was also taken into consideration here. Though the latter two cases of four and eight sprites were left out in Figure 6.4 for sake of legibility, they are given here for completeness. In terms of Lattice-Boltzmann computations, only the case of 303 cells is considered. Not surprisingly, the graphs illustrate what was already extracted from Figure 6.4 above. The LBM computations manifest as a constantly thick layer in the runtime graphs. While making up for the lion’s share of computing time for low particle numbers, they very rapidly lose in significance for high particle counts. Exactly contrary behavior can be seen from the particle update that clearly dominates the overall runtime for higher particle numbers. An interesting role in between plays the rendering, steadily increasing in computational effort with an increasing number of sprites and having the big share somewhere in the low to center span, where the peak is much higher for more sprites per particle. Almost of no importance when it comes to computing time and consequently indiscernible in the graph is the particle emission, that only for the smallest particle counts has a noticeable share of overall runtime.
6.3 Dynamic Lighting All measurements for the visualization so far have been performed with dynamic lighting disabled to emphasize the dependencies on particle and sprite numbers. Enabling dynamic lighting
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
41
6. Performance Aspects attaches a point light source to every display primitive that is moving with the primitive. The resulting high number of light sources is supposed to have a significant influence on the rendering time. Figure 6.9 compares rendering times with static lighting to those with dynamic lighting for a varying number of illuminated objects. The graph shows a linear dependence on the number of sprites as expected, with a penalty of about 35% for dynamic lighting with one illuminated object over static lighting. For two, four and eight illuminated objects, the curves have a constant offset from the single object case proportional to the object number. This is due to the additional computations required for calculating the illumination of these surfaces, proportional to the number of illuminated triangles but independent of the number of light sources. While the curves are almost perfect straight lines apart from outliers at single points up to a sprite count of 3200, all of them show serious fluctuation above this number. It is hard to guess what exactly is the cause for this behavior, but it is perfectly reproducible. Most probably it is due to a hardware limitation of the video card. Note, that those fluctuations are also present in the previous graphs, but not noticeable due to the different scaling.
42
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
7 Examples And Results Visual results for selected example setups are presented in this chapter. Additionally, the necessary description of a scene represented by its parameter file is discussed.
7.1 The Scene Description The simulation framework developed in the previous chapters needs to be provided with a description of the scene to simulate as input. Targeting a very flexible yet powerful specification of the required input data, a parameter file based approach was chosen. All components are highly configurable, what gives the user maximum control of the simulation without the need to change the implementation and recompile. In order to handle a large number of possible options, the parameter file is hierarchically organized in blocks, grouping parameters affecting the same component of the simulation logically together. Where necessary, blocks can be nested to further increase flexibility. This structure was inspired by the configuration files for waLBerla, the comprehensive Lattice-Boltzmann solver developed at the Chair for System Simulation, presented in [FGD+ 07]. Following a well-defined syntax, the parameter file is parsed into a hierarchical tree data structure by a custom configuration file parser. Malformed configuration files are rejected with a precise indication where the syntax error was found. The parser itself makes no distinction of data type of the parameters. During the individual components’ setup phases, this data structure is queried for the required configuration parameters. A configuration file consits of the following blocks, some of them optional: domain (required by LBM and Particle System) Specifies the domain size in lattice cells. parameters (required by LBM and Particle System) Contains basic simulation parameters for both core components, like the number of time steps to simulate. vtk (optional for LBM) If present, VTK output of the LBM velocity, density, and flag field is written to a series of files with the specified basename. boundaries (required by LBM) Specifies the boundary conditions. Contains the subblocks top, bottom, left, right, front, and back for the individual sides of the domain cuboid that in turn contain subblocks for the different kinds of boundary conditions noslip, velocity, inflow, outflow, and pressure. Each of those may appear multiple times, defining a rectangular boundary patch, where the missing third coordinate is automatically set according to the surrounding superblock. These patches may not overlap and regions not covered default to no-slip. obstacles (optional for LBM and Particle System) May contain any number of the subblocks cuboid_stationary, sphere_stationary, and sphere_moving, each defining an obstacle of the given type by size, location, and for the last kind velocity.
43
7. Examples And Results
(a) 1000 particles, 1000 sprites
(b) 800 particles, 1600 sprites
(c) 500 particles, 2000 sprites
(d) 300 particles, 2400 sprites
Figure 7.1: Simulation after 100 time steps for different numbers of sprites displayed
particles (required by Particle System) Holds the parameters specific to the particle system and the subblocks defining the emitters. The emitter parameters are specified according to Section 4.3.4. irrlicht (optional) If present, the Irrlicht OpenGL visualization is enabled with the specified parameters. This block also contains subblocks defining the fire textures and optional static meshes or planes to be inserted into the scene.
7.2 Example Setups and Visual Results In this section, results of simulation runs are presented in form of screenshots.
7.2.1 Influence of Varying Sprite Number per Particle To begin, we want to pick up the thought from Section 6.2 on the maximum number of sprites that are possible in order to still sustain an interactive 20 frames per second. For this time constraint of 50ms per time step, a maximum particle number of 1000, 800, 500, and 300 was measured on the test system for 1, 2, 4, and 8 sprites per particle. A visual comparison of a campfire with the resulting total sprite counts of 1000, 1600, 2000, and 2400 can be seen in Figure 7.1. Obviously the fire appears slightly more dense from (a) to (d). In cases where this is intended, increasing the number of sprites per particle results in a performance benefit. There
44
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
7. Examples And Results
Figure 7.2: A soccer ball shot through a campfire with and without dynamic lighting
is a caveat however, in that the temperature calculations are solely based on the particles, thus varying their number affects the temperature distribution and leads to different results.
7.2.2 Dynamic Lighting A far more obvious visual difference makes the activation and deactivation of dynamic lighting. Figure 7.2 shows a scene, where a soccer ball is shot through a campfire. Dynamic lighting creates a very different visual quality, colors appear bright where those of the constantly lit scene seem rather dull in comparison. The result looks much more realistic and convincing so that for the remaining scenes to show, it will always be enabled.
7.2.3 Selected Example Scenes To convey an impression what kinds of simulations are possible with the framework, a selection of example scenes is presented in this subsection. The first one is a campfire blown over by a strong wind from one side (see Figure 7.3). An inflow boundary patch in the otherwise no-slip bottom of the domain creates the advecting flow for the emission source, one of the sides is set to inflow to model the wind and the remainder is an outflow region, where the flow can leave the domain. The wood and stones of the campfire are inserted as a static mesh that does not interact with the flow. Furthermore, a plane pasted with a grass texture represents the ground. An extension of the scenario used in Section 7.2.2 to demonstrate the effect of dynamic lighting can be seen in Figures 7.4 and 7.5: Instead of a single soccer ball, two and three soccer balls are shot through the fire, respectively. They are shot in from different corners such that they pass through the fire one after another. As the screenshots show, the balls suppress the air when crossing the fire, or rather the particles in the simulation, and drag them behind a little, leaving a small particle gap afterwards. The fire is advected by the same inflow as in the previous example, but this time all but the bottom plane is set to outflow. A teapot placed on the campfire as example of a resting obstacle can be seen in Figure 7.6. The teapot itself is a static mesh just like the logs and stones of the campfire and cannot interact with the flow. Therefore the shape of the teapot was approximated by a spherical obstacle of
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
45
7. Examples And Results
Figure 7.3: A campfire with strong wind from the side
Figure 7.4: Two soccer balls shot through a campfire from different sides
46
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
7. Examples And Results
Figure 7.5: Three soccer balls shot through a campfire from different sides
Figure 7.6: A teapot placed on a campfire
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
47
7. Examples And Results
Figure 7.7: A teapot placed on a stove inside a room
Figure 7.8: A fire calmly burning in a fireplace
appropriate radius. Inflow and outflow were defined the same way as in the two previous setups. The flames obviously spread a lot broader here, as they are blocked in their natural upward motion. However, they seem not to be able to pass by the teapot and ascend. The same teapot placed on a stove in a small room is depicted in Figure 7.7. In this scenario smoke can only exit through a chimney below the ceiling. The teapot is modeled the same way as in the previous scene and similarly the flames are kept below the pot and cannot pass by the sides. Figure 7.8 shows another indoor scene, a fire calmly burning in a fireplace, where again the airflow is channeled by the chimney, that is the only way out. There is a bit of convection into the room though, recognizable by the smoke particles in the right image. In both scenarios the whole domain boundary is a fixed wall, apart from an inlet patch on the floor and an outlet in the ceiling, where the chimney ends. The brickwork of stove and chimney in Figure 7.7 is also modelled as no-slip boundary, just like the coving of the fireplace that is not visible in Figure 7.8.
7.2.4 Evaluation of the Results The presented screenshots demonstrate that the visualization is capable of creating a convincing depiction of fire based on the data coming from the particle system and the underlying LBM. All this is far from being photo-realistic, but is delivered in real-time and with interactive frame rates, while it is possible to freely navigate through the scene. The soccer ball scenarios demonstrate the interaction with the environment in a physically sound way, whereas the teapot scenarios exhibit limitations of the underlying model.
48
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
8 Conclusion Simulation of freely fed fire advected by a Lattice-Boltzmann calculated flow field was successfully demonstrated in this thesis. To this end, an LBM fluid solver was developed and extended by a Smagorinsky subgrid model to cope with turbulent flows, and the handling of various kinds of boundary conditions, including moving curved boundaries of obstacles. As core component of the fire simulation, a particle system based on the model of Wei et al. [WLMK02] was implemented. It features a linear temperature model, can handle fire as well as smoke, and was extended by provision for buoyancy forces that are combined with the LBM-computed velocity field to determine the particle movements. Integration of the Irrlicht 3D engine adds visualization in real-time, where textured billboards are used to represent the particles on the screen. Their coloring is performed according to the current temperature using a black body color table lookup. Furthermore, a file parser was developed to extract parameters from configuration files containing a scene description in a way they can be retrieved in the setup phase of the simulation. The LBM proves to be an apt tool for handling environmental influences like wind fields and obstacles in the flow, delivering high performance while keeping the implementation fairly simple. Sufficiently accurate results can already be achieved on rather coarse grids. Harnessing the possibilities of the versatile configuration approach, complex scenarios for simulation can be described easily. The presented performance results demonstrate that the set goal of interactive frame rates can be reached on modern hardware even for complex scenarios, as the visualization allows the number of displayed particles to be kept quite low without losing much detail. Thus it is possible to move around in the scene in real-time while the simulation is running. There still remain many open points to work on, however. As the implementation was not explicitly targeted on performance, there is a high potential for optimization left. The LBM solver could be extended for instance by parallelization, blocking, and grid compression techniques. Adaptive coarsening or grid refinement could also prove worth investigating in order to simulate the critical regions around obstacle boundaries in more detail while saving clock cycles in areas of homogeneous flow. A very promising way to go lies in porting the Lattice-Boltzmann computations to the GPU using a GPGPU framework such as CUDA. Impressive results harnessing state-of-the-art GPU compute power for the LBM have been given in [Hab08, T¨ol08]. Looking at the particle system, the quadratic complexity of the temperature calculations is a weak point. Limiting the heat exchange only to particles nearby by introducing a cutoff radius or space partitioning could bring this problem to a linear complexity class. Apart from performance optimization, a number of functional extension are conceivable. On top of the list is the possibility for the flames to spread, which requires tracking the fire front as Zhao et al. have done in [ZWF+ 03]. The catching on fire of flammable objects could be easily integrated in such a model as well. For modeling more realistic scenes, insertion of arbitrary polygonal meshes as obstacles, possibly even moving, into the voxel lattice would be a nice-tohave feature, especially in combination with spreading of fire fronts. A point so far not solved satisfactory according to [Suc01, Chapter 14] is a coupling of the temperature model back into the LBM. It could nevertheless be worth evaluating current thermal LBM model to see whether or not they provide an alternative.
49
8. Conclusion For the visualization part, volume rendering techniques like blobs or textured splats as demonstrated in [WLMK02] could be employed to increase visual quality. Staying with the chosen approach, a sound way for alternating the textures of the display primitives could create visually more pleasing results, as could a proper fading of the smoke particles. Incorporating further visual effects like heat-based refraction blurring objects seen through the fire or a more realistic illumination are also conceivable. Finally, the parameterization could be made more intuitive by allowing real-world quantities to be specified instead of the somewhat abstract lattice quantities where appropriate. The high number of parameters required could be alleviated by providing more default values and combining given parameters to determine the values of others where possible. More interaction and fine-grained control of the simulation could be attained by providing the user with an interface to change certain parameters at runtime with immediate effect.
50
Simulation and Visualization of Fire with the Lattice-Boltzmann Method
Bibliography [AMHH08] T. Akenine-M¨oller, E. Haines, and N. Hoffman. Real-Time Rendering 3rd Edition. A. K. Peters, Ltd., Natick, MA, USA, 2008. [Don04]
S. Donath. On Optimized Implementations of the Lattice Boltzmann Method on Contemporary Architectures. Bachelor’s Thesis, Aug 2004. Betr. Wellein, Hager, Zeiser, F. Deserno.
[FGD+ 07]
C. Feichtinger, J. G¨otz, S. Donath, K. Iglberger, and U. R¨ ude. Concepts of waLBerla Prototype 0.1. Technical Report 07-10, 2007.
[Geb09]
N. Gebhardt. Irrlicht engine - a free open source 3d engine. website, April 2009.
[Hab06]
J. Habich. Improving computational efficiency of Lattice Boltzmann methods on complex geometries. Bachelor’s Thesis, Dec 2006. Betr. Hager, Wellein, Zeiser (RRZE), U. R¨ ude.
[Hab08]
J. Habich. Performance Evaluation of Numeric Compute Kernels on NVIDIA GPUs. Master’s thesis, IMMD10, Jul 2008.
[HSCD96]
S. Hou, J. Sterling, S. Chen, and G. D. Doolen. A lattice boltzmann subgrid model for high reynolds number flows. Fields Institute Communications, 6:151–166, Jan 1996.
[Igl03]
K. Iglberger. Performance Analysis and Optimization of the Lattice Boltzmann Method in 3D. Studienarbeit, Sep 2003. Tutor M. Kowarschik.
[Igl05]
K. Iglberger. Lattice-Boltzmann Simulation of Flow around moving Particles. Master’s thesis, Jun 2005. Betr. N. Th¨ urey.
[KCR00]
S. A. King, R. A. Crawfis, and W. Reid. Fast volume rendering and animation of amorphous phenomena. In In Proc. International Workshop on Volume Graphics, pages 229–242, 2000.
[KY08]
P. H. Kao and R. J. Yang. An investigation into curved and moving boundary treatments in the lattice Boltzmann method. Journal of Computational Physics, 227(11):5671–5690, 2008.
[Nas01]
K. Nassau. The Physics and Chemistry of Color: The Fifteen Causes of Color, 2nd Edition. Wiley, July 2001.
[NM99]
T. E. Nielsen and S. T. Madsen. Modelling, animation, and visualization of fire. Master’s thesis, University of Copenhagen, Denmark, April 1999.
51
Bibliography [Per85]
K. Perlin. An image synthesizer. In B. A. Barsky, editor, Computer Graphics (SIGGRAPH ’85 Proceedings), volume 19, pages 287–296, July 1985.
[PH89]
K. Perlin and E. M. Hoffert. Hypertexture. In Jeffrey Lane, editor, Computer Graphics (SIGGRAPH ’89 Proceedings), volume 23, pages 253–262, July 1989.
[QdL92]
Y. H. Qian, D. d’Humieres, and P. Lallemand. Lattice BGK model for Navier-Stokes equation. Europhysics letters(Print), 17(6):479–484, 1992.
[Ree83]
W. T. Reeves. Particle systems – a technique for modeling a class of fuzzy objects. ACM Trans. Graphics, 2:91–108, April 1983.
[Suc01]
S. Succi. The Lattice Boltzmann Equation for Fluid Dynamics and Beyond. Oxford University Press, Oxford, 2001.
[Th¨ u07]
N. Th¨ urey. Physically based Animation of Free Surface Flows with the Lattice Boltzmann Method. PhD thesis, FAU Erlangen, 2007.
[T¨ol08]
J. T¨olke. Implementation of a Lattice Boltzmann kernel using the Compute Unified Device Architecture developed by nVIDIA. Computing and Visualization in Science, pages 1–11, 2008.
[WG00]
D. A. Wolf-Gladrow. Lattice-Gas, Cellular Automata and Lattice Boltzmann Models, An Introduction. Lecture Notes in Mathematics. Springer, Heidelberg, Berlin, 2000.
[WLMK02] X. Wei, W. Li, K. Mueller, and A. Kaufman. Simulating fire with texture splats. In IEEE Visualization, pages 227–234, 2002. [WLMK04] X. Wei, W. Li, K. Mueller, and A. Kaufman. The lattice-boltzmann method for simulating gaseous phenomena. IEEE Transactions on Visualization and Computer Graphics, 10(2):164–176, 2004. [WZF+ 03] X. Wei, Y. Zhao, Z. Fan, W. Li, S. Yoakum-Stover, and A. Kaufman. Blowing in the wind. In SCA ’03: Proceedings of the 2003 ACM SIGGRAPH/Eurographics symposium on Computer animation, pages 75–85, Aire-la-Ville, Switzerland, Switzerland, 2003. Eurographics Association. [ZWF+ 03] Y. Zhao, X. Wei, Z. Fan, A. Kaufman, and H. Qin. Voxels on fire. In VIS ’03: Proceedings of the 14th IEEE Visualization 2003 (VIS’03), page 36, Washington, DC, USA, 2003. IEEE Computer Society.
52
Simulation and Visualization of Fire with the Lattice-Boltzmann Method