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

Last change on this file since 293 was 293, checked in by epyon, 11 years ago
  • mesh_creator class, currently for transforms, later for const safety
  • pre_transform and transformation moved out of assimp_loader
  • pre_transfrom and transformation works on ANY mesh_data/mesh_nodes_data
  • cleanups
File size: 15.1 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 <glm/gtx/transform.hpp>
10#include "nv/io/std_stream.hh"
11#include "nv/gfx/mesh_creator.hh"
12#include "nv/lib/assimp.hh"
13
14using namespace nv;
15
16const int MAX_BONES = 64;
17
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
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
60nv::assimp_loader::assimp_loader( const string& a_ext, uint32 a_assimp_flags /*= 0 */ )
61        : m_scene( nullptr ), m_mesh_count(0)
62{
63        m_ext   = a_ext;
64        m_assimp_flags = a_assimp_flags;
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}
83
84
85bool nv::assimp_loader::load( stream& source )
86{
87        load_assimp_library();
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..." );
92        int size = (int)source.size();
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;
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{
117        const aiScene* scene = (const aiScene*)m_scene;
118        const aiMesh*  mesh  = scene->mMeshes[ index ];
119        data->set_name( mesh->mName.data );
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
128        data->add_channel( channel );
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] = 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( 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
240                        NV_LOG( nv::LOG_NOTICE, "Mesh #"<<mc<<"   - " << std::string( mesh->mName.data ) );
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
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                sint16 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                                        sint16 index = (sint16)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] = (sint16)iname->second;
314                                }
315                        }
316                        if ( m > 0 && bones.size() > 0 )
317                        {
318                                mesh_raw_channel* channel = meshes[m].get_raw_channels()[0];
319                                NV_ASSERT( !channel->is_index(), "index channel in release_merged!" );
320                                assimp_skinned_vtx* va = (assimp_skinned_vtx*)channel->data;
321                                for ( unsigned v = 0; v < channel->count; ++v )
322                                {
323                                        assimp_skinned_vtx& vertex = va[v];
324
325                                        for (uint32 i = 0 ; i < 4; ++i)
326                                        {
327                                                if ( vertex.boneweight[i] > 0.0f )
328                                                {
329                                                        vertex.boneindex[i] = translate[vertex.boneindex[i]];
330                                                }
331                                        }
332                                }
333                        }
334                }       
335        }
336        mesh_node_data* bones = new mesh_node_data[ final_bones.size() ];
337        std::copy( final_bones.begin(), final_bones.end(), bones );
338        return new mesh_nodes_data( "bones", final_bones.size(), bones );
339}
340
341mesh_nodes_data* nv::assimp_loader::release_animation( size_t index )
342{
343        if ( m_scene == nullptr ) return nullptr;
344        const aiScene* scene = (const aiScene*)m_scene;
345        if ( scene->mRootNode == nullptr || scene->mAnimations == nullptr || scene->mAnimations[index] == nullptr) return nullptr;
346
347        const aiNode*      root = scene->mRootNode;
348        const aiAnimation* anim = scene->mAnimations[index];
349
350        uint32 count = count_nodes( scene->mRootNode );
351        mesh_node_data* data    = new mesh_node_data[count];
352
353        uint16 frame_rate     = (uint16)anim->mTicksPerSecond;
354        float  duration       = (float)anim->mDuration;
355        bool   flat           = false;
356
357        load_node( index, data, root, 0, -1 );
358
359        return new mesh_nodes_data( anim->mName.data, count, data, frame_rate, duration, flat );
360}
361
362nv::uint32 nv::assimp_loader::count_nodes( const void* node ) const
363{
364        const aiNode* ainode = (const aiNode*)node;
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
373nv::sint16 nv::assimp_loader::load_node( uint32 anim_id, mesh_node_data* nodes, const void* vnode, sint16 this_id, sint16 parent_id )
374{
375        const aiScene* scene = (const aiScene*)m_scene;
376        const aiNode*  node  = (const aiNode*)vnode;
377        string name( node->mName.data );
378        const aiAnimation* anim  = scene->mAnimations[anim_id];
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
388        mesh_node_data& a_data = nodes[ this_id ];
389
390        a_data.name      = name;
391        a_data.target_id = -1;
392        a_data.parent_id = parent_id;
393        // This value is ignored by the create_transformed_keys, but needed by create_direct_keys!
394        // TODO: find a common solution!
395        //       This is bad because create_transformed_keys never uses node-transformations for
396        //       node's without keys
397        a_data.transform = nv::assimp_mat4_cast( node->mTransformation );
398        if (this_id == 0)
399                a_data.transform = mat4();
400        a_data.data = nullptr;
401
402        if (anode) create_keys( &a_data, anode );
403
404        nv::sint16 next = this_id + 1;
405        for ( unsigned i = 0; i < node->mNumChildren; ++i )
406        {
407                next = load_node( anim_id, nodes, node->mChildren[i], next, this_id );
408        }
409
410        return next;
411}
412
413void nv::assimp_loader::create_keys( mesh_node_data* data, const void* vnode )
414{
415        const aiNodeAnim* node = (const aiNodeAnim*)vnode;
416        if ( node->mNumPositionKeys == 0 && node->mNumRotationKeys == 0 && node->mNumScalingKeys == 0 )
417        {
418                return;
419        }
420
421        data->data = new key_data;
422        key_raw_channel* raw_pchannel = key_raw_channel::create<assimp_key_p>( node->mNumPositionKeys );
423        key_raw_channel* raw_rchannel = key_raw_channel::create<assimp_key_r>( node->mNumRotationKeys );
424        //key_raw_channel* raw_schannel = key_raw_channel::create<assimp_key_s>( node->mNumScalingKeys );
425        data->data->add_channel( raw_pchannel );
426        data->data->add_channel( raw_rchannel );
427        //data->data->add_channel( raw_schannel );
428        assimp_key_p* pchannel = ((assimp_key_p*)(raw_pchannel->data));
429        assimp_key_r* rchannel = ((assimp_key_r*)(raw_rchannel->data));
430        //assimp_key_s* schannel = ((assimp_key_s*)(raw_schannel->data));
431
432        for ( unsigned np = 0; np < node->mNumPositionKeys; ++np )
433        {
434                pchannel[np].time     = (float)node->mPositionKeys[np].mTime;
435                pchannel[np].position = assimp_vec3_cast(node->mPositionKeys[np].mValue);
436        }
437        for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
438        {
439                rchannel[np].time     = (float)node->mRotationKeys[np].mTime;
440                rchannel[np].rotation = assimp_quat_cast(node->mRotationKeys[np].mValue );
441        }
442//      if ( node->mNumScalingKeys > 0 )
443//      {
444//              nv::vec3 scale_vec0 = assimp_vec3_cast( node->mScalingKeys[0].mValue );
445//              float scale_value   = glm::length( glm::abs( scale_vec0 - nv::vec3(1,1,1) ) );
446//              if ( node->mNumScalingKeys > 1 || scale_value > 0.001 )
447//              {
448//                      NV_LOG( nv::LOG_WARNING, "scale key significant!" );
449//                      for ( unsigned np = 0; np < node->mNumRotationKeys; ++np )
450//                      {
451//                              schannel[np].time  = (float)node->mScalingKeys[np].mTime;
452//                              schannel[np].scale = assimp_vec3_cast(node->mScalingKeys[np].mValue);
453//                      }
454//              }
455//              else
456//              {
457//                      schannel[0].time  = (float)node->mScalingKeys[0].mTime;
458//                      schannel[0].scale = assimp_vec3_cast(node->mScalingKeys[0].mValue);
459//              }
460//      }
461
462}
463
464mesh_data_pack* nv::assimp_loader::release_mesh_data_pack()
465{
466        if ( m_scene == nullptr || m_mesh_count == 0 ) return nullptr;
467        const aiScene* scene = (const aiScene*)m_scene;
468        bool has_bones = false;
469        mesh_data* meshes = new mesh_data[ m_mesh_count ];
470        for ( size_t m = 0; m < m_mesh_count; ++m )
471        {
472                const aiMesh* mesh = scene->mMeshes[ m ];
473                meshes[m].set_name( mesh->mName.data );
474                if ( mesh->mNumBones > 0 ) has_bones = true;
475                load_mesh_data(&meshes[m],m);
476        }
477
478        mesh_nodes_data* nodes = ( has_bones ? release_merged_bones( meshes ) : release_animation(0) );
479        return new mesh_data_pack( m_mesh_count, meshes, nodes );
480}
481
482size_t nv::assimp_loader::get_nodes_data_count() const
483{
484        if ( m_scene == nullptr ) return 0;
485        const aiScene* scene = (const aiScene*)m_scene;
486        return scene->mNumAnimations;   
487}
488
489mesh_nodes_data* nv::assimp_loader::release_mesh_nodes_data( size_t index /*= 0 */ )
490{
491        return release_animation( index );
492}
493
Note: See TracBrowser for help on using the repository browser.