VisPyVisuals.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Dennis Hayrullin #
  5. # Date: 2/5/2016 #
  6. # MIT Licence #
  7. # ##########################################################
  8. from vispy.visuals import CompoundVisual, LineVisual, MeshVisual, TextVisual, MarkersVisual
  9. from vispy.scene.visuals import VisualNode, generate_docstring, visuals
  10. from vispy.gloo import set_state
  11. from vispy.color import Color
  12. from shapely.geometry import Polygon, LineString, LinearRing
  13. import threading
  14. import numpy as np
  15. from flatcamGUI.VisPyTesselators import GLUTess
  16. class FlatCAMLineVisual(LineVisual):
  17. def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip',
  18. method='gl', antialias=False):
  19. LineVisual.__init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip',
  20. method='gl', antialias=True)
  21. def clear_data(self):
  22. self._bounds = None
  23. self._pos = None
  24. self._changed['pos'] = True
  25. self.update()
  26. def _update_shape_buffers(data, triangulation='glu'):
  27. """
  28. Translates Shapely geometry to internal buffers for speedup redraws
  29. :param data: dict
  30. Input shape data
  31. :param triangulation: str
  32. Triangulation engine
  33. """
  34. mesh_vertices = [] # Vertices for mesh
  35. mesh_tris = [] # Faces for mesh
  36. mesh_colors = [] # Face colors
  37. line_pts = [] # Vertices for line
  38. line_colors = [] # Line color
  39. geo, color, face_color, tolerance = data['geometry'], data['color'], data['face_color'], data['tolerance']
  40. if geo is not None and not geo.is_empty:
  41. simple = geo.simplify(tolerance) if tolerance else geo # Simplified shape
  42. pts = [] # Shape line points
  43. tri_pts = [] # Mesh vertices
  44. tri_tris = [] # Mesh faces
  45. if type(geo) == LineString:
  46. # Prepare lines
  47. pts = _linestring_to_segments(list(simple.coords))
  48. elif type(geo) == LinearRing:
  49. # Prepare lines
  50. pts = _linearring_to_segments(list(simple.coords))
  51. elif type(geo) == Polygon:
  52. # Prepare polygon faces
  53. if face_color is not None:
  54. if triangulation == 'glu':
  55. gt = GLUTess()
  56. tri_tris, tri_pts = gt.triangulate(simple)
  57. else:
  58. print("Triangulation type '%s' isn't implemented. Drawing only edges." % triangulation)
  59. # Prepare polygon edges
  60. if color is not None:
  61. pts = _linearring_to_segments(list(simple.exterior.coords))
  62. for ints in simple.interiors:
  63. pts += _linearring_to_segments(list(ints.coords))
  64. # Appending data for mesh
  65. if len(tri_pts) > 0 and len(tri_tris) > 0:
  66. mesh_tris += tri_tris
  67. mesh_vertices += tri_pts
  68. mesh_colors += [Color(face_color).rgba] * (len(tri_tris) // 3)
  69. # Appending data for line
  70. if len(pts) > 0:
  71. line_pts += pts
  72. line_colors += [Color(color).rgba] * len(pts)
  73. # Store buffers
  74. data['line_pts'] = line_pts
  75. data['line_colors'] = line_colors
  76. data['mesh_vertices'] = mesh_vertices
  77. data['mesh_tris'] = mesh_tris
  78. data['mesh_colors'] = mesh_colors
  79. # Clear shapely geometry
  80. del data['geometry']
  81. return data
  82. def _linearring_to_segments(arr):
  83. # Close linear ring
  84. """
  85. Translates linear ring to line segments
  86. :param arr: numpy.array
  87. Array of linear ring vertices
  88. :return: numpy.array
  89. Line segments
  90. """
  91. if arr[0] != arr[-1]:
  92. arr.append(arr[0])
  93. return _linestring_to_segments(arr)
  94. def _linestring_to_segments(arr):
  95. """
  96. Translates line strip to segments
  97. :param arr: numpy.array
  98. Array of line strip vertices
  99. :return: numpy.array
  100. Line segments
  101. """
  102. return [arr[i // 2] for i in range(0, len(arr) * 2)][1:-1]
  103. class ShapeGroup(object):
  104. def __init__(self, collection):
  105. """
  106. Represents group of shapes in collection
  107. :param collection: ShapeCollection
  108. Collection to work with
  109. """
  110. self._collection = collection
  111. self._indexes = []
  112. self._visible = True
  113. self._color = None
  114. def add(self, **kwargs):
  115. """
  116. Adds shape to collection and store index in group
  117. :param kwargs: keyword arguments
  118. Arguments for ShapeCollection.add function
  119. """
  120. self._indexes.append(self._collection.add(**kwargs))
  121. def clear(self, update=False):
  122. """
  123. Removes group shapes from collection, clear indexes
  124. :param update: bool
  125. Set True to redraw collection
  126. """
  127. for i in self._indexes:
  128. self._collection.remove(i, False)
  129. del self._indexes[:]
  130. if update:
  131. self._collection.redraw([]) # Skip waiting results
  132. def redraw(self):
  133. """
  134. Redraws shape collection
  135. """
  136. self._collection.redraw(self._indexes)
  137. @property
  138. def visible(self):
  139. """
  140. Visibility of group
  141. :return: bool
  142. """
  143. return self._visible
  144. @visible.setter
  145. def visible(self, value):
  146. """
  147. Visibility of group
  148. :param value: bool
  149. """
  150. self._visible = value
  151. for i in self._indexes:
  152. self._collection.data[i]['visible'] = value
  153. self._collection.redraw([])
  154. class ShapeCollectionVisual(CompoundVisual):
  155. def __init__(self, line_width=1, triangulation='vispy', layers=3, pool=None, **kwargs):
  156. """
  157. Represents collection of shapes to draw on VisPy scene
  158. :param line_width: float
  159. Width of lines/edges
  160. :param triangulation: str
  161. Triangulation method used for polygons translation
  162. 'vispy' - VisPy lib triangulation
  163. 'gpc' - Polygon2 lib
  164. :param layers: int
  165. Layers count
  166. Each layer adds 2 visuals on VisPy scene. Be careful: more layers cause less fps
  167. :param kwargs:
  168. """
  169. self.data = {}
  170. self.last_key = -1
  171. # Thread locks
  172. self.key_lock = threading.Lock()
  173. self.results_lock = threading.Lock()
  174. self.update_lock = threading.Lock()
  175. # Process pool
  176. self.pool = pool
  177. self.results = {}
  178. self._meshes = [MeshVisual() for _ in range(0, layers)]
  179. # self._lines = [LineVisual(antialias=True) for _ in range(0, layers)]
  180. self._lines = [FlatCAMLineVisual(antialias=True) for _ in range(0, layers)]
  181. self._line_width = line_width
  182. self._triangulation = triangulation
  183. visuals_ = [self._lines[i // 2] if i % 2 else self._meshes[i // 2] for i in range(0, layers * 2)]
  184. CompoundVisual.__init__(self, visuals_, **kwargs)
  185. for m in self._meshes:
  186. pass
  187. m.set_gl_state(polygon_offset_fill=True, polygon_offset=(1, 1), cull_face=False)
  188. for l in self._lines:
  189. pass
  190. l.set_gl_state(blend=True)
  191. self.freeze()
  192. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  193. update=False, layer=1, tolerance=0.01, linewidth=None):
  194. """
  195. Adds shape to collection
  196. :return:
  197. :param shape: shapely.geometry
  198. Shapely geometry object
  199. :param color: str, tuple
  200. Line/edge color
  201. :param face_color: str, tuple
  202. Polygon face color
  203. :param visible: bool
  204. Shape visibility
  205. :param update: bool
  206. Set True to redraw collection
  207. :param layer: int
  208. Layer number. 0 - lowest.
  209. :param tolerance: float
  210. Geometry simplifying tolerance
  211. :param linewidth: int
  212. Not used, for compatibility
  213. :return: int
  214. Index of shape
  215. """
  216. # Get new key
  217. self.key_lock.acquire(True)
  218. self.last_key += 1
  219. key = self.last_key
  220. self.key_lock.release()
  221. # Prepare data for translation
  222. self.data[key] = {'geometry': shape, 'color': color, 'alpha': alpha, 'face_color': face_color,
  223. 'visible': visible, 'layer': layer, 'tolerance': tolerance}
  224. # Add data to process pool if pool exists
  225. try:
  226. self.results[key] = self.pool.map_async(_update_shape_buffers, [self.data[key]])
  227. except Exception as e:
  228. self.data[key] = _update_shape_buffers(self.data[key])
  229. if update:
  230. self.redraw() # redraw() waits for pool process end
  231. return key
  232. def remove(self, key, update=False):
  233. """
  234. Removes shape from collection
  235. :param key: int
  236. Shape index to remove
  237. :param update:
  238. Set True to redraw collection
  239. """
  240. # Remove process result
  241. self.results_lock.acquire(True)
  242. if key in list(self.results.copy().keys()):
  243. del self.results[key]
  244. self.results_lock.release()
  245. # Remove data
  246. del self.data[key]
  247. if update:
  248. self.__update()
  249. def clear(self, update=False):
  250. """
  251. Removes all shapes from collection
  252. :param update: bool
  253. Set True to redraw collection
  254. """
  255. self.data.clear()
  256. if update:
  257. self.__update()
  258. def __update(self):
  259. """
  260. Merges internal buffers, sets data to visuals, redraws collection on scene
  261. """
  262. mesh_vertices = [[] for _ in range(0, len(self._meshes))] # Vertices for mesh
  263. mesh_tris = [[] for _ in range(0, len(self._meshes))] # Faces for mesh
  264. mesh_colors = [[] for _ in range(0, len(self._meshes))] # Face colors
  265. line_pts = [[] for _ in range(0, len(self._lines))] # Vertices for line
  266. line_colors = [[] for _ in range(0, len(self._lines))] # Line color
  267. # Lock sub-visuals updates
  268. self.update_lock.acquire(True)
  269. # Merge shapes buffers
  270. for data in list(self.data.values()):
  271. if data['visible'] and 'line_pts' in data:
  272. try:
  273. line_pts[data['layer']] += data['line_pts']
  274. line_colors[data['layer']] += data['line_colors']
  275. mesh_tris[data['layer']] += [x + len(mesh_vertices[data['layer']])
  276. for x in data['mesh_tris']]
  277. mesh_vertices[data['layer']] += data['mesh_vertices']
  278. mesh_colors[data['layer']] += data['mesh_colors']
  279. except Exception as e:
  280. print("Data error", e)
  281. # Updating meshes
  282. for i, mesh in enumerate(self._meshes):
  283. if len(mesh_vertices[i]) > 0:
  284. set_state(polygon_offset_fill=False)
  285. mesh.set_data(np.asarray(mesh_vertices[i]), np.asarray(mesh_tris[i], dtype=np.uint32)
  286. .reshape((-1, 3)), face_colors=np.asarray(mesh_colors[i]))
  287. else:
  288. mesh.set_data()
  289. mesh._bounds_changed()
  290. # Updating lines
  291. for i, line in enumerate(self._lines):
  292. if len(line_pts[i]) > 0:
  293. line.set_data(np.asarray(line_pts[i]), np.asarray(line_colors[i]), self._line_width, 'segments')
  294. else:
  295. line.clear_data()
  296. line._bounds_changed()
  297. self._bounds_changed()
  298. self.update_lock.release()
  299. def redraw(self, indexes=None):
  300. """
  301. Redraws collection
  302. :param indexes: list
  303. Shape indexes to get from process pool
  304. """
  305. # Only one thread can update data
  306. self.results_lock.acquire(True)
  307. for i in list(self.data.copy().keys()) if not indexes else indexes:
  308. if i in list(self.results.copy().keys()):
  309. try:
  310. self.results[i].wait() # Wait for process results
  311. if i in self.data:
  312. self.data[i] = self.results[i].get()[0] # Store translated data
  313. del self.results[i]
  314. except Exception as e:
  315. print(e, indexes)
  316. self.results_lock.release()
  317. self.__update()
  318. def lock_updates(self):
  319. self.update_lock.acquire(True)
  320. def unlock_updates(self):
  321. self.update_lock.release()
  322. class TextGroup(object):
  323. def __init__(self, collection):
  324. self._collection = collection
  325. self._index = None
  326. self._visible = None
  327. def set(self, **kwargs):
  328. """
  329. Adds text to collection and store index
  330. :param kwargs: keyword arguments
  331. Arguments for TextCollection.add function
  332. """
  333. self._index = self._collection.add(**kwargs)
  334. def clear(self, update=False):
  335. """
  336. Removes text from collection, clear index
  337. :param update: bool
  338. Set True to redraw collection
  339. """
  340. if self._index is not None:
  341. self._collection.remove(self._index, False)
  342. self._index = None
  343. if update:
  344. self._collection.redraw()
  345. def redraw(self):
  346. """
  347. Redraws text collection
  348. """
  349. self._collection.redraw()
  350. @property
  351. def visible(self):
  352. """
  353. Visibility of group
  354. :return: bool
  355. """
  356. return self._visible
  357. @visible.setter
  358. def visible(self, value):
  359. """
  360. Visibility of group
  361. :param value: bool
  362. """
  363. self._visible = value
  364. if self._index:
  365. try:
  366. self._collection.data[self._index]['visible'] = value
  367. except KeyError as e:
  368. print("VisPyVisuals.TextGroup.visible --> KeyError --> %s" % str(e))
  369. pass
  370. self._collection.redraw()
  371. class TextCollectionVisual(TextVisual):
  372. def __init__(self, **kwargs):
  373. """
  374. Represents collection of shapes to draw on VisPy scene
  375. :param kwargs: keyword arguments
  376. Arguments to pass for TextVisual
  377. """
  378. self.data = {}
  379. self.last_key = -1
  380. self.lock = threading.Lock()
  381. self.method = 'gpu'
  382. super(TextCollectionVisual, self).__init__(**kwargs)
  383. self.freeze()
  384. def add(self, text, pos, visible=True, update=True, font_size=9, color='black'):
  385. """
  386. Adds array of text to collection
  387. :param text: list
  388. Array of strings ['str1', 'str2', ... ]
  389. :param pos: list
  390. Array of string positions [(0, 0), (10, 10), ... ]
  391. :param visible: bool
  392. | Set True to make it visible
  393. :param update: bool
  394. Set True to redraw collection
  395. :param font_size: int
  396. Set font size to redraw collection
  397. :param color: string
  398. Set font color to redraw collection
  399. :return: int
  400. Index of array
  401. """
  402. # Get new key
  403. self.lock.acquire(True)
  404. self.last_key += 1
  405. key = self.last_key
  406. self.lock.release()
  407. # Prepare data for translation
  408. self.data[key] = {'text': text, 'pos': pos, 'visible': visible,'font_size': font_size, 'color': color}
  409. if update:
  410. self.redraw()
  411. return key
  412. def remove(self, key, update=False):
  413. """
  414. Removes shape from collection
  415. :param key: int
  416. Shape index to remove
  417. :param update:
  418. Set True to redraw collection
  419. """
  420. del self.data[key]
  421. if update:
  422. self.__update()
  423. def clear(self, update=False):
  424. """
  425. Removes all shapes from colleciton
  426. :param update: bool
  427. Set True to redraw collection
  428. """
  429. self.data.clear()
  430. if update:
  431. self.__update()
  432. def __update(self):
  433. """
  434. Merges internal buffers, sets data to visuals, redraws collection on scene
  435. """
  436. labels = []
  437. pos = []
  438. font_s = 9
  439. color = 'black'
  440. # Merge buffers
  441. for data in list(self.data.values()):
  442. if data['visible']:
  443. try:
  444. labels += data['text']
  445. pos += data['pos']
  446. font_s = data['font_size']
  447. color = data['color']
  448. except Exception as e:
  449. print("Data error", e)
  450. # Updating text
  451. if len(labels) > 0:
  452. self.text = labels
  453. self.pos = pos
  454. self.font_size = font_s
  455. self.color = color
  456. else:
  457. self.text = None
  458. self.pos = (0, 0)
  459. self._bounds_changed()
  460. def redraw(self):
  461. """
  462. Redraws collection
  463. """
  464. self.__update()
  465. # Add 'enabled' property to visual nodes
  466. def create_fast_node(subclass):
  467. # Create a new subclass of Node.
  468. # Decide on new class name
  469. clsname = subclass.__name__
  470. if not (clsname.endswith('Visual') and
  471. issubclass(subclass, visuals.BaseVisual)):
  472. raise RuntimeError('Class "%s" must end with Visual, and must '
  473. 'subclass BaseVisual' % clsname)
  474. clsname = clsname[:-6]
  475. # Generate new docstring based on visual docstring
  476. try:
  477. doc = generate_docstring(subclass, clsname)
  478. except Exception:
  479. # If parsing fails, just return the original Visual docstring
  480. doc = subclass.__doc__
  481. # New __init__ method
  482. def __init__(self, *args, **kwargs):
  483. parent = kwargs.pop('parent', None)
  484. name = kwargs.pop('name', None)
  485. self.name = name # to allow __str__ before Node.__init__
  486. self._visual_superclass = subclass
  487. # parent: property,
  488. # _parent: attribute of Node class
  489. # __parent: attribute of fast_node class
  490. self.__parent = parent
  491. self._enabled = False
  492. subclass.__init__(self, *args, **kwargs)
  493. self.unfreeze()
  494. VisualNode.__init__(self, parent=parent, name=name)
  495. self.freeze()
  496. # Create new class
  497. cls = type(clsname, (VisualNode, subclass),
  498. {'__init__': __init__, '__doc__': doc})
  499. # 'Enabled' property clears/restores 'parent' property of Node class
  500. # Scene will be painted quicker than when using 'visible' property
  501. def get_enabled(self):
  502. return self._enabled
  503. def set_enabled(self, enabled):
  504. if enabled:
  505. self.parent = self.__parent # Restore parent
  506. else:
  507. if self.parent: # Store parent
  508. self.__parent = self.parent
  509. self.parent = None
  510. cls.enabled = property(get_enabled, set_enabled)
  511. return cls
  512. ShapeCollection = create_fast_node(ShapeCollectionVisual)
  513. TextCollection = create_fast_node(TextCollectionVisual)
  514. Cursor = create_fast_node(MarkersVisual)