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

Last change on this file since 241 was 241, checked in by epyon, 11 years ago
  • significant simplification of the md5 code
  • proper instancing for both md5 animations and meshes
  • transform_vectors
File size: 14.4 KB
Line 
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
16// based on http://tfc.duke.free.fr/coding/md5-specs-en.html
17
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{
25//      stream.ignore( std::numeric_limits<std::streamsize>::max(), ' ' );
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
38static void unit_quat_w( glm::quat& quat )
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;
75                        for ( size_t i = 0; i < m_num_joints; ++i )
76                        {
77                                int parent_id;
78                                sstream >> joint.name >> parent_id;
79                                discard( sstream, "(" );
80                                sstream >> joint.pos.x >> joint.pos.y >> joint.pos.z;
81                                discard( sstream, ")" );
82                                discard( sstream, "(" );
83                                sstream >> joint.orient.x >> joint.orient.y >> joint.orient.z;
84                                remove_quotes( joint.name );
85                                unit_quat_w( joint.orient );
86                                m_joints.push_back( joint );
87                                next_line( sstream );
88                        }
89                        discard( sstream, "}" );
90                }
91                else if ( command == "mesh" )
92                {
93                        md5_mesh_data* mesh = new md5_mesh_data();
94
95                        int num_verts, num_tris, num_weights;
96
97                        discard( sstream, "{" );
98                        sstream >> command;
99                        while ( command != "}" )
100                        {
101                                if ( command == "shader" )
102                                {
103                                        sstream >> mesh->m_shader;
104                                        remove_quotes( mesh->m_shader );
105                                        // texturePath.replace_extension( ".tga" );
106                                        next_line( sstream );
107                                }
108                                else if ( command == "numverts")
109                                {
110                                        sstream >> num_verts;
111
112                                        {
113                                                mesh_raw_channel* ch_pnt = mesh_raw_channel::create<md5_vtx_pnt>( num_verts );
114                                                mesh_raw_channel* ch_t   = mesh_raw_channel::create<md5_vtx_t>( num_verts );
115                                                mesh->m_pntdata          = (md5_vtx_pnt*)ch_pnt->data;
116                                                mesh->m_tdata            = (md5_vtx_t*)ch_t->data;
117                                                mesh->add_channel( ch_pnt );
118                                                mesh->add_channel( ch_t );
119                                        }
120                                        mesh->m_vtx_data.resize( num_verts );
121
122                                        next_line( sstream );
123                                        std::string line;
124                                        for ( int i = 0; i < num_verts; ++i )
125                                        {
126                                                md5_vtx_data& vdata = mesh->m_vtx_data[i];
127                                                size_t weight_count;
128                                                size_t start_weight;
129                                                vec2 texcoord;
130
131                                                std::getline( sstream, line );
132                                                sscanf( line.c_str(), "%*s %*u ( %f %f ) %u %u", &(texcoord.x), &(texcoord.y), &(start_weight), &(weight_count) );
133                                                vdata.start_weight = start_weight;
134                                                vdata.weight_count = weight_count;
135                                                mesh->m_tdata[i].texcoord = texcoord;
136                                        } 
137                                }
138                                else if ( command == "numtris" )
139                                {
140                                        sstream >> num_tris;
141
142                                        mesh_raw_index_channel* ch_i = mesh_raw_index_channel::create<uint32>( num_tris * 3 );
143                                        uint32* vtx_i                = (uint32*)ch_i->data;
144                                        mesh->m_idata                = vtx_i;
145                                        uint32 idx = 0;
146                                        mesh->set_index_channel( ch_i );
147
148                                        next_line( sstream );
149                                        std::string line;
150                                        for ( int i = 0; i < num_tris; ++i )
151                                        {
152                                                size_t ti0;
153                                                size_t ti1;
154                                                size_t ti2;
155
156                                                std::getline( sstream, line );
157                                                sscanf( line.c_str(), "%*s %*u %u %u %u )", &(ti0), &(ti1), &(ti2));
158
159                                                vtx_i[idx++] = (uint32)ti0;
160                                                vtx_i[idx++] = (uint32)ti1;
161                                                vtx_i[idx++] = (uint32)ti2;
162                                        }             
163                                }
164                                else if ( command == "numweights" )
165                                {
166                                        sstream >> num_weights;
167                                        mesh->m_weights.reserve( num_weights );
168                                        next_line( sstream );
169                                        std::string line;
170                                        for ( int i = 0; i < num_weights; ++i )
171                                        {
172                                                md5_weight weight;
173
174                                                std::getline( sstream, line );
175                                                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));
176                                                mesh->m_weights.push_back(weight);
177                                        }
178                                }
179                                else
180                                {
181                                        next_line( sstream );
182                                }
183
184                                sstream >> command;
185                        }
186
187                        prepare_mesh( mesh );
188
189                        m_meshes.push_back(mesh);
190                }
191                sstream >> command;
192        }
193
194        assert( m_joints.size() == m_num_joints );
195        assert( m_meshes.size() == m_num_meshes );
196        return true;
197}
198
199bool md5_loader::prepare_mesh( md5_mesh_data* mdata )
200{
201        uint32 vtx_count = mdata->m_vtx_data.size();
202        md5_vtx_pnt* vtcs = mdata->m_pntdata;
203
204        for ( uint32 i = 0; i < vtx_count; ++i )
205        {
206                md5_vtx_data& vdata = mdata->m_vtx_data[i];
207                md5_vtx_pnt& vtc = vtcs[i];
208
209                vtc.position = glm::vec3(0);
210                vtc.normal   = glm::vec3(0);
211                vtc.tangent  = glm::vec3(0);
212
213                for ( size_t j = 0; j < vdata.weight_count; ++j )
214                {
215                        md5_weight& weight = mdata->m_weights[vdata.start_weight + j];
216                        md5_joint&  joint  = m_joints[weight.joint_id];
217
218                        glm::vec3 rot_pos = joint.orient * weight.pos;
219
220                        vtc.position += ( joint.pos + rot_pos ) * weight.bias;
221                }
222        }
223
224        // Prepare normals
225        uint32 tri_count = mdata->get_count() / 3;
226        for ( unsigned int i = 0; i < tri_count; ++i )
227        {
228                uint32 ti0 = mdata->m_idata[ i * 3 ];
229                uint32 ti1 = mdata->m_idata[ i * 3 + 1 ];
230                uint32 ti2 = mdata->m_idata[ i * 3 + 2 ];
231 
232                glm::vec3 v1 = vtcs[ ti0 ].position;
233                glm::vec3 v2 = vtcs[ ti1 ].position;
234                glm::vec3 v3 = vtcs[ ti2 ].position;
235                glm::vec3 xyz1 = v3 - v1;
236                glm::vec3 xyz2 = v2 - v1;
237
238                glm::vec3 normal = glm::cross( xyz1, xyz2 );
239
240                vtcs[ ti0 ].normal += normal;
241                vtcs[ ti1 ].normal += normal;
242                vtcs[ ti2 ].normal += normal;
243
244                const vec2& w1 = mdata->m_tdata[ ti0 ].texcoord;
245                const vec2& w2 = mdata->m_tdata[ ti1 ].texcoord;
246                const vec2& w3 = mdata->m_tdata[ ti2 ].texcoord;
247
248                vec2 st1 = w3 - w1;
249                vec2 st2 = w2 - w1;
250
251                float coef = 1.0f / (st1.x * st2.y - st2.x * st1.y);
252
253                vec3 tangent = (( xyz1 * st2.y ) - ( xyz2 * st1.y )) * coef;
254
255                vtcs[ ti0 ].tangent += tangent;
256                vtcs[ ti1 ].tangent += tangent;
257                vtcs[ ti2 ].tangent += tangent;
258        }
259
260        for ( size_t i = 0; i < vtx_count; ++i )
261        {
262                md5_vtx_data& vdata = mdata->m_vtx_data[i];
263
264                glm::vec3 normal  = glm::normalize( vtcs[i].normal );
265                glm::vec3 tangent = glm::normalize( vtcs[i].tangent );
266                vtcs[i].normal   = normal;
267                vtcs[i].tangent  = tangent;
268
269                vdata.normal  = glm::vec3(0);
270                vdata.tangent = glm::vec3(0);
271 
272                for ( size_t j = 0; j < vdata.weight_count; ++j )
273                {
274                        const md5_weight& weight = mdata->m_weights[vdata.start_weight + j];
275                        const md5_joint&  joint  = m_joints[weight.joint_id];
276                        vdata.normal  += ( normal  * joint.orient ) * weight.bias;
277                        vdata.tangent += ( tangent * joint.orient ) * weight.bias;
278                }
279        }
280
281        return true;
282}
283
284
285md5_animation::md5_animation()
286        : m_md5_version( 0 )
287        , m_num_frames( 0 )
288        , m_num_joints( 0 )
289        , m_frame_rate( 0 )
290        , m_num_animated_components( 0 )
291        , m_anim_duration( 0 )
292        , m_frame_duration( 0 )
293{
294
295}
296
297md5_animation::~md5_animation()
298{
299
300}
301
302bool md5_animation::load_animation( stream& source )
303{
304        std::vector<md5_joint_info> joint_infos;
305        std::vector<transform>      base_frames;
306        m_num_frames = 0;
307
308        std_stream sstream( &source );
309        std::string command;
310
311        sstream >> command;
312        while ( !sstream.eof() )
313        {
314                if ( command == "MD5Version" )
315                {
316                        sstream >> m_md5_version;
317                        assert( m_md5_version == 10 );
318                }
319                else if ( command == "commandline" )
320                {
321                        next_line( sstream );
322                }
323                else if ( command == "numFrames" )
324                {
325                        sstream >> m_num_frames;
326                        next_line( sstream );
327                }
328                else if ( command == "numJoints" )
329                {
330                        sstream >> m_num_joints;
331                        m_joints.reserve( m_num_joints );
332                        next_line( sstream );
333                }
334                else if ( command == "frameRate" )
335                {
336                        sstream >> m_frame_rate;
337                        next_line( sstream );
338                }
339                else if ( command == "numAnimatedComponents" )
340                {
341                        sstream >> m_num_animated_components;
342                        next_line( sstream );
343                }
344                else if ( command == "hierarchy" )
345                {
346                        discard( sstream, "{" );
347                        for ( size_t i = 0; i < m_num_joints; ++i )
348                        {
349                                md5_joint_info joint;
350                                sstream >> joint.name >> joint.parent_id >> joint.flags >> joint.start_index;
351                                remove_quotes( joint.name );
352                                joint_infos.push_back( joint );
353                                m_joints.push_back( md5_joint( joint.parent_id, m_num_frames ) );
354                                next_line( sstream );
355                        }
356                        discard( sstream, "}" );
357                }
358                else if ( command == "bounds" )
359                {
360                        discard( sstream, "{" );
361                        next_line( sstream );
362                        for ( size_t i = 0; i < m_num_frames; ++i )
363                        {
364//                              vec3 min;
365//                              vec3 max;
366//                              discard( sstream, "(" );
367//                              sstream >> min.x >> min.y >> min.z;
368//                              discard( sstream, ")" );
369//                              discard( sstream, "(" );
370//                              sstream >> max.x >> max.y >> max.z;
371//                              m_bounds.push_back( bound );
372                                next_line( sstream );
373                        }
374
375                        discard( sstream, "}" );
376                        next_line( sstream );
377                }
378                else if ( command == "baseframe" )
379                {
380                        discard( sstream, "{" );
381                        next_line( sstream );
382
383                        for ( size_t i = 0; i < m_num_joints; ++i )
384                        {
385                                transform base_frame;
386                                vec3 pos;
387                                quat orient;
388                                discard( sstream, "(" );
389                                sstream >> pos.x >> pos.y >> pos.z;
390                                discard( sstream, ")" );
391                                discard( sstream, "(" );
392                                sstream >> orient.x >> orient.y >> orient.z;
393                                next_line( sstream );
394
395                                base_frames.emplace_back( pos, orient );
396                        }
397                        discard( sstream, "}" );
398                        next_line( sstream );
399                }
400                else if ( command == "frame" )
401                {
402                        std::vector<float> frame;
403                        int frame_id;
404                        sstream >> frame_id;
405                        discard( sstream, "{" );
406                        next_line( sstream );
407
408                        frame.reserve( m_num_animated_components );
409                        char buf[50];
410                        for ( size_t i = 0; i < m_num_animated_components; ++i )
411                        {
412                                sstream >> buf;
413                                frame.push_back((float)atof(buf));
414                        }
415
416                        build_frame_skeleton( joint_infos, base_frames, frame );
417
418                        discard( sstream, "}" );
419                        next_line( sstream );
420                }
421
422                sstream >> command;
423        }
424
425
426        m_frame_duration = 1.0f / (float)m_frame_rate;
427        m_anim_duration = ( m_frame_duration * (float)m_num_frames );
428
429        return true;
430}
431
432
433void nv::md5_animation::update_skeleton( std::vector<transform>& skeleton, float anim_time ) const
434{
435        NV_ASSERT( skeleton.size() == m_num_joints, "Incompatible skeleton passed!" );
436        anim_time = glm::clamp( anim_time, 0.0f, m_anim_duration );
437        float frame_num = anim_time * (float)m_frame_rate;
438        size_t frame0 = (size_t)floorf( frame_num );
439        size_t frame1 = (size_t)ceilf( frame_num );
440        frame0 = frame0 % m_num_frames;
441        frame1 = frame1 % m_num_frames;
442
443        float interpolation = fmodf( anim_time, m_frame_duration ) / m_frame_duration;
444
445        for ( size_t i = 0; i < m_num_joints; ++i )
446        {
447                const transform_vector& keys = m_joints[i].keys;
448                skeleton[i] = interpolate( keys.get(frame0), keys.get(frame1), interpolation );
449        }
450}
451
452void md5_animation::build_frame_skeleton( const std::vector<md5_joint_info>& joint_infos, const std::vector<transform>& base_frames, const std::vector<float>& frame_data )
453{
454        size_t index = m_joints[0].keys.size();
455        for ( unsigned int i = 0; i < joint_infos.size(); ++i )
456        {
457                unsigned int j = 0;
458
459                const md5_joint_info& jinfo = joint_infos[i];
460
461
462                int parent_id = jinfo.parent_id;
463
464                vec3 pos    = base_frames[i].get_position();
465                quat orient = base_frames[i].get_orientation();
466                if ( jinfo.flags & 1 )  pos.x    = frame_data[ jinfo.start_index + j++ ];
467                if ( jinfo.flags & 2 )  pos.y    = frame_data[ jinfo.start_index + j++ ];
468                if ( jinfo.flags & 4 )  pos.z    = frame_data[ jinfo.start_index + j++ ];
469                if ( jinfo.flags & 8 )  orient.x = frame_data[ jinfo.start_index + j++ ];
470                if ( jinfo.flags & 16 ) orient.y = frame_data[ jinfo.start_index + j++ ];
471                if ( jinfo.flags & 32 ) orient.z = frame_data[ jinfo.start_index + j++ ];
472                unit_quat_w( orient );
473
474                if ( parent_id >= 0 ) // Has a parent joint
475                {
476                        const transform_vector& ptv = m_joints[ size_t( parent_id ) ].keys;
477                        transform ptr;
478                        if ( ptv.size() > index ) ptr = ptv.get( index );
479                        glm::vec3 rot_pos = ptr.get_orientation() * pos;
480
481                        pos    = ptr.get_position() + rot_pos;
482                        orient = ptr.get_orientation() * orient;
483
484                        orient = glm::normalize( orient );
485                }
486
487                m_joints[i].keys.insert( transform( pos, orient ) );
488        }
489}
490
491mesh_data* nv::md5_loader::release_mesh_data( size_t index )
492{
493        mesh_data* result = m_meshes[ index ];
494        m_meshes[ index ] = nullptr;
495        return result;
496}
497
498md5_mesh_instance* nv::md5_mesh_data::spawn() const
499{
500        return new md5_mesh_instance( this );
501}
502
503nv::md5_loader::~md5_loader()
504{
505        for ( auto m : m_meshes ) { if (m) delete m; }
506}
507
508nv::md5_mesh_instance::md5_mesh_instance( const md5_mesh_data* a_data )
509        : m_data( a_data ), m_size( 0 ), m_indices( 0 ), m_pntdata( nullptr )
510{
511        m_size = m_data->m_vtx_data.size();
512        m_indices = m_data->get_count();
513        m_pntdata = new md5_vtx_pnt[ m_size ];
514        std::copy_n( m_data->m_pntdata, m_size, m_pntdata );
515}
516
517void nv::md5_mesh_instance::apply( const std::vector< transform >& skeleton )
518{
519        for ( unsigned int i = 0; i < m_size; ++i )
520        {
521                const md5_vtx_data& vert = m_data->m_vtx_data[i];
522                md5_vtx_pnt& result = m_pntdata[i];
523
524                result.position = glm::vec3(0);
525                result.normal   = glm::vec3(0);
526                result.tangent  = glm::vec3(0);
527
528                for ( size_t j = 0; j < vert.weight_count; ++j )
529                {
530                        const md5_weight& weight = m_data->m_weights[vert.start_weight + j];
531                        const transform& joint = skeleton[weight.joint_id];
532
533                        glm::vec3 rot_pos = joint.get_orientation() * weight.pos;
534                        result.position += ( joint.get_position() + rot_pos ) * weight.bias;
535
536                        result.normal  += ( joint.get_orientation() * vert.normal  ) * weight.bias;
537                        result.tangent += ( joint.get_orientation() * vert.tangent ) * weight.bias;
538                }
539        }
540}
Note: See TracBrowser for help on using the repository browser.