Jump to content

  • Log In with Google      Sign In   
  • Create Account

lib3ds and texture mapping?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
7 replies to this topic

#1 Adam West   Members   -  Reputation: 219

Like
0Likes
Like

Posted 07 April 2012 - 09:37 PM

hello again!

i have fixed up a few problems on my 3ds loader using lib3ds, my only problem now is that i have no idea how to load a texture map onto the loaded model. do i have to use lib3ds Material or something like that?

3ds.h

#include "main.h"
#include "lib3ds/file.h"
#include "lib3ds/mesh.h"
#include "lib3ds/material.h"

class Object
{
public:
Object(const char* filename);
virtual ~Object();
  virtual void Draw() const;
virtual void CreateVBO();
void applyTexture(const char*texfilename);

protected:
void GetFaces();
unsigned int m_TotalFaces;
Lib3dsFile * m_model;

Lib3dsMesh* Mesh;
GLuint textureObject;
GLuint m_VertexVBO, m_NormalVBO, m_TexCoordVBO;
};

3ds.cpp
#include "3dsloader.h"
#include "shader.h"

Object::Object(const char* filename)
{
m_TotalFaces = 0;
m_model = lib3ds_file_load(filename);
// If loading the model failed, we throw an exception
if(!m_model)
{
  cout << ("Unable to load ", filename);
}
Lib3dsMesh* mesh = lib3ds_file_mesh_by_name(m_model,"filename");


}
Object::~Object()
{
if(m_model) // if the file isn't freed yet
  lib3ds_file_free(m_model); //free up memory
}

void Object::GetFaces()
{
m_TotalFaces = 0;
Lib3dsMesh * mesh;
// Loop through every mesh.
for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next)
{
  // Add the number of faces this mesh has to the total number of faces.
  m_TotalFaces += mesh->faces;
}   
}
void Object::CreateVBO()
{
  assert(m_model != NULL);
  // Calculate the number of faces we have in total
  GetFaces();
  // Allocate memory for our vertices and normals
  Lib3dsVector * vertices = new Lib3dsVector[m_TotalFaces * 3];
  Lib3dsVector * normals = new Lib3dsVector[m_TotalFaces * 3];
  Lib3dsTexel* texCoords = new Lib3dsTexel[m_TotalFaces * 3];
 
  Lib3dsMesh * mesh;
  unsigned int FinishedFaces = 0;
  // Loop through all the meshes
  for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next)
  {
  
lib3ds_mesh_calculate_normals(mesh, &normals[FinishedFaces*3]);
   // Loop through every face
   for(unsigned int cur_face = 0; cur_face < mesh->faces;cur_face++)
   {
  
    Lib3dsFace * face = &mesh->faceL[cur_face];
    for(unsigned int i = 0;i < 3;i++)
    {
	
	 if(mesh->texels)
	 {
	  memcpy(&texCoords[FinishedFaces*2 + i], mesh->texelL[face->points[ i ]], sizeof(Lib3dsTexel));
	 }   
	 memcpy(&vertices[FinishedFaces*3 + i], mesh->pointL[face->points[ i ]].pos, sizeof(Lib3dsVector));
   
    }
   
    FinishedFaces++;
   }
 
  }

  // Generate a Vertex Buffer Object and store it with our vertices
  glGenBuffers(1, &m_VertexVBO);
  glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, vertices, GL_STATIC_DRAW);
  // Generate another Vertex Buffer Object and store the normals in it
  glGenBuffers(1, &m_NormalVBO);
  glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, normals, GL_STATIC_DRAW);
  // Generate a third VBO and store the texture coordinates in it.
  glGenBuffers(1, &m_TexCoordVBO);
  glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsTexel) * 3 * m_TotalFaces, texCoords, GL_STATIC_DRAW);

  // Clean up our allocated memory
  delete vertices;
  delete normals;
  delete texCoords;
 
  // We no longer need lib3ds
  lib3ds_file_free(m_model);
  m_model = NULL;
}
void Object::applyTexture(const char*texfilename)
{
 
  textureObject = SOIL_load_OGL_texture(texfilename,SOIL_LOAD_AUTO,SOIL_CREATE_NEW_ID,SOIL_FLAG_MIPMAPS);
	  
    glBindTexture(GL_TEXTURE_2D,textureObject);// use our newest texture
}

void Object::Draw() const
{



// Enable vertex, normal and texture-coordinate arrays.
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); 



// Bind the VBO with the normals.
glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO);
// The pointer for the normals is NULL which means that OpenGL will use the currently bound VBO.
glNormalPointer(GL_FLOAT, 0, NULL);

glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO);	
glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO);
glVertexPointer(3, GL_FLOAT, 0, NULL);
// Render the triangles.
glDrawArrays(GL_TRIANGLES, 0, m_TotalFaces * 3);


glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);   
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

at the moment all of the texture co-ordinates are messed up, it looks like this:

Posted Image

the output should actually be a perfectly mapped pyramid with no black parts

Sponsor:

#2 Adam West   Members   -  Reputation: 219

Like
0Likes
Like

Posted 09 April 2012 - 10:29 PM

no one has any ideas??

#3 the_visualist   Members   -  Reputation: 168

Like
0Likes
Like

Posted 10 April 2012 - 01:00 AM

Just create a simple plane model, save it as .3ds and load it. Then see at which point the texture coordinates get messed up. It should be 0/0, 0/1, 1/1 etc. when you load it.
If you want to save yourself a lot of time, then forget about 3ds, its lacking things in too many ways. Try .obj for a simple format that also supports bigger meshes. Its also very easy to create your own loader for it.

#4 Adam West   Members   -  Reputation: 219

Like
0Likes
Like

Posted 10 April 2012 - 05:43 AM

thanks man!

#5 f1af   Members   -  Reputation: 100

Like
0Likes
Like

Posted 16 April 2012 - 05:00 AM

number of tex coord not equal numer of face. if tex coord on neighboring face is equal - both face has one texcoord.
for example, if you have default cube-object, you have 24 faces, but 8 vertexes and 8 texcoord.


	 1,1 | | 1,1
0,0 	 0,1 | | 0,1	   0,0  
-------------- --------------


this two face have 3 tex coord. not 6. 3 on both. somsing like that...

#6 Adam West   Members   -  Reputation: 219

Like
0Likes
Like

Posted 16 April 2012 - 05:07 AM

number of tex coord not equal numer of face. if tex coord on neighboring face is equal - both face has one texcoord.
for example, if you have default cube-object, you have 24 faces, but 8 vertexes and 8 texcoord.


	 1,1 | | 1,1
0,0 	 0,1 | | 0,1	   0,0  
-------------- --------------


this two face have 3 tex coord. not 6. 3 on both. somsing like that...




could you modify my code so it makes more sense. this could help me and many other people with this problem?

#7 f1af   Members   -  Reputation: 100

Like
0Likes
Like

Posted 16 April 2012 - 05:32 AM

it uogly, in the future I fix it function. but if call this function after load 3ds, tex coord will by fixed.

void WorkBase::vertexNoDifTexCoordExtract( SPtr<BaseMesh> baseMesh ) const
{
    SPtr<BaseSide> sptrSide;
    SPtr<BaseAI> sptrBaseAI;
    uint indexCount, indexOfVertex, pointCount = baseMesh->point()->count() / 8;
    
    char doneIndex[pointCount];
    memset( doneIndex, 0, pointCount*sizeof( char ) );
    
    for ( uint i = 0; baseMesh->side()->next( &i, &sptrSide ); )
    {
        for ( uint j = 0; sptrSide->arrayIndex()->next( &j, &sptrBaseAI ); )
        {
            indexCount = sptrBaseAI->index()->count();
            
            if (indexCount>64000) continue;
            
            for ( uint n = 0; n < indexCount; n++ )
            {
                indexOfVertex = *sptrBaseAI->index()->atRo( n );
                
                if ( !doneIndex[indexOfVertex] ) doneIndex[indexOfVertex] = 1;
                else
                {
                    for ( uint m = 0; m < 8; m++ )
                    {
                        if (( indexOfVertex*8 + m ) < baseMesh->point()->count() ) // TODO kastil', need normal fix
                        {
                            float varFloat = *baseMesh->point()->atRo( indexOfVertex * 8 + m );
                            baseMesh->point()->appendVar( varFloat );
                        }
                    }
                    
                    *sptrBaseAI->index()->atRw( n ) = baseMesh->point()->count() / 8 - 1;
                }
            }
        }
    }
    
}

AI - its Array Indexes.

If u intresting, if u need, I can give my code of load 3ds. Its class, inherit from some python-3ds-module-source-code, not lib3ds. In the future I wont use lib3ds. But now.. my uogly, but working code:



#include "drawlib/scene/loader_3ds.h"

#include "drawlib/scene/scene_manager.h"


namespace drawlib
{


Loader3DS::Loader3DS( SceneManager *sceneManager )
{
    m_sceneManager = sceneManager;
    m_forStreamSteckStart = 0;
    m_forStreamSteckEnd = 0;
    m_wasError = false;
    setIsSimple( false );
    reset();
}


Loader3DS::~Loader3DS()
{
}


void Loader3DS:<img src='http://public.gamedev.net//public/style_emoticons/<#EMO_DIR#>/tongue.png' class='bbc_emoticon' alt=':P' />_updatePersent()
{
    int persent = 1 + (( 100 * m_currentFileDevice->at() ) / m_currentFileDevice->size() );
    
    if ( m_sceneManager->jobManager()->isThreadOn() )
        setProgress( persent );
}


void Loader3DS::setWasErrorToFalse()
{
    m_wasError = false;
}


bool Loader3DS::getWasError() const
{
    return m_wasError;
}


void Loader3DS::load( SPtr<BaseMesh> baseMesh, QString fileName, QString *nameObject )
{
    if ( nameObject ) *nameObject = "3ds";
    
    m_sceneManager->storer()->mesh()->setHide( baseMesh, true );
    
    m_listForStreamBaseMesh.append( baseMesh );
    m_listForStreamFileName.append( fileName );
    
    m_sceneManager->jobManager()->doRun( this );
}


void Loader3DS::reset()
{
    JobThread::reset();
    
    // m_sceneManager=0; - not need
    
    m_baseAI.reset();
    m_baseSide.reset();
    m_baseMaterial.reset();
    m_baseMesh.reset();
    
    m_baseAIMaterial.reset();
    m_baseSideMaterial.reset();
    
    m_fileName = QString::null;
    m_pathToFile = QString::null;
    m_mapMaterial.clear();
    
    m_indexOffset = 0;
    m_version = 0;
    m_count_mapUV = 0;
    
    if ( m_forStreamSteckStart == m_forStreamSteckEnd )
    {
        m_forStreamSteckStart = 0;
        m_forStreamSteckEnd = 0;
        m_listForStreamBaseMesh.clear();
        m_listForStreamFileName.clear();
    }
}



/**************************************************************
 ************************ for QThread *************************
 *************************************************************/

void Loader3DS::startJob()
{
    m_baseMesh = *m_listForStreamBaseMesh.at( m_forStreamSteckStart );
    m_fileName = *m_listForStreamFileName.at( m_forStreamSteckStart );
    m_forStreamSteckStart++;
    
    setName( "load: \"" + QFileInfo( m_fileName ).fileName() + "\"" );
    
    m_baseMesh->reset();
    m_pathToFile = QFileInfo( m_fileName ).dirPath();
    // m_baseMesh->point()->setBlokSize( 250000 );
    
    if ( !ProcessFile( m_fileName.latin1() ) ) m_wasError = true;
    
    if ( m_version != 3 ) m_wasError = true;
}


void Loader3DS::endJob()
{
    m_baseMesh = *m_listForStreamBaseMesh.at( m_forStreamSteckEnd );
    m_forStreamSteckEnd++;
    
    m_sceneManager->workBase()->vertexNoDifTexCoordExtract( m_baseMesh );
    m_sceneManager->workBase()->normalize( m_baseMesh );
    
    m_baseMesh->update();
    uint textureId = 0;
    QValueList<uint> filter;
    
    for ( uint i = 0; m_baseMesh->side()->next( &i, &m_baseSide ); )
    {
        if ( !m_baseSide->getMaterialId() ) continue;
        
        m_baseMaterial = m_sceneManager->storer()->material()->idToSPtr( m_baseSide->getMaterialId() );
        textureId = m_baseMaterial->getTextureId();
        
        if ( !textureId ) continue;
        
        if ( filter.find( textureId ) != filter.end() ) continue;
        else filter.append( textureId );
        
        m_sceneManager->storer()->texture()->idToSPtr( textureId )->update();
    }
    
    m_sceneManager->storer()->mesh()->setHide( m_baseMesh, false );
    reset();
}



/**************************************************************
 ********************* Check correct 3ds **********************
 *************************************************************/

bool Loader3DS::UserVersion( uint version )
{
    m_version = version;
    
    if ( m_version != 3 ) return false;
    
    return true;
}



/**************************************************************
 *********************** Material list ************************
 *************************************************************/

void Loader3DS::UserMatName( const string name )
{
    uint id;
    BaseMaterial *baseMaterial;
    m_sceneManager->storer()->material()->create( baseMaterial, id );
    m_baseMaterial.set( baseMaterial );
    m_mapMaterial[name] = id;
}


void Loader3DS::UserMatColor( float c0, float c1, float c2, int flag )
{
    if ( flag == 1 ) m_baseMaterial->color()->setColor( c0 / 1.4f, c1 / 1.4f, c2 / 1.4f );
    else if ( flag == 2 ) m_baseMaterial->color()->setColorAmbient( c0, c1, c2 );
    else m_baseMaterial->color()->setColorSpecular( c0, c1, c2 );
}


void Loader3DS::UserMapFile( const string fileName )
{
    uint textureId;
    BaseTexture *baseTexture;
    SPtr<BaseTexture> baseTextureSPtr;
    
    m_sceneManager->storer()->texture()->create( baseTexture, textureId );
    baseTextureSPtr.set( baseTexture );
    
    if ( m_sceneManager->loaderImage()->load( baseTextureSPtr,
            m_pathToFile + "/" + QString( fileName ).lower() ) )
        m_baseMaterial->setTextureId( textureId );
        
    p_updatePersent();
}



/**************************************************************
 *************************** Vertex ***************************
 *************************************************************/

void Loader3DS::User3dVertCount( unsigned short count )
{
    count = 0;
    m_indexOffset = m_baseMesh->point()->count() / 8;
    m_count_mapUV = 0;
    
    p_updatePersent();
}


void Loader3DS::User3dVert( float x, float y, float z )
{
    m_baseMesh->point()->appendVar( 0 );
    m_baseMesh->point()->appendVar( 0 );
    
    m_baseMesh->point()->appendVar( 0 );
    m_baseMesh->point()->appendVar( 0 );
    m_baseMesh->point()->appendVar( 0 );
    
    m_baseMesh->point()->appendVar( x );
    m_baseMesh->point()->appendVar( y );
    m_baseMesh->point()->appendVar( z );
}


void Loader3DS::UserMapVertex( float u, float v )
{
    *m_baseMesh->point()->atRw(( m_indexOffset + m_count_mapUV )*8 + 0 ) = u;
    *m_baseMesh->point()->atRw(( m_indexOffset + m_count_mapUV )*8 + 1 ) = v;
    m_count_mapUV++;
}



/**************************************************************
 *************************** Index ****************************
 *************************************************************/

void Loader3DS::User3dFaceCount( unsigned short )
{
    m_baseSide = m_baseMesh->side()->createSPtr();
    m_baseAI = m_baseSide->arrayIndex()->createSPtr();
    m_baseAI->setMode( GL_TRIANGLES );
    m_indexForSmoothCount = 0;
    
    p_updatePersent();
}


void Loader3DS::User3dFace( unsigned short a, unsigned short b, unsigned short c, unsigned short )
{
    m_baseAI->index()->appendVar( a + m_indexOffset );
    m_baseAI->index()->appendVar( b + m_indexOffset );
    m_baseAI->index()->appendVar( c + m_indexOffset );
}


void Loader3DS::UserFaceSmoothList( uint Index )
{
    m_baseSide->appendSmoothFace( Index, m_indexForSmoothCount );
    m_indexForSmoothCount++;
}



/**************************************************************
 ********************* Material on side ***********************
 *************************************************************/

void Loader3DS::UserFaceMaterialName( string name )
{
    m_baseSideMaterial = m_baseMesh->side()->createSPtr();;
    m_baseAIMaterial = m_baseSideMaterial->arrayIndex()->createSPtr();
    m_baseAIMaterial->setMode( GL_TRIANGLES );
    m_baseSideMaterial->setMaterialId( m_mapMaterial[name] );
}


void Loader3DS::UserFaceMaterialNumber( int number )
{
    uint a = m_baseAI->index()->atRo( number * 3 )[0];
    uint b = m_baseAI->index()->atRo( number * 3 )[1];
    uint c = m_baseAI->index()->atRo( number * 3 )[2];
    
    m_baseAIMaterial->index()->appendVar( a );
    m_baseAIMaterial->index()->appendVar( b );
    m_baseAIMaterial->index()->appendVar( c );
    
    m_baseAI->index()->atRw( number*3 )[0] = ( uint ) - 1;
    m_baseAI->index()->atRw( number*3 )[1] = ( uint ) - 1;
    m_baseAI->index()->atRw( number*3 )[2] = ( uint ) - 1;
}


void Loader3DS::User3dFaceFinish()
{
    SPtr<BaseSide> oldBaseSide = m_baseSide;
    SPtr<BaseAI> oldBaseAI = m_baseAI;
    
    m_baseSide = m_baseMesh->side()->createSPtr();
    m_baseAI = m_baseSide->arrayIndex()->createSPtr();
    m_baseAI->setMode( GL_TRIANGLES );
    
    for ( uint i = 0, a = 0; i < oldBaseAI->index()->count(); i++ )
    {
        a = oldBaseAI->index()->atRo( i )[0];
        if ( a != ( uint ) - 1 ) m_baseAI->index()->appendVar( a );
    }
    
    m_baseMesh->side()->removeBySPtr( oldBaseSide );
    
    if ( !m_baseAI->index()->count() )
        m_baseMesh->side()->removeBySPtr( m_baseSide );
}


}



#8 f1af   Members   -  Reputation: 100

Like
0Likes
Like

Posted 16 April 2012 - 05:38 AM

e, e. whell come to hell.. %))




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS