четверг, 22 мая 2008 г.

Class for parsing 3ds file.

After googling I found information about 3ds format and proved that it is so simple.


// OGLObject.h
#pragma once

#define MAX_VERTEXES 80000
#define MAX_POLYGONS 80000
#define MAX_NAME_SIZE 20

typedef struct VertextTypeStruct {
float x;
float y;
float z;
} VertexType;

typedef struct PolygonTypeStruct {
int a;
int b;
int c;
} PolygonType;

typedef struct MapCoordinatesStruct {
float u;
float v;
} MapCoordinates;

//
// Create for one 3ds file
//
class OGLObject
{
public:
OGLObject();
~OGLObject();

char * name() const;
int id() const;
VertexType * vertexes( ) const;
PolygonType * polygons( ) const;

public:
int load3DS( char * filename );
int loadTexture( char * filename );
private:
char * m_name;

int m_countOfVertex;
int m_countOfPolygons;

VertexType * m_vertexes;
PolygonType * m_polygons;
MapCoordinates * m_mapCoordinates;

int m_idTexture;
};


// OGLObject.cpp
int OGLObject::load3DS(char *filename)
{
int i;
FILE * l_file = fopen( filename, "rb" );
if (l_file == NULL)
{
return 0;
} // File could't be found
unsigned short l_chunkId;
unsigned int l_chunkLength;
unsigned char l_char;
unsigned short l_quantity;
unsigned short l_faceFlags;

while( ftell( l_file ) < filelength( fileno( l_file ) ) )
{
fread( &l_chunkId, 2, 1, l_file );
fread( &l_chunkLength, 4, 1, l_file );

switch( l_chunkId )
{
case 0x4d4d: // MAIN CHUNK
break;
case 0x3d3d: // 3D EDITOR CHUNK
break;
case 0x4000: // OBJECT BLOCK
// Parse name of object
i = 0;
do
{
fread( &l_char, 1, 1, l_file );
m_name[i] = l_char;
i++;
} while (l_char != '\0' && i < 20);
break;
case 0x4100: // EMPTY chunk
break;
case 0x4110: // VERTICES LIST
fread( &l_quantity, sizeof( unsigned short ), 1, l_file );
m_countOfVertex = l_quantity;
for(i = 0; i < l_quantity; i++)
{
fread( &m_vertexes[i].x, sizeof( float ), 1, l_file );
fread( &m_vertexes[i].y, sizeof( float ), 1, l_file );
fread( &m_vertexes[i].z, sizeof( float ), 1, l_file );
}
break;
case 0x4120:
fread( &l_quantity, sizeof( unsigned short ), 1, l_file );
m_countOfPolygons = l_quantity;
for(i = 0; i < l_quantity; i++)
{
fread( &m_polygons[i].a, sizeof( unsigned short ), 1, l_file );
fread( &m_polygons[i].b, sizeof( unsigned short ), 1, l_file );
fread( &m_polygons[i].c, sizeof( unsigned short ), 1, l_file );
fread( &l_faceFlags, sizeof( float ), 1, l_file );
}
break;
case 0x4140:
fread ( &l_quantity, sizeof (unsigned short), 1, l_file);
for (i = 0; i < l_quantity; i++)
{
fread (&m_mapCoordinates[i].u, sizeof (float), 1, l_file);
fread (&m_mapCoordinates[i].v, sizeof (float), 1, l_file);
}
break;
default:
fseek( l_file, l_chunkLength - 6, SEEK_CUR );
}
}
fclose( l_file );
return 1;
}

Комментариев нет: