source: trunk/src/formats/assimp_loader.cc @ 451

Last change on this file since 451 was 451, checked in by epyon, 10 years ago
  • math library started
File size: 15.3 KB
RevLine 
[395]1// Copyright (C) 2014-2015 ChaosForge Ltd
[248]2// http://chaosforge.org/
3//
[395]4// This file is part of Nova libraries.
5// For conditions of distribution and use, see copying.txt file in root folder.
[248]6
7#include "nv/formats/assimp_loader.hh"
[416]8
9#include "nv/interface/data_channel_access.hh"
[432]10#include "nv/stl/hash_store.hh"
[248]11#include "nv/lib/assimp.hh"
12
13using namespace nv;
14
[323]15const unsigned MAX_BONES = 64;
[250]16
[293]17struct assimp_plain_vtx
18{
19        vec3 position;
20        vec3 normal;
21        vec2 texcoord;
22        vec4 tangent;
23
24        assimp_plain_vtx() {}
25        assimp_plain_vtx( const vec3& v, const vec2& t, const vec3& n, const vec4& g )
26        {
27                position = v;
28                texcoord = t;
29                normal   = n;
30                tangent  = g;
31        }
32};
33
34struct assimp_skinned_vtx
35{
36        vec3  position;
37        vec3  normal;
38        vec2  texcoord;
39        vec4  tangent;
40        ivec4 boneindex;
41        vec4  boneweight;
42
43        assimp_skinned_vtx() {}
44        assimp_skinned_vtx( const vec3& v, const vec2& t, const vec3& n, const vec4& g )
45        {
46                position = v;
47                texcoord = t;
48                normal   = n;
49                tangent  = g;
50        }
51};
52
[410]53struct assimp_key_p  { float time; vec3 translation; };
[291]54struct assimp_key_r  { float time; quat rotation; };
55struct assimp_key_s  { float time; vec3 scale; };
56struct assimp_key_tr { transform tform; };
57
58
[425]59nv::assimp_loader::assimp_loader( string_table* strings, const string_view& a_ext, uint32 a_assimp_flags /*= 0 */ )
60        : mesh_loader( strings ), m_scene( nullptr ), m_mesh_count(0)
[250]61{
[284]62        m_ext   = a_ext;
63        m_assimp_flags = a_assimp_flags;
[277]64        if ( m_assimp_flags == 0 )
65        {
66                m_assimp_flags = (
67                        aiProcess_CalcTangentSpace                              | 
68                        aiProcess_GenSmoothNormals                              | 
69                        aiProcess_JoinIdenticalVertices                 |   
70                        aiProcess_ImproveCacheLocality                  | 
71                        aiProcess_LimitBoneWeights                              | 
72                        aiProcess_RemoveRedundantMaterials      | 
73                        aiProcess_SplitLargeMeshes                              | 
74                        aiProcess_Triangulate                                   | 
75                        aiProcess_GenUVCoords                   | 
76                        aiProcess_SortByPType                   | 
77                        aiProcess_FindDegenerates               | 
78                        aiProcess_FindInvalidData               | 
79                        0 );
80        }
81}
[284]82
83
[248]84bool nv::assimp_loader::load( stream& source )
85{
[292]86        load_assimp_library();
[406]87        if ( m_scene != nullptr ) aiReleaseImport( reinterpret_cast<const aiScene*>( m_scene ) );
[248]88        m_scene = nullptr;
89        m_mesh_count = 0;
[365]90        NV_LOG_NOTICE( "AssImp loading file..." );
[323]91        size_t size = source.size();
[248]92        char* data  = new char[ size ];
93        source.read( data, size, 1 );
[425]94        const aiScene* scene = aiImportFileFromMemory( data, size, m_assimp_flags, m_ext.data() );
[248]95
96        if( !scene)
97        {
[365]98                NV_LOG_ERROR( aiGetErrorString() );
[248]99                return false;
100        }
101        m_scene      = scene;
102        m_mesh_count = scene->mNumMeshes;
[365]103        NV_LOG_NOTICE( "Loading successfull" );
[248]104        return true;
105}
106
[416]107data_channel_set* nv::assimp_loader::release_mesh_data( size_t index /*= 0 */ )
[248]108{
109        if ( index >= m_mesh_count ) return nullptr;
[424]110        data_channel_set* result = data_channel_set_creator::create_set( 2 );
[287]111        load_mesh_data( result, index );
112        return result;
113}
[416]114void nv::assimp_loader::load_mesh_data( data_channel_set* data, size_t index )
[287]115{
[406]116        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[248]117        const aiMesh*  mesh  = scene->mMeshes[ index ];
118
119        bool skinned = mesh->mNumBones > 0;
[415]120
121        data_descriptor desc;
[248]122        if ( skinned )
[415]123                desc.initialize< assimp_skinned_vtx >();
[248]124        else
[415]125                desc.initialize< assimp_plain_vtx >();
[417]126        data_channel_set_creator maccess( data );
[425]127        const char* name = mesh->mName.data;
128        maccess.set_name( make_name( name ) );
[417]129        uint8*  cdata   = maccess.add_channel( desc, mesh->mNumVertices ).raw_data();
130        uint16* indices = reinterpret_cast<uint16*>( maccess.add_channel< index_u16 >( mesh->mNumFaces * 3 ).raw_data() );
[248]131
[332]132        if ( mesh->mTangents && mesh->mBitangents )
[415]133                for ( unsigned int i = 0; i < mesh->mNumVertices; i++ )
134                {
135                        vec3 v = assimp_vec3_cast( mesh->mVertices[i] );
136                        vec3 n = glm::normalize( assimp_vec3_cast( mesh->mNormals[i] ) );
137                        vec3 t = glm::normalize( assimp_vec3_cast( mesh->mTangents[i] ) );
138                        vec3 b = glm::normalize( assimp_vec3_cast( mesh->mBitangents[i] ) );
139                        vec2 s = assimp_st_cast( mesh->mTextureCoords[0][i] );
[248]140
[451]141                        vec3 t_i = glm::normalize( t - n * glm::dot( n, t ) );
[415]142                        float det = ( glm::dot( glm::cross( n, t ), b ) );
143                        det = ( det < 0.0f ? -1.0f : 1.0f );
144                        nv::vec4 vt( t_i[0], t_i[1], t_i[2], det );
145                        if ( skinned )
146                                reinterpret_cast<assimp_skinned_vtx*>( cdata )[i] = assimp_skinned_vtx( v, s, n, vt );
147                        else
148                                reinterpret_cast<assimp_plain_vtx*>( cdata )[i] = assimp_plain_vtx( v, s, n, vt );
149                }
[248]150
151        if ( skinned )
152        {
[413]153                assimp_skinned_vtx* vtx = reinterpret_cast< assimp_skinned_vtx* >( cdata );
[248]154                for (unsigned int m=0; m<mesh->mNumBones; m++)
155                {
156                        aiBone* bone  = mesh->mBones[m];
157                        for (unsigned int w=0; w<bone->mNumWeights; w++)
158                        {
159                                assimp_skinned_vtx& v = vtx[ bone->mWeights[w].mVertexId ];
160                                bool found = false;
[406]161                                for ( int i = 0 ; i < 4; ++i )
[248]162                                {
163                                        if ( v.boneweight[i] <= 0.0f )
164                                        {
[406]165                                                v.boneindex[i]  = int( m );
[248]166                                                v.boneweight[i] = bone->mWeights[w].mWeight;
167                                                found = true;
168                                                break;
169                                        }
170                                }
171                                NV_ASSERT( found, "Too many weights!" );
172                        }
173                }
174        }
175
176        for (unsigned int i=0; i<mesh->mNumFaces; i++)
177        {
178                const aiFace* face = &mesh->mFaces[i];
179                for (unsigned int j=0; j<face->mNumIndices; j++)
180                {
[406]181                        indices[ i*3 + j ] = uint16( face->mIndices[j] );
[248]182                }
183        }
[416]184
[248]185}
186
187nv::assimp_loader::~assimp_loader()
188{
[406]189        if ( m_scene != nullptr ) aiReleaseImport( reinterpret_cast<const aiScene*>( m_scene ) );
[248]190}
191
[427]192bool nv::assimp_loader::load_bones( size_t index, array_ref< data_channel_set* > bones )
[248]193{
194        if ( m_scene == nullptr ) return false;
[406]195        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[248]196        const aiMesh*  mesh  = scene->mMeshes[ index ];
197
198        for (unsigned int m=0; m<mesh->mNumBones; m++)
199        {
200                aiBone* bone   = mesh->mBones[m];
[293]201                mat4    offset = assimp_mat4_cast( bone->mOffsetMatrix );
[427]202                bones[m] = data_channel_set_creator::create_set( 0 );
203                data_channel_set_creator access( bones[m] );
[425]204                const char* name = bone->mName.data;
205                access.set_name( make_name( name ) );
[424]206                access.set_transform( offset );
[248]207        }
208        return true;
209}
210
211void nv::assimp_loader::scene_report() const
212{
[406]213        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[248]214        if ( scene == nullptr ) return;
215
[365]216        NV_LOG_NOTICE( "------------------------" );
217        NV_LOG_NOTICE( "Texture   count - ", scene->mNumTextures );
218        NV_LOG_NOTICE( "Animation count - ", scene->mNumAnimations );
219        NV_LOG_NOTICE( "Material  count - ", scene->mNumMaterials );
220        NV_LOG_NOTICE( "Meshes    count - ", scene->mNumMeshes );
221        NV_LOG_NOTICE( "------------------------" );
[248]222
223        aiNode* root = scene->mRootNode;
224        if (root)
225        {
[365]226                NV_LOG_NOTICE( "Root node  - ", root->mName.data );
227                NV_LOG_NOTICE( "  meshes   - ", root->mNumMeshes );
228                NV_LOG_NOTICE( "  children - ", root->mNumChildren );
[248]229        }
230        else
231        {
[365]232                NV_LOG_NOTICE( "No root node!" );
[248]233        }
[365]234        NV_LOG_NOTICE( "------------------------" );
[248]235
236        if ( scene->mNumMeshes > 0 )
237        {
238                for ( nv::uint32 mc = 0; mc < scene->mNumMeshes; mc++ )
239                {
240                        aiMesh* mesh = scene->mMeshes[mc];
241
[406]242                        NV_LOG_NOTICE( "Mesh #", mc, "   - ", string_view( static_cast<char*>( mesh->mName.data ) ) );
[365]243                        NV_LOG_NOTICE( "  bones   - ", mesh->mNumBones );
244                        NV_LOG_NOTICE( "  uvs     - ", mesh->mNumUVComponents[0] );
245                        NV_LOG_NOTICE( "  verts   - ", mesh->mNumVertices );
246                        NV_LOG_NOTICE( "  faces   - ", mesh->mNumFaces );
[248]247
[365]248                        //                      NV_LOG_NOTICE(  "Bones:" );
[248]249                        //                      for (unsigned int m=0; m<mesh->mNumBones; m++)
250                        //                      {
251                        //                              aiBone* bone  = mesh->mBones[m];
[365]252                        //                              NV_LOG_NOTICE( bone->mName.C_Str() );
[248]253                        //                      }
254                }
255        }
256        else
257        {
[365]258                NV_LOG_NOTICE( "No meshes!" );
[248]259        }
[365]260        NV_LOG_NOTICE( "------------------------" );
[248]261
262
263        //      if ( scene->mNumMaterials > 0 )
264        //      {
265        //              for (unsigned int m=0; m < scene->mNumMaterials; m++)
266        //              {
267        //                      int texIndex = 0;
268        //                      aiReturn texFound = aiReturn_SUCCESS;
269        //                      aiString path;  // filename
270        //                      while (texFound == aiReturn_SUCCESS)
271        //                      {
272        //                              texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
[365]273        //                              NV_LOG_NOTICE( "  material - ", path.data );
[248]274        //                              texIndex++;
275        //                      }
276        //              }
277        //      }
278        //      else
279        //      {
[365]280        //              NV_LOG_NOTICE( "No materials" );
[248]281        //      }
[365]282        //      NV_LOG_NOTICE( "------------------------" );
[248]283
284}
285
[416]286mesh_nodes_data* nv::assimp_loader::release_merged_bones( data_channel_set* meshes )
[248]287{
[406]288        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[427]289        mesh_nodes_data* result = new mesh_nodes_data( make_name( "bones" ) );
[432]290        hash_store< shash64, uint16 > names;
[291]291        for ( unsigned int m = 0; m < m_mesh_count; ++m )
[248]292        {
[323]293                uint16 translate[MAX_BONES];
[427]294                vector< data_channel_set* > bones;
[291]295                const aiMesh*  mesh  = scene->mMeshes[ m ];
296                if ( mesh->mNumBones != 0 )
[248]297                {
[291]298                        bones.resize( mesh->mNumBones );
299                        load_bones( m, bones );
300                        for ( unsigned int b = 0; b < mesh->mNumBones; ++b )
301                        {
[248]302
[427]303                                data_channel_set* bone = bones[b];
304                                auto iname = names.find( bone->get_name() );
[291]305                                if ( iname == names.end() )
306                                {
[428]307                                        NV_ASSERT( result->size() < MAX_BONES, "Too many bones to merge!" );
308                                        uint16 index = uint16( result->size() );
[427]309                                        result->push_back( bone );
310                                        names[ bone->get_name() ] = index;
[291]311                                        translate[b] = index;
312                                }
313                                else
314                                {
[323]315                                        translate[b] = iname->second;
[291]316                                }
[248]317                        }
[291]318                        if ( m > 0 && bones.size() > 0 )
[248]319                        {
[417]320                                data_channel_access< assimp_skinned_vtx > channel( const_cast< raw_data_channel* >( meshes[m].get_channel(0) ) );
[413]321                                for ( unsigned v = 0; v < channel.size(); ++v )
[291]322                                {
[413]323                                        assimp_skinned_vtx& vertex = channel.data()[v];
[248]324
[406]325                                        for ( int i = 0 ; i < 4; ++i)
[248]326                                        {
[291]327                                                if ( vertex.boneweight[i] > 0.0f )
328                                                {
[406]329                                                        vertex.boneindex[i] = int( translate[vertex.boneindex[i]] );
[291]330                                                }
[248]331                                        }
332                                }
333                        }
[291]334                }       
[248]335        }
[427]336
337        return result;
[248]338}
339
[294]340mesh_nodes_data* nv::assimp_loader::release_mesh_nodes_data( size_t index /*= 0*/ )
[249]341{
342        if ( m_scene == nullptr ) return nullptr;
[406]343        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[291]344        if ( scene->mRootNode == nullptr || scene->mAnimations == nullptr || scene->mAnimations[index] == nullptr) return nullptr;
[249]345
346        const aiNode*      root = scene->mRootNode;
[291]347        const aiAnimation* anim = scene->mAnimations[index];
[249]348
[291]349        uint32 count = count_nodes( scene->mRootNode );
[249]350
[406]351        uint16 frame_rate     = static_cast<uint16>( anim->mTicksPerSecond );
352        float  duration       = static_cast<float>( anim->mDuration );
[293]353        bool   flat           = false;
[287]354
[427]355        data_channel_set** temp = new data_channel_set*[ count ];
356        array_ref< data_channel_set* > temp_ref( temp, count );
357        load_node( index, temp_ref, root, 0, -1 );
[291]358
[427]359        mesh_nodes_data* result = new mesh_nodes_data( make_name( static_cast<const char*>( anim->mName.data ) ), frame_rate, duration, flat );
360        for ( auto set : temp_ref )
361        {
362                result->push_back( set );
363        }
364        delete temp;
365        return result;
[249]366}
367
368nv::uint32 nv::assimp_loader::count_nodes( const void* node ) const
369{
[406]370        const aiNode* ainode = reinterpret_cast< const aiNode* >( node );
[249]371        nv::uint32 count = 1;
372        for ( unsigned i = 0; i < ainode->mNumChildren; ++i )
373        {
374                count += count_nodes( ainode->mChildren[i] );
375        }
376        return count;
377}
378
[427]379nv::sint16 nv::assimp_loader::load_node( uint32 anim_id, array_ref< data_channel_set* > nodes, const void* vnode, sint16 this_id, sint16 parent_id )
[249]380{
[406]381        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
382        const aiNode*  node  = reinterpret_cast<const aiNode*>( vnode );
[425]383        string_view name( static_cast< const char* >( node->mName.data ) );
[291]384        const aiAnimation* anim  = scene->mAnimations[anim_id];
[249]385        const aiNodeAnim*  anode = nullptr;
386
387        for ( unsigned i = 0 ; i < anim->mNumChannels ; i++ )
388        {
389                anode = anim->mChannels[i];
[425]390                if ( string_view( static_cast< const char* >( anode->mNodeName.data ) ) == name ) break;
[249]391                anode = nullptr;
392        }
393
[427]394        nodes[ this_id ] = anode ? create_keys( anode ) : data_channel_set_creator::create_set( 0 );
[249]395
[427]396        data_channel_set_creator access( nodes[this_id] );
[425]397        access.set_name( make_name( name ) );
[424]398        access.set_parent_id( parent_id );
[279]399        // This value is ignored by the create_transformed_keys, but needed by create_direct_keys!
400        // TODO: find a common solution!
401        //       This is bad because create_transformed_keys never uses node-transformations for
402        //       node's without keys
[424]403        access.set_transform( nv::assimp_mat4_cast( node->mTransformation ) );
404        if ( this_id == 0 ) access.set_transform( mat4() );
[249]405
[291]406        nv::sint16 next = this_id + 1;
[249]407        for ( unsigned i = 0; i < node->mNumChildren; ++i )
408        {
[293]409                next = load_node( anim_id, nodes, node->mChildren[i], next, this_id );
[249]410        }
[287]411
[249]412        return next;
413}
414
[427]415data_channel_set* nv::assimp_loader::create_keys( const void* vnode )
[249]416{
[406]417        const aiNodeAnim* node = reinterpret_cast< const aiNodeAnim* >( vnode );
[282]418        if ( node->mNumPositionKeys == 0 && node->mNumRotationKeys == 0 && node->mNumScalingKeys == 0 )
419        {
[427]420                return data_channel_set_creator::create_set( 0 );
[282]421        }
[427]422       
423        data_channel_set* set = data_channel_set_creator::create_set( 2 );
424        data_channel_set_creator key_set( set );
[249]425
[417]426        assimp_key_p* pchannel = key_set.add_channel< assimp_key_p >( node->mNumPositionKeys ).data();
427        assimp_key_r* rchannel = key_set.add_channel< assimp_key_r >( node->mNumRotationKeys ).data();
428//      assimp_key_s* schannel = key_set.add_channel< assimp_key_s >( node->mNumScalingKeys ).data();
[282]429
[249]430        for ( unsigned np = 0; np < node->mNumPositionKeys; ++np )
431        {
[410]432                pchannel[np].time        = static_cast<float>( node->mPositionKeys[np].mTime );
433                pchannel[np].translation = assimp_vec3_cast(node->mPositionKeys[np].mValue);
[249]434        }
435        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
436        {
[406]437                rchannel[np].time     = static_cast<float>( node->mRotationKeys[np].mTime );
[293]438                rchannel[np].rotation = assimp_quat_cast(node->mRotationKeys[np].mValue );
[249]439        }
[287]440//      if ( node->mNumScalingKeys > 0 )
441//      {
[451]442//              vec3 scale_vec0 = assimp_vec3_cast( node->mScalingKeys[0].mValue );
443//              float scale_value   = glm::length( math::abs( scale_vec0 - vec3(1,1,1) ) );
[287]444//              if ( node->mNumScalingKeys > 1 || scale_value > 0.001 )
445//              {
446//                      NV_LOG( nv::LOG_WARNING, "scale key significant!" );
447//                      for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
448//                      {
449//                              schannel[np].time  = (float)node->mScalingKeys[np].mTime;
450//                              schannel[np].scale = assimp_vec3_cast(node->mScalingKeys[np].mValue);
451//                      }
452//              }
453//              else
454//              {
455//                      schannel[0].time  = (float)node->mScalingKeys[0].mTime;
456//                      schannel[0].scale = assimp_vec3_cast(node->mScalingKeys[0].mValue);
457//              }
458//      }
[427]459        return set;
[287]460}
461
462mesh_data_pack* nv::assimp_loader::release_mesh_data_pack()
463{
[291]464        if ( m_scene == nullptr || m_mesh_count == 0 ) return nullptr;
[406]465        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[291]466        bool has_bones = false;
[424]467        data_channel_set* meshes = data_channel_set_creator::create_set_array( m_mesh_count, 2 );
[291]468        for ( size_t m = 0; m < m_mesh_count; ++m )
[249]469        {
[291]470                const aiMesh* mesh = scene->mMeshes[ m ];
[425]471                data_channel_set_creator( &meshes[m] ).set_name( make_name( static_cast<const char*>( mesh->mName.data ) ) );
[291]472                if ( mesh->mNumBones > 0 ) has_bones = true;
473                load_mesh_data(&meshes[m],m);
[249]474        }
[291]475
[294]476        mesh_nodes_data* nodes = ( has_bones ? release_merged_bones( meshes ) : release_mesh_nodes_data(0) );
[291]477        return new mesh_data_pack( m_mesh_count, meshes, nodes );
[287]478}
[284]479
[376]480nv::size_t nv::assimp_loader::get_nodes_data_count() const
[287]481{
[291]482        if ( m_scene == nullptr ) return 0;
[406]483        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[291]484        return scene->mNumAnimations;   
[249]485}
486
[291]487
Note: See TracBrowser for help on using the repository browser.