BVHLoader.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /**
  2. * @author herzig / http://github.com/herzig
  3. * @author Mugen87 / https://github.com/Mugen87
  4. *
  5. * Description: reads BVH files and outputs a single Skeleton and an AnimationClip
  6. *
  7. * Currently only supports bvh files containing a single root.
  8. *
  9. */
  10. import {
  11. AnimationClip,
  12. Bone,
  13. FileLoader,
  14. Loader,
  15. Quaternion,
  16. QuaternionKeyframeTrack,
  17. Skeleton,
  18. Vector3,
  19. VectorKeyframeTrack
  20. } from "../../../build/three.module.js";
  21. var BVHLoader = function ( manager ) {
  22. Loader.call( this, manager );
  23. this.animateBonePositions = true;
  24. this.animateBoneRotations = true;
  25. };
  26. BVHLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27. constructor: BVHLoader,
  28. load: function ( url, onLoad, onProgress, onError ) {
  29. var scope = this;
  30. var loader = new FileLoader( scope.manager );
  31. loader.setPath( scope.path );
  32. loader.load( url, function ( text ) {
  33. onLoad( scope.parse( text ) );
  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 Vector3(),
  89. rotation: new Quaternion()
  90. };
  91. bone.frames.push( keyframe );
  92. var quat = new Quaternion();
  93. var vx = new Vector3( 1, 0, 0 );
  94. var vy = new Vector3( 0, 1, 0 );
  95. var vz = new 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 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 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 Bone
  193. */
  194. function toTHREEBone( source, list ) {
  195. var bone = new 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 AnimationClip from the keyframe data saved in each bone.
  208. bone: bvh root node
  209. returns: a 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 VectorKeyframeTrack( '.bones[' + bone.name + '].position', times, positions ) );
  237. }
  238. if ( scope.animateBoneRotations ) {
  239. tracks.push( new QuaternionKeyframeTrack( '.bones[' + bone.name + '].quaternion', times, rotations ) );
  240. }
  241. }
  242. return new 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 Skeleton( threeBones ),
  261. clip: threeClip
  262. };
  263. }
  264. } );
  265. export { BVHLoader };