Jeff Molofee - NeHe's OpenGL Tutorials

Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

(!LoadTGA(&textures[6], "Data/Ground.tga")) || // Load The Ground Texture

(!LoadTGA(&textures[7], "Data/Sky.tga")) || // Load The Sky Texture

(!LoadTGA(&textures[8], "Data/Crosshair.tga")) || // Load The Crosshair Texture

(!LoadTGA(&textures[9], "Data/Font.tga"))) // Load The Crosshair Texture

{

return FALSE; // If Loading Failed, Return False

}

If all of the images loaded and were successfully turned into textures, we can continue with initialization. The font texture is loaded, so it's safe to build our font. We do this by jumping to BuildFont().

We then set up OpenGL. The background color is set to black, the alpha is also set to 0.0f. The depth buffer is set up and enabled with less than or equal testing.

The glBlendFunc() is a VERY important line of code. We set the blend function to (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). This blends the object with whats on the screen using the alpha values stored in the objects texture. After setting the blend mode, we enable blending. We then enable 2D texture mapping, and finally, we enable GL_CULL_FACE. This removes the back face from each object ( no point in wasting cycles drawing something we can't see ). We draw all of our quads with a counter clockwise winding so the proper face is culled.

Earlier in the tutorial I talked about using the glAlphaFunc() instead of alpha blending. If you want to use the Alpha Function, comment out the 2 lines of blending code and uncomment the 2 lines under glEnable(GL_BLEND). You can also comment out the qsort() function in the InitObject() section of code.

The program should run ok, but the sky texture will not be there. The reason is because the sky texture has an alpha value of 0.5f. When I was talking about the Alpha Function earlier on, I mentioned that it only works with alpha values of 0 or 1. You will have to modify the alpha channel for the sky texture if you want it to appear! Again, if you decide to use the Alpha Function instead, you don't have to sort the objects. Both methods have the good points! Below is a quick quote from the SGI site:

"The alpha function discards fragments instead of drawing them into the frame buffer. Therefore sorting of the primitives is not necessary (unless some other mode like alpha blending is enabled). The disadvantage is that pixels must be completely opaque or completely transparent" .

BuildFont(); // Build Our Font Display List

glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background

glClearDepth(1.0f); // Depth Buffer Setup

glDepthFunc(GL_LEQUAL); // Type Of Depth Testing

glEnable(GL_DEPTH_TEST); // Enable Depth Testing

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Enable Alpha Blending (disable alpha testing)

glEnable(GL_BLEND); // Enable Blending (disable alpha testing)

// glAlphaFunc(GL_GREATER,0.1f); // Set Alpha Testing (disable blending)

// glEnable(GL_ALPHA_TEST); // Enable Alpha Testing (disable blending)

glEnable(GL_TEXTURE_2D); // Enable Texture Mapping

glEnable(GL_CULL_FACE); // Remove Back Face

At this point in the program, none of the objects have been defined. So we loop through all thirty objects calling InitObject() for each object.

for (int loop=0; loop<30; loop++) // Loop Through 30 Objects

InitObject(loop); // Initialize Each Object

return TRUE; // Return TRUE (Initialization Successful)

}

In our init code, we called BuildFont() which builds our 95 display lists. The following line of code deletes all 95 display lists before the program quits.

void Deinitialize(void) // Any User DeInitialization Goes Here

{

glDeleteLists(base, 95); // Delete All 95 Font Display Lists

}

Now for the tricky stuff… The code that does the actual selecting of the objects. The first line of code below allocates a buffer that we can use to store information about our selected objects into. The variable hits will hold the number of hits detected while in selection mode.

void Selection(void) // This Is Where Selection Is Done

{

GLuint buffer[512]; // Set Up A Selection Buffer

GLint hits; // The Number Of Objects That We Selected

In the code below, we check to see if the game is over (FALSE). If it is, there is no point in selecting anything, so we return (exit). If the game is still active (TRUE), we play a gunshot sound using the Playsound() command. The only time Selection() is called is when the mouse button has been pressed, and every time the button is pressed, we want to play the gunshot sound. The sound is played in async mode so that it doesn't halt the program while the sound is playing.

if (game) // Is Game Over?

return; // If So, Don't Bother Checking For Hits

PlaySound("data/shot.wav", NULL, SND_ASYNC); // Play Gun Shot Sound

Now we set up a viewport. viewport[] will hold the current x, y, length and width of the current viewport (OpenGL Window).

glGetIntegerv(GL_VIEWPORT, viewport) gets the current viewport boundries and stores them in viewport[]. Initially, the boundries are equal the the OpenGL window dimensions. glSelectBuffer(512, buffer) tells OpenGL to use buffer for it's selection buffer.

// The Size Of The Viewport. [0] Is , [1] Is , [2] Is , [3] Is

GLint viewport[4];

// This Sets The Array To The Size And Location Of The Screen Relative To The Window

glGetIntegerv(GL_VIEWPORT, viewport);

glSelectBuffer(512, buffer); // Tell OpenGL To Use Our Array For Selection

All of the code below is very important. The first line puts OpenGL in selection mode. In selection mode, nothing is drawn to the screen. Instead, information about objects rendered while in selection mode will be stored in the selection buffer.

Next we initialize the name stack by calling glInitNames() and glPushName(0). It's important to note that if the program is not in selection mode, a call to glPushName() will be ignored. Of course we are in selection mode, but it's something to keep in mind.

// Puts OpenGL In Selection Mode. Nothing Will Be Drawn. Object ID's and Extents Are Stored In The Buffer.

(void) glRenderMode(GL_SELECT);

glInitNames(); // Initializes The Name Stack

glPushName(0); // Push 0 (At Least One Entry) Onto The Stack

After preparing the name stack, we have to to restrict drawing to the area just under our crosshair. In order to do this we have to select the projection matrix. After selecting the projection matrix we push it onto the stack. We then reset the projection matrix using glLoadIdentity().

We restrict drawing using gluPickMatrix(). The first parameter is our current mouse position on the x-axis, the second parameter is the current mouse position on the y-axis, then the width and height of the picking region. Finally the current viewport[]. The viewport[] indicates the current viewport boundaries. mouse_x and mouse_y will be the center of the picking region.

glMatrixMode(GL_PROJECTION); // Selects The Projection Matrix

glPushMatrix(); // Push The Projection Matrix

glLoadIdentity(); // Resets The Matrix

// This Creates A Matrix That Will Zoom Up To A Small Portion Of The Screen, Where The Mouse Is.

gluPickMatrix((GLdouble) mouse_x, (GLdouble) (viewport[3]-mouse_y), 1.0f, 1.0f, viewport);

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «NeHe's OpenGL Tutorials»

Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Jeff Jacobson - Sleep Tight
Jeff Jacobson
Jeff Salyards - Veil of the Deserters
Jeff Salyards
Jeff LaSala - The Darkwood Mask
Jeff LaSala
Jeff Lindsay - Dexter's Final Cut
Jeff Lindsay
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «NeHe's OpenGL Tutorials»

Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x