2
0

BVHLoader.js 8.9 KB

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