animationCurveEditorComponent.tsx 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. import * as React from "react";
  2. import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
  3. import { faTimes } from "@fortawesome/free-solid-svg-icons";
  4. import { Animation } from 'babylonjs/Animations/animation';
  5. import { Vector2, Vector3, Quaternion } from 'babylonjs/Maths/math.vector';
  6. import { Size } from 'babylonjs/Maths/math.size';
  7. import { Color3, Color4 } from 'babylonjs/Maths/math.color';
  8. import { EasingFunction } from 'babylonjs/Animations/easing';
  9. import { IAnimationKey } from 'babylonjs/Animations/animationKey';
  10. import { IKeyframeSvgPoint } from './keyframeSvgPoint';
  11. import { SvgDraggableArea } from './svgDraggableArea';
  12. import { Timeline } from './timeline';
  13. import { Playhead } from './playhead';
  14. import { Notification } from './notification';
  15. import { GraphActionsBar } from './graphActionsBar';
  16. import { Scene } from "babylonjs/scene";
  17. import { ButtonLineComponent } from '../../../lines/buttonLineComponent';
  18. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  19. import { TargetedAnimation } from "babylonjs/Animations/animationGroup";
  20. import { Nullable } from 'babylonjs/types';
  21. require("./curveEditor.scss");
  22. interface IAnimationCurveEditorComponentProps {
  23. close: (event: any) => void;
  24. playOrPause?: () => void;
  25. title: string;
  26. scene: Scene;
  27. entity: IAnimatable | TargetedAnimation;
  28. }
  29. interface ICanvasAxis {
  30. value: number;
  31. label: number;
  32. }
  33. export class AnimationCurveEditorComponent extends React.Component<IAnimationCurveEditorComponentProps, {
  34. animationName: string,
  35. animationType: string,
  36. animationTargetProperty: string,
  37. isOpen: boolean,
  38. selected: Animation | null,
  39. currentPathData: string | undefined,
  40. svgKeyframes: IKeyframeSvgPoint[] | undefined,
  41. currentFrame: number,
  42. currentValue: number,
  43. frameAxisLength: ICanvasAxis[],
  44. valueAxisLength: ICanvasAxis[],
  45. isFlatTangentMode: boolean,
  46. isTangentMode: boolean,
  47. isBrokenMode: boolean,
  48. lerpMode: boolean,
  49. scale: number,
  50. playheadOffset: number,
  51. notification: string,
  52. currentPoint: SVGPoint | undefined,
  53. lastFrame: number,
  54. playheadPos: number,
  55. isPlaying: boolean
  56. }> {
  57. // Height scale *Review this functionaliy
  58. private _heightScale: number = 100;
  59. // Canvas Length *Review this functionality
  60. readonly _entityName: string;
  61. readonly _canvasLength: number = 20;
  62. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  63. private _frames: Vector2[] = [];
  64. private _isPlaying: boolean = false;
  65. private _graphCanvas: React.RefObject<HTMLDivElement>;
  66. private _selectedCurve: React.RefObject<SVGPathElement>;
  67. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  68. private _isTargetedAnimation: boolean;
  69. constructor(props: IAnimationCurveEditorComponentProps) {
  70. super(props);
  71. this._entityName = (this.props.entity as any).id;
  72. // Review is we really need this refs
  73. this._graphCanvas = React.createRef();
  74. this._selectedCurve = React.createRef();
  75. this._svgCanvas = React.createRef();
  76. console.log(this.props.entity instanceof TargetedAnimation)
  77. let initialSelection;
  78. let initialPathData;
  79. let initialLerpMode;
  80. if (this.props.entity instanceof TargetedAnimation) {
  81. this._isTargetedAnimation = true;
  82. initialSelection = this.props.entity.animation;
  83. initialLerpMode = this.analizeAnimation(this.props.entity.animation);
  84. initialPathData = this.getPathData(this.props.entity.animation);
  85. } else {
  86. this._isTargetedAnimation = false;
  87. initialLerpMode = this.analizeAnimation(this.props.entity.animations && this.props.entity.animations[0]);
  88. initialSelection = this.props.entity.animations !== null ? this.props.entity.animations[0] : null;
  89. initialPathData = this.props.entity.animations !== null ? this.getPathData(this.props.entity.animations[0]) : "";
  90. }
  91. // will update this until we have a top scroll/zoom feature
  92. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  93. this.state = {
  94. selected: initialSelection,
  95. isOpen: true,
  96. currentPathData: initialPathData,
  97. svgKeyframes: this._svgKeyframes,
  98. animationTargetProperty: 'position.x',
  99. animationName: "",
  100. animationType: "Float",
  101. currentFrame: 0,
  102. currentValue: 1,
  103. isFlatTangentMode: false,
  104. isTangentMode: false,
  105. isBrokenMode: false,
  106. lerpMode: initialLerpMode,
  107. playheadOffset: this._graphCanvas.current ? (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10) : 0,
  108. frameAxisLength: (new Array(this._canvasLength)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } }),
  109. valueAxisLength: (new Array(10)).fill(0).map((s, i) => { return { value: i * 10, label: valueInd[i] } }),
  110. notification: "",
  111. lastFrame: 0,
  112. currentPoint: undefined,
  113. scale: 1,
  114. playheadPos: 0,
  115. isPlaying: this.isAnimationPlaying()
  116. }
  117. }
  118. componentDidMount() {
  119. setTimeout(() => this.resetPlayheadOffset(), 500);
  120. }
  121. /**
  122. * Notifications
  123. * To add notification we set the state and clear to make the notification bar hide.
  124. */
  125. clearNotification() {
  126. this.setState({ notification: "" });
  127. }
  128. /**
  129. * Zoom and Scroll
  130. * This section handles zoom and scroll
  131. * of the graph area.
  132. */
  133. zoom(e: React.WheelEvent<HTMLDivElement>) {
  134. e.nativeEvent.stopImmediatePropagation();
  135. console.log(e.deltaY);
  136. let scaleX = 1;
  137. if (Math.sign(e.deltaY) === -1) {
  138. scaleX = (this.state.scale - 0.01);
  139. } else {
  140. scaleX = (this.state.scale + 0.01);
  141. }
  142. this.setState({ scale: scaleX }, this.setAxesLength);
  143. }
  144. setAxesLength() {
  145. let length = Math.round(this._canvasLength * this.state.scale);// Check Undefined, or NaN
  146. let highestFrame = 100;
  147. if (this.state.selected !== null) {
  148. highestFrame = this.state.selected.getHighestFrame();
  149. }
  150. if (length < (highestFrame * 2) / 10) {
  151. length = (highestFrame * 2) / 10
  152. }
  153. let valueLines = Math.round((this.state.scale * this._heightScale) / 10);
  154. let newFrameLength = (new Array(length)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } });
  155. let newValueLength = (new Array(valueLines)).fill(0).map((s, i) => { return { value: i * 10, label: this.getValueLabel(i * 10) } });
  156. this.setState({ frameAxisLength: newFrameLength, valueAxisLength: newValueLength });
  157. this.resetPlayheadOffset();
  158. }
  159. getValueLabel(i: number) {
  160. // Need to update this when Y axis grows
  161. let label = 0;
  162. if (i === 0) {
  163. label = 2;
  164. }
  165. if (i === 50) {
  166. label = 1;
  167. } else {
  168. label = ((100 - (i * 2)) * 0.01) + 1;
  169. }
  170. return label;
  171. }
  172. resetPlayheadOffset() {
  173. if (this._graphCanvas && this._graphCanvas.current) {
  174. this.setState({ playheadOffset: (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10 * this.state.scale) });
  175. }
  176. }
  177. /**
  178. * Add New Animation
  179. * This section handles events from AnimationCreation.
  180. */
  181. handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {
  182. event.preventDefault();
  183. this.setState({ animationName: event.target.value.trim() });
  184. }
  185. handleTypeChange(event: React.ChangeEvent<HTMLSelectElement>) {
  186. event.preventDefault();
  187. this.setState({ animationType: event.target.value });
  188. }
  189. handlePropertyChange(event: React.ChangeEvent<HTMLInputElement>) {
  190. event.preventDefault();
  191. this.setState({ animationTargetProperty: event.target.value });
  192. }
  193. setListItem(animation: Animation, i: number) {
  194. let element;
  195. switch (animation.dataType) {
  196. case Animation.ANIMATIONTYPE_FLOAT:
  197. element = <li className={this.state.selected && this.state.selected.name === animation.name ? 'active' : ''} key={i} onClick={() => this.selectAnimation(animation)}>
  198. <p>{animation.name}&nbsp;
  199. <span>{animation.targetProperty}</span></p>
  200. {!(this.props.entity instanceof TargetedAnimation) ? this.state.selected && this.state.selected.name === animation.name ? <ButtonLineComponent label={"Remove"} onClick={() => this.deleteAnimation()} /> : null : null}
  201. </li>
  202. break;
  203. case Animation.ANIMATIONTYPE_VECTOR2:
  204. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  205. <ul>
  206. <li key={`${i}_x`}>Property <strong>X</strong></li>
  207. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  208. </ul>
  209. </li>
  210. break;
  211. case Animation.ANIMATIONTYPE_VECTOR3:
  212. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  213. <ul>
  214. <li key={`${i}_x`}>Property <strong>X</strong></li>
  215. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  216. <li key={`${i}_z`}>Property <strong>Z</strong></li>
  217. </ul>
  218. </li>
  219. break;
  220. case Animation.ANIMATIONTYPE_QUATERNION:
  221. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  222. <ul>
  223. <li key={`${i}_x`}>Property <strong>X</strong></li>
  224. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  225. <li key={`${i}_z`}>Property <strong>Z</strong></li>
  226. <li key={`${i}_w`}>Property <strong>W</strong></li>
  227. </ul>
  228. </li>
  229. break;
  230. case Animation.ANIMATIONTYPE_COLOR3:
  231. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  232. <ul>
  233. <li key={`${i}_r`}>Property <strong>R</strong></li>
  234. <li key={`${i}_g`}>Property <strong>G</strong></li>
  235. <li key={`${i}_b`}>Property <strong>B</strong></li>
  236. </ul>
  237. </li>
  238. break;
  239. case Animation.ANIMATIONTYPE_COLOR4:
  240. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  241. <ul>
  242. <li key={`${i}_r`}>Property <strong>R</strong></li>
  243. <li key={`${i}_g`}>Property <strong>G</strong></li>
  244. <li key={`${i}_b`}>Property <strong>B</strong></li>
  245. <li key={`${i}_a`}>Property <strong>A</strong></li>
  246. </ul>
  247. </li>
  248. break;
  249. case Animation.ANIMATIONTYPE_SIZE:
  250. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  251. <ul>
  252. <li key={`${i}_width`}>Property <strong>Width</strong></li>
  253. <li key={`${i}_height`}>Property <strong>Height</strong></li>
  254. </ul>
  255. </li>
  256. break;
  257. default: console.log("not recognized");
  258. element = null;
  259. break;
  260. }
  261. return element;
  262. }
  263. getAnimationTypeofChange(selected: string) {
  264. let dataType = 0;
  265. switch (selected) {
  266. case "Float":
  267. dataType = Animation.ANIMATIONTYPE_FLOAT;
  268. break;
  269. case "Quaternion":
  270. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  271. break;
  272. case "Vector3":
  273. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  274. break;
  275. case "Vector2":
  276. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  277. break;
  278. case "Size":
  279. dataType = Animation.ANIMATIONTYPE_SIZE;
  280. break;
  281. case "Color3":
  282. dataType = Animation.ANIMATIONTYPE_COLOR3;
  283. break;
  284. case "Color4":
  285. dataType = Animation.ANIMATIONTYPE_COLOR4;
  286. break;
  287. }
  288. return dataType;
  289. }
  290. deleteAnimation() {
  291. let currentSelected = this.state.selected;
  292. if (this.props.entity instanceof TargetedAnimation) {
  293. console.log("no animation remove allowed");
  294. } else {
  295. let animations = (this.props.entity as IAnimatable).animations;
  296. if (animations) {
  297. let updatedAnimations = animations.filter(anim => anim !== currentSelected);
  298. (this.props.entity as IAnimatable).animations = updatedAnimations as Nullable<Animation[]>;
  299. }
  300. }
  301. }
  302. addAnimation() {
  303. if (this.state.animationName != "" && this.state.animationTargetProperty != "") {
  304. let matchTypeTargetProperty = this.state.animationTargetProperty.split('.');
  305. let animationDataType = this.getAnimationTypeofChange(this.state.animationType);
  306. let matched = false;
  307. if (matchTypeTargetProperty.length === 1) {
  308. let match = (this.props.entity as any)[matchTypeTargetProperty[0]];
  309. if (match) {
  310. switch (match.constructor.name) {
  311. case "Vector2":
  312. animationDataType === Animation.ANIMATIONTYPE_VECTOR2 ? matched = true : matched = false;
  313. break;
  314. case "Vector3":
  315. animationDataType === Animation.ANIMATIONTYPE_VECTOR3 ? matched = true : matched = false;
  316. break;
  317. case "Quaternion":
  318. animationDataType === Animation.ANIMATIONTYPE_QUATERNION ? matched = true : matched = false;
  319. break;
  320. case "Color3":
  321. animationDataType === Animation.ANIMATIONTYPE_COLOR3 ? matched = true : matched = false;
  322. break;
  323. case "Color4":
  324. animationDataType === Animation.ANIMATIONTYPE_COLOR4 ? matched = true : matched = false;
  325. break;
  326. case "Size":
  327. animationDataType === Animation.ANIMATIONTYPE_SIZE ? matched = true : matched = false;
  328. break;
  329. default: console.log("not recognized");
  330. break;
  331. }
  332. } else {
  333. this.setState({ notification: `The selected entity doesn't have a ${matchTypeTargetProperty[0]} property` });
  334. }
  335. } else if (matchTypeTargetProperty.length > 1) {
  336. let match = (this.props.entity as any)[matchTypeTargetProperty[0]][matchTypeTargetProperty[1]];
  337. if (typeof match === "number") {
  338. animationDataType === Animation.ANIMATIONTYPE_FLOAT ? matched = true : matched = false;
  339. }
  340. }
  341. if (matched) {
  342. let startValue;
  343. let endValue;
  344. let outTangent;
  345. let inTangent;
  346. // Default start and end values for new animations
  347. switch (animationDataType) {
  348. case Animation.ANIMATIONTYPE_FLOAT:
  349. startValue = 1;
  350. endValue = 1;
  351. outTangent = 0;
  352. inTangent = 0;
  353. break;
  354. case Animation.ANIMATIONTYPE_VECTOR2:
  355. startValue = new Vector2(1, 1);
  356. endValue = new Vector2(1, 1);
  357. outTangent = Vector2.Zero();
  358. inTangent = Vector2.Zero();
  359. break;
  360. case Animation.ANIMATIONTYPE_VECTOR3:
  361. startValue = new Vector3(1, 1, 1);
  362. endValue = new Vector3(1, 1, 1);
  363. outTangent = Vector3.Zero();
  364. inTangent = Vector3.Zero();
  365. break;
  366. case Animation.ANIMATIONTYPE_QUATERNION:
  367. startValue = new Quaternion(1, 1, 1, 1);
  368. endValue = new Quaternion(1, 1, 1, 1);
  369. outTangent = Quaternion.Zero();
  370. inTangent = Quaternion.Zero();
  371. break;
  372. case Animation.ANIMATIONTYPE_COLOR3:
  373. startValue = new Color3(1, 1, 1);
  374. endValue = new Color3(1, 1, 1);
  375. outTangent = new Color3(0, 0, 0);
  376. inTangent = new Color3(0, 0, 0);
  377. break;
  378. case Animation.ANIMATIONTYPE_COLOR4:
  379. startValue = new Color4(1, 1, 1, 1);
  380. endValue = new Color4(1, 1, 1, 1);
  381. outTangent = new Color4(0, 0, 0, 0);
  382. inTangent = new Color4(0, 0, 0, 0);
  383. break;
  384. case Animation.ANIMATIONTYPE_SIZE:
  385. startValue = new Size(1, 1);
  386. endValue = new Size(1, 1);
  387. outTangent = Size.Zero();
  388. inTangent = Size.Zero();
  389. break;
  390. default: console.log("not recognized");
  391. break;
  392. }
  393. let alreadyAnimatedProperty = (this.props.entity as IAnimatable).animations?.find(anim =>
  394. anim.targetProperty === this.state.animationTargetProperty
  395. , this);
  396. let alreadyAnimationName = (this.props.entity as IAnimatable).animations?.find(anim =>
  397. anim.name === this.state.animationName
  398. , this);
  399. if (alreadyAnimatedProperty) {
  400. this.setState({ notification: `The property "${this.state.animationTargetProperty}" already has an animation` });
  401. } else if (alreadyAnimationName) {
  402. this.setState({ notification: `There is already an animation with the name: "${this.state.animationName}"` });
  403. } else {
  404. let animation = new Animation(this.state.animationName, this.state.animationTargetProperty, 30, animationDataType);
  405. // Start with two keyframes
  406. var keys = [];
  407. keys.push({
  408. frame: 0,
  409. value: startValue,
  410. outTangent: outTangent
  411. });
  412. keys.push({
  413. inTangent: inTangent,
  414. frame: 100,
  415. value: endValue
  416. });
  417. animation.setKeys(keys);
  418. (this.props.entity as IAnimatable).animations?.push(animation);
  419. }
  420. } else {
  421. this.setState({ notification: `The property "${this.state.animationTargetProperty}" is not a "${this.state.animationType}" type` });
  422. }
  423. } else {
  424. this.setState({ notification: "You need to provide a name and target property." });
  425. }
  426. }
  427. /**
  428. * Keyframe Manipulation
  429. * This section handles events from SvgDraggableArea.
  430. */
  431. selectKeyframe(id: string) {
  432. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  433. if (kf.id === id) {
  434. kf.selected = !kf.selected
  435. }
  436. return kf;
  437. });
  438. this.setState({ svgKeyframes: updatedKeyframes });
  439. }
  440. selectedControlPoint(type: string, id: string) {
  441. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  442. if (kf.id === id) {
  443. this.setState({ isFlatTangentMode: false });
  444. if (type === "left") {
  445. kf.isLeftActive = !kf.isLeftActive;
  446. kf.isRightActive = false;
  447. }
  448. if (type === "right") {
  449. kf.isRightActive = !kf.isRightActive;
  450. kf.isLeftActive = false;
  451. }
  452. }
  453. return kf;
  454. });
  455. this.setState({ svgKeyframes: updatedKeyframes });
  456. }
  457. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) {
  458. let animation = this.state.selected as Animation;
  459. // Bug: After play/stop we get an extra keyframe at 0
  460. let keys = [...animation.getKeys()];
  461. let newFrame = 0;
  462. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  463. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  464. newFrame = 1;
  465. } else {
  466. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x);
  467. }
  468. }
  469. keys[index].frame = newFrame; // This value comes as percentage/frame/time
  470. keys[index].value = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2; // this value comes inverted svg from 0 = 100 to 100 = 0
  471. if (updatedSvgKeyFrame.isLeftActive) {
  472. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  473. // Rotate
  474. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.leftControlPoint.y) / this._heightScale) * 2;
  475. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  476. keys[index].inTangent = keyframeValue - updatedValue;
  477. if (!this.state.isBrokenMode) {
  478. // Right control point if exists
  479. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  480. // Sets opposite value
  481. keys[index].outTangent = keys[index].inTangent * -1
  482. }
  483. }
  484. }
  485. }
  486. if (updatedSvgKeyFrame.isRightActive) {
  487. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  488. // Rotate
  489. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.rightControlPoint.y) / this._heightScale) * 2;
  490. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  491. keys[index].outTangent = keyframeValue - updatedValue;
  492. if (!this.state.isBrokenMode) {
  493. if (updatedSvgKeyFrame.leftControlPoint !== null) { // Sets opposite value
  494. keys[index].inTangent = keys[index].outTangent * -1
  495. }
  496. }
  497. }
  498. }
  499. animation.setKeys(keys);
  500. this.selectAnimation(animation);
  501. }
  502. /**
  503. * Actions
  504. * This section handles events from GraphActionsBar.
  505. */
  506. handleFrameChange(event: React.ChangeEvent<HTMLInputElement>) {
  507. event.preventDefault();
  508. this.changeCurrentFrame(parseInt(event.target.value))
  509. }
  510. handleValueChange(event: React.ChangeEvent<HTMLInputElement>) {
  511. event.preventDefault();
  512. this.setState({ currentValue: parseFloat(event.target.value) }, () => {
  513. if (this.state.selected !== null) {
  514. let animation = this.state.selected;
  515. let keys = animation.getKeys();
  516. let isKeyframe = keys.find(k => k.frame === this.state.currentFrame);
  517. if (isKeyframe) {
  518. let updatedKeys = keys.map(k => {
  519. if (k.frame === this.state.currentFrame) {
  520. k.value = this.state.currentValue;
  521. }
  522. return k;
  523. });
  524. this.state.selected.setKeys(updatedKeys);
  525. this.selectAnimation(animation);
  526. }
  527. }
  528. });
  529. }
  530. setFlatTangent() {
  531. if (this.state.selected !== null) {
  532. let animation = this.state.selected;
  533. this.setState({ isFlatTangentMode: !this.state.isFlatTangentMode }, () => this.selectAnimation(animation));
  534. }
  535. }
  536. // Use this for Bezier curve mode
  537. setTangentMode() {
  538. if (this.state.selected !== null) {
  539. let animation = this.state.selected;
  540. this.setState({ isTangentMode: !this.state.isTangentMode }, () => this.selectAnimation(animation));
  541. }
  542. }
  543. setBrokenMode() {
  544. if (this.state.selected !== null) {
  545. let animation = this.state.selected;
  546. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () => this.selectAnimation(animation));
  547. }
  548. }
  549. setLerpMode() {
  550. if (this.state.selected !== null) {
  551. let animation = this.state.selected;
  552. this.setState({ lerpMode: !this.state.lerpMode }, () => this.selectAnimation(animation));
  553. }
  554. }
  555. addKeyframeClick() {
  556. if (this.state.selected !== null) {
  557. let currentAnimation = this.state.selected;
  558. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  559. let keys = currentAnimation.getKeys();
  560. let x = this.state.currentFrame;
  561. let y = this.state.currentValue;
  562. keys.push({ frame: x, value: y, inTangent: 0, outTangent: 0 });
  563. keys.sort((a, b) => a.frame - b.frame);
  564. currentAnimation.setKeys(keys);
  565. this.selectAnimation(currentAnimation);
  566. }
  567. }
  568. }
  569. removeKeyframeClick() {
  570. if (this.state.selected !== null) {
  571. let currentAnimation = this.state.selected;
  572. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  573. let keys = currentAnimation.getKeys();
  574. let x = this.state.currentFrame;
  575. let filteredKeys = keys.filter(kf => kf.frame !== x);
  576. currentAnimation.setKeys(filteredKeys);
  577. this.selectAnimation(currentAnimation);
  578. }
  579. }
  580. }
  581. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  582. event.preventDefault();
  583. if (this.state.selected !== null) {
  584. var svg = event.target as SVGSVGElement;
  585. var pt = svg.createSVGPoint();
  586. pt.x = event.clientX;
  587. pt.y = event.clientY;
  588. var inverse = svg.getScreenCTM()?.inverse();
  589. var cursorpt = pt.matrixTransform(inverse);
  590. var currentAnimation = this.state.selected;
  591. var keys = currentAnimation.getKeys();
  592. var height = 100;
  593. var middle = (height / 2);
  594. var keyValue;
  595. if (cursorpt.y < middle) {
  596. keyValue = 1 + ((100 / cursorpt.y) * .1)
  597. }
  598. if (cursorpt.y > middle) {
  599. keyValue = 1 - ((100 / cursorpt.y) * .1)
  600. }
  601. keys.push({ frame: cursorpt.x, value: keyValue });
  602. currentAnimation.setKeys(keys);
  603. this.selectAnimation(currentAnimation);
  604. }
  605. }
  606. updateKeyframe(keyframe: Vector2, index: number) {
  607. let anim = this.state.selected as Animation;
  608. var keys: IAnimationKey[] = [];
  609. var svgKeyframes = this.state.svgKeyframes?.map((k, i) => {
  610. if (i === index) {
  611. k.keyframePoint.x = keyframe.x;
  612. k.keyframePoint.y = keyframe.y;
  613. }
  614. var height = 100;
  615. var middle = (height / 2);
  616. var keyValue;
  617. if (k.keyframePoint.y < middle) {
  618. keyValue = 1 + ((100 / k.keyframePoint.y) * .1)
  619. }
  620. if (k.keyframePoint.y > middle) {
  621. keyValue = 1 - ((100 / k.keyframePoint.y) * .1)
  622. }
  623. keys.push({ frame: k.keyframePoint.x, value: keyValue })
  624. return k;
  625. });
  626. anim.setKeys(keys);
  627. this.setState({ svgKeyframes: svgKeyframes });
  628. }
  629. /**
  630. * Curve Rendering Functions
  631. * This section handles how to render curves.
  632. */
  633. getAnimationProperties(animation: Animation) {
  634. let easingType, easingMode;
  635. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  636. if (easingFunction === undefined) {
  637. easingType = undefined
  638. easingMode = undefined;
  639. } else {
  640. easingType = easingFunction.constructor.name;
  641. easingMode = easingFunction.getEasingMode();
  642. }
  643. return { easingType, easingMode }
  644. }
  645. linearInterpolation(keyframes: IAnimationKey[], data: string, middle: number): string {
  646. keyframes.forEach((key, i) => {
  647. var point = new Vector2(0, 0);
  648. point.x = key.frame;
  649. point.y = this._heightScale - (key.value * middle);
  650. this.setKeyframePointLinear(point, i);
  651. if (i !== 0) {
  652. data += ` L${point.x} ${point.y}`
  653. }
  654. });
  655. return data;
  656. }
  657. setKeyframePointLinear(point: Vector2, index: number) {
  658. let svgKeyframe = { keyframePoint: point, rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  659. this._svgKeyframes.push(svgKeyframe);
  660. }
  661. getPathData(animation: Animation) {
  662. // Check if Tangent mode is active and broken mode is active. (Only one tangent moves)
  663. let keyframes = animation.getKeys();
  664. if (keyframes === undefined) {
  665. return "";
  666. }
  667. // Checks if Flat Tangent is active (tangents are set to zero)
  668. if (this.state && this.state.isFlatTangentMode) {
  669. keyframes = animation.getKeys().map(kf => {
  670. if (kf.inTangent !== undefined) {
  671. kf.inTangent = 0;
  672. }
  673. if (kf.outTangent !== undefined) {
  674. kf.outTangent = 0;
  675. }
  676. return kf;
  677. });
  678. } else {
  679. keyframes = animation.getKeys();
  680. }
  681. const startKey = keyframes[0];
  682. let middle = this._heightScale / 2;
  683. // START OF LINE/CURVE
  684. let data: string | undefined = `M${startKey.frame}, ${this._heightScale - (startKey.value * middle)}`;
  685. if (this.state && this.state.lerpMode) {
  686. data = this.linearInterpolation(keyframes, data, middle);
  687. } else {
  688. if (this.getAnimationData(animation).usesTangents) {
  689. data = this.curvePathWithTangents(keyframes, data, middle, animation.dataType);
  690. } else {
  691. const { easingMode, easingType } = this.getAnimationProperties(animation);
  692. if (easingType !== undefined && easingMode !== undefined) {
  693. let easingFunction = animation.getEasingFunction();
  694. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction)
  695. } else {
  696. if (this.state !== undefined) {
  697. let emptyTangents = keyframes.map((kf, i) => {
  698. if (i === 0) {
  699. kf.outTangent = 0;
  700. } else if (i === keyframes.length - 1) {
  701. kf.inTangent = 0;
  702. } else {
  703. kf.inTangent = 0;
  704. kf.outTangent = 0;
  705. }
  706. return kf;
  707. });
  708. data = this.curvePathWithTangents(emptyTangents, data, middle, animation.dataType);
  709. } else {
  710. data = this.linearInterpolation(keyframes, data, middle);
  711. }
  712. }
  713. }
  714. }
  715. return data;
  716. }
  717. getAnimationData(animation: Animation) {
  718. // General Props
  719. let loopMode = animation.loopMode;
  720. let name = animation.name;
  721. let blendingSpeed = animation.blendingSpeed;
  722. let targetProperty = animation.targetProperty;
  723. let targetPropertyPath = animation.targetPropertyPath;
  724. let framesPerSecond = animation.framePerSecond;
  725. let highestFrame = animation.getHighestFrame();
  726. let serialized = animation.serialize();
  727. let usesTangents = animation.getKeys().find(kf => kf.hasOwnProperty('inTangent') || kf.hasOwnProperty('outTangent')) !== undefined ? true : false;
  728. return { loopMode, name, blendingSpeed, targetPropertyPath, targetProperty, framesPerSecond, highestFrame, serialized, usesTangents }
  729. }
  730. drawAllFrames(initialKey: IAnimationKey, endKey: IAnimationKey, easingFunction: EasingFunction) {
  731. let i = initialKey.frame;
  732. for (i; i < endKey.frame; i++) {
  733. (i * 100 / endKey.frame)
  734. let dy = easingFunction.easeInCore(i);
  735. let value = this._heightScale - (dy * (this._heightScale / 2));
  736. this._frames.push(new Vector2(i, value));
  737. }
  738. }
  739. curvePathFlat(keyframes: IAnimationKey[], data: string, middle: number, dataType: number) {
  740. keyframes.forEach((key, i) => {
  741. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  742. var pointA = new Vector2(0, 0);
  743. if (i === 0) {
  744. pointA.set(key.frame, this._heightScale - (key.value * middle));
  745. this.setKeyframePoint([pointA], i, keyframes.length);
  746. } else {
  747. pointA.set(keyframes[i - 1].frame, this._heightScale - (keyframes[i - 1].value * middle));
  748. let defaultWeight = 10;
  749. let nextKeyframe = keyframes[i + 1];
  750. let prevKeyframe = keyframes[i - 1];
  751. if (nextKeyframe !== undefined) {
  752. let distance = keyframes[i + 1].frame - key.frame;
  753. defaultWeight = distance * .33;
  754. }
  755. if (prevKeyframe !== undefined) {
  756. let distance = key.frame - keyframes[i - 1].frame;
  757. defaultWeight = distance * .33;
  758. }
  759. let tangentA = new Vector2(pointA.x + defaultWeight, pointA.y);
  760. let pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  761. let tangentB = new Vector2(pointB.x - defaultWeight, pointB.y);
  762. this.setKeyframePoint([pointA, tangentA, tangentB, pointB], i, keyframes.length);
  763. data += ` C${tangentA.x} ${tangentA.y} ${tangentB.x} ${tangentB.y} ${pointB.x} ${pointB.y} `
  764. }
  765. }
  766. });
  767. return data;
  768. }
  769. curvePathWithTangents(keyframes: IAnimationKey[], data: string, middle: number, type: number) {
  770. keyframes.forEach((key, i) => {
  771. let svgKeyframe;
  772. let outTangent;
  773. let inTangent;
  774. let defaultWeight = 5;
  775. var inT = key.inTangent === undefined ? null : key.inTangent;
  776. var outT = key.outTangent === undefined ? null : key.outTangent;
  777. let y = this._heightScale - (key.value * middle);
  778. let nextKeyframe = keyframes[i + 1];
  779. let prevKeyframe = keyframes[i - 1];
  780. if (nextKeyframe !== undefined) {
  781. let distance = keyframes[i + 1].frame - key.frame;
  782. defaultWeight = distance * .33;
  783. }
  784. if (prevKeyframe !== undefined) {
  785. let distance = key.frame - keyframes[i - 1].frame;
  786. defaultWeight = distance * .33;
  787. }
  788. if (inT !== null) {
  789. let valueIn = (y * inT) + y;
  790. inTangent = new Vector2(key.frame - defaultWeight, valueIn)
  791. } else {
  792. inTangent = null;
  793. }
  794. if (outT !== null) {
  795. let valueOut = (y * outT) + y;
  796. outTangent = new Vector2(key.frame + defaultWeight, valueOut);
  797. } else {
  798. outTangent = null;
  799. }
  800. if (i === 0) {
  801. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: null, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  802. if (outTangent !== null) {
  803. data += ` C${outTangent.x} ${outTangent.y} `;
  804. }
  805. } else {
  806. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: inTangent, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  807. if (outTangent !== null && inTangent !== null) {
  808. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y} `
  809. } else if (inTangent !== null) {
  810. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `
  811. }
  812. }
  813. if (this.state) {
  814. let prev = this.state.svgKeyframes?.find(kf => kf.id === i.toString());
  815. if (prev) {
  816. svgKeyframe.isLeftActive = prev?.isLeftActive;
  817. svgKeyframe.isRightActive = prev?.isRightActive;
  818. svgKeyframe.selected = prev?.selected
  819. }
  820. }
  821. this._svgKeyframes.push(svgKeyframe);
  822. }, this);
  823. return data;
  824. }
  825. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  826. // This will get 1/4 and 3/4 of points in eased curve
  827. const u = .25;
  828. const v = .75;
  829. keyframes.forEach((key, i) => {
  830. // Gets previous initial point of curve segment
  831. var pointA = new Vector2(0, 0);
  832. if (i === 0) {
  833. pointA.x = key.frame;
  834. pointA.y = this._heightScale - (key.value * middle);
  835. this.setKeyframePoint([pointA], i, keyframes.length);
  836. } else {
  837. pointA.x = keyframes[i - 1].frame;
  838. pointA.y = this._heightScale - (keyframes[i - 1].value * middle)
  839. // Gets the end point of this curve segment
  840. var pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  841. // Get easing value of percentage to get the bezier control points below
  842. let du = easingFunction.easeInCore(u); // What to do here, when user edits the curve? Option 1: Modify the curve with the new control points as BezierEaseCurve(x,y,z,w)
  843. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  844. // Direction of curve up/down
  845. let yInt25 = 0;
  846. if (pointB.y > pointA.y) { // if pointB.y > pointA.y = goes down
  847. yInt25 = ((pointB.y - pointA.y) * du) + pointA.y
  848. } else if (pointB.y < pointA.y) { // if pointB.y < pointA.y = goes up
  849. yInt25 = pointA.y - ((pointA.y - pointB.y) * du);
  850. }
  851. let yInt75 = 0;
  852. if (pointB.y > pointA.y) {
  853. yInt75 = ((pointB.y - pointA.y) * dv) + pointA.y
  854. } else if (pointB.y < pointA.y) {
  855. yInt75 = pointA.y - ((pointA.y - pointB.y) * dv)
  856. }
  857. // Intermediate points in curve
  858. let intermediatePoint25 = new Vector2(((pointB.x - pointA.x) * u) + pointA.x, yInt25);
  859. let intermediatePoint75 = new Vector2(((pointB.x - pointA.x) * v) + pointA.x, yInt75);
  860. // Gets the four control points of bezier curve
  861. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  862. if (controlPoints === undefined) {
  863. console.log("error getting bezier control points");
  864. } else {
  865. this.setKeyframePoint(controlPoints, i, keyframes.length);
  866. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`
  867. }
  868. }
  869. });
  870. return data;
  871. }
  872. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  873. let svgKeyframe;
  874. if (index === 0) {
  875. svgKeyframe = { keyframePoint: controlPoints[0], rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  876. } else {
  877. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  878. svgKeyframe = { keyframePoint: controlPoints[3], rightControlPoint: null, leftControlPoint: controlPoints[2], id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  879. }
  880. this._svgKeyframes.push(svgKeyframe);
  881. }
  882. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v: number, p3: Vector2): Vector2[] | undefined {
  883. let a = 0.0;
  884. let b = 0.0;
  885. let c = 0.0;
  886. let d = 0.0;
  887. let det = 0.0;
  888. let q1: Vector2 = new Vector2();
  889. let q2: Vector2 = new Vector2();
  890. let controlA: Vector2 = p0;
  891. let controlB: Vector2 = new Vector2();
  892. let controlC: Vector2 = new Vector2();
  893. let controlD: Vector2 = p3;
  894. if ((u <= 0.0) || (u >= 1.0) || (v <= 0.0) || (v >= 1.0) || (u >= v)) {
  895. return undefined;
  896. }
  897. a = 3 * (1 - u) * (1 - u) * u; b = 3 * (1 - u) * u * u;
  898. c = 3 * (1 - v) * (1 - v) * v; d = 3 * (1 - v) * v * v;
  899. det = a * d - b * c;
  900. if (det == 0.0) return undefined;
  901. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  902. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  903. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  904. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  905. controlB.x = (d * q1.x - b * q2.x) / det;
  906. controlB.y = (d * q1.y - b * q2.y) / det;
  907. controlC.x = ((-c) * q1.x + a * q2.x) / det;
  908. controlC.y = ((-c) * q1.y + a * q2.y) / det;
  909. return [controlA, controlB, controlC, controlD];
  910. }
  911. /**
  912. * Core functions
  913. * This section handles main Curve Editor Functions.
  914. */
  915. selectAnimation(animation: Animation) {
  916. this.playStopAnimation();
  917. this._svgKeyframes = [];
  918. const pathData = this.getPathData(animation);
  919. let lastFrame = animation.getHighestFrame();
  920. if (pathData === "") {
  921. console.log("no keyframes in this animation");
  922. }
  923. this.setState({ selected: animation, currentPathData: pathData, svgKeyframes: this._svgKeyframes, lastFrame: lastFrame });
  924. }
  925. isAnimationPlaying() {
  926. let target = this.props.entity;
  927. if (this.props.entity instanceof TargetedAnimation) {
  928. target = this.props.entity.target;
  929. }
  930. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  931. }
  932. playPause(direction: number) {
  933. if (this.state.selected) {
  934. let target = this.props.entity;
  935. if (this.props.entity instanceof TargetedAnimation) {
  936. target = this.props.entity.target;
  937. }
  938. if (this.state.isPlaying) {
  939. this.props.scene.stopAnimation(target);
  940. this.setState({ isPlaying: false })
  941. this._isPlaying = false;
  942. this.forceUpdate();
  943. } else {
  944. let keys = this.state.selected.getKeys();
  945. let firstFrame = keys[0].frame;
  946. let LastFrame = keys[keys.length - 1].frame;
  947. if (direction === 1){
  948. this.props.scene.beginAnimation(target, firstFrame, LastFrame, true);
  949. }
  950. if (direction === -1){
  951. this.props.scene.beginAnimation(target, LastFrame, firstFrame, true);
  952. }
  953. this._isPlaying = true;
  954. this.setState({ isPlaying: true });
  955. this.forceUpdate();
  956. }
  957. }
  958. }
  959. playStopAnimation() {
  960. let target = this.props.entity;
  961. if (this.props.entity instanceof TargetedAnimation) {
  962. target = this.props.entity.target;
  963. }
  964. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  965. if (this._isPlaying) {
  966. this.props.playOrPause && this.props.playOrPause();
  967. return true;
  968. } else {
  969. this._isPlaying = false;
  970. return false;
  971. }
  972. }
  973. analizeAnimation(animation: Animation | null) {
  974. if (animation !== null) {
  975. const { easingMode, easingType } = this.getAnimationProperties(animation);
  976. let hasDefinedTangents = this.getAnimationData(animation).usesTangents;
  977. if (easingType === undefined && easingMode === undefined && !hasDefinedTangents) {
  978. return true;
  979. } else {
  980. return false;
  981. }
  982. } else {
  983. return false;
  984. }
  985. }
  986. /**
  987. * Timeline
  988. * This section controls the timeline.
  989. */
  990. changeCurrentFrame(frame: number) {
  991. let currentValue;
  992. let selectedCurve = this._selectedCurve.current;
  993. if (selectedCurve) {
  994. var curveLength = selectedCurve.getTotalLength();
  995. let frameValue = (frame * curveLength) / 100;
  996. let currentP = selectedCurve.getPointAtLength(frameValue);
  997. let middle = this._heightScale / 2;
  998. let offset = (((currentP?.y * this._heightScale) - (this._heightScale ** 2) / 2) / middle) / this._heightScale;
  999. let unit = Math.sign(offset);
  1000. currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  1001. this.setState({ currentFrame: frame, currentValue: currentValue, currentPoint: currentP });
  1002. }
  1003. }
  1004. updateFrameInKeyFrame(frame: number, index: number) {
  1005. if (this.state && this.state.selected) {
  1006. let animation = this.state.selected;
  1007. let keys = [...animation.getKeys()];
  1008. keys[index].frame = frame;
  1009. animation.setKeys(keys);
  1010. this.selectAnimation(animation);
  1011. }
  1012. }
  1013. render() {
  1014. return (
  1015. <div id="animation-curve-editor">
  1016. <Notification message={this.state.notification} open={this.state.notification !== "" ? true : false} close={() => this.clearNotification()} />
  1017. <div className="header">
  1018. <div className="title">{this.props.title}</div>
  1019. <div className="close" onClick={(event: React.MouseEvent<HTMLDivElement, MouseEvent>) => this.props.close(event)}>
  1020. <FontAwesomeIcon icon={faTimes} />
  1021. </div>
  1022. </div>
  1023. <GraphActionsBar currentValue={this.state.currentValue}
  1024. currentFrame={this.state.currentFrame}
  1025. handleFrameChange={(e) => this.handleFrameChange(e)}
  1026. handleValueChange={(e) => this.handleValueChange(e)}
  1027. addKeyframe={() => this.addKeyframeClick()}
  1028. removeKeyframe={() => this.removeKeyframeClick()}
  1029. brokenMode={this.state.isBrokenMode}
  1030. brokeTangents={() => this.setBrokenMode()}
  1031. lerpMode={this.state.lerpMode}
  1032. setLerpMode={() => this.setLerpMode()}
  1033. flatTangent={() => this.setFlatTangent()} />
  1034. <div className="content">
  1035. <div className="row">
  1036. <div className="animation-list">
  1037. <div style={{ display: this._isTargetedAnimation ? "none" : "block" }}>
  1038. <div className="label-input">
  1039. <label>Animation Name</label>
  1040. <input type="text" value={this.state.animationName} onChange={(e) => this.handleNameChange(e)}></input>
  1041. </div>
  1042. <div className="label-input">
  1043. <label>Type</label>
  1044. <select onChange={(e) => this.handleTypeChange(e)} value={this.state.animationType}>
  1045. <option value="Float">Float</option>
  1046. <option value="Vector3">Vector3</option>
  1047. <option value="Vector2">Vector2</option>
  1048. <option value="Quaternion">Quaternion</option>
  1049. <option value="Color3">Color3</option>
  1050. <option value="Color4">Color4</option>
  1051. <option value="Size">Size</option>
  1052. </select>
  1053. </div>
  1054. <div className="label-input">
  1055. <label>Target Property</label>
  1056. <input type="text" value={this.state.animationTargetProperty} onChange={(e) => this.handlePropertyChange(e)}></input>
  1057. </div>
  1058. <ButtonLineComponent label={"Add Animation"} onClick={() => this.addAnimation()} />
  1059. </div>
  1060. <div className="object-tree">
  1061. <h2>{this._entityName}</h2>
  1062. <ul>
  1063. {
  1064. this.props.entity instanceof TargetedAnimation ? this.setListItem(this.props.entity.animation, 0) :
  1065. this.props.entity.animations && this.props.entity.animations.map((animation, i) => {
  1066. return this.setListItem(animation, i);
  1067. })}
  1068. </ul>
  1069. </div>
  1070. </div>
  1071. <div ref={this._graphCanvas} className="graph-chart" onWheel={(e) => this.zoom(e)} >
  1072. <Playhead frame={this.state.currentFrame} offset={this.state.playheadOffset} />
  1073. {this.state.svgKeyframes && <SvgDraggableArea ref={this._svgCanvas}
  1074. selectKeyframe={(id: string) => this.selectKeyframe(id)}
  1075. viewBoxScale={this.state.frameAxisLength.length} scale={this.state.scale}
  1076. keyframeSvgPoints={this.state.svgKeyframes}
  1077. selectedControlPoint={(type: string, id: string) => this.selectedControlPoint(type, id)}
  1078. updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) => this.renderPoints(updatedSvgKeyFrame, index)}>
  1079. {/* Frame Labels */}
  1080. { /* Vertical Grid */}
  1081. {this.state.frameAxisLength.map((f, i) =>
  1082. <svg key={i}>
  1083. <text x={f.value} y="-2" dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.value}</text>
  1084. <line x1={f.value} y1="0" x2={f.value} y2="100%"></line>
  1085. </svg>
  1086. )}
  1087. {this.state.valueAxisLength.map((f, i) => {
  1088. return <svg key={i}>
  1089. <text x="-3" y={f.value} dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.label.toFixed(1)}</text>
  1090. <line x1="0" y1={f.value} x2="100%" y2={f.value}></line>
  1091. </svg>
  1092. })}
  1093. { /* Single Curve -Modify this for multiple selection and view */}
  1094. <path ref={this._selectedCurve} pathLength={this.state.lastFrame} id="curve" d={this.state.currentPathData} style={{ stroke: 'red', fill: 'none', strokeWidth: '0.5' }}></path>
  1095. {this._frames && this._frames.map(frame =>
  1096. <svg x={frame.x} y={frame.y} style={{ overflow: 'visible' }}>
  1097. <circle cx="0" cy="0" r="2" stroke="black" strokeWidth="1" fill="white" />
  1098. </svg>
  1099. )}
  1100. </SvgDraggableArea>
  1101. }
  1102. </div>
  1103. </div>
  1104. <div className="row">
  1105. <Timeline currentFrame={this.state.currentFrame} playPause={(direction: number) => this.playPause(direction)} isPlaying={this.state.isPlaying} dragKeyframe={(frame: number, index: number) => this.updateFrameInKeyFrame(frame, index)} onCurrentFrameChange={(frame: number) => this.changeCurrentFrame(frame)} keyframes={this.state.selected && this.state.selected.getKeys()} selected={this.state.selected && this.state.selected.getKeys()[0]}></Timeline>
  1106. </div>
  1107. </div>
  1108. </div>
  1109. );
  1110. }
  1111. }