animationCurveEditorComponent.tsx 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  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. import { KeyframeSvgPoint } from "./keyframeSvgPoint";
  25. require("./curveEditor.scss");
  26. interface IAnimationCurveEditorComponentProps {
  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. canvasLength: number;
  86. lastKeyframeCreated: Nullable<string>;
  87. canvasWidthScale: number;
  88. }
  89. > {
  90. private _snippetUrl = "https://snippet.babylonjs.com";
  91. // Height scale *Review this functionaliy
  92. private _heightScale: number = 100;
  93. private _scaleFactor: number = 2;
  94. private _currentScale: number = 10;
  95. // Canvas Length *Review this functionality
  96. readonly _entityName: string;
  97. //private _canvasLength: number;
  98. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  99. private _isPlaying: boolean = false;
  100. private _graphCanvas: React.RefObject<HTMLDivElement>;
  101. private _editor: React.RefObject<HTMLDivElement>;
  102. //private _selectedCurve: React.RefObject<SVGPathElement>;
  103. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  104. private _isTargetedAnimation: boolean;
  105. private _pixelFrameUnit: number;
  106. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  107. private _mainAnimatable: Nullable<Animatable>;
  108. constructor(props: IAnimationCurveEditorComponentProps) {
  109. super(props);
  110. this._entityName = (this.props.entity as any).id;
  111. this._editor = React.createRef();
  112. this._graphCanvas = React.createRef();
  113. this._svgCanvas = React.createRef();
  114. this._pixelFrameUnit = 10;
  115. let initialSelection;
  116. let initialPathData;
  117. let initialLerpMode;
  118. if (this.props.entity instanceof TargetedAnimation) {
  119. this._isTargetedAnimation = true;
  120. initialSelection = this.props.entity.animation;
  121. initialLerpMode = initialSelection !== undefined ? this.analizeAnimationForLerp(initialSelection) : false;
  122. initialPathData = initialSelection !== undefined ? this.getPathData(initialSelection) : undefined;
  123. } else {
  124. this._isTargetedAnimation = false;
  125. let hasAnimations =
  126. this.props.entity.animations !== undefined || this.props.entity.animations !== null
  127. ? this.props.entity.animations
  128. : false;
  129. initialSelection = hasAnimations !== false ? hasAnimations && hasAnimations[0] : null;
  130. initialLerpMode =
  131. initialSelection !== undefined
  132. ? this.analizeAnimationForLerp(this.props.entity.animations && initialSelection)
  133. : false;
  134. initialPathData = initialSelection && this.getPathData(initialSelection);
  135. initialPathData = initialPathData === null || initialPathData === undefined ? undefined : initialPathData;
  136. }
  137. const _canvasLength = 240;
  138. this.stopAnimation();
  139. // will update this until we have a top scroll/zoom feature
  140. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  141. this.state = {
  142. selected: initialSelection,
  143. isOpen: true,
  144. svgKeyframes: this._svgKeyframes,
  145. currentFrame: 0,
  146. currentValue: 1,
  147. isFlatTangentMode: false,
  148. isTangentMode: false,
  149. isBrokenMode: false,
  150. lerpMode: initialLerpMode,
  151. playheadOffset: this._graphCanvas.current
  152. ? this._graphCanvas.current.children[0].clientWidth / (_canvasLength * 10)
  153. : 0,
  154. frameAxisLength: this.setFrameAxis(_canvasLength),
  155. valueAxisLength: new Array(10).fill(0).map((s, i) => {
  156. return { value: i * 10, label: valueInd[i] };
  157. }),
  158. notification: "",
  159. currentPoint: undefined,
  160. scale: 1,
  161. playheadPos: 0,
  162. isPlaying: false,
  163. selectedPathData: initialPathData,
  164. selectedCoordinate: 0,
  165. animationLimit: _canvasLength / 2,
  166. canvasLength: _canvasLength,
  167. fps: 60,
  168. isLooping: true,
  169. panningY: 0,
  170. panningX: 0,
  171. repositionCanvas: false,
  172. actionableKeyframe: { frame: undefined, value: undefined },
  173. valueScale: CurveScale.default,
  174. lastKeyframeCreated: null,
  175. canvasWidthScale: 200,
  176. };
  177. }
  178. componentDidMount() {
  179. this.state.selected && this.selectAnimation(this.state.selected);
  180. }
  181. componentDidUpdate(prevProps: IAnimationCurveEditorComponentProps, prevState: any) {
  182. if (prevState.currentFrame !== this.state.currentFrame) {
  183. this.onCurrentFrameChangeChangeScene(this.state.currentFrame);
  184. }
  185. }
  186. onCurrentFrameChangeChangeScene(value: number) {
  187. if (!this._mainAnimatable) {
  188. return;
  189. }
  190. this._mainAnimatable.goToFrame(value);
  191. }
  192. /**
  193. * Notifications
  194. * To add notification we set the state and clear to make the notification bar hide.
  195. */
  196. clearNotification = () => {
  197. this.setState({ notification: "" });
  198. };
  199. /**
  200. * Zoom and Scroll
  201. * This section handles zoom and scroll
  202. * of the graph area.
  203. */
  204. zoom = (e: React.WheelEvent<HTMLDivElement>) => {
  205. e.nativeEvent.stopImmediatePropagation();
  206. let scaleX = 1;
  207. if (Math.sign(e.deltaY) === -1) {
  208. scaleX = this.state.scale; //- 0.01; //+ 0.01;
  209. }
  210. this.setState({ scale: scaleX });
  211. };
  212. setFrameAxis(currentLength: number) {
  213. let halfNegative = new Array(currentLength).fill(0).map((s, i) => {
  214. return { value: -i * 10, label: -i };
  215. });
  216. let halfPositive = new Array(currentLength).fill(0).map((s, i) => {
  217. return { value: i * 10, label: i };
  218. });
  219. return [...halfNegative, ...halfPositive];
  220. }
  221. setValueLines(type: CurveScale) {
  222. switch (type) {
  223. case CurveScale.default:
  224. this._heightScale = 100;
  225. this._scaleFactor = 2;
  226. break;
  227. case CurveScale.float:
  228. this._scaleFactor = 2.5;
  229. this._heightScale = 120;
  230. break;
  231. case CurveScale.degrees:
  232. this._scaleFactor = 50;
  233. this._heightScale = 200;
  234. break;
  235. case CurveScale.integers:
  236. this._scaleFactor = 320;
  237. break;
  238. case CurveScale.radians:
  239. this._scaleFactor = 0.8;
  240. break;
  241. }
  242. const lineV = this._heightScale / 10;
  243. const initialValues = new Array(this._currentScale).fill(0).map((_, i) => {
  244. return {
  245. value: i * lineV,
  246. label: (this._scaleFactor * ((this._currentScale - i) / this._currentScale)).toFixed(2),
  247. };
  248. });
  249. initialValues.shift();
  250. const valueHeight = Math.abs(Math.round(this.state.panningY / this._currentScale));
  251. const sign = Math.sign(this.state.panningY);
  252. const pannedValues = new Array(valueHeight).fill(0).map((s, i) => {
  253. return sign === -1
  254. ? {
  255. value: -i * lineV,
  256. label: (i + this._currentScale) / (this._currentScale / this._scaleFactor),
  257. }
  258. : {
  259. value: (i + lineV) * this._currentScale,
  260. label: (i * -1) / (this._currentScale / this._scaleFactor),
  261. };
  262. });
  263. return [...initialValues, ...pannedValues];
  264. }
  265. getValueLabel(i: number) {
  266. // Need to update this when Y axis grows
  267. let label = 0;
  268. if (i === 0) {
  269. label = 2;
  270. }
  271. if (i === 50) {
  272. label = 1;
  273. } else {
  274. label = (100 - i * 2) * 0.01 + 1;
  275. }
  276. return label;
  277. }
  278. resetPlayheadOffset() {
  279. if (this._graphCanvas && this._graphCanvas.current) {
  280. this.setState({
  281. playheadOffset:
  282. this._graphCanvas.current.children[0].clientWidth /
  283. (this.state.canvasLength * 10 * this.state.scale),
  284. });
  285. }
  286. }
  287. encodeCurveId(animationName: string, keyframeIndex: number) {
  288. return animationName + "_" + keyframeIndex;
  289. }
  290. decodeCurveId(id: string) {
  291. const order = parseInt(id.split("_")[3]);
  292. const coordinate = parseInt(id.split("_")[2]);
  293. return { order, coordinate };
  294. }
  295. getKeyframeValueFromAnimation(id: string) {
  296. const animation = this.state.selected as Animation;
  297. const { order, coordinate } = this.decodeCurveId(id);
  298. const keys = [...animation.getKeys()];
  299. const key = keys.find((_, i) => i === order);
  300. if (key) {
  301. const valueAsArray = this.getValueAsArray(animation.dataType, key.value);
  302. return { frame: key?.frame, value: valueAsArray[coordinate] };
  303. } else {
  304. return undefined;
  305. }
  306. }
  307. /**
  308. * Keyframe Manipulation
  309. * This section handles events from SvgDraggableArea.
  310. */
  311. selectKeyframe = (id: string, multiselect: boolean) => {
  312. let frameValue: IActionableKeyFrame | undefined;
  313. const selectedKeyFrame = this.state.svgKeyframes?.find((kf) => kf.id === id)?.selected;
  314. if (!multiselect) {
  315. frameValue = this.getKeyframeValueFromAnimation(id);
  316. this.deselectKeyframes();
  317. } else {
  318. frameValue = { frame: undefined, value: undefined };
  319. }
  320. if (selectedKeyFrame) {
  321. frameValue = { frame: undefined, value: undefined };
  322. }
  323. const updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  324. if (kf.id === id) {
  325. kf.selected = !selectedKeyFrame;
  326. }
  327. return kf;
  328. });
  329. this.setState({
  330. svgKeyframes: updatedKeyframes,
  331. actionableKeyframe: frameValue ?? this.state.actionableKeyframe,
  332. });
  333. };
  334. selectKeyframeFromId = (id: string, actionableKeyframe: IActionableKeyFrame) => {
  335. this.deselectKeyframes();
  336. const updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  337. if (kf.id === id) {
  338. kf.selected = true;
  339. }
  340. return kf;
  341. });
  342. this.setState({
  343. svgKeyframes: updatedKeyframes,
  344. actionableKeyframe: actionableKeyframe ?? this.state.actionableKeyframe,
  345. });
  346. };
  347. resetActionableKeyframe = () => {
  348. this.setState({
  349. actionableKeyframe: { frame: undefined, value: undefined },
  350. });
  351. };
  352. selectedControlPoint = (type: string, id: string) => {
  353. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  354. if (kf.id === id) {
  355. kf.isLeftActive = true;
  356. kf.isRightActive = false;
  357. if (type === "left") {
  358. kf.isLeftActive = true;
  359. kf.isRightActive = false;
  360. }
  361. if (type === "right") {
  362. kf.isRightActive = true;
  363. kf.isLeftActive = false;
  364. }
  365. }
  366. return kf;
  367. });
  368. this.setState({ svgKeyframes: updatedKeyframes });
  369. };
  370. deselectKeyframes = () => {
  371. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  372. kf.isLeftActive = false;
  373. kf.isRightActive = false;
  374. kf.selected = false;
  375. return kf;
  376. });
  377. this.setState({
  378. svgKeyframes: updatedKeyframes,
  379. actionableKeyframe: { frame: undefined, value: undefined },
  380. });
  381. };
  382. updateValuePerCoordinate(
  383. dataType: number,
  384. value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion,
  385. newValue: number,
  386. coordinate?: number
  387. ) {
  388. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  389. value = newValue;
  390. }
  391. if (dataType === Animation.ANIMATIONTYPE_VECTOR2) {
  392. switch (coordinate) {
  393. case SelectedCoordinate.x:
  394. (value as Vector2).x = newValue;
  395. break;
  396. case SelectedCoordinate.y:
  397. (value as Vector2).y = newValue;
  398. break;
  399. }
  400. }
  401. if (dataType === Animation.ANIMATIONTYPE_VECTOR3) {
  402. switch (coordinate) {
  403. case SelectedCoordinate.x:
  404. (value as Vector3).x = newValue;
  405. break;
  406. case SelectedCoordinate.y:
  407. (value as Vector3).y = newValue;
  408. break;
  409. case SelectedCoordinate.z:
  410. (value as Vector3).z = newValue;
  411. break;
  412. }
  413. }
  414. if (dataType === Animation.ANIMATIONTYPE_QUATERNION) {
  415. switch (coordinate) {
  416. case SelectedCoordinate.x:
  417. (value as Quaternion).x = newValue;
  418. break;
  419. case SelectedCoordinate.y:
  420. (value as Quaternion).y = newValue;
  421. break;
  422. case SelectedCoordinate.z:
  423. (value as Quaternion).z = newValue;
  424. break;
  425. case SelectedCoordinate.w:
  426. (value as Quaternion).w = newValue;
  427. break;
  428. }
  429. }
  430. if (dataType === Animation.ANIMATIONTYPE_COLOR3) {
  431. switch (coordinate) {
  432. case SelectedCoordinate.r:
  433. (value as Color3).r = newValue;
  434. break;
  435. case SelectedCoordinate.g:
  436. (value as Color3).g = newValue;
  437. break;
  438. case SelectedCoordinate.b:
  439. (value as Color3).b = newValue;
  440. break;
  441. }
  442. }
  443. if (dataType === Animation.ANIMATIONTYPE_COLOR4) {
  444. switch (coordinate) {
  445. case SelectedCoordinate.r:
  446. (value as Color4).r = newValue;
  447. break;
  448. case SelectedCoordinate.g:
  449. (value as Color4).g = newValue;
  450. break;
  451. case SelectedCoordinate.b:
  452. (value as Color4).b = newValue;
  453. break;
  454. case SelectedCoordinate.a:
  455. (value as Color4).a = newValue;
  456. break;
  457. }
  458. }
  459. if (dataType === Animation.ANIMATIONTYPE_SIZE) {
  460. switch (coordinate) {
  461. case SelectedCoordinate.width:
  462. (value as Size).width = newValue;
  463. break;
  464. case SelectedCoordinate.g:
  465. (value as Size).height = newValue;
  466. break;
  467. }
  468. }
  469. return value;
  470. }
  471. forceFrameZeroToExist(keys: IAnimationKey[]) {
  472. const zeroFrame = keys.find((x) => Math.abs(x.frame) === 0);
  473. if (zeroFrame === undefined) {
  474. const prevToZero = keys.filter((x) => Math.sign(x.frame) === -1).sort((a, b) => b.frame - a.frame);
  475. let value;
  476. if (prevToZero.length !== 0) {
  477. value = prevToZero[0].value;
  478. } else {
  479. value = 1;
  480. }
  481. const frame: IAnimationKey = { frame: 0, value };
  482. keys.push(frame);
  483. keys.sort((a, b) => a.frame - b.frame);
  484. }
  485. }
  486. renderPoints = (updatedSvgKeyFrame: IKeyframeSvgPoint, id: string) => {
  487. let animation = this.state.selected as Animation;
  488. const { order: index, coordinate } = this.decodeCurveId(id);
  489. let keys = [...animation.getKeys()];
  490. let newFrame = 0;
  491. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  492. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  493. newFrame = 0;
  494. } else {
  495. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x / this._pixelFrameUnit);
  496. }
  497. }
  498. if (newFrame > keys[index].frame) {
  499. if (index === keys.length - 1) {
  500. keys[index].frame = newFrame;
  501. } else {
  502. const nextKf = keys[index + 1];
  503. if (nextKf) {
  504. if (nextKf.frame <= newFrame) {
  505. keys[index].frame = keys[index].frame;
  506. } else {
  507. keys[index].frame = newFrame;
  508. }
  509. }
  510. }
  511. }
  512. if (newFrame < keys[index].frame) {
  513. if (index === 0) {
  514. keys[index].frame = newFrame;
  515. } else {
  516. const prevKf = keys[index - 1];
  517. if (prevKf) {
  518. if (prevKf.frame >= newFrame) {
  519. keys[index].frame = keys[index].frame;
  520. } else {
  521. keys[index].frame = newFrame;
  522. }
  523. }
  524. }
  525. }
  526. let updatedValue =
  527. ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * this._scaleFactor;
  528. const updatedValueInCoordinate = this.updateValuePerCoordinate(
  529. animation.dataType,
  530. keys[index].value,
  531. updatedValue,
  532. coordinate
  533. );
  534. keys[index].value = updatedValueInCoordinate;
  535. this.updateLeftControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  536. this.updateRightControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  537. this.forceFrameZeroToExist(keys);
  538. animation.setKeys(keys);
  539. this.setState({
  540. actionableKeyframe: { frame: newFrame, value: updatedValueInCoordinate },
  541. });
  542. this.selectAnimation(animation, coordinate);
  543. };
  544. updateLeftControlPoint(
  545. updatedSvgKeyFrame: IKeyframeSvgPoint,
  546. key: IAnimationKey,
  547. dataType: number,
  548. coordinate: number
  549. ) {
  550. if (updatedSvgKeyFrame.isLeftActive) {
  551. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  552. // Rotate Control Points
  553. // Get the previous svgKeyframe and measure distance between these two points
  554. let distanceWithPreviousKeyframe = this.getControlPointWeight(updatedSvgKeyFrame);
  555. // Get a quarter of that value for amplitude
  556. let distanceAmplitudeOfX = updatedSvgKeyFrame.leftControlPoint.x - distanceWithPreviousKeyframe;
  557. let slope =
  558. (updatedSvgKeyFrame.leftControlPoint.y - updatedSvgKeyFrame.keyframePoint.y) /
  559. (updatedSvgKeyFrame.leftControlPoint.x - updatedSvgKeyFrame.keyframePoint.x);
  560. let newValueOfY =
  561. (distanceAmplitudeOfX - updatedSvgKeyFrame.leftControlPoint.x) * slope +
  562. updatedSvgKeyFrame.keyframePoint.y;
  563. let updatedValue =
  564. ((newValueOfY - updatedSvgKeyFrame.keyframePoint.y) * this._scaleFactor) / this._heightScale;
  565. if (updatedValue > -100 && updatedValue < 100) {
  566. key.inTangent = this.updateValuePerCoordinate(dataType, key.inTangent, updatedValue, coordinate);
  567. if (!this.state.isBrokenMode) {
  568. // Right control point if exists
  569. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  570. // Sets opposite value
  571. key.outTangent = key.inTangent * -1;
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. updateRightControlPoint(
  579. updatedSvgKeyFrame: IKeyframeSvgPoint,
  580. key: IAnimationKey,
  581. dataType: number,
  582. coordinate: number
  583. ) {
  584. if (updatedSvgKeyFrame.isRightActive) {
  585. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  586. // Rotate Control Points
  587. // Get the next svgKeyframe and measure distance between these two points
  588. let distanceWithNextKeyframe = this.getControlPointWeight(updatedSvgKeyFrame);
  589. let distanceAmplitudeOfX = updatedSvgKeyFrame.rightControlPoint.x + distanceWithNextKeyframe;
  590. let slope =
  591. (updatedSvgKeyFrame.rightControlPoint.y - updatedSvgKeyFrame.keyframePoint.y) /
  592. (updatedSvgKeyFrame.rightControlPoint.x - updatedSvgKeyFrame.keyframePoint.x);
  593. let newValueOfY =
  594. (distanceAmplitudeOfX - updatedSvgKeyFrame.rightControlPoint.x) * slope +
  595. updatedSvgKeyFrame.keyframePoint.y;
  596. let updatedValue =
  597. ((newValueOfY - updatedSvgKeyFrame.keyframePoint.y) * this._scaleFactor) / this._heightScale;
  598. if (updatedValue > -100 && updatedValue < 100) {
  599. key.outTangent = this.updateValuePerCoordinate(dataType, key.outTangent, updatedValue, coordinate);
  600. if (!this.state.isBrokenMode) {
  601. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  602. // Sets opposite value
  603. key.inTangent = key.outTangent * -1;
  604. }
  605. }
  606. }
  607. }
  608. }
  609. }
  610. getControlPointWeight(updatedSvgKeyFrame: IKeyframeSvgPoint) {
  611. let distanceWithPreviousKeyframe = this.state.canvasWidthScale / 4;
  612. if (this.state.svgKeyframes) {
  613. let indexOfKeyframe = this.state.svgKeyframes.indexOf(updatedSvgKeyFrame);
  614. let previousKeyframe = this.state.svgKeyframes[indexOfKeyframe - 1];
  615. if (previousKeyframe?.keyframePoint) {
  616. distanceWithPreviousKeyframe =
  617. Vector2.Distance(updatedSvgKeyFrame.keyframePoint, previousKeyframe.keyframePoint) / 2;
  618. }
  619. }
  620. let distanceWithNextKeyframe = this.state.canvasWidthScale / 4;
  621. if (this.state.svgKeyframes) {
  622. let indexOfKeyframe = this.state.svgKeyframes.indexOf(updatedSvgKeyFrame);
  623. let nextKeyframe = this.state.svgKeyframes[indexOfKeyframe + 1];
  624. if (nextKeyframe?.keyframePoint) {
  625. distanceWithNextKeyframe =
  626. Vector2.Distance(nextKeyframe.keyframePoint, updatedSvgKeyFrame.keyframePoint) / 2;
  627. }
  628. }
  629. if (distanceWithPreviousKeyframe < distanceWithNextKeyframe) {
  630. return distanceWithPreviousKeyframe;
  631. } else {
  632. return distanceWithNextKeyframe;
  633. }
  634. }
  635. handleFrameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  636. event.preventDefault();
  637. let frame;
  638. if (event.target.value === "") {
  639. frame = "";
  640. } else {
  641. frame = parseInt(event.target.value);
  642. }
  643. this.setState({
  644. actionableKeyframe: {
  645. frame: frame,
  646. value: this.state.actionableKeyframe.value,
  647. },
  648. });
  649. };
  650. handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  651. event.preventDefault();
  652. let value;
  653. if (event.target.value !== undefined) {
  654. if (event.target.value !== "") {
  655. value = parseFloat(event.target.value);
  656. } else {
  657. value = "";
  658. }
  659. this.setState({
  660. actionableKeyframe: {
  661. frame: this.state.actionableKeyframe.frame,
  662. value: value,
  663. },
  664. });
  665. }
  666. };
  667. setKeyframeValueFromInput = (actionableKeyframe: IActionableKeyFrame) => {
  668. this.setState(
  669. {
  670. actionableKeyframe,
  671. },
  672. this.setKeyframeValue
  673. );
  674. };
  675. setKeyframeValue = () => {
  676. if (
  677. this.state.actionableKeyframe.frame !== "" &&
  678. this.state.actionableKeyframe.frame !== undefined &&
  679. this.state.actionableKeyframe.value !== "" &&
  680. this.state.actionableKeyframe.value !== undefined
  681. ) {
  682. if (this.state.selected !== null) {
  683. let currentSelected = this.state.svgKeyframes?.find((kf) => kf.selected);
  684. if (currentSelected) {
  685. let { order, coordinate } = this.decodeCurveId(currentSelected.id);
  686. let animation = this.state.selected;
  687. let keys = animation.getKeys();
  688. let isKeyframe = keys.find((_, i) => i === order);
  689. if (isKeyframe) {
  690. let updatedKeys = keys.map((k, i) => {
  691. if (i === order) {
  692. k.frame = this.state.actionableKeyframe.frame as number;
  693. const currentValue = this.getValueAsArray(animation.dataType, k.value);
  694. currentValue[coordinate] = this.state.actionableKeyframe.value;
  695. k.value = currentValue.length === 1 ? currentValue[0] : currentValue;
  696. }
  697. return k;
  698. });
  699. this.forceFrameZeroToExist(updatedKeys);
  700. this.state.selected.setKeys(updatedKeys);
  701. this.selectAnimation(animation);
  702. this.setCanvasPosition({
  703. frame: this.state.actionableKeyframe.frame as number,
  704. value: this.state.actionableKeyframe.value,
  705. });
  706. }
  707. }
  708. }
  709. }
  710. };
  711. setFlatTangent = () => {
  712. const keyframes = this.state.svgKeyframes?.filter((kf) => kf.selected).map((k) => this.decodeCurveId(k.id));
  713. if (this.state.selected !== null) {
  714. let currentAnimation = this.state.selected;
  715. const keys = currentAnimation.getKeys();
  716. keyframes?.forEach((k) => {
  717. const keyframe = keys[k.order];
  718. keyframe.inTangent = this.returnZero(currentAnimation.dataType);
  719. keyframe.outTangent = this.returnZero(currentAnimation.dataType);
  720. });
  721. currentAnimation.setKeys(keys);
  722. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  723. }
  724. };
  725. setBrokenMode = () => {
  726. if (this.state.selected !== null) {
  727. let animation = this.state.selected;
  728. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () =>
  729. this.selectAnimation(animation, this.state.selectedCoordinate)
  730. );
  731. }
  732. };
  733. setLerpToActiveControlPoint = () => {
  734. const animation = this.state.selected;
  735. if (this.state.svgKeyframes && animation) {
  736. const keys = animation.getKeys();
  737. const selectedControlPoint = this.state.svgKeyframes.find(
  738. (keyframe: IKeyframeSvgPoint) => keyframe.selected && (keyframe.isLeftActive || keyframe.isRightActive)
  739. );
  740. if (selectedControlPoint !== null && selectedControlPoint) {
  741. const { order, coordinate } = this.decodeCurveId(selectedControlPoint.id);
  742. const key = keys[order];
  743. if (selectedControlPoint.isLeftActive && selectedControlPoint.leftControlPoint !== null) {
  744. key.inTangent = undefined;
  745. } else if (selectedControlPoint.isRightActive && selectedControlPoint.rightControlPoint !== null) {
  746. key.outTangent = undefined;
  747. }
  748. this.selectAnimation(animation, coordinate);
  749. }
  750. }
  751. };
  752. addKeyframeClick = () => {
  753. if (this.state.selected !== null) {
  754. let currentAnimation = this.state.selected;
  755. let keys = currentAnimation.getKeys();
  756. let x = this.state.currentFrame;
  757. let existValue = keys.find((k) => k.frame === x);
  758. if (existValue === undefined) {
  759. let y = this.state.actionableKeyframe.value ?? 1;
  760. // check if value exists...
  761. let arrayValue: any = [];
  762. let emptyValue = this.returnZero(currentAnimation.dataType);
  763. if (emptyValue) {
  764. arrayValue = this.getValueAsArray(currentAnimation.dataType, emptyValue);
  765. }
  766. // calculate point between prevkeyframe and nextkeyframe.
  767. const previousKFs = keys.filter((kf) => kf.frame < x);
  768. const nextKFs = keys.filter((kf) => kf.frame > x);
  769. const prev = previousKFs.slice(-1)[0];
  770. const next = nextKFs[0];
  771. if (prev === undefined && next) {
  772. y = next.value;
  773. }
  774. if (prev && next === undefined) {
  775. y = prev.value;
  776. }
  777. if (prev && next) {
  778. const value1 = new Vector2(prev.frame, prev.value);
  779. const tangent1 = new Vector2(prev.outTangent, prev.outTangent);
  780. const value2 = new Vector2(next.frame, next.value);
  781. const tangent2 = new Vector2(next.inTangent, next.inTangent);
  782. const amount = (x - prev.frame) / (next.frame - prev.frame);
  783. const newV = Vector2.Hermite(value1, tangent1, value2, tangent2, amount);
  784. y = newV.y;
  785. }
  786. arrayValue[this.state.selectedCoordinate] = y;
  787. let actualValue = this.setValueAsType(currentAnimation.dataType, arrayValue);
  788. const recentlyCreated = {
  789. frame: x,
  790. value: actualValue,
  791. };
  792. keys.push(recentlyCreated);
  793. keys.sort((a, b) => a.frame - b.frame);
  794. const newIndex = keys.findIndex((kf) => kf.frame === x);
  795. const id = `${currentAnimation.name}_${currentAnimation.targetProperty}_${this.state.selectedCoordinate}`;
  796. const curvedId = this.encodeCurveId(id, newIndex);
  797. this.setState({ lastKeyframeCreated: curvedId });
  798. this.forceFrameZeroToExist(keys);
  799. currentAnimation.setKeys(keys);
  800. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  801. }
  802. }
  803. };
  804. removeKeyframeClick = () => {
  805. if (this.state.selected !== null) {
  806. let currentAnimation = this.state.selected;
  807. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  808. let keys = currentAnimation.getKeys();
  809. let x = this.state.currentFrame;
  810. let filteredKeys = keys.filter((kf) => kf.frame !== x);
  811. currentAnimation.setKeys(filteredKeys);
  812. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  813. }
  814. }
  815. };
  816. removeKeyframes = (points: IKeyframeSvgPoint[]) => {
  817. if (this.state.selected !== null) {
  818. let currentAnimation = this.state.selected;
  819. const indexesToRemove = points.map((p) => {
  820. return {
  821. index: parseInt(p.id.split("_")[3]),
  822. coordinate: parseInt(p.id.split("_")[2]),
  823. };
  824. });
  825. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  826. let keys = currentAnimation.getKeys();
  827. let filteredKeys = keys.filter((_, i) => {
  828. return !indexesToRemove.find((x) => x.index === i);
  829. });
  830. currentAnimation.setKeys(filteredKeys);
  831. this.deselectKeyframes();
  832. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  833. }
  834. }
  835. };
  836. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  837. event.preventDefault();
  838. if (this.state.selected !== null) {
  839. var svg = event.target as SVGSVGElement;
  840. var pt = svg.createSVGPoint();
  841. pt.x = event.clientX;
  842. pt.y = event.clientY;
  843. var inverse = svg.getScreenCTM()?.inverse();
  844. var cursorpt = pt.matrixTransform(inverse);
  845. var currentAnimation = this.state.selected;
  846. var keys = currentAnimation.getKeys();
  847. var height = 100;
  848. var middle = height / 2;
  849. var keyValue;
  850. if (cursorpt.y < middle) {
  851. keyValue = 1 + (100 / cursorpt.y) * 0.1;
  852. }
  853. if (cursorpt.y > middle) {
  854. keyValue = 1 - (100 / cursorpt.y) * 0.1;
  855. }
  856. keys.push({ frame: cursorpt.x, value: keyValue });
  857. currentAnimation.setKeys(keys);
  858. this.selectAnimation(currentAnimation);
  859. }
  860. }
  861. /**
  862. * Curve Rendering Functions
  863. * This section handles how to render curves.
  864. */
  865. setKeyframePointLinear(point: Vector2, index: number) {
  866. // here set the ID to a unique id
  867. let svgKeyframe = {
  868. keyframePoint: point,
  869. rightControlPoint: null,
  870. leftControlPoint: null,
  871. id: index.toString(),
  872. selected: false,
  873. isLeftActive: false,
  874. isRightActive: false,
  875. };
  876. this._svgKeyframes.push(svgKeyframe);
  877. }
  878. flatTangents(keyframes: IAnimationKey[], dataType: number) {
  879. // Checks if Flat Tangent is active (tangents are set to zero)
  880. let flattened;
  881. if (this.state && this.state.isFlatTangentMode) {
  882. flattened = keyframes.map((kf) => {
  883. if (kf.inTangent !== undefined) {
  884. kf.inTangent = this.returnZero(dataType);
  885. }
  886. if (kf.outTangent !== undefined) {
  887. kf.outTangent = this.returnZero(dataType);
  888. }
  889. return kf;
  890. });
  891. } else {
  892. flattened = keyframes;
  893. }
  894. this.setState({ isFlatTangentMode: false });
  895. return flattened;
  896. }
  897. returnZero(dataType: number) {
  898. switch (dataType) {
  899. case Animation.ANIMATIONTYPE_FLOAT:
  900. return 0;
  901. case Animation.ANIMATIONTYPE_VECTOR3:
  902. return Vector3.Zero();
  903. case Animation.ANIMATIONTYPE_VECTOR2:
  904. return Vector2.Zero();
  905. case Animation.ANIMATIONTYPE_QUATERNION:
  906. return Quaternion.Zero();
  907. case Animation.ANIMATIONTYPE_COLOR3:
  908. return new Color3(0, 0, 0);
  909. case Animation.ANIMATIONTYPE_COLOR4:
  910. return new Color4(0, 0, 0, 0);
  911. case Animation.ANIMATIONTYPE_SIZE:
  912. return new Size(0, 0);
  913. default:
  914. return 0;
  915. }
  916. }
  917. getValueAsArray(valueType: number, value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion) {
  918. switch (valueType) {
  919. case Animation.ANIMATIONTYPE_FLOAT:
  920. return [value as number];
  921. case Animation.ANIMATIONTYPE_VECTOR3:
  922. return (value as Vector3).asArray();
  923. case Animation.ANIMATIONTYPE_VECTOR2:
  924. return (value as Vector2).asArray();
  925. case Animation.ANIMATIONTYPE_QUATERNION:
  926. return (value as Quaternion).asArray();
  927. case Animation.ANIMATIONTYPE_COLOR3:
  928. return (value as Color3).asArray();
  929. case Animation.ANIMATIONTYPE_COLOR4:
  930. return (value as Color4).asArray();
  931. case Animation.ANIMATIONTYPE_SIZE:
  932. return [(value as Size).width, (value as Size).height];
  933. default:
  934. return [];
  935. }
  936. }
  937. setValueAsType(valueType: number, arrayValue: number[]) {
  938. switch (valueType) {
  939. case Animation.ANIMATIONTYPE_FLOAT:
  940. return arrayValue[0];
  941. case Animation.ANIMATIONTYPE_VECTOR3:
  942. return new Vector3(arrayValue[0], arrayValue[1], arrayValue[2]);
  943. case Animation.ANIMATIONTYPE_VECTOR2:
  944. return new Vector2(arrayValue[0], arrayValue[1]);
  945. case Animation.ANIMATIONTYPE_QUATERNION:
  946. return new Quaternion(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  947. case Animation.ANIMATIONTYPE_COLOR3:
  948. return new Color3(arrayValue[0], arrayValue[1], arrayValue[2]);
  949. case Animation.ANIMATIONTYPE_COLOR4:
  950. return new Color4(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  951. case Animation.ANIMATIONTYPE_SIZE:
  952. return new Size(arrayValue[0], arrayValue[1]);
  953. default:
  954. return arrayValue[0];
  955. }
  956. }
  957. getPathData(animation: Animation | null) {
  958. if (animation === null) {
  959. return undefined;
  960. }
  961. var keyframes = animation.getKeys();
  962. if (keyframes === undefined || keyframes.length === 0) {
  963. return undefined;
  964. } else {
  965. const {
  966. easingMode,
  967. easingType,
  968. usesTangents,
  969. valueType,
  970. highestFrame,
  971. name,
  972. targetProperty,
  973. } = this.getAnimationData(animation);
  974. //keyframes = this.flatTangents(keyframes, valueType); // This will break because we are using setState before mounted...
  975. const startKey = keyframes[0];
  976. let middle = this._heightScale / this._scaleFactor; //?
  977. let collection: ICurveData[] = [];
  978. const colors = ["red", "green", "blue", "white", "#7a4ece"];
  979. const startValue = this.getValueAsArray(valueType, startKey.value);
  980. for (var d = 0; d < startValue.length; d++) {
  981. const id = `${name}_${targetProperty}_${d}`;
  982. const curveColor = valueType === Animation.ANIMATIONTYPE_FLOAT ? colors[4] : colors[d];
  983. // START OF LINE/CURVE
  984. let data: string | undefined = `M${startKey.frame * this._pixelFrameUnit}, ${
  985. this._heightScale - startValue[d] * middle
  986. }`; //
  987. if (this.state) {
  988. if (usesTangents) {
  989. data = this.curvePathWithTangents(keyframes, data, middle, valueType, d, id);
  990. } else {
  991. if (easingType !== undefined && easingMode !== undefined) {
  992. let easingFunction = animation.getEasingFunction();
  993. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction);
  994. } else {
  995. if (this.state !== undefined) {
  996. data = this.curvePathWithTangents(keyframes, data, middle, valueType, d, id);
  997. }
  998. }
  999. }
  1000. }
  1001. collection.push({
  1002. pathData: data,
  1003. pathLength: highestFrame,
  1004. domCurve: React.createRef(),
  1005. color: curveColor,
  1006. id: id,
  1007. });
  1008. }
  1009. return collection;
  1010. }
  1011. }
  1012. getAnimationData(animation: Animation) {
  1013. // General Props
  1014. let loopMode = animation.loopMode;
  1015. let name = animation.name;
  1016. let blendingSpeed = animation.blendingSpeed;
  1017. let targetProperty = animation.targetProperty;
  1018. let targetPropertyPath = animation.targetPropertyPath;
  1019. let framesPerSecond = animation.framePerSecond;
  1020. let highestFrame = animation.getHighestFrame();
  1021. //let serialized = animation.serialize();
  1022. let usesTangents =
  1023. animation.getKeys().find((kf) => kf.hasOwnProperty("inTangent") || kf.hasOwnProperty("outTangent")) !==
  1024. undefined
  1025. ? true
  1026. : false;
  1027. let valueType = animation.dataType;
  1028. // easing properties
  1029. let easingType, easingMode;
  1030. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  1031. if (easingFunction === undefined) {
  1032. easingType = undefined;
  1033. easingMode = undefined;
  1034. } else {
  1035. easingType = easingFunction.constructor.name;
  1036. easingMode = easingFunction.getEasingMode();
  1037. }
  1038. return {
  1039. loopMode,
  1040. name,
  1041. blendingSpeed,
  1042. targetPropertyPath,
  1043. targetProperty,
  1044. framesPerSecond,
  1045. highestFrame,
  1046. usesTangents,
  1047. easingType,
  1048. easingMode,
  1049. valueType,
  1050. };
  1051. }
  1052. curvePathWithTangents(
  1053. keyframes: IAnimationKey[],
  1054. data: string,
  1055. middle: number,
  1056. type: number,
  1057. coordinate: number,
  1058. animationName: string
  1059. ) {
  1060. keyframes.forEach((key, i) => {
  1061. // Create a unique id for curve
  1062. const curveId = this.encodeCurveId(animationName, i);
  1063. // identify type of value and split...
  1064. const keyframe_valueAsArray = this.getValueAsArray(type, key.value)[coordinate];
  1065. let svgKeyframe;
  1066. let outTangent;
  1067. let inTangent;
  1068. let defaultWeight = this.state.canvasWidthScale / 2; // Get weight depending on prev and next frame distance
  1069. //distanceWithPreviousKeyframe = Vector2.Distance(updatedSvgKeyFrame.keyframePoint, previousKeyframe.keyframePoint) / 4;
  1070. // For inTangent
  1071. // has prev frame?
  1072. let weightIn = 0;
  1073. if (keyframes[i - 1] !== undefined) {
  1074. let prevIn = new Vector2(keyframes[i - 1].frame, keyframes[i - 1].value);
  1075. let currIn = new Vector2(key.frame, key.value);
  1076. weightIn = (Vector2.Distance(prevIn, currIn) / 2) * this._pixelFrameUnit;
  1077. }
  1078. // For outTangent
  1079. // has next frame?
  1080. let weightOut = 0;
  1081. if (keyframes[i + 1] !== undefined) {
  1082. let prevOut = new Vector2(keyframes[i + 1].frame, keyframes[i + 1].value);
  1083. let currOut = new Vector2(key.frame, key.value);
  1084. weightOut = (Vector2.Distance(prevOut, currOut) / 2) * this._pixelFrameUnit;
  1085. }
  1086. if (weightIn !== 0 && weightOut !== 0) {
  1087. if (weightIn < weightOut) {
  1088. defaultWeight = weightIn > defaultWeight ? defaultWeight : weightIn;
  1089. } else {
  1090. defaultWeight = weightOut > defaultWeight ? defaultWeight : weightOut;
  1091. }
  1092. }
  1093. if (weightIn === 0 && weightOut !== 0) {
  1094. defaultWeight = weightOut > defaultWeight ? defaultWeight : weightOut;
  1095. }
  1096. if (weightIn !== 0 && weightOut === 0) {
  1097. defaultWeight = weightIn > defaultWeight ? defaultWeight : weightIn;
  1098. }
  1099. // if curve doesnt have tangents then must be null to have linear
  1100. // right now has 0 then the linear will show a slight curve as flat tangents...
  1101. let defaultTangent: number | null = null;
  1102. if (i !== 0 || i !== keyframes.length - 1) {
  1103. defaultTangent = null;
  1104. }
  1105. var inT =
  1106. key.inTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.inTangent)[coordinate];
  1107. var outT =
  1108. key.outTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.outTangent)[coordinate];
  1109. let y = this._heightScale - keyframe_valueAsArray * middle;
  1110. if (inT !== null) {
  1111. let valueIn = y * inT + y;
  1112. inTangent = new Vector2(key.frame * this._pixelFrameUnit - defaultWeight, valueIn);
  1113. } else {
  1114. inTangent = null;
  1115. }
  1116. if (outT !== null) {
  1117. let valueOut = y * outT + y;
  1118. outTangent = new Vector2(key.frame * this._pixelFrameUnit + defaultWeight, valueOut);
  1119. } else {
  1120. outTangent = null;
  1121. }
  1122. if (i === 0) {
  1123. svgKeyframe = {
  1124. keyframePoint: new Vector2(
  1125. key.frame * this._pixelFrameUnit,
  1126. this._heightScale - keyframe_valueAsArray * middle
  1127. ),
  1128. rightControlPoint: outTangent,
  1129. leftControlPoint: null,
  1130. id: curveId,
  1131. selected: false,
  1132. isLeftActive: false,
  1133. isRightActive: false,
  1134. };
  1135. if (outTangent !== null) {
  1136. data += ` C${outTangent.x} ${outTangent.y} `;
  1137. } else {
  1138. data += ` C${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `;
  1139. }
  1140. } else {
  1141. svgKeyframe = {
  1142. keyframePoint: new Vector2(
  1143. key.frame * this._pixelFrameUnit,
  1144. this._heightScale - keyframe_valueAsArray * middle
  1145. ),
  1146. rightControlPoint: outTangent,
  1147. leftControlPoint: inTangent,
  1148. id: curveId,
  1149. selected: false,
  1150. isLeftActive: false,
  1151. isRightActive: false,
  1152. };
  1153. if (outTangent !== null && inTangent !== null) {
  1154. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y}`;
  1155. }
  1156. if (outTangent === null && inTangent !== null) {
  1157. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y}`;
  1158. }
  1159. if (inTangent === null && outTangent !== null) {
  1160. const prev = this._svgKeyframes[i - 1];
  1161. data += ` ${prev.keyframePoint.x} ${prev.keyframePoint.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y}`;
  1162. }
  1163. if (inTangent === null && outTangent === null) {
  1164. const prev = this._svgKeyframes[i - 1];
  1165. data += ` ${prev.keyframePoint.x} ${prev.keyframePoint.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y}`;
  1166. }
  1167. }
  1168. if (this.state) {
  1169. let prev = this.state.svgKeyframes?.find((kf) => kf.id === curveId);
  1170. if (prev) {
  1171. svgKeyframe.isLeftActive = prev?.isLeftActive;
  1172. svgKeyframe.isRightActive = prev?.isRightActive;
  1173. svgKeyframe.selected = prev?.selected;
  1174. }
  1175. }
  1176. this._svgKeyframes.push(svgKeyframe);
  1177. }, this);
  1178. const lastCurveEnd = data.lastIndexOf("C");
  1179. const cleanedData = data.substring(0, lastCurveEnd);
  1180. return cleanedData;
  1181. }
  1182. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  1183. // This will get 1/4 and 3/4 of points in eased curve
  1184. const u = 0.25;
  1185. const v = 0.75;
  1186. keyframes.forEach((key, i) => {
  1187. // identify type of value and split...
  1188. // Gets previous initial point of curve segment
  1189. var pointA = new Vector2(0, 0);
  1190. if (i === 0) {
  1191. pointA.x = key.frame;
  1192. pointA.y = this._heightScale - key.value * middle;
  1193. this.setKeyframePoint([pointA], i, keyframes.length);
  1194. } else {
  1195. pointA.x = keyframes[i - 1].frame;
  1196. pointA.y = this._heightScale - keyframes[i - 1].value * middle;
  1197. // Gets the end point of this curve segment
  1198. var pointB = new Vector2(key.frame, this._heightScale - key.value * middle);
  1199. // Get easing value of percentage to get the bezier control points below
  1200. 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)
  1201. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  1202. // Direction of curve up/down
  1203. let yInt25 = 0;
  1204. if (pointB.y > pointA.y) {
  1205. // if pointB.y > pointA.y = goes down
  1206. yInt25 = (pointB.y - pointA.y) * du + pointA.y;
  1207. } else if (pointB.y < pointA.y) {
  1208. // if pointB.y < pointA.y = goes up
  1209. yInt25 = pointA.y - (pointA.y - pointB.y) * du;
  1210. }
  1211. let yInt75 = 0;
  1212. if (pointB.y > pointA.y) {
  1213. yInt75 = (pointB.y - pointA.y) * dv + pointA.y;
  1214. } else if (pointB.y < pointA.y) {
  1215. yInt75 = pointA.y - (pointA.y - pointB.y) * dv;
  1216. }
  1217. // Intermediate points in curve
  1218. let intermediatePoint25 = new Vector2((pointB.x - pointA.x) * u + pointA.x, yInt25);
  1219. let intermediatePoint75 = new Vector2((pointB.x - pointA.x) * v + pointA.x, yInt75);
  1220. // Gets the four control points of bezier curve
  1221. let controlPoints = this.interpolateControlPoints(
  1222. pointA,
  1223. intermediatePoint25,
  1224. u,
  1225. intermediatePoint75,
  1226. v,
  1227. pointB
  1228. );
  1229. if (controlPoints !== undefined) {
  1230. this.setKeyframePoint(controlPoints, i, keyframes.length);
  1231. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`;
  1232. }
  1233. }
  1234. });
  1235. return data;
  1236. }
  1237. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  1238. let svgKeyframe;
  1239. if (index === 0) {
  1240. svgKeyframe = {
  1241. keyframePoint: controlPoints[0],
  1242. rightControlPoint: null,
  1243. leftControlPoint: null,
  1244. id: index.toString(),
  1245. selected: false,
  1246. isLeftActive: false,
  1247. isRightActive: false,
  1248. };
  1249. } else {
  1250. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  1251. svgKeyframe = {
  1252. keyframePoint: controlPoints[3],
  1253. rightControlPoint: null,
  1254. leftControlPoint: controlPoints[2],
  1255. id: index.toString(),
  1256. selected: false,
  1257. isLeftActive: false,
  1258. isRightActive: false,
  1259. };
  1260. }
  1261. this._svgKeyframes.push(svgKeyframe);
  1262. }
  1263. interpolateControlPoints(
  1264. p0: Vector2,
  1265. p1: Vector2,
  1266. u: number,
  1267. p2: Vector2,
  1268. v: number,
  1269. p3: Vector2
  1270. ): Vector2[] | undefined {
  1271. let a = 0.0;
  1272. let b = 0.0;
  1273. let c = 0.0;
  1274. let d = 0.0;
  1275. let det = 0.0;
  1276. let q1: Vector2 = new Vector2();
  1277. let q2: Vector2 = new Vector2();
  1278. let controlA: Vector2 = p0;
  1279. let controlB: Vector2 = new Vector2();
  1280. let controlC: Vector2 = new Vector2();
  1281. let controlD: Vector2 = p3;
  1282. if (u <= 0.0 || u >= 1.0 || v <= 0.0 || v >= 1.0 || u >= v) {
  1283. return undefined;
  1284. }
  1285. a = 3 * (1 - u) * (1 - u) * u;
  1286. b = 3 * (1 - u) * u * u;
  1287. c = 3 * (1 - v) * (1 - v) * v;
  1288. d = 3 * (1 - v) * v * v;
  1289. det = a * d - b * c;
  1290. if (det == 0.0) return undefined;
  1291. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  1292. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  1293. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  1294. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  1295. controlB.x = (d * q1.x - b * q2.x) / det;
  1296. controlB.y = (d * q1.y - b * q2.y) / det;
  1297. controlC.x = (-c * q1.x + a * q2.x) / det;
  1298. controlC.y = (-c * q1.y + a * q2.y) / det;
  1299. return [controlA, controlB, controlC, controlD];
  1300. }
  1301. deselectAnimation = () => {
  1302. const animations = (this.props.entity as IAnimatable).animations;
  1303. if (animations && animations.length === 0) {
  1304. setTimeout(() => this.cleanCanvas(), 0);
  1305. }
  1306. this.cleanCanvas();
  1307. };
  1308. cleanCanvas = () => {
  1309. this.setState({
  1310. selected: null,
  1311. svgKeyframes: [],
  1312. selectedPathData: undefined,
  1313. selectedCoordinate: 0,
  1314. });
  1315. };
  1316. /**
  1317. * Core functions
  1318. * This section handles main Curve Editor Functions.
  1319. */
  1320. selectAnimation = (animation: Animation, coordinate?: SelectedCoordinate) => {
  1321. this._svgKeyframes = [];
  1322. let updatedPath;
  1323. let filteredSvgKeys;
  1324. let selectedCurve = 0;
  1325. this.stopAnimation();
  1326. if (coordinate === undefined) {
  1327. updatedPath = this.getPathData(animation);
  1328. } else {
  1329. let curves = this.getPathData(animation);
  1330. updatedPath = [];
  1331. filteredSvgKeys = this._svgKeyframes?.filter((curve) => {
  1332. let id = parseInt(curve.id.split("_")[2]);
  1333. if (id === coordinate) {
  1334. return true;
  1335. } else {
  1336. return false;
  1337. }
  1338. });
  1339. curves?.map((curve) => {
  1340. let id = parseInt(curve.id.split("_")[2]);
  1341. if (id === coordinate) {
  1342. updatedPath.push(curve);
  1343. }
  1344. });
  1345. selectedCurve = coordinate;
  1346. }
  1347. // check for empty svgKeyframes, lastframe, selected
  1348. this.setState(
  1349. {
  1350. selected: animation,
  1351. svgKeyframes: coordinate !== undefined ? filteredSvgKeys : this._svgKeyframes,
  1352. selectedPathData: updatedPath,
  1353. selectedCoordinate: selectedCurve,
  1354. fps: animation.framePerSecond,
  1355. },
  1356. this.postSelectionEvents
  1357. );
  1358. };
  1359. postSelectionEvents = () => {
  1360. if (this.state.lastKeyframeCreated !== null) {
  1361. this.deselectKeyframes();
  1362. this.selectKeyframe(this.state.lastKeyframeCreated, false);
  1363. this.setState({ lastKeyframeCreated: null });
  1364. }
  1365. this.setMainAnimatable();
  1366. if (this.state.selected) {
  1367. const lastKeyframe = this.state.selected.getHighestFrame();
  1368. const currentLimit = this.state.animationLimit;
  1369. if (currentLimit < lastKeyframe) {
  1370. this.changeAnimationLimit(lastKeyframe);
  1371. }
  1372. }
  1373. };
  1374. setMainAnimatable() {
  1375. if (this.state.selected !== null) {
  1376. let target = this.props.entity;
  1377. if (this.props.entity instanceof TargetedAnimation) {
  1378. target = this.props.entity.target;
  1379. }
  1380. this.props.scene.stopAllAnimations();
  1381. if (this._mainAnimatable?.target !== target) {
  1382. const keys = this.state.selected.getKeys();
  1383. if (keys.length !== 0) {
  1384. const firstFrame = keys[0].frame;
  1385. const LastFrame = this.state.selected.getHighestFrame();
  1386. this._mainAnimatable = this.props.scene.beginAnimation(
  1387. target,
  1388. firstFrame,
  1389. LastFrame,
  1390. this.state.isLooping
  1391. );
  1392. this._mainAnimatable.stop();
  1393. }
  1394. }
  1395. }
  1396. }
  1397. isAnimationPlaying() {
  1398. let target = this.props.entity;
  1399. if (this.props.entity instanceof TargetedAnimation) {
  1400. target = this.props.entity.target;
  1401. }
  1402. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1403. }
  1404. stopAnimation() {
  1405. let target = this.props.entity;
  1406. if (this.props.entity instanceof TargetedAnimation) {
  1407. target = this.props.entity.target;
  1408. }
  1409. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1410. if (this._isPlaying) {
  1411. this.props.playOrPause && this.props.playOrPause();
  1412. if (this.state !== undefined) {
  1413. this.setState({ isPlaying: false });
  1414. }
  1415. this._isPlaying = false;
  1416. }
  1417. }
  1418. setIsLooping = () => {
  1419. this.setState({ isLooping: !this.state.isLooping, isPlaying: false }, () => this.stopAnimation());
  1420. };
  1421. setFramesPerSecond = (fps: number) => {
  1422. this.setState({ fps: fps, isPlaying: false }, () => this.stopAnimation());
  1423. };
  1424. analizeAnimationForLerp(animation: Animation | null) {
  1425. if (animation !== null) {
  1426. const { easingMode, easingType, usesTangents } = this.getAnimationData(animation);
  1427. if (easingType === undefined && easingMode === undefined && !usesTangents) {
  1428. return true;
  1429. } else {
  1430. return false;
  1431. }
  1432. } else {
  1433. return false;
  1434. }
  1435. }
  1436. /**
  1437. * Timeline
  1438. * This section controls the timeline.
  1439. */
  1440. changeCurrentFrame = (frame: number) => {
  1441. this.stopAnimation();
  1442. const currentValue = this.calculateCurrentPointInCurve(frame);
  1443. const value = currentValue ?? 0;
  1444. const keyframe: IAnimationKey = { frame, value };
  1445. this.setState(
  1446. {
  1447. currentFrame: frame,
  1448. isPlaying: false,
  1449. },
  1450. () => {
  1451. if (this.state.selected) {
  1452. const index = this.state.selected.getKeys().findIndex((x) => x.frame === keyframe.frame);
  1453. const animationName = `${this.state.selected.name}_${this.state.selected.targetProperty}_${this.state.selectedCoordinate}`;
  1454. const id = this.encodeCurveId(animationName, index);
  1455. this.selectKeyframeFromId(id, keyframe);
  1456. }
  1457. this.setCanvasPosition(keyframe);
  1458. }
  1459. );
  1460. };
  1461. calculateCurrentPointInCurve = (frame: number): number | undefined => {
  1462. if (
  1463. this.state.selectedPathData !== undefined &&
  1464. this.state.selectedPathData[this.state.selectedCoordinate] !== undefined
  1465. ) {
  1466. const selectedCurve = this.state.selectedPathData[this.state.selectedCoordinate].domCurve.current;
  1467. if (selectedCurve !== null) {
  1468. const curveLength = selectedCurve.getTotalLength();
  1469. const frameValue = (frame * curveLength) / 100;
  1470. const currentPointInCurve = selectedCurve.getPointAtLength(frameValue);
  1471. const middle = this._heightScale / 2;
  1472. const offset =
  1473. (currentPointInCurve?.y * this._heightScale - this._heightScale ** 2 / 2) /
  1474. middle /
  1475. this._heightScale;
  1476. const unit = Math.sign(offset);
  1477. const currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  1478. this.setState({
  1479. currentValue: currentValue,
  1480. currentPoint: currentPointInCurve,
  1481. });
  1482. return currentValue;
  1483. }
  1484. }
  1485. return undefined;
  1486. };
  1487. setCanvasPosition = (keyframe: IAnimationKey) => {
  1488. if (this.state.selected) {
  1489. const positionX = (keyframe.frame - this._pixelFrameUnit) * this._pixelFrameUnit;
  1490. let value = 0;
  1491. if (keyframe.value === null) {
  1492. value = this.state.panningY;
  1493. } else {
  1494. value = this.getValueAsArray(this.state.selected.dataType, keyframe.value)[
  1495. this.state.selectedCoordinate
  1496. ];
  1497. }
  1498. const valueScale = this._heightScale / this._scaleFactor;
  1499. const positionY = value === 0 ? 0 : valueScale - value * valueScale;
  1500. this.setState({ panningX: positionX, panningY: positionY, repositionCanvas: true });
  1501. }
  1502. };
  1503. setCurrentFrame = (direction: number) => {
  1504. this.setState({
  1505. currentFrame: this.state.currentFrame + direction,
  1506. });
  1507. };
  1508. changeAnimationLimit = (limit: number) => {
  1509. this.stopAnimation();
  1510. const doubleLimit = limit * 2;
  1511. this.setState({
  1512. animationLimit: limit,
  1513. canvasLength: doubleLimit,
  1514. frameAxisLength: this.setFrameAxis(doubleLimit),
  1515. });
  1516. };
  1517. updateFrameInKeyFrame = (frame: number, index: number) => {
  1518. if (this.state && this.state.selected) {
  1519. let animation = this.state.selected;
  1520. let keys = [...animation.getKeys()];
  1521. keys[index].frame = frame;
  1522. animation.setKeys(keys);
  1523. this.selectAnimation(animation);
  1524. }
  1525. };
  1526. playPause = (direction: number) => {
  1527. this.registerObs();
  1528. if (this.state.selected) {
  1529. let target = this.props.entity;
  1530. if (this.props.entity instanceof TargetedAnimation) {
  1531. target = this.props.entity.target;
  1532. }
  1533. if (this.state.isPlaying && direction === 0) {
  1534. this.props.scene.stopAnimation(target);
  1535. this.setState({ isPlaying: false });
  1536. this._isPlaying = false;
  1537. this.forceUpdate();
  1538. } else {
  1539. if (this.state.isPlaying) {
  1540. this.props.scene.stopAnimation(target);
  1541. }
  1542. this.props.scene.stopAllAnimations();
  1543. let keys = this.state.selected.getKeys();
  1544. if (keys.length !== 0) {
  1545. let firstFrame = keys[0].frame;
  1546. let LastFrame = this.state.selected.getHighestFrame();
  1547. if (direction === 1) {
  1548. this._mainAnimatable = this.props.scene.beginAnimation(
  1549. target,
  1550. firstFrame,
  1551. LastFrame,
  1552. this.state.isLooping
  1553. );
  1554. }
  1555. if (direction === -1) {
  1556. this._mainAnimatable = this.props.scene.beginAnimation(
  1557. target,
  1558. LastFrame,
  1559. firstFrame,
  1560. this.state.isLooping
  1561. );
  1562. }
  1563. if (!this.state.isLooping && this._mainAnimatable) {
  1564. this._mainAnimatable.onAnimationEnd = () => this.playPause(0);
  1565. }
  1566. }
  1567. const zeroFrames = keys.filter((x) => x.frame === 0);
  1568. if (zeroFrames.length > 1) {
  1569. keys.shift();
  1570. }
  1571. keys.sort((a, b) => a.frame - b.frame);
  1572. this._isPlaying = true;
  1573. this.setState({ isPlaying: true });
  1574. this.forceUpdate();
  1575. }
  1576. }
  1577. };
  1578. moveFrameTo(e: React.MouseEvent<SVGRectElement, MouseEvent>) {
  1579. this.stopAnimation();
  1580. var svg = e.currentTarget as SVGRectElement;
  1581. var CTM = svg.getScreenCTM();
  1582. let position;
  1583. if (CTM) {
  1584. position = new Vector2((e.clientX - CTM.e) / CTM.a, (e.clientY - CTM.f) / CTM.d);
  1585. let selectedFrame = Math.round(position.x / this._pixelFrameUnit);
  1586. this.setState({ currentFrame: selectedFrame, isPlaying: false }, () => {
  1587. if (this.state.selected) {
  1588. const index = this.state.selected.getKeys().findIndex((x) => x.frame === selectedFrame);
  1589. const keyframe = this.state.selected.getKeys().find((x) => x.frame === selectedFrame);
  1590. if (index !== undefined && keyframe !== undefined) {
  1591. const animationName = `${this.state.selected.name}_${this.state.selected.targetProperty}_${this.state.selectedCoordinate}`;
  1592. const id = this.encodeCurveId(animationName, index);
  1593. this.selectKeyframeFromId(id, keyframe);
  1594. this.setCanvasPosition(keyframe);
  1595. }
  1596. }
  1597. });
  1598. }
  1599. }
  1600. registerObs() {
  1601. if (this._onBeforeRenderObserver) {
  1602. this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  1603. this._onBeforeRenderObserver = null;
  1604. }
  1605. this._onBeforeRenderObserver = this.props.scene.onBeforeRenderObservable.add(() => {
  1606. if (!this._isPlaying || !this._mainAnimatable) {
  1607. return;
  1608. }
  1609. this.setState({
  1610. currentFrame: Math.round(this._mainAnimatable.masterFrame),
  1611. });
  1612. });
  1613. }
  1614. componentWillUnmount() {
  1615. this.playPause(0);
  1616. if (this._onBeforeRenderObserver) {
  1617. this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  1618. this._onBeforeRenderObserver = null;
  1619. }
  1620. }
  1621. isCurrentFrame(frame: number) {
  1622. return this.state.currentFrame === frame;
  1623. }
  1624. setPanningY = (panningY: number) => {
  1625. this.setState({ panningY });
  1626. };
  1627. setPanningX = (panningX: number) => {
  1628. this.setState({ panningX });
  1629. };
  1630. canvasPositionEnded = () => {
  1631. this.setState({ repositionCanvas: false });
  1632. };
  1633. setNotificationMessage = (message: string) => {
  1634. this.setState({ notification: message });
  1635. };
  1636. frameSelectedKeyframes = () => {
  1637. // get selected keyframes
  1638. // get adjacent keyframes
  1639. // found canvas boundaries
  1640. // zoom to fit
  1641. // if not selected keyframes
  1642. // remove zoom
  1643. };
  1644. render() {
  1645. return (
  1646. <div ref={this._editor} id="animation-curve-editor">
  1647. <Notification
  1648. message={this.state.notification}
  1649. open={this.state.notification !== "" ? true : false}
  1650. close={this.clearNotification}
  1651. />
  1652. <GraphActionsBar
  1653. setKeyframeValue={this.setKeyframeValueFromInput}
  1654. enabled={this.state.selected === null || this.state.selected === undefined ? false : true}
  1655. title={this._entityName}
  1656. actionableKeyframe={this.state.actionableKeyframe}
  1657. handleFrameChange={this.handleFrameChange}
  1658. handleValueChange={this.handleValueChange}
  1659. addKeyframe={this.addKeyframeClick}
  1660. removeKeyframe={this.removeKeyframeClick}
  1661. frameSelectedKeyframes={this.frameSelectedKeyframes}
  1662. brokenMode={this.state.isBrokenMode}
  1663. brokeTangents={this.setBrokenMode}
  1664. lerpMode={this.state.lerpMode}
  1665. setLerpToActiveControlPoint={this.setLerpToActiveControlPoint}
  1666. flatTangent={this.setFlatTangent}
  1667. />
  1668. <div className="content">
  1669. <div className="row">
  1670. <EditorControls
  1671. deselectAnimation={this.deselectAnimation}
  1672. selectAnimation={this.selectAnimation}
  1673. isTargetedAnimation={this._isTargetedAnimation}
  1674. entity={this.props.entity}
  1675. selected={this.state.selected}
  1676. lockObject={this.props.lockObject}
  1677. setNotificationMessage={this.setNotificationMessage}
  1678. globalState={this.props.globalState}
  1679. snippetServer={this._snippetUrl}
  1680. fps={this.state.fps}
  1681. setFps={this.setFramesPerSecond}
  1682. setIsLooping={this.setIsLooping}
  1683. />
  1684. <div ref={this._graphCanvas} className="graph-chart" onWheel={this.zoom}>
  1685. {this.state.svgKeyframes && (
  1686. <SvgDraggableArea
  1687. ref={this._svgCanvas}
  1688. viewBoxScale={this.state.frameAxisLength.length}
  1689. scale={this.state.scale}
  1690. removeSelectedKeyframes={this.removeKeyframes}
  1691. deselectKeyframes={this.deselectKeyframes}
  1692. updatePosition={this.renderPoints}
  1693. panningY={this.setPanningY}
  1694. panningX={this.setPanningX}
  1695. setCurrentFrame={this.setCurrentFrame}
  1696. positionCanvas={new Vector2(this.state.panningX, this.state.panningY)}
  1697. repositionCanvas={this.state.repositionCanvas}
  1698. canvasPositionEnded={this.canvasPositionEnded}
  1699. keyframeSvgPoints={this.state.svgKeyframes}
  1700. resetActionableKeyframe={this.resetActionableKeyframe}>
  1701. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1702. return (
  1703. <text
  1704. key={`value_inline_${i}`}
  1705. x={this.state.panningX - 5}
  1706. y={line.value}
  1707. dx="2"
  1708. textAnchor="middle"
  1709. dy="-1"
  1710. style={{
  1711. fontSize: `${0.18 * this.state.scale}em`,
  1712. fontWeight: "bold",
  1713. textAlign: "center",
  1714. }}>
  1715. {line.label}
  1716. </text>
  1717. );
  1718. })}
  1719. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1720. return (
  1721. <line
  1722. key={i}
  1723. x1={-((this.state.frameAxisLength.length * 10) / 2)}
  1724. y1={line.value}
  1725. x2={this.state.frameAxisLength.length * 10}
  1726. y2={line.value}></line>
  1727. );
  1728. })}
  1729. {/* Multiple Curves */}
  1730. {this.state.selectedPathData?.map((curve, i) => (
  1731. <path
  1732. key={i}
  1733. ref={curve.domCurve}
  1734. pathLength={curve.pathLength}
  1735. id="curve"
  1736. d={curve.pathData}
  1737. style={{
  1738. stroke: curve.color,
  1739. fill: "none",
  1740. strokeWidth: "0.5",
  1741. }}></path>
  1742. ))}
  1743. {this.state.svgKeyframes.map((keyframe, i) => (
  1744. <KeyframeSvgPoint
  1745. key={`${keyframe.id}_${i}`}
  1746. id={keyframe.id}
  1747. keyframePoint={keyframe.keyframePoint}
  1748. leftControlPoint={keyframe.leftControlPoint}
  1749. rightControlPoint={keyframe.rightControlPoint}
  1750. isLeftActive={keyframe.isLeftActive}
  1751. isRightActive={keyframe.isRightActive}
  1752. selected={keyframe.selected}
  1753. selectedControlPoint={this.selectedControlPoint}
  1754. selectKeyframe={this.selectKeyframe}
  1755. />
  1756. ))}
  1757. <rect
  1758. onClick={(e) => this.moveFrameTo(e)}
  1759. x={-((this.state.frameAxisLength.length * 10) / 2)}
  1760. y={91 + this.state.panningY + "%"}
  1761. width={this.state.frameAxisLength.length * 10}
  1762. height="9%"
  1763. fill="#222"
  1764. style={{ cursor: "pointer" }}></rect>
  1765. {this.state.frameAxisLength.map((f, i) => (
  1766. <svg key={i} x="0" y={96 + this.state.panningY + "%"} className="frame-contain">
  1767. <text
  1768. x={f.value}
  1769. y="1px"
  1770. dx="2px"
  1771. style={{ fontSize: `${0.2 * this.state.scale}em` }}>
  1772. {f.label}
  1773. </text>
  1774. <line x1={f.value} y1="0" x2={f.value} y2="5%"></line>
  1775. {f.value % this.state.fps === 0 && f.value !== 0 ? (
  1776. <line
  1777. x1={f.value * this._pixelFrameUnit}
  1778. y1="-100%"
  1779. x2={f.value * this._pixelFrameUnit}
  1780. y2="5%"></line>
  1781. ) : null}
  1782. {this.state.selected && this.isCurrentFrame(f.label) ? (
  1783. <svg>
  1784. <line
  1785. x1={f.value}
  1786. y1="0"
  1787. x2={f.value}
  1788. y2="-100%"
  1789. style={{
  1790. stroke: "#a4a4a4",
  1791. strokeWidth: 0.4,
  1792. }}
  1793. />
  1794. <svg x={f.value} y="-1">
  1795. <circle
  1796. className="svg-playhead"
  1797. cx="0"
  1798. cy="0"
  1799. r="2%"
  1800. fill="white"
  1801. />
  1802. <text
  1803. x="0"
  1804. y="1%"
  1805. textAnchor="middle"
  1806. style={{
  1807. fontSize: `${0.17 * this.state.scale}em`,
  1808. pointerEvents: "none",
  1809. fontWeight: 600,
  1810. }}>
  1811. {f.label}
  1812. </text>
  1813. </svg>
  1814. </svg>
  1815. ) : null}
  1816. </svg>
  1817. ))}
  1818. </SvgDraggableArea>
  1819. )}
  1820. <div
  1821. style={{
  1822. width: 30,
  1823. height: "inherit",
  1824. position: "absolute",
  1825. zIndex: 1,
  1826. pointerEvents: "none",
  1827. backgroundColor: "rgb(188 188 188 / 11%)",
  1828. top: 40,
  1829. }}></div>
  1830. <ScaleLabel current={this.state.valueScale} />
  1831. </div>
  1832. </div>
  1833. <div className="row-bottom">
  1834. <Timeline
  1835. currentFrame={this.state.currentFrame}
  1836. playPause={this.playPause}
  1837. isPlaying={this.state.isPlaying}
  1838. dragKeyframe={this.updateFrameInKeyFrame}
  1839. onCurrentFrameChange={this.changeCurrentFrame}
  1840. onAnimationLimitChange={this.changeAnimationLimit}
  1841. animationLimit={this.state.animationLimit}
  1842. keyframes={this.state.selected && this.state.selected.getKeys()}
  1843. selected={this.state.selected && this.state.selected.getKeys()[0]}
  1844. fps={this.state.fps}
  1845. repositionCanvas={this.setCanvasPosition}></Timeline>
  1846. </div>
  1847. </div>
  1848. </div>
  1849. );
  1850. }
  1851. }