BVHLoader.js 8.8 KB

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