source: trunk/src/formats/md5_loader.cc @ 226

Last change on this file since 226 was 226, checked in by epyon, 11 years ago
  • md5 implementation fixes and optimizations
File size: 17.6 KB
RevLine 
[190]1// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz
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/md5_loader.hh"
8
9#include <glm/gtc/constants.hpp>
10#include "nv/logging.hh"
11#include "nv/io/std_stream.hh"
12#include <cstring>
13
14using namespace nv;
15
[191]16// based on http://tfc.duke.free.fr/coding/md5-specs-en.html
17
[190]18static void next_line( std::istream& stream )
19{
20        stream.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
21}
22
23static inline void discard( std::istream& stream, const std::string& token )
24{
[226]25//      stream.ignore( std::numeric_limits<std::streamsize>::max(), ' ' );
[190]26        std::string discarded;
27        stream >> discarded;
28        assert( discarded == token );
29}
30
31
32static void remove_quotes( std::string& str )
33{
34        size_t n;
35        while ( ( n = str.find('\"') ) != std::string::npos ) str.erase(n,1);
36}
37
[198]38static void unit_quat_w( glm::quat& quat )
[190]39{
40        float t = 1.0f - ( quat.x * quat.x ) - ( quat.y * quat.y ) - ( quat.z * quat.z );
41        quat.w = ( t < 0.0f ? 0.0f : -sqrtf(t) );
42}
43
44bool md5_loader::load( stream& source )
45{
46        std_stream sstream( &source );
47        std::string command;
48
49        sstream >> command;
50        while ( !sstream.eof() )
51        {
52                if ( command == "MD5Version" )
53                {
54                        sstream >> m_md5_version;
55                        assert( m_md5_version == 10 );
56                }
57                else if ( command == "commandline" )
58                {
59                        next_line( sstream );
60                }
61                else if ( command == "numJoints" )
62                {
63                        sstream >> m_num_joints;
64                        m_joints.reserve( m_num_joints );
65                }
66                else if ( command == "numMeshes" )
67                {
68                        sstream >> m_num_meshes;
69                        m_meshes.reserve( m_num_meshes );
70                }
71                else if ( command == "joints" )
72                {
73                        discard( sstream, "{" );
74                        md5_joint joint;
[191]75                        for ( size_t i = 0; i < m_num_joints; ++i )
[190]76                        {
77                                sstream >> joint.name >> joint.parent_id;
78                                discard( sstream, "(" );
79                                sstream >> joint.pos.x >> joint.pos.y >> joint.pos.z;
80                                discard( sstream, ")" );
81                                discard( sstream, "(" );
82                                sstream >> joint.orient.x >> joint.orient.y >> joint.orient.z;
83                                remove_quotes( joint.name );
84                                unit_quat_w( joint.orient );
85                                m_joints.push_back( joint );
86                                next_line( sstream );
87                        }
88                        discard( sstream, "}" );
89                }
90                else if ( command == "mesh" )
91                {
[224]92                        md5_mesh* mesh = new md5_mesh;
[190]93                        int num_verts, num_tris, num_weights;
94
95                        discard( sstream, "{" );
96                        sstream >> command;
97                        while ( command != "}" )
98                        {
99                                if ( command == "shader" )
100                                {
[224]101                                        sstream >> mesh->shader;
102                                        remove_quotes( mesh->shader );
[190]103                                        // texturePath.replace_extension( ".tga" );
104                                        next_line( sstream );
105                                }
106                                else if ( command == "numverts")
107                                {
108                                        sstream >> num_verts;
109                                        next_line( sstream );
[226]110                                        std::string line;
[190]111                                        for ( int i = 0; i < num_verts; ++i )
112                                        {
113                                                md5_vertex vert;
114
[226]115                                                std::getline( sstream, line );
116                                                sscanf( line.c_str(), "%*s %*u ( %f %f ) %u %u", &(vert.texcoord.x), &(vert.texcoord.y), &(vert.start_weight), &(vert.weight_count) );
117
118//                                              std::string ignore;
119//                                              discard( sstream, "vert" );
120//                                              sstream >> ignore;
121//                                              discard( sstream, "(" );
122//                                              sstream >> vert.texcoord.x >> vert.texcoord.y;
123//                                              discard( sstream, ")" );
124//                                              sstream >> vert.start_weight >> vert.weight_count;
125//                                              next_line( sstream );
126
[224]127                                                mesh->verts.push_back(vert);
128                                                mesh->texcoord_buffer.push_back( vert.texcoord );
[190]129                                        } 
130                                }
131                                else if ( command == "numtris" )
132                                {
133                                        sstream >> num_tris;
134                                        next_line( sstream );
[226]135                                        std::string line;
[190]136                                        for ( int i = 0; i < num_tris; ++i )
137                                        {
138                                                md5_triangle tri;
139
[226]140                                                std::getline( sstream, line );
141                                                sscanf( line.c_str(), "%*s %*u %u %u %u )", &(tri.indices[0]), &(tri.indices[1]), &(tri.indices[2]));
142
143//                                              std::string ignore;
144//                                              discard( sstream, "tri" );
145//                                              sstream >> ignore >> tri.indices[0] >> tri.indices[1] >> tri.indices[2];
146//                                              next_line( sstream );
147
[224]148                                                mesh->tris.push_back( tri );
149                                                mesh->index_buffer.push_back( (uint32)tri.indices[0] );
150                                                mesh->index_buffer.push_back( (uint32)tri.indices[1] );
151                                                mesh->index_buffer.push_back( (uint32)tri.indices[2] );
[190]152                                        }             
153                                }
154                                else if ( command == "numweights" )
155                                {
156                                        sstream >> num_weights;
[226]157                                        mesh->weights.reserve( num_weights );
[190]158                                        next_line( sstream );
[226]159                                        std::string line;
[190]160                                        for ( int i = 0; i < num_weights; ++i )
161                                        {
162                                                md5_weight weight;
[226]163
164                                                std::getline( sstream, line );
165                                                sscanf( line.c_str(), "%*s %*u %u %f ( %f %f %f )", &(weight.joint_id), &(weight.bias), &(weight.pos.x), &(weight.pos.y), &(weight.pos.z));
166
167//                                              std::string ignore;
168//                                              discard( sstream, "weight" );
169//                                              sstream >> ignore >> weight.joint_id >> weight.bias;
170//                                              discard( sstream, "(" );
171//                                              sstream >> weight.pos.x >> weight.pos.y >> weight.pos.z;
172//                                              discard( sstream, ")" );
173//                                              next_line( sstream );
174                                                mesh->weights.push_back(weight);
[190]175                                        }
176                                }
177                                else
178                                {
179                                        next_line( sstream );
180                                }
181
182                                sstream >> command;
183                        }
184
185                        prepare_mesh( mesh );
186                        prepare_normals( mesh );
187
188                        m_meshes.push_back(mesh);
189                }
190                sstream >> command;
191        }
192
193        assert( m_joints.size() == m_num_joints );
194        assert( m_meshes.size() == m_num_meshes );
195        return true;
196}
197
[224]198bool md5_loader::prepare_mesh( md5_mesh* mesh )
[190]199{
[224]200        mesh->position_buffer.clear();
201        mesh->texcoord_buffer.clear();
[190]202
[224]203        for ( uint32 i = 0; i < mesh->verts.size(); ++i )
[190]204        {
[224]205                md5_vertex& vert = mesh->verts[i];
[190]206
207                vert.position = glm::vec3(0);
208                vert.normal   = glm::vec3(0);
209                vert.tangent  = glm::vec3(0);
210
[200]211                for ( size_t j = 0; j < vert.weight_count; ++j )
[190]212                {
[224]213                        md5_weight& weight = mesh->weights[vert.start_weight + j];
[190]214                        md5_joint&  joint  = m_joints[weight.joint_id];
215
216                        glm::vec3 rot_pos = joint.orient * weight.pos;
217
218                        vert.position += ( joint.pos + rot_pos ) * weight.bias;
219                }
220
[224]221                mesh->position_buffer.push_back(vert.position);
222                mesh->texcoord_buffer.push_back(vert.texcoord);
[190]223        }
224
225        return true;
226}
227
[224]228bool md5_loader::prepare_normals( md5_mesh* mesh )
[190]229{
[224]230        mesh->normal_buffer.clear();
[190]231
[224]232        for ( unsigned int i = 0; i < mesh->tris.size(); ++i )
[190]233        {
[224]234                const md5_triangle& tri = mesh->tris[i];
235                glm::vec3 v1 = mesh->verts[ tri.indices[0] ].position;
236                glm::vec3 v2 = mesh->verts[ tri.indices[1] ].position;
237                glm::vec3 v3 = mesh->verts[ tri.indices[2] ].position;
[190]238                glm::vec3 xyz1 = v3 - v1;
239                glm::vec3 xyz2 = v2 - v1;
240
241                glm::vec3 normal = glm::cross( xyz1, xyz2 );
242
[224]243                mesh->verts[ tri.indices[0] ].normal += normal;
244                mesh->verts[ tri.indices[1] ].normal += normal;
245                mesh->verts[ tri.indices[2] ].normal += normal;
[190]246
[224]247                const vec2& w1 = mesh->verts[ tri.indices[0] ].texcoord;
248                const vec2& w2 = mesh->verts[ tri.indices[1] ].texcoord;
249                const vec2& w3 = mesh->verts[ tri.indices[2] ].texcoord;
[190]250
251                vec2 st1 = w3 - w1;
252                vec2 st2 = w2 - w1;
253
254                float coef = 1.0f / (st1.x * st2.y - st2.x * st1.y);
255
256                vec3 tangent = (( xyz1 * st2.y ) - ( xyz2 * st1.y )) * coef;
257
[224]258                mesh->verts[ tri.indices[0] ].tangent += tangent;
259                mesh->verts[ tri.indices[1] ].tangent += tangent;
260                mesh->verts[ tri.indices[2] ].tangent += tangent;
[190]261        }
262
[224]263        for ( size_t i = 0; i < mesh->verts.size(); ++i )
[190]264        {
[224]265                md5_vertex& vert = mesh->verts[i];
[190]266
267                glm::vec3 normal  = glm::normalize( vert.normal );
268                glm::vec3 tangent = glm::normalize( vert.tangent );
[224]269                mesh->normal_buffer.push_back( normal );
270                mesh->tangent_buffer.push_back( tangent );
[190]271
272                vert.normal  = glm::vec3(0);
273                vert.tangent = glm::vec3(0);
274
[200]275                for ( size_t j = 0; j < vert.weight_count; ++j )
[190]276                {
[224]277                        const md5_weight& weight = mesh->weights[vert.start_weight + j];
[190]278                        const md5_joint&  joint  = m_joints[weight.joint_id];
279                        vert.normal  += ( normal  * joint.orient ) * weight.bias;
280                        vert.tangent += ( tangent * joint.orient ) * weight.bias;
281                }
282        }
283
284        return true;
285}
286
[224]287mesh_data* nv::md5_loader::release_submesh_data( uint32 mesh_id )
288{
289        mesh_data_creator m;
290        m.get_positions().assign( m_meshes[mesh_id]->position_buffer.begin(), m_meshes[mesh_id]->position_buffer.begin() );
291        m.get_normals()  .assign( m_meshes[mesh_id]->normal_buffer.begin(),   m_meshes[mesh_id]->normal_buffer.begin() );
292        m.get_tangents() .assign( m_meshes[mesh_id]->tangent_buffer.begin(),  m_meshes[mesh_id]->tangent_buffer.begin() );
293        m.get_texcoords().assign( m_meshes[mesh_id]->texcoord_buffer.begin(), m_meshes[mesh_id]->texcoord_buffer.begin() );
294        m.get_indices()  .assign( m_meshes[mesh_id]->index_buffer.begin(),    m_meshes[mesh_id]->index_buffer.begin() );
295
296        return m.release();
297}
298
299/*
[190]300mesh* md5_loader::release_mesh()
301{
302        mesh* m = new mesh();
303        auto position = m->add_attribute< vec3 >( "nv_position" );
304        auto normal   = m->add_attribute< vec3 >( "nv_normal" );
305        auto texcoord = m->add_attribute< vec2 >( "nv_texcoord" );
[197]306        auto tangent  = m->add_attribute< vec3 >( "nv_tangent" );
[190]307        auto indices  = m->add_indices< uint32 >();
308
309        position->get().assign( m_meshes[0].position_buffer.begin(), m_meshes[0].position_buffer.end() );
310        normal  ->get().assign( m_meshes[0].normal_buffer.begin(),   m_meshes[0].normal_buffer.end() );
311        texcoord->get().assign( m_meshes[0].texcoord_buffer.begin(), m_meshes[0].texcoord_buffer.end() );
312        tangent ->get().assign( m_meshes[0].tangent_buffer.begin(),  m_meshes[0].tangent_buffer.end() );
313        indices ->get().assign( m_meshes[0].index_buffer.begin(),    m_meshes[0].index_buffer.end() );
314
315        m_size = m_meshes[0].index_buffer.size();
316        return m;
317}
[224]318*/
[191]319
320md5_animation::md5_animation()
321        : m_md5_version( 0 )
322        , m_num_frames( 0 )
323        , m_num_joints( 0 )
324        , m_frame_rate( 0 )
325        , m_num_animated_components( 0 )
326        , m_anim_duration( 0 )
327        , m_frame_duration( 0 )
328        , m_anim_time( 0 )
329{
330
331}
332
333md5_animation::~md5_animation()
334{
335
336}
337
338bool md5_animation::load_animation( stream& source )
339{
340        m_joint_infos.clear();
341        m_bounds.clear();
342        m_base_frames.clear();
343        m_frames.clear();
344        m_animated_skeleton.joints.clear();
345        m_num_frames = 0;
346
347        std_stream sstream( &source );
348        std::string command;
349
350        sstream >> command;
351        while ( !sstream.eof() )
352        {
353                if ( command == "MD5Version" )
354                {
355                        sstream >> m_md5_version;
356                        assert( m_md5_version == 10 );
357                }
358                else if ( command == "commandline" )
359                {
360                        next_line( sstream );
361                }
362                else if ( command == "numFrames" )
363                {
364                        sstream >> m_num_frames;
365                        next_line( sstream );
366                }
367                else if ( command == "numJoints" )
368                {
369                        sstream >> m_num_joints;
370                        next_line( sstream );
371                }
372                else if ( command == "frameRate" )
373                {
374                        sstream >> m_frame_rate;
375                        next_line( sstream );
376                }
377                else if ( command == "numAnimatedComponents" )
378                {
379                        sstream >> m_num_animated_components;
380                        next_line( sstream );
381                }
382                else if ( command == "hierarchy" )
383                {
384                        discard( sstream, "{" );
[198]385                        for ( size_t i = 0; i < m_num_joints; ++i )
[191]386                        {
387                                md5_joint_info joint;
388                                sstream >> joint.name >> joint.parent_id >> joint.flags >> joint.start_index;
389                                remove_quotes( joint.name );
390                                m_joint_infos.push_back( joint );
391                                next_line( sstream );
392                        }
393                        discard( sstream, "}" );
394                }
395                else if ( command == "bounds" )
396                {
397                        discard( sstream, "{" );
398                        next_line( sstream );
[198]399                        for ( size_t i = 0; i < m_num_frames; ++i )
[191]400                        {
401                                md5_bound bound;
402                                discard( sstream, "(" );
403                                sstream >> bound.min.x >> bound.min.y >> bound.min.z;
404                                discard( sstream, ")" );
405                                discard( sstream, "(" );
406                                sstream >> bound.max.x >> bound.max.y >> bound.max.z;
407
408                                m_bounds.push_back( bound );
409
410                                next_line( sstream );
411                        }
412
413                        discard( sstream, "}" );
414                        next_line( sstream );
415                }
416                else if ( command == "baseframe" )
417                {
418                        discard( sstream, "{" );
419                        next_line( sstream );
420
[198]421                        for ( size_t i = 0; i < m_num_joints; ++i )
[191]422                        {
423                                md5_base_frame base_frame;
424                                discard( sstream, "(" );
425                                sstream >> base_frame.pos.x >> base_frame.pos.y >> base_frame.pos.z;
426                                discard( sstream, ")" );
427                                discard( sstream, "(" );
428                                sstream >> base_frame.orient.x >> base_frame.orient.y >> base_frame.orient.z;
429                                next_line( sstream );
430
431                                m_base_frames.push_back( base_frame );
432                        }
433                        discard( sstream, "}" );
434                        next_line( sstream );
435                }
436                else if ( command == "frame" )
437                {
438                        md5_frame_data frame;
439                        sstream >> frame.frame_id;
440                        discard( sstream, "{" );
441                        next_line( sstream );
442
[226]443                        frame.frame_data.reserve( m_num_animated_components );
444                        char buf[50];
[198]445                        for ( size_t i = 0; i < m_num_animated_components; ++i )
[191]446                        {
[226]447                                sstream >> buf;
448                                frame.frame_data.push_back((float)atof(buf));
[191]449                        }
450
451                        m_frames.push_back(frame);
452
453                        build_frame_skeleton( m_skeletons, m_joint_infos, m_base_frames, frame );
454
455                        discard( sstream, "}" );
456                        next_line( sstream );
457                }
458
459                sstream >> command;
460        }
461
462        m_animated_skeleton.joints.assign( m_num_joints, md5_skeleton_joint() );
463
464        m_frame_duration = 1.0f / (float)m_frame_rate;
465        m_anim_duration = ( m_frame_duration * (float)m_num_frames );
466        m_anim_time = 0.0f;
467
[198]468        assert( m_joint_infos.size() == m_num_joints );
469        assert( m_bounds.size()      == m_num_frames );
470        assert( m_base_frames.size() == m_num_joints );
471        assert( m_frames.size()      == m_num_frames );
472        assert( m_skeletons.size()   == m_num_frames );
[191]473
474        return true;
475}
476
477void md5_animation::update( float delta_time )
478{
479        if ( m_num_frames < 1 ) return;
480
481        m_anim_time += delta_time;
482
483        while ( m_anim_time > m_anim_duration ) m_anim_time -= m_anim_duration;
484        while ( m_anim_time < 0.0f ) m_anim_time += m_anim_duration;
485
486        float frame_num = m_anim_time * (float)m_frame_rate;
[200]487        size_t frame0 = (size_t)floorf( frame_num );
488        size_t frame1 = (size_t)ceilf( frame_num );
[191]489        frame0 = frame0 % m_num_frames;
490        frame1 = frame1 % m_num_frames;
491
492        float interpolate = fmodf( m_anim_time, m_frame_duration ) / m_frame_duration;
493
494        interpolate_skeletons( m_animated_skeleton, m_skeletons[frame0], m_skeletons[frame1], interpolate );
495}
496
497void md5_animation::build_frame_skeleton( md5_frame_skeleton_list& skeletons, const md5_joint_info_list& joint_infos, const md5_base_frame_list& base_frames, const md5_frame_data& frame_data )
498{
499        md5_frame_skeleton skeleton;
500
501        for ( unsigned int i = 0; i < joint_infos.size(); ++i )
502        {
503                unsigned int j = 0;
504
505                const md5_joint_info& jinfo = joint_infos[i];
506                md5_skeleton_joint animated_joint = base_frames[i];
507
508                animated_joint.parent = jinfo.parent_id;
509
510                if ( jinfo.flags & 1 )  animated_joint.pos.x    = frame_data.frame_data[ jinfo.start_index + j++ ];
511                if ( jinfo.flags & 2 )  animated_joint.pos.y    = frame_data.frame_data[ jinfo.start_index + j++ ];
512                if ( jinfo.flags & 4 )  animated_joint.pos.z    = frame_data.frame_data[ jinfo.start_index + j++ ];
513                if ( jinfo.flags & 8 )  animated_joint.orient.x = frame_data.frame_data[ jinfo.start_index + j++ ];
514                if ( jinfo.flags & 16 ) animated_joint.orient.y = frame_data.frame_data[ jinfo.start_index + j++ ];
515                if ( jinfo.flags & 32 ) animated_joint.orient.z = frame_data.frame_data[ jinfo.start_index + j++ ];
516
517                unit_quat_w( animated_joint.orient );
518
519                if ( animated_joint.parent >= 0 ) // Has a parent joint
520                {
[200]521                        md5_skeleton_joint& pjoint = skeleton.joints[static_cast< size_t >( animated_joint.parent ) ];
[191]522                        glm::vec3 rot_pos = pjoint.orient * animated_joint.pos;
523
524                        animated_joint.pos    = pjoint.pos + rot_pos;
525                        animated_joint.orient = pjoint.orient * animated_joint.orient;
526
527                        animated_joint.orient = glm::normalize( animated_joint.orient );
528                }
529
530                skeleton.joints.push_back( animated_joint );
531        }
532
533        skeletons.push_back( skeleton );
534}
535
536void md5_animation::interpolate_skeletons( md5_frame_skeleton& final_skeleton, const md5_frame_skeleton& skeleton0, const md5_frame_skeleton& skeleton1, float interpolate )
537{
[198]538        for ( size_t i = 0; i < m_num_joints; ++i )
[191]539        {
540                md5_skeleton_joint& final_joint = final_skeleton.joints[i];
541                const md5_skeleton_joint& joint0 = skeleton0.joints[i];
542                const md5_skeleton_joint& joint1 = skeleton1.joints[i];
543
544                final_joint.parent = joint0.parent;
545
[192]546                final_joint.orient = glm::slerp( joint0.orient, joint1.orient, interpolate );
[191]547                final_joint.pos    = glm::mix( joint0.pos, joint1.pos, interpolate );
548        }
549}
550
551bool md5_loader::check_animation( const md5_animation& animation ) const
552{
553        if ( m_num_joints != animation.get_num_joints() )
554        {
555                return false;
556        }
557
558        for ( uint32 i = 0; i < m_joints.size(); ++i )
559        {
560                const md5_joint& mjoint = m_joints[i];
561                const md5_animation::md5_joint_info& ajoint = animation.get_joint_info( i );
562
563                if ( mjoint.name != ajoint.name || mjoint.parent_id != ajoint.parent_id )
564                {
565                        return false;
566                }
567        }
568
569        return true;
570}
571
[224]572bool md5_loader::prepare_animated_mesh( md5_mesh* mesh, const md5_animation::md5_frame_skeleton& skel )
[191]573{
[224]574        for ( unsigned int i = 0; i < mesh->verts.size(); ++i )
[191]575        {
[224]576                const md5_vertex& vert = mesh->verts[i];
577                glm::vec3& pos     = mesh->position_buffer[i];
578                glm::vec3& normal  = mesh->normal_buffer[i];
579                glm::vec3& tangent = mesh->tangent_buffer[i];
[191]580
581                pos     = glm::vec3(0);
582                normal  = glm::vec3(0);
583                tangent = glm::vec3(0);
584
[200]585                for ( size_t j = 0; j < vert.weight_count; ++j )
[191]586                {
[224]587                        const md5_weight& weight = mesh->weights[vert.start_weight + j];
[191]588                        const md5_animation::md5_skeleton_joint& joint = skel.joints[weight.joint_id];
589
590                        glm::vec3 rot_pos = joint.orient * weight.pos;
591                        pos += ( joint.pos + rot_pos ) * weight.bias;
592
593                        normal  += ( joint.orient * vert.normal  ) * weight.bias;
594                        tangent += ( joint.orient * vert.tangent ) * weight.bias;
595                }
596        }
597        return true;
598}
599
600void md5_loader::apply( const md5_animation& animation )
601{
602        const md5_animation::md5_frame_skeleton& skeleton = animation.get_skeleton();
603
604        for ( unsigned int i = 0; i < m_meshes.size(); ++i )
605        {
606                prepare_animated_mesh( m_meshes[i], skeleton );
607        }
608}
609
610size_t nv::md5_loader::get_size()
611{
612        return m_size;
613}
Note: See TracBrowser for help on using the repository browser.