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

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