BVHLoader.js 8.3 KB

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