MVP_Model.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 = -2.0877;
  101. double OPTITRACK_X_SCALE = -1 * ((1.816 / 0.0254 * 96) / (1.816));
  102. double OPTITRACK_Y_SCALE = -1 * ((1.360 / 0.0254 * 96) / (1.360));
  103. Image rightImageWithoutOverlay;
  104. List<InternalLine> leftLineList;
  105. List<Tuple<bool, InternalLine>> rightLineList;
  106. List<Point> currentLine = new List<Point>();
  107. public MVP_Model(MVP_Presenter presenter)
  108. {
  109. programPresenter = presenter;
  110. historyOfActions = new ActionHistory();
  111. //redrawAss = new RedrawAssistant();
  112. //overlayItems = new List<Tuple<bool, HashSet<Point>>>();
  113. rightLineList = new List<Tuple<bool, InternalLine>>();
  114. canvasActive = false;
  115. UpdateUI();
  116. rightImageSize = new ImageDimension(0, 0);
  117. leftImageSize = new ImageDimension(0, 0);
  118. connector = new OptiTrackConnector();
  119. armband = new Armband();
  120. if (connector.Init(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  121. {
  122. connector.StartTracking(getOptiTrackPosition);
  123. }
  124. }
  125. [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
  126. private static extern bool SetCursorPos(int X, int Y);
  127. [DllImport("user32.dll")]
  128. public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
  129. public enum MouseEventType : int
  130. {
  131. LeftDown = 0x02,
  132. LeftUp = 0x04,
  133. RightDown = 0x08,
  134. RightUp = 0x10
  135. }
  136. /**************************/
  137. /*** INTERNAL FUNCTIONS ***/
  138. /**************************/
  139. /// <summary>
  140. /// Change the status of whether or not the lines are shown.
  141. /// </summary>
  142. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  143. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  144. private void ChangeLines(HashSet<int> lines, bool shown)
  145. {
  146. foreach (int lineId in lines)
  147. {
  148. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  149. {
  150. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// A function that populates the matrixes needed for deletion detection with line data.
  156. /// </summary>
  157. private void RepopulateDeletionMatrixes()
  158. {
  159. if (canvasActive)
  160. {
  161. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  162. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  163. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  164. {
  165. if (lineTuple.Item1)
  166. {
  167. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  168. }
  169. }
  170. }
  171. }
  172. /// <summary>
  173. /// Tells the Presenter to Update the UI
  174. /// </summary>
  175. private void UpdateUI()
  176. {
  177. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded, optiTrackInUse);
  178. }
  179. /// <summary>
  180. /// A function that checks the deletion matrixes at a certain point
  181. /// and returns all Line ids at that point and in a square around it in a certain range.
  182. /// </summary>
  183. /// <param name="p">The point around which to check.</param>
  184. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  185. /// <returns>A List of all lines.</returns>
  186. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  187. {
  188. HashSet<int> returnSet = new HashSet<int>();
  189. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  190. {
  191. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  192. {
  193. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  194. {
  195. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  196. }
  197. }
  198. }
  199. return returnSet;
  200. }
  201. /********************************************/
  202. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  203. /********************************************/
  204. /// <summary>
  205. /// A function to update the dimensions of the left and right canvas when the window is resized.
  206. /// </summary>
  207. /// <param name="LeftCanvas">The size of the left canvas.</param>
  208. /// <param name="RightCanvas">The size of the right canvas.</param>
  209. public void ResizeEvent(ImageDimension LeftCanvas, ImageDimension RightCanvas)
  210. {
  211. if(LeftCanvas.Height >= 0 && LeftCanvas.Width>= 0) { leftImageSize = LeftCanvas; }
  212. if(RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  213. RepopulateDeletionMatrixes();
  214. }
  215. /// <summary>
  216. /// A function to reset the right image.
  217. /// </summary>
  218. public void ResetRightImage()
  219. {
  220. rightLineList.Clear();
  221. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  222. programPresenter.ClearRightLines();
  223. }
  224. /// <summary>
  225. /// The function to set the left image.
  226. /// </summary>
  227. /// <param name="width">The width of the left image.</param>
  228. /// <param name="height">The height of the left image.</param>
  229. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  230. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  231. {
  232. leftImageSize = new ImageDimension(width, height);
  233. rightImageSize = new ImageDimension(width, height);
  234. leftLineList = listOfLines;
  235. graphicLoaded = true;
  236. programPresenter.UpdateLeftLines(leftLineList);
  237. CanvasActivated();
  238. /*
  239. var workingCanvas = GetEmptyCanvas(width, height);
  240. var workingGraph = Graphics.FromImage(workingCanvas);
  241. leftLineList = listOfLines;
  242. //redrawAss = new RedrawAssistant(leftLineList);
  243. //overlayItems = redrawAss.Initialize(markerRadius);
  244. //Lines
  245. foreach (InternalLine line in leftLineList)
  246. {
  247. line.DrawLine(workingGraph);
  248. }
  249. leftImage = workingCanvas;
  250. programPresenter.UpdateLeftImage(leftImage);
  251. //Set right image to same size as left image and delete linelist
  252. DrawEmptyCanvasRight();
  253. rightLineList = new List<Tuple<bool, InternalLine>>();
  254. */
  255. }
  256. /// <summary>
  257. /// A function to tell the model a new canvas was activated.
  258. /// </summary>
  259. public void CanvasActivated()
  260. {
  261. canvasActive = true;
  262. RepopulateDeletionMatrixes();
  263. UpdateUI();
  264. }
  265. /// <summary>
  266. /// Will undo the last action taken, if the action history allows it.
  267. /// </summary>
  268. public void Undo()
  269. {
  270. if (historyOfActions.CanUndo())
  271. {
  272. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  273. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  274. switch (undoAction)
  275. {
  276. case SketchAction.ActionType.Delete:
  277. //Deleted Lines need to be shown
  278. ChangeLines(affectedLines, true);
  279. break;
  280. case SketchAction.ActionType.Draw:
  281. //Drawn lines need to be hidden
  282. ChangeLines(affectedLines, false);
  283. break;
  284. default:
  285. break;
  286. }
  287. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  288. programPresenter.UpdateRightLines(rightLineList);
  289. }
  290. RepopulateDeletionMatrixes();
  291. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  292. UpdateUI();
  293. }
  294. /// <summary>
  295. /// Will redo the last action undone, if the action history allows it.
  296. /// </summary>
  297. public void Redo()
  298. {
  299. if (historyOfActions.CanRedo())
  300. {
  301. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  302. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  303. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  304. switch (redoAction)
  305. {
  306. case SketchAction.ActionType.Delete:
  307. //Deleted Lines need to be redeleted
  308. ChangeLines(affectedLines, false);
  309. break;
  310. case SketchAction.ActionType.Draw:
  311. //Drawn lines need to be redrawn
  312. ChangeLines(affectedLines, true);
  313. break;
  314. default:
  315. break;
  316. }
  317. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  318. programPresenter.UpdateRightLines(rightLineList);
  319. RepopulateDeletionMatrixes();
  320. }
  321. UpdateUI();
  322. }
  323. /// <summary>
  324. /// The function called by the Presenter to change the drawing state of the program.
  325. /// </summary>
  326. /// <param name="nowDrawing">The new drawingstate of the program</param>
  327. public void ChangeState(bool nowDrawing)
  328. {
  329. inDrawingMode = nowDrawing;
  330. UpdateUI();
  331. }
  332. public void ChangeOptiTrack(bool usingOptiTrack)
  333. {
  334. optiTrackInUse = usingOptiTrack;
  335. }
  336. /// <summary>
  337. /// Updates the current cursor position of the model.
  338. /// </summary>
  339. /// <param name="p">The new cursor position</param>
  340. public void SetCurrentCursorPosition(Point p)
  341. {
  342. if (!optiTrackInUse) currentCursorPosition = p;
  343. }
  344. /// <summary>
  345. /// Updates the current cursor position of the model.
  346. /// </summary>
  347. /// <param name="p">The new cursor position</param>
  348. public void SetCurrentFingerPosition(Point p)
  349. {
  350. Point correctedPoint = ConvertToPixels(p);
  351. currentCursorPosition = p;
  352. }
  353. private Point ConvertToPixels(Point p)
  354. {
  355. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * OPTITRACK_X_SCALE;
  356. double yCoordinate = (p.Y - OPTITRACK_Y_OFFSET) * OPTITRACK_Y_SCALE;
  357. return new Point(xCoordinate, yCoordinate);
  358. }
  359. /// <summary>
  360. /// Start a new Line, when the Mouse is pressed down.
  361. /// </summary>
  362. public void StartNewLine()
  363. {
  364. if (inDrawingMode)
  365. {
  366. currentLine.Clear();
  367. currentLine.Add(currentCursorPosition);
  368. }
  369. }
  370. /// <summary>
  371. /// Finish the current Line, when the pressed Mouse is released.
  372. /// </summary>
  373. public void FinishCurrentLine()
  374. {
  375. if (inDrawingMode && currentLine.Count > 0)
  376. {
  377. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  378. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  379. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  380. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  381. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  382. programPresenter.UpdateRightLines(rightLineList);
  383. currentLine.Clear();
  384. programPresenter.UpdateCurrentLine(currentLine);
  385. }
  386. UpdateUI();
  387. }
  388. public float optiTrackX;
  389. public float optiTrackY;
  390. public float optiTrackZ;
  391. private bool optiTrackInsideDrawingZone;
  392. private double WARNING_ZONE_BOUNDARY= 0.05; //5cm
  393. private Armband armband;
  394. void getOptiTrackPosition(OptiTrack.Frame frame)
  395. {
  396. optiTrackX = frame.Trackables[0].X;
  397. optiTrackY = frame.Trackables[0].Y;
  398. optiTrackZ = frame.Trackables[0].Z;
  399. }
  400. /// <summary>
  401. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  402. /// </summary>
  403. public void Tick()
  404. {
  405. if (optiTrackInUse)
  406. {
  407. if (CheckInsideDrawingZone(optiTrackZ))
  408. {
  409. SetCurrentFingerPosition(new Point(optiTrackX, optiTrackY));
  410. if (!optiTrackInsideDrawingZone)
  411. {
  412. optiTrackInsideDrawingZone = true;
  413. StartNewLine();
  414. }
  415. if(optiTrackZ > WARNING_ZONE_BOUNDARY)
  416. {
  417. armband.pushForward();
  418. }
  419. else if(optiTrackZ < -1 * WARNING_ZONE_BOUNDARY)
  420. {
  421. armband.pushBackward();
  422. }
  423. }
  424. else
  425. {
  426. if (optiTrackInsideDrawingZone)
  427. {
  428. optiTrackInsideDrawingZone = false;
  429. FinishCurrentLine();
  430. }
  431. }
  432. }
  433. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  434. else { previousCursorPosition = currentCursorPosition; }
  435. cursorPositions.Enqueue(currentCursorPosition);
  436. //Drawing
  437. if (inDrawingMode && programPresenter.IsMousePressed())
  438. {
  439. currentLine.Add(currentCursorPosition);
  440. programPresenter.UpdateCurrentLine(currentLine);
  441. }
  442. //Deleting
  443. if (!inDrawingMode && programPresenter.IsMousePressed())
  444. {
  445. List<Point> uncheckedPoints= GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  446. foreach (Point currPoint in uncheckedPoints)
  447. {
  448. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  449. if (linesToDelete.Count > 0)
  450. {
  451. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  452. foreach (int lineID in linesToDelete)
  453. {
  454. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  455. }
  456. RepopulateDeletionMatrixes();
  457. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  458. programPresenter.UpdateRightLines(rightLineList);
  459. }
  460. }
  461. }
  462. }
  463. private bool CheckInsideDrawingZone(float optiTrackZ)
  464. {
  465. if (Math.Abs(optiTrackZ) > WARNING_ZONE_BOUNDARY * 2) return false;
  466. return true;
  467. }
  468. /// <summary>
  469. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  470. /// </summary>
  471. /// <param name="CanvasSize">The size of the canvas</param>
  472. public void UpdateSizes(ImageDimension CanvasSize)
  473. {
  474. if (rightImageWithoutOverlay != null)
  475. {
  476. int widthImage = rightImageSize.Width;
  477. int heightImage = rightImageSize.Height;
  478. int widthBox = CanvasSize.Width;
  479. int heightBox = CanvasSize.Height;
  480. float imageRatio = (float)widthImage / (float)heightImage;
  481. float containerRatio = (float)widthBox / (float)heightBox;
  482. float zoomFactor = 0;
  483. if (imageRatio >= containerRatio)
  484. {
  485. //Image is wider than it is high
  486. zoomFactor = (float)widthImage / (float)widthBox;
  487. }
  488. else
  489. {
  490. //Image is higher than it is wide
  491. zoomFactor = (float)heightImage / (float)heightBox;
  492. }
  493. markerRadius = (int)(10 * zoomFactor);
  494. deletionRadius = (int)(5 * zoomFactor);
  495. }
  496. }
  497. /// <summary>
  498. /// If there is unsaved progress.
  499. /// </summary>
  500. /// <returns>True if there is progress that has not been saved.</returns>
  501. public bool HasUnsavedProgress()
  502. {
  503. return !historyOfActions.IsEmpty();
  504. }
  505. }
  506. }