UnitGraph.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. package ui.view.inspector;
  2. import java.awt.BasicStroke;
  3. import java.awt.Color;
  4. import java.awt.Cursor;
  5. import java.awt.Graphics;
  6. import java.awt.Graphics2D;
  7. import java.awt.RenderingHints;
  8. import java.awt.event.ComponentEvent;
  9. import java.awt.event.ComponentListener;
  10. import java.awt.event.MouseEvent;
  11. import java.awt.event.MouseListener;
  12. import java.awt.event.MouseMotionListener;
  13. import java.awt.geom.Path2D;
  14. import java.awt.geom.Point2D;
  15. import java.util.ArrayList;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.ListIterator;
  19. import java.util.Optional;
  20. import java.util.Set;
  21. import javax.swing.JPanel;
  22. import classes.HolonElement;
  23. import interfaces.GraphEditable.GraphType;
  24. import interfaces.TimelineDependent;
  25. import ui.controller.Control;
  26. import ui.model.Model;
  27. import utility.Maths;
  28. import utility.Vector2Int;
  29. /**
  30. * This Class represents a Graph where the User can model the behavior of
  31. * elements and switches over time.
  32. *
  33. * @author Tom Troppmann
  34. */
  35. public class UnitGraph extends JPanel implements MouseListener, MouseMotionListener, ComponentListener {
  36. // Normal Settings
  37. private static final int border = 4;
  38. private static final int clickThreshholdSquared = 25;
  39. // Display Settings
  40. /**
  41. * The size of a dot in the graph. It should be at least 1.
  42. */
  43. private static final int dotSize = 8;
  44. /** The Color of a dot in the graph. */
  45. private static final Color dotColor = Color.blue;
  46. private static final Color editDotColor = new Color(255, 119, 0);
  47. private static final Color[] seriesColorArray = { Color.blue, Color.cyan, Color.black, Color.green, Color.gray,
  48. Color.magenta, Color.yellow, Color.PINK, Color.red };
  49. private static final Color globalCurveColor = new Color(255, 30, 30);
  50. // Intern Variables
  51. private class Series {
  52. public LinkedList<UnitGraphPoint> points = new LinkedList<UnitGraphPoint>();
  53. public TimelineDependent element;
  54. public GraphType type;
  55. public Color color;
  56. }
  57. private ArrayList<Series> seriesList = new ArrayList<Series>();
  58. private Vector2Int editPosition;
  59. private Optional<Series> actualSeries;
  60. private class GlobalCurve {
  61. public LinkedList<UnitGraphPoint> points = new LinkedList<UnitGraphPoint>();
  62. public float minEnergy;
  63. public float maxEnergy;
  64. }
  65. private Optional<GlobalCurve> globalCurve = Optional.empty();
  66. private boolean editMode = false;
  67. private Set<HolonElement> elements;
  68. private enum EditPointType {
  69. Normal, StartPoint, EndPoint
  70. };
  71. private Model model;
  72. private int widthWithBorder, heightWithBorder;
  73. private EditPointType editPointType;
  74. /**
  75. * Constructor.
  76. *
  77. * @param model the Model
  78. * @param control the Controller
  79. */
  80. public UnitGraph(Control control) {
  81. setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
  82. this.model = control.getModel();
  83. this.setBackground(Color.WHITE);
  84. this.addMouseListener(this);
  85. this.addMouseMotionListener(this);
  86. this.addComponentListener(this);
  87. }
  88. /**
  89. * When the UnitGraph should represent a new GraphEditable Element. Its Updates
  90. * the Graph and give access to the Element.
  91. *
  92. * @param element
  93. */
  94. public void addNewSeries(TimelineDependent element) {
  95. Series series = new Series();
  96. overrideUnitGraph(series, element.getStateGraph());
  97. series.element = element;
  98. series.type = element.getGraphType();
  99. series.color = seriesColorArray[element.hashCode() % seriesColorArray.length];
  100. seriesList.add(series);
  101. repaint();
  102. }
  103. public void clearSeries() {
  104. seriesList.clear();
  105. repaint();
  106. }
  107. public void setGlobalCurve(Set<HolonElement> elements) {
  108. // TODO debug timing -> if to long async
  109. if(elements.isEmpty()) {
  110. this.globalCurve = Optional.empty();
  111. return;
  112. }
  113. GlobalCurve curve = new GlobalCurve();
  114. curve.maxEnergy = elements.stream().map(ele -> ele.getEnergy()).filter(energy -> energy > 0).reduce(0.0f,
  115. Float::sum);
  116. curve.minEnergy = elements.stream().map(ele -> ele.getEnergy()).filter(energy -> energy < 0).reduce(0.0f,
  117. Float::sum);
  118. float[] sample = new float[model.getMaxIterations()];
  119. // sample energy
  120. for (HolonElement element : elements) {
  121. for (int i = 0; i < model.getMaxIterations(); i++) {
  122. sample[i] += element.getEnergyAtTimeStep(i);
  123. }
  124. }
  125. // sample curve
  126. for (int i = 0; i < model.getMaxIterations(); i++) {
  127. curve.points.add(new UnitGraphPoint((double) i / (double)model.getMaxIterations(),
  128. Maths.inverseLinearInterpolation(curve.minEnergy, curve.maxEnergy, sample[i]), false));
  129. }
  130. // update displayPosition
  131. for (UnitGraphPoint p : curve.points) {
  132. p.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
  133. }
  134. // set global curve
  135. this.globalCurve = Optional.of(curve);
  136. this.elements = elements;
  137. }
  138. private void updateGlobalCurve() {
  139. setGlobalCurve(this.elements);
  140. }
  141. /**
  142. * Paints the Graph, the Grid, the actual Line from the currentIteration
  143. *
  144. * @param g Graphics
  145. */
  146. public void paintComponent(Graphics g) {
  147. super.paintComponent(g);
  148. Graphics2D g2D = (Graphics2D) g;
  149. drawGrid(g2D);
  150. g2D.setColor(Color.BLACK);
  151. g2D.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
  152. g2D.setStroke(new BasicStroke(2f));
  153. drawUnitGraph(g2D);
  154. g2D.setColor(dotColor);
  155. if (editMode) {
  156. drawUnitGraphPointsReleased(g2D);
  157. } else {
  158. drawUnitGraphPoints(g2D);
  159. }
  160. g2D.setColor(dotColor);
  161. g2D.setStroke(new BasicStroke(1));
  162. drawCurrentIterartionLine(g2D);
  163. g2D.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1.0f, new float[]{6}, 3));
  164. this.globalCurve.ifPresent(curve -> {
  165. g2D.setColor(globalCurveColor);
  166. drawDoubleGraph(g2D, curve.points);
  167. });
  168. }
  169. // Draw Methods only to let the User see the changes. Nothing its saved here or
  170. // changed.
  171. /**
  172. * Helper Method to draw the UnitGraphPanel.
  173. * {@link UnitGraph#paintComponent(Graphics)}
  174. * <p>
  175. * This Methods draws the UnitGraph whether its a boolGraph or a doubleGraph.
  176. *
  177. * @param g to draw.
  178. */
  179. private void drawUnitGraph(Graphics2D g) {
  180. boolean drawSnappingHintFlag = false;
  181. for (Series series : this.seriesList) {
  182. g.setColor(series.color);
  183. switch (series.type) {
  184. case boolGraph:
  185. if (editMode) {
  186. drawBoolGraphInEditMode(g, series);
  187. drawSnappingHintFlag = true;
  188. } else
  189. drawBoolGraph(g, series);
  190. break;
  191. case doubleGraph:
  192. if (editMode)
  193. drawDoubleGraphInEditMode(g, series);
  194. else
  195. drawDoubleGraph(g, series.points);
  196. break;
  197. default:
  198. throw new UnsupportedOperationException();
  199. }
  200. }
  201. if (drawSnappingHintFlag) {
  202. drawSnappingHint(g);
  203. }
  204. }
  205. /**
  206. * Helper Method to draw the UnitGraphPanel.
  207. * {@link UnitGraph#paintComponent(Graphics)}
  208. * <p>
  209. * This Methods draws the UnitGraphPoints of the UnitGraph.
  210. *
  211. * @param g to draw.
  212. */
  213. private void drawUnitGraphPoints(Graphics2D g) {
  214. g.setColor(dotColor);
  215. for (Series series : seriesList) {
  216. for (UnitGraphPoint p : series.points) {
  217. drawDot(g, p.displayedPosition);
  218. }
  219. }
  220. }
  221. /**
  222. * Helper Method to draw the UnitGraphPanel.
  223. * {@link UnitGraph#paintComponent(Graphics)}
  224. * <p>
  225. * This Methods draws the UnitGraphPoints of the UnitGraph when its in EditMode.
  226. *
  227. * @param g to draw.
  228. */
  229. private void drawUnitGraphPointsReleased(Graphics2D g) {
  230. drawUnitGraphPoints(g);
  231. g.setColor(editDotColor);
  232. drawDot(g, editPosition);
  233. }
  234. /**
  235. * Helper Method to draw the UnitGraphPanel.
  236. * {@link UnitGraph#paintComponent(Graphics)}
  237. * <p>
  238. * This Methods draws the Grid on the Canvas.
  239. *
  240. * @param g2D to draw.
  241. */
  242. private void drawGrid(Graphics2D g2D) {
  243. g2D.setStroke(new BasicStroke(1));
  244. g2D.setColor(Color.lightGray);
  245. int amountOfLines = 10;
  246. int width = widthWithBorder + 2 * border;
  247. int height = heightWithBorder;
  248. for (int i = 0; i <= amountOfLines; i++) {
  249. int linehieght = (int) (((double) i / (double) amountOfLines) * (double) height) + border;
  250. g2D.drawLine(0, linehieght, width, linehieght);
  251. }
  252. }
  253. /**
  254. * Helper Method to draw the UnitGraphPanel.
  255. * {@link UnitGraph#paintComponent(Graphics)}
  256. * <p>
  257. * This Method draws the CurrentIterationLine.
  258. *
  259. * @param g2D to draw.
  260. */
  261. private void drawCurrentIterartionLine(Graphics2D g) {
  262. int cur = model.getCurrentIteration();
  263. int max = model.getMaxIterations();
  264. if (isLocalPeriedDifferentInSeries()) {
  265. for (Series series : seriesList) {
  266. double where;
  267. if (!series.element.isUsingLocalPeriod()) {
  268. where = ((double) cur) / ((double) max);
  269. } else {
  270. int lPeriod = series.element.getLocalPeriod();
  271. where = ((double) cur % lPeriod) / ((double) lPeriod);
  272. }
  273. Vector2Int oben = new Vector2Int(border + (int) (where * widthWithBorder), 0);
  274. Vector2Int unten = new Vector2Int(border + (int) (where * widthWithBorder),
  275. 2 * border + heightWithBorder);
  276. g.setColor(series.color);
  277. drawLine(g, oben, unten);
  278. }
  279. } else {
  280. double where;
  281. if (!isUsingLocalPeriod()) {
  282. where = ((double) cur) / ((double) max);
  283. } else {
  284. int lPeriod = getFirstLocalPeriod();
  285. where = ((double) cur % lPeriod) / ((double) lPeriod);
  286. }
  287. Vector2Int oben = new Vector2Int(border + (int) (where * widthWithBorder), 0);
  288. Vector2Int unten = new Vector2Int(border + (int) (where * widthWithBorder), 2 * border + heightWithBorder);
  289. g.setColor(dotColor);
  290. drawLine(g, oben, unten);
  291. }
  292. }
  293. /**
  294. * Helper Method to draw the UnitGraphPanel.
  295. * {@link UnitGraph#paintComponent(Graphics)}
  296. * <p>
  297. * This Method draws a line between two Positions on the Canvas.
  298. *
  299. * @param g2D to draw.
  300. * @param start the Position of one end of the line to draw.
  301. * @param end the other Ends Position of the Line to draw.
  302. */
  303. private void drawLine(Graphics2D g, Vector2Int start, Vector2Int end) {
  304. Path2D.Double path = new Path2D.Double();
  305. path.moveTo(start.getX(), start.getY());
  306. path.lineTo(end.getX(), end.getY());
  307. g.draw(path);
  308. }
  309. /**
  310. * Helper Method to draw the UnitGraphPanel.
  311. * {@link UnitGraph#paintComponent(Graphics)}
  312. * <p>
  313. * Initialize a Cubic BezierCurve.
  314. *
  315. * @param start The Position to start the Curve.
  316. */
  317. private Path2D.Double initBezier(Vector2Int start) {
  318. // Good Source for basic understanding for Bezier Curves
  319. // http://www.theappguruz.com/blog/bezier-curve-in-games
  320. Path2D.Double path = new Path2D.Double();
  321. path.moveTo(start.getX(), start.getY());
  322. return path;
  323. }
  324. /**
  325. * Helper Method to draw the UnitGraphPanel.
  326. * {@link UnitGraph#paintComponent(Graphics)}
  327. * <p>
  328. * Calculate the Path of a the Cubic BezierCurve with the special controlPoints
  329. * to make the wanted behavior.
  330. *
  331. * @param path the path of the Bezier.
  332. * @param actaul the actual Position of the Path.
  333. * @param target the end Position of the Curve.
  334. */
  335. private void curveTo(Path2D.Double path, Vector2Int actual, Vector2Int target) {
  336. double mitte = (actual.getX() + target.getX()) * 0.5;
  337. path.curveTo(mitte, actual.getY(), mitte, target.getY(), target.getX(), target.getY());
  338. }
  339. /**
  340. * Helper Method to draw the UnitGraphPanel.
  341. * {@link UnitGraph#paintComponent(Graphics)}
  342. * <p>
  343. * Draws a Dot at a Position.
  344. *
  345. * @param g to draw.
  346. * @param p the position of the Dot.
  347. */
  348. private void drawDot(Graphics2D g, Vector2Int p) {
  349. g.fillOval(p.getX() - dotSize / 2, p.getY() - dotSize / 2, dotSize, dotSize);
  350. }
  351. /**
  352. * Helper Method to draw the UnitGraphPanel.
  353. * {@link UnitGraph#paintComponent(Graphics)}
  354. * <p>
  355. * This Method draws the UnitGraph as BoolGraph.
  356. *
  357. * @param g2D to draw.
  358. */
  359. private void drawBoolGraph(Graphics2D g, Series series) {
  360. if (series.points.size() <= 1)
  361. return;
  362. LinkedList<Vector2Int> cornerPoints = new LinkedList<Vector2Int>();
  363. ListIterator<UnitGraphPoint> iter = series.points.listIterator();
  364. Vector2Int actual = series.points.getFirst().displayedPosition;
  365. Path2D.Double path = new Path2D.Double();
  366. path.moveTo(actual.getX(), actual.getY());
  367. while (iter.hasNext()) {
  368. Vector2Int target = iter.next().displayedPosition;
  369. // BooleanConnection
  370. path.lineTo(target.getX(), actual.getY()); // line to corner
  371. cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); // save corner
  372. path.lineTo(target.getX(), target.getY()); // line to next Point
  373. actual = target;
  374. }
  375. g.draw(path);
  376. // Draw the Points on the Corner that dont exist in Data but should be visual
  377. g.setColor(dotColor);
  378. for (Vector2Int p : cornerPoints) {
  379. drawDot(g, p);
  380. }
  381. }
  382. /**
  383. * Helper Method to draw the UnitGraphPanel.
  384. * {@link UnitGraph#paintComponent(Graphics)}
  385. * <p>
  386. * This Method draws the UnitGraph as BoolGraph in EditMode.
  387. *
  388. * @param g2D to draw.
  389. */
  390. private void drawBoolGraphInEditMode(Graphics2D g, Series series) {
  391. LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
  392. LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
  393. for (UnitGraphPoint p : series.points) {
  394. if (p.displayedPosition.getX() < editPosition.getX())
  395. before.add(p.displayedPosition);
  396. else
  397. after.add(p.displayedPosition);
  398. }
  399. g.setColor(series.color);
  400. drawBoolGraphFromList(g, before);
  401. g.setColor(series.color);
  402. drawBoolGraphFromList(g, after);
  403. // EditGraph
  404. LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
  405. if (!before.isEmpty())
  406. middle.add(before.getLast());
  407. middle.add(editPosition);
  408. if (!after.isEmpty())
  409. middle.add(after.getFirst());
  410. g.setColor(editDotColor);
  411. drawBoolGraphFromList(g, middle);
  412. }
  413. /**
  414. * Helper Method to draw the UnitGraphPanel.
  415. * {@link UnitGraph#paintComponent(Graphics)}
  416. * <p>
  417. * This Method draws a red Hint to signal the User the snapping of the hovered
  418. * Point under the Cursor in EditMode.
  419. *
  420. * @param g2D to draw.
  421. */
  422. private void drawSnappingHint(Graphics2D g) {
  423. // ColorHint
  424. g.setColor(Color.RED);
  425. // Threshhold Line
  426. final float dash1[] = { 10.0f };
  427. final BasicStroke dashed = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1,
  428. 0.0f);
  429. g.setStroke(dashed);
  430. int halfheight = border + heightWithBorder / 2;
  431. g.drawLine(0, halfheight, widthWithBorder + 2 * border, halfheight);
  432. // Threshhold Text
  433. g.drawString("Snapping Threshold", 10, halfheight - 2);
  434. }
  435. /**
  436. * Helper Method to draw the UnitGraphPanel.
  437. * {@link UnitGraph#paintComponent(Graphics)}
  438. * <p>
  439. * This Method draws a partial Graph from a Position List as BoolGraph.
  440. *
  441. * @param g2D to draw.
  442. * @param list the PositionList to draw a BoolGraph
  443. */
  444. private void drawBoolGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
  445. if (list.size() <= 1)
  446. return;
  447. ListIterator<Vector2Int> iter = list.listIterator();
  448. LinkedList<Vector2Int> cornerPoints = new LinkedList<Vector2Int>();
  449. Vector2Int actual = list.getFirst();
  450. Path2D.Double path = new Path2D.Double();
  451. path.moveTo(actual.getX(), actual.getY());
  452. while (iter.hasNext()) {
  453. Vector2Int target = iter.next();
  454. // BooleanConnection
  455. path.lineTo(target.getX(), actual.getY()); // line to corner
  456. cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); // save corner
  457. path.lineTo(target.getX(), target.getY()); // line to next Point
  458. actual = target;
  459. }
  460. g.draw(path);
  461. g.setColor(dotColor);
  462. for (Vector2Int p : cornerPoints) {
  463. drawDot(g, p);
  464. }
  465. }
  466. /**
  467. * Helper Method to draw the UnitGraphPanel.
  468. * {@link UnitGraph#paintComponent(Graphics)}
  469. * <p>
  470. * This Method draws the UnitGraph as DoubleGraph.
  471. *
  472. * @param g2D to draw.
  473. */
  474. private void drawDoubleGraph(Graphics2D g, List<UnitGraphPoint> points) {
  475. if (points.isEmpty())
  476. return;
  477. ListIterator<UnitGraphPoint> iter = points.listIterator();
  478. Vector2Int actual = iter.next().displayedPosition;
  479. Path2D.Double path = this.initBezier(actual);
  480. while (iter.hasNext()) {
  481. Vector2Int target = iter.next().displayedPosition;
  482. this.curveTo(path, actual, target);
  483. actual = target;
  484. }
  485. g.draw(path);
  486. }
  487. /**
  488. * Helper Method to draw the UnitGraphPanel.
  489. * {@link UnitGraph#paintComponent(Graphics)}
  490. * <p>
  491. * This Method draws the UnitGraph as DoubleGraph in EditMode.
  492. *
  493. * @param g2D to draw.
  494. */
  495. private void drawDoubleGraphInEditMode(Graphics2D g, Series series) {
  496. LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
  497. LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
  498. for (UnitGraphPoint p : series.points) {
  499. if (p.displayedPosition.getX() < editPosition.getX())
  500. before.add(p.displayedPosition);
  501. else
  502. after.add(p.displayedPosition);
  503. }
  504. drawUnitGraphFromList(g, before);
  505. drawUnitGraphFromList(g, after);
  506. // EditGraph
  507. LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
  508. if (!before.isEmpty())
  509. middle.add(before.getLast());
  510. middle.add(editPosition);
  511. if (!after.isEmpty())
  512. middle.add(after.getFirst());
  513. g.setColor(editDotColor);
  514. drawUnitGraphFromList(g, middle);
  515. }
  516. /**
  517. * Helper Method to draw the UnitGraphPanel.
  518. * {@link UnitGraph#paintComponent(Graphics)}
  519. * <p>
  520. * This Method draws a partial Graph from a Position List as DoubleGraph.
  521. *
  522. * @param g2D to draw.
  523. * @param list the PositionList to draw a DoubleGraph
  524. */
  525. private void drawUnitGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
  526. if (list.size() <= 1)
  527. return;
  528. ListIterator<Vector2Int> iter = list.listIterator();
  529. Vector2Int actual = list.getFirst();
  530. Path2D.Double path = this.initBezier(actual);
  531. while (iter.hasNext()) {
  532. Vector2Int target = iter.next();
  533. curveTo(path, actual, target);
  534. actual = target;
  535. }
  536. g.draw(path);
  537. }
  538. // Under the hood functions to calculate and function the
  539. /**
  540. * A unitgraphpoint have a x and y position to store the data of a graph point.
  541. * Also it have a displayposition to store the Position of the GraphPoints on
  542. * the Canvas. e.g. when the canvas has 500 width and 200 height a GraphPoint
  543. * with the X=0.5 and Y=1.0 should have a displayposition of (250,3) when border
  544. * is 3.
  545. */
  546. private void updateRepresentativePositions() {
  547. for (Series series : seriesList) {
  548. for (UnitGraphPoint p : series.points) {
  549. p.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
  550. }
  551. }
  552. this.globalCurve.ifPresent(curve -> {
  553. for (UnitGraphPoint p : curve.points) {
  554. p.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
  555. }
  556. });
  557. }
  558. /**
  559. * Takes a List of GraphPoints and convert it to the actual UnitGraphPoints with
  560. * displayposition in the {@link #seriesList}
  561. *
  562. * @param stateCurve the list of GraphPoint
  563. */
  564. private void overrideUnitGraph(Series series, LinkedList<Point2D.Double> stateCurve) {
  565. series.points.clear();
  566. for (Point2D.Double p : stateCurve) {
  567. UnitGraphPoint point = new UnitGraphPoint(p);
  568. point.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
  569. series.points.add(point);
  570. }
  571. }
  572. /**
  573. * When the PanelSize Change the width and height to calculate the drawings have
  574. * to be adjusted.
  575. */
  576. private void calculateWidthHeight() {
  577. widthWithBorder = this.getWidth() - 2 * border;
  578. heightWithBorder = this.getHeight() - 2 * border;
  579. }
  580. /**
  581. * Save the actualGraphPoint List to the GraphEditable Element.
  582. */
  583. private void saveGraph() {
  584. for (Series series : seriesList) {
  585. LinkedList<Point2D.Double> actual = series.element.getStateGraph();
  586. actual.clear();
  587. for (UnitGraphPoint p : series.points) {
  588. actual.add(p.getPoint());
  589. }
  590. series.element.sampleGraph();
  591. }
  592. }
  593. /**
  594. * Remove a UnitGraphPoint from the UnitGraphPoint list ({@link #seriesList}
  595. * when its near a given Position.
  596. *
  597. * @param mPosition
  598. */
  599. private void removePointNearPosition(Series series, Vector2Int mPosition) {
  600. ListIterator<UnitGraphPoint> iter = series.points.listIterator();
  601. while (iter.hasNext()) {
  602. if (near(mPosition, iter.next().displayedPosition, series.type)) {
  603. iter.remove();
  604. break;
  605. }
  606. }
  607. }
  608. private void removePointsNearPosition(Vector2Int mPosition) {
  609. for (Series series : seriesList) {
  610. removePointNearPosition(series, mPosition);
  611. }
  612. }
  613. private Optional<Series> detectSeries(Vector2Int mPosition) {
  614. return seriesList.stream().min((a, b) -> {
  615. float minDistanceA = a.points.stream().map(point -> point.displayedPosition.getSquaredDistance(mPosition))
  616. .min(Float::compare).get();
  617. float minDistanceB = b.points.stream().map(point -> point.displayedPosition.getSquaredDistance(mPosition))
  618. .min(Float::compare).get();
  619. return Float.compare(minDistanceA, minDistanceB);
  620. });
  621. }
  622. /**
  623. * Determine if the Point is a StartPoint , EndPoint or a NormalPoint a.k.a. in
  624. * between Points.
  625. *
  626. * @param mPosition The Position to check.
  627. */
  628. private EditPointType detectStartEndPoint(Series series, Vector2Int mPosition) {
  629. UnitGraphPoint first = series.points.getFirst();
  630. UnitGraphPoint last = series.points.getLast();
  631. if (near(mPosition, first.displayedPosition, series.type))
  632. return EditPointType.StartPoint;
  633. else if (near(mPosition, last.displayedPosition, series.type))
  634. return EditPointType.EndPoint;
  635. else
  636. return EditPointType.Normal;
  637. }
  638. /**
  639. * Determine if a Point is near the Cursor (depends on Mode what near means). To
  640. * detect if it should grab the Point or create a new Point.
  641. *
  642. * @param actual
  643. * @param target
  644. * @return
  645. */
  646. private boolean near(Vector2Int actual, Vector2Int target, GraphType graphType) {
  647. switch (graphType) {
  648. case boolGraph: // Distance only with X
  649. int xDis = target.getX() - actual.getX();
  650. return xDis * xDis < clickThreshholdSquared;
  651. case doubleGraph:
  652. return actual.getSquaredDistance(target) < clickThreshholdSquared;
  653. default:
  654. return false;
  655. }
  656. }
  657. /**
  658. * When the Mouse Drag a Point it updates each time the position.
  659. *
  660. * @param newPosition
  661. */
  662. private void updateEditPointPosition(Vector2Int newPosition, EditPointType editPointType, GraphType graphType) {
  663. // make it in the bounds of the UnitGraph no Point out of the Border
  664. Vector2Int currentPosition = setInBounds(newPosition);
  665. if (editPointType != EditPointType.Normal) {
  666. attachToBorder(currentPosition, editPointType);
  667. }
  668. if (graphType == GraphType.boolGraph) {
  669. snapBoolean(currentPosition);
  670. }
  671. editPosition = currentPosition;
  672. }
  673. /**
  674. * No Point on the UnitGraph should exit the UnitGraph.
  675. *
  676. * @param p the Position
  677. * @return the updated Position.
  678. */
  679. private Vector2Int setInBounds(Vector2Int p) {
  680. p.clampX(border, border + widthWithBorder);
  681. p.clampY(border, border + heightWithBorder);
  682. return p;
  683. }
  684. /**
  685. * For Switches the Point have to be Snap to the Top or the Bottem.
  686. *
  687. * @param p the Position
  688. * @return the updated Position.
  689. */
  690. private Vector2Int snapBoolean(Vector2Int p) {
  691. if (p.getY() < border + heightWithBorder / 2) {
  692. p.setY(border);
  693. } else {
  694. p.setY(border + heightWithBorder);
  695. }
  696. return p;
  697. }
  698. /**
  699. * The First Point has to be at 0(LeftSide) and Last Point has to be at
  700. * 1(RightSide).
  701. *
  702. * @param p the Position
  703. * @return the updated Position.
  704. */
  705. private Vector2Int attachToBorder(Vector2Int p, EditPointType editPointType) {
  706. switch (editPointType) {
  707. case StartPoint:
  708. p.setX(border);
  709. break;
  710. case EndPoint:
  711. p.setX(border + widthWithBorder);
  712. break;
  713. default:
  714. break;
  715. }
  716. return p;
  717. }
  718. /**
  719. * Insert a Position in the UnitGraphList at the right order. Its sorted based
  720. * on the xValues.
  721. *
  722. * @param pos The new UnitGraphPoints Position
  723. */
  724. private void insertNewGraphPoint(Series series, Vector2Int pos) {
  725. setInBounds(pos);
  726. ListIterator<UnitGraphPoint> iter = series.points.listIterator();
  727. while (iter.hasNext()) {
  728. Vector2Int tempPosition = iter.next().displayedPosition;
  729. if (pos.getX() <= tempPosition.getX()) {
  730. // previous to go back a position to make the new point before the the Position
  731. // with greater X
  732. iter.previous();
  733. iter.add(generateUnitGraphPoint(pos));
  734. break;
  735. }
  736. }
  737. if (!iter.hasNext()) // if behind last point
  738. {
  739. iter.add(generateUnitGraphPoint(pos));
  740. }
  741. }
  742. /**
  743. * Generate a UnitGraphPoint from a normal Position in the UnitGraph.
  744. *
  745. * @param pos the normal pos with xValues from 0..Width and yValues from
  746. * 0..Height
  747. * @return a UnitGraphPoint
  748. */
  749. private UnitGraphPoint generateUnitGraphPoint(Vector2Int pos) {
  750. UnitGraphPoint temp = new UnitGraphPoint((double) (pos.getX() - border) / (double) widthWithBorder,
  751. 1 - (double) (pos.getY() - border) / (double) heightWithBorder, true);
  752. temp.displayedPosition = pos;
  753. return temp;
  754. }
  755. /**
  756. * Update the Point Position
  757. */
  758. @Override
  759. public void mouseDragged(MouseEvent e) {
  760. actualSeries.ifPresent(series -> {
  761. updateEditPointPosition(new Vector2Int(e.getPoint().x, e.getPoint().y), this.editPointType, series.type);
  762. updateGlobalCurve();
  763. repaint();
  764. });
  765. }
  766. @Override
  767. public void mouseMoved(MouseEvent e) {
  768. }
  769. @Override
  770. public void mouseClicked(MouseEvent e) {
  771. }
  772. @Override
  773. public void mouseEntered(MouseEvent e) {
  774. }
  775. @Override
  776. public void mouseExited(MouseEvent e) {
  777. }
  778. /**
  779. * The First Step. When LeftMouseButton its checks if a point is to grab under
  780. * the cursor or create a new Point. Then enter EditMode. When RightMouseButton
  781. * its delete a point if its under the Curser.
  782. */
  783. @Override
  784. public void mousePressed(MouseEvent e) {
  785. Vector2Int mPosition = new Vector2Int(e.getPoint().x, e.getPoint().y);
  786. actualSeries = detectSeries(mPosition);
  787. actualSeries.ifPresent(series -> {
  788. if (e.getButton() == MouseEvent.BUTTON3) {
  789. // RightMouseButtonEvent
  790. editPointType = detectStartEndPoint(series, mPosition);
  791. if (editPointType == EditPointType.Normal) {
  792. removePointsNearPosition(mPosition);
  793. repaint();
  794. }
  795. editMode = false;
  796. } else if (e.getButton() == MouseEvent.BUTTON1) {
  797. // LeftMouseButtonEvent
  798. editPointType = detectStartEndPoint(series, mPosition);
  799. removePointsNearPosition(mPosition);
  800. updateEditPointPosition(mPosition, editPointType, series.type);
  801. editMode = true;
  802. repaint();
  803. }
  804. });
  805. }
  806. /**
  807. * The last step to save the Changes. Its insert the Hovering Point and exit
  808. * EditMode.
  809. */
  810. @Override
  811. public void mouseReleased(MouseEvent e) {
  812. if (editMode && actualSeries.isPresent()) {
  813. for (Series series : seriesList) {
  814. this.insertNewGraphPoint(series, editPosition);
  815. }
  816. editMode = false;
  817. }
  818. saveGraph();
  819. updateGlobalCurve();
  820. repaint();
  821. }
  822. /**
  823. * When the Component is Resized.
  824. *
  825. * @param e ComponentEvent
  826. */
  827. public void componentResized(ComponentEvent e) {
  828. calculateWidthHeight();
  829. updateRepresentativePositions();
  830. repaint();
  831. }
  832. @Override
  833. public void componentHidden(ComponentEvent e) {
  834. }
  835. @Override
  836. public void componentMoved(ComponentEvent e) {
  837. }
  838. @Override
  839. public void componentShown(ComponentEvent e) {
  840. }
  841. /**
  842. * Resets the graph to normal.
  843. */
  844. public void reset() {
  845. for (Series series : seriesList) {
  846. series.element.reset();
  847. overrideUnitGraph(series, series.element.getStateGraph());
  848. }
  849. repaint();
  850. }
  851. // LocalMode access methods...
  852. // To access a element from the GUI for the LocalMode
  853. public void setUseLocalPeriod(boolean state) {
  854. for (Series series : seriesList) {
  855. series.element.setUseLocalPeriod(state);
  856. }
  857. }
  858. public void setLocalPeriod(int localLength) {
  859. for (Series series : seriesList) {
  860. series.element.setLocalPeriod(localLength);
  861. }
  862. }
  863. public boolean isLocalPeriedDifferentInSeries() {
  864. return seriesList.stream().map(series -> series.element.getLocalPeriod()).distinct().count() > 1;
  865. }
  866. public int getFirstLocalPeriod() {
  867. return seriesList.isEmpty() ? 0 : seriesList.get(0).element.getLocalPeriod();
  868. }
  869. public boolean isUsingLocalPeriod() {
  870. return seriesList.stream().anyMatch(series -> series.element.isUsingLocalPeriod());
  871. }
  872. }