BVHLoader.js 9.2 KB

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