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

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

Интервал:

Закладка:

Сделать

// Load An Uncompressed File

bool LoadUncompressedTGA(Texture *, char *, FILE *);

// Load A Compressed File

bool LoadCompressedTGA(Texture *, char *, FILE *);

Now, on to the cpp file, and the real brunt of the code. I will leave out some of the error message code and the like to make the tutorial shorter and more readable. You may look in the included file (link at the bottom of the article)

Right off the bat we have to include the file we just made so at the top of the file put.

#include "tga.h" // Include The Header We Just Made

We don't have to include any other files, because we included them inside our header we just completed.

The next thing we see is the first function, which is called LoadTGA(…).

// Load A TGA File!

bool LoadTGA(Texture * texture, char * filename) {

It takes two parameters. The first is a pointer to a Texture structure, which you must have declared in your code some where (see included example). The second parameter is a string that tells the computer where to find your texture file.

The first two lines of the function declare a file pointer and then open the file specified by "filename" which was passed to the function in the second parem for reading.

FILE * fTGA; // Declare File Pointer

fTGA = fopen(filename, "rb"); // Open File For Reading

The next few lines check to make sure that the file opened correctly.

if (fTGA == NULL) // If Here Was An Error

{

…Error code…

return false; // Return False

}

Next we try to read the first twelve bytes of the file and store them in out TGAHeader structure so we can check on the file type. If fread fails, the file is closed, an error displayed, and the function returns false.

// Attempt To Read The File Header

if (fread(&tgaheader, sizeof(TGAHeader), 1, fTGA) == 0) {

…Error code here…

return false; // Return False If It Fails

}

Next we try to determine what type of file it is by comparing our newly aquired header with our two hard coded ones. This will tell us if its compressed, uncompressed, or even if its the wrong file type. For this purpose we will use the memcmp(…) function.

// If The File Header Matches The Uncompressed Header

if (memcmp(uTGAcompare, &tgaheader, sizeof(tgaheader)) == 0) {

// Load An Uncompressed TGA

LoadUncompressedTGA(texture, filename, fTGA);

}

// If The File Header Matches The Compressed Header

else if(memcmp(cTGAcompare, &tgaheader, sizeof(tgaheader)) == 0) {

// Load A Compressed TGA

LoadCompressedTGA(texture, filename, fTGA);

} else // If It Doesn't Match Either One

{

…Error code here…

return false; // Return False

}

We will begin this section with the loading of an UNCOMPRESSED file. This function is heavily based on NeHe's code in lesson 25.

First thing we come to, as always, is the function header.

// Load An Uncompressed TGA!

bool LoadUncompressedTGA(Texture * texture, char * filename, FILE * fTGA) {

This function takes three parameters. The first two are the same as from LoadTGA, and are simply passed on. The third is the file pointer from the previous function so that we dont lose our place.

Next we try to read the next 6 bytes of the file, and store them in tga.header. If it fails, we run some error code, and return false.

// Attempt To Read Next 6 Bytes

if (fread(tga.header, sizeof(tga.header), 1, fTGA) == 0) {

…Error code here…

return false; // Return False

}

Now we have all the information we need to calculate the height, width and bpp of our image. We store it in both the texture and local structure.

texture->width = tga.header[1] * 256 + tga.header[0]; // Calculate Height

texture->height = tga.header[3] * 256 + tga.header[2]; // Calculate The Width

texture->bpp = tga.header[4]; // Calculate Bits Per Pixel

tga.Width = texture->width; // Copy Width Into Local Structure

tga.Height = texture->height; // Copy Height Into Local Structure

tga.Bpp = texture->bpp; // Copy Bpp Into Local Structure

Now we check to make sure that the height and width are at least one pixel, and that the bpp is either 24 or 32. If any of the values are outside their boundries we again display an error, close the file, and leave the function.

// Make Sure All Information Is Valid

if ((texture->width <= 0) || (texture->height <= 0) || ((texture->bpp != 24) && (texture->bpp !=32))) {

…Error code here…

return false; // Return False

}

Next we set the type of the image. 24 bit images are type GL_RGB and 32 bit images are type GL_RGBA

if (texture->bpp == 24) // Is It A 24bpp Image?

{

texture->type = GL_RGB; // If So, Set Type To GL_RGB

} else // If It's Not 24, It Must Be 32

{

texture->type = GL_RGBA; // So Set The Type To GL_RGBA

}

Now we caclulate the BYTES per pixel and the total size of the image data.

tga.bytesPerPixel = (tga.Bpp / 8); // Calculate The BYTES Per Pixel

// Calculate Memory Needed To Store Image

tga.imageSize = (tga.bytesPerPixel * tga.Width * tga.Height);

We need some place to store all that image data so we will use malloc to allocate the right amount of memory.

Then we check to make sure memory was allocated, and is not NULL. If there was an error, run error handling code.

// Allocate Memory

texture->imageData = (GLubyte *)malloc(tga.imageSize);

if (texture->imageData == NULL) // Make Sure It Was Allocated Ok

{

…Error code here…

return false; // If Not, Return False

}

Here we try to read all the image data. If we can't, we trigger error code again.

// Attempt To Read All The Image Data

if (fread(texture->imageData, 1, tga.imageSize, fTGA) != tga.imageSize) {

…Error code here…

return false; // If We Cant, Return False

}

TGA files store their image in reverse order than what OpenGL wants so we much change the format from BGR to RGB. To do this we swap the first and third bytes in every pixel.

Steve Thomas Adds: I've got a little speedup in TGA loading code. It concerns switching BGR into RGB using only 3 binary operations. Instead of using a temp variable you XOR the two bytes 3 times.

Then we close the file, and exit the function successfully.

// Start The Loop

for (GLuint cswap = 0; cswap < (int)tga.imageSize; cswap += tga.bytesPerPixel) {

// 1st Byte XOR 3rd Byte XOR 1st Byte XOR 3rd Byte

texture->imageData[cswap] ^= texture->imageData[cswap+2] ^= texture->imageData[cswap] ^= texture->imageData[cswap+2];

}

fclose(fTGA); // Close The File

return true; // Return Success

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

Интервал:

Закладка:

Сделать

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