animationCurveEditorComponent.tsx 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. import * as React from "react";
  2. import { Animation } from "babylonjs/Animations/animation";
  3. import { Vector2, Vector3, Quaternion } from "babylonjs/Maths/math.vector";
  4. import { Color3, Color4 } from "babylonjs/Maths/math.color";
  5. import { Size } from "babylonjs/Maths/math.size";
  6. import { EasingFunction } from "babylonjs/Animations/easing";
  7. import { IAnimationKey } from "babylonjs/Animations/animationKey";
  8. import { IKeyframeSvgPoint } from "./keyframeSvgPoint";
  9. import { SvgDraggableArea } from "./svgDraggableArea";
  10. import { Timeline } from "./timeline";
  11. import { Notification } from "./notification";
  12. import { GraphActionsBar } from "./graphActionsBar";
  13. import { Scene } from "babylonjs/scene";
  14. import { IAnimatable } from "babylonjs/Animations/animatable.interface";
  15. import { Animatable } from "babylonjs/Animations/animatable";
  16. import { TargetedAnimation } from "babylonjs/Animations/animationGroup";
  17. import { EditorControls } from "./editorControls";
  18. import { SelectedCoordinate } from "./animationListTree";
  19. import { LockObject } from "../lockObject";
  20. import { GlobalState } from "../../../../globalState";
  21. import { Nullable } from "babylonjs/types";
  22. import { Observer } from "babylonjs/Misc/observable";
  23. import { ScaleLabel } from "./scale-label";
  24. require("./curveEditor.scss");
  25. interface IAnimationCurveEditorComponentProps {
  26. close: (event: any) => void;
  27. playOrPause?: () => void;
  28. scene: Scene;
  29. entity: IAnimatable | TargetedAnimation;
  30. lockObject: LockObject;
  31. globalState: GlobalState;
  32. }
  33. interface ICanvasAxis {
  34. value: number;
  35. label: number;
  36. }
  37. export enum CurveScale {
  38. float,
  39. radians,
  40. degrees,
  41. integers,
  42. default,
  43. }
  44. export interface IActionableKeyFrame {
  45. frame?: number | string;
  46. value?: any;
  47. }
  48. interface ICurveData {
  49. pathData: string;
  50. pathLength: number;
  51. domCurve: React.RefObject<SVGPathElement>;
  52. color: string;
  53. id: string;
  54. }
  55. export class AnimationCurveEditorComponent extends React.Component<
  56. IAnimationCurveEditorComponentProps,
  57. {
  58. isOpen: boolean;
  59. selected: Animation | null;
  60. svgKeyframes: IKeyframeSvgPoint[] | undefined;
  61. currentFrame: number;
  62. currentValue: number;
  63. frameAxisLength: ICanvasAxis[];
  64. valueAxisLength: ICanvasAxis[];
  65. isFlatTangentMode: boolean;
  66. isTangentMode: boolean;
  67. isBrokenMode: boolean;
  68. lerpMode: boolean;
  69. scale: number;
  70. playheadOffset: number;
  71. notification: string;
  72. currentPoint: SVGPoint | undefined;
  73. playheadPos: number;
  74. isPlaying: boolean;
  75. selectedPathData: ICurveData[] | undefined;
  76. selectedCoordinate: number;
  77. animationLimit: number;
  78. fps: number;
  79. isLooping: boolean;
  80. panningY: number;
  81. panningX: number;
  82. repositionCanvas: boolean;
  83. actionableKeyframe: IActionableKeyFrame;
  84. valueScale: CurveScale;
  85. }
  86. > {
  87. private _snippetUrl = "https://snippet.babylonjs.com";
  88. // Height scale *Review this functionaliy
  89. private _heightScale: number = 100;
  90. private _scaleFactor: number = 2;
  91. private _currentScale: number = 10;
  92. // Canvas Length *Review this functionality
  93. readonly _entityName: string;
  94. readonly _canvasLength: number = 20;
  95. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  96. private _isPlaying: boolean = false;
  97. private _graphCanvas: React.RefObject<HTMLDivElement>;
  98. //private _selectedCurve: React.RefObject<SVGPathElement>;
  99. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  100. private _isTargetedAnimation: boolean;
  101. private _pixelFrameUnit: number;
  102. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  103. private _mainAnimatable: Nullable<Animatable>;
  104. constructor(props: IAnimationCurveEditorComponentProps) {
  105. super(props);
  106. this._entityName = (this.props.entity as any).id;
  107. this._graphCanvas = React.createRef();
  108. this._svgCanvas = React.createRef();
  109. this._pixelFrameUnit = 10;
  110. let initialSelection;
  111. let initialPathData;
  112. let initialLerpMode;
  113. if (this.props.entity instanceof TargetedAnimation) {
  114. this._isTargetedAnimation = true;
  115. initialSelection = this.props.entity.animation;
  116. initialLerpMode = initialSelection !== undefined ? this.analizeAnimationForLerp(initialSelection) : false;
  117. initialPathData = initialSelection !== undefined ? this.getPathData(initialSelection) : undefined;
  118. } else {
  119. this._isTargetedAnimation = false;
  120. let hasAnimations = this.props.entity.animations !== undefined || this.props.entity.animations !== null ? this.props.entity.animations : false;
  121. initialSelection = hasAnimations !== false ? hasAnimations && hasAnimations[0] : null;
  122. initialLerpMode = initialSelection !== undefined ? this.analizeAnimationForLerp(this.props.entity.animations && initialSelection) : false;
  123. initialPathData = initialSelection && this.getPathData(initialSelection);
  124. initialPathData = initialPathData === null || initialPathData === undefined ? undefined : initialPathData;
  125. }
  126. this._canvasLength = 240;
  127. this.stopAnimation();
  128. // will update this until we have a top scroll/zoom feature
  129. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  130. this.state = {
  131. selected: initialSelection,
  132. isOpen: true,
  133. svgKeyframes: this._svgKeyframes,
  134. currentFrame: 0,
  135. currentValue: 1,
  136. isFlatTangentMode: false,
  137. isTangentMode: false,
  138. isBrokenMode: false,
  139. lerpMode: initialLerpMode,
  140. playheadOffset: this._graphCanvas.current ? this._graphCanvas.current.children[0].clientWidth / (this._canvasLength * 10) : 0,
  141. frameAxisLength: this.setFrameAxis(this._canvasLength),
  142. valueAxisLength: new Array(10).fill(0).map((s, i) => {
  143. return { value: i * 10, label: valueInd[i] };
  144. }),
  145. notification: "",
  146. currentPoint: undefined,
  147. scale: 1,
  148. playheadPos: 0,
  149. isPlaying: false,
  150. selectedPathData: initialPathData,
  151. selectedCoordinate: 0,
  152. animationLimit: this._canvasLength / 2,
  153. fps: 60,
  154. isLooping: true,
  155. panningY: 0,
  156. panningX: 0,
  157. repositionCanvas: false,
  158. actionableKeyframe: { frame: undefined, value: undefined },
  159. valueScale: CurveScale.default,
  160. };
  161. }
  162. componentDidMount() {
  163. this.state.selected && this.selectAnimation(this.state.selected);
  164. }
  165. componentDidUpdate(prevProps: IAnimationCurveEditorComponentProps, prevState: any) {
  166. if (prevState.currentFrame !== this.state.currentFrame) {
  167. this.onCurrentFrameChangeChangeScene(this.state.currentFrame);
  168. }
  169. }
  170. onCurrentFrameChangeChangeScene(value: number) {
  171. if (!this._mainAnimatable) {
  172. return;
  173. }
  174. this._mainAnimatable.goToFrame(value);
  175. }
  176. /**
  177. * Notifications
  178. * To add notification we set the state and clear to make the notification bar hide.
  179. */
  180. clearNotification() {
  181. this.setState({ notification: "" });
  182. }
  183. /**
  184. * Zoom and Scroll
  185. * This section handles zoom and scroll
  186. * of the graph area.
  187. */
  188. zoom(e: React.WheelEvent<HTMLDivElement>) {
  189. e.nativeEvent.stopImmediatePropagation();
  190. let scaleX = 1;
  191. if (Math.sign(e.deltaY) === -1) {
  192. scaleX = this.state.scale; //- 0.01; //+ 0.01;
  193. }
  194. this.setState({ scale: scaleX });
  195. }
  196. setFrameAxis(currentLength: number) {
  197. let halfNegative = new Array(currentLength / 2).fill(0).map((s, i) => {
  198. return { value: -i * 10, label: -i };
  199. });
  200. let halfPositive = new Array(currentLength / 2).fill(0).map((s, i) => {
  201. return { value: i * 10, label: i };
  202. });
  203. return [...halfNegative, ...halfPositive];
  204. }
  205. setValueLines(type: CurveScale) {
  206. switch (type) {
  207. case CurveScale.default:
  208. this._heightScale = 100;
  209. this._scaleFactor = 2;
  210. break;
  211. case CurveScale.float:
  212. this._scaleFactor = 2.5;
  213. this._heightScale = 120;
  214. break;
  215. case CurveScale.degrees:
  216. this._scaleFactor = 50;
  217. this._heightScale = 200;
  218. break;
  219. case CurveScale.integers:
  220. this._scaleFactor = 320;
  221. break;
  222. case CurveScale.radians:
  223. this._scaleFactor = 0.8;
  224. break;
  225. }
  226. const lineV = this._heightScale / 10;
  227. const initialValues = new Array(this._currentScale).fill(0).map((_, i) => {
  228. return {
  229. value: i * lineV,
  230. label: (this._scaleFactor * ((this._currentScale - i) / this._currentScale)).toFixed(2),
  231. };
  232. });
  233. initialValues.shift();
  234. const valueHeight = Math.abs(Math.round(this.state.panningY / this._currentScale));
  235. const sign = Math.sign(this.state.panningY);
  236. const pannedValues = new Array(valueHeight).fill(0).map((s, i) => {
  237. return sign === -1
  238. ? {
  239. value: -i * lineV,
  240. label: (i + this._currentScale) / (this._currentScale / this._scaleFactor),
  241. }
  242. : {
  243. value: (i + lineV) * this._currentScale,
  244. label: (i * -1) / (this._currentScale / this._scaleFactor),
  245. };
  246. });
  247. return [...initialValues, ...pannedValues];
  248. }
  249. getValueLabel(i: number) {
  250. // Need to update this when Y axis grows
  251. let label = 0;
  252. if (i === 0) {
  253. label = 2;
  254. }
  255. if (i === 50) {
  256. label = 1;
  257. } else {
  258. label = (100 - i * 2) * 0.01 + 1;
  259. }
  260. return label;
  261. }
  262. resetPlayheadOffset() {
  263. if (this._graphCanvas && this._graphCanvas.current) {
  264. this.setState({
  265. playheadOffset: this._graphCanvas.current.children[0].clientWidth / (this._canvasLength * 10 * this.state.scale),
  266. });
  267. }
  268. }
  269. encodeCurveId(animationName: string, coordinate: number) {
  270. return animationName + "_" + coordinate;
  271. }
  272. decodeCurveId(id: string) {
  273. const order = parseInt(id.split("_")[3]);
  274. const coordinate = parseInt(id.split("_")[2]);
  275. return { order, coordinate };
  276. }
  277. getKeyframeValueFromAnimation(id: string) {
  278. const animation = this.state.selected as Animation;
  279. const { order, coordinate } = this.decodeCurveId(id);
  280. const keys = [...animation.getKeys()];
  281. const key = keys.find((_, i) => i === order);
  282. if (key) {
  283. const valueAsArray = this.getValueAsArray(animation.dataType, key.value);
  284. return { frame: key?.frame, value: valueAsArray[coordinate] };
  285. } else {
  286. return undefined;
  287. }
  288. }
  289. /**
  290. * Keyframe Manipulation
  291. * This section handles events from SvgDraggableArea.
  292. */
  293. selectKeyframe(id: string, multiselect: boolean) {
  294. const frameValue = this.getKeyframeValueFromAnimation(id);
  295. const selectedKeyFrame = this.state.svgKeyframes?.find((kf) => kf.id === id)?.selected;
  296. if (!multiselect) {
  297. this.deselectKeyframes();
  298. }
  299. const updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  300. if (kf.id === id) {
  301. kf.selected = !selectedKeyFrame;
  302. }
  303. return kf;
  304. });
  305. this.setState({
  306. svgKeyframes: updatedKeyframes,
  307. actionableKeyframe: frameValue ?? this.state.actionableKeyframe,
  308. });
  309. }
  310. resetActionableKeyframe() {
  311. this.setState({
  312. actionableKeyframe: { frame: undefined, value: undefined },
  313. });
  314. }
  315. selectedControlPoint(type: string, id: string) {
  316. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  317. if (kf.id === id) {
  318. this.setState({ isFlatTangentMode: false });
  319. if (type === "left") {
  320. kf.isLeftActive = !kf.isLeftActive;
  321. kf.isRightActive = false;
  322. }
  323. if (type === "right") {
  324. kf.isRightActive = !kf.isRightActive;
  325. kf.isLeftActive = false;
  326. }
  327. }
  328. return kf;
  329. });
  330. this.setState({ svgKeyframes: updatedKeyframes });
  331. }
  332. deselectKeyframes() {
  333. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  334. kf.isLeftActive = false;
  335. kf.isRightActive = false;
  336. kf.selected = false;
  337. return kf;
  338. });
  339. this.setState({
  340. svgKeyframes: updatedKeyframes,
  341. actionableKeyframe: { frame: undefined, value: undefined },
  342. });
  343. }
  344. updateValuePerCoordinate(dataType: number, value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion, newValue: number, coordinate?: number) {
  345. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  346. value = newValue;
  347. }
  348. if (dataType === Animation.ANIMATIONTYPE_VECTOR2) {
  349. switch (coordinate) {
  350. case SelectedCoordinate.x:
  351. (value as Vector2).x = newValue;
  352. break;
  353. case SelectedCoordinate.y:
  354. (value as Vector2).y = newValue;
  355. break;
  356. }
  357. }
  358. if (dataType === Animation.ANIMATIONTYPE_VECTOR3) {
  359. switch (coordinate) {
  360. case SelectedCoordinate.x:
  361. (value as Vector3).x = newValue;
  362. break;
  363. case SelectedCoordinate.y:
  364. (value as Vector3).y = newValue;
  365. break;
  366. case SelectedCoordinate.z:
  367. (value as Vector3).z = newValue;
  368. break;
  369. }
  370. }
  371. if (dataType === Animation.ANIMATIONTYPE_QUATERNION) {
  372. switch (coordinate) {
  373. case SelectedCoordinate.x:
  374. (value as Quaternion).x = newValue;
  375. break;
  376. case SelectedCoordinate.y:
  377. (value as Quaternion).y = newValue;
  378. break;
  379. case SelectedCoordinate.z:
  380. (value as Quaternion).z = newValue;
  381. break;
  382. case SelectedCoordinate.w:
  383. (value as Quaternion).w = newValue;
  384. break;
  385. }
  386. }
  387. if (dataType === Animation.ANIMATIONTYPE_COLOR3) {
  388. switch (coordinate) {
  389. case SelectedCoordinate.r:
  390. (value as Color3).r = newValue;
  391. break;
  392. case SelectedCoordinate.g:
  393. (value as Color3).g = newValue;
  394. break;
  395. case SelectedCoordinate.b:
  396. (value as Color3).b = newValue;
  397. break;
  398. }
  399. }
  400. if (dataType === Animation.ANIMATIONTYPE_COLOR4) {
  401. switch (coordinate) {
  402. case SelectedCoordinate.r:
  403. (value as Color4).r = newValue;
  404. break;
  405. case SelectedCoordinate.g:
  406. (value as Color4).g = newValue;
  407. break;
  408. case SelectedCoordinate.b:
  409. (value as Color4).b = newValue;
  410. break;
  411. case SelectedCoordinate.a:
  412. (value as Color4).a = newValue;
  413. break;
  414. }
  415. }
  416. if (dataType === Animation.ANIMATIONTYPE_SIZE) {
  417. switch (coordinate) {
  418. case SelectedCoordinate.width:
  419. (value as Size).width = newValue;
  420. break;
  421. case SelectedCoordinate.g:
  422. (value as Size).height = newValue;
  423. break;
  424. }
  425. }
  426. return value;
  427. }
  428. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, id: string) {
  429. let animation = this.state.selected as Animation;
  430. const { order: index, coordinate } = this.decodeCurveId(id);
  431. let keys = [...animation.getKeys()];
  432. let newFrame = 0;
  433. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  434. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  435. newFrame = 1;
  436. } else {
  437. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x / this._pixelFrameUnit);
  438. }
  439. }
  440. if (newFrame > keys[index].frame) {
  441. if (index === keys.length - 1) {
  442. keys[index].frame = newFrame;
  443. } else {
  444. const nextKf = keys[index + 1];
  445. if (nextKf) {
  446. if (nextKf.frame <= newFrame) {
  447. keys[index].frame = keys[index].frame;
  448. } else {
  449. keys[index].frame = newFrame;
  450. }
  451. }
  452. }
  453. }
  454. if (newFrame < keys[index].frame) {
  455. if (index === 0) {
  456. keys[index].frame = newFrame;
  457. } else {
  458. const prevKf = keys[index - 1];
  459. if (prevKf) {
  460. if (prevKf.frame >= newFrame) {
  461. keys[index].frame = keys[index].frame;
  462. } else {
  463. keys[index].frame = newFrame;
  464. }
  465. }
  466. }
  467. }
  468. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * this._scaleFactor;
  469. const updatedValueInCoordinate = this.updateValuePerCoordinate(animation.dataType, keys[index].value, updatedValue, coordinate);
  470. keys[index].value = updatedValueInCoordinate;
  471. this.updateLeftControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  472. this.updateRightControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  473. animation.setKeys(keys);
  474. this.setState({
  475. actionableKeyframe: { frame: newFrame, value: updatedValueInCoordinate },
  476. });
  477. this.selectAnimation(animation, coordinate);
  478. }
  479. updateLeftControlPoint(updatedSvgKeyFrame: IKeyframeSvgPoint, key: IAnimationKey, dataType: number, coordinate: number) {
  480. if (updatedSvgKeyFrame.isLeftActive) {
  481. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  482. // Rotate
  483. let newValue = ((this._heightScale - updatedSvgKeyFrame.leftControlPoint.y) / this._heightScale) * 2;
  484. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  485. let updatedValue = keyframeValue - newValue;
  486. key.inTangent = this.updateValuePerCoordinate(dataType, key.inTangent, updatedValue, coordinate);
  487. if (!this.state.isBrokenMode) {
  488. // Right control point if exists
  489. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  490. // Sets opposite value
  491. key.outTangent = key.inTangent * -1;
  492. }
  493. }
  494. }
  495. }
  496. }
  497. updateRightControlPoint(updatedSvgKeyFrame: IKeyframeSvgPoint, key: IAnimationKey, dataType: number, coordinate: number) {
  498. if (updatedSvgKeyFrame.isRightActive) {
  499. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  500. // Rotate
  501. let newValue = ((this._heightScale - updatedSvgKeyFrame.rightControlPoint.y) / this._heightScale) * 2;
  502. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  503. let updatedValue = keyframeValue - newValue;
  504. key.outTangent = this.updateValuePerCoordinate(dataType, key.outTangent, updatedValue, coordinate);
  505. if (!this.state.isBrokenMode) {
  506. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  507. // Sets opposite value
  508. key.inTangent = key.outTangent * -1;
  509. }
  510. }
  511. }
  512. }
  513. }
  514. handleFrameChange(event: React.ChangeEvent<HTMLInputElement>) {
  515. event.preventDefault();
  516. let frame;
  517. if (event.target.value === "") {
  518. frame = "";
  519. } else {
  520. frame = parseInt(event.target.value);
  521. }
  522. this.setState({
  523. actionableKeyframe: {
  524. frame: frame,
  525. value: this.state.actionableKeyframe.value,
  526. },
  527. });
  528. }
  529. handleValueChange(event: React.ChangeEvent<HTMLInputElement>) {
  530. event.preventDefault();
  531. let value;
  532. if (event.target.value !== undefined) {
  533. if (event.target.value !== "") {
  534. value = parseFloat(event.target.value);
  535. } else {
  536. value = "";
  537. }
  538. this.setState({
  539. actionableKeyframe: {
  540. frame: this.state.actionableKeyframe.frame,
  541. value: value,
  542. },
  543. });
  544. }
  545. }
  546. setKeyframeValue() {
  547. if (this.state.actionableKeyframe.frame !== "" && this.state.actionableKeyframe.frame !== undefined && this.state.actionableKeyframe.value !== "" && this.state.actionableKeyframe.value !== undefined) {
  548. if (this.state.selected !== null) {
  549. let currentSelected = this.state.svgKeyframes?.find((kf) => kf.selected);
  550. if (currentSelected) {
  551. let { order, coordinate } = this.decodeCurveId(currentSelected.id);
  552. let animation = this.state.selected;
  553. let keys = animation.getKeys();
  554. let isKeyframe = keys.find((_, i) => i === order);
  555. if (isKeyframe) {
  556. let updatedKeys = keys.map((k, i) => {
  557. if (i === order) {
  558. k.frame = this.state.actionableKeyframe.frame as number;
  559. const currentValue = this.getValueAsArray(animation.dataType, k.value);
  560. currentValue[coordinate] = this.state.actionableKeyframe.value;
  561. k.value = currentValue.length === 1 ? currentValue[0] : currentValue;
  562. }
  563. return k;
  564. });
  565. this.state.selected.setKeys(updatedKeys);
  566. this.selectAnimation(animation);
  567. }
  568. }
  569. }
  570. }
  571. }
  572. setFlatTangent() {
  573. const keyframes = this.state.svgKeyframes?.filter((kf) => kf.selected).map((k) => this.decodeCurveId(k.id));
  574. if (this.state.selected !== null) {
  575. let currentAnimation = this.state.selected;
  576. const keys = currentAnimation.getKeys();
  577. keyframes?.forEach((k) => {
  578. const keyframe = keys[k.order];
  579. keyframe.inTangent = this.returnZero(currentAnimation.dataType);
  580. keyframe.outTangent = this.returnZero(currentAnimation.dataType);
  581. });
  582. currentAnimation.setKeys(keys);
  583. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  584. }
  585. }
  586. // Use this for Bezier curve mode
  587. setTangentMode() {
  588. if (this.state.selected !== null) {
  589. let animation = this.state.selected;
  590. this.setState({ isTangentMode: !this.state.isTangentMode }, () => this.selectAnimation(animation));
  591. }
  592. }
  593. setBrokenMode() {
  594. if (this.state.selected !== null) {
  595. let animation = this.state.selected;
  596. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () => this.selectAnimation(animation));
  597. }
  598. }
  599. setLerpMode() {
  600. if (this.state.selected !== null) {
  601. let animation = this.state.selected;
  602. this.setState({ lerpMode: !this.state.lerpMode }, () => this.selectAnimation(animation));
  603. }
  604. }
  605. addKeyframeClick() {
  606. if (this.state.selected !== null) {
  607. let currentAnimation = this.state.selected;
  608. let keys = currentAnimation.getKeys();
  609. let x = this.state.currentFrame;
  610. let y = this.state.actionableKeyframe.value ?? 1;
  611. // check if value exists...
  612. let arrayValue: any = [];
  613. let emptyValue = this.returnZero(currentAnimation.dataType);
  614. let existValue = keys.find((k) => k.frame === x);
  615. if (existValue !== undefined) {
  616. arrayValue = this.getValueAsArray(currentAnimation.dataType, existValue.value);
  617. } else {
  618. // Set empty if doesn't exist
  619. if (emptyValue) {
  620. arrayValue = this.getValueAsArray(currentAnimation.dataType, emptyValue);
  621. }
  622. }
  623. // calculate point between prevkeyframe and nextkeyframe.
  624. const previousKFs = keys.filter((kf) => kf.frame < x);
  625. const nextKFs = keys.filter((kf) => kf.frame > x);
  626. const prev = previousKFs.slice(-1)[0];
  627. const next = nextKFs[0];
  628. if (prev === undefined && next) {
  629. y = next.value;
  630. }
  631. if (prev && next === undefined) {
  632. y = prev.value;
  633. }
  634. if (prev && next) {
  635. const value1 = new Vector2(prev.frame, prev.value);
  636. const tangent1 = new Vector2(prev.outTangent, prev.outTangent);
  637. const value2 = new Vector2(next.frame, next.value);
  638. const tangent2 = new Vector2(next.inTangent, next.inTangent);
  639. const amount = (x - prev.frame) / (next.frame - prev.frame);
  640. const newV = Vector2.Hermite(value1, tangent1, value2, tangent2, amount);
  641. y = newV.y;
  642. }
  643. arrayValue[this.state.selectedCoordinate] = y;
  644. let actualValue = this.setValueAsType(currentAnimation.dataType, arrayValue);
  645. keys.push({
  646. frame: x,
  647. value: actualValue,
  648. inTangent: emptyValue,
  649. outTangent: emptyValue,
  650. });
  651. keys.sort((a, b) => a.frame - b.frame);
  652. currentAnimation.setKeys(keys);
  653. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  654. }
  655. }
  656. removeKeyframeClick() {
  657. if (this.state.selected !== null) {
  658. let currentAnimation = this.state.selected;
  659. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  660. let keys = currentAnimation.getKeys();
  661. let x = this.state.currentFrame;
  662. let filteredKeys = keys.filter((kf) => kf.frame !== x);
  663. currentAnimation.setKeys(filteredKeys);
  664. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  665. }
  666. }
  667. }
  668. removeKeyframes(points: IKeyframeSvgPoint[]) {
  669. if (this.state.selected !== null) {
  670. let currentAnimation = this.state.selected;
  671. const indexesToRemove = points.map((p) => {
  672. return {
  673. index: parseInt(p.id.split("_")[3]),
  674. coordinate: parseInt(p.id.split("_")[2]),
  675. };
  676. });
  677. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  678. let keys = currentAnimation.getKeys();
  679. let filteredKeys = keys.filter((_, i) => {
  680. return !indexesToRemove.find((x) => x.index === i);
  681. });
  682. currentAnimation.setKeys(filteredKeys);
  683. this.deselectKeyframes();
  684. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  685. }
  686. }
  687. }
  688. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  689. event.preventDefault();
  690. if (this.state.selected !== null) {
  691. var svg = event.target as SVGSVGElement;
  692. var pt = svg.createSVGPoint();
  693. pt.x = event.clientX;
  694. pt.y = event.clientY;
  695. var inverse = svg.getScreenCTM()?.inverse();
  696. var cursorpt = pt.matrixTransform(inverse);
  697. var currentAnimation = this.state.selected;
  698. var keys = currentAnimation.getKeys();
  699. var height = 100;
  700. var middle = height / 2;
  701. var keyValue;
  702. if (cursorpt.y < middle) {
  703. keyValue = 1 + (100 / cursorpt.y) * 0.1;
  704. }
  705. if (cursorpt.y > middle) {
  706. keyValue = 1 - (100 / cursorpt.y) * 0.1;
  707. }
  708. keys.push({ frame: cursorpt.x, value: keyValue });
  709. currentAnimation.setKeys(keys);
  710. this.selectAnimation(currentAnimation);
  711. }
  712. }
  713. /**
  714. * Curve Rendering Functions
  715. * This section handles how to render curves.
  716. */
  717. setKeyframePointLinear(point: Vector2, index: number) {
  718. // here set the ID to a unique id
  719. let svgKeyframe = {
  720. keyframePoint: point,
  721. rightControlPoint: null,
  722. leftControlPoint: null,
  723. id: index.toString(),
  724. selected: false,
  725. isLeftActive: false,
  726. isRightActive: false,
  727. };
  728. this._svgKeyframes.push(svgKeyframe);
  729. }
  730. flatTangents(keyframes: IAnimationKey[], dataType: number) {
  731. // Checks if Flat Tangent is active (tangents are set to zero)
  732. let flattened;
  733. if (this.state && this.state.isFlatTangentMode) {
  734. flattened = keyframes.map((kf) => {
  735. if (kf.inTangent !== undefined) {
  736. kf.inTangent = this.returnZero(dataType);
  737. }
  738. if (kf.outTangent !== undefined) {
  739. kf.outTangent = this.returnZero(dataType);
  740. }
  741. return kf;
  742. });
  743. } else {
  744. flattened = keyframes;
  745. }
  746. this.setState({ isFlatTangentMode: false });
  747. return flattened;
  748. }
  749. returnZero(dataType: number) {
  750. switch (dataType) {
  751. case Animation.ANIMATIONTYPE_FLOAT:
  752. return 0;
  753. case Animation.ANIMATIONTYPE_VECTOR3:
  754. return Vector3.Zero();
  755. case Animation.ANIMATIONTYPE_VECTOR2:
  756. return Vector2.Zero();
  757. case Animation.ANIMATIONTYPE_QUATERNION:
  758. return Quaternion.Zero();
  759. case Animation.ANIMATIONTYPE_COLOR3:
  760. return new Color3(0, 0, 0);
  761. case Animation.ANIMATIONTYPE_COLOR4:
  762. return new Color4(0, 0, 0, 0);
  763. case Animation.ANIMATIONTYPE_SIZE:
  764. return new Size(0, 0);
  765. default:
  766. return 0;
  767. }
  768. }
  769. getValueAsArray(valueType: number, value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion) {
  770. switch (valueType) {
  771. case Animation.ANIMATIONTYPE_FLOAT:
  772. return [value as number];
  773. case Animation.ANIMATIONTYPE_VECTOR3:
  774. return (value as Vector3).asArray();
  775. case Animation.ANIMATIONTYPE_VECTOR2:
  776. return (value as Vector2).asArray();
  777. case Animation.ANIMATIONTYPE_QUATERNION:
  778. return (value as Quaternion).asArray();
  779. case Animation.ANIMATIONTYPE_COLOR3:
  780. return (value as Color3).asArray();
  781. case Animation.ANIMATIONTYPE_COLOR4:
  782. return (value as Color4).asArray();
  783. case Animation.ANIMATIONTYPE_SIZE:
  784. return [(value as Size).width, (value as Size).height];
  785. default:
  786. return [];
  787. }
  788. }
  789. setValueAsType(valueType: number, arrayValue: number[]) {
  790. switch (valueType) {
  791. case Animation.ANIMATIONTYPE_FLOAT:
  792. return arrayValue[0];
  793. case Animation.ANIMATIONTYPE_VECTOR3:
  794. return new Vector3(arrayValue[0], arrayValue[1], arrayValue[2]);
  795. case Animation.ANIMATIONTYPE_VECTOR2:
  796. return new Vector2(arrayValue[0], arrayValue[1]);
  797. case Animation.ANIMATIONTYPE_QUATERNION:
  798. return new Quaternion(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  799. case Animation.ANIMATIONTYPE_COLOR3:
  800. return new Color3(arrayValue[0], arrayValue[1], arrayValue[2]);
  801. case Animation.ANIMATIONTYPE_COLOR4:
  802. return new Color4(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  803. case Animation.ANIMATIONTYPE_SIZE:
  804. return new Size(arrayValue[0], arrayValue[1]);
  805. default:
  806. return arrayValue[0];
  807. }
  808. }
  809. getPathData(animation: Animation | null) {
  810. if (animation === null) {
  811. return undefined;
  812. }
  813. var keyframes = animation.getKeys();
  814. if (keyframes === undefined) {
  815. return undefined;
  816. } else {
  817. const { easingMode, easingType, usesTangents, valueType, highestFrame, name, targetProperty } = this.getAnimationData(animation);
  818. keyframes = this.flatTangents(keyframes, valueType);
  819. const startKey = keyframes[0];
  820. let middle = this._heightScale / this._scaleFactor; //?
  821. let collection: ICurveData[] = [];
  822. const colors = ["red", "green", "blue", "white", "#7a4ece"];
  823. const startValue = this.getValueAsArray(valueType, startKey.value);
  824. for (var d = 0; d < startValue.length; d++) {
  825. const id = `${name}_${targetProperty}_${d}`;
  826. const curveColor = valueType === Animation.ANIMATIONTYPE_FLOAT ? colors[4] : colors[d];
  827. // START OF LINE/CURVE
  828. let data: string | undefined = `M${startKey.frame * this._pixelFrameUnit}, ${this._heightScale - startValue[d] * middle}`; //
  829. if (this.state) {
  830. if (usesTangents) {
  831. data = this.curvePathWithTangents(keyframes, data, middle, valueType, d, id);
  832. } else {
  833. if (easingType !== undefined && easingMode !== undefined) {
  834. let easingFunction = animation.getEasingFunction();
  835. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction);
  836. } else {
  837. if (this.state !== undefined) {
  838. let emptyTangents = keyframes.map((kf, i) => {
  839. if (i === 0) {
  840. kf.outTangent = this.returnZero(valueType);
  841. } else if (i === keyframes.length - 1) {
  842. kf.inTangent = this.returnZero(valueType);
  843. } else {
  844. kf.inTangent = this.returnZero(valueType);
  845. kf.outTangent = this.returnZero(valueType);
  846. }
  847. return kf;
  848. });
  849. data = this.curvePathWithTangents(emptyTangents, data, middle, valueType, d, id);
  850. }
  851. }
  852. }
  853. }
  854. collection.push({
  855. pathData: data,
  856. pathLength: highestFrame,
  857. domCurve: React.createRef(),
  858. color: curveColor,
  859. id: id,
  860. });
  861. }
  862. return collection;
  863. }
  864. }
  865. getAnimationData(animation: Animation) {
  866. // General Props
  867. let loopMode = animation.loopMode;
  868. let name = animation.name;
  869. let blendingSpeed = animation.blendingSpeed;
  870. let targetProperty = animation.targetProperty;
  871. let targetPropertyPath = animation.targetPropertyPath;
  872. let framesPerSecond = animation.framePerSecond;
  873. let highestFrame = animation.getHighestFrame();
  874. //let serialized = animation.serialize();
  875. let usesTangents = animation.getKeys().find((kf) => kf.hasOwnProperty("inTangent") || kf.hasOwnProperty("outTangent")) !== undefined ? true : false;
  876. let valueType = animation.dataType;
  877. // easing properties
  878. let easingType, easingMode;
  879. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  880. if (easingFunction === undefined) {
  881. easingType = undefined;
  882. easingMode = undefined;
  883. } else {
  884. easingType = easingFunction.constructor.name;
  885. easingMode = easingFunction.getEasingMode();
  886. }
  887. return {
  888. loopMode,
  889. name,
  890. blendingSpeed,
  891. targetPropertyPath,
  892. targetProperty,
  893. framesPerSecond,
  894. highestFrame,
  895. usesTangents,
  896. easingType,
  897. easingMode,
  898. valueType,
  899. };
  900. }
  901. curvePathWithTangents(keyframes: IAnimationKey[], data: string, middle: number, type: number, coordinate: number, animationName: string) {
  902. keyframes.forEach((key, i) => {
  903. // Create a unique id for curve
  904. const curveId = this.encodeCurveId(animationName, i);
  905. // identify type of value and split...
  906. const keyframe_valueAsArray = this.getValueAsArray(type, key.value)[coordinate];
  907. let svgKeyframe;
  908. let outTangent;
  909. let inTangent;
  910. let defaultWeight = 5;
  911. let defaultTangent: number | null = null;
  912. if (i !== 0 || i !== keyframes.length - 1) {
  913. defaultTangent = 0;
  914. }
  915. var inT = key.inTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.inTangent)[coordinate];
  916. var outT = key.outTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.outTangent)[coordinate];
  917. let y = this._heightScale - keyframe_valueAsArray * middle;
  918. if (inT !== null) {
  919. let valueIn = y * inT + y;
  920. inTangent = new Vector2(key.frame * this._pixelFrameUnit - defaultWeight, valueIn);
  921. } else {
  922. inTangent = null;
  923. }
  924. if (outT !== null) {
  925. let valueOut = y * outT + y;
  926. outTangent = new Vector2(key.frame * this._pixelFrameUnit + defaultWeight, valueOut);
  927. } else {
  928. outTangent = null;
  929. }
  930. if (i === 0) {
  931. svgKeyframe = {
  932. keyframePoint: new Vector2(key.frame * this._pixelFrameUnit, this._heightScale - keyframe_valueAsArray * middle),
  933. rightControlPoint: outTangent,
  934. leftControlPoint: null,
  935. id: curveId,
  936. selected: false,
  937. isLeftActive: false,
  938. isRightActive: false,
  939. };
  940. if (outTangent !== null) {
  941. data += ` C${outTangent.x} ${outTangent.y} `;
  942. }
  943. } else {
  944. svgKeyframe = {
  945. keyframePoint: new Vector2(key.frame * this._pixelFrameUnit, this._heightScale - keyframe_valueAsArray * middle),
  946. rightControlPoint: outTangent,
  947. leftControlPoint: inTangent,
  948. id: curveId,
  949. selected: false,
  950. isLeftActive: false,
  951. isRightActive: false,
  952. };
  953. if (outTangent !== null && inTangent !== null) {
  954. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y} `;
  955. } else if (inTangent !== null) {
  956. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `;
  957. }
  958. }
  959. if (this.state) {
  960. let prev = this.state.svgKeyframes?.find((kf) => kf.id === curveId);
  961. if (prev) {
  962. svgKeyframe.isLeftActive = prev?.isLeftActive;
  963. svgKeyframe.isRightActive = prev?.isRightActive;
  964. svgKeyframe.selected = prev?.selected;
  965. }
  966. }
  967. this._svgKeyframes.push(svgKeyframe);
  968. }, this);
  969. return data;
  970. }
  971. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  972. // This will get 1/4 and 3/4 of points in eased curve
  973. const u = 0.25;
  974. const v = 0.75;
  975. keyframes.forEach((key, i) => {
  976. // identify type of value and split...
  977. // Gets previous initial point of curve segment
  978. var pointA = new Vector2(0, 0);
  979. if (i === 0) {
  980. pointA.x = key.frame;
  981. pointA.y = this._heightScale - key.value * middle;
  982. this.setKeyframePoint([pointA], i, keyframes.length);
  983. } else {
  984. pointA.x = keyframes[i - 1].frame;
  985. pointA.y = this._heightScale - keyframes[i - 1].value * middle;
  986. // Gets the end point of this curve segment
  987. var pointB = new Vector2(key.frame, this._heightScale - key.value * middle);
  988. // Get easing value of percentage to get the bezier control points below
  989. 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)
  990. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  991. // Direction of curve up/down
  992. let yInt25 = 0;
  993. if (pointB.y > pointA.y) {
  994. // if pointB.y > pointA.y = goes down
  995. yInt25 = (pointB.y - pointA.y) * du + pointA.y;
  996. } else if (pointB.y < pointA.y) {
  997. // if pointB.y < pointA.y = goes up
  998. yInt25 = pointA.y - (pointA.y - pointB.y) * du;
  999. }
  1000. let yInt75 = 0;
  1001. if (pointB.y > pointA.y) {
  1002. yInt75 = (pointB.y - pointA.y) * dv + pointA.y;
  1003. } else if (pointB.y < pointA.y) {
  1004. yInt75 = pointA.y - (pointA.y - pointB.y) * dv;
  1005. }
  1006. // Intermediate points in curve
  1007. let intermediatePoint25 = new Vector2((pointB.x - pointA.x) * u + pointA.x, yInt25);
  1008. let intermediatePoint75 = new Vector2((pointB.x - pointA.x) * v + pointA.x, yInt75);
  1009. // Gets the four control points of bezier curve
  1010. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  1011. if (controlPoints !== undefined) {
  1012. this.setKeyframePoint(controlPoints, i, keyframes.length);
  1013. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`;
  1014. }
  1015. }
  1016. });
  1017. return data;
  1018. }
  1019. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  1020. let svgKeyframe;
  1021. if (index === 0) {
  1022. svgKeyframe = {
  1023. keyframePoint: controlPoints[0],
  1024. rightControlPoint: null,
  1025. leftControlPoint: null,
  1026. id: index.toString(),
  1027. selected: false,
  1028. isLeftActive: false,
  1029. isRightActive: false,
  1030. };
  1031. } else {
  1032. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  1033. svgKeyframe = {
  1034. keyframePoint: controlPoints[3],
  1035. rightControlPoint: null,
  1036. leftControlPoint: controlPoints[2],
  1037. id: index.toString(),
  1038. selected: false,
  1039. isLeftActive: false,
  1040. isRightActive: false,
  1041. };
  1042. }
  1043. this._svgKeyframes.push(svgKeyframe);
  1044. }
  1045. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v: number, p3: Vector2): Vector2[] | undefined {
  1046. let a = 0.0;
  1047. let b = 0.0;
  1048. let c = 0.0;
  1049. let d = 0.0;
  1050. let det = 0.0;
  1051. let q1: Vector2 = new Vector2();
  1052. let q2: Vector2 = new Vector2();
  1053. let controlA: Vector2 = p0;
  1054. let controlB: Vector2 = new Vector2();
  1055. let controlC: Vector2 = new Vector2();
  1056. let controlD: Vector2 = p3;
  1057. if (u <= 0.0 || u >= 1.0 || v <= 0.0 || v >= 1.0 || u >= v) {
  1058. return undefined;
  1059. }
  1060. a = 3 * (1 - u) * (1 - u) * u;
  1061. b = 3 * (1 - u) * u * u;
  1062. c = 3 * (1 - v) * (1 - v) * v;
  1063. d = 3 * (1 - v) * v * v;
  1064. det = a * d - b * c;
  1065. if (det == 0.0) return undefined;
  1066. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  1067. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  1068. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  1069. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  1070. controlB.x = (d * q1.x - b * q2.x) / det;
  1071. controlB.y = (d * q1.y - b * q2.y) / det;
  1072. controlC.x = (-c * q1.x + a * q2.x) / det;
  1073. controlC.y = (-c * q1.y + a * q2.y) / det;
  1074. return [controlA, controlB, controlC, controlD];
  1075. }
  1076. deselectAnimation() {
  1077. this.setState({
  1078. selected: null,
  1079. svgKeyframes: [],
  1080. selectedPathData: [],
  1081. selectedCoordinate: 0,
  1082. });
  1083. }
  1084. /**
  1085. * Core functions
  1086. * This section handles main Curve Editor Functions.
  1087. */
  1088. selectAnimation(animation: Animation, coordinate?: SelectedCoordinate) {
  1089. this._svgKeyframes = [];
  1090. let updatedPath;
  1091. let filteredSvgKeys;
  1092. let selectedCurve = 0;
  1093. if (coordinate === undefined) {
  1094. this.stopAnimation();
  1095. updatedPath = this.getPathData(animation);
  1096. } else {
  1097. let curves = this.getPathData(animation);
  1098. updatedPath = [];
  1099. filteredSvgKeys = this._svgKeyframes?.filter((curve) => {
  1100. let id = parseInt(curve.id.split("_")[2]);
  1101. if (id === coordinate) {
  1102. return true;
  1103. } else {
  1104. return false;
  1105. }
  1106. });
  1107. curves?.map((curve) => {
  1108. let id = parseInt(curve.id.split("_")[2]);
  1109. if (id === coordinate) {
  1110. updatedPath.push(curve);
  1111. }
  1112. });
  1113. selectedCurve = coordinate;
  1114. }
  1115. // check for empty svgKeyframes, lastframe, selected
  1116. this.setState(
  1117. {
  1118. selected: animation,
  1119. svgKeyframes: coordinate !== undefined ? filteredSvgKeys : this._svgKeyframes,
  1120. selectedPathData: updatedPath,
  1121. selectedCoordinate: selectedCurve,
  1122. fps: animation.framePerSecond,
  1123. },
  1124. () => this.setMainAnimatable()
  1125. );
  1126. }
  1127. setMainAnimatable() {
  1128. if (this.state.selected) {
  1129. let target = this.props.entity;
  1130. if (this.props.entity instanceof TargetedAnimation) {
  1131. target = this.props.entity.target;
  1132. }
  1133. this.props.scene.stopAllAnimations();
  1134. if (this._mainAnimatable?.target !== target) {
  1135. const keys = this.state.selected.getKeys();
  1136. const firstFrame = keys[0].frame;
  1137. const LastFrame = this.state.selected.getHighestFrame();
  1138. this._mainAnimatable = this.props.scene.beginAnimation(target, firstFrame, LastFrame, this.state.isLooping);
  1139. this._mainAnimatable.pause();
  1140. }
  1141. }
  1142. }
  1143. isAnimationPlaying() {
  1144. let target = this.props.entity;
  1145. if (this.props.entity instanceof TargetedAnimation) {
  1146. target = this.props.entity.target;
  1147. }
  1148. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1149. }
  1150. stopAnimation() {
  1151. let target = this.props.entity;
  1152. if (this.props.entity instanceof TargetedAnimation) {
  1153. target = this.props.entity.target;
  1154. }
  1155. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1156. if (this._isPlaying) {
  1157. this.props.playOrPause && this.props.playOrPause();
  1158. }
  1159. }
  1160. setIsLooping() {
  1161. this.setState({ isLooping: !this.state.isLooping, isPlaying: false }, () => this.stopAnimation());
  1162. }
  1163. setFramesPerSecond(fps: number) {
  1164. this.setState({ fps: fps, isPlaying: false }, () => this.stopAnimation());
  1165. }
  1166. analizeAnimationForLerp(animation: Animation | null) {
  1167. if (animation !== null) {
  1168. const { easingMode, easingType, usesTangents } = this.getAnimationData(animation);
  1169. if (easingType === undefined && easingMode === undefined && !usesTangents) {
  1170. return true;
  1171. } else {
  1172. return false;
  1173. }
  1174. } else {
  1175. return false;
  1176. }
  1177. }
  1178. /**
  1179. * Timeline
  1180. * This section controls the timeline.
  1181. */
  1182. changeCurrentFrame(frame: number) {
  1183. let currentValue;
  1184. this.stopAnimation();
  1185. if (this.state.selectedPathData) {
  1186. let selectedCurve = this.state.selectedPathData[this.state.selectedCoordinate].domCurve.current;
  1187. if (selectedCurve) {
  1188. var curveLength = selectedCurve.getTotalLength();
  1189. let frameValue = (frame * curveLength) / 100;
  1190. let currentP = selectedCurve.getPointAtLength(frameValue);
  1191. let middle = this._heightScale / 2;
  1192. let offset = (currentP?.y * this._heightScale - this._heightScale ** 2 / 2) / middle / this._heightScale;
  1193. let unit = Math.sign(offset);
  1194. currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  1195. this.setState({
  1196. currentFrame: frame,
  1197. currentValue: currentValue,
  1198. currentPoint: currentP,
  1199. isPlaying: false,
  1200. });
  1201. }
  1202. }
  1203. }
  1204. setCanvasPosition(frame: number) {
  1205. this.setState({ panningX: (frame - 10) * 10, repositionCanvas: true });
  1206. }
  1207. setCurrentFrame(direction: number) {
  1208. this.setState({
  1209. currentFrame: this.state.currentFrame + direction,
  1210. });
  1211. }
  1212. changeAnimationLimit(limit: number) {
  1213. this.setState({
  1214. animationLimit: limit,
  1215. });
  1216. }
  1217. updateFrameInKeyFrame(frame: number, index: number) {
  1218. if (this.state && this.state.selected) {
  1219. let animation = this.state.selected;
  1220. let keys = [...animation.getKeys()];
  1221. keys[index].frame = frame;
  1222. animation.setKeys(keys);
  1223. this.selectAnimation(animation);
  1224. }
  1225. }
  1226. playPause(direction: number) {
  1227. this.registerObs();
  1228. if (this.state.selected) {
  1229. let target = this.props.entity;
  1230. if (this.props.entity instanceof TargetedAnimation) {
  1231. target = this.props.entity.target;
  1232. }
  1233. if (this.state.isPlaying && direction === 0) {
  1234. this.props.scene.stopAnimation(target);
  1235. this.setState({ isPlaying: false });
  1236. this._isPlaying = false;
  1237. this.forceUpdate();
  1238. } else {
  1239. if (this.state.isPlaying) {
  1240. this.props.scene.stopAnimation(target);
  1241. }
  1242. let keys = this.state.selected.getKeys();
  1243. let firstFrame = keys[0].frame;
  1244. let LastFrame = this.state.selected.getHighestFrame();
  1245. if (direction === 1) {
  1246. // Runtime Animation adds Frame 0
  1247. this._mainAnimatable = this.props.scene.beginAnimation(target, firstFrame, LastFrame, this.state.isLooping);
  1248. }
  1249. if (direction === -1) {
  1250. // Runtime Animation adds Frame 0
  1251. this._mainAnimatable = this.props.scene.beginAnimation(target, LastFrame, firstFrame, this.state.isLooping);
  1252. }
  1253. this._isPlaying = true;
  1254. this.setState({ isPlaying: true });
  1255. this.forceUpdate();
  1256. }
  1257. }
  1258. }
  1259. moveFrameTo(e: React.MouseEvent<SVGRectElement, MouseEvent>) {
  1260. this.stopAnimation();
  1261. var svg = e.currentTarget as SVGRectElement;
  1262. var CTM = svg.getScreenCTM();
  1263. let position;
  1264. if (CTM) {
  1265. position = new Vector2((e.clientX - CTM.e) / CTM.a, (e.clientY - CTM.f) / CTM.d);
  1266. let selectedFrame = Math.round(position.x / this._pixelFrameUnit);
  1267. this.setState({ currentFrame: selectedFrame, isPlaying: false });
  1268. }
  1269. }
  1270. registerObs() {
  1271. this._onBeforeRenderObserver = this.props.scene.onBeforeRenderObservable.add(() => {
  1272. if (!this._isPlaying || !this._mainAnimatable) {
  1273. return;
  1274. }
  1275. this.setState({
  1276. currentFrame: Math.round(this._mainAnimatable.masterFrame),
  1277. });
  1278. });
  1279. }
  1280. componentWillUnmount() {
  1281. if (this._onBeforeRenderObserver) {
  1282. this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  1283. this._onBeforeRenderObserver = null;
  1284. }
  1285. }
  1286. isCurrentFrame(frame: number) {
  1287. return this.state.currentFrame === frame;
  1288. }
  1289. render() {
  1290. return (
  1291. <div id="animation-curve-editor">
  1292. <Notification message={this.state.notification} open={this.state.notification !== "" ? true : false} close={() => this.clearNotification()} />
  1293. <GraphActionsBar
  1294. setKeyframeValue={() => this.setKeyframeValue()}
  1295. enabled={this.state.selected === null || this.state.selected === undefined ? false : true}
  1296. title={this._entityName}
  1297. close={this.props.close}
  1298. actionableKeyframe={this.state.actionableKeyframe}
  1299. handleFrameChange={(e) => this.handleFrameChange(e)}
  1300. handleValueChange={(e) => this.handleValueChange(e)}
  1301. addKeyframe={() => this.addKeyframeClick()}
  1302. removeKeyframe={() => this.removeKeyframeClick()}
  1303. brokenMode={this.state.isBrokenMode}
  1304. brokeTangents={() => this.setBrokenMode()}
  1305. lerpMode={this.state.lerpMode}
  1306. setLerpMode={() => this.setLerpMode()}
  1307. flatTangent={() => this.setFlatTangent()}
  1308. />
  1309. <div className="content">
  1310. <div className="row">
  1311. <EditorControls
  1312. deselectAnimation={() => this.deselectAnimation()}
  1313. selectAnimation={(animation: Animation, axis?: SelectedCoordinate) => this.selectAnimation(animation, axis)}
  1314. isTargetedAnimation={this._isTargetedAnimation}
  1315. entity={this.props.entity}
  1316. selected={this.state.selected}
  1317. lockObject={this.props.lockObject}
  1318. setNotificationMessage={(message: string) => {
  1319. this.setState({ notification: message });
  1320. }}
  1321. globalState={this.props.globalState}
  1322. snippetServer={this._snippetUrl}
  1323. fps={this.state.fps}
  1324. setFps={(fps: number) => this.setFramesPerSecond(fps)}
  1325. setIsLooping={() => this.setIsLooping()}
  1326. />
  1327. <div ref={this._graphCanvas} className="graph-chart" onWheel={(e) => this.zoom(e)}>
  1328. {this.state.svgKeyframes && (
  1329. <SvgDraggableArea
  1330. ref={this._svgCanvas}
  1331. selectKeyframe={(id: string, multiselect: boolean) => this.selectKeyframe(id, multiselect)}
  1332. viewBoxScale={this.state.frameAxisLength.length}
  1333. scale={this.state.scale}
  1334. keyframeSvgPoints={this.state.svgKeyframes}
  1335. removeSelectedKeyframes={(points: IKeyframeSvgPoint[]) => this.removeKeyframes(points)}
  1336. selectedControlPoint={(type: string, id: string) => this.selectedControlPoint(type, id)}
  1337. deselectKeyframes={() => this.deselectKeyframes()}
  1338. updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint, id: string) => this.renderPoints(updatedSvgKeyFrame, id)}
  1339. panningY={(panningY: number) => {
  1340. this.setState({ panningY: panningY });
  1341. }}
  1342. panningX={(panningX: number) => {
  1343. this.setState({ panningX: panningX });
  1344. }}
  1345. setCurrentFrame={(direction: number) => this.setCurrentFrame(direction)}
  1346. positionCanvas={this.state.panningX}
  1347. repositionCanvas={this.state.repositionCanvas}
  1348. canvasPositionEnded={() => this.setState({ repositionCanvas: false })}
  1349. resetActionableKeyframe={() => this.resetActionableKeyframe()}
  1350. >
  1351. {/* Multiple Curves */}
  1352. {this.state.selectedPathData?.map((curve, i) => (
  1353. <path
  1354. key={i}
  1355. ref={curve.domCurve}
  1356. pathLength={curve.pathLength}
  1357. id="curve"
  1358. d={curve.pathData}
  1359. style={{
  1360. stroke: curve.color,
  1361. fill: "none",
  1362. strokeWidth: "0.5",
  1363. }}
  1364. ></path>
  1365. ))}
  1366. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1367. return (
  1368. <text
  1369. key={`value_inline_${i}`}
  1370. x={this.state.panningX - 5}
  1371. y={line.value}
  1372. dx="2"
  1373. textAnchor="middle"
  1374. dy="-1"
  1375. style={{
  1376. fontSize: `${0.18 * this.state.scale}em`,
  1377. fontWeight: "bold",
  1378. textAlign: "center",
  1379. }}
  1380. >
  1381. {line.label}
  1382. </text>
  1383. );
  1384. })}
  1385. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1386. return <line key={i} x1={-((this.state.frameAxisLength.length * 10) / 2)} y1={line.value} x2={this.state.frameAxisLength.length * 10} y2={line.value}></line>;
  1387. })}
  1388. <rect onClick={(e) => this.moveFrameTo(e)} x={-((this.state.frameAxisLength.length * 10) / 2)} y={91 + this.state.panningY + "%"} width={this.state.frameAxisLength.length * 10} height="9%" fill="#222" style={{ cursor: "pointer" }}></rect>
  1389. {this.state.frameAxisLength.map((f, i) => (
  1390. <svg key={i} x="0" y={96 + this.state.panningY + "%"} className="frame-contain">
  1391. <text x={f.value} y="0" dx="2px" style={{ fontSize: `${0.17 * this.state.scale}em` }}>
  1392. {f.label}
  1393. </text>
  1394. <line x1={f.value} y1="0" x2={f.value} y2="5%"></line>
  1395. {f.value % this.state.fps === 0 && f.value !== 0 ? <line x1={f.value} y1="-100%" x2={f.value} y2="5%"></line> : null}
  1396. {this.state.selected && this.isCurrentFrame(f.label) ? (
  1397. <svg>
  1398. <line
  1399. x1={f.value}
  1400. y1="0"
  1401. x2={f.value}
  1402. y2="-100%"
  1403. style={{
  1404. stroke: "white",
  1405. strokeWidth: 0.4,
  1406. }}
  1407. />
  1408. <svg x={f.value} y="-1">
  1409. <circle className="svg-playhead" cx="0" cy="0" r="2%" fill="white" />
  1410. <text
  1411. x="0"
  1412. y="1%"
  1413. textAnchor="middle"
  1414. style={{
  1415. fontSize: `${0.17 * this.state.scale}em`,
  1416. pointerEvents: "none",
  1417. fontWeight: 600,
  1418. }}
  1419. >
  1420. {f.label}
  1421. </text>
  1422. </svg>
  1423. </svg>
  1424. ) : null}
  1425. </svg>
  1426. ))}
  1427. </SvgDraggableArea>
  1428. )}
  1429. <ScaleLabel current={this.state.valueScale} />
  1430. </div>
  1431. </div>
  1432. <div className="row-bottom">
  1433. <Timeline
  1434. currentFrame={this.state.currentFrame}
  1435. playPause={(direction: number) => this.playPause(direction)}
  1436. isPlaying={this.state.isPlaying}
  1437. dragKeyframe={(frame: number, index: number) => this.updateFrameInKeyFrame(frame, index)}
  1438. onCurrentFrameChange={(frame: number) => this.changeCurrentFrame(frame)}
  1439. onAnimationLimitChange={(limit: number) => this.changeAnimationLimit(limit)}
  1440. animationLimit={this.state.animationLimit}
  1441. keyframes={this.state.selected && this.state.selected.getKeys()}
  1442. selected={this.state.selected && this.state.selected.getKeys()[0]}
  1443. fps={this.state.fps}
  1444. repositionCanvas={(frame: number) => this.setCanvasPosition(frame)}
  1445. ></Timeline>
  1446. </div>
  1447. </div>
  1448. </div>
  1449. );
  1450. }
  1451. }