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

Last change on this file since 376 was 376, checked in by epyon, 10 years ago
  • stl/assert.hh, stl/capi.hh, size_t independent
  • GCC 4.8 compatibility
  • using template usage
  • various minor changes
File size: 14.7 KB
Line 
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 "nv/io/std_stream.hh"
10#include "nv/gfx/mesh_creator.hh"
11#include "nv/lib/assimp.hh"
12
13using namespace nv;
14
15const unsigned MAX_BONES = 64;
16
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
53struct assimp_key_p  { float time; vec3 position; };
54struct assimp_key_r  { float time; quat rotation; };
55struct assimp_key_s  { float time; vec3 scale; };
56struct assimp_key_tr { transform tform; };
57
58
59nv::assimp_loader::assimp_loader( const string& a_ext, uint32 a_assimp_flags /*= 0 */ )
60        : m_scene( nullptr ), m_mesh_count(0)
61{
62        m_ext   = a_ext;
63        m_assimp_flags = a_assimp_flags;
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}
82
83
84bool nv::assimp_loader::load( stream& source )
85{
86        load_assimp_library();
87        if ( m_scene != nullptr ) aiReleaseImport( (const aiScene*)m_scene );
88        m_scene = nullptr;
89        m_mesh_count = 0;
90        NV_LOG_NOTICE( "AssImp loading file..." );
91        size_t size = source.size();
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        {
98                NV_LOG_ERROR( aiGetErrorString() );
99                return false;
100        }
101        m_scene      = scene;
102        m_mesh_count = scene->mNumMeshes;
103        NV_LOG_NOTICE( "Loading successfull" );
104        return true;
105}
106
107mesh_data* nv::assimp_loader::release_mesh_data( size_t index /*= 0 */ )
108{
109        if ( index >= m_mesh_count ) return nullptr;
110        mesh_data* result = new mesh_data;
111        load_mesh_data( result, index );
112        return result;
113}
114void nv::assimp_loader::load_mesh_data( mesh_data* data, size_t index )
115{
116        const aiScene* scene = (const aiScene*)m_scene;
117        const aiMesh*  mesh  = scene->mMeshes[ index ];
118        data->set_name( mesh->mName.data );
119
120        bool skinned = mesh->mNumBones > 0;
121        mesh_raw_channel* channel = nullptr;
122        if ( skinned )
123                channel = mesh_raw_channel::create< assimp_skinned_vtx >( mesh->mNumVertices );
124        else
125                channel = mesh_raw_channel::create< assimp_plain_vtx >( mesh->mNumVertices );
126
127        data->add_channel( channel );
128        if ( mesh->mTangents && mesh->mBitangents )
129        for (unsigned int i=0; i<mesh->mNumVertices; i++)
130        {
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 ] ) );
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                                        {
161                                                v.boneindex[i]  = (int)m;
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
172        mesh_raw_channel* ichannel = mesh_raw_channel::create_index( USHORT, mesh->mNumFaces * 3 );
173        data->add_channel( ichannel );
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
190bool nv::assimp_loader::load_bones( size_t index, std::vector< mesh_node_data >& bones )
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];
199                mat4    offset = assimp_mat4_cast( bone->mOffsetMatrix );
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;
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_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( "------------------------" );
220
221        aiNode* root = scene->mRootNode;
222        if (root)
223        {
224                NV_LOG_NOTICE( "Root node  - ", root->mName.data );
225                NV_LOG_NOTICE( "  meshes   - ", root->mNumMeshes );
226                NV_LOG_NOTICE( "  children - ", root->mNumChildren );
227        }
228        else
229        {
230                NV_LOG_NOTICE( "No root node!" );
231        }
232        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
240                        NV_LOG_NOTICE( "Mesh #", mc, "   - ", std::string( mesh->mName.data ) );
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 );
245
246                        //                      NV_LOG_NOTICE(  "Bones:" );
247                        //                      for (unsigned int m=0; m<mesh->mNumBones; m++)
248                        //                      {
249                        //                              aiBone* bone  = mesh->mBones[m];
250                        //                              NV_LOG_NOTICE( bone->mName.C_Str() );
251                        //                      }
252                }
253        }
254        else
255        {
256                NV_LOG_NOTICE( "No meshes!" );
257        }
258        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_NOTICE( "  material - ", path.data );
272        //                              texIndex++;
273        //                      }
274        //              }
275        //      }
276        //      else
277        //      {
278        //              NV_LOG_NOTICE( "No materials" );
279        //      }
280        //      NV_LOG_NOTICE( "------------------------" );
281
282}
283
284mesh_nodes_data* nv::assimp_loader::release_merged_bones( mesh_data* meshes )
285{
286        const aiScene* scene = (const aiScene*)m_scene;
287        std::vector< mesh_node_data > final_bones;
288        std::unordered_map< std::string, uint16 > names;
289        for ( unsigned int m = 0; m < m_mesh_count; ++m )
290        {
291                uint16 translate[MAX_BONES];
292                std::vector< mesh_node_data > bones;
293                const aiMesh*  mesh  = scene->mMeshes[ m ];
294                if ( mesh->mNumBones != 0 )
295                {
296                        bones.resize( mesh->mNumBones );
297                        load_bones( m, bones );
298                        for ( unsigned int b = 0; b < mesh->mNumBones; ++b )
299                        {
300
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!" );
306                                        uint16 index = (uint16)final_bones.size();
307                                        final_bones.push_back( bone );
308                                        names[ bone.name ] = index;
309                                        translate[b] = index;
310                                }
311                                else
312                                {
313                                        translate[b] = iname->second;
314                                }
315                        }
316                        if ( m > 0 && bones.size() > 0 )
317                        {
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];
323
324                                        for (uint32 i = 0 ; i < 4; ++i)
325                                        {
326                                                if ( vertex.boneweight[i] > 0.0f )
327                                                {
328                                                        vertex.boneindex[i] = (int)translate[vertex.boneindex[i]];
329                                                }
330                                        }
331                                }
332                        }
333                }       
334        }
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 );
338}
339
340mesh_nodes_data* nv::assimp_loader::release_mesh_nodes_data( size_t index /*= 0*/ )
341{
342        if ( m_scene == nullptr ) return nullptr;
343        const aiScene* scene = (const aiScene*)m_scene;
344        if ( scene->mRootNode == nullptr || scene->mAnimations == nullptr || scene->mAnimations[index] == nullptr) return nullptr;
345
346        const aiNode*      root = scene->mRootNode;
347        const aiAnimation* anim = scene->mAnimations[index];
348
349        uint32 count = count_nodes( scene->mRootNode );
350        mesh_node_data* data    = new mesh_node_data[count];
351
352        uint16 frame_rate     = (uint16)anim->mTicksPerSecond;
353        float  duration       = (float)anim->mDuration;
354        bool   flat           = false;
355
356        load_node( index, data, root, 0, -1 );
357
358        return new mesh_nodes_data( anim->mName.data, count, data, frame_rate, duration, flat );
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
372nv::sint16 nv::assimp_loader::load_node( uint32 anim_id, mesh_node_data* nodes, const void* vnode, sint16 this_id, sint16 parent_id )
373{
374        const aiScene* scene = (const aiScene*)m_scene;
375        const aiNode*  node  = (const aiNode*)vnode;
376        string name( node->mName.data );
377        const aiAnimation* anim  = scene->mAnimations[anim_id];
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
387        mesh_node_data& a_data = nodes[ this_id ];
388
389        a_data.name      = name;
390        a_data.target_id = -1;
391        a_data.parent_id = parent_id;
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
396        a_data.transform = nv::assimp_mat4_cast( node->mTransformation );
397        if (this_id == 0)
398                a_data.transform = mat4();
399        a_data.data = nullptr;
400
401        if (anode) create_keys( &a_data, anode );
402
403        nv::sint16 next = this_id + 1;
404        for ( unsigned i = 0; i < node->mNumChildren; ++i )
405        {
406                next = load_node( anim_id, nodes, node->mChildren[i], next, this_id );
407        }
408
409        return next;
410}
411
412void nv::assimp_loader::create_keys( mesh_node_data* data, const void* vnode )
413{
414        const aiNodeAnim* node = (const aiNodeAnim*)vnode;
415        if ( node->mNumPositionKeys == 0 && node->mNumRotationKeys == 0 && node->mNumScalingKeys == 0 )
416        {
417                return;
418        }
419
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 );
423        //key_raw_channel* raw_schannel = key_raw_channel::create<assimp_key_s>( node->mNumScalingKeys );
424        data->data->add_channel( raw_pchannel );
425        data->data->add_channel( raw_rchannel );
426        //data->data->add_channel( raw_schannel );
427        assimp_key_p* pchannel = ((assimp_key_p*)(raw_pchannel->data));
428        assimp_key_r* rchannel = ((assimp_key_r*)(raw_rchannel->data));
429        //assimp_key_s* schannel = ((assimp_key_s*)(raw_schannel->data));
430
431        for ( unsigned np = 0; np < node->mNumPositionKeys; ++np )
432        {
433                pchannel[np].time     = (float)node->mPositionKeys[np].mTime;
434                pchannel[np].position = assimp_vec3_cast(node->mPositionKeys[np].mValue);
435        }
436        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
437        {
438                rchannel[np].time     = (float)node->mRotationKeys[np].mTime;
439                rchannel[np].rotation = assimp_quat_cast(node->mRotationKeys[np].mValue );
440        }
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{
465        if ( m_scene == nullptr || m_mesh_count == 0 ) return nullptr;
466        const aiScene* scene = (const aiScene*)m_scene;
467        bool has_bones = false;
468        mesh_data* meshes = new mesh_data[ m_mesh_count ];
469        for ( size_t m = 0; m < m_mesh_count; ++m )
470        {
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);
475        }
476
477        mesh_nodes_data* nodes = ( has_bones ? release_merged_bones( meshes ) : release_mesh_nodes_data(0) );
478        return new mesh_data_pack( m_mesh_count, meshes, nodes );
479}
480
481nv::size_t nv::assimp_loader::get_nodes_data_count() const
482{
483        if ( m_scene == nullptr ) return 0;
484        const aiScene* scene = (const aiScene*)m_scene;
485        return scene->mNumAnimations;   
486}
487
488
Note: See TracBrowser for help on using the repository browser.