__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. """
  2. Python Library to Read and Write Surface Files in Freesurfer's TriangularSurface Format
  3. compatible with Freesurfer's MRISwriteTriangularSurface()
  4. https://github.com/freesurfer/freesurfer/blob/release_6_0_0/include/mrisurf.h#L1281
  5. https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/mrisurf.c
  6. https://raw.githubusercontent.com/freesurfer/freesurfer/release_6_0_0/utils/mrisurf.c
  7. Freesurfer
  8. https://surfer.nmr.mgh.harvard.edu/
  9. Edit Surface File
  10. >>> from freesurfer_surface import Surface, Vertex, Triangle
  11. >>>
  12. >>> surface = Surface.read_triangular('bert/surf/lh.pial'))
  13. >>>
  14. >>> vertex_a = surface.add_vertex(Vertex(0.0, 0.0, 0.0))
  15. >>> vertex_b = surface.add_vertex(Vertex(1.0, 1.0, 1.0))
  16. >>> vertex_c = surface.add_vertex(Vertex(2.0, 2.0, 2.0))
  17. >>> surface.triangles.append(Triangle((vertex_a, vertex_b, vertex_c)))
  18. >>>
  19. >>> surface.write_triangular('somewhere/else/lh.pial')
  20. List Labels in Annotation File
  21. >>> from freesurfer_surface import Annotation
  22. >>>
  23. >>> annotation = Annotation.read('bert/label/lh.aparc.annot')
  24. >>> for label in annotation.labels.values():
  25. >>> print(label.index, label.hex_color_code, label.name)
  26. Find Border of Labelled Region
  27. >>> surface = Surface.read_triangular('bert/surf/lh.pial'))
  28. >>> surface.load_annotation_file('bert/label/lh.aparc.annot')
  29. >>> region, = filter(lambda l: l.name == 'precentral',
  30. >>> annotation.labels.values())
  31. >>> print(surface.find_label_border_polygonal_chains(region))
  32. """
  33. import collections
  34. import contextlib
  35. import copy
  36. import datetime
  37. import itertools
  38. import locale
  39. import re
  40. import struct
  41. import typing
  42. import numpy
  43. try:
  44. from freesurfer_surface.version import __version__
  45. except ImportError: # ModuleNotFoundError not available in python<3.6
  46. # package is not installed
  47. __version__ = None
  48. class UnsupportedLocaleSettingError(locale.Error):
  49. pass
  50. @contextlib.contextmanager
  51. def setlocale(temporary_locale):
  52. primary_locale = locale.setlocale(locale.LC_ALL)
  53. try:
  54. yield locale.setlocale(locale.LC_ALL, temporary_locale)
  55. except locale.Error as exc:
  56. if str(exc) == "unsupported locale setting":
  57. raise UnsupportedLocaleSettingError(temporary_locale) from exc
  58. raise exc # pragma: no cover
  59. finally:
  60. locale.setlocale(locale.LC_ALL, primary_locale)
  61. class Vertex(numpy.ndarray):
  62. def __new__(cls, right: float, anterior: float, superior: float):
  63. return numpy.array((right, anterior, superior), dtype=float).view(cls)
  64. @property
  65. def right(self) -> float:
  66. return self[0]
  67. @property
  68. def anterior(self) -> float:
  69. return self[1]
  70. @property
  71. def superior(self) -> float:
  72. return self[2]
  73. @property
  74. def __dict__(self) -> typing.Dict[str, float]:
  75. return {
  76. "right": self.right,
  77. "anterior": self.anterior,
  78. "superior": self.superior,
  79. }
  80. def __format_coords(self) -> str:
  81. return ", ".join(
  82. "{}={}".format(name, getattr(self, name))
  83. for name in ["right", "anterior", "superior"]
  84. )
  85. def __repr__(self) -> str:
  86. return "{}({})".format(type(self).__name__, self.__format_coords())
  87. def distance_mm(
  88. self,
  89. others: typing.Union["Vertex", typing.Iterable["Vertex"], numpy.ndarray],
  90. ) -> numpy.ndarray:
  91. if isinstance(others, Vertex):
  92. others = others.reshape((1, 3))
  93. return numpy.linalg.norm(self - others, axis=1)
  94. class PolygonalCircuit:
  95. _VERTEX_INDICES_TYPE = typing.Tuple[int]
  96. def __init__(self, vertex_indices: _VERTEX_INDICES_TYPE):
  97. self._vertex_indices = tuple(vertex_indices)
  98. assert all(isinstance(idx, int) for idx in self._vertex_indices)
  99. @property
  100. def vertex_indices(self):
  101. return self._vertex_indices
  102. def _normalize(self) -> "PolygonalCircuit":
  103. vertex_indices = collections.deque(self.vertex_indices)
  104. vertex_indices.rotate(-numpy.argmin(self.vertex_indices))
  105. if len(vertex_indices) > 2 and vertex_indices[-1] < vertex_indices[1]:
  106. vertex_indices.reverse()
  107. vertex_indices.rotate(1)
  108. return type(self)(vertex_indices)
  109. def __eq__(self, other: "PolygonalCircuit") -> bool:
  110. # pylint: disable=protected-access
  111. return self._normalize().vertex_indices == other._normalize().vertex_indices
  112. def __hash__(self) -> int:
  113. # pylint: disable=protected-access
  114. return hash(self._normalize()._vertex_indices)
  115. def adjacent_vertex_indices(
  116. self, vertices_num: int = 2
  117. ) -> typing.Iterable[typing.Tuple[int]]:
  118. vertex_indices_cycle = list(
  119. itertools.islice(
  120. itertools.cycle(self.vertex_indices),
  121. 0,
  122. len(self.vertex_indices) + vertices_num - 1,
  123. )
  124. )
  125. return zip(
  126. *(
  127. itertools.islice(
  128. vertex_indices_cycle, offset, len(self.vertex_indices) + offset
  129. )
  130. for offset in range(vertices_num)
  131. )
  132. )
  133. class LineSegment(PolygonalCircuit):
  134. def __init__(self, indices: PolygonalCircuit._VERTEX_INDICES_TYPE):
  135. super().__init__(indices)
  136. assert len(self.vertex_indices) == 2
  137. def __repr__(self) -> str:
  138. return "LineSegment(vertex_indices={})".format(self.vertex_indices)
  139. class Triangle(PolygonalCircuit):
  140. def __init__(self, indices: PolygonalCircuit._VERTEX_INDICES_TYPE):
  141. super().__init__(indices)
  142. assert len(self.vertex_indices) == 3
  143. def __repr__(self) -> str:
  144. return "Triangle(vertex_indices={})".format(self.vertex_indices)
  145. class PolygonalChainsNotOverlapingError(ValueError):
  146. pass
  147. class PolygonalChain:
  148. def __init__(self, vertex_indices: typing.Iterable[int]):
  149. self.vertex_indices = collections.deque(vertex_indices) # type: Deque[int]
  150. def __eq__(self, other: "PolygonalChain") -> bool:
  151. return self.vertex_indices == other.vertex_indices
  152. def __repr__(self) -> str:
  153. return "PolygonalChain(vertex_indices={})".format(tuple(self.vertex_indices))
  154. def connect(self, other: "PolygonalChain") -> None:
  155. if self.vertex_indices[-1] == other.vertex_indices[0]:
  156. self.vertex_indices.pop()
  157. self.vertex_indices.extend(other.vertex_indices)
  158. elif self.vertex_indices[-1] == other.vertex_indices[-1]:
  159. self.vertex_indices.pop()
  160. self.vertex_indices.extend(reversed(other.vertex_indices))
  161. elif self.vertex_indices[0] == other.vertex_indices[0]:
  162. self.vertex_indices.popleft()
  163. self.vertex_indices.extendleft(other.vertex_indices)
  164. elif self.vertex_indices[0] == other.vertex_indices[-1]:
  165. self.vertex_indices.popleft()
  166. self.vertex_indices.extendleft(reversed(other.vertex_indices))
  167. else:
  168. raise PolygonalChainsNotOverlapingError()
  169. def adjacent_vertex_indices(
  170. self, vertices_num: int = 2
  171. ) -> typing.Iterable[typing.Tuple[int]]:
  172. return zip(
  173. *(
  174. itertools.islice(self.vertex_indices, offset, len(self.vertex_indices))
  175. for offset in range(vertices_num)
  176. )
  177. )
  178. def segments(self) -> typing.Iterable[LineSegment]:
  179. return map(LineSegment, self.adjacent_vertex_indices(2))
  180. class Label:
  181. # pylint: disable=too-many-arguments
  182. def __init__(
  183. self, index: int, name: str, red: int, green: int, blue: int, transparency: int
  184. ):
  185. self.index = index # type: int
  186. self.name = name # type: str
  187. self.red = red # type: int
  188. self.green = green # type: int
  189. self.blue = blue # type: int
  190. self.transparency = transparency # type: int
  191. @property
  192. def color_code(self) -> int:
  193. if self.index == 0: # unknown
  194. return 0
  195. return int.from_bytes(
  196. (self.red, self.green, self.blue, self.transparency),
  197. byteorder="little",
  198. signed=False,
  199. )
  200. @property
  201. def hex_color_code(self) -> str:
  202. return "#{:02x}{:02x}{:02x}".format(self.red, self.green, self.blue)
  203. def __str__(self) -> str:
  204. return "Label(name={}, index={}, color={})".format(
  205. self.name, self.index, self.hex_color_code
  206. )
  207. def __repr__(self) -> str:
  208. return str(self)
  209. class Annotation:
  210. # pylint: disable=too-few-public-methods
  211. _TAG_OLD_COLORTABLE = b"\0\0\0\x01"
  212. def __init__(self):
  213. self.vertex_label_index = {} # type: Dict[int, int]
  214. self.colortable_path = None # type: Optional[bytes]
  215. self.labels = {} # type: Dict[int, Label]
  216. @staticmethod
  217. def _read_label(stream: typing.BinaryIO) -> Label:
  218. index, name_length = struct.unpack(">II", stream.read(4 * 2))
  219. name = stream.read(name_length - 1).decode()
  220. assert stream.read(1) == b"\0"
  221. red, green, blue, transparency = struct.unpack(">IIII", stream.read(4 * 4))
  222. return Label(
  223. index=index,
  224. name=name,
  225. red=red,
  226. green=green,
  227. blue=blue,
  228. transparency=transparency,
  229. )
  230. def _read(self, stream: typing.BinaryIO) -> None:
  231. # https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles
  232. (annotations_num,) = struct.unpack(">I", stream.read(4))
  233. annotations = [
  234. struct.unpack(">II", stream.read(4 * 2)) for _ in range(annotations_num)
  235. ]
  236. assert stream.read(4) == self._TAG_OLD_COLORTABLE
  237. colortable_version, _, filename_length = struct.unpack(
  238. ">III", stream.read(4 * 3)
  239. )
  240. assert colortable_version > 0 # new version
  241. self.colortable_path = stream.read(filename_length - 1)
  242. assert stream.read(1) == b"\0"
  243. (labels_num,) = struct.unpack(">I", stream.read(4))
  244. self.labels = {
  245. label.index: label
  246. for label in (self._read_label(stream) for _ in range(labels_num))
  247. }
  248. label_index_by_color_code = {
  249. label.color_code: label.index for label in self.labels.values()
  250. }
  251. self.vertex_label_index = {
  252. vertex_index: label_index_by_color_code[color_code]
  253. for vertex_index, color_code in annotations
  254. }
  255. assert not stream.read(1)
  256. @classmethod
  257. def read(cls, annotation_file_path: str) -> "Annotation":
  258. annotation = cls()
  259. with open(annotation_file_path, "rb") as annotation_file:
  260. # pylint: disable=protected-access
  261. annotation._read(annotation_file)
  262. return annotation
  263. class Surface:
  264. # pylint: disable=too-many-instance-attributes
  265. _MAGIC_NUMBER = b"\xff\xff\xfe"
  266. _TAG_CMDLINE = b"\x00\x00\x00\x03"
  267. _TAG_OLD_SURF_GEOM = b"\x00\x00\x00\x14"
  268. _TAG_OLD_USEREALRAS = b"\x00\x00\x00\x02"
  269. _DATETIME_FORMAT = "%a %b %d %H:%M:%S %Y"
  270. def __init__(self):
  271. self.creator = None # type: Optional[bytes]
  272. self.creation_datetime = None # type: Optional[datetime.datetime]
  273. self.vertices = [] # type: List[Vertex]
  274. self.triangles = [] # type: List[Triangle]
  275. self.using_old_real_ras = False # type: bool
  276. self.volume_geometry_info = None # type: Optional[Tuple[bytes]]
  277. self.command_lines = [] # type: List[bytes]
  278. self.annotation = None # type: Optional[Annotation]
  279. @classmethod
  280. def _read_cmdlines(cls, stream: typing.BinaryIO) -> typing.Iterator[str]:
  281. while True:
  282. tag = stream.read(4)
  283. if not tag:
  284. return
  285. assert tag == cls._TAG_CMDLINE # might be TAG_GROUP_AVG_SURFACE_AREA
  286. # TAGwrite
  287. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/tags.c#L94
  288. (str_length,) = struct.unpack(">Q", stream.read(8))
  289. yield stream.read(str_length - 1)
  290. assert stream.read(1) == b"\x00"
  291. def _read_triangular(self, stream: typing.BinaryIO):
  292. assert stream.read(3) == self._MAGIC_NUMBER
  293. self.creator, creation_dt_str = re.match(
  294. rb"^created by (\w+) on (.* \d{4})\n", stream.readline()
  295. ).groups()
  296. with setlocale("C"):
  297. self.creation_datetime = datetime.datetime.strptime(
  298. creation_dt_str.decode(), self._DATETIME_FORMAT
  299. )
  300. assert stream.read(1) == b"\n"
  301. # fwriteInt
  302. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/fio.c#L290
  303. vertices_num, triangles_num = struct.unpack(">II", stream.read(4 * 2))
  304. self.vertices = [
  305. Vertex(*struct.unpack(">fff", stream.read(4 * 3)))
  306. for _ in range(vertices_num)
  307. ]
  308. self.triangles = [
  309. Triangle(struct.unpack(">III", stream.read(4 * 3)))
  310. for _ in range(triangles_num)
  311. ]
  312. assert all(
  313. vertex_idx < vertices_num
  314. for triangle in self.triangles
  315. for vertex_idx in triangle.vertex_indices
  316. )
  317. assert stream.read(4) == self._TAG_OLD_USEREALRAS
  318. (using_old_real_ras,) = struct.unpack(">I", stream.read(4))
  319. assert using_old_real_ras in [0, 1], using_old_real_ras
  320. self.using_old_real_ras = bool(using_old_real_ras)
  321. assert stream.read(4) == self._TAG_OLD_SURF_GEOM
  322. # writeVolGeom
  323. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/transform.c#L368
  324. self.volume_geometry_info = tuple(stream.readline() for _ in range(8))
  325. self.command_lines = list(self._read_cmdlines(stream))
  326. @classmethod
  327. def read_triangular(cls, surface_file_path: str) -> "Surface":
  328. surface = cls()
  329. with open(surface_file_path, "rb") as surface_file:
  330. # pylint: disable=protected-access
  331. surface._read_triangular(surface_file)
  332. return surface
  333. @classmethod
  334. def _triangular_strftime(cls, creation_datetime: datetime.datetime) -> bytes:
  335. padded_day = "{:>2}".format(creation_datetime.day)
  336. fmt = cls._DATETIME_FORMAT.replace("%d", padded_day)
  337. with setlocale("C"):
  338. return creation_datetime.strftime(fmt).encode()
  339. def write_triangular(
  340. self,
  341. surface_file_path: str,
  342. creation_datetime: typing.Optional[datetime.datetime] = None,
  343. ):
  344. if creation_datetime is None:
  345. creation_datetime = datetime.datetime.now()
  346. with open(surface_file_path, "wb") as surface_file:
  347. surface_file.write(
  348. self._MAGIC_NUMBER
  349. + b"created by "
  350. + self.creator
  351. + b" on "
  352. + self._triangular_strftime(creation_datetime)
  353. + b"\n\n"
  354. + struct.pack(">II", len(self.vertices), len(self.triangles))
  355. )
  356. for vertex in self.vertices:
  357. surface_file.write(struct.pack(">fff", *vertex))
  358. for triangle in self.triangles:
  359. assert all(
  360. vertex_index < len(self.vertices)
  361. for vertex_index in triangle.vertex_indices
  362. )
  363. surface_file.write(struct.pack(">III", *triangle.vertex_indices))
  364. surface_file.write(
  365. self._TAG_OLD_USEREALRAS
  366. + struct.pack(">I", 1 if self.using_old_real_ras else 0)
  367. )
  368. surface_file.write(
  369. self._TAG_OLD_SURF_GEOM + b"".join(self.volume_geometry_info)
  370. )
  371. for command_line in self.command_lines:
  372. surface_file.write(
  373. self._TAG_CMDLINE
  374. + struct.pack(">Q", len(command_line) + 1)
  375. + command_line
  376. + b"\0"
  377. )
  378. def load_annotation_file(self, annotation_file_path: str) -> None:
  379. annotation = Annotation.read(annotation_file_path)
  380. assert len(annotation.vertex_label_index) <= len(self.vertices)
  381. assert max(annotation.vertex_label_index.keys()) < len(self.vertices)
  382. self.annotation = annotation
  383. def add_vertex(self, vertex: Vertex) -> int:
  384. self.vertices.append(vertex)
  385. return len(self.vertices) - 1
  386. def add_rectangle(
  387. self, vertex_indices: typing.Iterable[int]
  388. ) -> typing.Iterable[int]:
  389. vertex_indices = list(vertex_indices)
  390. if len(vertex_indices) == 3:
  391. vertex_indices.append(
  392. self.add_vertex(
  393. self.vertices[vertex_indices[0]]
  394. + self.vertices[vertex_indices[2]]
  395. - self.vertices[vertex_indices[1]]
  396. )
  397. )
  398. assert len(vertex_indices) == 4
  399. self.triangles.append(Triangle(vertex_indices[:3]))
  400. self.triangles.append(Triangle(vertex_indices[2:] + vertex_indices[:1]))
  401. def _triangle_count_by_adjacent_vertex_indices(
  402. self,
  403. ) -> typing.Dict[int, typing.Dict[int, int]]:
  404. counts = {
  405. vertex_index: collections.defaultdict(lambda: 0)
  406. for vertex_index in range(len(self.vertices))
  407. }
  408. for triangle in self.triangles:
  409. for vertex_index_pair in triangle.adjacent_vertex_indices(2):
  410. counts[vertex_index_pair[0]][vertex_index_pair[1]] += 1
  411. counts[vertex_index_pair[1]][vertex_index_pair[0]] += 1
  412. return counts
  413. def find_borders(self) -> typing.Iterator[PolygonalCircuit]:
  414. border_neighbours = {}
  415. for (
  416. vertex_index,
  417. neighbour_counts,
  418. ) in self._triangle_count_by_adjacent_vertex_indices().items():
  419. if not neighbour_counts:
  420. yield PolygonalCircuit((vertex_index,))
  421. else:
  422. neighbours = [
  423. neighbour_index
  424. for neighbour_index, counts in neighbour_counts.items()
  425. if counts != 2
  426. ]
  427. if neighbours:
  428. assert len(neighbours) % 2 == 0, (vertex_index, neighbour_counts)
  429. border_neighbours[vertex_index] = neighbours
  430. while border_neighbours:
  431. vertex_index, neighbour_indices = border_neighbours.popitem()
  432. cycle_indices = [vertex_index]
  433. border_neighbours[vertex_index] = neighbour_indices[1:]
  434. vertex_index = neighbour_indices[0]
  435. while vertex_index != cycle_indices[0]:
  436. neighbour_indices = border_neighbours.pop(vertex_index)
  437. neighbour_indices.remove(cycle_indices[-1])
  438. cycle_indices.append(vertex_index)
  439. if len(neighbour_indices) > 1:
  440. border_neighbours[vertex_index] = neighbour_indices[1:]
  441. vertex_index = neighbour_indices[0]
  442. assert vertex_index in border_neighbours, (
  443. vertex_index,
  444. cycle_indices,
  445. border_neighbours,
  446. )
  447. final_neighbour_indices = border_neighbours.pop(vertex_index)
  448. assert final_neighbour_indices == [cycle_indices[-1]], (
  449. vertex_index,
  450. final_neighbour_indices,
  451. cycle_indices,
  452. )
  453. yield PolygonalCircuit(cycle_indices)
  454. def _get_vertex_label_index(self, vertex_index: int) -> typing.Optional[int]:
  455. return self.annotation.vertex_label_index.get(vertex_index, None)
  456. def _find_label_border_segments(self, label: Label) -> typing.Iterator[LineSegment]:
  457. for triangle in self.triangles:
  458. border_vertex_indices = tuple(
  459. filter(
  460. lambda i: self._get_vertex_label_index(i) == label.index,
  461. triangle.vertex_indices,
  462. )
  463. )
  464. if len(border_vertex_indices) == 2:
  465. yield LineSegment(border_vertex_indices)
  466. def find_label_border_polygonal_chains(
  467. self, label: Label
  468. ) -> typing.Iterator[PolygonalChain]:
  469. segments = set(self._find_label_border_segments(label))
  470. available_chains = collections.deque(
  471. PolygonalChain(segment.vertex_indices) for segment in segments
  472. )
  473. # irrespective of its poor performance,
  474. # we keep this approach since it's easy to read and fast enough
  475. while available_chains:
  476. chain = available_chains.pop()
  477. last_chains_len = None
  478. while last_chains_len != len(available_chains):
  479. last_chains_len = len(available_chains)
  480. checked_chains = collections.deque()
  481. while available_chains:
  482. potential_neighbour = available_chains.pop()
  483. try:
  484. chain.connect(potential_neighbour)
  485. except PolygonalChainsNotOverlapingError:
  486. checked_chains.append(potential_neighbour)
  487. available_chains = checked_chains
  488. assert all((segment in segments) for segment in chain.segments())
  489. yield chain
  490. def _unused_vertices(self) -> typing.Set[int]:
  491. vertex_indices = set(range(len(self.vertices)))
  492. for triangle in self.triangles:
  493. for vertex_index in triangle.vertex_indices:
  494. vertex_indices.discard(vertex_index)
  495. return vertex_indices
  496. def remove_unused_vertices(self) -> None:
  497. vertex_index_conversion = [0] * len(self.vertices)
  498. for vertex_index in sorted(self._unused_vertices(), reverse=True):
  499. del self.vertices[vertex_index]
  500. vertex_index_conversion[vertex_index] -= 1
  501. vertex_index_conversion = numpy.cumsum(vertex_index_conversion)
  502. for triangle_index in range(len(self.triangles)):
  503. self.triangles[triangle_index] = Triangle(
  504. map(
  505. lambda i: i + int(vertex_index_conversion[i]),
  506. self.triangles[triangle_index].vertex_indices,
  507. )
  508. )
  509. def select_vertices(
  510. self, vertex_indices: typing.Iterable[int]
  511. ) -> typing.List[Vertex]:
  512. return [self.vertices[idx] for idx in vertex_indices]
  513. @staticmethod
  514. def unite(surfaces: typing.Iterable["Surface"]) -> "Surface":
  515. surfaces_iter = iter(surfaces)
  516. union = copy.deepcopy(next(surfaces_iter))
  517. for surface in surfaces_iter:
  518. vertex_index_offset = len(union.vertices)
  519. union.vertices.extend(surface.vertices)
  520. union.triangles.extend(
  521. Triangle(
  522. vertex_idx + vertex_index_offset
  523. for vertex_idx in triangle.vertex_indices
  524. )
  525. for triangle in surface.triangles
  526. )
  527. return union