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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

glShadeModel(GL_SMOOTH); // Enable Smooth Shading

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

glClearDepth(1.0f); // Depth Buffer Setup

glEnable(GL_DEPTH_TEST); // Enables Depth Testing

glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do

glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations

// Here we read read in the height map from the .raw file and put it in our

// g_HeightMap array. We also pass in the size of the .raw file (1024).

LoadRawFile("Data/Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap); // ( NEW )

return TRUE; // Initialization Went OK

}

This is used to index into our height map array. When ever we are dealing with arrays, we want to make sure that we don't go outside of them. To make sure that doesn't happen we use %. % will prevent our x / y values from exceeding MAX_SIZE – 1.

We check to make sure pHeightMap points to valid data, if not, we return 0.

Otherwise, we return the value stored at x, y in our height map. By now, you should know that we have to multiply y by the width of the image MAP_SIZE to move through the data. More on this below!

int Height(BYTE *pHeightMap, int X, int Y) // This Returns The Height From A Height Map Index

{

int x = X % MAP_SIZE; // Error Check Our x Value

int y = Y % MAP_SIZE; // Error Check Our y Value

if (!pHeightMap) return 0; // Make Sure Our Data Is Valid

We need to treat the single array like a 2D array. We can use the equation: index = (x + (y * arrayWidth) ). This is assuming we are visualizing it like: pHeightMap[x][y], otherwise it's the opposite: (y + (x * arrayWidth) ).

Now that we have the correct index, we will return the height at that index (data at x, y in our array).

return pHeightMap[x + (y * MAP_SIZE)]; // Index Into Our Height Array And Return The Height

}

Here we set the color for a vertex based on the height index. To make it darker, I start with –0.15f. We also get a ratio of the color from 0.0f to 1.0f by dividing the height by 256.0f. If there is no data this function returns without setting the color. If everything goes ok, we set the color to a shade of blue using glColor3f(0.0f, fColor, 0.0f). Try moving fColor to the red or green spots to change the color of the landscape.

void SetVertexColor(BYTE *pHeightMap, int x, int y) // This Sets The Color Value For A Particular Index

{ // Depending On The Height Index

if (!pHeightMap) return; // Make Sure Our Height Data Is Valid

float fColor = –0.15f + (Height(pHeightMap, x, y ) / 256.0f);

// Assign This Blue Shade To The Current Vertex

glColor3f(0.0f, 0.0f, fColor );

}

This is the code that actually draws our landscape. X and Y will be used to loop through the height map data. x, y and z will be used to render the quads making up the landscape.

As always, we check to see if the height map (pHeightMap) contains data. If not, we return without doing anything.

void RenderHeightMap(BYTE pHeightMap[]) // This Renders The Height Map As Quads

{

int X = 0, Y = 0; // Create Some Variables To Walk The Array With.

int x, y, z; // Create Some Variables For Readability

if (!pHeightMap) return; // Make Sure Our Height Data Is Valid

Since we can switch between lines and quads, we check our render state with the code below. If bRender = True, then we want to render polygons, otherwise we render lines.

if (bRender) // What We Want To Render

glBegin(GL_QUADS ); // Render Polygons

else

glBegin(GL_LINES); // Render Lines Instead

Next we actually need to draw the terrain from the height map. To do that, we just walk the array of height data and pluck out some heights to plot our points. If we could see this happening, it would draw the columns first (Y), then draw the rows. Notice that we have a STEP_SIZE. This determines how defined our height map is. The higher the STEP_SIZE, the more blocky the terrain looks, while the lower it gets, the more rounded (smooth) it becomes. If we set STEP_SIZE = 1 it would create a vertex for every pixel in the height map. I chose 16 as a decent size. Anything too much less gets to be insane and slow. Of course, you can increase the number when you get lighting in. Then vertex lighting would cover up the blocky shape. Instead of lighting, we just put a color value associated with every poly to simplify the tutorial. The higher the polygon, the brighter the color is.

for (X = 0; X < MAP_SIZE; X += STEP_SIZE) for (Y = 0; Y < MAP_SIZE; Y += STEP_SIZE) {

// Get The (X, Y, Z) Value For The Bottom Left Vertex

x = X;

y = Height(pHeightMap, X, Y );

z = Y;

// Set The Color Value Of The Current Vertex

SetVertexColor(pHeightMap, x, z);

glVertex3i(x, y, z); // Send This Vertex To OpenGL To Be Rendered

// Get The (X, Y, Z) Value For The Top Left Vertex

x = X;

y = Height(pHeightMap, X, Y + STEP_SIZE );

z = Y + STEP_SIZE ;

// Set The Color Value Of The Current Vertex

SetVertexColor(pHeightMap, x, z);

glVertex3i(x, y, z); // Send This Vertex To OpenGL To Be Rendered

// Get The (X, Y, Z) Value For The Top Right Vertex

x = X + STEP_SIZE;

y = Height(pHeightMap, X + STEP_SIZE, Y + STEP_SIZE );

z = Y + STEP_SIZE ;

// Set The Color Value Of The Current Vertex

SetVertexColor(pHeightMap, x, z);

glVertex3i(x, y, z); // Send This Vertex To OpenGL To Be Rendered

// Get The (X, Y, Z) Value For The Bottom Right Vertex

x = X + STEP_SIZE;

y = Height(pHeightMap, X + STEP_SIZE, Y );

z = Y;

// Set The Color Value Of The Current Vertex

SetVertexColor(pHeightMap, x, z);

glVertex3i(x, y, z); // Send This Vertex To OpenGL To Be Rendered

}

glEnd();

After we are done, we set the color back to bright white with an alpha value of 1.0f. If there were other objects on the screen, we wouldn't want them showing up BLUE :)

glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Reset The Color

}

For those of you who haven't used gluLookAt(), what it does is position your camera position, your view, and your up vector. Here we set the camera in a obscure position to get a good outside view of the terrain. In order to avoid using such high numbers, we would divide the terrain's vertices by a scale constant, like we do in glScalef() below.

The values of gluLookAt() are as follows: The first three numbers represent where the camera is positioned. So the first three values move the camera 212 units on the x-axis, 60 units on the y-axis and 194 units on the z-axis from our center point. The next 3 values represent where we want the camera to look. In this tutorial, you will notice while running the demo that we are looking a little to the left. We are also look down towards the landscape. 186 is to the left of 212 which gives us the look to the left, and 55 is lower than 60, which gives us the appearance that we are higher than the landscape looking at it with a slight tilt (seeing a bit of the top of it). The value of 171 is how far away from the camera the object is. The last three values tell OpenGL which direction represents up. Our mountains travel upwards on the y-axis, so we set the value on the y-axis to 1. The other two values are set at 0.

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

Интервал:

Закладка:

Сделать

Похожие книги на «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