VisPyVisuals.py 27 KB

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