BVHLoader.js 9.0 KB

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