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

Last change on this file since 424 was 424, checked in by epyon, 10 years ago
  • refactoring WIP! (compiles though - warnings on purpose)
File size: 15.1 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"
[392]10#include "nv/stl/unordered_map.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
[380]59nv::assimp_loader::assimp_loader( const std::string& a_ext, uint32 a_assimp_flags /*= 0 */ )
[293]60        : 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 );
94        const aiScene* scene = aiImportFileFromMemory( data, size, m_assimp_flags, m_ext.c_str() );
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 );
127        maccess.set_name( mesh->mName.data );
128        uint8*  cdata   = maccess.add_channel( desc, mesh->mNumVertices ).raw_data();
129        uint16* indices = reinterpret_cast<uint16*>( maccess.add_channel< index_u16 >( mesh->mNumFaces * 3 ).raw_data() );
[248]130
[332]131        if ( mesh->mTangents && mesh->mBitangents )
[415]132                for ( unsigned int i = 0; i < mesh->mNumVertices; i++ )
133                {
134                        vec3 v = assimp_vec3_cast( mesh->mVertices[i] );
135                        vec3 n = glm::normalize( assimp_vec3_cast( mesh->mNormals[i] ) );
136                        vec3 t = glm::normalize( assimp_vec3_cast( mesh->mTangents[i] ) );
137                        vec3 b = glm::normalize( assimp_vec3_cast( mesh->mBitangents[i] ) );
138                        vec2 s = assimp_st_cast( mesh->mTextureCoords[0][i] );
[248]139
[415]140                        glm::vec3 t_i = glm::normalize( t - n * glm::dot( n, t ) );
141                        float det = ( glm::dot( glm::cross( n, t ), b ) );
142                        det = ( det < 0.0f ? -1.0f : 1.0f );
143                        nv::vec4 vt( t_i[0], t_i[1], t_i[2], det );
144                        if ( skinned )
145                                reinterpret_cast<assimp_skinned_vtx*>( cdata )[i] = assimp_skinned_vtx( v, s, n, vt );
146                        else
147                                reinterpret_cast<assimp_plain_vtx*>( cdata )[i] = assimp_plain_vtx( v, s, n, vt );
148                }
[248]149
150        if ( skinned )
151        {
[413]152                assimp_skinned_vtx* vtx = reinterpret_cast< assimp_skinned_vtx* >( cdata );
[248]153                for (unsigned int m=0; m<mesh->mNumBones; m++)
154                {
155                        aiBone* bone  = mesh->mBones[m];
156                        for (unsigned int w=0; w<bone->mNumWeights; w++)
157                        {
158                                assimp_skinned_vtx& v = vtx[ bone->mWeights[w].mVertexId ];
159                                bool found = false;
[406]160                                for ( int i = 0 ; i < 4; ++i )
[248]161                                {
162                                        if ( v.boneweight[i] <= 0.0f )
163                                        {
[406]164                                                v.boneindex[i]  = int( m );
[248]165                                                v.boneweight[i] = bone->mWeights[w].mWeight;
166                                                found = true;
167                                                break;
168                                        }
169                                }
170                                NV_ASSERT( found, "Too many weights!" );
171                        }
172                }
173        }
174
175        for (unsigned int i=0; i<mesh->mNumFaces; i++)
176        {
177                const aiFace* face = &mesh->mFaces[i];
178                for (unsigned int j=0; j<face->mNumIndices; j++)
179                {
[406]180                        indices[ i*3 + j ] = uint16( face->mIndices[j] );
[248]181                }
182        }
[416]183
[248]184}
185
186nv::assimp_loader::~assimp_loader()
187{
[406]188        if ( m_scene != nullptr ) aiReleaseImport( reinterpret_cast<const aiScene*>( m_scene ) );
[248]189}
190
[383]191bool nv::assimp_loader::load_bones( size_t index, array_ref< mesh_node_data > bones )
[248]192{
193        if ( m_scene == nullptr ) return false;
[406]194        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[248]195        const aiMesh*  mesh  = scene->mMeshes[ index ];
196
197        for (unsigned int m=0; m<mesh->mNumBones; m++)
198        {
199                aiBone* bone   = mesh->mBones[m];
[293]200                mat4    offset = assimp_mat4_cast( bone->mOffsetMatrix );
[424]201                bones[m].data = data_channel_set_creator::create_set( 0 );
202                data_channel_set_creator access( bones[m].data );
203                access.set_name( hash_string< uint64 >( bone->mName.data ) );
204                access.set_transform( offset );
[248]205        }
206        return true;
207}
208
209void nv::assimp_loader::scene_report() const
210{
[406]211        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[248]212        if ( scene == nullptr ) return;
213
[365]214        NV_LOG_NOTICE( "------------------------" );
215        NV_LOG_NOTICE( "Texture   count - ", scene->mNumTextures );
216        NV_LOG_NOTICE( "Animation count - ", scene->mNumAnimations );
217        NV_LOG_NOTICE( "Material  count - ", scene->mNumMaterials );
218        NV_LOG_NOTICE( "Meshes    count - ", scene->mNumMeshes );
219        NV_LOG_NOTICE( "------------------------" );
[248]220
221        aiNode* root = scene->mRootNode;
222        if (root)
223        {
[365]224                NV_LOG_NOTICE( "Root node  - ", root->mName.data );
225                NV_LOG_NOTICE( "  meshes   - ", root->mNumMeshes );
226                NV_LOG_NOTICE( "  children - ", root->mNumChildren );
[248]227        }
228        else
229        {
[365]230                NV_LOG_NOTICE( "No root node!" );
[248]231        }
[365]232        NV_LOG_NOTICE( "------------------------" );
[248]233
234        if ( scene->mNumMeshes > 0 )
235        {
236                for ( nv::uint32 mc = 0; mc < scene->mNumMeshes; mc++ )
237                {
238                        aiMesh* mesh = scene->mMeshes[mc];
239
[406]240                        NV_LOG_NOTICE( "Mesh #", mc, "   - ", string_view( static_cast<char*>( mesh->mName.data ) ) );
[365]241                        NV_LOG_NOTICE( "  bones   - ", mesh->mNumBones );
242                        NV_LOG_NOTICE( "  uvs     - ", mesh->mNumUVComponents[0] );
243                        NV_LOG_NOTICE( "  verts   - ", mesh->mNumVertices );
244                        NV_LOG_NOTICE( "  faces   - ", mesh->mNumFaces );
[248]245
[365]246                        //                      NV_LOG_NOTICE(  "Bones:" );
[248]247                        //                      for (unsigned int m=0; m<mesh->mNumBones; m++)
248                        //                      {
249                        //                              aiBone* bone  = mesh->mBones[m];
[365]250                        //                              NV_LOG_NOTICE( bone->mName.C_Str() );
[248]251                        //                      }
252                }
253        }
254        else
255        {
[365]256                NV_LOG_NOTICE( "No meshes!" );
[248]257        }
[365]258        NV_LOG_NOTICE( "------------------------" );
[248]259
260
261        //      if ( scene->mNumMaterials > 0 )
262        //      {
263        //              for (unsigned int m=0; m < scene->mNumMaterials; m++)
264        //              {
265        //                      int texIndex = 0;
266        //                      aiReturn texFound = aiReturn_SUCCESS;
267        //                      aiString path;  // filename
268        //                      while (texFound == aiReturn_SUCCESS)
269        //                      {
270        //                              texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
[365]271        //                              NV_LOG_NOTICE( "  material - ", path.data );
[248]272        //                              texIndex++;
273        //                      }
274        //              }
275        //      }
276        //      else
277        //      {
[365]278        //              NV_LOG_NOTICE( "No materials" );
[248]279        //      }
[365]280        //      NV_LOG_NOTICE( "------------------------" );
[248]281
282}
283
[416]284mesh_nodes_data* nv::assimp_loader::release_merged_bones( data_channel_set* meshes )
[248]285{
[406]286        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[383]287        vector< mesh_node_data > final_bones;
[420]288        unordered_map< uint64, uint16 > names;
[291]289        for ( unsigned int m = 0; m < m_mesh_count; ++m )
[248]290        {
[323]291                uint16 translate[MAX_BONES];
[383]292                vector< mesh_node_data > bones;
[291]293                const aiMesh*  mesh  = scene->mMeshes[ m ];
294                if ( mesh->mNumBones != 0 )
[248]295                {
[291]296                        bones.resize( mesh->mNumBones );
297                        load_bones( m, bones );
298                        for ( unsigned int b = 0; b < mesh->mNumBones; ++b )
299                        {
[248]300
[291]301                                mesh_node_data& bone = bones[b];
[424]302                                auto iname = names.find( bone.data->get_name() );
[291]303                                if ( iname == names.end() )
304                                {
305                                        NV_ASSERT( final_bones.size() < MAX_BONES, "Too many bones to merge!" );
[406]306                                        uint16 index = uint16( final_bones.size() );
[291]307                                        final_bones.push_back( bone );
[424]308                                        names[ bone.data->get_name() ] = index;
[291]309                                        translate[b] = index;
310                                }
311                                else
312                                {
[323]313                                        translate[b] = iname->second;
[291]314                                }
[248]315                        }
[291]316                        if ( m > 0 && bones.size() > 0 )
[248]317                        {
[417]318                                data_channel_access< assimp_skinned_vtx > channel( const_cast< raw_data_channel* >( meshes[m].get_channel(0) ) );
[413]319                                for ( unsigned v = 0; v < channel.size(); ++v )
[291]320                                {
[413]321                                        assimp_skinned_vtx& vertex = channel.data()[v];
[248]322
[406]323                                        for ( int i = 0 ; i < 4; ++i)
[248]324                                        {
[291]325                                                if ( vertex.boneweight[i] > 0.0f )
326                                                {
[406]327                                                        vertex.boneindex[i] = int( translate[vertex.boneindex[i]] );
[291]328                                                }
[248]329                                        }
330                                }
331                        }
[291]332                }       
[248]333        }
[291]334        mesh_node_data* bones = new mesh_node_data[ final_bones.size() ];
[392]335        raw_copy( final_bones.begin(), final_bones.end(), bones );
[423]336        int name_;
337        return new mesh_nodes_data( /*"bones"*/0, final_bones.size(), bones );
[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 );
350        mesh_node_data* data    = new mesh_node_data[count];
[249]351
[406]352        uint16 frame_rate     = static_cast<uint16>( anim->mTicksPerSecond );
353        float  duration       = static_cast<float>( anim->mDuration );
[293]354        bool   flat           = false;
[287]355
[293]356        load_node( index, data, root, 0, -1 );
[291]357
[423]358        int name;
359        return new mesh_nodes_data( /*anim->mName.data*/0, count, data, frame_rate, duration, flat );
[249]360}
361
362nv::uint32 nv::assimp_loader::count_nodes( const void* node ) const
363{
[406]364        const aiNode* ainode = reinterpret_cast< const aiNode* >( node );
[249]365        nv::uint32 count = 1;
366        for ( unsigned i = 0; i < ainode->mNumChildren; ++i )
367        {
368                count += count_nodes( ainode->mChildren[i] );
369        }
370        return count;
371}
372
[293]373nv::sint16 nv::assimp_loader::load_node( uint32 anim_id, mesh_node_data* nodes, const void* vnode, sint16 this_id, sint16 parent_id )
[249]374{
[406]375        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
376        const aiNode*  node  = reinterpret_cast<const aiNode*>( vnode );
[380]377        std::string name( node->mName.data );
[291]378        const aiAnimation* anim  = scene->mAnimations[anim_id];
[249]379        const aiNodeAnim*  anode = nullptr;
380
381        for ( unsigned i = 0 ; i < anim->mNumChannels ; i++ )
382        {
383                anode = anim->mChannels[i];
384                if ( std::string( anode->mNodeName.data ) == name ) break;
385                anode = nullptr;
386        }
387
[291]388        mesh_node_data& a_data = nodes[ this_id ];
[249]389
[424]390        if (anode)
391                create_keys( &a_data, anode );
392        else
393                a_data.data = data_channel_set_creator::create_set( 0 );
394
395        data_channel_set_creator access( a_data.data );
396        access.set_name( hash_string< uint64 >( name.c_str() ) );
397        access.set_parent_id( parent_id );
[279]398        // This value is ignored by the create_transformed_keys, but needed by create_direct_keys!
399        // TODO: find a common solution!
400        //       This is bad because create_transformed_keys never uses node-transformations for
401        //       node's without keys
[424]402        access.set_transform( nv::assimp_mat4_cast( node->mTransformation ) );
403        if ( this_id == 0 ) access.set_transform( mat4() );
[249]404
[291]405        nv::sint16 next = this_id + 1;
[249]406        for ( unsigned i = 0; i < node->mNumChildren; ++i )
407        {
[293]408                next = load_node( anim_id, nodes, node->mChildren[i], next, this_id );
[249]409        }
[287]410
[249]411        return next;
412}
413
[293]414void nv::assimp_loader::create_keys( mesh_node_data* data, const void* vnode )
[249]415{
[406]416        const aiNodeAnim* node = reinterpret_cast< const aiNodeAnim* >( vnode );
[282]417        if ( node->mNumPositionKeys == 0 && node->mNumRotationKeys == 0 && node->mNumScalingKeys == 0 )
418        {
419                return;
420        }
[249]421
[424]422        data->data = data_channel_set_creator::create_set( 2 );
[419]423        data_channel_set_creator key_set( data->data );
[413]424
[417]425        assimp_key_p* pchannel = key_set.add_channel< assimp_key_p >( node->mNumPositionKeys ).data();
426        assimp_key_r* rchannel = key_set.add_channel< assimp_key_r >( node->mNumRotationKeys ).data();
427//      assimp_key_s* schannel = key_set.add_channel< assimp_key_s >( node->mNumScalingKeys ).data();
[282]428
[249]429        for ( unsigned np = 0; np < node->mNumPositionKeys; ++np )
430        {
[410]431                pchannel[np].time        = static_cast<float>( node->mPositionKeys[np].mTime );
432                pchannel[np].translation = assimp_vec3_cast(node->mPositionKeys[np].mValue);
[249]433        }
434        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
435        {
[406]436                rchannel[np].time     = static_cast<float>( node->mRotationKeys[np].mTime );
[293]437                rchannel[np].rotation = assimp_quat_cast(node->mRotationKeys[np].mValue );
[249]438        }
[287]439//      if ( node->mNumScalingKeys > 0 )
440//      {
441//              nv::vec3 scale_vec0 = assimp_vec3_cast( node->mScalingKeys[0].mValue );
442//              float scale_value   = glm::length( glm::abs( scale_vec0 - nv::vec3(1,1,1) ) );
443//              if ( node->mNumScalingKeys > 1 || scale_value > 0.001 )
444//              {
445//                      NV_LOG( nv::LOG_WARNING, "scale key significant!" );
446//                      for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
447//                      {
448//                              schannel[np].time  = (float)node->mScalingKeys[np].mTime;
449//                              schannel[np].scale = assimp_vec3_cast(node->mScalingKeys[np].mValue);
450//                      }
451//              }
452//              else
453//              {
454//                      schannel[0].time  = (float)node->mScalingKeys[0].mTime;
455//                      schannel[0].scale = assimp_vec3_cast(node->mScalingKeys[0].mValue);
456//              }
457//      }
[417]458
[287]459}
460
461mesh_data_pack* nv::assimp_loader::release_mesh_data_pack()
462{
[291]463        if ( m_scene == nullptr || m_mesh_count == 0 ) return nullptr;
[406]464        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[291]465        bool has_bones = false;
[424]466        data_channel_set* meshes = data_channel_set_creator::create_set_array( m_mesh_count, 2 );
[291]467        for ( size_t m = 0; m < m_mesh_count; ++m )
[249]468        {
[291]469                const aiMesh* mesh = scene->mMeshes[ m ];
[416]470                data_channel_set_creator( &meshes[m] ).set_name( mesh->mName.data );
[291]471                if ( mesh->mNumBones > 0 ) has_bones = true;
472                load_mesh_data(&meshes[m],m);
[249]473        }
[291]474
[294]475        mesh_nodes_data* nodes = ( has_bones ? release_merged_bones( meshes ) : release_mesh_nodes_data(0) );
[291]476        return new mesh_data_pack( m_mesh_count, meshes, nodes );
[287]477}
[284]478
[376]479nv::size_t nv::assimp_loader::get_nodes_data_count() const
[287]480{
[291]481        if ( m_scene == nullptr ) return 0;
[406]482        const aiScene* scene = reinterpret_cast<const aiScene*>( m_scene );
[291]483        return scene->mNumAnimations;   
[249]484}
485
[291]486
Note: See TracBrowser for help on using the repository browser.