Simple and transparent: Jeff molofee (nehe)'s OpenGL tutorial-Lesson 8

Source: Internet
Author: User
Tags transparent image
Simple and transparent

The vast majority of effects in OpenGL are related to some types of (color) mixing. The definition of the mixed color is to combine the color of a certain pixel with the color of the corresponding pixel that has been drawn on the screen. How to combine these two colors depends on the component values of the alpha channel of the color and/or the mixed color function used. Alpha is usually the 4th color component at the end of the color value. In the previous lessons, we used gl_rgb to specify three components of the color. The corresponding gl_rgba can specify the Alpha component value. Furthermore, we can use glcolor4f () instead of glcolor3f ().
Most people think that the Alpha component represents the transparency of the material. This means that when the Alpha value is 0.0, the material is completely transparent. When the Alpha value is 1.0, the material is completely opaque.

Color mixing formula

If you are not familiar with mathematics and want to see how to make it transparent, skip this section. If you want to deeply understand the working principle of (color) mixing, this section should be suitable for you. 『Note:In fact, it is not difficult ^-^. In the original article, the formula is as follows. In fact, the basic principle of mixing is that the color and background color of each pixel of the image to be divided are separated according to the RGB rules, after mixing the RGB color component * Alpha value + RGB color component * (1-Alpha value) of the background, finally, the RGB components obtained by the hybrid operation are re-merged. 』
The formula is as follows:
(RS Sr + rd dr, gs sg + gd dg, BS Sb + bd dB, as SA + AD da)
OpenGL calculates the mixed color of the two pixels according to the above formula. The lower-case s and R indicate the source pixel and the target pixel respectively. Uppercase S and D are the corresponding color mixing factors. These determine how you mix these pixels. In most cases, the Alpha mixed color values of different color channels are the same, so that the source pixels (as, as) and the target pixels are 1, 1, 1, 1)-(as, ). The above formula is like the following:
(RS as + RD (1-As), GS as + Gd (1-As), BS as + BS (1-), as as + AD (1-))
This formula will generate transparent/translucent effects.

Color Mixing in OpenGL

The steps for implementing color mixing in OpenGL are similar to the OpenGL process we mentioned earlier. Then, set the formula and disable the write depth cache when creating a transparent object. Because we want to draw objects behind a translucent image. This is not the correct color mixing method, but most of the time this method works well in simple projects.
Supplement of Rui Martins: The correct color mixing process should be to draw all the scenes before creating transparent images. In addition, the image must be drawn in the order opposite to the depth cache (first draw the farthest object ).
Consider mixing two polygon (1 and 2) with Alpha, and different draw orders will produce different results. (Assuming that Polygon 1 is closest to the observer, draw polygon 2 and then polygon 1 in the correct process. As you can see in reality, the light from the two <transparent> polygon always first passes through polygon 2 and then through polygon 1, finally, it reaches the observer's eyes .)
InDeep cache EnabledYou should change the transparent imageSort by Depth, AndAfter all scenarios are drawnThen draw these transparent objects. Otherwise, you will get incorrect results. I know it is very painful to do so sometimes, but this is the right method.
We will use the code for Lesson 7. Add two new variables at the beginning of the Code. For clarity, I have rewritten the entire code segment.

# Include <windows. h> /// windows header file # include <stdio. h> // header file of the standard input/output library # include <Gl/GL. h> // header file of the opengl32 library # include <Gl/Glu. h> // the header file of the glu32 library # include <Gl/Glaux. h> // HDC = NULL in the header file of the Glaux Library; // hglrc HRC = NULL in the private GDI device description table; // The Permanent coloring description table hwnd = NULL; // save our window handle hinstance; // Save the program's instance bool keys [256]; // The array bool active for keyboard routines = true; // The activity flag of the window. The default value is truebool fullscreen = true; // The full screen flag is set to bool light in full screen mode by default ;/ /On/off of the light source // lighting on/offbool blend; // blending off/on? (New) bool LP; // is the L key pressed? Bool FP; // is the F key pressed? Bool bp; // is the B key pressed? (New) glfloat xrot; // X rotating glfloat yrot; // y rotating glfloat xspeed; // X rotating speed glfloat yspeed; // y rotating speed glfloat Z =-5.0f; // The distance from the screen depth to glfloat lightambient [] = {0.5f}; // the ambient light parameter glfloat lightdiffuse [] = {1.0f }; // diffuse light parameter glfloat lightposition [] = {0.0f}; // gluint filter; // filter type: gluint texture [3]; // 3 Texture storage space lresult callback wndproc (hwnd, uint, wparam, lparam); // wndproc Definition
Then move downLoadgltextures ()Here. Find"If (textureimage [0] = loadbmp ("Data/crate.bmp "))"This line. We now use colored glass textures to replace the wooden case textures in the previous lesson.
If (textureimage [0] = loadbmp ("Data/glass.bmp"); // load the glass Bitmap (modified)
InInitgl ()Add the following two lines to the code snippet. The first line draws the object in full brightness and performs a 50% Alpha mixture (translucent) on it ). When the hybrid option is enabled, this object will produce a 50% transparent effect. Set the hybrid type in the second row.
Supplement of Rui Martins: the alpha channel value is 0.0, which means the object material is completely transparent. 1.0 means that it is completely opaque.
Glcolor4f (1.0f, 1.0f, 1.0f, 0.5f); // brightness, 50% Alpha mixture (new) glblendfunc (gl_src_alpha, gl_one ); // semi-transparent hybrid function based on the Alpha Channel value of the source pixel (new)
Find the following code snippet near the end of Lesson 7.
If (Keys [vk_left]) // is the left direction key pressed? {Yspeed-= 0.01f; // If yes, reduce yspeed}
Next, we add the following code. These lines monitor whether keys B are pressed. If yes, check whether the mixed options are enabled. Set it to the opposite state.
If (Keys ['B'] &! BP) // is BP false when B Jian is pressed? {BP = true; // If yes, BP is set to true blend =! Blend; // switch the true/false of the mixed options if (blend) // is the mixed option enabled? {Glenable (gl_blend); // enable the hybrid gldisable (gl_depth_test); // disable the deep test} else // otherwise {gldisable (gl_blend); // disable the hybrid glable (gl_depth_test ); // open the deep test} If (! Keys ['B']) // is the key B released? {BP = false; // If yes, BP is set to false}

But how can we specify the color of the mixture when texture textures are used? It is very simple. When adjusting the texture mode, the color of each pixel in the texture is obtained by multiplying the alpha channel parameter with the current pixel color. For example, if the drawn color is (0.5, 0.6, 0.4), we will multiply the color (0.5, 0.6, 0.4, 0.2) (when the Alpha parameter is not specified, 0 by default ).
That's it! It is really easy to implement Alpha mixing Using OpenGL!

Original article note (11/13/99)

I (nehe) mixed color code was modified to make the displayed object look more realistic. At the same time, the Alpha parameter is used to mix the source pixel and the target pixel, which will make the artificial trace of the object very obvious. It will make the back of the object look darker along the side. Basically, objects look weird. The color mixing method I used may not be the best, but it does work. After the light source is enabled, the object looks lifelike. Thanks to the original code provided by Tom, the mixed color method is correct, but the object does not look as attractive as expected :)
The code is modified again because it is on some graphics cards.Gldepthmask ()Addressing issues exist in functions. This command does not seem very effective when enabling or disabling the deep buffer test on some cards, so I have converted the code for enabling or disabling the deep buffer test into an old-fashionedGlenableAndGldisable.

Alpha mixing of texture maps

The Alpha parameter used for texture maps can be read from the problem maps like the color. The method is as follows. You need to obtain the Alpha parameter while loading the required material. ThenGlteximage2d ()UseGl_rgbaColor format.

"Translator: the document of nehe seems very simple and arrogant. But how many other experts have you ever seen? I am not a master. I hope you are sincere .』
Below is the source code download link. Good luck!

Tom stanis

* Download visual c ++ code for this lesson.

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.