BVHLoader.js 8.5 KB

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