VisPyVisuals.py 27 KB

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