MVP_Model.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. using System.IO;
  13. using System.IO.Ports;
  14. namespace SketchAssistantWPF
  15. {
  16. public class MVP_Model
  17. {
  18. /// <summary>
  19. /// The Presenter of the MVP-Model.
  20. /// </summary>
  21. MVP_Presenter programPresenter;
  22. /// <summary>
  23. /// History of Actions
  24. /// </summary>
  25. ActionHistory historyOfActions;
  26. /// <summary>
  27. /// The connector class used to get frames from the Optitrack system.
  28. /// </summary>
  29. OptiTrackConnector connector;
  30. /// <summary>
  31. /// intensity of the tectile feedback occuring once every passed centimeter (ranging from 0.0 to 1.0)
  32. /// </summary>
  33. static readonly double TACTILE_SURFACE_FEEDBACK_INTENSITY = 1.0;
  34. /// <summary>
  35. /// duration of the tectile feedback occuring once every passed centimeter (in milliseconds)
  36. /// </summary>
  37. static readonly int TACTILE_SURFACE_FEEDBACK_DURATION = 15;
  38. /***********************/
  39. /*** CLASS VARIABLES ***/
  40. /***********************/
  41. /// <summary>
  42. /// this is a variable used for detecting whether the tracker is in the warning zone (0 +- variable), no drawing zone (0 +- 2 * variable) or normal drawing zone
  43. /// </summary>
  44. readonly double WARNING_ZONE_BOUNDARY = 0.10; //10cm
  45. /// <summary>
  46. /// If the program is in drawing mode.
  47. /// </summary>
  48. public bool inDrawingMode { get; private set; }
  49. /// <summary>
  50. /// if the program is using OptiTrack
  51. /// </summary>
  52. public bool optiTrackInUse { get; private set; }
  53. /// <summary>
  54. /// Size of deletion area
  55. /// </summary>
  56. int deletionRadius = 5;
  57. /// <summary>
  58. /// The Position of the Cursor in the right picture box
  59. /// </summary>
  60. Point currentCursorPosition;
  61. /// <summary>
  62. /// The Previous Cursor Position in the right picture box
  63. /// </summary>
  64. Point previousCursorPosition;
  65. /// <summary>
  66. /// Queue for the cursorPositions
  67. /// </summary>
  68. Queue<Point> cursorPositions = new Queue<Point>();
  69. /// <summary>
  70. /// The Position of the Cursor of opti track
  71. /// </summary>
  72. Point currentOptiCursorPosition;
  73. /// <summary>
  74. /// The Previous Cursor Position of opti track
  75. /// </summary>
  76. Point previousOptiCursorPosition;
  77. /// <summary>
  78. /// Queue for the cursorPositions of opti track
  79. /// </summary>
  80. Queue<Point> optiCursorPositions = new Queue<Point>();
  81. /// <summary>
  82. /// Lookup Matrix for checking postions of lines in the image
  83. /// </summary>
  84. bool[,] isFilledMatrix;
  85. /// <summary>
  86. /// Lookup Matrix for getting line ids at a certain postions of the image
  87. /// </summary>
  88. HashSet<int>[,] linesMatrix;
  89. /// <summary>
  90. /// Width of the LeftImageBox.
  91. /// </summary>
  92. public int leftImageBoxWidth;
  93. /// <summary>
  94. /// Height of the LeftImageBox.
  95. /// </summary>
  96. public int leftImageBoxHeight;
  97. /// <summary>
  98. /// Width of the RightImageBox.
  99. /// </summary>
  100. public int rightImageBoxWidth;
  101. /// <summary>
  102. /// Height of the RightImageBox.
  103. /// </summary>
  104. public int rightImageBoxHeight;
  105. /// <summary>
  106. /// The size of the right canvas.
  107. /// </summary>
  108. public ImageDimension rightImageSize { get; private set; }
  109. /// <summary>
  110. /// Indicates whether or not the canvas on the right side is active.
  111. /// </summary>
  112. public bool canvasActive { get; set; }
  113. /// <summary>
  114. /// Indicates if there is a graphic loaded in the left canvas.
  115. /// </summary>
  116. public bool graphicLoaded { get; set; }
  117. /// <summary>
  118. /// Whether or not an optitrack system is avaiable.
  119. /// </summary>
  120. public bool optitrackAvailable { get; private set; }
  121. /// <summary>
  122. /// x coordinate in real world. one unit is one meter. If standing in front of video wall facing it, moving left results in incrementation of x.
  123. /// </summary>
  124. public float optiTrackX;
  125. /// <summary>
  126. /// y coordinate in real world. one unit is one meter. If standing in front of video wall, moving up results in incrementation of y.
  127. /// </summary>
  128. public float optiTrackY;
  129. /// <summary>
  130. /// z coordinate in real world. one unit is one meter. If standing in front of video wall, moving back results in incrementation of y.
  131. /// </summary>
  132. public float optiTrackZ;
  133. /// <summary>
  134. /// keeps track of whether last tick the trackable was inside drawing zone or not.
  135. /// </summary>
  136. private bool optiTrackInsideDrawingZone = false;
  137. /// <summary>
  138. /// object of class wristband used for controlling the vibrotactile wristband
  139. /// </summary>
  140. private Wristband wristband;
  141. /// <summary>
  142. /// Is set to true when the trackable has passed to the backside of the drawing surface,
  143. /// invalidating all inputs on its way back.
  144. /// </summary>
  145. bool OptiMovingBack = false;
  146. /// <summary>
  147. /// The Layer in which the optitrack system was. 0 is drawing layer, -1 is in front, 1 is behind
  148. /// </summary>
  149. int OptiLayer = 0;
  150. /// <summary>
  151. /// The path traveled since the last tick
  152. /// </summary>
  153. double PathTraveled = 0;
  154. /// <summary>
  155. /// Whether or not the mouse is pressed.
  156. /// </summary>
  157. private bool mouseDown;
  158. /// <summary>
  159. /// A List of lines in the left canvas.
  160. /// </summary>
  161. List<InternalLine> leftLineList;
  162. /// <summary>
  163. /// A list of lines in the right canvas along with a boolean indicating if they should be drawn.
  164. /// </summary>
  165. List<Tuple<bool, InternalLine>> rightLineList;
  166. /// <summary>
  167. /// The line currently being drawin with optitrack.
  168. /// </summary>
  169. List<Point> currentLine = new List<Point>();
  170. /// <summary>
  171. /// If the COM5 port is available.
  172. /// </summary>
  173. bool comFiveAvailable = false;
  174. public MVP_Model(MVP_Presenter presenter)
  175. {
  176. //TODO remove
  177. var portName = "COM5";
  178. var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0);
  179. if (isValid)
  180. {
  181. Console.WriteLine("trying to initialize Armband...");
  182. int tmp = LocalArmbandInterface.SetupArmband();
  183. Console.WriteLine("Armband initialization terminated, exit code: " + tmp);
  184. comFiveAvailable = true;
  185. }
  186. else
  187. {
  188. Console.WriteLine("COM5 device not found");
  189. }
  190. programPresenter = presenter;
  191. historyOfActions = new ActionHistory();
  192. rightLineList = new List<Tuple<bool, InternalLine>>();
  193. canvasActive = false;
  194. UpdateUI();
  195. rightImageSize = new ImageDimension(0, 0);
  196. connector = new OptiTrackConnector();
  197. wristband = new Wristband();
  198. //Set up Optitrack
  199. optitrackAvailable = false;
  200. if (File.Exists(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  201. {
  202. if (connector.Init(@"C:\Users\videowall-pc-user\Documents\BP-SketchAssistant\SketchAssistant\optitrack_setup.ttp"))
  203. {
  204. optitrackAvailable = true;
  205. connector.StartTracking(GetOptiTrackPosition);
  206. }
  207. }
  208. }
  209. /**************************/
  210. /*** INTERNAL FUNCTIONS ***/
  211. /**************************/
  212. /// <summary>
  213. /// Check if the Optitrack trackable is in the drawing plane.
  214. /// </summary>
  215. /// <param name="optiTrackZ">The real world z coordinates of the trackable.</param>
  216. /// <returns>If the trackable is in front of the drawing plane</returns>
  217. private bool CheckInsideDrawingZone(float optiTrackZ)
  218. {
  219. if (Math.Abs(optiTrackZ) > WARNING_ZONE_BOUNDARY * 2) return false;
  220. return true;
  221. }
  222. /// <summary>
  223. /// Function that is called by the OptitrackController to pass frames to the model.
  224. /// </summary>
  225. /// <param name="frame">An Optitrack Frame</param>
  226. void GetOptiTrackPosition(OptiTrack.Frame frame)
  227. {
  228. if (frame.Trackables.Length >= 1)
  229. {
  230. optiTrackX = frame.Trackables[0].X;
  231. optiTrackY = frame.Trackables[0].Y;
  232. optiTrackZ = frame.Trackables[0].Z;
  233. }
  234. }
  235. /// <summary>
  236. /// Change the status of whether or not the lines are shown.
  237. /// </summary>
  238. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  239. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  240. private void ChangeLines(HashSet<int> lines, bool shown)
  241. {
  242. foreach (int lineId in lines)
  243. {
  244. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  245. {
  246. rightLineList[lineId] = new Tuple<bool, InternalLine>(shown, rightLineList[lineId].Item2);
  247. }
  248. }
  249. }
  250. /// <summary>
  251. /// Check if enough distance has been travelled to warrant a vibration.
  252. /// </summary>
  253. private void CheckPathTraveled()
  254. {
  255. var a = Math.Abs(previousOptiCursorPosition.X - currentOptiCursorPosition.X);
  256. var b = Math.Abs(previousOptiCursorPosition.Y - currentOptiCursorPosition.Y);
  257. PathTraveled += Math.Sqrt(Math.Pow(a,2) + Math.Pow(b,2));
  258. //Set the Interval of vibrations here
  259. if(PathTraveled > 15)
  260. {
  261. PathTraveled = 0;
  262. if(comFiveAvailable)
  263. LocalArmbandInterface.Actuate(0, TACTILE_SURFACE_FEEDBACK_INTENSITY, TACTILE_SURFACE_FEEDBACK_DURATION);
  264. }
  265. }
  266. /// <summary>
  267. /// A function that populates the matrixes needed for deletion detection with line data.
  268. /// </summary>
  269. private void RepopulateDeletionMatrixes()
  270. {
  271. if (canvasActive)
  272. {
  273. isFilledMatrix = new bool[rightImageSize.Width, rightImageSize.Height];
  274. linesMatrix = new HashSet<int>[rightImageSize.Width, rightImageSize.Height];
  275. foreach (Tuple<bool, InternalLine> lineTuple in rightLineList)
  276. {
  277. if (lineTuple.Item1)
  278. {
  279. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  280. }
  281. }
  282. }
  283. }
  284. /// <summary>
  285. /// Tells the Presenter to Update the UI
  286. /// </summary>
  287. private void UpdateUI()
  288. {
  289. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), canvasActive, graphicLoaded, optitrackAvailable, optiTrackInUse);
  290. }
  291. /// <summary>
  292. /// A function that checks the deletion matrixes at a certain point
  293. /// and returns all Line ids at that point and in a square around it in a certain range.
  294. /// </summary>
  295. /// <param name="p">The point around which to check.</param>
  296. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  297. /// <returns>A List of all lines.</returns>
  298. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  299. {
  300. HashSet<int> returnSet = new HashSet<int>();
  301. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  302. {
  303. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageSize.Width && pnt.Y < rightImageSize.Height)
  304. {
  305. if (isFilledMatrix[(int)pnt.X, (int)pnt.Y])
  306. {
  307. returnSet.UnionWith(linesMatrix[(int)pnt.X, (int)pnt.Y]);
  308. }
  309. }
  310. }
  311. return returnSet;
  312. }
  313. /// <summary>
  314. /// Converts given point to device-independent pixel.
  315. /// </summary>
  316. /// <param name="p">real world coordinate</param>
  317. /// <returns>The given Point converted to device-independent pixel </returns>
  318. private Point ConvertTo96thsOfInch(Point p)
  319. {
  320. //The position of the optitrack coordinate system
  321. // and sizes of the optitrack tracking area relative to the canvas.
  322. double OPTITRACK_X_OFFSET = -0.4854;
  323. double OPTITRACK_Y_OFFSET = 0.9;
  324. double OPTITRACK_CANVAS_HEIGHT = 1.2;
  325. double OPTITRACK_X_SCALE = 0.21 * (((1.8316/*size of canvas*/ / 0.0254) * 96) / (1.8316));
  326. double OPTITRACK_Y_SCALE = 0.205 * (((1.2 / 0.0254) * 96) / (1.2));
  327. //The coordinates on the display
  328. double xCoordinate = (p.X - OPTITRACK_X_OFFSET) * OPTITRACK_X_SCALE;
  329. double yCoordinate = (OPTITRACK_CANVAS_HEIGHT - (p.Y - OPTITRACK_Y_OFFSET)) * OPTITRACK_Y_SCALE;
  330. return new Point(xCoordinate, yCoordinate);
  331. }
  332. /// <summary>
  333. /// Updates the Optitrack coordiantes, aswell as the marker for optitrack.
  334. /// </summary>
  335. /// <param name="p">The new cursor position</param>
  336. private void SetCurrentFingerPosition(Point p)
  337. {
  338. Point correctedPoint = ConvertTo96thsOfInch(p);
  339. if (optiTrackZ < -2.2 * WARNING_ZONE_BOUNDARY && OptiLayer > -1)
  340. {
  341. OptiLayer = -1; OptiMovingBack = false;
  342. programPresenter.SetOverlayColor("optipoint", Brushes.Yellow);
  343. }
  344. else if (optiTrackZ > 2 * WARNING_ZONE_BOUNDARY && OptiLayer < 1)
  345. {
  346. programPresenter.SetOverlayColor("optipoint", Brushes.Red);
  347. OptiLayer = 1;
  348. }
  349. else if(optiTrackZ <= 2 * WARNING_ZONE_BOUNDARY && optiTrackZ >= -2.2 * WARNING_ZONE_BOUNDARY){
  350. if(OptiLayer > 0)
  351. OptiMovingBack = true;
  352. programPresenter.SetOverlayColor("optipoint", Brushes.Green);
  353. OptiLayer = 0;
  354. }
  355. currentOptiCursorPosition = correctedPoint;
  356. programPresenter.MoveOptiPoint(currentOptiCursorPosition);
  357. if (optiCursorPositions.Count > 0) { previousOptiCursorPosition = optiCursorPositions.Dequeue(); }
  358. else { previousOptiCursorPosition = currentOptiCursorPosition; }
  359. optiCursorPositions.Enqueue(currentOptiCursorPosition);
  360. }
  361. /********************************************/
  362. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  363. /********************************************/
  364. /// <summary>
  365. /// A function to update the dimensions of the left and right canvas when the window is resized.
  366. /// </summary>
  367. /// <param name="RightCanvas">The size of the right canvas.</param>
  368. public void ResizeEvent(ImageDimension RightCanvas)
  369. {
  370. if (RightCanvas.Height >= 0 && RightCanvas.Width >= 0) { rightImageSize = RightCanvas; }
  371. RepopulateDeletionMatrixes();
  372. }
  373. /// <summary>
  374. /// A function to reset the right image.
  375. /// </summary>
  376. public void ResetRightImage()
  377. {
  378. if(currentLine.Count > 0)
  379. FinishCurrentLine(true);
  380. rightLineList.Clear();
  381. programPresenter.PassLastActionTaken(historyOfActions.Reset());
  382. programPresenter.ClearRightLines();
  383. }
  384. /// <summary>
  385. /// The function to set the left image.
  386. /// </summary>
  387. /// <param name="width">The width of the left image.</param>
  388. /// <param name="height">The height of the left image.</param>
  389. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  390. public void SetLeftLineList(int width, int height, List<InternalLine> listOfLines)
  391. {
  392. rightImageSize = new ImageDimension(width, height);
  393. leftLineList = listOfLines;
  394. graphicLoaded = true;
  395. programPresenter.UpdateLeftLines(leftLineList);
  396. CanvasActivated();
  397. }
  398. /// <summary>
  399. /// A function to tell the model a new canvas was activated.
  400. /// </summary>
  401. public void CanvasActivated()
  402. {
  403. canvasActive = true;
  404. RepopulateDeletionMatrixes();
  405. UpdateUI();
  406. }
  407. /// <summary>
  408. /// Will undo the last action taken, if the action history allows it.
  409. /// </summary>
  410. public void Undo()
  411. {
  412. if (historyOfActions.CanUndo())
  413. {
  414. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  415. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  416. switch (undoAction)
  417. {
  418. case SketchAction.ActionType.Delete:
  419. //Deleted Lines need to be shown
  420. ChangeLines(affectedLines, true);
  421. break;
  422. case SketchAction.ActionType.Draw:
  423. //Drawn lines need to be hidden
  424. ChangeLines(affectedLines, false);
  425. break;
  426. default:
  427. break;
  428. }
  429. programPresenter.UpdateRightLines(rightLineList);
  430. }
  431. RepopulateDeletionMatrixes();
  432. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  433. UpdateUI();
  434. }
  435. /// <summary>
  436. /// Will redo the last action undone, if the action history allows it.
  437. /// </summary>
  438. public void Redo()
  439. {
  440. if (historyOfActions.CanRedo())
  441. {
  442. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  443. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  444. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  445. switch (redoAction)
  446. {
  447. case SketchAction.ActionType.Delete:
  448. //Deleted Lines need to be redeleted
  449. ChangeLines(affectedLines, false);
  450. break;
  451. case SketchAction.ActionType.Draw:
  452. //Drawn lines need to be redrawn
  453. ChangeLines(affectedLines, true);
  454. break;
  455. default:
  456. break;
  457. }
  458. programPresenter.UpdateRightLines(rightLineList);
  459. RepopulateDeletionMatrixes();
  460. }
  461. UpdateUI();
  462. }
  463. /// <summary>
  464. /// The function called by the Presenter to change the drawing state of the program.
  465. /// </summary>
  466. /// <param name="nowDrawing">The new drawingstate of the program</param>
  467. public void ChangeState(bool nowDrawing)
  468. {
  469. if(inDrawingMode && !nowDrawing && currentLine.Count > 0 && optiTrackInUse)
  470. FinishCurrentLine(true);
  471. inDrawingMode = nowDrawing;
  472. UpdateUI();
  473. }
  474. /// <summary>
  475. /// The function called by the Presenter to set a variable which describes if OptiTrack is in use
  476. /// </summary>
  477. /// <param name="usingOptiTrack">The status of optitrack button</param>
  478. public void SetOptiTrack(bool usingOptiTrack)
  479. {
  480. optiTrackInUse = usingOptiTrack;
  481. if (usingOptiTrack && optiTrackX == 0 && optiTrackY == 0 && optiTrackZ == 0)
  482. {
  483. programPresenter.PassWarning("Trackable not detected, please check if OptiTrack is activated and Trackable is recognized");
  484. optiTrackInUse = false;
  485. //Disable optipoint
  486. programPresenter.SetOverlayStatus("optipoint", false, currentCursorPosition);
  487. }
  488. else
  489. {
  490. //Enable optipoint
  491. programPresenter.SetOverlayStatus("optipoint", true, currentCursorPosition);
  492. }
  493. }
  494. /// <summary>
  495. /// Updates the current cursor position of the model.
  496. /// </summary>
  497. /// <param name="p">The new cursor position</param>
  498. public void SetCurrentCursorPosition(Point p)
  499. {
  500. currentCursorPosition = p;
  501. mouseDown = programPresenter.IsMousePressed();
  502. }
  503. /// <summary>
  504. /// Start a new Line, when the Mouse is pressed down.
  505. /// </summary>
  506. public void StartNewLine()
  507. {
  508. mouseDown = true;
  509. if (inDrawingMode)
  510. {
  511. if(optiTrackInUse)
  512. {
  513. currentLine.Clear();
  514. currentLine.Add(currentOptiCursorPosition);
  515. }
  516. else if (programPresenter.IsMousePressed())
  517. {
  518. currentLine.Clear();
  519. currentLine.Add(currentCursorPosition);
  520. }
  521. }
  522. }
  523. /// <summary>
  524. /// Finish the current Line, when the pressed Mouse is released.
  525. /// </summary>
  526. /// <param name="valid">Whether the up event is valid or not</param>
  527. public void FinishCurrentLine(bool valid)
  528. {
  529. mouseDown = false;
  530. if (valid)
  531. {
  532. if (inDrawingMode && currentLine.Count > 0)
  533. {
  534. InternalLine newLine = new InternalLine(currentLine, rightLineList.Count);
  535. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  536. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  537. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  538. //TODO: For the person implementing overlay: Add check if overlay needs to be added
  539. programPresenter.UpdateRightLines(rightLineList);
  540. currentLine.Clear();
  541. programPresenter.UpdateCurrentLine(currentLine);
  542. }
  543. }
  544. else
  545. {
  546. currentLine.Clear();
  547. }
  548. UpdateUI();
  549. }
  550. /// <summary>
  551. /// Finish the current Line, when the pressed Mouse is released.
  552. /// Overload that is used to pass a list of points to be used when one is available.
  553. /// </summary>
  554. /// <param name="p">The list of points</param>
  555. public void FinishCurrentLine(List<Point> p)
  556. {
  557. mouseDown = false;
  558. if (inDrawingMode && currentLine.Count > 0)
  559. {
  560. InternalLine newLine = new InternalLine(p, rightLineList.Count);
  561. rightLineList.Add(new Tuple<bool, InternalLine>(true, newLine));
  562. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  563. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  564. programPresenter.UpdateRightLines(rightLineList);
  565. currentLine.Clear();
  566. }
  567. UpdateUI();
  568. }
  569. /// <summary>
  570. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  571. /// </summary>
  572. public void Tick()
  573. {
  574. //Show startpoints
  575. if (leftLineList != null && leftLineList.Count > 0)
  576. {
  577. var templist = rightLineList.Where(tup => tup.Item1).ToList();
  578. if (templist.Count < leftLineList.Count)
  579. {
  580. programPresenter.SetOverlayStatus("startpoint", true, leftLineList[templist.Count].GetPoints()[0]);
  581. }
  582. else
  583. {
  584. programPresenter.SetOverlayStatus("startpoint", false, new Point(50, 50));
  585. }
  586. }
  587. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  588. else { previousCursorPosition = currentCursorPosition; }
  589. if(optitrackAvailable)
  590. SetCurrentFingerPosition(new Point(optiTrackX, optiTrackY));
  591. if (optiTrackInUse && inDrawingMode && !OptiMovingBack) // optitrack is being used
  592. {
  593. //outside of drawing zone
  594. if (!CheckInsideDrawingZone(optiTrackZ))
  595. {
  596. //Check if trackable was in drawing zone last tick & program is in drawing mode-> finish line
  597. if (optiTrackInsideDrawingZone && inDrawingMode)
  598. {
  599. optiTrackInsideDrawingZone = false;
  600. FinishCurrentLine(true);
  601. }
  602. }
  603. else //Draw with optitrack, when in drawing zone
  604. {
  605. //Optitrack wasn't in the drawing zone last tick -> start a new line
  606. if (!optiTrackInsideDrawingZone)
  607. {
  608. optiTrackInsideDrawingZone = true;
  609. StartNewLine();
  610. }
  611. else currentLine.Add(currentOptiCursorPosition);
  612. programPresenter.UpdateCurrentLine(currentLine);
  613. if (optiTrackZ > WARNING_ZONE_BOUNDARY)
  614. {
  615. wristband.PushForward();
  616. }
  617. else if (optiTrackZ < -1 * WARNING_ZONE_BOUNDARY)
  618. {
  619. wristband.PushBackward();
  620. }
  621. CheckPathTraveled();
  622. }
  623. }
  624. else if( !optiTrackInUse && inDrawingMode)
  625. {
  626. //drawing without optitrack
  627. cursorPositions.Enqueue(currentCursorPosition);
  628. if (inDrawingMode && programPresenter.IsMousePressed())
  629. {
  630. currentLine.Add(currentCursorPosition);
  631. //programPresenter.UpdateCurrentLine(currentLine);
  632. }
  633. }
  634. //Deletion mode for optitrack and regular use
  635. if (!inDrawingMode)
  636. {
  637. List<Point> uncheckedPoints = new List<Point>();
  638. if (programPresenter.IsMousePressed() && !optiTrackInUse) //without optitrack
  639. uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  640. if(optiTrackInUse && CheckInsideDrawingZone(optiTrackZ) && !OptiMovingBack) //with optitrack
  641. uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousOptiCursorPosition, currentOptiCursorPosition);
  642. foreach (Point currPoint in uncheckedPoints)
  643. {
  644. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  645. if (linesToDelete.Count > 0)
  646. {
  647. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  648. foreach (int lineID in linesToDelete)
  649. {
  650. rightLineList[lineID] = new Tuple<bool, InternalLine>(false, rightLineList[lineID].Item2);
  651. }
  652. RepopulateDeletionMatrixes();
  653. programPresenter.UpdateRightLines(rightLineList);
  654. }
  655. }
  656. }
  657. /*
  658. if (programPresenter.IsMousePressed()) //TODO only use if optitrack is in use (currently only available on different branch)
  659. {
  660. if(CentimeterGridPassed(previousCursorPosition, currentCursorPosition)) //TODO replace with optitrack coordinates (and introduce a buffer for previous real-world coordinates)
  661. {
  662. LocalArmbandInterface.Actuate(0, TACTILE_SURFACE_FEEDBACK_INTENSITY, TACTILE_SURFACE_FEEDBACK_DURATION);
  663. }
  664. }
  665. */
  666. }
  667. /// <summary>
  668. /// checks if the centimeter grid has been passed since the last tick and a vibrotactile feedback has to be sent to the user
  669. /// a high enough tick rate must be ensured to provide a useful feedback and avoid skipping necessary feedback
  670. /// </summary>
  671. /// <param name="previousCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the last tick</param>
  672. /// <param name="currentCursorPosition">the curser position in real world coordinates (obtained from Optitrack) at the current tick</param>
  673. /// <returns>true iff the grid has been passed</returns>
  674. private bool CentimeterGridPassed(Point previousCursorPositionRealWorldCoordinates, Point currentCursorPositionRealWorldCoordinates)
  675. {
  676. //truncate coordiates to int after converting to centimeters (from meters),
  677. if ((int)(previousCursorPositionRealWorldCoordinates.X * 100) != (int)(currentCursorPositionRealWorldCoordinates.X * 100)) return true;
  678. if ((int)(previousCursorPositionRealWorldCoordinates.Y * 100) != (int)(currentCursorPositionRealWorldCoordinates.Y * 100)) return true;
  679. return false;
  680. }
  681. /*
  682. /// <summary>
  683. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  684. /// </summary>
  685. /// <param name="CanvasSize">The size of the canvas</param>
  686. public void UpdateSizes(ImageDimension CanvasSize)
  687. {
  688. if (rightImageWithoutOverlay != null)
  689. {
  690. int widthImage = rightImageSize.Width;
  691. int heightImage = rightImageSize.Height;
  692. int widthBox = CanvasSize.Width;
  693. int heightBox = CanvasSize.Height;
  694. float imageRatio = (float)widthImage / (float)heightImage;
  695. float containerRatio = (float)widthBox / (float)heightBox;
  696. float zoomFactor = 0;
  697. if (imageRatio >= containerRatio)
  698. {
  699. //Image is wider than it is high
  700. zoomFactor = (float)widthImage / (float)widthBox;
  701. }
  702. else
  703. {
  704. //Image is higher than it is wide
  705. zoomFactor = (float)heightImage / (float)heightBox;
  706. }
  707. markerRadius = (int)(10 * zoomFactor);
  708. deletionRadius = (int)(5 * zoomFactor);
  709. }
  710. }
  711. */
  712. /// <summary>
  713. /// If there is unsaved progress.
  714. /// </summary>
  715. /// <returns>True if there is progress that has not been saved.</returns>
  716. public bool HasUnsavedProgress()
  717. {
  718. return !historyOfActions.IsEmpty();
  719. }
  720. }
  721. }