BVHLoader.js 8.8 KB

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