我一直在尝试将 3d 模型格式加载到 C++ 中,但我遇到了问题。一切都很好,除了 indicies 的短裤数组...当我尝试加载一个模型时,数组中的前 2 个空格是不正确的...如果我加载第二个模型;更多的短裤在模型数据中是错误的......
这是我的头文件:
#ifndef MODELDATA_H
#define MODELDATA_H
#include <GL/glu.h>
#include <string>
using namespace std;
class modelData
{
public:
modelData();
virtual ~modelData();
short m_vert_count;
short m_ind_count;
short m_tid;
GLfloat *m_verts;
GLfloat *m_tex;
GLint *m_ind;
void loadModel(string input);
void draw();
protected:
private:
};
#endif // MODELDATA_H
这是我的 cpp 文件:
#include "modelData.h"
#include <GL/glu.h>
#include <fstream>
#include <string.h>
#include <iostream>
using namespace std;
modelData::modelData()
{
//ctor
m_verts = NULL;
m_tex = NULL;
m_ind = NULL;
m_ind_count = 0;
m_vert_count = 0;
}
modelData::~modelData()
{
//dtor
delete[] m_verts;
delete[] m_tex;
delete[] m_ind;
m_ind_count = 0;
m_vert_count = 0;
}
void modelData::loadModel(string input)
{
short temp;
char *newInput = new char[input.size()+1];
newInput[input.size()]=0;
memcpy(newInput,input.c_str(),input.size());
ifstream a_file( newInput, ios::binary | ios::in );
delete newInput;
a_file.seekg( 0, ios::beg );
if ( ! a_file.read( reinterpret_cast<char*>( & m_vert_count ), sizeof( short ) ) )
{
cout << "Error reading from file: can't attain vertex buffer size" << endl;
return;
}
if ( ! a_file.read( reinterpret_cast<char*>( & m_ind_count ), sizeof( short ) ) )
{
cout << "Error reading from file: can't attain index buffer size" << endl;
return;
}
m_verts = new GLfloat[m_vert_count];
m_ind = new GLint[m_ind_count];
m_tex = new GLfloat[m_vert_count];
for (int i = 0; i < m_vert_count; i++)
{
if ( ! a_file.read( reinterpret_cast<char*>( & m_verts[i] ), sizeof( float ) ) )
{
cout << "Error reading from file: can't attain vertex buffer" << endl;
return;
}
}
for (int i = 0; i < ((m_vert_count)/3)*2; i++)
{
if ( ! a_file.read( reinterpret_cast<char*>( & m_tex[i] ), sizeof( float ) ) )
{
cout << "Error reading from file: can't attain texcoord buffer" << endl;
return;
}
}
for (int i = 0; i < m_ind_count; i++)
{
if ( ! a_file.read( reinterpret_cast<char*>( & m_ind[i] ), sizeof( short ) ) )
{
cout << "Error reading from file: can't attain index buffer" << endl;
return;
}
}
cout << m_vert_count << " " << m_ind_count << endl;
cout << "Model successfully loaded from " << input << " ...Jolly good." << endl;
}
void modelData::draw()
{
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT,0,m_verts);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2,GL_FLOAT,0,m_tex);
glDrawElements(GL_TRIANGLES,m_ind_count,GL_UNSIGNED_INT,m_ind);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
我希望代码不会太长或太乱,我真的不知道发生了什么……据我所知;m_verts[] 和 m_tex[] 看起来填充得很好,但是 m_ind[] 不断地通过数组弹出错误的数字......我是否错误地分配了数组?我不是在清理我应该清理的东西吗?
哦,我不认为这是导致问题的原因,但你会注意到我没有添加任何东西来进行大端或小端转换......这是因为我使用的英特尔机器似乎总是假设little endian 和我的 android 游戏引擎使用 little endian ......所以我认为这不是问题......
任何帮助或建议都会很棒。谢谢阅读。