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

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

Интервал:

Закладка:

Сделать

};

No real reason to explain the code below. We are loading TGA images in this tutorial instead of bitmaps. The structure below is used to store image data, as well as information about the TGA image. Read the tutorial on loading TGA files if you need a detailed explanation of the code below.

typedef struct // Create A Structure

{

GLubyte *imageData; // Image Data (Up To 32 Bits)

GLuint bpp; // Image Color Depth In Bits Per Pixel.

GLuint width; // Image Width

GLuint height; // Image Height

GLuint texID; // Texture ID Used To Select A Texture

} TextureImage; // Structure Name

The following code sets aside room for our 10 textures and 30 objects. If you plan to add more objects to the game make sure you increase the value from 30 to however many objects you want.

TextureImage textures[10]; // Storage For 10 Textures

objects object[30]; // Storage For 30 Objects

I didn't want to limit the size of each object. I wanted the vase to be taller than the can, I wanted the bucket to be wider than the vase. To make life easy, I create a structure that holds the objects width (w) and height (h).

I then set the width and height of each object in the last line of code. To get the coke cans width, I would check size[3].w. The Blueface is 0, the Bucket is 1, and the Target is 2, etc. The width is represented by w. Make sense?

struct dimensions { // Object Dimensions

GLfloat w; // Object Width

GLfloat h; // Object Height

};

// Size Of Each Object: Blueface, Bucket, Target, Coke, Vase

dimensions size[5] = { {1.0f,1.0f}, {1.0f,1.0f}, {1.0f,1.0f}, {0.5f,1.0f}, {0.75f,1.5f} };

The following large section of code loads our TGA images and converts them to textures. It's the same code I used in lesson 25 so if you need a detailed description go back and read lesson 25.

I use TGA images because they are capable of having an alpha channel. The alpha channel tells OpenGL which parts of the image are transparent and which parts are opaque. The alpha channel is created in an art program, and is saved inside the .TGA image. OpenGL loads the image, and uses the alpha channel to set the amount of transparency for each pixel in the image.

bool LoadTGA(TextureImage *texture, char *filename) // Loads A TGA File Into Memory

{

GLubyte TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; // Uncompressed TGA Header

GLubyte TGAcompare[12]; // Used To Compare TGA Header

GLubyte header[6]; // First 6 Useful Bytes From The Header

GLuint bytesPerPixel; // Holds Number Of Bytes Per Pixel Used In The TGA File

GLuint imageSize; // Used To Store The Image Size When Setting Aside Ram

GLuint temp; // Temporary Variable

GLuint type=GL_RGBA; // Set The Default GL Mode To RBGA (32 BPP)

FILE *file = fopen(filename, "rb"); // Open The TGA File

if (file==NULL || // Does File Even Exist?

fread(TGAcompare, 1, sizeof(TGAcompare), file) != sizeof(TGAcompare) || // Are There 12 Bytes To Read?

memcmp(TGAheader, TGAcompare, sizeof(TGAheader)) != 0 || // Does The Header Match What We Want?

fread(header, 1, sizeof(header), file) != sizeof(header)) // If So Read Next 6 Header Bytes

{

if (file == NULL) // Does The File Even Exist? *Added Jim Strong*

return FALSE; // Return False

else // Otherwise

{

fclose(file); // If Anything Failed, Close The File

return FALSE; // Return False

}

}

texture->width = header[1] * 256 + header[0]; // Determine The TGA Width (highbyte*256+lowbyte)

texture->height = header[3] * 256 + header[2]; // Determine The TGA Height (highbyte*256+lowbyte)

if (texture->width <=0 || // Is The Width Less Than Or Equal To Zero

texture->height <=0 || // Is The Height Less Than Or Equal To Zero

(header[4]!=24 && header[4]!=32)) // Is The TGA 24 or 32 Bit?

{

fclose(file); // If Anything Failed, Close The File

return FALSE; // Return False

}

texture->bpp = header[4]; // Grab The TGA's Bits Per Pixel (24 or 32)

bytesPerPixel = texture->bpp/8; // Divide By 8 To Get The Bytes Per Pixel

imageSize = texture->width*texture->height*bytesPerPixel; // Calculate The Memory Required For The TGA Data

texture->imageData=(GLubyte *)malloc(imageSize); // Reserve Memory To Hold The TGA Data

if (texture->imageData==NULL || // Does The Storage Memory Exist?

fread(texture->imageData, 1, imageSize, file) != imageSize) // Does The Image Size Match The Memory Reserved?

{

if (texture->imageData!=NULL) // Was Image Data Loaded

free(texture->imageData); // If So, Release The Image Data

fclose(file); // Close The File

return FALSE; // Return False

}

for(GLuint i=0; i

{ // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)

temp=texture->imageData[i]; // Temporarily Store The Value At Image Data 'i'

texture->imageData[i] = texture->imageData[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte

texture->imageData[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)

}

fclose (file); // Close The File

// Build A Texture From The Data

glGenTextures(1, &texture[0].texID); // Generate OpenGL texture IDs

glBindTexture(GL_TEXTURE_2D, texture[0].texID); // Bind Our Texture

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtered

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtered

if (texture[0].bpp==24) // Was The TGA 24 Bits

{

type=GL_RGB; // If So Set The 'type' To GL_RGB

}

glTexImage2D(GL_TEXTURE_2D, 0, type, texture[0].width, texture[0].height, 0, type, GL_UNSIGNED_BYTE, texture[0].imageData);

return true; // Texture Building Went Ok, Return True

}

The 2D texture font code is the same code I have used in previous tutorials. However, there are a few small changes. The thing you will notice is that we are only generating 95 display lists. If you look at the font texture, you will see there are only 95 characters counting the space at the top left of the image. The second thing you will notice is we divide by 16.0f for cx and we only divide by 8.0f for cy. The reason we do this is because the font texture is 256 pixels wide, but only half as tall (128 pixels). So to calculate cx we divide by 16.0f and to calculate cy we divide by half that (8.0f).

If you do not understand the code below, go back and read through Lesson 17. The font building code is explained in detail in lesson 17!

GLvoid BuildFont(GLvoid) // Build Our Font Display List

{

base=glGenLists(95); // Creating 95 Display Lists

glBindTexture(GL_TEXTURE_2D, textures[9].texID); // Bind Our Font Texture

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

Интервал:

Закладка:

Сделать

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