MVP_Model.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Controls;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Imaging;
  10. using OptiTrack;
  11. using System.Runtime.InteropServices;
  12. namespace SketchAssistantWPF
  13. {
  14. public class MVP_Model
  15. {
  16. /// <summary>
  17. /// The Presenter of the MVP-Model.
  18. /// </summary>
  19. MVP_Presenter programPresenter;
  20. /// <summary>
  21. /// History of Actions
  22. /// </summary>
  23. ActionHistory historyOfActions;
  24. /// <summary>
  25. /// The assistant responsible for the redraw mode
  26. /// </summary>
  27. //RedrawAssistant redrawAss;
  28. OptiTrackConnector connector;
  29. /***********************/
  30. /*** CLASS VARIABLES ***/
  31. /***********************/
  32. /// <summary>
  33. /// If the program is in drawing mode.
  34. /// </summary>
  35. bool inDrawingMode;
  36. /// <summary>
  37. /// if the program is using OptiTrack
  38. /// </summary>
  39. public bool optiTrackInUse{ get; private set; }
  40. /// <summary>
  41. /// Size of deletion area
  42. /// </summary>
  43. int deletionRadius = 5;
  44. /// <summary>
  45. /// Size of areas marking endpoints of lines in the redraw mode.
  46. /// </summary>
  47. int markerRadius = 10;
  48. /// <summary>
  49. /// The Position of the Cursor in the right picture box
  50. /// </summary>
  51. Point currentCursorPosition;
  52. /// <summary>
  53. /// The Previous Cursor Position in the right picture box
  54. /// </summary>
  55. Point previousCursorPosition;
  56. /// <summary>
  57. /// Queue for the cursorPositions
  58. /// </summary>
  59. Queue<Point> cursorPositions = new Queue<Point>();
  60. /// <summary>
  61. /// Lookup Matrix for checking postions of lines in the image
  62. /// </summary>
  63. bool[,] isFilledMatrix;
  64. /// <summary>
  65. /// Lookup Matrix for getting line ids at a certain postions of the image
  66. /// </summary>
  67. HashSet<int>[,] linesMatrix;
  68. /// <summary>
  69. /// List of items which will be overlayed over the right canvas.
  70. /// </summary>
  71. List<Tuple<bool, HashSet<Point>>> overlayItems;
  72. /// <summary>
  73. /// Width of the LeftImageBox.
  74. /// </summary>
  75. public int leftImageBoxWidth;
  76. /// <summary>
  77. /// Height of the LeftImageBox.
  78. /// </summary>
  79. public int leftImageBoxHeight;
  80. /// <summary>
  81. /// Width of the RightImageBox.
  82. /// </summary>
  83. public int rightImageBoxWidth;
  84. /// <summary>
  85. /// Height of the RightImageBox.
  86. /// </summary>
  87. public int rightImageBoxHeight;
  88. public ImageDimension leftImageSize { get; private set; }
  89. public ImageDimension rightImageSize { get; private set; }
  90. /// <summary>
  91. /// Indicates whether or not the canvas on the right side is active.
  92. /// </summary>
  93. public bool canvasActive {get; set;}
  94. /// <summary>
  95. /// Indicates if there is a graphic loaded in the left canvas.
  96. /// </summary>
  97. public bool graphicLoaded { get; set; }
  98. //TODO: calibrate
  99. double OPTITRACK_X_OFFSET = 0.7878 ;
  100. double OPTITRACK_Y_OFFSET = 0.7977 ;
  101. double OPTITRACK_CANVAS_HEIGHT = 1.29;
  102. double OPTITRACK_X_SCALE = -0.254 * (((1.816 / 0.0254) * 96) / (1.816));
  103. double OPTITRACK_Y_SCALE = 0.254 * (((1.360 / 0.0254) * 96) / (1.360));
  104. Image rightImageWithoutOverlay;
  105. List<InternalLine> leftLineList;
  106. List<Tuple<bool, InternalLine>> rightLineList;
  107. List<Point> currentLine = new List<Point>();
  108. public MVP_Model(MVP_Presenter presenter)
  109. {
  110. programPresenter = presenter;
  111. historyOfActions = new ActionHistory();
  112. //redrawAss = new RedrawAssistant();
  113. //overlayItems = new List<Tuple<bool, HashSet<Point>>>();
  114. rightLineList = new List<Tuple<bool, InternalLine>>();
  115. canvasActive = false;
  116. UpdateUI();
  117. rightImageSize = new ImageDimension(0, 0);
  118. leftImageSize = new ImageDimension(0, 0);
  119. connector = new OptiTrackConnector();
  120. armband = new Armband();
  121. if (connector.Init(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  122. {
  123. connector.StartTracking(getOptiTrackPosition);
  124. }
  125. }
  126. [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
  127. private static extern bool SetCursorPos(int X, int Y);
  128. //[DllImport("user32.dll")]
  129. //public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
  130. public enum MouseEventType : int
  131. {
  132. LeftDown = 0x02,
  133. LeftUp = 0x04,
  134. RightDown = 0x08,
  135. RightUp = 0x10
  136. }
  137. /**************************/
  138. /*** INTERNAL FUNCTIONS ***/
  139. /**************************/
  140. /// <summary>
  141. /// Change the status of whether or not the lines are shown.
  142. /// </summary>
  143. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  144. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  145. private void ChangeLines(HashSet<int> lines, bool shown)
  146. {
  147. foreach (int lineId in lines)
  148. {
  149. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  150. {
  151. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// A function that populates the matrixes needed for deletion detection with line data.
  157. /// </summary>
  158. private void RepopulateDeletionMatrixes()
  159. {
  160. if (canvasActive)
  161. {
  162. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  163. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  164. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  165. {
  166. if (lineTuple.Item1)
  167. {
  168. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Tells the Presenter to Update the UI
  175. /// </summary>
  176. private void UpdateUI()
  177. {
  178. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded, optiTrackInUse);
  179. }
  180. /// <summary>
  181. /// A function that checks the deletion matrixes at a certain point
  182. /// and returns all Line ids at that point and in a square around it in a certain range.
  183. /// </summary>
  184. /// <param name="p">The point around which to check.</param>
  185. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  186. /// <returns>A List of all lines.</returns>
  187. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  188. {
  189. HashSet<int> returnSet = new HashSet<int>();
  190. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  191. {
  192. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  193. {
  194. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  195. {
  196. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  197. }
  198. }
  199. }
  200. return returnSet;
  201. }
  202. /********************************************/
  203. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  204. /********************************************/
  205. /// <summary>
  206. /// A function to update the dimensions of the left and right canvas when the window is resized.
  207. /// </summary>
  208. /// <param name="LeftCanvas">The size of the left canvas.</param>
  209. /// <param name="RightCanvas">The size of the right canvas.</param>
  210. public void ResizeEvent(ImageDimension LeftCanvas, ImageDimension RightCanvas)
  211. {
  212. if(LeftCanvas.Height >= 0 && LeftCanvas.Width>= 0) { leftImageSize = LeftCanvas; }
  213. if(RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  214. RepopulateDeletionMatrixes();
  215. }
  216. /// <summary>
  217. /// A function to reset the right image.
  218. /// </summary>
  219. public void ResetRightImage()
  220. {
  221. rightLineList.Clear();
  222. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  223. programPresenter.ClearRightLines();
  224. }
  225. /// <summary>
  226. /// The function to set the left image.
  227. /// </summary>
  228. /// <param name="width">The width of the left image.</param>
  229. /// <param name="height">The height of the left image.</param>
  230. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  231. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  232. {
  233. leftImageSize = new ImageDimension(width, height);
  234. rightImageSize = new ImageDimension(width, height);
  235. leftLineList = listOfLines;
  236. graphicLoaded = true;
  237. programPresenter.UpdateLeftLines(leftLineList);
  238. CanvasActivated();
  239. /*
  240. var workingCanvas = GetEmptyCanvas(width, height);
  241. var workingGraph = Graphics.FromImage(workingCanvas);
  242. leftLineList = listOfLines;
  243. //redrawAss = new RedrawAssistant(leftLineList);
  244. //overlayItems = redrawAss.Initialize(markerRadius);
  245. //Lines
  246. foreach (InternalLine line in leftLineList)
  247. {
  248. line.DrawLine(workingGraph);
  249. }
  250. leftImage = workingCanvas;
  251. programPresenter.UpdateLeftImage(leftImage);
  252. //Set right image to same size as left image and delete linelist
  253. DrawEmptyCanvasRight();
  254. rightLineList = new List<Tuple<bool, InternalLine>>();
  255. */
  256. }
  257. /// <summary>
  258. /// A function to tell the model a new canvas was activated.
  259. /// </summary>
  260. public void CanvasActivated()
  261. {
  262. canvasActive = true;
  263. RepopulateDeletionMatrixes();
  264. UpdateUI();
  265. }
  266. /// <summary>
  267. /// Will undo the last action taken, if the action history allows it.
  268. /// </summary>
  269. public void Undo()
  270. {
  271. if (historyOfActions.CanUndo())
  272. {
  273. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  274. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  275. switch (undoAction)
  276. {
  277. case SketchAction.ActionType.Delete:
  278. //Deleted Lines need to be shown
  279. ChangeLines(affectedLines, true);
  280. break;
  281. case SketchAction.ActionType.Draw:
  282. //Drawn lines need to be hidden
  283. ChangeLines(affectedLines, false);
  284. break;
  285. default:
  286. break;
  287. }
  288. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  289. programPresenter.UpdateRightLines(rightLineList);
  290. }
  291. RepopulateDeletionMatrixes();
  292. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  293. UpdateUI();
  294. }
  295. /// <summary>
  296. /// Will redo the last action undone, if the action history allows it.
  297. /// </summary>
  298. public void Redo()
  299. {
  300. if (historyOfActions.CanRedo())
  301. {
  302. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  303. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  304. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  305. switch (redoAction)
  306. {
  307. case SketchAction.ActionType.Delete:
  308. //Deleted Lines need to be redeleted
  309. ChangeLines(affectedLines, false);
  310. break;
  311. case SketchAction.ActionType.Draw:
  312. //Drawn lines need to be redrawn
  313. ChangeLines(affectedLines, true);
  314. break;
  315. default:
  316. break;
  317. }
  318. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  319. programPresenter.UpdateRightLines(rightLineList);
  320. RepopulateDeletionMatrixes();
  321. }
  322. UpdateUI();
  323. }
  324. /// <summary>
  325. /// The function called by the Presenter to change the drawing state of the program.
  326. /// </summary>
  327. /// <param name="nowDrawing">The new drawingstate of the program</param>
  328. public void ChangeState(bool nowDrawing)
  329. {
  330. inDrawingMode = nowDrawing;
  331. UpdateUI();
  332. }
  333. /// <summary>
  334. /// The function called by the Presenter to set a variable which describes if OptiTrack is in use
  335. /// </summary>
  336. /// <param name="usingOptiTrack"></param>
  337. public void SetOptiTrack(bool usingOptiTrack)
  338. {
  339. optiTrackInUse = usingOptiTrack;
  340. if (usingOptiTrack && optiTrackX == 0 && optiTrackY == 0 && optiTrackZ == 0)
  341. {
  342. programPresenter.PassMessageToView("Trackable not detected, please check if OptiTrack is activated and Trackable is recognized", "Warning");
  343. }
  344. }
  345. /// <summary>
  346. /// Updates the current cursor position of the model.
  347. /// </summary>
  348. /// <param name="p">The new cursor position</param>
  349. public void SetCurrentCursorPosition(Point p)
  350. {
  351. if (!optiTrackInUse) currentCursorPosition = p;
  352. }
  353. /// <summary>
  354. /// Updates the current cursor position of the model.
  355. /// </summary>
  356. /// <param name="p">The new cursor position</param>
  357. public void SetCurrentFingerPosition(Point p)
  358. {
  359. Console.WriteLine("raw coordinates: " + p.X + ";" + p.Y);
  360. Point correctedPoint = ConvertTo96thsOfInch(p);
  361. Console.WriteLine(correctedPoint.X + "," + correctedPoint.Y);
  362. currentCursorPosition = correctedPoint;
  363. }
  364. private Point ConvertTo96thsOfInch(Point p)
  365. {
  366. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * OPTITRACK_X_SCALE;
  367. double yCoordinate = (OPTITRACK_CANVAS_HEIGHT - (p.Y - OPTITRACK_Y_OFFSET)) * OPTITRACK_Y_SCALE;
  368. return new Point(xCoordinate, yCoordinate);
  369. }
  370. private Point ConvertToPixel(Point p)
  371. {
  372. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * -1 * (/*Anzahl Pixel X-Richtung*/0 / (1.816)) + 0/*1/2 * x-richtung pixel*/; //TODO
  373. double yCoordinate = (((OPTITRACK_CANVAS_HEIGHT + 0/*meter von oberer Rand Leinwand zu oberer Rand Bildschirm*/) - (p.Y - OPTITRACK_Y_OFFSET))) * (/*Anzahl Pixel Y-Richtung*/0 / (1.360));
  374. return new Point(xCoordinate, yCoordinate);
  375. }
  376. /// <summary>
  377. /// Start a new Line, when the Mouse is pressed down.
  378. /// </summary>
  379. public void StartNewLine()
  380. {
  381. if (inDrawingMode)
  382. {
  383. currentLine.Clear();
  384. currentLine.Add(currentCursorPosition);
  385. }
  386. }
  387. /// <summary>
  388. /// Finish the current Line, when the pressed Mouse is released.
  389. /// </summary>
  390. public void FinishCurrentLine()
  391. {
  392. foreach (Point p in currentLine)
  393. {
  394. Console.WriteLine(p.X + ";" + p.Y);
  395. }
  396. if (inDrawingMode && currentLine.Count > 0)
  397. {
  398. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  399. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  400. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  401. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  402. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  403. programPresenter.UpdateRightLines(rightLineList);
  404. currentLine.Clear();
  405. programPresenter.UpdateCurrentLine(currentLine);
  406. }
  407. UpdateUI();
  408. }
  409. public float optiTrackX;
  410. public float optiTrackY;
  411. public float optiTrackZ;
  412. private bool optiTrackInsideDrawingZone = false;
  413. private double WARNING_ZONE_BOUNDARY= 0.10; //5cm
  414. private Armband armband;
  415. void getOptiTrackPosition(OptiTrack.Frame frame)
  416. {
  417. optiTrackX = frame.Trackables[0].X;
  418. optiTrackY = frame.Trackables[0].Y;
  419. optiTrackZ = frame.Trackables[0].Z;
  420. }
  421. /// <summary>
  422. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  423. /// </summary>
  424. public void Tick()
  425. {
  426. if (optiTrackInUse)
  427. {
  428. if (CheckInsideDrawingZone(optiTrackZ))
  429. {
  430. SetCurrentFingerPosition(new Point(optiTrackX, optiTrackY));
  431. if (!optiTrackInsideDrawingZone)
  432. {
  433. optiTrackInsideDrawingZone = true;
  434. StartNewLine();
  435. Console.WriteLine("new line begun");
  436. }
  437. if(optiTrackZ > WARNING_ZONE_BOUNDARY)
  438. {
  439. armband.pushForward();
  440. }
  441. else if(optiTrackZ < -1 * WARNING_ZONE_BOUNDARY)
  442. {
  443. armband.pushBackward();
  444. }
  445. }
  446. else
  447. {
  448. if (optiTrackInsideDrawingZone)
  449. {
  450. optiTrackInsideDrawingZone = false;
  451. FinishCurrentLine();
  452. Console.WriteLine("line finished");
  453. }
  454. }
  455. if(optiTrackX != 0 && optiTrackY != 0 && optiTrackZ != 0) {
  456. projectPointOntoScreen(optiTrackX, optiTrackY);
  457. }
  458. }
  459. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  460. else { previousCursorPosition = currentCursorPosition; }
  461. cursorPositions.Enqueue(currentCursorPosition);
  462. //Drawing
  463. if (optiTrackInUse)
  464. {
  465. if (CheckInsideDrawingZone(optiTrackZ))
  466. {
  467. Console.WriteLine("point added");
  468. currentLine.Add(currentCursorPosition);
  469. programPresenter.UpdateCurrentLine(currentLine);
  470. }
  471. }
  472. else if (inDrawingMode && programPresenter.IsMousePressed())
  473. {
  474. currentLine.Add(currentCursorPosition);
  475. programPresenter.UpdateCurrentLine(currentLine);
  476. }
  477. //Deleting
  478. if (!inDrawingMode && programPresenter.IsMousePressed())
  479. {
  480. List<Point> uncheckedPoints= GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  481. foreach (Point currPoint in uncheckedPoints)
  482. {
  483. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  484. if (linesToDelete.Count > 0)
  485. {
  486. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  487. foreach (int lineID in linesToDelete)
  488. {
  489. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  490. }
  491. RepopulateDeletionMatrixes();
  492. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  493. programPresenter.UpdateRightLines(rightLineList);
  494. }
  495. }
  496. }
  497. }
  498. private void projectPointOntoScreen(float optiTrackX, float optiTrackY)
  499. {
  500. Point auxiliaryPoint = ConvertToPixel(new Point(optiTrackX, optiTrackY));
  501. SetCursorPos((int)auxiliaryPoint.X, (int)auxiliaryPoint.Y);
  502. }
  503. private bool CheckInsideDrawingZone(float optiTrackZ)
  504. {
  505. if (Math.Abs(optiTrackZ) > WARNING_ZONE_BOUNDARY * 2) return false;
  506. return true;
  507. }
  508. /// <summary>
  509. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  510. /// </summary>
  511. /// <param name="CanvasSize">The size of the canvas</param>
  512. public void UpdateSizes(ImageDimension CanvasSize)
  513. {
  514. if (rightImageWithoutOverlay != null)
  515. {
  516. int widthImage = rightImageSize.Width;
  517. int heightImage = rightImageSize.Height;
  518. int widthBox = CanvasSize.Width;
  519. int heightBox = CanvasSize.Height;
  520. float imageRatio = (float)widthImage / (float)heightImage;
  521. float containerRatio = (float)widthBox / (float)heightBox;
  522. float zoomFactor = 0;
  523. if (imageRatio >= containerRatio)
  524. {
  525. //Image is wider than it is high
  526. zoomFactor = (float)widthImage / (float)widthBox;
  527. }
  528. else
  529. {
  530. //Image is higher than it is wide
  531. zoomFactor = (float)heightImage / (float)heightBox;
  532. }
  533. markerRadius = (int)(10 * zoomFactor);
  534. deletionRadius = (int)(5 * zoomFactor);
  535. }
  536. }
  537. /// <summary>
  538. /// If there is unsaved progress.
  539. /// </summary>
  540. /// <returns>True if there is progress that has not been saved.</returns>
  541. public bool HasUnsavedProgress()
  542. {
  543. return !historyOfActions.IsEmpty();
  544. }
  545. }
  546. }