animationCurveEditorComponent.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import * as React from "react";
  2. import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
  3. import { faTimes, faPlusCircle } from "@fortawesome/free-solid-svg-icons";
  4. import { Animation } from 'babylonjs/Animations/animation';
  5. import { Vector2 } from 'babylonjs/Maths/math.vector';
  6. import { EasingFunction, BezierCurveEase } from 'babylonjs/Animations/easing';
  7. import { IAnimationKey } from 'babylonjs/Animations/animationKey';
  8. import { IKeyframeSvgPoint } from './keyframeSvgPoint';
  9. import { SvgDraggableArea } from './svgDraggableArea';
  10. import { Scene } from "babylonjs/scene";
  11. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  12. require("./curveEditor.scss");
  13. interface IAnimationCurveEditorComponentProps {
  14. close: (event: any) => void;
  15. title: string;
  16. animations: Animation[];
  17. entityName: string;
  18. scene: Scene;
  19. entity: IAnimatable;
  20. }
  21. export class AnimationCurveEditorComponent extends React.Component<IAnimationCurveEditorComponentProps, { animations: Animation[], animationName: string, animationTargetProperty:string, isOpen: boolean, selected: Animation, currentPathData: string | undefined, svgKeyframes: IKeyframeSvgPoint[] | undefined }> {
  22. readonly _heightScale: number = 100;
  23. private _newAnimations: Animation[] = [];
  24. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  25. private _frames: Vector2[] = [];
  26. constructor(props: IAnimationCurveEditorComponentProps) {
  27. super(props);
  28. this.state = { animations: this._newAnimations,selected: this.props.animations[0], isOpen: true, currentPathData: this.getPathData(this.props.animations[0]), svgKeyframes: this._svgKeyframes, animationTargetProperty: 'position.x', animationName: "" }
  29. }
  30. handleNameChange(event: React.ChangeEvent<HTMLInputElement>){
  31. event.preventDefault();
  32. this.setState({animationName: event.target.value});
  33. }
  34. handlePropertyChange(event: React.ChangeEvent<HTMLInputElement>){
  35. event.preventDefault();
  36. this.setState({animationTargetProperty: event.target.value});
  37. }
  38. addAnimation(event: React.MouseEvent<HTMLDivElement>){
  39. event.preventDefault();
  40. if (this.state.animationName != "" && this.state.animationTargetProperty != ""){
  41. let animation = new Animation(this.state.animationName, this.state.animationTargetProperty, 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);
  42. var keys = []; 
  43.   keys.push({
  44.     frame: 0,
  45.     value: 1
  46.   });
  47.   keys.push({
  48. frame: 100,
  49. value: 1
  50. });
  51. animation.setKeys(keys);
  52. var bezierEase = new BezierCurveEase(10,0,10,0);
  53. bezierEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
  54. animation.setEasingFunction((bezierEase as unknown) as EasingFunction);
  55. // Need to redefine/refactor not to update the prop collection
  56. (this.props.entity as IAnimatable).animations?.push(animation);
  57. }
  58. }
  59. addKeyFrame(event: React.MouseEvent<SVGSVGElement>){
  60. event.preventDefault();
  61. if (event.button === 2){
  62. var svg = event.target as SVGSVGElement;
  63. var pt = svg.createSVGPoint();
  64. pt.x = event.clientX;
  65. pt.y = event.clientY;
  66. var inverse = svg.getScreenCTM()?.inverse();
  67. var cursorpt = pt.matrixTransform(inverse);
  68. var currentAnimation = this.state.selected;
  69. var keys = currentAnimation.getKeys();
  70. var height = 100;
  71. var middle = (height / 2);
  72. var keyValue;
  73. if (cursorpt.y < middle){
  74. keyValue = 1 + ((100/cursorpt.y) * .1)
  75. }
  76. if (cursorpt.y > middle){
  77. keyValue = 1 - ((100/cursorpt.y) * .1)
  78. }
  79. keys.push({ frame: cursorpt.x, value: keyValue });
  80. currentAnimation.setKeys(keys);
  81. this.selectAnimation(currentAnimation);
  82. }
  83. }
  84. updateKeyframe(keyframe: Vector2, index: number){
  85. let anim = this.state.selected as Animation;
  86. var keys: IAnimationKey[] = [];
  87. var svgKeyframes = this.state.svgKeyframes?.map((k, i) => {
  88. if (i === index){
  89. k.keyframePoint.x = keyframe.x;
  90. k.keyframePoint.y = keyframe.y;
  91. }
  92. var height = 100;
  93. var middle = (height / 2);
  94. var keyValue;
  95. if (k.keyframePoint.y < middle){
  96. keyValue = 1 + ((100/k.keyframePoint.y) * .1)
  97. }
  98. if (k.keyframePoint.y > middle){
  99. keyValue = 1 - ((100/k.keyframePoint.y) * .1)
  100. }
  101. keys.push({frame: k.keyframePoint.x, value: keyValue})
  102. return k;
  103. });
  104. anim.setKeys(keys);
  105. this.setState({ svgKeyframes: svgKeyframes})
  106. }
  107. getAnimationProperties(animation: Animation) {
  108. let easingType, easingMode;
  109. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  110. if (easingFunction === undefined){
  111. easingType = undefined
  112. easingMode = undefined;
  113. } else {
  114. easingType = easingFunction.constructor.name;
  115. easingMode = easingFunction.getEasingMode();
  116. }
  117. return { easingType, easingMode }
  118. }
  119. getPathData(animation: Animation) {
  120. const { easingMode, easingType } = this.getAnimationProperties(animation);
  121. const keyframes = animation.getKeys();
  122. if (keyframes === undefined) {
  123. return "";
  124. }
  125. const startKey = keyframes[0];
  126. // This assumes the startkey is always 0... beed to change this
  127. let middle = this._heightScale/2;
  128. // START OF LINE/CURVE
  129. let data: string | undefined = `M${startKey.frame}, ${this._heightScale - (startKey.value * middle)}`;
  130. if (easingType === undefined && easingMode === undefined){
  131. data = this.linearInterpolation(keyframes, data, middle);
  132. } else {
  133. let easingFunction = animation.getEasingFunction();
  134. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction)
  135. }
  136. return data;
  137. }
  138. drawAllFrames(initialKey: IAnimationKey,endKey: IAnimationKey, easingFunction: EasingFunction) {
  139. let i = initialKey.frame;
  140. for (i; i < endKey.frame; i++){
  141. (i * 100/ endKey.frame)
  142. let dy = easingFunction.easeInCore(i);
  143. let value = this._heightScale - (dy * (this._heightScale/2));
  144. this. _frames.push(new Vector2(i,value));
  145. }
  146. }
  147. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  148. // This will get 1/4 and 3/4 of points in eased curve
  149. const u = .25;
  150. const v = .75;
  151. keyframes.forEach((key, i) => {
  152. // Gets previous initial point of curve segment
  153. var pointA = new Vector2(0, 0);
  154. if (i === 0) {
  155. pointA.x = key.frame;
  156. pointA.y = this._heightScale - (key.value * middle);
  157. this.setKeyframePoint([pointA], i, keyframes.length);
  158. } else {
  159. pointA.x = keyframes[i - 1].frame;
  160. pointA.y = this._heightScale - (keyframes[i - 1].value * middle)
  161. // Gets the end point of this curve segment
  162. var pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  163. // Get easing value of percentage to get the bezier control points below
  164. 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)
  165. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  166. // Direction of curve up/down
  167. let yInt25 = 0;
  168. if (pointB.y > pointA.y) { // if pointB.y > pointA.y = goes down
  169. yInt25 = ((pointB.y - pointA.y) * du) + pointA.y
  170. } else if (pointB.y < pointA.y) { // if pointB.y < pointA.y = goes up
  171. yInt25 = pointA.y - ((pointA.y - pointB.y) * du);
  172. }
  173. let yInt75 = 0;
  174. if (pointB.y > pointA.y) {
  175. yInt75 = ((pointB.y - pointA.y) * dv) + pointA.y
  176. } else if (pointB.y < pointA.y) {
  177. yInt75 = pointA.y - ((pointA.y - pointB.y) * dv)
  178. }
  179. // Intermediate points in curve
  180. let intermediatePoint25 = new Vector2(((pointB.x - pointA.x) * u) + pointA.x, yInt25);
  181. let intermediatePoint75 = new Vector2(((pointB.x - pointA.x) * v) + pointA.x, yInt75);
  182. // Gets the four control points of bezier curve
  183. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  184. if (controlPoints === undefined){
  185. console.log("error getting bezier control points");
  186. } else {
  187. this.setKeyframePoint(controlPoints, i, keyframes.length);
  188. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`
  189. }
  190. }
  191. });
  192. return data;
  193. }
  194. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number){
  195. let animation = this.state.selected as Animation;
  196. let keys = [...animation.getKeys()];
  197. let newFrame = 0;
  198. if (updatedSvgKeyFrame.keyframePoint.x !== 0){
  199. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1){
  200. newFrame = 1;
  201. }else {
  202. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x);
  203. }
  204. }
  205. keys[index].frame = newFrame; // This value comes as percentage/frame/time
  206. keys[index].value = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y)/ this._heightScale)*2; // this value comes inverted svg from 0 = 100 to 100 = 0
  207. animation.setKeys(keys);
  208. this.selectAnimation(animation);
  209. }
  210. linearInterpolation(keyframes: IAnimationKey[], data: string, middle: number): string {
  211. keyframes.forEach((key, i) => {
  212. var point = new Vector2(0, 0);
  213. point.x = key.frame;
  214. point.y = this._heightScale - (key.value * middle);
  215. this.setKeyframePointLinear(point, i);
  216. if (i !== 0) {
  217. data += ` L${point.x} ${point.y}`
  218. }
  219. });
  220. return data;
  221. }
  222. setKeyframePointLinear(point: Vector2,index: number){
  223. let svgKeyframe = { keyframePoint: point, rightControlPoint: null, leftControlPoint: null, id: index.toString() }
  224. this._svgKeyframes.push(svgKeyframe);
  225. }
  226. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  227. let svgKeyframe;
  228. if (index === 0){
  229. svgKeyframe = { keyframePoint: controlPoints[0], rightControlPoint: null, leftControlPoint: null, id: index.toString() }
  230. }else {
  231. this._svgKeyframes[index-1].rightControlPoint = controlPoints[1];
  232. svgKeyframe = { keyframePoint: controlPoints[3], rightControlPoint: null, leftControlPoint: controlPoints[2], id: index.toString() }
  233. }
  234. this._svgKeyframes.push(svgKeyframe);
  235. }
  236. selectAnimation(animation: Animation) {
  237. this._svgKeyframes = [];
  238. const pathData = this.getPathData(animation);
  239. if (pathData === "") {
  240. console.log("no keyframes in this animation");
  241. }
  242. this.setState({ selected: animation, currentPathData: pathData, svgKeyframes: this._svgKeyframes });
  243. }
  244. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v:number, p3: Vector2 ): Vector2[] | undefined {
  245. let a=0.0;
  246. let b=0.0;
  247. let c=0.0;
  248. let d=0.0;
  249. let det=0.0;
  250. let q1: Vector2 = new Vector2();
  251. let q2: Vector2 = new Vector2();
  252. let controlA: Vector2 = p0;
  253. let controlB: Vector2 = new Vector2();
  254. let controlC: Vector2 = new Vector2();
  255. let controlD: Vector2 = p3;
  256. if ( (u<=0.0) || (u>=1.0) || (v<=0.0) || (v>=1.0) || (u>=v) ){
  257. return undefined;
  258. }
  259. a = 3*(1-u)*(1-u)*u; b = 3*(1-u)*u*u;
  260. c = 3*(1-v)*(1-v)*v; d = 3*(1-v)*v*v;
  261. det = a*d - b*c;
  262. if (det == 0.0) return undefined;
  263. q1.x = p1.x - ( (1-u)*(1-u)*(1-u)*p0.x + u*u*u*p3.x );
  264. q1.y = p1.y - ( (1-u)*(1-u)*(1-u)*p0.y + u*u*u*p3.y );
  265. q2.x = p2.x - ( (1-v)*(1-v)*(1-v)*p0.x + v*v*v*p3.x );
  266. q2.y = p2.y - ( (1-v)*(1-v)*(1-v)*p0.y + v*v*v*p3.y );
  267. controlB.x = (d*q1.x - b*q2.x)/det;
  268. controlB.y = (d*q1.y - b*q2.y)/det;
  269. controlC.x = ((-c)*q1.x + a*q2.x)/det;
  270. controlC.y = ((-c)*q1.y + a*q2.y)/det;
  271. return [controlA, controlB, controlC, controlD];
  272. }
  273. render() {
  274. return (
  275. <div id="animation-curve-editor">
  276. <div className="header">
  277. <div className="title">{this.props.title}</div>
  278. <div className="close" onClick={(event: React.MouseEvent<HTMLDivElement, MouseEvent>) => this.props.close(event)}>
  279. <FontAwesomeIcon icon={faTimes} />
  280. </div>
  281. </div>
  282. <div className="content">
  283. <div className="animation-list">
  284. <div>
  285. <div>
  286. <label>Animation Name</label>
  287. <input type="text" value={this.state.animationName} onChange={(e) => this.handleNameChange(e)}></input>
  288. </div>
  289. <div>
  290. <label>Target Property</label>
  291. <input type="text" value={this.state.animationTargetProperty} onChange={(e) => this.handlePropertyChange(e)}></input>
  292. </div>
  293. <div className="add" onClick={(e) => this.addAnimation(e)}>
  294. <FontAwesomeIcon icon={faPlusCircle} />
  295. </div>
  296. </div>
  297. <h2>{this.props.entityName}</h2>
  298. <ul>
  299. {this.props.animations && this.props.animations.map((animation, i) => {
  300. return <li className={this.state.selected.name === animation.name ? 'active' : ''} key={i} onClick={() => this.selectAnimation(animation)}>{animation.name} <strong>{animation.targetProperty}</strong></li>
  301. })}
  302. </ul>
  303. <h2>New Animations</h2>
  304. <ul>
  305. {this.state.animations && this.state.animations.map((animation, i) => {
  306. return <li className={this.state.selected.name === animation.name ? 'active' : ''} key={i} onClick={() => this.selectAnimation(animation)}>{animation.name} <strong>{animation.targetProperty}</strong></li>
  307. })}
  308. </ul>
  309. </div>
  310. <div className="graph-chart">
  311. { this.state.svgKeyframes && <SvgDraggableArea keyframeSvgPoints={this.state.svgKeyframes} updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint,index: number) => this.renderPoints(updatedSvgKeyFrame, index)}>
  312. {/* Frame Labels */}
  313. <text x="10" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>10</text>
  314. <text x="20" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>20</text>
  315. <text x="30" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>30</text>
  316. <text x="40" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>40</text>
  317. <text x="50" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>50</text>
  318. <text x="60" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>60</text>
  319. <text x="70" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>70</text>
  320. <text x="80" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>80</text>
  321. <text x="90" y="0" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>90</text>
  322. { /* Vertical Grid */}
  323. <line x1="10" y1="0" x2="10" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  324. <line x1="20" y1="0" x2="20" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  325. <line x1="30" y1="0" x2="30" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  326. <line x1="40" y1="0" x2="40" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  327. <line x1="50" y1="0" x2="50" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  328. <line x1="60" y1="0" x2="60" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  329. <line x1="70" y1="0" x2="70" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  330. <line x1="80" y1="0" x2="80" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  331. <line x1="90" y1="0" x2="90" y2="100" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  332. { /* Value Labels */}
  333. <text x="0" y="10" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>1.8</text>
  334. <text x="0" y="20" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>1.6</text>
  335. <text x="0" y="30" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>1.4</text>
  336. <text x="0" y="40" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>1.2</text>
  337. <text x="0" y="50" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>1</text>
  338. <text x="0" y="60" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>0.8</text>
  339. <text x="0" y="70" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>0.6</text>
  340. <text x="0" y="80" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>0.4</text>
  341. <text x="0" y="90" dx="-1em" style={{ font: 'italic 0.2em sans-serif' }}>0.2</text>
  342. { /* Horizontal Grid */}
  343. <line x1="0" y1="10" x2="100" y2="10" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  344. <line x1="0" y1="20" x2="100" y2="20" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  345. <line x1="0" y1="30" x2="100" y2="30" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  346. <line x1="0" y1="40" x2="100" y2="40" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  347. <line x1="0" y1="50" x2="100" y2="50" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  348. <line x1="0" y1="60" x2="100" y2="60" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  349. <line x1="0" y1="70" x2="100" y2="70" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  350. <line x1="0" y1="80" x2="100" y2="80" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  351. <line x1="0" y1="90" x2="100" y2="90" style={{ stroke: 'black', strokeWidth: '0.2px' }}></line>
  352. { /* Single Curve -Modify this for multiple selection and view */}
  353. <path id="curve" d={this.state.currentPathData} style={{ stroke: 'red', fill: 'none', strokeWidth: '0.5' }}></path>
  354. { this._frames && this._frames.map(frame =>
  355. <svg x={frame.x} y={frame.y} style={{overflow:'visible'}}>
  356. <circle cx="0" cy="0" r="2" stroke="black" strokeWidth="1" fill="white" />
  357. </svg>
  358. )}
  359. </SvgDraggableArea>
  360. }
  361. Animation name: {this.state.selected.name}
  362. </div>
  363. </div>
  364. </div>
  365. );
  366. }
  367. }