animationCurveEditorComponent.tsx 69 KB

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