Full text
Universidade do Minho Escola de Engenharia Departamento de Informática Nuno Filipe Maranhão dos Reis Space Colonization for the Procedural Generation of Lightning March 2022
Universidade do Minho Escola de Engenharia Departamento de Informática Nuno Filipe Maranhão dos Reis Space Colonization for the Procedural Generation of Lightning Master dissertation Integrated Master’s in Informatics Engineering Dissertation supervised by António José Borba Ramires Fernandes March 2022
COPYRIGHT AND TERMS OF USE FOR THIRD PARTY WORK This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. LICENSE GRANTED TO USERS OF THIS WORK: CC BY https://creativecommons.org/licenses/by/4.0/
ACKNOWLEDGEMENTS I would like to formally thank every member of faculty and staff that has played any part, however small, in my academic journey to this point. No matter how minute their contribution, I would not be here were it not for them. I also thank the scientific community and all those whose research, old and new, has contributed in any way, however small, to the development and formulation of this paper. I especially extend my gratitude to professor António José Borba Ramires Fernandes for supervising my work and being an invaluable guide throughout the fourth and fifth years of this course. On a more personal level, I’d like to thank my parents, Duarte Manuel Carvalho Gomes Grácio dos Reis and Sónia Maria Feiteira Maranhão dos Reis, as well as all of my family, especially my brother Ricardo Miguel Maranhão dos Reis, for their unquantifiable emotional and financial support both of which I’m extremely thankful for and forever indebted to. I also extend my deepest gratitude to Dr. Mariana Pequeno and Dr. Isabel Martins for their help during a terribly difficult thunderstorm in my life. Without their help and my parents’ watchful eyes and support, I would have never made it to this point. To those who have been partners in work throughout the many projects in this course, to those who have been friends, to those who have come and went, to my peers and all those not mentioned by name in this brief note of gratitude, I thank you for having been at my side, however small the period of time. a
STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. b
ABSTRACT The procedural generation of geometry within the space of computer graphics has been a topic of study for quite some time, benefiting from a more unpredictable brand of randomness. Similarly, the exploration of lighting as a phenomenon within virtual space has been a field of study of comparable age. Despite its age and early adoption, there is a surprising lack of research in emulating the phenomenon of lighting past its interactions with the world. Most implementations of procedurally generated lightning within video games are based on randomized data trees. When part of the skybox, 2D meshes or textures are randomly selected from a pre-made pool. There are, however, methods based entirely on the dielectric breakdown model, using approximations to solve a Laplacian equation. This dissertation aims to present an alternative approach to the randomized and procedural generation of lightning bolts based on the Space Colonization algorithm. While the algorithm was first conceived for use in botanical applications, modeling the growth of biological structures, the similarities between the results produced by the dielectric breakdown model and botanic modeling algorithms coupled with the visual likeness of a lightning bolt and certain trees, made for solid groundwork upon which to establish this unique approach. As such, this work largely aims to be a first step into this particular realm, showing Space Colonization as a suitable algorithm for this specific purpose. That being said, a large portion of time was spent iterating, modifying and experimenting with ideas that were either discarded or adapted, an effort primarily dedicated towards controlling and stifling the possible growth of branches in ways beyond the reduction of attractors. The original algorithm was altered, focus put especially on the creation of a singular channel at a time, mixing discoveries from previous research with the work done on manipulating Space Colonization. Instead of the venation patterns observed with the original work, the stifling of any growth means that each node has a chance, when created, of sprouting a branch and each branch is, in turn, a different, modified instance of the same underlying concept providing an additional level of control. Effort was equally placed on showcasing different properties inherent to a lightning strike, such as its iterative construction when descending from its origin. In the rendering section, along with recreating the bloom and glow effect seen in previous works, effort was put into recreating the strobing observed in capturing slow-motion footage of lightning bolts with special detail given to this. In addition, parameters were joined with a waypoint system to allow for a great degree of freedom when generating new bolts. KEYWORDS animation, lightning, physics, electric breakdown, patterns, rendering, real-time, computer graphics, physically plausible, space colonization. c
RESUMO A geração iterativa de geometria no contexto de computação gráfica é um tópico de estudo à já algum tempo apesar de usado em apenas contextos específicos, um ramo que benefícia de um tipo de aleatoriedade imprevisível. Similarmente, a exploração de relâmpagos como um fenómeno em espaço virtual é uma faceta de idade comparável. Apesar disto, o foco quando tratando relâmpagos tem caído marioritariamente nos seus efeitos após impacto. Estudos têm sido conduzidos no âmbito de mitigar o dano causado por estes em fuselagem de aeronaves e analizar o impacto de trovoada em estruturas críticas. No entanto, existe uma falta de investigação sobre a emulação deste fenómeno barra as suas interações com o mundo. A maioria das implementações iterativas em video jogos são baseadas em árvores de dados. Quando fazem parte do cenário, são marioritariamente meshes ou texturas 2D selecionas aleatoriamente de um conjunto. Existem, no entanto, métodos baseados num modelo de colapso elétrico usando apróximações a uma equação de Laplace. Esta dissertação tem como foco apresentar uma alternativa para a geração aleatória e iterativa de relâmpagos baseada no algoritmo de Space Colonization. Apesar deste algoritmo ter sido concebido para uso botânico, modelando o crescimento de estruturas biológicas, as similaridades entre os resultados obtidos pelo modelo de colapso elétrico e estes algoritmos de modelagem, quando considerados com a semelhança entre certos relâmpagos e árvores, constroem uma fundação sólida para o tópico. Neste âmbito, este trabalho é um primeiro passo que tem o intuito de mostrar a capacidade do algoritmo de Space Colonization em simular relâmpagos. Dito isto, uma grande porção do tempo de desenvolvimento dobrou-se sobre a iteração modificação e experimentação de ideias que foram discardadas ou adaptadas, um esforço primariamente dedicado em controlar o crescimento de ramos sem reduzir o número de atratores. O algoritmo original foi alterado, focando especialmente na criação de um único canal e fazendo uso de conhecimento prévio, oriundo de trabalho e investigação feita sobre manipulação de Space Colonization. Em vez de padrões de venação, observados no trabalho original, o impedimento de qualquer crescimento significa que cada nodo tem uma probabilidade, quando criado, de dar origem a um ramo e que cada ramo é uma instância diferente e modificada do mesmo conceito, algo que cria um nível de controlo mais profundo. Um esforço extra foi, também, realizado com o intuito de mostrar todas as propriedades diferentes, inerentes a um relâmpago tal como a construção iterativa durante a sua travessia. Na parte de renderização, foram recriados efeitos de brilho e bloom vistos em trabalhos prévios. Foi também dada especial atenção à recriação do efeito estroboscópico observado durante a análise de imagens em câmera lenta, algo que se tornou no foco principal desta parte. Adicionalmente, a adição de parâmetros foi conjugada com um sistema de pontos que dá um grau superior de liberdade ao utilizador. d
e PA L AV R A S -C H AV E animação, trovoada, relampagos, física, quebra dielétrica, padrões, renderização, tempo real, computação gráfica, fisicamente plausível, space colonization.
CONTENTS Contents 1INTRODUCTION 1 1.1 Lightning 1 1.2 Motivations and Goal 3 1.3 Structure of the Dissertation 4 2S TAT E O F T H E A R T 6 2.1 Visual Simulation of Lightning, Reed and Wyvill, 1994 7 2.2 Efficient rendering of lightning taking into account scattering, Dobashi et al., 2001 12 2.3 Physically Based Animation and Rendering of Lightning, Kim and Lin, 2004 14 2.4 Fast Simulation of Lightning for 3D Games, Bryan et al., 2005 17 2.5 Fast Animation of Lightning Using an Adaptive Mesh, Kim and Lin, 2007 19 2.5.1 LumosQuad 20 2.6 Physically Inspired, Interactive Lightning Generation, Yun et al, 2017 22 2.7 Space Colonization - Runions et al. 2005 & 2007 26 3SPACE COLONIZATION FOR LIGHTNING SIMULATION 29 3.1 Reproducing the Main Channel 31 3.2 Introducing Natural and User-Defined Branches 35 4RENDERING 41 4.1 Ordering Nodes and Preparing for Rendering 43 4.2 Building the Bolt 47 4.3 Simulating the Strobing Effect of a Lightning Bolt 51 5RESULTS 56 5.1 Explaining the Parameters and their Effects 57 5.2 Recreating Real Lightning 64 6CONCLUSION 69 6.1 Future Work 70
1.2. Motivations and Goal 3 Figure 2: A complete illustration of a lightning bolt’s lifespan. Source: Bermudez Arboleda (2003) 1.2 M OT I VAT I O N S A N D G O A L Computer graphics programs and simulation algorithms have many applications in the world of Engineering and Science. From helping in the understanding of phenomenons far too dangerous and/or rare to study, to simply recreating them for the purposes of education and entertainment, there are plenty of possible scenarios in which new ground can be tread. Among these is a clear divide between techniques which model physical phenomena
1.3. Structure of the Dissertation 4 via objective, quantifiable accuracy and those who forego it in favor of simpler algorithms that deliver an equally satisfactory result. The aren’t many more scenarios where this divide can be clearly seen than in the simulation of lightning. For better or worse, the driving influence in the realm of simulations that involve this mythical phenomena are the aviation and infrastructure maintenance sectors. However, for their purposes, modeling the shape of the bolt or how it propagates through the atmosphere is beyond the scope of what’s necessary. Their concern is to identify the zones that would easily attract lightning and to reinforce the underlying structure as to be able to not only resist the damage but maintain the safety of everyone within it. As such, many of the efforts to accurately depict lightning have been borne from the movie industry, the video game industry or computer scientists partnering with physics researchers in an attempt to further understand this ancient yet mysterious force. This is where the divide is made all the more clearer. Within the movie industry, it isn’t uncommon for lightning to be manually created either using traditional means, such as paper drawings, or computer software. These are often later added into a scene via computer generated imagery or video composition. Other possible tricks involve superimposing or composing video and pictures taken beforehand onto a scene that requires it. Similarly, when simulating lightning within video games, the two most common approaches rely on randomized data trees and pre-defined models when said lighting is part of the geometry. However, should it be visible only in the skybox of a scene, it is most often simply rendered using 2D meshes, textures or sprites randomly selected from a pool. When it comes to scholarly articles, however, there have been considerably few attempts at reproducing the phenomenon itself within a virtual space. The attempts that exist are, for the most part, more than a decade old and represent a historical step within this specific sphere. Most of all, however, nearly all of them attempt to model lightning from a purely physically plausible or accurate standpoint, using whatever information was available at the time and incorporating the contemporary knowledge around lightning. In contrast, this dissertation’s attention shifted towards a more organic view of lightning as an unpredictable phenomenon that grows step by step. Rather than emulate it using complex calculations and rigid physical models, a comparative approach seemed poised to deliver a suitably plausible replacement. Lightning and Trees share many commonalities, from the existence of a main channel and trunk, respectively, to the spreading of branches towards their goal. While trees seek to bathe in sunlight and grown branches in order to better reach it, increasing the amount of surface area exposed to it, lightning explores a myriad of pathways in an attempt to cancel its negative charge. By extending its feelers like a tree’s branches, it seeks a path of least resistance which it can use to nullify its charge. The goal of this dissertation is to attempt to present a tool capable of procedurally generating lightning using an algorithm inspired by organic designs and it is through these similarities with trees that this thesis hopes to introduce a first step in this specific topic. 1.3 S T RU C T U R E O F T H E D I S S E R TAT I O N Besides the current chapter, Chapter 2 will delve into the state of the art surrounding the simulation of lightning by presenting the most important articles in the field. Additionally, Section 2.7, the last section of said chapter
1.3. Structure of the Dissertation 5 will serve as an introduction into the history and intended use of the algorithm that was selected. Immediately after, Chapter 3 will explain the underlying idea and system by which this dissertation’s core algorithm functions in an effort to produce a visually appealing version of lightning. Specifically, Section 3.1 will outline the steps necessary for reproducing a lightning’s main channel while Section 3.2 serves as an analog for introducing branching patterns. The next chapter, Chapter 4, dives into the steps necessary to simulate the effects seen when a lightning bolt strikes. Section 4.1 serves as a bridge between the two chapters while Section 4.2 delves, in more detail, into how a lightning bolt can be constructed with Section 4.3 presenting ways in which certain effects can be simulated. Finally, a brief summary of user parameters and results achieved with these is show in Chapter 5 while Chapter 6 serves as a final word and reflection upon the work done with Section 6.1 presenting future hopes and work that can be done to further the dissertation’s premise.
2 S TAT E O F T H E A R T Throughout the years, Lightning Simulation has been an area of Computer Graphics with wavering interest. While there are many applications out there which study the behavior of lightning storms and their ensuing phenomena, they do so from an empirical standpoint, choosing to focus their lens on the damage such a destructive force may cause in human infrastructure, falling outside the realm of Computer Graphics. Of particular importance in these fields, is the heuristic simulation of lightning for aerospatial engineers whose labor is at particular risk of being struck by these discharges. However, lightning itself can be much more than a destructive influence. In 1994, Reed and Wyvill published their paper Reed and Wyvill (1994) and pioneered the simulation of lightning for its beauty and aesthetic, awesome impact rather than its destructive force. The presence of proper generated lighting, the authors go on to say in Reed and Wyvill (1994), can dramatically change a scene adding layers to rather mundane storms and deeply immersing the user into the scenery and its unfolding storyboard. However, as niche and complex as it is, lightning simulation has become a field of computer graphics that, when compared to others, has gone woefully underappreciated. Due to this fact, most of the presented articles are more than a decade old and provide a form of time-chamber into the unique difficulties encountered at the time. One must keep in mind that the evolution of technology follows Moore’s law and, as such, technical and technological barriers from even five years ago, let alone a decade, are quite irrelevant. That being said, however, it is important to keep the constraints the authors encountered at the time of researching and writing as to better understand why some decisions were made in lieu of others. This chapter will be composed of two distinct parts. In the first, several different research papers done around the topic of Lightning Simulation in the field of Computer Graphics will be documented and summarized through chronological order. While the eldest of these was published nearly thirty years ago, the relevant precedent it set, combined with the scarcity of research conducted into this specific topic, make them just as pressing as the most recent. The second part will focus around the core algorithm developed for this dissertation, Space Colonization, and its inception. Used in the field of algorithmic botany, the algorithm treats competition for space as its driving force. Through this feature, which could be likened to the feeler’s search for the path of least resistance, and the likeness seen between trees and lightning bolts, this work wishes to explore the possibility of using this algorithm for the latter’s simulation. As a result, an historical overview of its original use and and understanding of its structure was necessary. 6
2.1. Visual Simulation of Lightning, Reed and Wyvill, 1994 7 2.1 VISUAL SIMULATION OF LIGHTNING,REED AND WYVILL, 1994 While there have been articles and other investigative works, centered around this field, published in the webspace by computer scientists, none has been quite as influential as the first. Published in 1994, Reed and Wyvill (1994) has become a piece of computer science history following many citations. K. Todd Reed and Brian Wyvill, first published their article on January 7, 1994 and, since then, nearly every scientific work on the topic has referred to their original methodology in one way or another, even if only as an inspiration or to lay out historical groundwork. In their original method, the authors described a simple particle system which simulates the stepped leader progression towards ground zero, that is, the physical location where the lightning bolt strikes. While not based on any physical conjecture or formula, the authors took into account the qualitative research brought on by the thorough and tiresome examination of dozens of images, ensuring that the final product would replicate the sight of a bolt of lighting as accurately as possible. In Figure 3,Reed and Wyvill (1994) identifies the four stages of lightning observed during their research. (a) represents the beginning formations of a lightning strike in which a stepped leader descends from a charged cloud as a stream of negatively charged particles searching for a way to discharge their energy. (b) shows the period in which the stepped leader, forming branches in an effort to locate the proper path, obtains enough proximity to the ground to form an upward, positive leader. Most times, this leader is imperceptible though there are cases where they may grow to a few meters in length. (c) is the exact period in which both streams connect, discharging its energy in a blinding flash. This process is seen as the strike itself, lasting only a brief period of time. This, in turn, starts the process outlined in (d) where a dart leader descends onto the ground, following the pre-established path, to discharge whatever capacitance is left within the cloud. Their system operates by a random set of rotations in which each stroke segment depends on the ending of the last. The amount by which each rotation was made was determined by conducting a series of observations parallel to research done by both the authors and physicists alike, resulting in discovering a mean of 16 degrees between each segment’s angles. This, in the author’s words, ensured congruity between all traces of the stroke and guarantees a quasi-linear shape. Notably, the method described uses a linear distribution to determine the length of each segment and, while they inaccurately describe the length of a segment as varying between one meter to one kilometer (US Department of Commerce,2018b), they do correctly surmise that smaller segments produce the most visually realistic results. Branching in this method is controlled by a simple probability function following a set of outlined properties. The authors mention that it makes use of the distance traveled to calculate the probability for branching occurrences, yet warn of erratic behavior and difficulty controlling the ensuing branches in a consistent fashion. For rendering, a model is formed using a skeleton, as seen in Figure 4 composed of elementary particles such as points, lines, polygons, circles and even splines tied together through a hierarchical link. This skeleton is then surrounded by a scalar field with decreasing values as distance to the skeleton increases. Alongside this, a ray-tracing model was built making use of ellipsoids to influence the scalar field. The nearest distance between each traced ray to each primitive ellipsoid is calculated and the shortest distance is passed to an equation, building a final shape following the zero contour. Finally, passing a blending function, shown in Figure 5, in conjunction
2.1. Visual Simulation of Lightning, Reed and Wyvill, 1994 8 Figure 3: Identifying the four stages of lightning. Source: Reed and Wyvill (1994) with the field, before the final drawing of the contour, allows the authors to shape the lightning accordingly and dictate how separate surfaces should blend together. This final product can be seen in Figure 6. The authors highlight the need for such a solution due to the limitations imposed by the technology available. The use of line-segments prevented the authors from treating strokes as geometric objects, rendering the available shading methods inappropriate due to the lack of a definable surface. Since then, however, many others have iterated upon this work. Notably, Glassner (2000) performed a second pass upon the branches to add a degree of "tortuosity" to the represented bolts, as seen in Figure 7, while Sosorbaram et al. (2001) made use of a model which has then become a staple in the simulation of lightning surges: The Dieletric Breakdown Model,orDBM for short. (Niemeyer et al.,1984). The latter’s result can be seen in Figure 8 A dielectric breakdown is a formation of electrically conducting regions in an insulating material when exposed to a strong electric field. Most notably, the branching, fractal patterns that form as a result of this breakdown exhibit properties that allow modeling via the use of a Laplacian growth algorithm.
2.1. Visual Simulation of Lightning, Reed and Wyvill, 1994 9 Figure 4: The skeleton produced by Reed and Wyvill (1994)’s algorithm. Source: Reed and Wyvill (1994) Figure 5: Reed and Wyvill (1994)’s use of bloom and Gaussian blur to simulate light. Source: Reed and Wyvill (1994)
2.1. Visual Simulation of Lightning, Reed and Wyvill, 1994 10 Figure 6: Reed and Wyvill (1994)’s final product. Source: Reed and Wyvill (1994) Figure 7: The result of Glassner (2000)’s second pass. Source: Glassner (2000)
2.1. Visual Simulation of Lightning, Reed and Wyvill, 1994 11 Figure 8: Sosorbaram et al. (2001)’s adaptation which made use of the Dieletric Breakdown Model (DBM). Source: Sosorbaram et al. (2001)
2.2. Efficient rendering of lightning taking into account scattering, Dobashi et al., 2001 12 2.2 EFFICIENT RENDERING OF LIGHTNING TAKING INTO ACCOUNT SCATTERING,DOBASHI ET A L ., 2001 In Dobashi et al. (2001), an efficient method for creating realistic images of scenes that include lightning is proposed. The article outlines the design of an algorithm that can create lightning by taking into account atmospheric scattering when clouds and other phenomena are illuminated by it, something that was notably lacking in Reed and Wyvill (1994). Moreover, they fully utilized the graphics processing capabilities available at the time to accelerate image generation. Much like the previous article, it is important to note that the logic behind the proposed method and its implementation are of both historical significance and interest when creating 3D applications that include the realistic rendering of lightning, serving as the basis upon which modern methods have improved upon. Notably, in Reed and Wyvill (1994), lightning and its glow were rendered by employing a heuristic approach. However, as previously stated, clouds were not taken into account and the modeled glow became entirely at odds with the physical representation of lightning as one of the primary mechanisms for its existence is its interaction with the surrounding atmosphere. Moreover, while there were a large number of research reports on the generation of images taking into account atmospheric scattering, Dobashi et al. (2001) stipulates that these algorithms were only fit for natural light sources such as sunlight, skylight and artificial spotlights, making them unsuitable for the rendering of lightning strokes which are characterized by large, irregular forms that lack a proper surface. The authors highlight the need for understanding that these methods often took dozens of minutes to create an image, prompting them to develop a technique that would render in a fraction of the time previously required. In Dobashi et al. (2001), the technique developed in Reed and Wyvill (1994) for the generation of lightning strokes is used, representing them as a set of line segments. The generated bolt is then displayed by a drawing function with its color dictated entirely by the user. In tandem, the intensity of the clouds illuminated by lightning, along with their corresponding scattering, are computed by generating point light sources along the line segments, as seen in Figure 9. The authors highlight an interesting problem: generating too many light sources proves incredibly costly on the algorithm while the use of too little renders them moot for their intended purpose. Due to the fact both clouds and atmospheric scattering are rendered by summing the contributions from each light source, a balance needs to be struck between the quality of the render and the speed at which it is rendered. To get around this fact, or at least to somewhat alleviate the problem’s nature, the density distribution of clouds is expressed as a collective rather than a singular entity. These distributions are defined on three-dimensional voxels that the authors dubbed ‘metaballs’. These metaballs are placed at the center of each voxel and given two values: the center density, calculated using the average density of each cloud present at that given voxel and effective radius as clouds are not perfectly spherical. To achieve illumination, a billboard method is used to lower computational requirements and accelerate rendering times. The authors note, however, that despite their best efforts, this approach remained computationally expensive with a cost that is proportional to both the number of metaballs and their associated light sources.
2.5. Fast Animation of Lightning Using an Adaptive Mesh, Kim and Lin, 2007 19 Figure 16: Final result. Source: Bryan (2005) 2.5 FAST ANIMATION OF LIGHTNING USING AN ADAPTIVE MESH,KIM AND LIN, 2007 Kim and Lin (2007), is the authors’ second take on the development of a fast lightning renderer. As stated before, DBM is an expensive model to compute so the authors propose modifications and the use of an adaptive mesh, to increase its computational speed. Notably, this approach is built upon a symmetric discretization of the Poisson Growth worked upon in their previous article. While their previous algorithm produced visually acceptable results, the authors considered the possible running time and memory footprint prohibitive when imported over to 3D models. They cite that, in practice, they’ve found that in order to obtain results where artifacts are not distracting, a grid of 2563 cells must be used. Furthermore, in order to run a preconditioned conjugate gradient, seven arrays of this size are necessary and, even if assuming single precision, the method already racked half a gigabyte of memory data. Increasing the grid resolution to 5123 bloated the footprint exponentially to 3.7GB . Even with an efficient implementation, the matrix could become so large that simulations began taking days. The authors note that, until 2004, solving a Poisson problem over an adaptive grid had the caveat of producing a non-symmetric matrix, rendering its use an impossibility for this specific purpose. However, Losasso et al. (2004) overcame this limitation, allowing the use of a more robust gradient. Armed with this innovation, the authors coupled the use of an adaptive grid with a balanced octree to greatly simplify the implementation of their solver, resulting in the ability to produce complex images such as Figure 17.
2.5. Fast Animation of Lightning Using an Adaptive Mesh, Kim and Lin, 2007 20 Figure 17: Lightning in a bottle. Source: Kim and Lin (2007) This balanced octree is an octree where, given any leaf node, the size of each neighboring node differs by, at most, a factor of two. The authors chose to enforce this property because it constrains the maximum number of neighbors of a leaf node to 24 (four neighbors at each of the six cube faces). This is necessary to bound the complexity of performing incomplete factorization, as a leaf node and its neighbors define a row in the Poisson matrix. As a final step to ensure this property, a full scan of the octree is made and any outliers are remedied appropriately. The authors make use of a modified incomplete Cholesky algorithm for the factorization process, reporting that, in modest quadtree simulations, the number of iterations required for convergence is identical to those required by the original Cholesky preconditioner and that, by using this discretization, they were able to report a speed up of over two orders of magnitude. Ideally, in their words, a grid cell within the simulation should correspond to a pixel on screen. However, such a resolution was impractical and a comparative result was achieved by introducing jittering in the simulation results. Results for this article can be seen in Figure 18 and Figure 19. 2.5.1 LumosQuad Based on the methods developed in Kim and Lin (2007), Theodore Kim and Ming Lin, authors of said article, developed the 2D Lightning Simulation program LumosQuad. The program works by using an image with a black background as a free canvas, serving as a neutral zone. By painting different areas of the image in different colors, one can influence the output simulation in certain ways.
2.5. Fast Animation of Lightning Using an Adaptive Mesh, Kim and Lin, 2007 21 Figure 18: High voltage between two electrodes. Source: Kim and Lin (2007) Figure 19: Results using an user input. Source: Kim and Lin (2007) •Green - Prohibits the growing of lightning cells within the colored zones. • White - Represents the end pixel. Should the Lightning branch hit this pixel, the simulation is stopped and rendered. • Red - Represents the start pixel. It is the first negative charge created and the point from where all lightning branches. • Blue - Represents a waypoint system. Every pixel colored blue is preferred when lightning generation occurs. If possible, the generated leader will always pass through it. LumosQuad allows for many different tweaks within its render and simulation portions, Figure 20. The output of a given simulation results in two files, one .exr file and one .lightning file. The latter of the two represents the results of the simulation while the former contains the render itself. The render setting, scale, is a third parameter in the program’s input and change the render settings from large, blurry glows at smaller values to sharper, tighter ones at larger values.
2.6. Physically Inspired, Interactive Lightning Generation, Yun et al, 2017 22 (a) Input .ppm file. (b) Real-time simulation progression. (c) Output .exr file. Figure 20: Examples of LumosQuad’s functionality. 2.6 PHYSICALLY INSPIRED,INTERACTIVE LIGHTNING GENERATION,YUN ET AL, 2017 Yun et al. (2017) is what can be most defined as state-of-the-art and counter-poses itself against the models produced by Kim and Lin, explored earlier within this section(Kim and Lin (2007)&Kim and Lin (2004)) with the former also contributing to the methodology proposed herein. In contrast to said models, this one exhibits a reported increase in speed of about 20 times, taking 38ms on a 128x128 grid while using only a singular core. When compared to the aforementioned DBM method that makes use of conjugate gradients, the reported speed
2.6. Physically Inspired, Interactive Lightning Generation, Yun et al, 2017 23 ups are of over two orders of magnitude. When compared to a DBM approximation with a summation model of potentials, it showed twice as fast speeds while exhibiting better shape controls and being closer to the physical interpretation of a dielectric breakdown thus giving it wider applicability. An example of the DBM method is given in Figure 12 When searching for a method to better the current state of lightning simulation, Yun et al. (2017) looked for sources of inspiration in many works. Most of them have been mentioned in this section of the thesis, though the authors delineate a few more of relative importance. First, an emphasis is given to the fact current games and real-time applications make use of pre-rendered images or approaches based entirely on randomized data trees, both of which prove to be problematic. Lightning is a fairly expensive phenomenon to render but one that draws the eye of the user and, as such, the use of repetitive patterns and low quality sprites can severely hamper immersion. It is noted that a previous work using the GPU to solve the Laplace equation in real time had already been done by Matsuyama et al. (2006) however, the cost was simply too high to be implemented outside a dedicated application. Similarly, while Nvidia provides a real-time DirectX 10 example that uses a geometry shader, it suffers from the same downfalls as Reed and Wyvill (1994). In contrast to the aforementioned methods, Yun et al. (2017) proposes a physically-inspired method that generates lightning by better approximating the value distributions within an electric potential field. Many of the same difficulties were encountered, rendering the atmospheric scattering of lightning has always posed a problem to researchers within the Computer Graphics sphere. While Reed and Wyvill (1994) extended ray tracing to render the lightning stroke and glow, Sosorbaram et al. (2001) proposed a volume rendering technique using a 3D texture. Furthermore, Dobashi et al. (2001) pioneered the use of metaballs and pre-computed lookup tables to store the integrated intensity of scattered light. Kim’s previous work(Kim and Lin,2004) made use of an atmospheric point spread function which described light scattering as a convolution kernel used to render the final stroke. In Yun et al. (2017), however, the authors propose their own method based upon the basic properties of an electrical potential field. Using their gradient tendencies alone, the authors propose an approximation of the relation between electric potential and the distance between a given point and an electric charge. As seen in Figure 21 and Figure 22, where the leftmost simulation represents a typical cloud-to-ground bolt while the rightmost one represents lightning cascading from the red square to the blue one. By the authors’ claim, the approximation is extremely faithful to the ones obtained via the Laplacian Growth model. Computing the electric potential between candidate cells and other charged cells and passing them through a normalizing equation, allows the authors to divide charges into positive, negative and boundary charges. This division is then used to calculate the electrical potential for each type separately which, when computed with certain values, actively alters the shape and depth of the branching patterns formed by the simulation. Notably, Yun et al. (2017) provides an in-depth graphical representation of how changing the values in a given order can affect the shape of a lightning bolt. There are a few important constraints to keep in mind. First, there can be objects or obstacles that should not be hit by the bolt, such as a wall. For such obstacles, negative charges are assigned, allowing them to be treated as part of the boundary condition.
2.6. Physically Inspired, Interactive Lightning Generation, Yun et al, 2017 24 Figure 21: Laplacian Growth Model. Source: Yun et al. (2017) Figure 22: Yun’s Growth Model. Source: Yun et al. (2017) Moreover, in a complex scene, their method encountered local minima, similar to other potential field methods. Due to this and the fact their algorithm computed potentials based on distance, when a scene exhibits obstacles that block the target position from the starting position, the lightning branches could spread out excessively. To handle this problem, Yun et al. (2017) made use of waypoints that are generated by path planning methods such as an A* algorithm, as seen in Figure 23. Finally, jittering is also extensively used to reduce grid regularities that appear due to the lack of fine grid resolution. As for the physical characteristics, thickness and brightness are taken into account when rendering a stream which is further decomposed into main and secondary channels, the main channel being any path that connects the starting and target points while secondary channels are sub-branches originating from the main channel, connecting to nowhere. Lightning lines are rendered using billboard techniques such as rectangles while branches are represented by cylinders and spheres for three-dimensional scenes. Furthermore, the glow itself is created using a fast separable Gaussian Filter applied horizontally to the framebuffer texture and, then, used vertically upon the resulting image.
2.6. Physically Inspired, Interactive Lightning Generation, Yun et al, 2017 25 Figure 23: Local Minima and Waypoint Solution. Source: Yun et al. (2017) Taking all of this into consideration Yun et al. (2017), while also being the most recent, represents the most physically plausible representation of lightning able to be applied into real-time scenes as evidenced by Figure 24 and Figure 25. Figure 24: Yun’s results within the simulator itself. Source: Yun et al. (2017)
2.7. Space Colonization - Runions et al. 2005 & 2007 26 Figure 25: Yun et al. (2017)’s render composited into an image. Source: Yun et al. (2017) 2.7 SPACE COLONIZATION -RUNIONS ET AL. 2005 & 2007 First published in Runions et al. (2005), the Space Colonization (SC) algorithm treats competition for space as the key factor in determining its growth, first designed for the generation of leaves and, later on, trees in Runions et al. (2007). The method by which this competition promotes branch growth and generation relies entirely on the two central concepts of attractors and nodes where attractors compete with each other for the influence of a node’s growth direction. As seen in Figure 26, the algorithm develops as follows. (a) presents the initial state of the system in which nodes arrive at an envelope field populated with a set number of attractors. Afterwards, as seen in (b) , if the distance between a given node and an attractor is smaller than its given radius of influence, then the closest node to said attractor is selected. The radius of influence describes the circular zone, centered around the attractor, within which a node must be present to be a candidate for influence. As seen in (c) , once that selection is made, a unitary vector representing the direction between an attractor and its closest node is calculated. (d) represents the sum and subsequent normalization of all these conflicting
2.7. Space Colonization - Runions et al. 2005 & 2007 27 Figure 26: Example of a Space Colonization algorithm. Black points represent nodes while Cyan points represent attractors. Source: Runions et al. (2007) directions by which the next set of nodes will be grown as shown in (e) . Finally, (f) and (g) show the manner by which attractors are removed from the field. First, each attractor’s boundary condition each checked, that is, the minimum distance between an attractor and node or kill distance. If a node is found breaching said condition, then the mentioned attractor is deleted and the algorithm proceeds as seen in (h) . Notably, an attraction point can only influence its closest tree node while a given node can be influenced by as many attractors as necessary. As seen in Figure 27, the number of attraction points and kill distance between nodes and attractors has a tremendous influence in the shape of the tree and its branches as well as the latter’s density and offspring. (a) represents a tree generated by using twelve thousand attractors and a kill distance twice as big as the distance between a node and its child. (b) keeps the same kill distance but reduces the amount of attractors to fifteen hundred. c represents a tree with twelve thousand attractors once again, but a kill distance twenty times greater than the distance between nodes while d maintains this same kill distance but reduces the number of attractors to 375. As noted in the images, the larger the kill radius, the more sparse a the structure will be because the attraction points remain for a shorter number of iterations. Similarly, lowering the amount of attractors reduces the amount of nodes to seek which, in turn, inhibits competition between nodes lowering the amount of branches produced in total while increasing the size of primary branches, the ones that are directly connected to the tree’s trunk and drastically reducing the size of subsequent branches as well as stifling their ability to form. Similarly, seen in Figure 28, the method by which attractors are distributed has a similar impact on the shape of the resulting tree, with (a) resulting from a cylinder while (b) is born from a conical envelope. This degree of influence is aided, in part, by the fact the algorithm ceases to function only when no other attractors are within effective range and will endlessly expand to achieve said goal.
2.7. Space Colonization - Runions et al. 2005 & 2007 28 Figure 27: Impact of the number of attraction points and kill distance on tree form. Source: Runions et al. (2007) Figure 28: Impact of attractor distribution in tree form. Source: Runions et al. (2007)
3.2. Introducing Natural and User-Defined Branches 35 (a) Forked lightning. Source: flickr.com.(b) Simulated forked lightning. Figure 36: A main channel drawn as a consequence of the waypoint system. 3.2 INTRODUCING NATURAL AND USER-DEFINED BRANCHES With the main channel suitably defined and expanding, based on a Space Colonization (SC) algorithm, there was now a need to introduce support for branching structures, Figure 37. A core goal of this procedure was to allow for the branching to take root both naturally or with user input, the latter of which will be discussed later. Lightning can be said to exhibit three types of channels: primary, secondary and tertiary. The primary, or main channel, has already been extensively covered while the secondary and tertiary will be the main topics discussed in this section. Going forwards, secondary branches will relate to any and all streams that have a connection to the main channel while tertiary branches will be used to identify those which stem from the secondary ones. As the main channel is being actively constructed, the current node may, based on a given probability distribution and threshold value, be selected to support branching. This threshold value can be actively reduced and increased, with lower numbers producing less complex lightning, resulting in less overall branching. While studying images of branched lightning, it was noted that most of them exhibited a tendency to manifest less branches as the main channel neared the point of discharge. There were also cases where the opposite was true, and others where branches seemed to avoid the centermost point of the main channel. All these effects can be simulated with an appropriate probability distribution. As an example, a bimodal distribution could be applied if the user wishes to suppress branching halfway through the main channel. Similarly, any kind of skewed distribution could be used to favor a given region of the main branch. The first step towards creating a new branch lies in identifying a suitable ending condition. In this specific case, said condition is a coordinate signifying the endpoint. Using spherical coordinates for this process allows for easy
3.2. Introducing Natural and User-Defined Branches 36 (a) Single-channel lightning. Source: flickr.com [Edited]. (b) Branched lightning. Source: flickr.com [Edited]. Figure 37: Two examples of cloud-to-ground lighting. One contains a single channel while the other exhibits branches. access to three modifiable parameters that can be suitably manipulated as necessary. The first parameter, ϕ , known as the azimuthal angle can be determined randomly via the use of, for example, an uniform distribution. The inclination, θ , however, is a function of the distance from the branch to the floor. In this given scenario, the floor is a plane containing the endpoint of the main channel and perpendicular to its direction of growth, as seen in Figure 39. With the azimuthal angle randomly selected, determining phi is unnecessary, as such, the first necessary constraint becomes the inclination. Observing the real life phenomenon, it was determined that, the most distance a given branch is from this plane, the more freely the ensuing channel is allowed to flow. This effect is so stark that, at times, it resulted in the ability to grow upwards. With this in mind, rather than keeping a constant restriction on aperture, a variable interval was created with the acceptable range becoming smaller by approaching the same conic aperture given by the leader’s growth direction. As such, the more a given point approaches the floor plane, the more the ensuing smaller the resulting cone’s aperture, directly constraining growth directions. Determining the direction towards which the branch will propagate is merely the first of two steps. In order to maintain a solid foundation and approach the real phenomenon, a maximum length needs to be set for each branch. To avoid potential conflicts, this length was set as starting point’s distance to the previously mentioned floor. To better distribute the branch length and randomize branch appearance, this length should be multiplied
3.2. Introducing Natural and User-Defined Branches 37 (a) Source: flickr.com.(b) Source: flickr.com. (c) Source: flickr.com [Edited]. Figure 38: Examples of different branched lightning. with a random number. Different probability distributions can be used to obtain this number, each having its pros and cons.
3.2. Introducing Natural and User-Defined Branches 38 Figure 39: Diagrams exemplifying different endpoint selections. For a natural look, a uniform real distribution is desirable though a normal distribution can be used to homogenize branch length, linear distributions if longer or shorter branches are preferred and bimodal distributions to avoid medium sized branches while homogenizing extremes. With an endpoint defined and the previously selected node serving as the branch’s root, charge distribution follows. Following the same process done for the main channel, an envelope is created containing both points on its surface. For cones, one of the nodes should be its apex while the other should be placed at the center of the base. For cylinders, each node should be on opposite faces. For spheres, the placement doesn’t matter as long as they are diametrically opposed, and for free-form shapes, the only real requirement is that the shape allows for the lightning to ‘flow’ from one point to the other by navigating the sea of attractors, much like a tunnel connects two points. Having created the envelope, its inner volume is filled with a number of charges. The volume itself can be tweaked freely with wider envelopes allowing for more curvature and unpredictability while a smaller envelope straightens the branch considerably. Furthermore, the more charges available, the more tortuous the branch’s path will be. On the other hand, if too little charges are defined, there is a risk of the endpoint never being reached. Should this happen, a trigger should serve as a warning to forcefully halt the algorithm, coming into action whenever the branch’s propagation algorithm fails to detect any attractor within influence radius. In such a scenario, there are two possible solutions for the resulting problem. The algorithm to propagate the main branch could be halted in its entirely, resulting in a shorter bolt that failed to properly reach the pre-established floor. The second solution involves calculating the current direction vector, defined by the shortest distance between the last grown node and the floor plane. Using this vector as a reference, Reed and Wyvill (1994)’s 16-degree observation can then be used to further the propagation of the bolt artificially, either until a new suitable attractor is reach or until a node is within kill distance of the floor plane.
3.2. Introducing Natural and User-Defined Branches 39 When it comes to building the branches themselves, Figure 40, now that charges have been suitably distributed, the same algorithm used for the main channel can be applied with a few tweaks as necessity arises. One such suggestion lies reducing the chance of a node being selected to spawn a tertiary branch, further distancing the resulting branch from what one would usually perceive to be the likeness of a tree. To create the tertiary branches, the same steps that allowed for the creation of the secondary branch can be used though radial distance should be relative to the secondary branch rather than the main channel. Furthermore, a more aggressive trimming factor is advised to avoid jarring disparities. For user defined secondary and tertiary branches, parameters such as the root node, the endpoint, the envelope type, envelope width, charge density and individual complexity value can all be appropriately defined by the user to allow for full control over the branch structure even while following the same overall algorithmic structure and behavior as a naturally occurring secondary channel. As a final note, to facilitate the separation of nodes belonging to the main branch from those belonging to secondary branches, a new tag can be introduced to the definition of the data structure, allowing for an easy logical check which becomes necessary for the proper rendering of these separate entities.
3.2. Introducing Natural and User-Defined Branches 40 Figure 40: An example of secondary and tertiary branch definition.
4 RENDERING Rendering lightning comes with many challenges. From the manner in which it iteratively constructs itself as the stepped leader progresses towards the ground, to its light-emitting properties and how they might be best represented. Lightning is an ephemeral phenomenon, lasting only a few milliseconds. The flash of light that follows its strike is so blinding it tends to disorient an onlooker when viewed from close proximity. Along with this, there is a striking visual that is often engraved in one’s mind. Due to the composition of a lightning bolt, plasma, every element of a bolt is surrounded by a coronal effect. It radiates brightly along the main branch yet briskly decreases when viewing the branches that failed to locate suitable ground, Figure 41. This is a consequence of the extreme energy transferal that accompanies a lightning discharge. Extreme heat turns air into plasma, making way for an overwhelming amount of luminosity centered around the channel that transfers the most energy, while branches, much less luminous and infrequent, seem to be a consequence of atmospheric conditions and residual charges Wikipedia (2021). When pondering the problem of rendering, it seemed wise to review how previous scholars had handled the question in the past. Apart from Dobashi et al. (2001), whose focus laid on expanding the work in Reed and Wyvill (1994), all other works seemed to have tackled how to handle the addition of effects in similar ways. Just as most articles use a ray-tracing solution when rendering lightning within a 3D scene, the way they handle the effects on the branch itself is similar. Using a two-pass Gaussian blur in conjunction with an emissive texture, a technique called “bloom”, an effect similar to that of a glowing bolt can be achieved. Yun et al. (2017), specifically, makes use of several methods mentioned previously as well as the billboard rendering technique used for the clouds in Dobashi et al. (2001). By separating the lightning into a main and secondary channels, the very thickness of the geometry composing the lightning’s skeleton is manipulated, becoming thinner the further it propagates from the main branch. At the same time, the transparency of the very same structures is manipulated, increasing as thickness decreases, giving the illusion of slowly fading light. For the glow itself, a simple Gaussian Blur shader is used, solidifying the illusion. While most of the articles do tackle the iterative building of a bolt, none of them sought to display the dynamic nature of its luminosity past the differences present between branches and the main channel. Notably, there is no mention of the strobing phenomenon caused by the presence of dart leaders in which a bolt’s intensity waxes and wanes with time as secondary strikes follow the previously carved path. A special focus was placed in implementing this effect. 41
42 Figure 41: Branched lightning. Source: wikimedia.org. As seen in Figure 42, lightning comes generally in three stages. The creation of the bolt, whose ending is marked by a thundering whiteout. The primary, coronal glow which then strobes as dart leaders run their course and then the ensuing dissolution of the bolt as plasma cools and returns to gas. This chapter is split into the following sections: 1. Section 4.1 outlines the procedures necessary when preprocessing the data so that it can be rendered sequentially, a step required for stages 2 and 3. 2. Section 4.2 details the growing process of a lightning bolt and how its animation is achieved. 3. Section 4.3 tackles the coronal and strobing effects seen in lightning and how they are animated. This rendering process lasts for a full second by default, though the user can tweak the duration of each stage by making use of a coefficient variable.
4.1. Ordering Nodes and Preparing for Rendering 43 (a) Flash when lightning strikes. (b) Plasma’s glow effect. (c) The fading light after a lightning bolt. Figure 42: The effects of lightning perceived by the human eye. Source: youtube.com. 4.1 ORDERING NODES AND PREPARING FOR RENDERING The way lightning propagates through the air is tortuous yet it follows a logical step wherein its feelers descend from the air at, mostly, the same height, with most of them stopping and forming branches while a lucky winner discovers the proper path to reach their goal. Due to this, a branched lightning bolt created with the Space Colonization (SC) algorithm, unless sorted during construction, can’t be rendered in the same order as it was generated. Depending on how the algorithm is implemented, the main channel’s growth will either stop during the construction of a branch or continue before beginning the construction of branches one-by-one. This issue is
4.1. Ordering Nodes and Preparing for Rendering 44 further compounded by the existence of user-defined branches which need to be constructed in relation to the main bolt. Naturally then, it is necessary to sort the generated nodes so that rendering can be properly done. The most intuitive way to do this would be to simply transpose the current stored positions into a vertex vector and then translate the bolt into a type of data tree. Each of the tree’s nodes would be identified by the index of the position on the vertex vector and connect to the indices of the nodes that were grown from it. By placing the root node as the data tree’s root, the following data structure would be ordered appropriately and a level order traversal of it can then ensue to translate it into a vector for use in rendering. However, by converting the bolt to a map, a similar approach can be taken. By defining a node’s index as the key and its associated value as a vector containing the index of every node that was grown for it, a similar traversal can be used. By taking the root node as the first index to be read, it can then be added into the vector with its attached list. Iterating through said list then allows for the members to be appended to a queue that is forwarded to the main loop of the sorting system, repeating this process until the queue is empty. Since not all nodes contain children and, therefore, not all of them are a key within the map which, along with a finite number of nodes, guarantees an equally finite loop. While using a data map may not be the more intuitive of the two approaches, it is not only more efficient, but also able to eliminate any possible errors that may arise if the longest possible path is not the one leading to the end. The entire process can be seen in Figure 43. The result of this ordered traversal is stored within a vector containing a flag and number. The first of which signals whether a given node is part of the main channel or not while the number relates to the index within the vertex vector where this node’s information sits. By parsing a pairs of these structures at the time, a segment connecting two nodes can be easily identified. As such, this comprehensive list can then be used to fill two different OpenGL index vectors with more information as time elapses, resulting in a growing lightning bolt. The first of these vectors is reserved for indices that belong to the main branch while the other contains those that do not, a step required for the following Section 4.2 and outlined in Figure 44.
4.3. Simulating the Strobing Effect of a Lightning Bolt 51 4.3 SIMULATING THE STROBING EFFECT OF A LIGHTNING BOLT Two noteworthy effects exist when producing visually appealing imagery of lightning bolts. Not only are these effects intertwined, they require special attention whenever lightning is rendered. This fact is highlighted by a constant presence of a section in the implementations highlighted in Chapter 2, dedicated solely to the coronal glow exhibited in lightning. The other notable effect which has yet to be covered, is the waxing and waning of said glow, reminiscent of a strobing light. To simulate the coronal glow a bloom-like effect is used. Bloom, sometimes referred to as a glow (Figure 48 is a post-processing technique often used in computer graphics to enhance the way a viewer experiences a highintensity light source. The effect is characterized by the appearance of light fringes extending from a particularly bright object in an image, allowing the light to proliferate around its source, almost as if bleeding, and adding a layer that appears to glow to the user. Together, these effects characterize the technique and portray an illusion where an extremely bright light overwhelms the viewer. Figure 48: Bloom used to simulate light sources. Source: learnopengl.com. To implement a bloom effect, a few different steps are necessary. First, the scene is captured onto a texture and the main channel separated from its branches. Secondly, a blur is both of these textures, creating the glowing effect necessary. Finally, the original textures and the blurred result are blended together to create a singular output containing the scene, the main channel and branches with their necessary effects. In the current context, however, the application of a new step to the main branch, using dilation, is recommended to capture the necessary luminosity. For the first step, a single shader with different parameters is used to separate the scene, the main channel and the branches from each other, resulting in two different textures which store the relevant information. Afterwards, for the second step, the results of this separation are sent to their respective processing passes. For the main channel, a dilation shader is used to create the illusion of thickness seen when lightning finally strikes the ground, the result of which is seen in Figure 49. This shader simply takes any pixel belonging to the main branch and extends its color horizontally to the neighboring four pixels, two on each side. Afterwards, a Gaussian blur with a relatively small kernel is applied. This shader helps conceal any jagged features left from the dilation and gives the lightning a more natural look. Finally, another Gaussian blur, with a larger kernel size, is used to provide the necessary illusion for a glowing thunderbolt, seen in Figure 49c. A single blur shader, of a size smaller or equal to the first mentioned, is used on the branches.
4.3. Simulating the Strobing Effect of a Lightning Bolt 52 For the main branch’s larger, more prominent blur, a kernel size above 15 is advised along with five recursive applications. These subsequent applications are used to create brighter zones closer to the original bolt, resulting in a less jarring transition from the channel to its surrounding glow. For the secondary and tertiary branches, a kernel size of 9 is recommended along with a singular application, similar to the initial pass given to the primary branch. (a) Horizontal dilation (b) Branch blur. (c) Main bolt blur. [Edited] (d) Composite result. Figure 49: Textures used to store the results. [Contrast Edited] Blurring is generally a fairly straightforward post-processing technique where the results of neighboring pixels are blended together. In this case, the blur is applied based on a Gaussian distribution. For the specific case of a Gaussian blur, by following the Gaussian weights, the blurring shader gives higher priority to the original pixel and its most immediate neighbors, allowing its color to spread more naturally to its surroundings while avoiding jarring artifacts that may occasionally happen with linear blurs. The procedure itself can is illustrated in Figure 50 with its result shown in Figure 51. Figure 50: The procedure to apply a two-pass Gaussian blur. Source: learnopengl.com. To further the illusion of blinding luminosity, a MipMap of the blurred texture was made. By using one of the lower levels of the generated texture, a soft, glowing illusion that seems to overtake the surrounding scene is produced, emulating the way in which a lightning strike often colors the surrounding area and sky in a mixture of
4.3. Simulating the Strobing Effect of a Lightning Bolt 53 Figure 51: Image produced using a 15-pixel Gaussian blur on a single pixel. The canvas is 32 by 32. different colors dependent on atmospheric conditions, current lighting and other unknown variables. As such, it is possible for the color of this generated texture to be altered during the following blending process, allowing for the generation of wildly different illusions of ambient lighting as seen in Figure 52. (a) No MipMap texture. (b) Blue colored MipMap texture. (c) Light colored the MipMap texture. Figure 52: Different types of colors from the MipMap’ed texture. Finally, after the blur’s application, the blending process begins. Experimentation found that the best qualitative results came from additive blending of the dilated main channel and its respective blur along with simply using the blurred result of the associated branches rather than the original geometry. The result of the aforementioned addition is compared with the blurred branches. Since there may be overlap in blur regions between the main channel and the branches and no scene is present, the maximum value of each given pixel is selected, rather
4.3. Simulating the Strobing Effect of a Lightning Bolt 54 than simply adding the two together. If a scene was present, the maximum color intensity between the lightning’s components would be selected and then added with scene itself. A tweak to the overall luminosity of the output associated with the main branch and its blur is also recommended as the blur may, originally, lack the necessary brightness. To simulate the second effect, the strobing of the bolt itself, a few changes have to be made to the blending process. First, the process is divided into three distinct stages. The first one features the original textures where the lightning’s components were saved, exempt of any post-processing, akin to simply rendering the scene as is. After it strikes the ground, the bolt and its components achieve maximum luminosity and all the previously mentioned effects are applied, at their maximum strength, providing the same effect seen when the nearly imperceptible stepped leader touches the ground, releasing its charge. As such, stage two characterizes the waning phase of the lightning bolt. During this phase, the effects added via the post-processing passes lower in intensity until a threshold is achieved. On the other hand, stage three characterizes the waxing phase, where these sames effects increase in intensity until once more achieving their original color. After the bolt’s luminosity reaches its apex for the first time, these two stages can be indefinitely chained to recreate the strobing effect, as seen in Figure 53. Once the time comes for the bolt to dissipate, all that’s required is to tweak the first stage so that the previously threshold no longer exist and, instead, the effect fades in its entirely with the bolt itself.
4.3. Simulating the Strobing Effect of a Lightning Bolt 55 Figure 53: The strobing effect in action.
5 RESULTS The implementation of the algorithm and rendering procedures outlined in the previous chapters was done using the graphical engine Nau3D, available at github.com. In this chapter, results born from implementing the ideas previously presented will be shown. As the current implementation is able to support many user tweaks, made possible by tweaking certain variables, the space associated with these user parameters for both the construction and simulation of a lightning bolt with be explored and any and all variables used for each given image will be made readily available. Before exploring runtime parameters, an example will be shown of one of the possible configurations using default values, Figure 54a as well as a simulation using waypoints, Figure 54b. These waypoints , mentioned in Section 3.1, are specified in files further explained in Appendix A and then fed to the program via a buffer. The waypoint system is a feature available for both the main and secondary channels. (a) Lightning bolt with default values. (b) Lightning bolt using the waypoint system. Figure 54: Two examples of default bolts. 56
5.1. Explaining the Parameters and their Effects 57 5.1 EXPLAINING THE PARAMETERS AND THEIR EFFECTS This section is dedicated to exploring the runtime parameter space and their effects in the simulation of a lightning bolt. All of these make use of the following waypoints: (0.0, 1500.0, 0.0)and(0.0, 0.0, 0.0) , which define the beginning and end of the main branch, along with the default values of every other parameter unless otherwise specified, as seen in Figure 54a. The parameters explored, by order, are as follows: •Type of Branches Allowed •Secondary Branch Probability •Tertiary Branch Probability •Length of Secondary Branches •Length of Tertiary Branches •Envelope Type •Envelope Radius •Distance Between Nodes •Influence of Weighted Direction Typeo f BranchesAllowed , allows the user to specify if they wish only for primary channels to be simulated or if they want to allow secondary and tertiary to manifest during the simulation which are able to grow by default. Changes to this parameter can be seen in Figure 55.
5.1. Explaining the Parameters and their Effects 58 (a) Only primary branch allowed. (b) Primary and Secondary branches. Figure 55: Results from changing the Typeo f BranchesAllowed value. For run time variables, the mentioned SecondaryBranchProbability variable, first introduced in Section 3.2, allows the user to control the probability of branch formation manifested during the simulation, following a uniform distribution. Tertiary branches have, by default, a decreased base probability. Further stifling of their growth can be controlled with their own complexity variable named TertiaryBranchProbability . By default, the former is set at 0.145 while the latter is at 0.115 . Changes to these variables can be seen in Figure 56 and Figure 57 respectively.
5.1. Explaining the Parameters and their Effects 59 (a) SecondaryBranchProbability = 0.250 (b) SecondaryBranchProbability = 0.500 (c) SecondaryBranchProbability = 0.750 Figure 56: Results from changing the SecondaryBranchProbability value. (a) TertiaryBranchProbability = 0.250 (b) TertiaryBranchProbability = 0.500 (c) TertiaryBranchProbability = 0.750 Figure 57: Results from changing the TertiaryBranchProbability value. Two variables for Length exist, one for secondary and the other for tertiary branches. These represent a percentage and allow for the user to control the maximum allowed length of a branch, inherently reducing the size of any manifested branches of that given type. By default, both of these are at 1.0 . Changes to these parameters can be seen in Figure 58 and Figure 59 respectively.
5.1. Explaining the Parameters and their Effects 60 (a) SecondaryLength = 0.2 (b) SecondaryLength = 0.5 (c) SecondaryLength = 0.8 Figure 58: Results from changing the SecondaryLength value. (a) TertiaryLength = 0.2 (b) TertiaryLength = 0.5 (c) TertiaryLength = 0.8 Figure 59: Results from changing the TertiaryLength value. EnvelopeType and EnvelopeRadius , serve as ways to control the way in which charges are distributed. The former has two settings: Cylinder and Cone. The EnvelopeRadius controls the total volume of the envelope by altering its width, inherently stifling the ability of channels to curve, straightening them as a result. All of the results presented have, by default, an envelope type of cylinder and a EnvelopeRadius of 1 . Changes to EnvelopeType can be seen in Figure 60 while the effect of changing EnvelopeRadius can be see in Figure 61.
5.2. Recreating Real Lightning 67 •(−750.0, 1250.0, 0.0) Branch 2: •(0.0, 800.0, 0.0) •(425.0, 375.0, 425.0) (a) Edited to include waypoints. (b) Source: flickr.com. Figure 67: Comparing the simulation results with real lighting. (4) Finally, Figure 68 uses the following deviations from the default parameters: SecondaryBranchProbability is set at 0.275 . both Secondary and Tertiary Branch Length are set at 0.5 . The weighted direction has an In f luence of 0.560. For waypoints, there are two channels. The main channel abides by: •(0.0, 1500.0, 0.0) •(0.0, 700.0, 0.0) •(−250.0, 0.0, 0.0) While the fork uses, •(0.0, 700.0, 0.0)
5.2. Recreating Real Lightning 68 •(250.0, 0.0, 0.0) (a) Edited to include waypoints. (b) Source: flickr.com. Figure 68: Comparing the simulation results with real lighting. (5)
6 CONCLUSION A procedural rendition of a lightning simulator, based on the concept of using attraction points and the SC algorithm, was presented, verifying its ability to recreate lightning bolts beyond its original, intended use. Though many challenges were met along the way, the final result makes use of the algorithm’s strengths to interactively simulate what a lightning bolt might look like under user-specified conditions. The first goal of this dissertation was analyzing if the premise was possible. It began with an attempt at verifying the visual difference between trees and lightning and then to extend an organic algorithm, meant for botany, to recreate an approximation to the appearance of lightning in the real world. After an initial research, the algorithm’s application first revolved around emulating the main channel. Following in the footsteps of those who had delved into the area of lightning simulation in the past, the simulation will default to random shifts in direction should it not find any attractor. However, when it does, steps were taken to ensure a proper appearance. One such step was the addition of weighted growth which uses a directional vector, pointing from waypoint to waypoint, to influence a node’s direction of growth and helps guide the algorithm along its path, preventing unwanted behavior. Other forms of restricting the original SC algorithm were of extreme importance, especially keeping it from spreading widely. To this end, changes were made, no longer allowing any node to create multiple branches as it iterates. Simultaneously, a restriction was put in place, only allowing the latest node a chance to exhibit growth of any kind. Furthermore, only secondary and tertiary branches are allowed meaning that only the main channels and branches directly connected to the main channel are allowed to support branch growth. User variables were also introduced to mediate the growth of branches, the shape of the envelope upon which their charges are distributed and many others. By naturally constraining these values, the algorithm will attempt to emulate what a lightning bolt with such characteristics might possibly look like, even when faced with implausible circumstances. The final goal tackled the realistic portrayal of the strike itself, focusing on the proper rendering of effects and phenomena encountered in the observation of lighting strikes. Firstly, by increasing the amount of information fed to the index vector, the iterative construction seen during the stepped leader stage of lightning was achieved. Then, by making use of blur and bloom techniques, the glow associated with the intensity of a lightning bolt was properly portrayed. In conjunction with variable, adaptive blending, this blur was able to reproduce even the strobing effect seen during slow motion footage. A fading out of the geometry was added, emulating the similar lighting effects seen as a bolt dissipates. 69
6.1. Future Work 70 Overall, this dissertation presents a foundation in the area, a first step into this particular field. With that in mind, it has achieved what it set out to do, showing a great degree of freedom while accomplishing results that are visually comparable to the real phenomenon. 6.1 F U T U R E W O R K Overall, though the results are satisfactory, the fact remains that it is a proof of concept. Therefore, there are a myriad of topics that could be explored in the future, using this as a basis and improving upon its first steps. One such expansion would be to expand the scope of the simulation to adjacent, atmospheric effects related to lightning such as jets, elves, cloud-to-cloud discharges and similarly rare and esoteric events. The addition of upwards streamers is also another potential addition, requiring adjustments and specific modifications to the iterative construction of the bolt itself. Work is also required in the rendering part to integrate the resulting bolt into a scene. While the effects on the bolt itself are all available, no attempts were made to incorporate the way lightning may influence a scene’s lighting scheme. Using ray-tracing, light-maps or other similar techniques, it would be possible for the lightning strike to have a visual effect on the scenery surrounding it, though that falls beyond the scope of what was trying to be achieved. Another avenue that might be worth pursuing in the future is an attempt to integrate this manner of procedural generation with already known techniques or even use it to add an element of uncertainty to the current physicallybased approaches. Though research into this possibility is necessary, by using the DBM as a basis and then applying the SC algorithm to mediate expansion, an alternative to current physically-plausible algorithms may be discovered.
BIBLIOGRAPHY José-Luis Bermudez Arboleda. Lightning currents and electromagnetic fields associated with return strokes to elevated strike objects. page 178, 2003. doi: 10.5075/epfl-thesis-2741. URL http://infoscience. epfl.ch/record/33217. Jeremy L Bryan. Fast Simulation of Lightning for 3D Games. PhD thesis, University of Colorado at Colorado Springs, 2005. Y. Dobashi, T. Yamamoto, and T. Nishita. Efficient rendering of lightning taking into account scattering effects due to clouds and atmospheric particles. In Proceedings Ninth Pacific Conference on Computer Graphics and Applications. Pacific Graphics 2001, pages 390–399, 2001. doi: 10.1109/PCCGA.2001.962896. Andrew Glassner. The digital ceraunoscope: Synthetic thunder and lightning, part 1. IEEE Comput. Graph. Appl., 20(2):89–93, March 2000. ISSN 0272-1716. doi: 10.1109/38.824552. URL https://doi.org/10. 1109/38.824552. T. Kim and M. C. Lin. Physically based animation and rendering of lightning. In 12th Pacific Conference on Computer Graphics and Applications, 2004. PG 2004. Proceedings., pages 267–275, 2004. doi: 10.1109/ PCCGA.2004.1348357. T. Kim and M. C. Lin. Fast animation of lightning using an adaptive mesh. IEEE Transactions on Visualization and Computer Graphics, 13(2):390–402, 2007. doi: 10.1109/TVCG.2007.38. Frank Losasso, Frédéric Gibou, and Ron Fedkiw. Simulating water and smoke with an octree data structure. ACM Trans. Graph., 23(3):457–462, August 2004. ISSN 0730-0301. doi: 10.1145/1015706.1015745. URL https://doi.org/10.1145/1015706.1015745. K. Matsuyama, T. Fujimoto, and N. Chiba. Real-time animation of spark discharge. The Visual Computer, 22: 761–771, 2006. S. G. Narasimhan and S. K. Nayar. Shedding light on the weather. In 2003 IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 2003. Proceedings., volume 1, pages I–I, 2003. doi: 10.1109/ CVPR.2003.1211417. Nau3D. Nau3d: Opengl + optix 3d engine, Feb 2014. URL https://github.com/Nau3D/nau. L. Niemeyer, L. Pietronero, and H. J. Wiesmann. Fractal dimension of dielectric breakdown. Phys. Rev. Lett., 52: 1033–1036, Mar 1984. doi: 10.1103/PhysRevLett.52.1033. URL https://link.aps.org/doi/ 10.1103/PhysRevLett.52.1033. 71
BIBLIOGRAPHY 72 NOAA National Severe Storms Laboratory NSSL. Lightning basics, 2021a. URL https://www.nssl. noaa.gov/education/svrwx101/lightning/. NOAA National Severe Storms Laboratory NSSL. Lightning types, 2021b. URL https://www.nssl. noaa.gov/education/svrwx101/lightning/types/. Todd Reed and Brian Wyvill. Visual simulation of lightning. In Proceedings of the 21st Annual Conference on Computer Graphics and Interactive Techniques, SIGGRAPH ’94, page 359–364, New York, NY, USA, 1994. Association for Computing Machinery. ISBN 0897916670. doi: 10.1145/192161.192256. URL https://doi.org/10.1145/192161.192256. Adam Runions, Martin Fuhrer, Brendan Lane, Pavol Federl, Anne-Gaëlle Rolland-Lagan, and Przemyslaw Prusinkiewicz. Modeling and visualization of leaf venation patterns. ACM Trans. Graph., 24:702–711, 07 2005. doi: 10.1145/1073204.1073251. Adam Runions, Brendan Lane, and Przemyslaw Prusinkiewicz. Modeling trees with a space colonization algorithm. In Proceedings of the Third Eurographics Conference on Natural Phenomena, NPH’07, page 63–70, Goslar, DEU, 2007. Eurographics Association. ISBN 9783905673494. B. Sosorbaram, T. Fujimoto, K. Muraoka, and N. Chiba. Visual simulation of lightning taking into account cloud growth. In Proceedings. Computer Graphics International 2001, pages 89–95, 2001. doi: 10.1109/CGI.2001. 934662. NOAA US Department of Commerce. Understanding lightning: Subsequent dart leaders and return strokes, Mar 2018a. URL https://www.weather.gov/safety/lightning-science-dart- leaders. NOAA US Department of Commerce. Understanding lightning: Initiation of a stepped leader, Nov 2018b. URL https://www.weather.gov/safety/lightning-science-initiation- stepped-leader. Wikipedia. Lightning, Dec 2021. URL https://en.wikipedia.org/wiki/Lightning# Observational_variations. Stephen Wolfram. A New Kind of Science. Wolfram Media, 2002. ISBN 1579550088. URL https://www. wolframscience.com. Jeongsu Yun, Myung-Bae Son, Byungyoon Choi, T. Kim, and S. Yoon. Physically inspired, interactive lightning generation. Computer Animation and Virtual Worlds, 28, 2017.
A SUPPORTING FILES The waypoint system is divided into two separate pairs of files: waypoints and branchpoints; As per the Nau3D (2014) buffer system, a .mlib and .txt file are necessary to feed buffer information to the program. The user needs only to alter the x parameter in the a .mlib file in order to match the amount of lines present in the respective .txt file. Each of the latter files is structured in the same manner containing three floating-point numbers separated by a space, as seen in Figure 69. For the waypoint .txt file, each triad of numbers represents a point in space and each pair represents a starting and ending position for a given segment of the main branch. As such, the program will only execute if an even number of points is made available. The underlying system behind the branchpoint file is somewhat more complex. While it is visually similar, it is used to define branches connecting through a functionally different method. By taking its format as: A B C X Y Z A B C X Y Z The program determines how to grow the branch by making the following assumptions: A determines the distance from the very first node at which the branch will be formed, following a trajectory from this root to the final waypoint and attaching it to the closest available node. B determines the length of the branch. C determines the maximum amount of children a node is allowed to have. X , Y and Z are the coordinates defining a direction vector which the branch will follow. 0.0 1500.0 0.0 −50.0 1000.0 −50.0 −50.0 1000.0 −50.0 −150.0 700.0 −150.0 −150.0 700.0 −150.0 −50.0 500.0 −50.0 −50.0 500.0 −50.0 0.0 0.0 0.0 Figure 69: An example of a waypoint .txt file. 73