- Text
- Visual,
- Zanebug,
- Void,
- Static,
- Method,
- Task,
- Assembly,
- Server,
- Assemblies,
- Listing,
- Dndj,
- Archive

DNDJ 3-6 June.indd - sys-con.com's archive of magazines - SYS ...

The Science Behind the ArtExploring Fractal Landscapes with GDI+Generate realistic landscapes with hills, valleys, and coastlines,and investigate the features **of** GDI+BY KIERANMULCHRONEfractal images are strikinglybeautiful, bright, and complexand they’re everywherethese days – from art galleriesto image compression to moviegraphics to environmental modelling(see Figure 1). It really is amazing tosee a **con**cept from the dusty world **of**mathematics jump up and grab theworld’s attention. Fractals and associated**con**cepts came into being justat the time that powerful computersbecame cheap and widely accessible,and this is no coincidence. In the pastit was widely assumed that complexphenomena such as coastlines, trees,and mountain shapes could only bedescribed by complex and difficultmathematics, which could only beunderstood by a select few.This view has now been turned onits head and we can use simple equationsto generate immense complexityjust like that seen in nature. We cangenerate this complexity by using acomputer to churn through millions**of** simple computations, hence therelationship between the emergences**of** fractals and computing. The reasonI like fractals so much is that, togetherwith chaos theory and nonlineardynamics, they have brought mathematicsinto the “cool science” domain.Another reason I like fractals is thatalthough they look complex, they aresimple to generate (well, simple fora computer!). When equipped witha computer and some programmingskills, this new branch **of** mathematicsis virgin territory that can be exploredin an experimental and visual manner.I find that to be an exciting prospect.In this article I will show youhow simple it is to generate images**of** fractal landscapes complete withcoastlines, sea, and relief shading,just like those illustrated in Figure 1.Fortunately the GDI+ library **of** the.NET framework makes it equallysimple to render these images in planview as bitmaps. Ideally these shouldbe presented in 3D but that wouldintroduce another level **of** complexitythat is beyond the scope **of** the currentarticle.4Generating Fractal LandscapesMaking Random NumbersFirst **of** all the .NET framework providesa Random class specifically forgenerating random numbers; however,for the current example we require thenumbers to be distributed accordingto the normal (hopefully familiar bellcurve) distribution, whereas Randomf1Figure 1: A sequence **of** fractallandscapes generated usingthe computational and graphicscapabilities **of** .NET and GDI+.Each image is made by zoomingin on a small part **of** the previousimagegives us uniform or evenly distributedrandom numbers (i.e., each numberis equally likely to occur). In a normaldistribution numbers near a specifiedaverage occur more **of**ten than numbersaway from the average. A normaldistribution is characterised by a mean(i.e., average) and a variance, whichdescribes how far away from the meanvalues may occur (see Figure 2).For example, a large variance resultsin data spread widely around the average,whereas a small variance gives datatightly clustered around the average. Inorder to implement normally distributedrandom numbers in code I have createda new class called normal, whichis derived from the .NET Random class,as this saves a whole lot **of** work. It hastwo private data members for meanand variance implemented as properties,which can be specified in the**con**structor. The base class **con**structor**of** Random is called and its Randomnumber generator is seeded using thecurrent date and time. Finally I haveadded a method called NextNormal,which gives normally distributedRandom numbers by slightly modifyingRandom’s NextDouble method.4Random DisplacementsMuch **of** the algorithm for generatinga fractal landscape involvesmaking random adjusts to the height**of** points on a square grid. If therandom displacements were always**of** the same order **of** magnitude thenas square grid became smaller andsmaller, the displacements wouldbecome large in comparison tothe individual squares and leadingto a very jagged and unrealisticlandscape. We counteract this byscaling the random displacementsaccording to size **of** the smallestsquare. Of course we could try anystrategy we like to achieve this and indoing so many weird and wonderfullandscapes can be generated. Theusual approach however is to generaterandom displacements from a10**June** 2005 • dotnetdevelopersjournal.com

f 2f 3Figure 2: Illustrates three instances**of** the normal distribution all withaverage 0. The variance is 1 forthe tallest curve and then takes thevalues 2 and 3 for the progressivelylower curves. Higher variance hasthe effect **of** making values locatedaway from the average more likelyto occur.Figure 3: Schematic illustration **of**the landscape-generating algorithm.Given the elevation **of** points on asquare grid (i.e., the grey points in(a)) the elevations **of** points on afiner grid can be calculated (bothblack and grey points in (c)). First,the elevation **of** the midpoint **of**each square is the average **of** thefour diagonally adjacent grey points(see (b)) plus some random displacement.Next the elevation **of**the remaining points (i.e., the blackpoints in (c)) is calculated as theaverage **of** the four laterally adjacentpoints.normal distribution with a mean **of**0 and a variance **of** (2h 2 ) α where h isthe side length **of** the square and α isa value between 0 and 1. Therefore,as h gets smaller the variance getssmaller giving proportioned randomdisplacements. The α parameteradditionally allows us to **con**trol thejaggedness **of** the landscape closerto 0 means jagged and closer to 1means smoother. The fractal dimension(D) **of** the landscape is calculatedfrom α as D = 3 – α.4Landscape AlgorithmThe algorithm is relatively simpleand **con**sists **of** taking a large squareand filling in the details by progressivelyquartering the square andadjusting heights randomly.I have decided to take an approachthat makes the coding less taxing andmore efficient. Usually we would haveto deal with three space coordinates(x,y,z), however if we use a squarearray **of** floats to represent the landscapethen, by choosing a suitablesize, the indices **of** the array can correspondto the (x,y) coordinates andthe value stored at each array locationrepresents the height (z). For example,suppose that I sized my array to be 9by 9 (= 2 3 + 1), then I can **con**tinuouslyhalf my array to get integer indices i.e.,half **of** (0,8) is 4, half **of** (0, 4) is 2, half**of** (4, 8) is 6, etc. Therefore choosingmy array to be **of** size [2 n + 1, 2 n + 1]where n is a positive whole numbermakes halving squares painless.For simplicity I have chosen n= 9, so my array is 513 by 513 andultimately a bitmap **of** size 512 by512 will be generated. A variablecalled level is used to orchestratethe level **of** detail which needs to beinserted at any given stage and cantake values between 1 and n (i.e. 9right now). Using the level I can calculatethat the current square is **of**length 2 n /2 level-1 and that the quarteredsquare is **of** length 2 n /2 level .For example, at level 1 the currentsquare is **of** length 512 and thequartered square is **of** length 256.To begin with I set the level to1 and give values to the vertices **of**the current square (0,0), (0,512),(512,512), (512,0) **of** 0 plus a randomdisplacement with variance (2h 2 ) αwhere h is 2 n /2 level-1 , the currentsquare length. Two functions arethen called iteratively as the level isincreased by one each time to fill inthe details **of** the landscape.This procedure is illustrated inFigure 3. To begin with we have asquare grid with known elevationspreviously calculated for the vertices(i.e., the grey dots in Figure 3(a)). Thecenter points (i.e., the black dots inFigure 3(b)) can be calculated as theaverage elevation **of** the four adjacentvertices (grey dots) plus a random displacementwith variance (2h 2 ) α whereh is 2 n /2 level , the quartered squarelength. Finally elevations for the midpoints**of** each side (i.e., the black dotsin Figure 3(c)) can be calculated usingthe average elevation **of** the four adjacentgrey dots plus a random displacementwith variance (2h 2 ) α as before.The only potential problem occursnear the edges **of** the grid where somepoints may be missing, but this can beeffectively treated using special cases(e.g., using three instead **of** four points).4Zooming and CoordinateTransformations in GDI+The good news is that GDI+ providesa matrix class that takes care**of** most **of** the details **of** coordinatetransformations. The bad news is thatapplying methods **of** the matrix classto produce particular transformationsis not entirely clear from the documentation.However, by clearly statingthe problem we can easily solve it. Inthe **con**text **of** fractal landscapes wewould like the user to be able to selecta region **of** interest and zoom in on it.This involves a coordinate transformationbecause we would like what wasdisplayed in a smaller region to bedisplayed in a bigger region.f 4Figure 4: A general coordinatetransformationAUTHOR BIODr. Kieran Mulchrone currentlylectures in Modelling and NumericalComputing in the Department **of**Applied Mathematics, UniversityCollege, Cork, Ireland. However, hestarted out life as a geologist beforebecoming a s**of**tware developer (andshockingly enough for an academic,actually worked in the real world!),and then after all that settled backinto the comfort zone **of** academia.His research has to do with modellinggeological phenomena such assand ripples, coastal erosion, mudcracks, tectonics, etc. He is marriedwith four children, two dogs, and aTomagotche.4 k.mulchrone@ucc.iedotnetdevelopersjournal.com • **June** 200511

- Page 4 and 5: J u n e 2 0 0 5 V o l u m e 3 I s s
- Page 13 and 14: }}//constructor override the base c
- Page 16: Visual Studio ExtensibilityExtendin
- Page 20: Visual Studio ExtensibilityTable 1:
- Page 23 and 24: f 10f 11Figure 10: Adding aWindows
- Page 25 and 26: Listing 1 Add Task Event Handlerpri
- Page 28 and 29: Windows FormsAUTHOR BIO:Richard Art
- Page 30 and 31: ASP.NET Web FormsAjax-Driven Web Si
- Page 32 and 33: ASP.NET Web FormsAUTHOR BIOs:By: To
- Page 34 and 35: Compact FrameworksMobile Data Using
- Page 36 and 37: Compact FrameworksLanguage: C#Suppo
- Page 38 and 39: ASP.NET Web ServicesAsynchronous We
- Page 40: ASP.NET Web ServicesAUTHOR BIO:Aaro
- Page 43 and 44: f 2Figure 2: Zanebug GUI (results)A
- Page 45 and 46: Listing 1: Redirecting Assembly bin
- Page 47 and 48: foreach(string s in assemblies){log
- Page 49 and 50: introductorysubscription offer!A TR