BVHLoader.js 9.2 KB

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