BVHLoader.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. ( function () {
  2. /**
  3. * Description: reads BVH files and outputs a single THREE.Skeleton and an THREE.AnimationClip
  4. *
  5. * Currently only supports bvh files containing a single root.
  6. *
  7. */
  8. var BVHLoader = function ( manager ) {
  9. THREE.Loader.call( this, manager );
  10. this.animateBonePositions = true;
  11. this.animateBoneRotations = true;
  12. };
  13. BVHLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  14. constructor: BVHLoader,
  15. load: function ( url, onLoad, onProgress, onError ) {
  16. var scope = this;
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setPath( scope.path );
  19. loader.setRequestHeader( scope.requestHeader );
  20. loader.setWithCredentials( scope.withCredentials );
  21. loader.load( url, function ( text ) {
  22. try {
  23. onLoad( scope.parse( text ) );
  24. } catch ( e ) {
  25. if ( onError ) {
  26. onError( e );
  27. } else {
  28. console.error( e );
  29. }
  30. scope.manager.itemError( url );
  31. }
  32. }, onProgress, onError );
  33. },
  34. parse: function ( text ) {
  35. /*
  36. reads a string array (lines) from a BVH file
  37. and outputs a skeleton structure including motion data
  38. returns thee root node:
  39. { name: '', channels: [], children: [] }
  40. */
  41. function readBvh( lines ) {
  42. // read model structure
  43. if ( nextLine( lines ) !== 'HIERARCHY' ) {
  44. console.error( 'THREE.BVHLoader: HIERARCHY expected.' );
  45. }
  46. var list = []; // collects flat array of all bones
  47. var root = readNode( lines, nextLine( lines ), list ); // read motion data
  48. if ( nextLine( lines ) !== 'MOTION' ) {
  49. console.error( 'THREE.BVHLoader: MOTION expected.' );
  50. } // number of frames
  51. var tokens = nextLine( lines ).split( /[\s]+/ );
  52. var numFrames = parseInt( tokens[ 1 ] );
  53. if ( isNaN( numFrames ) ) {
  54. console.error( 'THREE.BVHLoader: Failed to read number of frames.' );
  55. } // frame time
  56. tokens = nextLine( lines ).split( /[\s]+/ );
  57. var frameTime = parseFloat( tokens[ 2 ] );
  58. if ( isNaN( frameTime ) ) {
  59. console.error( 'THREE.BVHLoader: Failed to read frame time.' );
  60. } // read frame data line by line
  61. for ( var i = 0; i < numFrames; i ++ ) {
  62. tokens = nextLine( lines ).split( /[\s]+/ );
  63. readFrameData( tokens, i * frameTime, root );
  64. }
  65. return list;
  66. }
  67. /*
  68. Recursively reads data from a single frame into the bone hierarchy.
  69. The passed bone hierarchy has to be structured in the same order as the BVH file.
  70. keyframe data is stored in bone.frames.
  71. - data: splitted string array (frame values), values are shift()ed so
  72. this should be empty after parsing the whole hierarchy.
  73. - frameTime: playback time for this keyframe.
  74. - bone: the bone to read frame data from.
  75. */
  76. function readFrameData( data, frameTime, bone ) {
  77. // end sites have no motion data
  78. if ( bone.type === 'ENDSITE' ) return; // add keyframe
  79. var keyframe = {
  80. time: frameTime,
  81. position: new THREE.Vector3(),
  82. rotation: new THREE.Quaternion()
  83. };
  84. bone.frames.push( keyframe );
  85. var quat = new THREE.Quaternion();
  86. var vx = new THREE.Vector3( 1, 0, 0 );
  87. var vy = new THREE.Vector3( 0, 1, 0 );
  88. var vz = new THREE.Vector3( 0, 0, 1 ); // parse values for each channel in node
  89. for ( var i = 0; i < bone.channels.length; i ++ ) {
  90. switch ( bone.channels[ i ] ) {
  91. case 'Xposition':
  92. keyframe.position.x = parseFloat( data.shift().trim() );
  93. break;
  94. case 'Yposition':
  95. keyframe.position.y = parseFloat( data.shift().trim() );
  96. break;
  97. case 'Zposition':
  98. keyframe.position.z = parseFloat( data.shift().trim() );
  99. break;
  100. case 'Xrotation':
  101. quat.setFromAxisAngle( vx, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  102. keyframe.rotation.multiply( quat );
  103. break;
  104. case 'Yrotation':
  105. quat.setFromAxisAngle( vy, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  106. keyframe.rotation.multiply( quat );
  107. break;
  108. case 'Zrotation':
  109. quat.setFromAxisAngle( vz, parseFloat( data.shift().trim() ) * Math.PI / 180 );
  110. keyframe.rotation.multiply( quat );
  111. break;
  112. default:
  113. console.warn( 'THREE.BVHLoader: Invalid channel type.' );
  114. }
  115. } // parse child nodes
  116. for ( var i = 0; i < bone.children.length; i ++ ) {
  117. readFrameData( data, frameTime, bone.children[ i ] );
  118. }
  119. }
  120. /*
  121. Recursively parses the HIERACHY section of the BVH file
  122. - lines: all lines of the file. lines are consumed as we go along.
  123. - firstline: line containing the node type and name e.g. 'JOINT hip'
  124. - list: collects a flat list of nodes
  125. returns: a BVH node including children
  126. */
  127. function readNode( lines, firstline, list ) {
  128. var node = {
  129. name: '',
  130. type: '',
  131. frames: []
  132. };
  133. list.push( node ); // parse node type and name
  134. var tokens = firstline.split( /[\s]+/ );
  135. if ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) {
  136. node.type = 'ENDSITE';
  137. node.name = 'ENDSITE'; // bvh end sites have no name
  138. } else {
  139. node.name = tokens[ 1 ];
  140. node.type = tokens[ 0 ].toUpperCase();
  141. }
  142. if ( nextLine( lines ) !== '{' ) {
  143. console.error( 'THREE.BVHLoader: Expected opening { after type & name' );
  144. } // parse OFFSET
  145. tokens = nextLine( lines ).split( /[\s]+/ );
  146. if ( tokens[ 0 ] !== 'OFFSET' ) {
  147. console.error( 'THREE.BVHLoader: Expected OFFSET but got: ' + tokens[ 0 ] );
  148. }
  149. if ( tokens.length !== 4 ) {
  150. console.error( 'THREE.BVHLoader: Invalid number of values for OFFSET.' );
  151. }
  152. var offset = new THREE.Vector3( parseFloat( tokens[ 1 ] ), parseFloat( tokens[ 2 ] ), parseFloat( tokens[ 3 ] ) );
  153. if ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) {
  154. console.error( 'THREE.BVHLoader: Invalid values of OFFSET.' );
  155. }
  156. node.offset = offset; // parse CHANNELS definitions
  157. if ( node.type !== 'ENDSITE' ) {
  158. tokens = nextLine( lines ).split( /[\s]+/ );
  159. if ( tokens[ 0 ] !== 'CHANNELS' ) {
  160. console.error( 'THREE.BVHLoader: Expected CHANNELS definition.' );
  161. }
  162. var numChannels = parseInt( tokens[ 1 ] );
  163. node.channels = tokens.splice( 2, numChannels );
  164. node.children = [];
  165. } // read children
  166. while ( true ) {
  167. var line = nextLine( lines );
  168. if ( line === '}' ) {
  169. return node;
  170. } else {
  171. node.children.push( readNode( lines, line, list ) );
  172. }
  173. }
  174. }
  175. /*
  176. recursively converts the internal bvh node structure to a THREE.Bone hierarchy
  177. source: the bvh root node
  178. list: pass an empty array, collects a flat list of all converted THREE.Bones
  179. returns the root THREE.Bone
  180. */
  181. function toTHREEBone( source, list ) {
  182. var bone = new THREE.Bone();
  183. list.push( bone );
  184. bone.position.add( source.offset );
  185. bone.name = source.name;
  186. if ( source.type !== 'ENDSITE' ) {
  187. for ( var i = 0; i < source.children.length; i ++ ) {
  188. bone.add( toTHREEBone( source.children[ i ], list ) );
  189. }
  190. }
  191. return bone;
  192. }
  193. /*
  194. builds a THREE.AnimationClip from the keyframe data saved in each bone.
  195. bone: bvh root node
  196. returns: a THREE.AnimationClip containing position and quaternion tracks
  197. */
  198. function toTHREEAnimation( bones ) {
  199. var tracks = []; // create a position and quaternion animation track for each node
  200. for ( var i = 0; i < bones.length; i ++ ) {
  201. var bone = bones[ i ];
  202. if ( bone.type === 'ENDSITE' ) continue; // track data
  203. var times = [];
  204. var positions = [];
  205. var rotations = [];
  206. for ( var j = 0; j < bone.frames.length; j ++ ) {
  207. var frame = bone.frames[ j ];
  208. times.push( frame.time ); // the animation system animates the position property,
  209. // so we have to add the joint offset to all values
  210. positions.push( frame.position.x + bone.offset.x );
  211. positions.push( frame.position.y + bone.offset.y );
  212. positions.push( frame.position.z + bone.offset.z );
  213. rotations.push( frame.rotation.x );
  214. rotations.push( frame.rotation.y );
  215. rotations.push( frame.rotation.z );
  216. rotations.push( frame.rotation.w );
  217. }
  218. if ( scope.animateBonePositions ) {
  219. tracks.push( new THREE.VectorKeyframeTrack( '.bones[' + bone.name + '].position', times, positions ) );
  220. }
  221. if ( scope.animateBoneRotations ) {
  222. tracks.push( new THREE.QuaternionKeyframeTrack( '.bones[' + bone.name + '].quaternion', times, rotations ) );
  223. }
  224. }
  225. return new THREE.AnimationClip( 'animation', - 1, tracks );
  226. }
  227. /*
  228. returns the next non-empty line in lines
  229. */
  230. function nextLine( lines ) {
  231. var line; // skip empty lines
  232. while ( ( line = lines.shift().trim() ).length === 0 ) {}
  233. return line;
  234. }
  235. var scope = this;
  236. var lines = text.split( /[\r\n]+/g );
  237. var bones = readBvh( lines );
  238. var threeBones = [];
  239. toTHREEBone( bones[ 0 ], threeBones );
  240. var threeClip = toTHREEAnimation( bones );
  241. return {
  242. skeleton: new THREE.Skeleton( threeBones ),
  243. clip: threeClip
  244. };
  245. }
  246. } );
  247. THREE.BVHLoader = BVHLoader;
  248. } )();