FileImporter.cs 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. namespace SketchAssistant
  10. {
  11. public class FileImporter
  12. {
  13. /// <summary>
  14. /// scale factor for coordinates of svg file
  15. /// </summary>
  16. double scale;
  17. /// <summary>
  18. /// line pointer for the current svg document
  19. /// </summary>
  20. int i;
  21. /// <summary>
  22. /// array containing all characters interpreted as whitespaces which seperate words/tokens in the input file
  23. /// </summary>
  24. readonly char[] whitespaces = new char[] { ' ' , ',' };
  25. /// <summary>
  26. /// number of points to create along the outline of an ellipse, divisible by 4
  27. /// </summary>
  28. readonly int samplingRateEllipse = 12;
  29. /// <summary>
  30. /// number of points to create on a bezier curve, including start and end point (even numbr will result in "flat" bezier curves, uneven number in "pointed" ones
  31. /// </summary>
  32. readonly int samplingRateBezier = 101;
  33. public FileImporter()
  34. {
  35. }
  36. /// <summary>
  37. /// parses a drawing consisting of line objects, given as a file in the application specific .isad format
  38. /// </summary>
  39. /// <param name="fileName">the path of the input file</param>
  40. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  41. public (int, int, List<Line>) ParseISADInputFile(String fileName)
  42. {
  43. return ParseISADInput(System.IO.File.ReadAllLines(fileName));
  44. }
  45. /// <summary>
  46. /// parses a drawing consisting of line objects, given as the content of a .isad file, seperated into lines
  47. /// </summary>
  48. /// <param name="allLines">an array holding all lines of the input file</param>
  49. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  50. private (int, int, List<Line>) ParseISADInput(String[] allLines)
  51. {
  52. if (allLines.Length == 0)
  53. {
  54. throw new FileImporterException("file is empty", "", -1);
  55. }
  56. if (!"drawing".Equals(allLines[0]))
  57. {
  58. throw new FileImporterException("file is not an interactive sketch assistant drawing", ".isad files have to start with the 'drawing' token", 1);
  59. }
  60. if (!"enddrawing".Equals(allLines[allLines.Length - 1]))
  61. {
  62. throw new FileImporterException("unterminated drawing definition", ".isad files have to end with the 'enddrawing' token", allLines.Length);
  63. }
  64. (int, int) dimensions = ParseISADHeader(allLines);
  65. List<Line> picture = ParseISADBody(allLines, dimensions.Item1, dimensions.Item2);
  66. return (dimensions.Item1, dimensions.Item2, picture);
  67. }
  68. /// <summary>
  69. /// parses the first two lines of an input file in .isad format
  70. /// </summary>
  71. /// <param name="allLines">the input file as an array of lines</param>
  72. /// <returns>the width and height of the left canvas</returns>
  73. private (int, int) ParseISADHeader(String[] allLines)
  74. {
  75. int width;
  76. int height;
  77. if (!(allLines.Length > 1) || !Regex.Match(allLines[1], @"^\d+x?\d+$", RegexOptions.None).Success)
  78. {
  79. throw new FileImporterException("invalid or missing canvas size definition", "format: [width]x[heigth]", 2);
  80. }
  81. String[] size = allLines[1].Split('x');
  82. width = Convert.ToInt32(size[0]);
  83. height = Convert.ToInt32(size[1]);
  84. return (width, height);
  85. }
  86. /// <summary>
  87. /// parses all line entries of an input file in .isad format
  88. /// </summary>
  89. /// <param name="allLines">the input file as an array of lines</param>
  90. /// <returns>the parsed picture as a list of lines</returns>
  91. private List<Line> ParseISADBody(String[] allLines, int width, int height)
  92. {
  93. String lineStartString = "line";
  94. String lineEndString = "endline";
  95. List<Line> drawing = new List<Line>();
  96. //number of the line currently being parsed, enumeration starting at 0, body starts at the third line, therefore lin number 2
  97. int i = 2;
  98. //parse 'line' token and complete line definition
  99. int lineStartPointer = i;
  100. //holds the line number of the next expected beginning of a line definition, or of the enddrawing token
  101. while (lineStartString.Equals(allLines[i]))
  102. {
  103. //start parsing next line
  104. i++;
  105. List<Point> newLine = new List<Point>();
  106. while (!lineEndString.Equals(allLines[i]))
  107. {
  108. if (i == allLines.Length)
  109. {
  110. throw new FileImporterException("unterminated line definition", null, (i + 1));
  111. }
  112. //parse single point definition
  113. if (!Regex.Match(allLines[i], @"^\d+;\d+$", RegexOptions.None).Success)
  114. {
  115. throw new FileImporterException("invalid Point definition: wrong format", "format: [xCoordinate];[yCoordinate]", (i + 1) );
  116. }
  117. String[] coordinates = allLines[i].Split(';');
  118. //no errors possible, convertability to int already checked above
  119. int xCoordinate = Convert.ToInt32(coordinates[0]);
  120. int yCoordinate = Convert.ToInt32(coordinates[1]);
  121. if (xCoordinate < 0 || yCoordinate < 0 || xCoordinate > width - 1 || yCoordinate > height - 1)
  122. {
  123. throw new FileImporterException("invalid Point definition: point out of bounds", null, (i + 1) );
  124. }
  125. newLine.Add(new Point(xCoordinate, yCoordinate));
  126. //start parsing next line
  127. i++;
  128. }
  129. //"parse" 'endline' token, syntax already checked at the beginning, and start parsing next line
  130. i++;
  131. //add line to drawing
  132. drawing.Add(new Line(newLine));
  133. //update lineStartPointer to the presumable start of the next line
  134. lineStartPointer = i;
  135. }
  136. //check if end of body is reached after there are no more line definitions
  137. if(i != allLines.Length - 1)
  138. {
  139. throw new FileImporterException("missing or invalid line definition token", "line definitions start with the 'line' token", (i + 1));
  140. }
  141. //return parsed picture
  142. return drawing;
  143. }
  144. /// <summary>
  145. /// connection point for testing use only: calls ParseISADInput(String[] allLines) and directly passes the given argument (effectively bypassing the File Input functionality)
  146. /// </summary>
  147. /// <param name="allLines">an array holding all lines of the input file</param>
  148. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  149. public (int, int, List<Line>) ParseISADInputForTesting(String[] allLines)
  150. {
  151. return ParseISADInput(allLines);
  152. }
  153. /// <summary>
  154. /// parses a svg drawing, given as a .svg file
  155. /// </summary>
  156. /// <param name="fileName">the path of the input file</param>
  157. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  158. public (int, int, List<Line>) ParseSVGInputFile(String fileName, int windowWidth, int windowHeight)
  159. {
  160. return ParseSVGInput(System.IO.File.ReadAllLines(fileName), windowWidth, windowHeight);
  161. }
  162. /// <summary>
  163. /// parses a svg drawing, given as the content of a .svg file, seperated into lines
  164. /// </summary>
  165. /// <param name="allLines">an array holding all lines of the input file</param>
  166. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  167. private (int, int, List<Line>) ParseSVGInput(String[] allLines, double windowWidth, double windowHeight)
  168. {
  169. i = 0; //reset line pointer
  170. if (allLines.Length == 0) //check for empty file
  171. {
  172. throw new FileImporterException("file is empty", "", -1);
  173. }
  174. (int, int) sizedef = ParseSVGHeader(allLines); //parse svg file header and get internal coordinate range
  175. i++;
  176. int width; //width of the resulting picture in pixels
  177. int height; //height of the resulting picture in pixels
  178. if (windowWidth / windowHeight > sizedef.Item1 / sizedef.Item2) //height dominant, width has to be smaller than drawing window to preserve xy-scale
  179. {
  180. scale = windowHeight / sizedef.Item2;
  181. Console.WriteLine("scale: (heights) " + windowHeight + "/" + sizedef.Item2);
  182. Console.WriteLine("widths: " + windowWidth + "/" + sizedef.Item1);
  183. height = (int)Math.Round(windowHeight);
  184. width = (int) Math.Round(scale * sizedef.Item1);
  185. Console.WriteLine(width + "x" + height + " (" + scale + ")");
  186. }
  187. else //width dominant, height has to be smaller than drawing window to preserve xy-scale
  188. {
  189. scale = windowWidth / sizedef.Item1;
  190. Console.WriteLine("scale: (widths) " + windowWidth + "/" + sizedef.Item1);
  191. Console.WriteLine("heights: " + windowHeight + "/" + sizedef.Item2);
  192. width = (int)Math.Round(windowWidth);
  193. height = (int)Math.Round(scale * sizedef.Item2);
  194. Console.WriteLine(width + "x" + height + " (" + scale + ")");
  195. }
  196. for(int j=0; j < allLines.Length; j++)
  197. {
  198. allLines[j] = allLines[j].Trim(whitespaces);
  199. }
  200. List<Line> picture = ParseSVGBody(allLines); //parse whole svg drawing into list of lines
  201. return (width, height, picture);
  202. }
  203. /// <summary>
  204. /// parses the svg file header and returns the internal coordinate range of this drawing, and iterates i to point to the start of svg element definitions
  205. /// </summary>
  206. /// <param name="allLines">an array holding all lines of the input file</param>
  207. /// <returns>the internal coordinate range of this drawing</returns>
  208. private (int, int) ParseSVGHeader(String[] allLines)
  209. {
  210. while (!allLines[i].StartsWith("<svg")) //skip non-relevant metadata at start of svg file
  211. {
  212. i++;
  213. }
  214. String[] currentLine = allLines[i].Split(' ');
  215. int width= -1;
  216. int height= -1;
  217. for(int j= 0; j < currentLine.Length; j++)
  218. {
  219. if (currentLine[j].StartsWith("width"))
  220. {
  221. width = Convert.ToInt32(ParseSingleSVGAttribute(currentLine[j]));
  222. }
  223. else if (currentLine[j].StartsWith("height"))
  224. {
  225. height = Convert.ToInt32(ParseSingleSVGAttribute(currentLine[j]));
  226. }
  227. }
  228. if(width == -1)
  229. {
  230. throw new FileImporterException("missing width definition in SVG header", "the header should contain the \"width=...\" attribute", i+1);
  231. }
  232. if (height == -1)
  233. {
  234. throw new FileImporterException("missing height definition in SVG header", "the header should contain the \"height=...\" attribute", i + 1);
  235. }
  236. return (width, height);
  237. }
  238. /// <summary>
  239. /// parses all relevant svg element definitions and skips the ones not representable by the sketch assistant
  240. /// </summary>
  241. /// <param name="allLines">an array holding all lines of the input file</param>
  242. /// <returns>the parsed picture as a list of lines</returns>
  243. private List<Line> ParseSVGBody(String[] allLines)
  244. {
  245. List<Line> picture = new List<Line>();
  246. while (!allLines[i].StartsWith("</svg"))
  247. {
  248. List<Line> element = ParseSingleSVGElement(allLines);
  249. if (element != null)
  250. {
  251. picture.AddRange(element);
  252. }
  253. i++;
  254. }
  255. return picture;
  256. }
  257. /// <summary>
  258. /// parses one toplevel svg element
  259. /// </summary>
  260. /// <param name="allLines">an array holding all lines of the input file</param>
  261. /// <returns>the parsed Element as a list of lines</returns>
  262. private List<Line> ParseSingleSVGElement(string[] allLines)
  263. {
  264. String[] currentElement = GetCurrentElement(allLines);
  265. if (currentElement[currentElement.Length - 1].EndsWith("/>")) //single line element
  266. {
  267. return ParseSingleLineSVGElement(currentElement);
  268. }
  269. else //element containing sub-elements
  270. {
  271. return ParseMultiLineSVGElement(currentElement, allLines);
  272. }
  273. }
  274. /// <summary>
  275. /// parses a single toplevel svg element only taking one line
  276. /// </summary>
  277. /// <param name="allLines">an array holding all lines of the input file</param>
  278. /// <returns>the parsed element as a Line object, or null if the element is not supported</returns>
  279. private List<Line> ParseSingleLineSVGElement(string[] currentElement)
  280. {
  281. List<Point> points= null;
  282. List<Line> element = null;
  283. switch (currentElement[0])
  284. {
  285. case "<rect":
  286. points = parseRect(currentElement);
  287. break;
  288. case "<circle":
  289. points = parseCircle(currentElement);
  290. break;
  291. case "<ellipse":
  292. points = parseEllipse(currentElement);
  293. break;
  294. case "<line":
  295. points = parseLine(currentElement);
  296. break;
  297. case "<polyline":
  298. points = parsePolyline(currentElement);
  299. break;
  300. case "<polygon":
  301. points = parsePolygon(currentElement);
  302. break;
  303. case "<path":
  304. element = parsePath(currentElement);
  305. break;
  306. default: //unsupported svg element
  307. Console.WriteLine("unsupported element: " + currentElement[0] + currentElement[0].Length);
  308. return null;
  309. }
  310. if (element == null)
  311. {
  312. element = new List<Line>();
  313. element.Add(new Line(points));
  314. }
  315. return element;
  316. }
  317. /// <summary>
  318. /// parses a rectangle definition into a List of Points representing a single line around the rectangle (in clockwise direction)
  319. /// </summary>
  320. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  321. /// <returns>the parsed element as a List of Points</returns>
  322. private List<Point> parseRect(string[] currentElement)
  323. {
  324. double x = 0;
  325. double y = 0;
  326. double w = 0;
  327. double h = 0;
  328. double rx = 0;
  329. double ry = 0;
  330. for(int j= 0; j < currentElement.Length; j++)
  331. {
  332. if (currentElement[j].StartsWith("x="))
  333. {
  334. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  335. }
  336. else if (currentElement[j].StartsWith("y="))
  337. {
  338. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  339. }
  340. else if (currentElement[j].StartsWith("width="))
  341. {
  342. w = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  343. }
  344. else if (currentElement[j].StartsWith("height="))
  345. {
  346. h = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  347. }
  348. else if (currentElement[j].StartsWith("rx="))
  349. {
  350. rx = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  351. }
  352. else if (currentElement[j].StartsWith("ry="))
  353. {
  354. ry = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  355. }
  356. }
  357. List<Point> rect = new List<Point>();
  358. rect.Add(ScaleAndCreatePoint(x, y));
  359. rect.Add(ScaleAndCreatePoint(x + w, y));
  360. rect.Add(ScaleAndCreatePoint(x + w, y + h));
  361. rect.Add(ScaleAndCreatePoint(x, y + h));
  362. rect.Add(ScaleAndCreatePoint(x, y));
  363. Console.WriteLine("parsed point: " + x + ";" + y);
  364. return rect;
  365. }
  366. /// <summary>
  367. /// parses a circle definition into a List of Points
  368. /// </summary>
  369. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  370. /// <returns>the parsed element as a List of Points</returns>
  371. private List<Point> parseCircle(string[] currentElement)
  372. {
  373. double x = 0;
  374. double y = 0;
  375. double r = 0;
  376. for (int j = 0; j < currentElement.Length; j++)
  377. {
  378. if (currentElement[j].StartsWith("cx="))
  379. {
  380. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  381. }
  382. else if (currentElement[j].StartsWith("cy="))
  383. {
  384. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  385. }
  386. else if (currentElement[j].StartsWith("r="))
  387. {
  388. r = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  389. }
  390. }
  391. return SampleEllipse(x, y, r, r);
  392. }
  393. /// <summary>
  394. /// parses a ellipse definition into a List of Points
  395. /// </summary>
  396. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  397. /// <returns>the parsed element as a List of Points</returns>
  398. private List<Point> parseEllipse(string[] currentElement)
  399. {
  400. double x = 0;
  401. double y = 0;
  402. double rx = 0;
  403. double ry = 0;
  404. for (int j = 0; j < currentElement.Length; j++)
  405. {
  406. if (currentElement[j].StartsWith("cx="))
  407. {
  408. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  409. }
  410. else if (currentElement[j].StartsWith("cy="))
  411. {
  412. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  413. }
  414. else if (currentElement[j].StartsWith("rx="))
  415. {
  416. rx = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  417. }
  418. else if (currentElement[j].StartsWith("ry="))
  419. {
  420. ry = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  421. }
  422. }
  423. return SampleEllipse(x, y, rx, ry);
  424. }
  425. /// <summary>
  426. /// parses a line definition into a List of two Points
  427. /// </summary>
  428. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  429. /// <returns>the parsed element as a List of Points</returns>
  430. private List<Point> parseLine(string[] currentElement)
  431. {
  432. double x1 = 0;
  433. double y1 = 0;
  434. double x2 = 0;
  435. double y2 = 0;
  436. for (int j = 0; j < currentElement.Length; j++)
  437. {
  438. if (currentElement[j].StartsWith("x1="))
  439. {
  440. x1 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  441. }
  442. else if (currentElement[j].StartsWith("y1="))
  443. {
  444. y1 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  445. }
  446. else if (currentElement[j].StartsWith("x2="))
  447. {
  448. x2 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  449. }
  450. else if (currentElement[j].StartsWith("y2="))
  451. {
  452. y2 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  453. }
  454. }
  455. List<Point> line = new List<Point>();
  456. line.Add(ScaleAndCreatePoint(x1, y1));
  457. line.Add(ScaleAndCreatePoint(x2, y2));
  458. return line;
  459. }
  460. /// <summary>
  461. /// parses a polyline definition into a List of Points
  462. /// </summary>
  463. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  464. /// <returns>the parsed element as a List of Points</returns>
  465. private List<Point> parsePolyline(string[] currentElement)
  466. {
  467. String[] points = null;
  468. for (int j = 0; j < currentElement.Length; j++)
  469. {
  470. if (currentElement[j].StartsWith("points="))
  471. {
  472. List<String> pointDefs = new List<string>();
  473. pointDefs.Add(currentElement[j].Substring(8)); //parse first point coordinates by removing 'points="'
  474. j++;
  475. while (!currentElement[j].EndsWith("\""))
  476. {
  477. pointDefs.Add(currentElement[j]); //parse intermediate point coordinates
  478. j++;
  479. }
  480. pointDefs.Add(currentElement[j].Trim('"')); //parse last point coordinates by removing '"'
  481. points = pointDefs.ToArray();
  482. }
  483. }
  484. List<Point> polyline = new List<Point>();
  485. for (int k = 0; k < points.Length - 1; k += 2)
  486. {
  487. polyline.Add(ScaleAndCreatePoint(Convert.ToDouble(points[k], CultureInfo.InvariantCulture), Convert.ToDouble(points[k + 1], CultureInfo.InvariantCulture)));
  488. }
  489. return polyline;
  490. }
  491. /// <summary>
  492. /// parses a polygon definition into a List of Points
  493. /// </summary>
  494. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  495. /// <returns>the parsed element as a List of Points</returns>
  496. private List<Point> parsePolygon(string[] currentElement)
  497. {
  498. String[] points = null;
  499. for (int j = 0; j < currentElement.Length; j++)
  500. {
  501. if (currentElement[j].StartsWith("points="))
  502. {
  503. List<String> pointDefs = new List<string>();
  504. pointDefs.Add(currentElement[j].Substring(8)); //parse first point coordinates by removing 'points="'
  505. j++;
  506. while (!currentElement[j].EndsWith("\""))
  507. {
  508. pointDefs.Add(currentElement[j]); //parse intermediate point coordinates
  509. j++;
  510. }
  511. pointDefs.Add(currentElement[j].Trim('"')); //parse last point coordinates by removing '"'
  512. points = pointDefs.ToArray();
  513. }
  514. }
  515. List<Point> polygon = new List<Point>();
  516. for (int k = 0; k < points.Length - 1; k+=2)
  517. {
  518. polygon.Add(ScaleAndCreatePoint(Convert.ToDouble(points[k], CultureInfo.InvariantCulture), Convert.ToDouble(points[k+1], CultureInfo.InvariantCulture)));
  519. Console.WriteLine("parsed point: " + points[k] + ";" + points[k + 1]);
  520. }
  521. polygon.Add(ScaleAndCreatePoint(Convert.ToDouble(points[0], CultureInfo.InvariantCulture), Convert.ToDouble(points[1], CultureInfo.InvariantCulture))); //close polygon
  522. Console.WriteLine("parsed point: " + points[0] + ";" + points[1]);
  523. return polygon;
  524. }
  525. /// <summary>
  526. /// parses a path definition into a List of Points
  527. /// </summary>
  528. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  529. /// <returns>the parsed element as a List of Points</returns>
  530. private List<Line> parsePath(string[] currentElement)
  531. {
  532. List<String> pathElements = new List<string>();
  533. for (int j = 0; j < currentElement.Length; j++)
  534. {
  535. if (currentElement[j].StartsWith("d="))
  536. {
  537. pathElements.Add(currentElement[j].Substring(3)); //parse first path element by removing 'd="'
  538. j++;
  539. while (!currentElement[j].EndsWith("\""))
  540. {
  541. pathElements.Add(currentElement[j]); //parse intermediate path element
  542. j++;
  543. }
  544. pathElements.Add(currentElement[j].Trim('"')); //parse last path element by removing '"'
  545. }
  546. }
  547. normalizePathDeclaration(pathElements); //expand path data to always explicitly have the command descriptor in front of the appropriate number of arguments and to seperate command descriptors, coordinates and other tokens always into seperate list elements (equivalent to seperation with spaces in the input file, but svg allows also for comma as a seperator, and for omitting seperators where possible without losing information (refer to svg grammer) to reduce file size
  548. List<Line> element = new List<Line>();
  549. List<Point> currentLine = new List<Point>();
  550. double lastBezierControlPointX= 0;
  551. double lastBezierControlPointY= 0;
  552. double lastPositionX;
  553. double lastPositionY;
  554. double initialPositionX= -1;
  555. double initialPositionY= -1;
  556. bool newSubpath = true;
  557. //assume that svg is well formatted with spaces between each token, no emitted characters and only "[char] (appropriateNumber*[coordinate])" segments
  558. //pathElements = PreparePathElements(pathElements); //split pathElement list objects until every object is atomar (single character or single number (coordinate))
  559. //int k = 0; //index of active element in pathElements is always 0
  560. (List<Point>, double, double) valuesArc; //list of points, new values for: lastPositionX, lastPositionY
  561. (List<Point>, double, double, double, double) valuesBezierCurve; //list of points, new values for: lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY
  562. (Point, double, double) valuesSinglePoint = parse_M_L(pathElements); //new point, new values for: lastPositionX, lastPositionY
  563. currentLine = new List<Point>();
  564. currentLine.Add(valuesSinglePoint.Item1);
  565. lastPositionX = valuesSinglePoint.Item2;
  566. lastPositionY = valuesSinglePoint.Item3;
  567. String currentToken;
  568. while (!(pathElements.Count == 0)){
  569. if (newSubpath)
  570. {
  571. initialPositionX = lastPositionX; //update buffers for coordinates of first point of active subpath
  572. initialPositionY = lastPositionY;
  573. newSubpath = false;
  574. }
  575. currentToken = pathElements.First();
  576. if (currentToken.Equals("M"))
  577. {
  578. element.Add(new Line(currentLine)); //save current line
  579. valuesSinglePoint = parse_M_L(pathElements);
  580. currentLine = new List<Point>(); //create new empty line
  581. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  582. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  583. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  584. }
  585. else if (currentToken.Equals("m"))
  586. {
  587. element.Add(new Line(currentLine)); //save current line
  588. valuesSinglePoint = parse_m_l(pathElements, lastPositionX, lastPositionY);
  589. currentLine = new List<Point>(); //create new empty line
  590. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  591. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  592. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  593. }
  594. else if (currentToken.Equals("Z") || currentToken.Equals("z"))
  595. {
  596. valuesSinglePoint = parse_Z(pathElements, initialPositionX, initialPositionY); //method call only used for uniform program structure... only real effect of method is to consume one token
  597. newSubpath = true;
  598. currentLine.Add(valuesSinglePoint.Item1); //add point to old line
  599. element.Add(new Line(currentLine)); //save current line
  600. currentLine = new List<Point>(); //create new empty line
  601. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  602. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  603. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  604. }
  605. else if (currentToken.Equals("L"))
  606. {
  607. valuesSinglePoint = parse_M_L(pathElements);
  608. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  609. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  610. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  611. }
  612. else if (currentToken.Equals("l"))
  613. {
  614. valuesSinglePoint = parse_m_l(pathElements, lastPositionX, lastPositionY);
  615. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  616. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  617. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  618. }
  619. else if (currentToken.Equals("H"))
  620. {
  621. valuesSinglePoint = parse_H(pathElements, lastPositionY);
  622. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  623. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  624. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  625. }
  626. else if (currentToken.Equals("h"))
  627. {
  628. valuesSinglePoint = parse_h(pathElements, lastPositionX, lastPositionY);
  629. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  630. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  631. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  632. }
  633. else if (currentToken.Equals("V"))
  634. {
  635. valuesSinglePoint = parse_V(pathElements, lastPositionX);
  636. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  637. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  638. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  639. }
  640. else if (currentToken.Equals("v"))
  641. {
  642. valuesSinglePoint = parse_v(pathElements, lastPositionX, lastPositionY);
  643. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  644. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  645. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  646. }
  647. else if (currentToken.Equals("C"))
  648. {
  649. valuesBezierCurve = parse_C(pathElements, lastPositionX, lastPositionY);
  650. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  651. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  652. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  653. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  654. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  655. }
  656. else if (currentToken.Equals("c"))
  657. {
  658. valuesBezierCurve = parse_C(pathElements, lastPositionX, lastPositionY);
  659. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  660. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  661. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  662. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  663. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  664. }
  665. else if (currentToken.Equals("S"))
  666. {
  667. valuesBezierCurve = parse_S(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  668. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  669. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  670. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  671. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  672. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  673. }
  674. else if (currentToken.Equals("s"))
  675. {
  676. valuesBezierCurve = parse_s(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  677. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  678. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  679. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  680. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  681. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  682. }
  683. else if (currentToken.Equals("Q"))
  684. {
  685. valuesBezierCurve = parse_Q(pathElements, lastPositionX, lastPositionY);
  686. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  687. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  688. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  689. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  690. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  691. }
  692. else if (currentToken.Equals("q"))
  693. {
  694. valuesBezierCurve = parse_q(pathElements, lastPositionX, lastPositionY);
  695. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  696. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  697. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  698. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  699. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  700. }
  701. else if (currentToken.Equals("T"))
  702. {
  703. valuesBezierCurve = parse_T(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  704. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  705. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  706. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  707. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  708. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  709. }
  710. else if (currentToken.Equals("t"))
  711. {
  712. valuesBezierCurve = parse_t(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  713. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  714. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  715. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  716. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  717. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  718. }
  719. else if (currentToken.Equals("A"))
  720. {
  721. valuesArc = parse_A(pathElements, lastPositionX, lastPositionY);
  722. currentLine.AddRange(valuesArc.Item1); //add points to new line
  723. lastPositionX = valuesArc.Item2; //save last point coordinates
  724. lastPositionY = valuesArc.Item3; //save last point coordinates
  725. }
  726. else if (currentToken.Equals("a"))
  727. {
  728. valuesArc = parse_a(pathElements, lastPositionX, lastPositionY);
  729. currentLine.AddRange(valuesArc.Item1); //add points to new line
  730. lastPositionX = valuesArc.Item2; //save last point coordinates
  731. lastPositionY = valuesArc.Item3; //save last point coordinates
  732. }
  733. else
  734. {
  735. throw new FileImporterException("invalid path argument or path data formatting: read argument " + pathElements.First(), "valid path arguments are: {M,Z,L,H,V,C,S,Q,T,A} in upper and lower case", i + 1);
  736. }
  737. }
  738. if (currentLine.Count > 1)
  739. {
  740. element.Add(new Line(currentLine)); //save current line
  741. }
  742. return element;
  743. }
  744. private void normalizePathDeclaration(List<string> pathElements)
  745. {
  746. Char lastCommand = 'M';
  747. int argumentCounter = 0;
  748. for( int j= 0; j < pathElements.Count; j++)
  749. {
  750. String currentElement = pathElements.ElementAt(j);
  751. if (currentElement.Length != 1)
  752. {
  753. if ((currentElement.First() >= 'A' && currentElement.First() <= 'Z') || (currentElement.First() >= 'a' && currentElement.First() <= 'z')) //seperate a single command descriptor / letter
  754. {
  755. pathElements.RemoveAt(j);
  756. pathElements.Insert(j, currentElement.First() + ""); //insert letter as seperate element
  757. pathElements.Insert(j + 1, currentElement.Substring(1)); //insert rest of String at next position so it will be processed again
  758. lastCommand = currentElement.First();
  759. argumentCounter = 0;
  760. }
  761. else if ((currentElement.First() >= '0' && currentElement.First() <= '9') || currentElement.First() == '-' || currentElement.First() == '+') //seperate a single coordinate / number
  762. {
  763. bool decimalPointEncountered = false; //reuse the decimalPointEncountered flag for control flow first...
  764. switch (lastCommand){ //ceck for reaching of next command with omitted command descriptor
  765. case 'M':
  766. if (argumentCounter >= 2) decimalPointEncountered = true;
  767. break;
  768. case 'm':
  769. if (argumentCounter >= 2) decimalPointEncountered = true;
  770. break;
  771. case 'L':
  772. if (argumentCounter >= 2) decimalPointEncountered = true;
  773. break;
  774. case 'l':
  775. if (argumentCounter >= 2) decimalPointEncountered = true;
  776. break;
  777. case 'V':
  778. if (argumentCounter >= 1) decimalPointEncountered = true;
  779. break;
  780. case 'v':
  781. if (argumentCounter >= 1) decimalPointEncountered = true;
  782. break;
  783. case 'H':
  784. if (argumentCounter >= 1) decimalPointEncountered = true;
  785. break;
  786. case 'h':
  787. if (argumentCounter >= 1) decimalPointEncountered = true;
  788. break;
  789. case 'C':
  790. if (argumentCounter >= 6) decimalPointEncountered = true;
  791. break;
  792. case 'c':
  793. if (argumentCounter >= 6) decimalPointEncountered = true;
  794. break;
  795. case 'S':
  796. if (argumentCounter >= 4) decimalPointEncountered = true;
  797. break;
  798. case 's':
  799. if (argumentCounter >= 4) decimalPointEncountered = true;
  800. break;
  801. case 'Q':
  802. if (argumentCounter >= 4) decimalPointEncountered = true;
  803. break;
  804. case 'q':
  805. if (argumentCounter >= 4) decimalPointEncountered = true;
  806. break;
  807. case 'T':
  808. if (argumentCounter >= 2) decimalPointEncountered = true;
  809. break;
  810. case 't':
  811. if (argumentCounter >= 2) decimalPointEncountered = true;
  812. break;
  813. case 'A':
  814. if (argumentCounter >= 7) decimalPointEncountered = true;
  815. break;
  816. case 'a':
  817. if (argumentCounter >= 7) decimalPointEncountered = true;
  818. break;
  819. }
  820. if (decimalPointEncountered)
  821. {
  822. pathElements.Insert(j, lastCommand + ""); //repeat command descriptor
  823. j++; //skip command descriptor (was put into active position in the list
  824. argumentCounter = 0; //reset argument counter
  825. }
  826. decimalPointEncountered = false;
  827. for (int k = 1; k < currentElement.Length; k++)
  828. {
  829. if (!decimalPointEncountered && currentElement.ElementAt(k) == '.') //allow up to one decimal point in numbers
  830. {
  831. decimalPointEncountered = true;
  832. }
  833. else if (!((currentElement.ElementAt(k) >= '0' && currentElement.ElementAt(k) <= '9')))
  834. {
  835. pathElements.RemoveAt(j);
  836. pathElements.Insert(j, currentElement.Substring(0, k - 1)); //insert number as seperate element
  837. pathElements.Insert(j + 1, currentElement.Substring(k)); //insert rest of String at next position so it will be processed again
  838. break;
  839. }
  840. }
  841. argumentCounter++;
  842. }
  843. else //parse non-space seperators and skip other unsupported characters (the only other valid ones per svg standard would be weird tokens looking like format descriptors (e.g. '#xC'), these are unsopported and will likely cause an error or other inconsitencies during parsing)
  844. {
  845. for (int k = 1; k < currentElement.Length; k++)
  846. {
  847. if (((currentElement.ElementAt(k) >= '0' && currentElement.ElementAt(k) <= '9')) || currentElement.ElementAt(k) == '-' || currentElement.ElementAt(k) == '+' || (currentElement.ElementAt(k) >= 'A' && currentElement.ElementAt(k) <= 'Z') || (currentElement.ElementAt(k) >= 'a' && currentElement.ElementAt(k) <= 'z'))
  848. {
  849. pathElements.RemoveAt(j);
  850. pathElements.Insert(j + 1, currentElement.Substring(k)); //insert rest of String at next position so it will be processed again
  851. break;
  852. }
  853. }
  854. }
  855. }
  856. else
  857. {
  858. if ((currentElement.First() >= 'A' && currentElement.First() <= 'Z') || (currentElement.First() >= 'a' && currentElement.First() <= 'z')) //update lastCommand buffer when reading single letter
  859. {
  860. lastCommand = currentElement.First();
  861. argumentCounter = 0;
  862. }
  863. else if(!((currentElement.First() >= '0' && currentElement.First() <= '9') || currentElement.First() == '-' || currentElement.First() == '+')) //not a number
  864. {
  865. pathElements.RemoveAt(j); //remove element
  866. j--; //decrement index pointer so next element will not be skipped (indices of all folowing elements just decreased by 1)
  867. }
  868. }
  869. }
  870. }
  871. private (Point, double, double) parse_Z(List<string> pathElements, double initialPositionX, double initialPositionY)
  872. {
  873. pathElements.RemoveAt(0); //remove element descriptor token
  874. return (ScaleAndCreatePoint(initialPositionX, initialPositionY), initialPositionX, initialPositionY);
  875. }
  876. /// <summary>
  877. /// parses a "moveto", "close loop" or "lineto" path element with absolute coordinates
  878. /// </summary>
  879. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  880. /// <returns>the point at the end of the move, close loop or line action and its exact, unscaled coordinates</returns>
  881. private (Point, double, double) parse_M_L(List<string> pathElements)
  882. {
  883. pathElements.RemoveAt(0); //remove element descriptor token
  884. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x coordinate
  885. pathElements.RemoveAt(0); //remove x coordinate token
  886. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y coordinate
  887. pathElements.RemoveAt(0); //remove y coordinate token
  888. return (ScaleAndCreatePoint(x, y), x, y);
  889. }
  890. /// <summary>
  891. /// parses a "moveto", "close loop" or "lineto" path element with relative coordinates
  892. /// </summary>
  893. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  894. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  895. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  896. /// <returns>the point at the end of the move, close loop or line action and its exact, unscaled coordinates</returns>
  897. private (Point, double, double) parse_m_l(List<string> pathElements, double lastPositionX, double lastPositionY)
  898. {
  899. pathElements.RemoveAt(0); //remove element descriptor token
  900. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative x coordinate
  901. pathElements.RemoveAt(0); //remove x coordinate token
  902. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative y coordinate
  903. pathElements.RemoveAt(0); //remove y coordinate token
  904. x = lastPositionX + x; //compute absolute x coordinate
  905. y = lastPositionY + y; //compute absolute y coordinate
  906. return (ScaleAndCreatePoint(x, y), x, y);
  907. }
  908. /// <summary>
  909. /// parses a "horizontal lineto" path element with absolute coordinates
  910. /// </summary>
  911. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  912. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  913. /// <returns>the point at the end of the horizontal line action and its exact, unscaled coordinates</returns>
  914. private (Point, double, double) parse_H(List<string> pathElements, double lastPositionY)
  915. {
  916. pathElements.RemoveAt(0); //remove element descriptor token
  917. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x coordinate
  918. pathElements.RemoveAt(0); //remove x coordinate token
  919. return (ScaleAndCreatePoint(x, lastPositionY), x, lastPositionY);
  920. }
  921. /// <summary>
  922. /// parses a "horizontal lineto" path element with relative coordinates
  923. /// </summary>
  924. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  925. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  926. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  927. /// <returns>the point at the end of the horizontal line action and its exact, unscaled coordinates</returns>
  928. private (Point, double, double) parse_h(List<string> pathElements, double lastPositionX, double lastPositionY)
  929. {
  930. pathElements.RemoveAt(0); //remove element descriptor token
  931. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative x coordinate
  932. pathElements.RemoveAt(0); //remove x coordinate token
  933. x = lastPositionX + x; //compute absolute x coordinate
  934. return (ScaleAndCreatePoint(x, lastPositionY), x, lastPositionY);
  935. }
  936. /// <summary>
  937. /// parses a "vertical lineto" path element with absolute coordinates
  938. /// </summary>
  939. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  940. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  941. /// <returns>the point at the end of the vertical line action and its exact, unscaled coordinates</returns>
  942. private (Point, double, double) parse_V(List<string> pathElements, double lastPositionX)
  943. {
  944. pathElements.RemoveAt(0); //remove element descriptor token
  945. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y coordinate
  946. pathElements.RemoveAt(0); //remove y coordinate token
  947. return (ScaleAndCreatePoint(lastPositionX, y), lastPositionX, y);
  948. }
  949. /// <summary>
  950. /// parses a "vertical lineto" path element with relative coordinates
  951. /// </summary>
  952. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  953. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  954. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  955. /// <returns>the point at the end of the vertical line action and its exact, unscaled coordinates</returns>
  956. private (Point, double, double) parse_v(List<string> pathElements, double lastPositionX, double lastPositionY)
  957. {
  958. pathElements.RemoveAt(0); //remove element descriptor token
  959. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative y coordinate
  960. pathElements.RemoveAt(0); //remove y coordinate token
  961. y = lastPositionY + y; //compute absolute y coordinate
  962. return (ScaleAndCreatePoint(lastPositionX, y), lastPositionX, y);
  963. }
  964. /// <summary>
  965. /// parses a "cubic bezier curve" path element with absolute coordinates
  966. /// </summary>
  967. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  968. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  969. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  970. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  971. private (List<Point>, double, double, double, double) parse_C(List<string> pathElements, double lastPositionX, double lastPositionY)
  972. {
  973. pathElements.RemoveAt(0); //remove element descriptor token
  974. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point x coordinate
  975. pathElements.RemoveAt(0); //remove x coordinate token
  976. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point y coordinate
  977. pathElements.RemoveAt(0); //remove y coordinate token
  978. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  979. pathElements.RemoveAt(0); //remove x coordinate token
  980. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  981. pathElements.RemoveAt(0); //remove y coordinate token
  982. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  983. pathElements.RemoveAt(0); //remove x coordinate token
  984. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  985. pathElements.RemoveAt(0); //remove y coordinate token
  986. return (SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  987. }
  988. /// <summary>
  989. /// parses a "cubic bezier curve" path element with relative coordinates
  990. /// </summary>
  991. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  992. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  993. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  994. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  995. private (List<Point>, double, double, double, double) parse_c(List<string> pathElements, double lastPositionX, double lastPositionY)
  996. {
  997. pathElements.RemoveAt(0); //remove element descriptor token
  998. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point x coordinate
  999. pathElements.RemoveAt(0); //remove x coordinate token
  1000. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point y coordinate
  1001. pathElements.RemoveAt(0); //remove y coordinate token
  1002. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1003. pathElements.RemoveAt(0); //remove x coordinate token
  1004. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1005. pathElements.RemoveAt(0); //remove y coordinate token
  1006. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1007. pathElements.RemoveAt(0); //remove x coordinate token
  1008. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1009. pathElements.RemoveAt(0); //remove y coordinate token
  1010. x1 = lastPositionX + x1; //compute absolute x coordinate
  1011. y1 = lastPositionY + y1; //compute absolute y coordinate
  1012. x2 = lastPositionX + x2; //compute absolute x coordinate
  1013. y2 = lastPositionY + y2; //compute absolute y coordinate
  1014. x = lastPositionX + x; //compute absolute x coordinate
  1015. y = lastPositionY + y; //compute absolute y coordinate
  1016. return (SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1017. }
  1018. /// <summary>
  1019. /// parses a "cubic bezier curve shorthand" path element with absolute coordinates
  1020. /// </summary>
  1021. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1022. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1023. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1024. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1025. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1026. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1027. private (List<Point>, double, double, double, double) parse_S(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1028. {
  1029. pathElements.RemoveAt(0); //remove element descriptor token
  1030. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1031. pathElements.RemoveAt(0); //remove x coordinate token
  1032. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1033. pathElements.RemoveAt(0); //remove y coordinate token
  1034. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1035. pathElements.RemoveAt(0); //remove x coordinate token
  1036. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1037. pathElements.RemoveAt(0); //remove y coordinate token
  1038. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1039. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1040. return (SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1041. }
  1042. /// <summary>
  1043. /// parses a "cubic bezier curve shorthand" path element with relative coordinates
  1044. /// </summary>
  1045. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1046. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1047. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1048. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1049. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1050. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1051. private (List<Point>, double, double, double, double) parse_s(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1052. {
  1053. pathElements.RemoveAt(0); //remove element descriptor token
  1054. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1055. pathElements.RemoveAt(0); //remove x coordinate token
  1056. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1057. pathElements.RemoveAt(0); //remove y coordinate token
  1058. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1059. pathElements.RemoveAt(0); //remove x coordinate token
  1060. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1061. pathElements.RemoveAt(0); //remove y coordinate token
  1062. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1063. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1064. x2 = lastPositionX + x2; //compute absolute x coordinate
  1065. y2 = lastPositionY + y2; //compute absolute y coordinate
  1066. x = lastPositionX + x; //compute absolute x coordinate
  1067. y = lastPositionY + y; //compute absolute y coordinate
  1068. return (SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1069. }
  1070. /// <summary>
  1071. /// parses a "quadratic bezier curve" path element with absolute coordinates
  1072. /// </summary>
  1073. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1074. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1075. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1076. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1077. private (List<Point>, double, double, double, double) parse_Q(List<string> pathElements, double lastPositionX, double lastPositionY)
  1078. {
  1079. pathElements.RemoveAt(0); //remove element descriptor token
  1080. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point x coordinate
  1081. pathElements.RemoveAt(0); //remove x coordinate token
  1082. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point y coordinate
  1083. pathElements.RemoveAt(0); //remove y coordinate token
  1084. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1085. pathElements.RemoveAt(0); //remove x coordinate token
  1086. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1087. pathElements.RemoveAt(0); //remove y coordinate token
  1088. return (SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1089. }
  1090. /// <summary>
  1091. /// parses a "quadratic bezier curve" path element with relative coordinates
  1092. /// </summary>
  1093. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1094. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1095. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1096. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1097. private (List<Point>, double, double, double, double) parse_q(List<string> pathElements, double lastPositionX, double lastPositionY)
  1098. {
  1099. pathElements.RemoveAt(0); //remove element descriptor token
  1100. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point x coordinate
  1101. pathElements.RemoveAt(0); //remove x coordinate token
  1102. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point y coordinate
  1103. pathElements.RemoveAt(0); //remove y coordinate token
  1104. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1105. pathElements.RemoveAt(0); //remove x coordinate token
  1106. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1107. pathElements.RemoveAt(0); //remove y coordinate token
  1108. x1 = lastPositionX + x1; //compute absolute x coordinate
  1109. y1 = lastPositionY + y1; //compute absolute y coordinate
  1110. x = lastPositionX + x; //compute absolute x coordinate
  1111. y = lastPositionY + y; //compute absolute y coordinate
  1112. return (SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1113. }
  1114. /// <summary>
  1115. /// parses a "quadratic bezier curve shorthand" path element with absolute coordinates
  1116. /// </summary>
  1117. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1118. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1119. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1120. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1121. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1122. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1123. private (List<Point>, double, double, double, double) parse_T(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1124. {
  1125. pathElements.RemoveAt(0); //remove element descriptor token
  1126. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1127. pathElements.RemoveAt(0); //remove x coordinate token
  1128. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1129. pathElements.RemoveAt(0); //remove y coordinate token
  1130. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1131. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1132. return (SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1133. }
  1134. /// <summary>
  1135. /// parses a "quadratic bezier curve shorthand" path element with relative coordinates
  1136. /// </summary>
  1137. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1138. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1139. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1140. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1141. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1142. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1143. private (List<Point>, double, double, double, double) parse_t(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1144. {
  1145. pathElements.RemoveAt(0); //remove element descriptor token
  1146. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1147. pathElements.RemoveAt(0); //remove x coordinate token
  1148. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1149. pathElements.RemoveAt(0); //remove y coordinate token
  1150. x = lastPositionX + x; //compute absolute x coordinate
  1151. y = lastPositionY + y; //compute absolute y coordinate
  1152. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1153. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1154. return (SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1155. }
  1156. /// <summary>
  1157. /// parses a "elliptical arc" path element with absolute coordinates
  1158. /// </summary>
  1159. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1160. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1161. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1162. /// <returns>a List of Points containing all sampled points on the elliptic arc, aswell as the unscaled x and y coordinates of the last point of the arc<returns>
  1163. private (List<Point>, double, double) parse_A(List<string> pathElements, double lastPositionX, double lastPositionY)
  1164. {
  1165. pathElements.RemoveAt(0); //remove element descriptor token
  1166. double rx = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x radius
  1167. pathElements.RemoveAt(0); //remove x radius token
  1168. double ry = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y radius
  1169. pathElements.RemoveAt(0); //remove y radius token
  1170. double thetha = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse rotation
  1171. pathElements.RemoveAt(0); //remove rotation token
  1172. bool largeArcFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse large arc flag
  1173. pathElements.RemoveAt(0); //remove large arc flag token
  1174. bool sweepFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse sweep flag
  1175. pathElements.RemoveAt(0); //remove sweep flag token
  1176. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1177. pathElements.RemoveAt(0); //remove x coordinate token
  1178. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1179. pathElements.RemoveAt(0); //remove y coordinate token
  1180. x = x - lastPositionX; //compute relative x coordinate
  1181. y = y - lastPositionY; //compute relative y coordinate
  1182. return (sampleArc(lastPositionX, lastPositionY, rx, ry, x, y, thetha, largeArcFlag, sweepFlag), x, y);
  1183. }
  1184. /// <summary>
  1185. /// parses a "elliptical arc" path element with relative coordinates
  1186. /// </summary>
  1187. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1188. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1189. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1190. /// <returns>a List of Points containing all sampled points on the elliptic arc, aswell as the unscaled x and y coordinates of the last point of the arc</returns>
  1191. private (List<Point>, double, double) parse_a(List<string> pathElements, double lastPositionX, double lastPositionY)
  1192. {
  1193. pathElements.RemoveAt(0); //remove element descriptor token
  1194. double rx = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x radius
  1195. pathElements.RemoveAt(0); //remove x radius token
  1196. double ry = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y radius
  1197. pathElements.RemoveAt(0); //remove y radius token
  1198. double thetha = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse rotation
  1199. pathElements.RemoveAt(0); //remove rotation token
  1200. bool largeArcFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse large arc flag
  1201. pathElements.RemoveAt(0); //remove large arc flag token
  1202. bool sweepFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse sweep flag
  1203. pathElements.RemoveAt(0); //remove sweep flag token
  1204. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1205. pathElements.RemoveAt(0); //remove x coordinate token
  1206. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1207. pathElements.RemoveAt(0); //remove y coordinate token
  1208. return (sampleArc(lastPositionX, lastPositionY, rx, ry, x, y, thetha, largeArcFlag, sweepFlag), x, y);
  1209. }
  1210. /// <summary>
  1211. /// samles an arc of an ellipse into a list of points
  1212. /// </summary>
  1213. /// <param name="lastPositionX">x coordinate of last point</param>
  1214. /// <param name="lastPositionY">y coordinate of last point</param>
  1215. /// <param name="rx">x radius of the ellipse</param>
  1216. /// <param name="ry">y radius of the ellipse</param>
  1217. /// <param name="nextPositionXRelative">x coordinate of next point</param>
  1218. /// <param name="nextPositionYRelative">y coordinate of next point</param>
  1219. /// <param name="thetha">rotation of the ellipse around the x axis</param>
  1220. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1221. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1222. /// <returns></returns>
  1223. private List<Point> sampleArc(double lastPositionX, double lastPositionY, double rx, double ry, double nextPositionXRelative, double nextPositionYRelative, double thetha, bool largeArcFlag, bool sweepFlag)
  1224. {
  1225. double cos = Math.Cos(thetha / 180 * Math.PI);
  1226. double sin = Math.Sin(thetha / 180 * Math.PI);
  1227. double targetXTransformed = cos * nextPositionXRelative - sin * nextPositionYRelative; //rotate target point counterclockwise around the start point by [thetha] degrees, thereby practically rotating an intermediate coordinate system, which has its origin in the start point, clockwise by the same amount
  1228. double targetYTransformed = sin * nextPositionXRelative + cos * nextPositionYRelative;
  1229. (double[], double[]) values = sampleEllipticArcBiasedNoRotation(rx, ry, nextPositionXRelative, nextPositionYRelative, largeArcFlag, sweepFlag);
  1230. List<Point> result = new List<Point>();
  1231. for (int j = 0; j < values.Item1.Length; j++)
  1232. {
  1233. double xCoordinateRelative = cos * values.Item1[j] + sin * values.Item2[j]; //rotate backwards so intermediate coordinate system and "real" coordinate system have the same rotation again
  1234. double yCoordinateRelative = cos * values.Item2[j] - sin * values.Item1[j];
  1235. double xCoordinateAbsolute = lastPositionX + xCoordinateRelative; //translate relative to absolute coordinates (intermediate coordinate system is now again aligned with the "real" one (the virtual pane on which all vectorgraphic elements are placed) (note that this "real" coordinate system is still not the same as the one actually representing pixels for drawing, as it still has to be scaled appropriately (done inside the ScaleAndCreatePoint method)))
  1236. double yCoordinateAbsolute = lastPositionY + yCoordinateRelative;
  1237. result.Add(ScaleAndCreatePoint(xCoordinateAbsolute, yCoordinateAbsolute));
  1238. }
  1239. result.Add(ScaleAndCreatePoint(lastPositionX + nextPositionXRelative, lastPositionY + nextPositionYRelative)); //add end point
  1240. return result;
  1241. }
  1242. /// <summary>
  1243. /// samples an elliptical arc with given radii through coordinate origin and endpoint with specified properties
  1244. /// </summary>
  1245. /// <param name="rx">x radius</param>
  1246. /// <param name="ry">y radius</param>
  1247. /// <param name="nextPositionXRelative">x coordinate of next point</param>
  1248. /// <param name="nextPositionYRelative">y coordinate of next point</param>
  1249. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1250. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1251. /// <returns></returns>
  1252. private (double[], double[]) sampleEllipticArcBiasedNoRotation(double rx, double ry, double nextPositionXRelative, double nextPositionYRelative, bool largeArcFlag, bool sweepFlag)
  1253. {
  1254. double xStretchFactor = rx / ry; //get rx to ry ratio
  1255. (double[], double[]) values = sampleCircleArcBiasedNoRotation(ry, nextPositionXRelative, nextPositionYRelative, largeArcFlag, sweepFlag); //get a circular arc with radius ry
  1256. for (int j = 0; j < values.Item1.Length; j++)
  1257. {
  1258. values.Item1[j] = values.Item1[j] * xStretchFactor; //correct x coordinates to get an elliptical arc from a circular one
  1259. }
  1260. return values;
  1261. }
  1262. /// <summary>
  1263. /// samples a circular arc with given radius through coordinate origin and endpoint with specified properties
  1264. /// </summary>
  1265. /// <param name="r">radius</param>
  1266. /// <param name="nextPositionXRelative">x coordinate of next point</param>
  1267. /// <param name="nextPositionYRelative">y coordinate of next point</param>
  1268. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1269. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1270. /// <returns></returns>
  1271. private (double[], double[]) sampleCircleArcBiasedNoRotation(double r, double nextPositionXRelative, double nextPositionYRelative, bool largeArcFlag, bool sweepFlag)
  1272. {
  1273. // code adapted from https://stackoverflow.com/a/36211852
  1274. double radsq = r * r;
  1275. double q = Math.Sqrt(((nextPositionXRelative) * (nextPositionXRelative)) + ((nextPositionYRelative) * (nextPositionYRelative))); //Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
  1276. double x3 = (nextPositionXRelative) / 2; //(x1 + x2) / 2;
  1277. double y3 = (nextPositionYRelative) / 2; //(y1 + y2) / 2;
  1278. Console.WriteLine("radsq: " + radsq);
  1279. Console.WriteLine("q: " + q);
  1280. Console.WriteLine("x3: " + x3);
  1281. Console.WriteLine("y3: " + y3);
  1282. bool xPlusFlag; //flags needed to select center point "left" of the line between origin and the endpoint (will be used to select correct one ("left" or "right" one) later together with flags passed as arguments
  1283. bool yPlusFlag;
  1284. if (nextPositionXRelative > 0)
  1285. {
  1286. yPlusFlag = true; //left point lies above line
  1287. }
  1288. else
  1289. {
  1290. yPlusFlag = false; //left point lies below line
  1291. }
  1292. if (nextPositionYRelative > 0)
  1293. {
  1294. xPlusFlag = false; //left point lies left of line
  1295. }
  1296. else
  1297. {
  1298. xPlusFlag = true; //left point lies right of line
  1299. }
  1300. if(sweepFlag != largeArcFlag) //need "right" center point, not "left" one (refer to svg specification, sweepFlag means going around the circle in "clockwise" direction, largeArcFlag means tracing the larger of the two possible arcs in the selected direction)
  1301. {
  1302. xPlusFlag = !xPlusFlag;
  1303. yPlusFlag = !yPlusFlag;
  1304. }
  1305. double xC; // coordinates of center point of circle
  1306. double yC;
  1307. if(xPlusFlag) xC = x3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionYRelative) / q); //x3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((y1 - y2) / q);
  1308. else xC = x3 - Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionYRelative) / q);
  1309. if (yPlusFlag) yC = y3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionXRelative) / q); //y3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((x2-x1) / q);
  1310. else yC = y3 - Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionXRelative) / q);
  1311. Console.WriteLine("radsq - ((q / 2) * (q / 2))): " + (radsq - ((q / 2) * (q / 2))));
  1312. Console.WriteLine("Math.Sqrt(radsq - ((q / 2) * (q / 2))): " + Math.Sqrt(radsq - ((q / 2) * (q / 2))));
  1313. Console.WriteLine("computed center of circle (relative): point1= (0,0), point2= (" + nextPositionXRelative + "," + nextPositionYRelative + "), center= (" + xC + "," + yC + ")");
  1314. (double[], double[]) values = sampleCircleArcBiasedAroundCenter(-xC, -yC, nextPositionXRelative - xC, nextPositionYRelative - yC, r, sweepFlag);
  1315. for (int j = 0; j < values.Item1.Length; j++)
  1316. {
  1317. values.Item1[j] = values.Item1[j] + xC; //correct center point coordinate bias
  1318. values.Item2[j] = values.Item2[j] + yC;
  1319. }
  1320. return values;
  1321. }
  1322. /// <summary>
  1323. /// samples a circular arc with given radius around the center from the startpoint to the endpoint in the specified direction
  1324. /// </summary>
  1325. /// <param name="xStartPoint">x coordinate of the start point</param>
  1326. /// <param name="yStartPoint">y coordinate of the start point</param>
  1327. /// <param name="xFinalPoint">x coordinate of the final point</param>
  1328. /// <param name="yFinalPoint">y coordinate of the final point</param>
  1329. /// <param name="r">radius</param>
  1330. /// <param name="clockwise">direction</param>
  1331. /// <returns></returns>
  1332. private (double[], double[]) sampleCircleArcBiasedAroundCenter(double xStartPoint, double yStartPoint, double xFinalPoint, double yFinalPoint, double r, bool clockwise)
  1333. {
  1334. double phiEnd = Math.Atan2(yFinalPoint, xFinalPoint); // angles between points and origin and the positive x Axis
  1335. double phiStart = Math.Atan2(yStartPoint, xStartPoint);
  1336. double angle = ((double)2 * Math.PI) / (double)samplingRateEllipse; //compute angle increment (equal to the one used for ellipses)
  1337. int numberOfPoints = (int) Math.Ceiling(Math.Abs(phiEnd - phiStart) / angle); //compute number of points to sample
  1338. double[] xValues = new double[numberOfPoints];
  1339. double[] yValues = new double[numberOfPoints];
  1340. double phiCurrent = phiStart;
  1341. for (int j = 0; j < numberOfPoints-1; j++) //compute offset values of points for one quadrant
  1342. {
  1343. if (clockwise) phiCurrent -= angle; //get new angle
  1344. else phiCurrent += angle;
  1345. yValues[j] = Math.Sin(phiCurrent) * r; //angles are relative to positive x Axis!
  1346. xValues[j] = Math.Cos(phiCurrent) * r;
  1347. }
  1348. xValues[numberOfPoints - 1] = xFinalPoint; //(last segment always has an angle of less than or exactly 'angle')
  1349. yValues[numberOfPoints - 1] = yFinalPoint;
  1350. return (xValues, yValues);
  1351. }
  1352. /// <summary>
  1353. /// samples a cubic bezier curve with a static number of steps (samplingRateBezier)
  1354. /// </summary>
  1355. /// <param name="lastPositionX">x coordinate of last point</param>
  1356. /// <param name="lastPositionY">y coordinate of last point</param>
  1357. /// <param name="controlPoint1X">x coordinate of control point 1</param>
  1358. /// <param name="controlPoint1Y">y coordinate of control point 1</param>
  1359. /// <param name="controlPoint2X">x coordinate of control point 2</param>
  1360. /// <param name="controlPoint2Y">y coordinate of control point 2</param>
  1361. /// <param name="nextPositionX">x coordinate of next point</param>
  1362. /// <param name="nextPositionY">y coordinate of next point</param>
  1363. /// <returns>a List of Points containing all sampled points</returns>
  1364. private List<Point> SampleCubicBezier(double lastPositionX, double lastPositionY, double controlPoint1X, double controlPoint1Y, double controlPoint2X, double controlPoint2Y, double nextPositionX, double nextPositionY)
  1365. {
  1366. (double[], double[]) line1 = CreateDiscreteLine(lastPositionX, lastPositionY, controlPoint1X, controlPoint1Y);
  1367. (double[], double[]) line2 = CreateDiscreteLine(controlPoint1X, controlPoint1Y, controlPoint2X, controlPoint2Y);
  1368. (double[], double[]) line3 = CreateDiscreteLine(controlPoint2X, controlPoint2Y, nextPositionX, nextPositionY);
  1369. (double[], double[]) quadraticBezier1 = computeBezierStep(line1.Item1, line1.Item2, line2.Item1, line2.Item2);
  1370. (double[], double[]) quadraticBezier2 = computeBezierStep(line2.Item1, line2.Item2, line3.Item1, line3.Item2);
  1371. (double[], double[]) values = computeBezierStep(quadraticBezier1.Item1, quadraticBezier1.Item2, quadraticBezier2.Item1, quadraticBezier2.Item2);
  1372. List<Point> result = new List<Point>();
  1373. for (int j = 0; j < samplingRateBezier; j++)
  1374. {
  1375. result.Add(ScaleAndCreatePoint(values.Item1[j], values.Item2[j]));
  1376. }
  1377. return result;
  1378. }
  1379. /// <summary>
  1380. /// samples a quadratic bezier curve with a static number of steps (samplingRateBezier)
  1381. /// </summary>
  1382. /// <param name="lastPositionX">x coordinate of last point</param>
  1383. /// <param name="lastPositionY">y coordinate of last point</param>
  1384. /// <param name="controlPointX">x coordinate of control point</param>
  1385. /// <param name="controlPointY">y coordinate of control point</param>
  1386. /// <param name="nextPositionX">x coordinate of next point</param>
  1387. /// <param name="nextPositionY">y coordinate of next point</param>
  1388. /// <returns>a List of Points containing all sampled points</returns>
  1389. private List<Point> SampleQuadraticBezier(double lastPositionX, double lastPositionY, double controlPointX, double controlPointY, double nextPositionX, double nextPositionY)
  1390. {
  1391. (double[], double[]) line1 = CreateDiscreteLine(lastPositionX, lastPositionY, controlPointX, controlPointY);
  1392. (double[], double[]) line2 = CreateDiscreteLine(controlPointX, controlPointY, nextPositionX, nextPositionY);
  1393. (double[], double[]) values = computeBezierStep(line1.Item1, line1.Item2, line2.Item1, line2.Item2);
  1394. List<Point> result = new List<Point>();
  1395. for (int j = 0; j < samplingRateBezier; j++)
  1396. {
  1397. result.Add(ScaleAndCreatePoint(values.Item1[j], values.Item2[j]));
  1398. }
  1399. return result;
  1400. }
  1401. /// <summary>
  1402. /// create a discrete line with [samplingRateBezier] points (including start and end point) between two points
  1403. /// </summary>
  1404. /// <param name="point1X">coordinate of point 1</param>
  1405. /// <param name="point1Y">y coordinate of point 1</param>
  1406. /// <param name="point2X">x coordinate of point 2</param>
  1407. /// <param name="point2Y">y coordinate of point 2</param>
  1408. /// <returns>the discrete line as arrays of x and y coordinates</returns>
  1409. private (double[], double[]) CreateDiscreteLine(double point1X, double point1Y, double point2X, double point2Y)
  1410. {
  1411. double[] resultX = new double[samplingRateBezier];
  1412. double[] resultY = new double[samplingRateBezier];
  1413. for (int j = 0; j < samplingRateBezier; j++)
  1414. {
  1415. (double, double) pointResult = LinearInterpolationForBezier(point1X, point1Y, point2X, point2Y, j);
  1416. resultX[j] = pointResult.Item1;
  1417. resultY[j] = pointResult.Item2;
  1418. }
  1419. return (resultX, resultY);
  1420. }
  1421. /// <summary>
  1422. /// computes the discrete bezier curve between two given dicrete lines/curves
  1423. /// </summary>
  1424. /// <param name="line1X">x coordinates of all points in line 1</param>
  1425. /// <param name="line1Y">y coordinates of all points in line 1</param>
  1426. /// <param name="line2X">x coordinates of all points in line 2</param>
  1427. /// <param name="line2Y">y coordinates of all points in line 2</param>
  1428. /// <returns>the discrete bezier curve</returns>
  1429. private (double[], double[]) computeBezierStep(double[] line1X, double[] line1Y, double[] line2X, double[] line2Y)
  1430. {
  1431. double[] resultX = new double[samplingRateBezier];
  1432. double[] resultY = new double[samplingRateBezier];
  1433. for (int j = 0; j < samplingRateBezier; j++)
  1434. {
  1435. (double, double) pointResult = LinearInterpolationForBezier(line1X[j], line1Y[j], line2X[j], line2Y[j], j);
  1436. resultX[j] = pointResult.Item1;
  1437. resultY[j] = pointResult.Item2;
  1438. }
  1439. return (resultX, resultY);
  1440. }
  1441. /// <summary>
  1442. /// creates the linearly interpolated point at j/(samplingRateBezier - 1) between point 1 and point 2
  1443. /// </summary>
  1444. /// <param name="point1X">x coordinate of point 1</param>
  1445. /// <param name="point1Y">y coordinate of point 1</param>
  1446. /// <param name="point2X">x coordinate of point 2</param>
  1447. /// <param name="point2Y">y coordinate of point 2</param>
  1448. /// <param name="j">number of point to be interpolated, at a total number of [samplingRateBezier] points</param>
  1449. /// <returns>the linearly interpolated point</returns>
  1450. private (double, double) LinearInterpolationForBezier(double point1X, double point1Y, double point2X, double point2Y, int j)
  1451. {
  1452. double factor = ((double)1 / (double)(samplingRateBezier - 1)) * (double)j; //factor for linear interpolation
  1453. double x = point1X + ((point2X - point1X) * factor);
  1454. double y = point1Y + ((point2Y - point1Y) * factor);
  1455. return (x, y);
  1456. }
  1457. /// <summary>
  1458. /// parses a hierarchical svg element and all its sub-elements
  1459. /// </summary>
  1460. /// <param name="currentElement">the definition of the top level element as whitespace seperated String[]</param>
  1461. /// <param name="allLines">an array holding all lines of the input file</param>
  1462. /// <returns>the parsed element as a Line object, or null if the element is not supported</returns>
  1463. private List<Line> ParseMultiLineSVGElement(string[] currentElement, string[] allLines)
  1464. {
  1465. throw new NotImplementedException();
  1466. }
  1467. /// <summary>
  1468. /// removes the name of the attribute aswell as the '="' at the beginning and the '"' or '">' at the end of an attribute definition
  1469. /// </summary>
  1470. /// <param name="definition">the definition from the svg file</param>
  1471. /// <returns>the value of the attribute, as String (the part of definition contained between '"'s)</returns>
  1472. private String ParseSingleSVGAttribute(String definition)
  1473. {
  1474. return definition.Split('"')[1];
  1475. }
  1476. /// <summary>
  1477. /// fetches a single svg element definition that may extend ovr several lines of the input file, iterates i to point to the last line of the element definition
  1478. /// </summary>
  1479. /// <param name="allLines">an array holding all lines of the input file</param>
  1480. /// <returns>the definition of the current svg element, as String[] split by whitespaces</returns>
  1481. private String[] GetCurrentElement(String[] allLines)
  1482. {
  1483. List<String> currentElementTemp = allLines[i].Split(whitespaces).ToList();
  1484. while (!currentElementTemp.Last().EndsWith(">"))
  1485. {
  1486. i++;
  1487. currentElementTemp.AddRange(allLines[i].Split(whitespaces).ToList());
  1488. }
  1489. return currentElementTemp.ToArray();
  1490. }
  1491. /// <summary>
  1492. /// applies the scale factor to the coordinates and creates a new Point
  1493. /// </summary>
  1494. /// <param name="x">unscaled x coordinate</param>
  1495. /// <param name="y">unscaled y coordinate</param>
  1496. /// <returns>new Point with scaled coordinates</returns>
  1497. private Point ScaleAndCreatePoint(double x, double y)
  1498. {
  1499. return new Point((int)Math.Round(x * scale), (int)Math.Round(y * scale));
  1500. }
  1501. /// <summary>
  1502. /// creates a representation of an ellipse as a List of Points by sampling the outline of the ellipse
  1503. /// </summary>
  1504. /// <param name="x">x coordinate of the center of the ellipse</param>
  1505. /// <param name="y">y coordinate of the center of the ellipse</param>
  1506. /// <param name="rx">x radius of the ellipse</param>
  1507. /// <param name="ry">y radius of the ellipse</param>
  1508. /// <returns>the parsed element as a List of Points</returns>
  1509. private List<Point> SampleEllipse(double x, double y, double rx, double ry)
  1510. {
  1511. List<Point> ellipse = new List<Point>();
  1512. double angle = ((double)2 * Math.PI) / (double)samplingRateEllipse;
  1513. double yScale = ry / rx;
  1514. Console.WriteLine("parsing ellipse: " + x + ";" + y + "(" + rx + "x" + ry + ")" + " " + yScale + ":" + angle);
  1515. double[] xValues = new double[samplingRateEllipse / 4];
  1516. double[] yValues = new double[samplingRateEllipse / 4];
  1517. for (int j = 0; j < samplingRateEllipse / 4; j++) //compute offset values of points for one quadrant
  1518. {
  1519. xValues[j] = Math.Sin((double)j * angle) * rx;
  1520. yValues[j] = Math.Cos((double)j * angle) * rx;
  1521. Console.WriteLine("parsed ellipse value: " + xValues[j] + ";" + yValues[j]);
  1522. }
  1523. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for first quadrant
  1524. {
  1525. int xCoord = Convert.ToInt32(Math.Round(x + xValues[j]));
  1526. int yCoord = Convert.ToInt32(Math.Round(y - yValues[j] * yScale));
  1527. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1528. Console.WriteLine("parsed ellipse point: " + xCoord + ";" + yCoord + " pointCount: " + (samplingRateEllipse / 4));
  1529. }
  1530. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for second quadrant
  1531. {
  1532. int xCoord = Convert.ToInt32(Math.Round(x + yValues[j]));
  1533. int yCoord = Convert.ToInt32(Math.Round(y + xValues[j] * yScale));
  1534. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1535. Console.WriteLine("parsed ellipse point: " + xCoord + ";" + yCoord + " pointCount: " + (samplingRateEllipse / 4));
  1536. }
  1537. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for third quadrant
  1538. {
  1539. int xCoord = Convert.ToInt32(Math.Round(x - xValues[j]));
  1540. int yCoord = Convert.ToInt32(Math.Round(y + yValues[j] * yScale));
  1541. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1542. Console.WriteLine("parsed ellipse point: " + xCoord + ";" + yCoord + " pointCount: " + (samplingRateEllipse / 4));
  1543. }
  1544. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for fourth quadrant
  1545. {
  1546. int xCoord = Convert.ToInt32(Math.Round(x - yValues[j]));
  1547. int yCoord = Convert.ToInt32(Math.Round(y - xValues[j] * yScale));
  1548. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1549. Console.WriteLine("parsed ellipse point: " + xCoord + ";" + yCoord + " pointCount: " + (samplingRateEllipse / 4));
  1550. }
  1551. ellipse.Add(ScaleAndCreatePoint(Convert.ToInt32(Math.Round(x + 0)), Convert.ToInt32(Math.Round(y - rx * yScale)))); //close ellipse
  1552. return ellipse;
  1553. }
  1554. }
  1555. }