Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.58 KB | None | 0 0
  1. using Makie
  2. using GeometryTypes
  3.  
  4. # Константы
  5. const openBranch = "("
  6. const closeBranch = ")"
  7.  
  8. const SHIRINA = 1500 # ширина (x)
  9. const VISOTA = 800 # высота (y)
  10. RADIUS = 30
  11.  
  12. # inputStr = "(((a+b)*(c+(d-(-b))))-(a/(d-(-b))))"
  13. inputStr = "((a+b)+((a+b)*c))"
  14.  
  15. # Структука "вершина"
  16. # n - номер вершины
  17. # childLeft - номер вершины левого ребенка
  18. # childRight - номер вершины правого ребенка
  19. # textShort - текст "развернутой" вершины
  20. # textFull - текст "свернутой" вершины
  21. # level - уровень
  22. # xLeft - левая граница по X
  23. # xRight - правая граница по X
  24. # x - координата x точки ((xLeft + xRight) / 2)
  25. # y - координата y точки
  26. # needChanged - нужно ли перерасчитывать вершину (для интерактивности), 1 - нужно, 0 - не нужно
  27. mutable struct Vertex
  28. index
  29. childLeft
  30. childRight
  31. textShort
  32. textFull
  33. level
  34. xLeft
  35. xRight
  36. x
  37. y
  38. needChanged
  39. end
  40.  
  41. # Массив с вершинами (изначальный)
  42. verteces = []
  43.  
  44. # Массив с вершинами (текущий)
  45. vertecesCurrent = []
  46.  
  47. function printVertecesCurrent()
  48. println("vertecesCurrent:")
  49. for i = 1:length(vertecesCurrent)
  50. println(vertecesCurrent[i])
  51. end
  52. end
  53.  
  54. # разбивает строку вида (arg1[+*-/]arg2) на 2 аргумента и знак и возвращает arg1, sign, arg2
  55. # (arg1 может отсутствовать (Например "(-b)"), в таком случае arg1 = "")
  56. function bracketParse(str)
  57. # Изначально flag = 0
  58. # При встрече открывающей скобки (всегда первый элемент) переключаем flag = 1
  59. # Пока flag = 1, добавляем символы в arg1
  60. # При встрече одного из знаков [+*-/], переключаем flag = 2 и записываем текущий сивмол в sign
  61. # Пока flag = 2, добавляем символы в arg2
  62. # При встрече закрывающей скобки (всегда последний элемент) завершаем работу
  63. flag = 0
  64.  
  65. sign = ""
  66. arg1 = ""
  67. arg2 = ""
  68.  
  69. for i = 1:length(str)
  70. symbol = SubString(str, i, i)
  71.  
  72. if symbol == openBranch
  73. flag = 1
  74. elseif occursin(r"[+*-/]", symbol)
  75. flag = 2
  76. sign = symbol
  77. elseif symbol == closeBranch
  78. break
  79. elseif flag == 1
  80. arg1 = arg1 * symbol
  81. elseif flag == 2
  82. arg2 = arg2 * symbol
  83. end
  84.  
  85. end
  86.  
  87. return arg1, sign, arg2
  88. end
  89.  
  90. # Проверяет наличие выражения в массиве (сравнение идет по атрибуту textFull)
  91. function checkExpInTextFull(exp)
  92. for i = 1:length(verteces)
  93. v = verteces[i]
  94. if v.textFull == exp
  95. return true
  96. end
  97. end
  98. return false
  99. end
  100.  
  101. # Расчитывает массив verteces
  102. function calculateVerteces(str)
  103. # Не открывающая скобка может быть только после последней замены, когда строка принимает вид vertex_X
  104. # В таком случае замена не нужна
  105. if SubString(str, 1, 1) == openBranch
  106. haveBranch = false
  107. indexStart = 1
  108.  
  109. # Начальное количество элементов в массиве
  110. # Необходимо для замены новых добавившихся элментов
  111. startLengthVerteces = length(verteces)
  112.  
  113. # Идем по строке, пока не встретим конструкцию "(arg1*sign*arg2)"
  114. for i = 1:length(str)
  115. symbol = SubString(str, i, i)
  116.  
  117. if symbol == openBranch
  118. indexStart = i
  119. haveBranch = true
  120. elseif symbol == closeBranch && haveBranch
  121. # Вытаскиываем выражение из строки
  122. branchExp = SubString(str, indexStart, i)
  123.  
  124. # Разбиваем выражение на аргументы и знак (arg1 может быть равен пустой строке). Например (-b)
  125. arg1, sign, arg2 = bracketParse(branchExp)
  126. indexLeft = 0
  127. indexRight = 0
  128.  
  129. isArgsEqual = false
  130.  
  131. # Если первый и второй аргументы равны, тогда добавляем в массив только второй аргумент
  132. if arg1 != arg2
  133. if arg1 != ""
  134. # Если аргумент не иммеет вид "vertex_X"
  135. # Аргумент имеет такой вид только в том случае, если он уже был заменен
  136. if !occursin(r"^vertex_[0-9]+", arg1)
  137. # Если аргумент новый, то мы вычисляем его атрибуты и добавлем в массив
  138. indexLeft = length(verteces) + 1
  139. childLeft = 0
  140. childRight = 0
  141. textShort = arg1
  142. textFull = arg1
  143.  
  144. level = 0
  145. xLeft = 0
  146. xRight = 0
  147. x = 0
  148. y = 0
  149. needChanged = 0
  150. push!(verteces, Vertex(indexLeft, childLeft, childRight, textShort, textFull, level, xLeft, xRight, x, y, needChanged))
  151. else
  152. # Если аргумент старый, то мы его не добавляем в массив.
  153. # Вычисляем какой это аргумент по номеру и запоминаем этот номер для добавления ссылки на этот аргумент при занесении всего выражения
  154. indexLeft = parse(Int64, SubString(arg1, 8, length(arg1)))
  155. end
  156. end
  157. else
  158. isArgsEqual = true
  159. end
  160.  
  161. # Все аналогично arg1, за исключением проверки на пустую строку, т.к. arg2 всегда присутствует
  162. if !occursin(r"^vertex_[0-9]+", arg2)
  163. indexRight = length(verteces) + 1
  164. childLeft = 0
  165. childRight = 0
  166. textShort = arg2
  167. textFull = arg2
  168.  
  169. level = 0
  170. xLeft = 0
  171. xRight = 0
  172. x = 0
  173. y = 0
  174. needChanged = 0
  175. push!(verteces, Vertex(indexRight, childLeft, childRight, textShort, textFull, level, xLeft, xRight, x, y, needChanged))
  176. else
  177. indexRight = parse(Int64, SubString(arg2, 8, length(arg2)))
  178. end
  179.  
  180. # Если аргументы одинаковые, то мы добавляем только второй аргумент
  181. # В таком случае индекс левого и правого ребенка совпадает
  182. if isArgsEqual
  183. indexLeft = indexRight
  184. end
  185.  
  186. # Высчитываем атрибуты для всего выражения
  187. index = length(verteces) + 1
  188. childLeft = indexLeft
  189. childRight = indexRight
  190. textShort = sign
  191.  
  192. textFull = "("
  193. # Если arg1 отсутсвует, тогда в полное выражение его не добавляем
  194. if childLeft != 0
  195. textFull = textFull * verteces[childLeft].textFull
  196. end
  197. textFull = textFull * sign * verteces[childRight].textFull * ")"
  198.  
  199. level = 0
  200. xLeft = 0
  201. xRight = 0
  202. x = 0
  203. y = 0
  204. needChanged = 0
  205. push!(verteces, Vertex(index, childLeft, childRight, textShort, textFull, level, xLeft, xRight, x, y, needChanged))
  206.  
  207. # Заменяем добавленные выражения
  208. # Сначала заменяем последнее, т.к. оно включает предыдущие (если были)
  209. oldExp = branchExp
  210. newExp = "vertex_$(verteces[end].index)"
  211. str = replace(str, oldExp => newExp)
  212.  
  213. # Если sign = "+|*", то мы замеянем не только arg1*sign*arg2, но и arg2*sign*arg1
  214. if occursin(r"[+*]", sign)
  215. oldExp = "(" * arg2 * sign * arg1 * ")"
  216. newExp = "vertex_$(verteces[end].index)"
  217. str = replace(str, oldExp => newExp)
  218. end
  219.  
  220. # После этого заменяем остальные (если были)
  221. for i = startLengthVerteces + 1:length(verteces) - 1
  222. oldExp = verteces[i].textFull
  223. newExp = "vertex_$(verteces[i].index)"
  224. str = replace(str, oldExp => newExp)
  225. end
  226.  
  227. # println(str)
  228. # Запускаем рекурсию для обновленной строки
  229. calculateVerteces(str)
  230.  
  231. break
  232. end
  233.  
  234. end
  235.  
  236.  
  237. else
  238. # Удаляет внешние скобки у выражений, т.к. они лишние
  239. for i = 1:length(verteces)
  240. v = verteces[i]
  241. if SubString(v.textFull, 1, 1) == openBranch
  242. v.textFull = SubString(v.textFull, 2, length(v.textFull) - 1)
  243. end
  244. end
  245. end
  246. end
  247.  
  248. # Рассчитывает уровни в массиве verteces
  249. # Рассчитывает границы по X в массиве verteces
  250. function calculateVertecesLevelsAndBordersX(index, level, xLeft, xRight)
  251. v = verteces[index]
  252.  
  253. # Если уровень равен нулю, значит он еще не инициализирован, в таком случае инициализриуем его и границы
  254. # Если уровень меньше текущего, тогда заменяем его на новый, и заменяекм границы
  255. if v.level == 0 || v.level < level
  256. v.level = level
  257. v.xLeft = xLeft
  258. v.xRight = xRight
  259. end
  260.  
  261. # Рекурсия для левого
  262. childLeft = v.childLeft
  263. if childLeft != 0
  264. calculateVertecesLevelsAndBordersX(childLeft, level + 1, xLeft, xLeft + (xRight - xLeft) / 2)
  265. end
  266.  
  267. # Рекурсия для правого
  268. childRight = v.childRight
  269. if childRight != 0
  270. if childLeft != 0
  271. calculateVertecesLevelsAndBordersX(childRight, level + 1, xLeft + (xRight - xLeft) / 2, xRight)
  272. else
  273. # Если childLeft == 0, т.е. всего один ребенок, то тогда границы не меняются
  274. calculateVertecesLevelsAndBordersX(childRight, level + 1, xLeft, xRight)
  275. end
  276. end
  277. end
  278.  
  279. # Рассчитывает уровни в массиве vertecesCurrent
  280. # Рассчитывает границы по X в массиве vertecesCurrent
  281. function calculateVertecesCurrentLevelsAndBordersX(index, level, xLeft, xRight)
  282. v = vertecesCurrent[index]
  283.  
  284. # Если уровень равен нулю, значит он еще не инициализирован, в таком случае инициализриуем его и границы
  285. # Если уровень меньше текущего, тогда заменяем его на новый, и заменяекм границы
  286. if v.needChanged == 1
  287. if v.level == 0 || v.level < level
  288. v.level = level
  289. v.xLeft = xLeft
  290. v.xRight = xRight
  291. end
  292. end
  293.  
  294. # Рекурсия для левого
  295. childLeft = v.childLeft
  296. if childLeft != 0
  297. calculateVertecesCurrentLevelsAndBordersX(childLeft, level + 1, xLeft, xLeft + (xRight - xLeft) / 2)
  298. end
  299.  
  300. # Рекурсия для правого
  301. childRight = v.childRight
  302. if childRight != 0
  303. if childLeft != 0
  304. calculateVertecesCurrentLevelsAndBordersX(childRight, level + 1, xLeft + (xRight - xLeft) / 2, xRight)
  305. else
  306. # Если childLeft == 0, т.е. всего один ребенок, то тогда границы не меняются
  307. calculateVertecesCurrentLevelsAndBordersX(childRight, level + 1, xLeft, xRight)
  308. end
  309. end
  310. end
  311.  
  312. # Инициализирует массив vertecesCurrent
  313. function initVertecesCurrent()
  314. for i = 1:length(verteces)
  315. v = verteces[i]
  316. # Создаем копию объекта, чтобы не было ссылок
  317. push!(
  318. vertecesCurrent,
  319. Vertex(v.index, v.childLeft, v.childRight, v.textShort, v.textFull, v.level, v.xLeft, v.xRight, v.x, v.y, v.needChanged)
  320. )
  321. end
  322. recalcDownUpVertecesCurrent()
  323. # printVertecesCurrent()
  324. # recalcAndSwapChildrenIfNeed()
  325. end
  326.  
  327. # Очищает уровни и позиции всех вершин, у которых needChanged = 1 в массиве vertecesCurrent для перерасчета
  328. function clearLevelsAndPosVertecesCurrent()
  329. for i = 1:length(vertecesCurrent)
  330. v = vertecesCurrent[i]
  331. if v.needChanged == 1
  332. v.level = 0
  333. v.xLeft = 0
  334. v.xRight = 0
  335. v.x = 0
  336. v.y = 0
  337. end
  338. end
  339. end
  340.  
  341. # Перерасчиывает массив vertecesCurrent снизу вверх
  342. function recalcDownUpVertecesCurrent()
  343. level = getMaxLevelVerteces() - 1
  344. while level >= 1
  345. for i = 1:length(vertecesCurrent)
  346. v = vertecesCurrent[i]
  347. if v.level == level
  348. if v.childLeft != 0 && v.childRight != 0
  349. v.x = (vertecesCurrent[v.childLeft].x + vertecesCurrent[v.childRight].x) / 2
  350. elseif v.childLeft != 0
  351. v.x = vertecesCurrent[v.childLeft].x
  352. elseif v.childRight != 0
  353. v.x = vertecesCurrent[v.childRight].x
  354. end
  355. end
  356. end
  357. level = level - 1
  358. end
  359. end
  360.  
  361. # Меняет детей местами, если левый находится справа, а правый слева
  362. function recalcAndSwapChildrenIfNeed()
  363. maxLevel = getMaxLevelVerteces()
  364. # Идем по всем уровням сверху вниз
  365. for level = 1:maxLevel
  366. # Для каждого уровня идем по массиву
  367. for i = 1:length(vertecesCurrent)
  368. v = vertecesCurrent[i]
  369. # Если встретили элемент нужного нам уровня
  370. if v.level == level
  371. # Проверяем, правильно ли у него расположены дети
  372. if vertecesCurrent[v.childLeft].x > vertecesCurrent[v.childRight].x
  373. # Если дети расположены не правильно, то меняем их x, xLeft, xRight местами
  374. vLeft = vertecesCurrent[v.childLeft]
  375. vRight = vertecesCurrent[v.childRight]
  376.  
  377. vLeft.x, vLeft.xLeft, vLeft.xRight, vRight.x, vRight.xLeft, vRight.xRight = vRight.x, vRight.xLeft, vRight.xRight, vLeft.x, vLeft.xLeft, vLeft.xRight
  378.  
  379. # Перераситываем координаты для их детей
  380. # Сначала показываем, что для всех их детей надо пересчитать координаты, устанавливая флаг needChanged = 1, и удаляя их координаты x, y, xLeft, xRight
  381. if vLeft.childLeft != 0
  382. setNeedChangedOnChildren(vLeft.childLeft)
  383. end
  384. if vLeft.childRight != 0
  385. setNeedChangedOnChildren(vLeft.childRight)
  386. end
  387. if vRight.childLeft != 0
  388. setNeedChangedOnChildren(vRight.childLeft)
  389. end
  390. if vRight.childRight != 0
  391. setNeedChangedOnChildren(vRight.childRight)
  392. end
  393.  
  394. clearLevelsAndPosVertecesCurrent()
  395. calculateVertecesCurrentLevelsAndBordersX(length(vertecesCurrent), 1, 0, SHIRINA)
  396. calculatePosVertecesCurrent()
  397. setNeedChangedZero()
  398. # recalcDownUpVertecesCurrent()
  399.  
  400. return
  401.  
  402. end
  403. end
  404. end
  405. end
  406. end
  407.  
  408. # Перерасчиывает массив vertecesCurrent
  409. function recalcVertecesCurrent()
  410. clearLevelsAndPosVertecesCurrent()
  411. calculateVertecesCurrentLevelsAndBordersX(length(vertecesCurrent), 1, 0, SHIRINA)
  412. calculatePosVertecesCurrent()
  413. setNeedChangedZero()
  414. recalcDownUpVertecesCurrent()
  415.  
  416. # recalcAndSwapChildrenIfNeed()
  417. end
  418.  
  419. # Возвращает максимальный уровень из массива verteces
  420. function getMaxLevelVerteces()
  421. level = 1
  422. for i = 1:length(verteces)
  423. if verteces[i].level > level
  424. level = verteces[i].level
  425. end
  426. end
  427. return level
  428. end
  429.  
  430. # Возвращает максимальный уровень из массива vertecesCurrent
  431. function getMaxLevelVertecesCurrent()
  432. level = 1
  433. for i = 1:length(vertecesCurrent)
  434. if vertecesCurrent[i].level > level
  435. level = vertecesCurrent[i].level
  436. end
  437. end
  438. return level
  439. end
  440.  
  441. # Расчитывает позицию (x, y) вершины массива verteces
  442. function calculatePosVerteces()
  443. maxLevel = getMaxLevelVerteces()
  444.  
  445. for i = 1:length(verteces)
  446. v = verteces[i]
  447. v.x = (v.xLeft + v.xRight) / 2
  448. v.y = VISOTA / (maxLevel + 1) * (maxLevel - v.level + 1)
  449. end
  450. end
  451.  
  452. # Расчитывает позицию (x, y) вершины массива vertecesCurrent
  453. function calculatePosVertecesCurrent()
  454. # maxLevel = getMaxLevelVertecesCurrent()
  455. maxLevel = getMaxLevelVerteces()
  456.  
  457. for i = 1:length(vertecesCurrent)
  458. v = vertecesCurrent[i]
  459. if v.needChanged == 1
  460. v.x = (v.xLeft + v.xRight) / 2
  461. v.y = VISOTA / (maxLevel + 1) * (maxLevel - v.level + 1)
  462. end
  463. end
  464. end
  465.  
  466. # Проверяет, лежит ли точка (x, y) внутри круга с центром в точке (xc, yc) и радиусом (радиус задан как глобальная константа)
  467. function checkVertexInCircle(x, y, xc, yc)
  468. if (x - xc) ^ 2 + (y - yc) ^ 2 <= RADIUS ^ 2
  469. return true
  470. else
  471. return false
  472. end
  473. end
  474.  
  475. # Проверяет, лежит ли точка (x, y) внутри какой-либо вершины из массива verteces
  476. function checkPointInVertecesCurrent(x, y)
  477. for i = 1:length(vertecesCurrent)
  478. v = vertecesCurrent[i]
  479. if checkVertexInCircle(x, y, v.x, v.y)
  480. return i
  481. end
  482. end
  483. return -1
  484. end
  485.  
  486. # После перерасчета устанавливает needChanged = 0 у всех
  487. function setNeedChangedZero()
  488. for i = 1:length(vertecesCurrent)
  489. v = vertecesCurrent[i]
  490. v.needChanged = 0
  491. end
  492. end
  493.  
  494. # Устанавливает у вершины с данным индексом и у всех ее детей needChanged = 1
  495. function setNeedChangedOnChildren(index)
  496. v = vertecesCurrent[index]
  497. v.needChanged = 1
  498. if v.childLeft != 0
  499. setNeedChangedOnChildren(v.childLeft)
  500. end
  501. if v.childRight != 0
  502. setNeedChangedOnChildren(v.childRight)
  503. end
  504. end
  505.  
  506. # Интерактивность
  507. function interactivity(scene, index)
  508. v = vertecesCurrent[index]
  509.  
  510. # Развертка
  511. if v.childLeft == 0 && v.childRight == 0
  512. v.childLeft = verteces[index].childLeft
  513. if v.childLeft != 0
  514. setNeedChangedOnChildren(v.childLeft)
  515. end
  516. v.childRight = verteces[index].childRight
  517. if v.childRight != 0
  518. setNeedChangedOnChildren(v.childRight)
  519. end
  520. v.textShort = verteces[index].textShort
  521. else # Свертка
  522. # Обозначаем needChanged = 1 у всех детей, для того, чтобы пересчитать координаты
  523. if v.childLeft != 0
  524. setNeedChangedOnChildren(v.childLeft)
  525. end
  526. if v.childRight != 0
  527. setNeedChangedOnChildren(v.childRight)
  528. end
  529.  
  530. v.childLeft = 0
  531. v.childRight = 0
  532. v.textShort = v.textFull
  533. end
  534.  
  535. recalcVertecesCurrent()
  536. drawGraph(scene)
  537. end
  538.  
  539. # Очищает сцену
  540. function clearScene(scene)
  541. arr = Point{2,Float32}[]
  542. xLeft = 0
  543. xRight = 500
  544. yTop = 500
  545. yBot = 0
  546. mas = []
  547. push!(arr, Point2f0(xLeft, yBot))
  548. push!(arr, Point2f0(xLeft, yTop))
  549. push!(arr, Point2f0(xRight, yTop))
  550. push!(arr, Point2f0(xRight, yBot))
  551. push!(arr, Point2f0(xLeft, yBot))
  552. poly!(scene, arr, color = :white, strokewidth = 10000, strokecolor = :white)
  553. end
  554.  
  555. # Рисует круг в точке (x, y) с текстом "text" внутри
  556. function drawCircleWithText(scene, x, y, text)
  557. radius = convert(Float32, RADIUS)
  558.  
  559. points = decompose(Point2f0, Circle(Point2f0(x, y), radius))
  560. poly!(scene, points, color = :white, strokewidth = 2, strokecolor = :black)
  561.  
  562. text!(scene, text, textsize = 20, position = (x, y), align = (:center, :center))
  563. end
  564.  
  565. # Рисует линию из точки (x1, y1) в точку (x2, y2)
  566. function drawLine(scene, x1, y1, x2, y2)
  567. linesegments!(scene, [Point(x1,y1)=> Point(x2,y2)] )
  568. end
  569.  
  570. # Проверяет наличие элемента в массиве
  571. function checkElemInArray(elem, arr)
  572. for i = 1:length(arr)
  573. if arr[i] == elem
  574. return true
  575. end
  576. end
  577. return false
  578. end
  579.  
  580. # Рисует все вершины
  581. function drawCircles(scene, index, drawnVerteces)
  582. v = vertecesCurrent[index]
  583. drawCircleWithText(scene, v.x, v.y, v.textShort)
  584. # Добавляем в массив отрисованных вершин текущую вершину
  585. push!(drawnVerteces, index)
  586.  
  587. # Если левый ребенок еще не был отрисован
  588. if !checkElemInArray(v.childLeft, drawnVerteces)
  589. if v.childLeft != 0
  590. drawCircles(scene, v.childLeft, drawnVerteces)
  591. end
  592. end
  593.  
  594. # Если правый ребенок еще не был отрисован
  595. if !checkElemInArray(v.childRight, drawnVerteces)
  596. if v.childRight != 0
  597. drawCircles(scene, v.childRight, drawnVerteces)
  598. end
  599. end
  600. end
  601.  
  602. # Переводит градусы в радианы
  603. function degreeToRad(degree)
  604. return degree * pi / 180
  605. end
  606.  
  607. # Рисует "стрелку"
  608. function drawArrow(scene)
  609. end
  610.  
  611. # Рисует ребра графа от заданной вершины, а так же все ребра "детей" этой вершины
  612. function drawEdges(scene, index)
  613. # Угол, на который смещаются ребра относительно оси OX
  614. offsetAngle = 75
  615.  
  616. v = vertecesCurrent[index]
  617. x = v.x
  618. y = v.y
  619.  
  620. if v.childLeft != 0
  621. vLeft = vertecesCurrent[v.childLeft]
  622.  
  623. xLeft1 = x - RADIUS * cos(degreeToRad(offsetAngle))
  624. yLeft1 = y - RADIUS * sin(degreeToRad(offsetAngle))
  625.  
  626. xLeft2 = vLeft.x
  627. yLeft2 = vLeft.y + RADIUS
  628.  
  629. drawLine(scene, xLeft1, yLeft1, xLeft2, yLeft2)
  630. drawEdges(scene, v.childLeft)
  631. end
  632.  
  633. if v.childRight != 0
  634. if v.childLeft != 0
  635. vRight = vertecesCurrent[v.childRight]
  636.  
  637. xRight1 = x + RADIUS * cos(degreeToRad(offsetAngle))
  638. yRight1 = y - RADIUS * sin(degreeToRad(offsetAngle))
  639.  
  640. xRight2 = vRight.x
  641. yRight2 = vRight.y + RADIUS
  642.  
  643. drawLine(scene, xRight1, yRight1, xRight2, yRight2)
  644. drawEdges(scene, v.childRight)
  645. else
  646. vRight = vertecesCurrent[v.childRight]
  647.  
  648. xRight1 = x
  649. yRight1 = y - RADIUS
  650.  
  651. xRight2 = vRight.x
  652. yRight2 = vRight.y + RADIUS
  653.  
  654. drawLine(scene, xRight1, yRight1, xRight2, yRight2)
  655. drawEdges(scene, v.childRight)
  656. end
  657.  
  658.  
  659. end
  660. end
  661.  
  662. # Рисует граф
  663. function drawGraph(scene)
  664. clearScene(scene)
  665.  
  666. # Массив в котором содержатся все отрисованные вершины
  667. drawnVerteces = []
  668. drawCircles(scene, length(vertecesCurrent), drawnVerteces)
  669.  
  670. drawEdges(scene, length(vertecesCurrent))
  671. end
  672.  
  673. # Добавляем события на кнопки мыши
  674. function addMouseEvents(scene)
  675. on(scene.events.mousebuttons) do buttons
  676. if ispressed(scene, Mouse.left)
  677. pos = to_world(scene, Point2f0(scene.events.mouseposition[]))
  678.  
  679. numberVertex = checkPointInVertecesCurrent(pos[1], pos[2])
  680. if numberVertex != -1
  681. interactivity(scene, numberVertex)
  682. end
  683. end
  684. return
  685. end
  686. end
  687.  
  688. # Рисует формулу
  689. function drawFormula(formula)
  690. calculateVerteces(formula)
  691. calculateVertecesLevelsAndBordersX(length(verteces), 1, 0, SHIRINA)
  692. calculatePosVerteces()
  693.  
  694. initVertecesCurrent()
  695.  
  696. scene = Scene(resolution = (SHIRINA, VISOTA))
  697. addMouseEvents(scene)
  698. # Рисуем граф
  699. drawGraph(scene)
  700.  
  701. # Без этого не рисуется ????????????????????????
  702. clicks = Node(Point2f0[(0,0)])
  703. scatter!(scene, clicks, color = :red, marker = '+', markersize = 0)
  704. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement