資源簡介
opengl實現(xiàn)導入正方體obj文件+旋轉+平移+貼圖
圖形學作業(yè)C++
代碼片段和文件信息
#include?“ObjLoader.h“
using?namespace?std;
GLuint?texGround;
GLuint?texWall;
#define?BMP_Header_Length?54??//圖像數(shù)據(jù)在內存塊中的偏移量
string?filePath?=?“data/cube.obj“;
ObjLoader?objModel?=?ObjLoader(filePath);
static?float?c?=?3.1415926?/?180.0f;
static?float?r?=?1.0f;
static?int?degree?=?90;
static?int?oldPosY?=?-1;
static?int?oldPosX?=?-1;
static?float?up_down_y?=?0;
static?float?left_right_x?=?0;
static?float?mousemove1?=?r*cos(c*degree);
static?float?mousemove3?=?r*sin(c*degree);
static?float?headx?=?0.0f;
static?float?heady?=?0.0f;
static?float?headz?=?0.0f;
//?函數(shù)power_of_two用于判斷一個整數(shù)是不是2的整數(shù)次冪
int?power_of_two(int?n)
{
if?(n?<=?0)
return?0;
return?(n?&?(n?-?1))?==?0;
}
/*?函數(shù)load_texture
*?讀取一個BMP文件作為紋理
*?如果失敗,返回0,如果成功,返回紋理編號
*/
GLuint?load_texture(const?char*?file_name)
{
GLint?width?height?total_bytes;
GLubyte*?pixels?=?0;
GLuint?last_texture_ID?=?0?texture_ID?=?0;
//?打開文件,如果失敗,返回
FILE*?pFile?=?fopen(file_name?“rb“);
if?(pFile?==?0)
return?0;
//?讀取文件中圖象的寬度和高度
fseek(pFile?0x0012?SEEK_SET);
fread(&width?4?1?pFile);
fread(&height?4?1?pFile);
fseek(pFile?BMP_Header_Length?SEEK_SET);
//?計算每行像素所占字節(jié)數(shù),并根據(jù)此數(shù)據(jù)計算總像素字節(jié)數(shù)
{
GLint?line_bytes?=?width?*?3;
while?(line_bytes?%?4?!=?0)
++line_bytes;
total_bytes?=?line_bytes?*?height;
}
//?根據(jù)總像素字節(jié)數(shù)分配內存
pixels?=?(GLubyte*)malloc(total_bytes);
if?(pixels?==?0)
{
fclose(pFile);
return?0;
}
//?讀取像素數(shù)據(jù)
if?(fread(pixels?total_bytes?1?pFile)?<=?0)
{
free(pixels);
fclose(pFile);
return?0;
}
//?對就舊版本的兼容,如果圖象的寬度和高度不是的整數(shù)次方,則需要進行縮放
//?若圖像寬高超過了OpenGL規(guī)定的最大值,也縮放
{
GLint?max;
glGetIntegerv(GL_MAX_TEXTURE_SIZE?&max);
if?(!power_of_two(width)
||?!power_of_two(height)
||?width?>?max
||?height?>?max)
{
const?GLint?new_width?=?256;
const?GLint?new_height?=?256;?//?規(guī)定縮放后新的大小為邊長的正方形
GLint?new_line_bytes?new_total_bytes;
GLubyte*?new_pixels?=?0;
//?計算每行需要的字節(jié)數(shù)和總字節(jié)數(shù)
new_line_bytes?=?new_width?*?3;
while?(new_line_bytes?%?4?!=?0)
++new_line_bytes;
new_total_bytes?=?new_line_bytes?*?new_height;
//?分配內存
new_pixels?=?(GLubyte*)malloc(new_total_bytes);
if?(new_pixels?==?0)
{
free(pixels);
fclose(pFile);
return?0;
}
//?進行像素縮放
gluScaleImage(GL_RGB
width?height?GL_UNSIGNED_BYTE?pixels
new_width?new_height?GL_UNSIGNED_BYTE?new_pixels);
//?釋放原來的像素數(shù)據(jù),把pixels指向新的像素數(shù)據(jù),并重新設置width和height
free(pixels);
pixels?=?new_pixels;
width?=?new_width;
height?=?new_height;
}
}
//?分配一個新的紋理編號
glGenTextures(1?&texture_ID);
if?(texture_ID?==?0)
{
free(pixels);
fclose(pFile);
return?0;
}
//?綁定新的紋理,載入紋理并設置紋理參數(shù)
//?在綁定前,先獲得原來綁定的紋理編號,以便在最后進行恢復
GLint?lastTextureID?=?last_texture_ID;
glGetIntegerv(GL_TEXTURE_BINDING_2D?&lastTextureID);
glBindTexture(GL_TEXTURE_2D?texture_ID);
glTexParameteri(GL_TEXTURE_2D?GL_TEXTURE_MIN_FILTER?GL_LINEAR);
評論
共有 條評論