KeyframeTrack.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import { StringKeyframeTrack } from './tracks/StringKeyframeTrack.js';
  2. import { BooleanKeyframeTrack } from './tracks/BooleanKeyframeTrack.js';
  3. import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack.js';
  4. import { ColorKeyframeTrack } from './tracks/ColorKeyframeTrack.js';
  5. import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack.js';
  6. import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack.js';
  7. import {
  8. InterpolateLinear,
  9. InterpolateSmooth,
  10. InterpolateDiscrete
  11. } from '../constants.js';
  12. import { CubicInterpolant } from '../math/interpolants/CubicInterpolant.js';
  13. import { LinearInterpolant } from '../math/interpolants/LinearInterpolant.js';
  14. import { DiscreteInterpolant } from '../math/interpolants/DiscreteInterpolant.js';
  15. import { AnimationUtils } from './AnimationUtils.js';
  16. /**
  17. *
  18. * A timed sequence of keyframes for a specific property.
  19. *
  20. *
  21. * @author Ben Houston / http://clara.io/
  22. * @author David Sarno / http://lighthaus.us/
  23. * @author tschw
  24. */
  25. function KeyframeTrack( name, times, values, interpolation ) {
  26. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  27. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  28. this.name = name;
  29. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  30. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  31. this.setInterpolation( interpolation || this.DefaultInterpolation );
  32. }
  33. // Static methods:
  34. Object.assign( KeyframeTrack, {
  35. // Serialization (in static context, because of constructor invocation
  36. // and automatic invocation of .toJSON):
  37. parse: function ( json ) {
  38. if ( json.type === undefined ) {
  39. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  40. }
  41. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  42. if ( json.times === undefined ) {
  43. var times = [], values = [];
  44. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  45. json.times = times;
  46. json.values = values;
  47. }
  48. // derived classes can define a static parse method
  49. if ( trackType.parse !== undefined ) {
  50. return trackType.parse( json );
  51. } else {
  52. // by default, we assume a constructor compatible with the base
  53. return new trackType( json.name, json.times, json.values, json.interpolation );
  54. }
  55. },
  56. toJSON: function ( track ) {
  57. var trackType = track.constructor;
  58. var json;
  59. // derived classes can define a static toJSON method
  60. if ( trackType.toJSON !== undefined ) {
  61. json = trackType.toJSON( track );
  62. } else {
  63. // by default, we assume the data can be serialized as-is
  64. json = {
  65. 'name': track.name,
  66. 'times': AnimationUtils.convertArray( track.times, Array ),
  67. 'values': AnimationUtils.convertArray( track.values, Array )
  68. };
  69. var interpolation = track.getInterpolation();
  70. if ( interpolation !== track.DefaultInterpolation ) {
  71. json.interpolation = interpolation;
  72. }
  73. }
  74. json.type = track.ValueTypeName; // mandatory
  75. return json;
  76. },
  77. _getTrackTypeForValueTypeName: function ( typeName ) {
  78. switch ( typeName.toLowerCase() ) {
  79. case 'scalar':
  80. case 'double':
  81. case 'float':
  82. case 'number':
  83. case 'integer':
  84. return NumberKeyframeTrack;
  85. case 'vector':
  86. case 'vector2':
  87. case 'vector3':
  88. case 'vector4':
  89. return VectorKeyframeTrack;
  90. case 'color':
  91. return ColorKeyframeTrack;
  92. case 'quaternion':
  93. return QuaternionKeyframeTrack;
  94. case 'bool':
  95. case 'boolean':
  96. return BooleanKeyframeTrack;
  97. case 'string':
  98. return StringKeyframeTrack;
  99. }
  100. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  101. }
  102. } );
  103. Object.assign( KeyframeTrack.prototype, {
  104. constructor: KeyframeTrack,
  105. TimeBufferType: Float32Array,
  106. ValueBufferType: Float32Array,
  107. DefaultInterpolation: InterpolateLinear,
  108. InterpolantFactoryMethodDiscrete: function ( result ) {
  109. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  110. },
  111. InterpolantFactoryMethodLinear: function ( result ) {
  112. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  113. },
  114. InterpolantFactoryMethodSmooth: function ( result ) {
  115. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  116. },
  117. setInterpolation: function ( interpolation ) {
  118. var factoryMethod;
  119. switch ( interpolation ) {
  120. case InterpolateDiscrete:
  121. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  122. break;
  123. case InterpolateLinear:
  124. factoryMethod = this.InterpolantFactoryMethodLinear;
  125. break;
  126. case InterpolateSmooth:
  127. factoryMethod = this.InterpolantFactoryMethodSmooth;
  128. break;
  129. }
  130. if ( factoryMethod === undefined ) {
  131. var message = "unsupported interpolation for " +
  132. this.ValueTypeName + " keyframe track named " + this.name;
  133. if ( this.createInterpolant === undefined ) {
  134. // fall back to default, unless the default itself is messed up
  135. if ( interpolation !== this.DefaultInterpolation ) {
  136. this.setInterpolation( this.DefaultInterpolation );
  137. } else {
  138. throw new Error( message ); // fatal, in this case
  139. }
  140. }
  141. console.warn( 'THREE.KeyframeTrack:', message );
  142. return this;
  143. }
  144. this.createInterpolant = factoryMethod;
  145. return this;
  146. },
  147. getInterpolation: function () {
  148. switch ( this.createInterpolant ) {
  149. case this.InterpolantFactoryMethodDiscrete:
  150. return InterpolateDiscrete;
  151. case this.InterpolantFactoryMethodLinear:
  152. return InterpolateLinear;
  153. case this.InterpolantFactoryMethodSmooth:
  154. return InterpolateSmooth;
  155. }
  156. },
  157. getValueSize: function () {
  158. return this.values.length / this.times.length;
  159. },
  160. // move all keyframes either forwards or backwards in time
  161. shift: function ( timeOffset ) {
  162. if ( timeOffset !== 0.0 ) {
  163. var times = this.times;
  164. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  165. times[ i ] += timeOffset;
  166. }
  167. }
  168. return this;
  169. },
  170. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  171. scale: function ( timeScale ) {
  172. if ( timeScale !== 1.0 ) {
  173. var times = this.times;
  174. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  175. times[ i ] *= timeScale;
  176. }
  177. }
  178. return this;
  179. },
  180. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  181. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  182. trim: function ( startTime, endTime ) {
  183. var times = this.times,
  184. nKeys = times.length,
  185. from = 0,
  186. to = nKeys - 1;
  187. while ( from !== nKeys && times[ from ] < startTime ) {
  188. ++ from;
  189. }
  190. while ( to !== - 1 && times[ to ] > endTime ) {
  191. -- to;
  192. }
  193. ++ to; // inclusive -> exclusive bound
  194. if ( from !== 0 || to !== nKeys ) {
  195. // empty tracks are forbidden, so keep at least one keyframe
  196. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  197. var stride = this.getValueSize();
  198. this.times = AnimationUtils.arraySlice( times, from, to );
  199. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  200. }
  201. return this;
  202. },
  203. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  204. validate: function () {
  205. var valid = true;
  206. var valueSize = this.getValueSize();
  207. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  208. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  209. valid = false;
  210. }
  211. var times = this.times,
  212. values = this.values,
  213. nKeys = times.length;
  214. if ( nKeys === 0 ) {
  215. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  216. valid = false;
  217. }
  218. var prevTime = null;
  219. for ( var i = 0; i !== nKeys; i ++ ) {
  220. var currTime = times[ i ];
  221. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  222. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  223. valid = false;
  224. break;
  225. }
  226. if ( prevTime !== null && prevTime > currTime ) {
  227. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  228. valid = false;
  229. break;
  230. }
  231. prevTime = currTime;
  232. }
  233. if ( values !== undefined ) {
  234. if ( AnimationUtils.isTypedArray( values ) ) {
  235. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  236. var value = values[ i ];
  237. if ( isNaN( value ) ) {
  238. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  239. valid = false;
  240. break;
  241. }
  242. }
  243. }
  244. }
  245. return valid;
  246. },
  247. // removes equivalent sequential keys as common in morph target sequences
  248. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  249. optimize: function () {
  250. var times = this.times,
  251. values = this.values,
  252. stride = this.getValueSize(),
  253. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  254. writeIndex = 1,
  255. lastIndex = times.length - 1;
  256. for ( var i = 1; i < lastIndex; ++ i ) {
  257. var keep = false;
  258. var time = times[ i ];
  259. var timeNext = times[ i + 1 ];
  260. // remove adjacent keyframes scheduled at the same time
  261. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  262. if ( ! smoothInterpolation ) {
  263. // remove unnecessary keyframes same as their neighbors
  264. var offset = i * stride,
  265. offsetP = offset - stride,
  266. offsetN = offset + stride;
  267. for ( var j = 0; j !== stride; ++ j ) {
  268. var value = values[ offset + j ];
  269. if ( value !== values[ offsetP + j ] ||
  270. value !== values[ offsetN + j ] ) {
  271. keep = true;
  272. break;
  273. }
  274. }
  275. } else {
  276. keep = true;
  277. }
  278. }
  279. // in-place compaction
  280. if ( keep ) {
  281. if ( i !== writeIndex ) {
  282. times[ writeIndex ] = times[ i ];
  283. var readOffset = i * stride,
  284. writeOffset = writeIndex * stride;
  285. for ( var j = 0; j !== stride; ++ j ) {
  286. values[ writeOffset + j ] = values[ readOffset + j ];
  287. }
  288. }
  289. ++ writeIndex;
  290. }
  291. }
  292. // flush last keyframe (compaction looks ahead)
  293. if ( lastIndex > 0 ) {
  294. times[ writeIndex ] = times[ lastIndex ];
  295. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  296. values[ writeOffset + j ] = values[ readOffset + j ];
  297. }
  298. ++ writeIndex;
  299. }
  300. if ( writeIndex !== times.length ) {
  301. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  302. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  303. }
  304. return this;
  305. }
  306. } );
  307. export { KeyframeTrack };