import FreeCAD as App import FreeCADGui as Gui class PartCachedView: def __init__(self, direction, x_direction, obj): self.direction = direction self.x_direction = x_direction self.doc_name = obj.Document.Name self.obj_name = obj.Name self.cached_lines = None def render(self): import numpy as np import os doc = App.getDocument(self.doc_name) #: :type doc: App.Document obj = doc.getObject(self.obj_name) #: :type obj: App.DocumentObject # create temporary view page = doc.addObject('TechDraw::DrawPage', 'TmpPage') if not page.KeepUpdated: page.KeepUpdated = True template = doc.addObject('TechDraw::DrawSVGTemplate', 'Template') import ahb_locator template.Template = os.path.join(os.path.dirname(ahb_locator.__file__), "resources/A4_Landscape_blank.svg") page.Template = template tmpView = doc.addObject('TechDraw::DrawViewPart', 'TmpView') tmpView.Direction = self.direction tmpView.XDirection = self.x_direction tmpView.Perspective = False tmpView.ScaleType = 'Custom' tmpView.Scale = 1.0 tmpView.XSource = [obj] page.addView(tmpView) tmpView.recompute() # copy edges relative to center tmpCenter = self.computePartCenter(tmpView, obj) # count lines tmpEdges = tmpView.getVisibleEdges() numLines = 0 for edge in tmpEdges: if not hasattr(edge.Curve, 'Degree') or edge.Curve.Degree == 1: numLines += 1 # store all lines in a packed array of floats (for each line: X1, Y1, X2, Y2) self.cached_lines = np.empty([numLines, 4]) lineIdx = 0 for edge in tmpEdges: if not hasattr(edge.Curve, 'Degree') or edge.Curve.Degree == 1: sx = 1.0 sy = -1.0 self.cached_lines[lineIdx] = [ edge.Vertexes[0].Point.x*sx - tmpCenter.x, edge.Vertexes[0].Point.y*sy - tmpCenter.y, edge.Vertexes[1].Point.x*sx - tmpCenter.x, edge.Vertexes[1].Point.y*sy - tmpCenter.y ] lineIdx = lineIdx + 1 # delete temporary view doc.removeObject(page.Name) def computePartCenter(self, view, obj): if obj.TypeId == 'App::Link': partLink = obj objectCenterWorld = partLink.LinkPlacement.Matrix.multiply(partLink.LinkedObject.Shape.CenterOfGravity) else: objectCenterWorld = obj.Shape.CenterOfGravity vertId = view.makeCosmeticVertex3d(objectCenterWorld) vert = view.getCosmeticVertex(vertId) objectCenterView = vert.Point view.removeCosmeticVertex(vertId) return objectCenterView class PartsCache: part_views = {} def getPart2DView(self, view, obj): key = (view.Direction.x, view.Direction.y, view.Direction.z, view.XDirection.x, view.XDirection.y, view.XDirection.z, obj.Document.Name, obj.Name) part_view = self.part_views.get(key, None) if part_view is None: part_view = PartCachedView(view.Direction, view.XDirection, obj) part_view.render() self.part_views[key] = part_view return part_view