ParseDXF.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from shapely.geometry import LineString, Point
  8. from shapely.affinity import rotate
  9. # Vector was an older name for Vec3; try both for backward compatibility:
  10. try:
  11. from ezdxf.math import Vec3 as ezdxf_vector
  12. except ImportError:
  13. from ezdxf.math import Vector as ezdxf_vector
  14. from appParsers.ParseFont import *
  15. from appParsers.ParseDXF_Spline import *
  16. import logging
  17. log = logging.getLogger('base2')
  18. def distance(pt1, pt2):
  19. return math.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  20. def dxfpoint2shapely(point):
  21. geo = Point(point.dxf.location).buffer(0.01)
  22. return geo
  23. def dxfline2shapely(line):
  24. try:
  25. start = (line.dxf.start[0], line.dxf.start[1])
  26. stop = (line.dxf.end[0], line.dxf.end[1])
  27. except Exception as e:
  28. log.debug(str(e))
  29. return None
  30. geo = LineString([start, stop])
  31. return geo
  32. def dxfcircle2shapely(circle, n_points=100):
  33. ocs = circle.ocs()
  34. # if the extrusion attribute is not (0, 0, 1) then we have to change the coordinate system from OCS to WCS
  35. if circle.dxf.extrusion != (0, 0, 1):
  36. center_pt = ocs.to_wcs(circle.dxf.center)
  37. else:
  38. center_pt = circle.dxf.center
  39. radius = circle.dxf.radius
  40. geo = Point(center_pt).buffer(radius, int(n_points / 4))
  41. return geo
  42. def dxfarc2shapely(arc, n_points=100):
  43. # ocs = arc.ocs()
  44. # # if the extrusion attribute is not (0, 0, 1) then we have to change the coordinate system from OCS to WCS
  45. # if arc.dxf.extrusion != (0, 0, 1):
  46. # arc_center = ocs.to_wcs(arc.dxf.center)
  47. # start_angle = math.radians(arc.dxf.start_angle) + math.pi
  48. # end_angle = math.radians(arc.dxf.end_angle) + math.pi
  49. # dir = 'CW'
  50. # else:
  51. # arc_center = arc.dxf.center
  52. # start_angle = math.radians(arc.dxf.start_angle)
  53. # end_angle = math.radians(arc.dxf.end_angle)
  54. # dir = 'CCW'
  55. #
  56. # center_x = arc_center[0]
  57. # center_y = arc_center[1]
  58. # radius = arc.dxf.radius
  59. #
  60. # point_list = []
  61. #
  62. # if start_angle > end_angle:
  63. # start_angle += 2 * math.pi
  64. #
  65. # line_seg = int((n_points * (end_angle - start_angle)) / math.pi)
  66. # step_angle = (end_angle - start_angle) / float(line_seg)
  67. #
  68. # angle = start_angle
  69. # for step in range(line_seg + 1):
  70. # if dir == 'CCW':
  71. # x = center_x + radius * math.cos(angle)
  72. # y = center_y + radius * math.sin(angle)
  73. # else:
  74. # x = center_x + radius * math.cos(-angle)
  75. # y = center_y + radius * math.sin(-angle)
  76. # point_list.append((x, y))
  77. # angle += step_angle
  78. #
  79. #
  80. # log.debug("X = %.4f, Y = %.4f, Radius = %.4f, start_angle = %.1f, stop_angle = %.1f, step_angle = %.4f, dir=%s" %
  81. # (center_x, center_y, radius, start_angle, end_angle, step_angle, dir))
  82. #
  83. # geo = LineString(point_list)
  84. # return geo
  85. ocs = arc.ocs()
  86. # if the extrusion attribute is not (0, 0, 1) then we have to change the coordinate system from OCS to WCS
  87. if arc.dxf.extrusion != (0, 0, 1):
  88. arc_center = ocs.to_wcs(arc.dxf.center)
  89. start_angle = arc.dxf.start_angle + 180
  90. end_angle = arc.dxf.end_angle + 180
  91. direction = 'CW'
  92. else:
  93. arc_center = arc.dxf.center
  94. start_angle = arc.dxf.start_angle
  95. end_angle = arc.dxf.end_angle
  96. direction = 'CCW'
  97. center_x = arc_center[0]
  98. center_y = arc_center[1]
  99. radius = arc.dxf.radius
  100. point_list = []
  101. if start_angle > end_angle:
  102. start_angle = start_angle - 360
  103. angle = start_angle
  104. step_angle = float(abs(end_angle - start_angle) / n_points)
  105. while angle <= end_angle:
  106. if direction == 'CCW':
  107. x = center_x + radius * math.cos(math.radians(angle))
  108. y = center_y + radius * math.sin(math.radians(angle))
  109. else:
  110. x = center_x + radius * math.cos(math.radians(-angle))
  111. y = center_y + radius * math.sin(math.radians(-angle))
  112. point_list.append((x, y))
  113. angle += abs(step_angle)
  114. # in case the number of segments do not cover everything until the end of the arc
  115. if angle != end_angle:
  116. if direction == 'CCW':
  117. x = center_x + radius * math.cos(math.radians(end_angle))
  118. y = center_y + radius * math.sin(math.radians(end_angle))
  119. else:
  120. x = center_x + radius * math.cos(math.radians(- end_angle))
  121. y = center_y + radius * math.sin(math.radians(- end_angle))
  122. point_list.append((x, y))
  123. # log.debug("X = %.4f, Y = %.4f, Radius = %.4f, start_angle = %.1f, stop_angle = %.1f, step_angle = %.4f" %
  124. # (center_x, center_y, radius, start_angle, end_angle, step_angle))
  125. geo = LineString(point_list)
  126. return geo
  127. def dxfellipse2shapely(ellipse, ellipse_segments=100):
  128. # center = ellipse.dxf.center
  129. # start_angle = ellipse.dxf.start_param
  130. # end_angle = ellipse.dxf.end_param
  131. ocs = ellipse.ocs()
  132. # if the extrusion attribute is not (0, 0, 1) then we have to change the coordinate system from OCS to WCS
  133. if ellipse.dxf.extrusion != (0, 0, 1):
  134. center = ocs.to_wcs(ellipse.dxf.center)
  135. start_angle = ocs.to_wcs(ellipse.dxf.start_param)
  136. end_angle = ocs.to_wcs(ellipse.dxf.end_param)
  137. direction = 'CW'
  138. else:
  139. center = ellipse.dxf.center
  140. start_angle = ellipse.dxf.start_param
  141. end_angle = ellipse.dxf.end_param
  142. direction = 'CCW'
  143. # print("Dir = %s" % dir)
  144. major_axis = ellipse.dxf.major_axis
  145. ratio = ellipse.dxf.ratio
  146. points_list = []
  147. major_axis = Vector(list(major_axis))
  148. major_x = major_axis[0]
  149. major_y = major_axis[1]
  150. if start_angle >= end_angle:
  151. end_angle += 2.0 * math.pi
  152. line_seg = int((ellipse_segments * (end_angle - start_angle)) / math.pi)
  153. step_angle = abs(end_angle - start_angle) / float(line_seg)
  154. angle = start_angle
  155. for step in range(line_seg + 1):
  156. if direction == 'CW':
  157. major_dim = normalize_2(major_axis)
  158. minor_dim = normalize_2(Vector([ratio * k for k in major_axis]))
  159. vx = (major_dim[0] + major_dim[1]) * math.cos(angle)
  160. vy = (minor_dim[0] - minor_dim[1]) * math.sin(angle)
  161. x = center[0] + major_x * vx - major_y * vy
  162. y = center[1] + major_y * vx + major_x * vy
  163. angle += step_angle
  164. else:
  165. major_dim = normalize_2(major_axis)
  166. minor_dim = (Vector([ratio * k for k in major_dim]))
  167. vx = (major_dim[0] + major_dim[1]) * math.cos(angle)
  168. vy = (minor_dim[0] + minor_dim[1]) * math.sin(angle)
  169. x = center[0] + major_x * vx + major_y * vy
  170. y = center[1] + major_y * vx + major_x * vy
  171. angle += step_angle
  172. points_list.append((x, y))
  173. geo = LineString(points_list)
  174. return geo
  175. def dxfpolyline2shapely(polyline):
  176. final_pts = []
  177. pts = polyline.points()
  178. for i in pts:
  179. final_pts.append((i[0], i[1]))
  180. if polyline.is_closed:
  181. final_pts.append(final_pts[0])
  182. geo = LineString(final_pts)
  183. return geo
  184. def dxflwpolyline2shapely(lwpolyline):
  185. final_pts = []
  186. for point in lwpolyline:
  187. x, y, _, _, _ = point
  188. final_pts.append((x, y))
  189. if lwpolyline.closed:
  190. final_pts.append(final_pts[0])
  191. geo = LineString(final_pts)
  192. return geo
  193. def dxfsolid2shapely(solid):
  194. iterator = 0
  195. corner_list = []
  196. try:
  197. corner_list.append(solid[iterator])
  198. iterator += 1
  199. except Exception:
  200. return Polygon(corner_list)
  201. def dxfspline2shapely(spline):
  202. # for old version of ezdxf
  203. # with spline.edit_data() as spline_data:
  204. # ctrl_points = spline_data.control_points
  205. # try:
  206. # # required if using old version of ezdxf
  207. # knot_values = spline_data.knot_values
  208. # except AttributeError:
  209. # knot_values = spline_data.knots
  210. ctrl_points = spline.control_points
  211. knot_values = spline.knots
  212. is_closed = spline.closed
  213. degree = spline.dxf.degree
  214. x_list, y_list, _ = spline2Polyline(ctrl_points, degree=degree, closed=is_closed, segments=20, knots=knot_values)
  215. points_list = zip(x_list, y_list)
  216. geo = LineString(points_list)
  217. return geo
  218. def dxftrace2shapely(trace):
  219. iterator = 0
  220. corner_list = []
  221. try:
  222. corner_list.append(trace[iterator])
  223. iterator += 1
  224. except Exception:
  225. return Polygon(corner_list)
  226. def getdxfgeo(dxf_object):
  227. msp = dxf_object.modelspace()
  228. geos = get_geo(dxf_object, msp)
  229. # geo_block = get_geo_from_block(dxf_object)
  230. return geos
  231. def get_geo_from_insert(dxf_object, insert):
  232. geo_block_transformed = []
  233. phi = insert.dxf.rotation
  234. tr = insert.dxf.insert
  235. sx = insert.dxf.xscale
  236. sy = insert.dxf.yscale
  237. r_count = insert.dxf.row_count
  238. r_spacing = insert.dxf.row_spacing
  239. c_count = insert.dxf.column_count
  240. c_spacing = insert.dxf.column_spacing
  241. # print(phi, tr)
  242. # identify the block given the 'INSERT' type entity name
  243. block = dxf_object.blocks[insert.dxf.name]
  244. block_coords = (block.block.dxf.base_point[0], block.block.dxf.base_point[1])
  245. # get a list of geometries found in the block
  246. geo_block = get_geo(dxf_object, block)
  247. # iterate over the geometries found and apply any transformation found in the 'INSERT' entity attributes
  248. for geo in geo_block:
  249. # get the bounds of the geometry
  250. # minx, miny, maxx, maxy = geo.bounds
  251. if tr[0] != 0 or tr[1] != 0:
  252. geo = translate(geo, (tr[0] - block_coords[0]), (tr[1] - block_coords[1]))
  253. # support for array block insertions
  254. if r_count > 1:
  255. for r in range(r_count):
  256. geo_block_transformed.append(translate(geo, (tr[0] + (r * r_spacing) - block_coords[0]), 0))
  257. if c_count > 1:
  258. for c in range(c_count):
  259. geo_block_transformed.append(translate(geo, 0, (tr[1] + (c * c_spacing) - block_coords[1])))
  260. if sx != 1 or sy != 1:
  261. geo = scale(geo, sx, sy)
  262. if phi != 0:
  263. if isinstance(tr, str) and tr.lower() == 'c':
  264. tr = 'center'
  265. elif isinstance(tr, ezdxf_vector):
  266. tr = list(tr)
  267. geo = rotate(geo, phi, origin=tr)
  268. geo_block_transformed.append(geo)
  269. return geo_block_transformed
  270. def get_geo(dxf_object, container):
  271. # store shapely geometry here
  272. geo = []
  273. for dxf_entity in container:
  274. g = []
  275. # print("Entity", dxf_entity.dxftype())
  276. if dxf_entity.dxftype() == 'POINT':
  277. g = dxfpoint2shapely(dxf_entity,)
  278. elif dxf_entity.dxftype() == 'LINE':
  279. g = dxfline2shapely(dxf_entity,)
  280. elif dxf_entity.dxftype() == 'CIRCLE':
  281. g = dxfcircle2shapely(dxf_entity)
  282. elif dxf_entity.dxftype() == 'ARC':
  283. g = dxfarc2shapely(dxf_entity)
  284. elif dxf_entity.dxftype() == 'ELLIPSE':
  285. g = dxfellipse2shapely(dxf_entity)
  286. elif dxf_entity.dxftype() == 'LWPOLYLINE':
  287. g = dxflwpolyline2shapely(dxf_entity)
  288. elif dxf_entity.dxftype() == 'POLYLINE':
  289. g = dxfpolyline2shapely(dxf_entity)
  290. elif dxf_entity.dxftype() == 'SOLID':
  291. g = dxfsolid2shapely(dxf_entity)
  292. elif dxf_entity.dxftype() == 'TRACE':
  293. g = dxftrace2shapely(dxf_entity)
  294. elif dxf_entity.dxftype() == 'SPLINE':
  295. g = dxfspline2shapely(dxf_entity)
  296. elif dxf_entity.dxftype() == 'INSERT':
  297. g = get_geo_from_insert(dxf_object, dxf_entity)
  298. else:
  299. log.debug(" %s is not supported yet." % dxf_entity.dxftype())
  300. if g is not None:
  301. if type(g) == list:
  302. for subg in g:
  303. geo.append(subg)
  304. else:
  305. geo.append(g)
  306. return geo
  307. def getdxftext(exf_object, object_type, units=None):
  308. pass
  309. # def get_geo_from_block(dxf_object):
  310. # geo_block_transformed = []
  311. #
  312. # msp = dxf_object.modelspace()
  313. # # iterate through all 'INSERT' entities found in modelspace msp
  314. # for insert in msp.query('INSERT'):
  315. # phi = insert.dxf.rotation
  316. # tr = insert.dxf.insert
  317. # sx = insert.dxf.xscale
  318. # sy = insert.dxf.yscale
  319. # r_count = insert.dxf.row_count
  320. # r_spacing = insert.dxf.row_spacing
  321. # c_count = insert.dxf.column_count
  322. # c_spacing = insert.dxf.column_spacing
  323. #
  324. # # print(phi, tr)
  325. #
  326. # # identify the block given the 'INSERT' type entity name
  327. # print(insert.dxf.name)
  328. # block = dxf_object.blocks[insert.dxf.name]
  329. # block_coords = (block.block.dxf.base_point[0], block.block.dxf.base_point[1])
  330. #
  331. # # get a list of geometries found in the block
  332. # # store shapely geometry here
  333. # geo_block = []
  334. #
  335. # for dxf_entity in block:
  336. # g = []
  337. # # print("Entity", dxf_entity.dxftype())
  338. # if dxf_entity.dxftype() == 'POINT':
  339. # g = dxfpoint2shapely(dxf_entity, )
  340. # elif dxf_entity.dxftype() == 'LINE':
  341. # g = dxfline2shapely(dxf_entity, )
  342. # elif dxf_entity.dxftype() == 'CIRCLE':
  343. # g = dxfcircle2shapely(dxf_entity)
  344. # elif dxf_entity.dxftype() == 'ARC':
  345. # g = dxfarc2shapely(dxf_entity)
  346. # elif dxf_entity.dxftype() == 'ELLIPSE':
  347. # g = dxfellipse2shapely(dxf_entity)
  348. # elif dxf_entity.dxftype() == 'LWPOLYLINE':
  349. # g = dxflwpolyline2shapely(dxf_entity)
  350. # elif dxf_entity.dxftype() == 'POLYLINE':
  351. # g = dxfpolyline2shapely(dxf_entity)
  352. # elif dxf_entity.dxftype() == 'SOLID':
  353. # g = dxfsolid2shapely(dxf_entity)
  354. # elif dxf_entity.dxftype() == 'TRACE':
  355. # g = dxftrace2shapely(dxf_entity)
  356. # elif dxf_entity.dxftype() == 'SPLINE':
  357. # g = dxfspline2shapely(dxf_entity)
  358. # elif dxf_entity.dxftype() == 'INSERT':
  359. # log.debug("Not supported yet.")
  360. # else:
  361. # log.debug("Not supported yet.")
  362. #
  363. # if g is not None:
  364. # if type(g) == list:
  365. # for subg in g:
  366. # geo_block.append(subg)
  367. # else:
  368. # geo_block.append(g)
  369. #
  370. # # iterate over the geometries found and apply any transformation found in the 'INSERT' entity attributes
  371. # for geo in geo_block:
  372. # if tr[0] != 0 or tr[1] != 0:
  373. # geo = translate(geo, (tr[0] - block_coords[0]), (tr[1] - block_coords[1]))
  374. #
  375. # # support for array block insertions
  376. # if r_count > 1:
  377. # for r in range(r_count):
  378. # geo_block_transformed.append(translate(geo, (tr[0] + (r * r_spacing) - block_coords[0]), 0))
  379. #
  380. # if c_count > 1:
  381. # for c in range(c_count):
  382. # geo_block_transformed.append(translate(geo, 0, (tr[1] + (c * c_spacing) - block_coords[1])))
  383. #
  384. # if sx != 1 or sy != 1:
  385. # geo = scale(geo, sx, sy)
  386. # if phi != 0:
  387. # geo = rotate(geo, phi, origin=tr)
  388. #
  389. # geo_block_transformed.append(geo)
  390. # return geo_block_transformed