Also play the visual effect: VC ++ programming to achieve the simulation flame

Source: Internet
Author: User
Also play the visual effect: VC ++ programming to achieve the simulation flame-general Linux technology-Linux programming and kernel information, the following is to read details. Introduction

The basic principles of computer simulation technology are the same. The mysterious and complex nuclear explosion is similar to water waves, flame, smoke, and other very common natural phenomena. There is no big difference in the simulation process. All of them have gone through the summary from the physical object to the physical characteristics. Then, a mathematical model is established, and a simulation algorithm is proposed based on the mathematical model. Finally, a series of steps such as dynamic simulation are carried out through the computer. In this paper, the flame is used as the simulation object, and a mathematical model and simulation algorithm are established through the analysis of the characteristics of heat source, heat diffusion and convection. In order to give full play to the computer's hardware acceleration of graphics, the DirectDraw technology is used to accelerate the display of the simulation results, so that the flame combustion process can be simulated in a realistic and smooth manner.

Simple approximate model design

Although flame is a very common natural phenomenon in nature, according to fluid mechanics knowledge, flame can be expressed as a complex three-dimensional dynamic fluid system. For example, accurate simulation of such a complex fluid system in a computer requires a very large and complex mathematical model, and the computing workload will be huge, in the existing microcomputer, it is almost difficult to ensure its dynamic real-time performance, which also loses the meaning of simulation. Therefore, the model should be as simple as possible during simulation to achieve as realistic as possible.

From the physical point of view, to generate flame, first there must be a fire source. Second, in order to produce the "Flame" effect, the fire source must be centered upwards and spread around, in addition, the temperature will gradually decrease as the flame is gradually removed from the fire source during the diffusion process, which is visually indicated by the cool-down of the flame. In addition, due to the high temperature of the flame, the proportion of the surrounding air is reduced by heat expansion, so there will be air convection, which will blow the flame up, so that the distance from the flame to the surrounding area is far less than the distance from the upward diffusion. Based on the above several points, we can take corresponding simulation measures: the setting of the fire source can be identified by a binary bitmap, non-fire sources are filled with low-brightness pixels, and fire source points are set to high-brightness pixels. The bitmap pixel value can be determined whether the current point is a fire source.




(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/col/attachment/2006/3/613953.jpg'); ">

The temperature of the fire source can be described by the brightness of the vertex where it is located. For the simulation of flame diffusion, in order to minimize the calculation workload, a certain fire source point (x, y) is used here) and the mean of the left and right adjacent four points to approximate, that is, Pixel (x, y) = (Pixel (x, y) + Pixel (x, Y-1) + Pixel (x, y + 1) + Pixel (x-1, y) + Pixel (x + 1, y)/5, although the approximate algorithm does not take the positive cosine method accurately, however, the computation speed is extremely fast, and there is almost no difference in the results of subsequent experiments with the method of using the positive cosine. Because the flame temperature in the simulation process is realized by changing its brightness value, therefore, the cooling of the diffusion process can reduce a fixed brightness value for the pixel. The attenuation value depends on the desired flame cooling rate. The direct effect of convection on the flame is to keep the flame burning up, therefore, you can roll up the current flame by one or two pixels. According to the simulation algorithm described above, the flame diffusion and convection can be integrated to achieve this, which will reduce the computational workload to a certain extent and make the generated flame more realistic visually. The pseudocode that implements the above approximation model can be roughly designed as follows:

ARRAY_OF_BYTES: buffer1 (xsize * ysize), buffer2 (xsize * ysize)
While (TRUE ){
For (y = 1; y
For (x = 1; x
N1 = buffer1 (x + 1, y) // read 4 adjacent pixel values
N2 = buffer1 (x-1, y)
N3 = buffer1 (x, y + 1)
N4 = buffer1 (x, Y-1)
P = (n1 + n2 + n3 + n4 + p)/5); // mean of four adjacent pixels
P = p-c; // the attenuation of the same fixed cool-down
If (p <0)
P = 0
Buffer2 (x, Y-1) = p
}
}
Copy buffer2 to the screen; // display the next frame
Copy buffer2 to buffer1; // update Buffer1
}


Improved flame non-uniform cooling model

The flame can be simulated to a certain extent based on the above approximate model. However, because the random distribution flame is not introduced, it often looks rather monotonous, and the total flame increases linearly, the cool-down speed is also strictly consistent. To eliminate the above problems, we can solve them by introducing random non-uniform factors. One way is to randomly arrange the cooling values of each point so that the flame cooling process is uneven. However, because the flame simulation process is carried out in real time, to ensure smooth operation in the dynamic simulation process, it is best to use a pre-created cooling Bitmap (see the picture on the right) instead. Generally, the cooling bitmap is filled by randomly spreading thousands of different brightness points on the screen and applying smooth processing to it. It is much better to replace the original fixed cool-down attenuation value by using the value obtained in the cool-down diagram. At this time, the cool-down process is improved to Pixel (x, y) = Pixel (x, y) -Coolingmap (x, y) attenuation results make the cooling Attenuation Effect of the flame more realistic:

P = lightBuf2 + imgWidth * 2;
Pp = coolMap + coolMapWidth * 2;
P1 = lightBuf1 + imgWidth * 2;
P2 = p1-imgWidth;
P3 = p1-1;
P4 = p1 + 1;
P5 = p1 + imgWidth;
For (I = 0; I // calculate the mean of a vertex and its four adjacent pixels
C1 = (unsigned char) (UINT) * p1 + (UINT) * p2 + (UINT) * p3 + (UINT) * p4 + (UINT) * p5) /5 );
C2 = * pp;
If (c1> c2)
C1-= c2;
* P = c1;
Pp ++, p ++, p1 ++, p2 ++, p3 ++, p4 ++, p5 ++; // memory pointer correction
}

Because the flame is still spreading and convection while cooling and attenuation, these effects must be synchronized, this requires the bitmap to be rolled up and cooled at the same speed as the convection. To reduce unnecessary operations, scroll is implemented by changing the vertical offset of the cool-down bitmap in the memory:

Memcpy (lightBuf1, lightBuf1 + imgWidth * 3, imgWidth * (imgHeight-3 ));

Although the above steps have been improved to a certain extent, there are still some defects, such as survival, constant flame rising speed, and burning throughout the space. To make the simulation more realistic, you can set a seed point to improve the above defects. Similarly, for processing speed consideration, it is best to pre-set the seed point in the form of a bitmap. During simulation, you can directly move the pointer in the memory to access the seed point, the main code is roughly as follows:

Int t = RAND_MAX/5;
TopX = (imgWidth-seedMapWidth)/2; // seedMapWidth: Specifies the width of the bitmap.
TopY = (imgHeight-seedMapHeight)/2; // seedMapHeight: seedMapHeight
P = lightBuf1 + (topY + 2) * imgWidth + topX; // p, unsigned char pointer
Ps = seedMap + seedMapWidth * 2; // ps, unsigned char pointer
For (j = 0; j <(seedMapHeight-4); j ++ ){
P1 = p; // p1, unsigned char pointer
For (k = 0; k
If (* ps! = 0) {// ps, unsigned char pointer
If (rand () <t)
* P1 = 255;
}
P1 ++, ps ++; // pointer correction
}
P + = imgWidth; // pointer correction
}

Accelerated Graphic Display

In the previous algorithm design, we have been paying attention to reducing unnecessary computations in order to achieve the highest processing speed possible. However, good algorithms alone cannot achieve satisfactory visual effects. Many large games, despite complex scenarios and rapid changes in the scenario, rarely feel the unbearable pause of the game. This is not only because the game adopts good algorithms, but more importantly, the game uses a large number of Direct X technologies in the Process of interacting with players, this technology is a general term for many technologies such as Direct Draw, Direct Sound, and Direct 3D. DirectDraw is one of the most important components. It is mainly responsible for accelerating graphics and allows programmers to directly operate on video memory, hardware bitmap ing, and hardware coverage and page feed technologies. This technology also supports many important functions such as dual buffering and Graphic page feed, 3D z-buffers (z cache), and z-ordering hardware secondary coverage. It can be seen that the Direct Draw technology can greatly improve the graphic output effect of the simulation results and perform real-time flame simulation smoothly. Before using this technology, you must first perform pre-processing such as trial:

// Create a DirectDraw object (which is a program workflow and is omitted in the following code)
DirectDrawCreate (NULL, & lpDD, NULL );
// Obtain full-screen exclusive mode
LpDD-> SetCooperativeLevel (hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN );
// Set the Display Mode
LpDD-> SetDisplayMode (640,480, 16 );
// Fill in the Home Page Information
Ddsd. dwSize = sizeof (ddsd );
Ddsd. dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
Ddsd. ddsCaps. dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX;
Ddsd. dwBackBufferCount = 1; // a background page
// Create the Home Page
LpDD-> CreateSurface (& ddsd, & lpDDSPrimary, NULL );
Ddscaps. dwCaps = DDSCAPS_BACKBUFFER;
LpDDSPrimary-> GetAttachedSurface (& ddscaps, & lpDDSBack );
DDPIXELFORMAT pixelFormat;
PixelFormat. dwSize = sizeof (DDPIXELFORMAT );
LpDDSPrimary-> GetPixelFormat (& pixelFormat );
......

After initialization, You can plot the image on the background page and copy the background page to the home page to display the image of a frame:

LpDDSBack-> Blt (NULL, DDBLT_COLORFILL | DDBLT_WAIT, & ddbltfx );
Ddrval = lpDDSBack-> Lock (NULL, & ddsd, 0, NULL) // Lock the background page
While (ddrval = DDERR_WASSTILLDRAWING );
If (ddrval = DD_ OK ){
Fire. render (WORD *) ddsd. lpSurface); // finishes rendering a frame of flame.
LpDDSBack-> Unlock (NULL); // Unlock the background page
}
While (1 ){
Ddrval = lpDDSPrimary-> Flip (NULL, 0); // page feed
If (ddrval = DD_ OK)
Break;
If (ddrval = DDERR_SURFACELOST ){
Ddrval = lpDDSPrimary-> Restore (); // Restore the Home Page
If (ddrval! = DD_ OK)
Break;
}
If (ddrval! = DDERR_WASSTILLDRAWING)
Break;
}

The flame is simulated based on the above algorithm, and the visual fidelity of the speed and simulation results is very good. The picture on the right is a frame captured during the simulation process. It can be seen that although the previous algorithm design process adopted a seemingly excessive approximation, it did not produce any negative effect. The experiment shows that the method used in this paper to process images in the data buffer zone has nothing to do with the complexity of the simulation object flame in terms of Program Calculation and display speed, therefore, similar methods can easily simulate other complex physical and natural phenomena.




(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/col/attachment/2006/3/613955.jpg'); ">

Conclusion

This article briefly introduces the general design and implementation process of simulation programs through computer simulation of flame. By understanding the program design ideas and implementation methods described in this article, similar methods can be used to flexibly select different software interfaces, such as OpenGL and Direct3D, to simulate other natural phenomena. The program described in this article is debugged by Microsoft Visual C ++ 6.0 under Windows 98 (DirectX 5.0 is required ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.