VisPyVisuals.py 27 KB

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