VisPyVisuals.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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='gpc', 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):
  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. :return: int
  212. Index of shape
  213. """
  214. # Get new key
  215. self.key_lock.acquire(True)
  216. self.last_key += 1
  217. key = self.last_key
  218. self.key_lock.release()
  219. # Prepare data for translation
  220. self.data[key] = {'geometry': shape, 'color': color, 'alpha': alpha, 'face_color': face_color,
  221. 'visible': visible, 'layer': layer, 'tolerance': tolerance}
  222. # Add data to process pool if pool exists
  223. try:
  224. self.results[key] = self.pool.map_async(_update_shape_buffers, [self.data[key]])
  225. except:
  226. self.data[key] = _update_shape_buffers(self.data[key])
  227. if update:
  228. self.redraw() # redraw() waits for pool process end
  229. return key
  230. def remove(self, key, update=False):
  231. """
  232. Removes shape from collection
  233. :param key: int
  234. Shape index to remove
  235. :param update:
  236. Set True to redraw collection
  237. """
  238. # Remove process result
  239. self.results_lock.acquire(True)
  240. if key in list(self.results.copy().keys()):
  241. del self.results[key]
  242. self.results_lock.release()
  243. # Remove data
  244. del self.data[key]
  245. if update:
  246. self.__update()
  247. def clear(self, update=False):
  248. """
  249. Removes all shapes from collection
  250. :param update: bool
  251. Set True to redraw collection
  252. """
  253. self.data.clear()
  254. if update:
  255. self.__update()
  256. def __update(self):
  257. """
  258. Merges internal buffers, sets data to visuals, redraws collection on scene
  259. """
  260. mesh_vertices = [[] for _ in range(0, len(self._meshes))] # Vertices for mesh
  261. mesh_tris = [[] for _ in range(0, len(self._meshes))] # Faces for mesh
  262. mesh_colors = [[] for _ in range(0, len(self._meshes))] # Face colors
  263. line_pts = [[] for _ in range(0, len(self._lines))] # Vertices for line
  264. line_colors = [[] for _ in range(0, len(self._lines))] # Line color
  265. # Lock sub-visuals updates
  266. self.update_lock.acquire(True)
  267. # Merge shapes buffers
  268. for data in list(self.data.values()):
  269. if data['visible'] and 'line_pts' in data:
  270. try:
  271. line_pts[data['layer']] += data['line_pts']
  272. line_colors[data['layer']] += data['line_colors']
  273. mesh_tris[data['layer']] += [x + len(mesh_vertices[data['layer']])
  274. for x in data['mesh_tris']]
  275. mesh_vertices[data['layer']] += data['mesh_vertices']
  276. mesh_colors[data['layer']] += data['mesh_colors']
  277. except Exception as e:
  278. print("Data error", e)
  279. # Updating meshes
  280. for i, mesh in enumerate(self._meshes):
  281. if len(mesh_vertices[i]) > 0:
  282. set_state(polygon_offset_fill=False)
  283. mesh.set_data(np.asarray(mesh_vertices[i]), np.asarray(mesh_tris[i], dtype=np.uint32)
  284. .reshape((-1, 3)), face_colors=np.asarray(mesh_colors[i]))
  285. else:
  286. mesh.set_data()
  287. mesh._bounds_changed()
  288. # Updating lines
  289. for i, line in enumerate(self._lines):
  290. if len(line_pts[i]) > 0:
  291. line.set_data(np.asarray(line_pts[i]), np.asarray(line_colors[i]), self._line_width, 'segments')
  292. else:
  293. line.clear_data()
  294. line._bounds_changed()
  295. self._bounds_changed()
  296. self.update_lock.release()
  297. def redraw(self, indexes=None):
  298. """
  299. Redraws collection
  300. :param indexes: list
  301. Shape indexes to get from process pool
  302. """
  303. # Only one thread can update data
  304. self.results_lock.acquire(True)
  305. for i in list(self.data.copy().keys()) if not indexes else indexes:
  306. if i in list(self.results.copy().keys()):
  307. try:
  308. self.results[i].wait() # Wait for process results
  309. if i in self.data:
  310. self.data[i] = self.results[i].get()[0] # Store translated data
  311. del self.results[i]
  312. except Exception as e:
  313. print(e, indexes)
  314. self.results_lock.release()
  315. self.__update()
  316. def lock_updates(self):
  317. self.update_lock.acquire(True)
  318. def unlock_updates(self):
  319. self.update_lock.release()
  320. class TextGroup(object):
  321. def __init__(self, collection):
  322. self._collection = collection
  323. self._index = None
  324. self._visible = None
  325. def set(self, **kwargs):
  326. """
  327. Adds text to collection and store index
  328. :param kwargs: keyword arguments
  329. Arguments for TextCollection.add function
  330. """
  331. self._index = self._collection.add(**kwargs)
  332. def clear(self, update=False):
  333. """
  334. Removes text from collection, clear index
  335. :param update: bool
  336. Set True to redraw collection
  337. """
  338. if self._index is not None:
  339. self._collection.remove(self._index, False)
  340. self._index = None
  341. if update:
  342. self._collection.redraw()
  343. def redraw(self):
  344. """
  345. Redraws text collection
  346. """
  347. self._collection.redraw()
  348. @property
  349. def visible(self):
  350. """
  351. Visibility of group
  352. :return: bool
  353. """
  354. return self._visible
  355. @visible.setter
  356. def visible(self, value):
  357. """
  358. Visibility of group
  359. :param value: bool
  360. """
  361. self._visible = value
  362. try:
  363. self._collection.data[self._index]['visible'] = value
  364. except KeyError:
  365. print("VisPyVisuals.TextGroup.visible --> KeyError")
  366. pass
  367. self._collection.redraw()
  368. class TextCollectionVisual(TextVisual):
  369. def __init__(self, **kwargs):
  370. """
  371. Represents collection of shapes to draw on VisPy scene
  372. :param kwargs: keyword arguments
  373. Arguments to pass for TextVisual
  374. """
  375. self.data = {}
  376. self.last_key = -1
  377. self.lock = threading.Lock()
  378. super(TextCollectionVisual, self).__init__(**kwargs)
  379. self.freeze()
  380. def add(self, text, pos, visible=True, update=True):
  381. """
  382. Adds array of text to collection
  383. :param text: list
  384. Array of strings ['str1', 'str2', ... ]
  385. :param pos: list
  386. Array of string positions [(0, 0), (10, 10), ... ]
  387. :param update: bool
  388. Set True to redraw collection
  389. :return: int
  390. Index of array
  391. """
  392. # Get new key
  393. self.lock.acquire(True)
  394. self.last_key += 1
  395. key = self.last_key
  396. self.lock.release()
  397. # Prepare data for translation
  398. self.data[key] = {'text': text, 'pos': pos, 'visible': visible}
  399. if update:
  400. self.redraw()
  401. return key
  402. def remove(self, key, update=False):
  403. """
  404. Removes shape from collection
  405. :param key: int
  406. Shape index to remove
  407. :param update:
  408. Set True to redraw collection
  409. """
  410. del self.data[key]
  411. if update:
  412. self.__update()
  413. def clear(self, update=False):
  414. """
  415. Removes all shapes from colleciton
  416. :param update: bool
  417. Set True to redraw collection
  418. """
  419. self.data.clear()
  420. if update:
  421. self.__update()
  422. def __update(self):
  423. """
  424. Merges internal buffers, sets data to visuals, redraws collection on scene
  425. """
  426. labels = []
  427. pos = []
  428. # Merge buffers
  429. for data in list(self.data.values()):
  430. if data['visible']:
  431. try:
  432. labels += data['text']
  433. pos += data['pos']
  434. except Exception as e:
  435. print("Data error", e)
  436. # Updating text
  437. if len(labels) > 0:
  438. self.text = labels
  439. self.pos = pos
  440. else:
  441. self.text = None
  442. self.pos = (0, 0)
  443. self._bounds_changed()
  444. def redraw(self):
  445. """
  446. Redraws collection
  447. """
  448. self.__update()
  449. # Add 'enabled' property to visual nodes
  450. def create_fast_node(subclass):
  451. # Create a new subclass of Node.
  452. # Decide on new class name
  453. clsname = subclass.__name__
  454. if not (clsname.endswith('Visual') and
  455. issubclass(subclass, visuals.BaseVisual)):
  456. raise RuntimeError('Class "%s" must end with Visual, and must '
  457. 'subclass BaseVisual' % clsname)
  458. clsname = clsname[:-6]
  459. # Generate new docstring based on visual docstring
  460. try:
  461. doc = generate_docstring(subclass, clsname)
  462. except Exception:
  463. # If parsing fails, just return the original Visual docstring
  464. doc = subclass.__doc__
  465. # New __init__ method
  466. def __init__(self, *args, **kwargs):
  467. parent = kwargs.pop('parent', None)
  468. name = kwargs.pop('name', None)
  469. self.name = name # to allow __str__ before Node.__init__
  470. self._visual_superclass = subclass
  471. # parent: property,
  472. # _parent: attribute of Node class
  473. # __parent: attribute of fast_node class
  474. self.__parent = parent
  475. self._enabled = False
  476. subclass.__init__(self, *args, **kwargs)
  477. self.unfreeze()
  478. VisualNode.__init__(self, parent=parent, name=name)
  479. self.freeze()
  480. # Create new class
  481. cls = type(clsname, (VisualNode, subclass),
  482. {'__init__': __init__, '__doc__': doc})
  483. # 'Enabled' property clears/restores 'parent' property of Node class
  484. # Scene will be painted quicker than when using 'visible' property
  485. def get_enabled(self):
  486. return self._enabled
  487. def set_enabled(self, enabled):
  488. if enabled:
  489. self.parent = self.__parent # Restore parent
  490. else:
  491. if self.parent: # Store parent
  492. self.__parent = self.parent
  493. self.parent = None
  494. cls.enabled = property(get_enabled, set_enabled)
  495. return cls
  496. ShapeCollection = create_fast_node(ShapeCollectionVisual)
  497. TextCollection = create_fast_node(TextCollectionVisual)
  498. Cursor = create_fast_node(MarkersVisual)