DirectX 9.0c Game Development Journal of RPG Programming Self-learning log 13:drawing with DirectX Graphics (drawing with DirectX Graphic) (6th section)

Source: Internet
Author: User

This article by Harry _ Spider-Man original, reproduced please indicate the source! If you have any questions, please contact [email protected]

This time we continue to talk about Jim Adams old brother's RPG Programming book Second edition of the second chapter of the 6th section: Alpha Blending, also known as alpha blending. The content of this section is not many, so just finish it at once!

Let's take a look at the headings of the sections in this section below for your reference:

1. enabling Alpha Blending ( turn on Alpha blending )

2. Drawing with Alpha Blending ( drawing with Alpha blending )

3. Transparent blitting with alpha testing ( transparent blitting with Alpha test )

4. Loading Textures with color keying ( load a texture with a colored keyword )

5. Enabling Alpha Testing ( turn on Alpha test )

6. a Transparent blitting Example ( a transparent blitting Example )

Note: This section of the original book also includes several sections on lighting, but I think it's better to tell them as part of the 7th section. This, of course, implies a corresponding delay in the subsequent chapter numbers.

Original translation:

===============================================================================

2.6 Alpha blend

Imagine standing on one of the tallest buildings in the world, heading for a window, and gazing at the vast city below. The light blue hue of the window glass gives all things a calming coloring similar to the morning sky.

Imagine the same scene, but this time it's in the language of the graphics. The entire world is constructed of polygons, which are solid objects for all practical applications. You can not see through them. So what if you want to see through a window in your game? The window that just now gives all objects a nice tonal effect?

The cool effect you want is not just mentioned, but also something called transparent blits(Transparent blits) (that is, you want to draw a polygon that is partially completely transparent).

Will draw a partially transparent (partially transparent, refers to a part of the picture is completely transparent, rather than refers to the entire picture is translucent) of the object is described in such terms, is to draw a hole in the middle of the wall. The hole is completely transparent, although the wall is solid, and your sight through the hole will not be obstructed.

These effects are possible through the use of a technique called Alpha blending (alpha blending). With alpha blending, you can change the transparency of a polygon so that you can see through it. If the polygon is colored, its color is blended with everything that follows the polygon. What's even more amazing is that you can use textures on this polygon to create some really awesome effects!

The transparency of an object is called an alpha value . You may have noticed that Direct3D has several ways of using alpha values. For example, when using textures, you can set a format that uses alpha values. The alpha value is stored in a place called the Alpha channel .

Attention

===============================================================================

The alpha channel is a value that is much like the color component (red, green, blue). It sets the transparency to be applied, and each pixel on the surface has its own alpha channel.

This alpha channel can be changed between 1 and 8 bits. If you have a 8-bit alpha channel, you can set 256 alpha values (from 0 to 255). A 4-bit alpha channel uses 16 alpha values (0-15).

===============================================================================

2.6.1 enablingalpha Blending ( enable Alpha blending )

Enabling the alpha blending function of Direct3D is simple, as long as you use the Idirect3ddevice9::setrenderstate function and set the appropriate rendering state (render states) is OK. The first render state is d3drs_alphablendenable, which actually enables alpha blending:

g_pd3ddevice =pre-initialized-Z Device object/To Enablealpha-blending, Use:g_pd3ddevice->setrenderstate ( D3drs_alphablendenbale,true); Set the Type Ofalpha blendingg_pd3ddevice->setrenderstate (d3drs_srcblend,                                                                 d3dblend_srcalpha); g_ Pd3ddevice->setrenderstate (D3drs_destblend,                                                                 d3dblend_invsrcalpha);//To Disablealpha-blending, Use:g_ Pd3ddevice->setrenderstate (D3drs_alphablendenbale,false);

Notice that there are two other render states (D3drs_srcblend and D3drs_destblend) in the preceding code. These two states tell Direct3D that you want to use alpha values when rendering. Sometimes you'll see that the D3drs_destblend value is set to D3dblend_one instead of D3dblend_invsrcalpha. I'll show you when they show up.


2.6.2 Drawing withalpha Blending ( drawn with Alpha blending )

In order to use alpha blending, the only additional information you need is how to add alpha values to your custom vertex information. You do this by adding the diffuse color component to the custom vertex structure body and descriptor. When you define the diffuse color, you must set the alpha value.

The following example creates a simple vertex structure that stores the X-y coordinates and the diffuse color component (which now contains an alpha value):

The custom vertexstructure and descriptortypedef struct {  FLOAT    x, y, Z;  D3dcolor Diffuse;} Svertex, #define VERTEXFVF (d3dfvf_xyz | D3dfvf_diffuse)//Define 3 Verticesin a local Arraysvertex verts = {  {     0.0f,  100.0f,  0.0f,  D3dcolor_rgba (255, 0, 0,)   },  {   100.0f, -100.0f,  0.0f,  d3dcolor_rgba (0, 255, 0, +)  },  { -100.0f,  -100.0f,  0.0f, D3dcolor_rgba (0, 0, 255, 255)  },};

The first vertex is set to red, and is 1.4 translucent (1.4 of the color will be blended). The second vertex is green and uses 1.2 semi-transparency (1.2 of the color is blended). The third vertex is blue and is completely opaque, indicating that no color will be mixed in. (In fact, this passage is very abstract.) Anyway , alpha value bit 0 is completely transparent, and 255 is completely opaque! )

If you add texture mapping coordinates and set a valid texture, you can set the diffuse color to full (red, green, and blue are set to 255), and then set the alpha value to blend the textures.


2.6.3 transparentblitting with Alpha testing ( transparent with alpha test blitting)

The Alpha test (Alpha testing) is a technique that tests the alpha value of a pixel before it is drawn to the display.

Pixels with alpha values that do not fall within a particular range are rejected and therefore do not reach the render stage. Similar to the translucent effect in the previous section, you can use the alpha test to render polygons that contain completely transparent portions.

Using the "hole in the Wall" example in the previous section, imagine that the wall is a polygon, and then you want to draw a hole in the heart. You want this polygon to be completely opaque (solid), except for this hole. You want this hole to be completely transparent. To achieve this effect, you use a technique called transparent blit (Transparent blit), which allows you to exclude parts of a texture, This allows you to glimpse the back of the graph from these voids.

The secret of transparent blitting is to build your texture and set a single color as the color keyword. color keys are colors that are not drawn when polygons are rendered.

For example, if you have a texture that has a circle in the middle and is surrounded by black (2.17), you can set the color keyword to black. When the texture is applied to a polygon and the polygon is drawn, the Direct3D does not swing these black pixels so that only the middle circle is rendered.


In practice, it is not the color keyword that marks a transparent pixel, but the alpha value of the pixel. To make a pixel completely transparent, its alpha value must be set to 0. For pixels to be drawn, the alpha value must be set to the highest, which is 255.

As you might have guessed, the pixel that matches the color keyword has an alpha value of 0, and all other pixels have a higher alpha value.

2.6.4 Loading textureswith color keying ( load a texture with color keywords )

When using alpha testing in this way, you do not need to set the diffuse color component in your custom vertex structure or descriptor. The alpha value is stored directly in the texture's pixel data. To set the alpha value in the texture pixel data, you use the extended version of the D3DXCreateTextureFromFile function to load the texture as follows:

HRESULT D3DXCreateTextureFromFileEx (Lpdirect3ddevice9      pdevice,//device object to create Withlpcstr                psrcfile ,//filename of texture to loaduint                     Width,//D3dx_defaultuint                     height,//d3dx_defaultuint                 miplevels,//D3DX _defaultdword                     usage,//0d3dformat                format,//color Format to Used3dpool                   pool,//D3dpool_manageddword Filter,//D3dx_filter_triangledword                 mipfilter,//d3dx_filter_triangled3dcolor              ColorKey,//Color key to use! D3dximage_info       *psrcinfo,//Nullpaletteentry         *ppalette,//Nulllpdirect3dtexture9 *pptexture);//Texture object to create

Most parameters use the default parameters shown above. The only thing you need to provide is the file name of the bitmap to load, which device object to use when creating the texture, and the color format used when the texture is loaded (type beginning with d3dfmt_, which must use an alpha value, such as D3dfmt_ A8R8B8G8) and the color keywords (in d3dcolor format).

When setting the value of the color keyword, use the D3dcolor_rgba or D3dcolor_colorvalue macro to set the color you want. For example, if you want to avoid black being drawn, use a color keyword to load the texture:

D3dcolor_rgba (0, 0, 0, 255);

Note The value of alpha is 255. It's important! In the load bitmap file (. BMP), you must also set the alpha value to 255. If you are working with a non-bitmap file that already contains the alpha channel value (for example,. TGA), you must match the alpha value set to the alpha value stored in the image file.

In this book, I only use bitmap files, so just remember to use an alpha value equal to 255. After setting the alpha value of each pixel of the texture, it is a good thing to use an alpha test to reject it based on the alpha value of the pixel.


2.6.5 Enablingalpha Testing ( Alpha test enabled )

Once the texture is loaded (and the color keyword and alpha values are set), you can enable the Alpha test by adding the following code at the time you initialize or the render loop:

g_pd3ddevice = pre-initialized deviceobjectg_pd3ddevice->setrenderstate (d3drs_alphatestenable,true); g_ Pd3ddevice->setrenderstate (d3drs_alpharef,0x08); G_pd3ddevice->setrenderstate (D3DRS_ALPHAFUNC,                                                               D3DCMP _greaterequal);

The D3drs_alpharef state is magical because it tells Direct3D which Alpha values (from 0 to 255) are allowed. After the three functions just shown are called, all pixels with an alpha value of less than 8 will be rejected. If you set the color keyword correctly, these three functions will force all alpha textures with a value of 0 to be excluded from the rendering phase, making them transparent!


2.6.6 a Transparent blitting Example ( a transparent blitting example)

Enough has been said, it's time to give some code! Here is a small example of loading a button image and displaying it on the screen. The black pixels of the texture are rejected, allowing the background color to penetrate:

g_pd3ddevice = pre-initialized deviceobject//Custom vertex structure and descriptortypedef struct {  floatx, y, Z, Rhw Screen coordinates  FLOAT        u, v;//Texture coordinates} Svertex; #define VERTEXFVF (D3DFVF_XYZRHW | D3DFVF_TEX1)//Vertex buffer and Textureidirect3dvertexbuffer9 *G_PVB = null;idirect3dtexture9 *g_ptexture = NULL;
Set up the vertex buffer and texture//assuming a 400x400 windowbyte *ptr;svertex verts[4] = {{0.0f, 0.0f, 0.0f, 1 .0f, 0.0f, 0.0f}, {399.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f}, {0.0f, 399.0f, 0.0f, 1.0f, 0.0f, 1.0f}, {399.0f, 399.0 F, 0.0f, 1.0f, 1.0f, 1.0f}};                                                       Create vertex buffer and stuff in Datag_pd3ddevice->createvertexbuffer (sizeof (Svertex) *4,0, Vertexfvf,d3dpool_managed, &G_PVB, NULL))) {G_pvb->lock (0,0, (void**) &ptr, 0))) Me mcpy (PTR, Verts, sizeof (Verts)); G_pvb->unlock ();                                                        Get Textured3dxcreatetexturefromfileex (g_pd3ddevice, "button.bmp", D3dx_default,d3dx_default, D3dx_default, 0, d3dfmt_a8r8g8b8,d3dpool_managed, D3                                Dx_filter_triangle, D3dx_filter_triangle,d3dcolor_rgba (0,0,0,255), NULL, Null,&g_ptexture); Set Alpha Testingg_pd3ddeviCe->setrenderstate (d3drs_alphatestenable,true); g_pd3ddevice->setrenderstate (D3DRS_ALPHAREF,0x01); g_ Pd3ddevice->setrenderstate (D3drs_alphafunc, d3dcmp_greaterequal); Clear device backbufferg_pd3ddevice->clear (0, Null,d3dclear_target, D3dcolor_rgba (0 , 128,128,255), 1.0f, 0), if (SUCCEEDED (G_pd3ddevice->beginscene ())) {//set stream source to particle vertex buffer g    _pd3ddevice->setstreamsource (0,G_PVB, 0, sizeof (Svertex));    Set vertex shader to particle type G_PD3DDEVICE->SETFVF (VERTEXFVF);    Set Texture g_pd3ddevice->settexture (0,g_ptexture);    Draw vertex buffer g_pd3ddevice->drawprimitive (d3dpt_trianglestrip,0, 2);    G_pd3ddevice->endscene ();    Clear Texture g_pd3ddevice->settexture (0,null); Turn off Alpha Testing g_pd3ddevice->setrenderstate (D3drs_alphatestenable,false);} Flip surfaces to display workg_pd3ddevice->present (null, NULL, Null,nulL); 

===============================================================================

All right, this is the end of the translation! Here's the time to send the code! Like last time, I will also send the original book code and my updated code. Here is my updated version of the code when it runs:


A few notes:

1, the updated version of the code on the previous update draw2d based on the change.

2, with two beautiful pictures to let the program not too boring.

3, the original book is a simple color of the vertex composed of two rectangles, vertex color with alpha value, and now use the two images without alpha value, so if the original blend factor to write code, then the effect is not ideal (you can try), So I replaced it with another blend factor, effect ... It's really good!

Finally, the following is given:

Alpha Code


DirectX 9.0c Game Development Journal of RPG Programming Self-learning log 13:drawing with DirectX Graphics (drawing with DirectX Graphic) (6th section)

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.