Python Part.BSplineCurve() Examples

The following are 30 code examples of Part.BSplineCurve(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Part , or try the search function .
Example #1
Source File: BSplineAlgorithms.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def debug(o):
    if not DEBUG:
        return()
    if isinstance(o,Part.BSplineCurve):
        FreeCAD.Console.PrintWarning("\nBSplineCurve\n")
        FreeCAD.Console.PrintWarning("Degree: %d\n"%(o.Degree))
        FreeCAD.Console.PrintWarning("NbPoles: %d\n"%(o.NbPoles))
        FreeCAD.Console.PrintWarning("Knots: %d (%0.2f - %0.2f)\n"%(o.NbKnots, o.FirstParameter, o.LastParameter))
        FreeCAD.Console.PrintWarning("Mults: %s\n"%(o.getMultiplicities()))
        FreeCAD.Console.PrintWarning("Periodic: %s\n"%(o.isPeriodic()))
    elif isinstance(o,Part.BSplineSurface):
        FreeCAD.Console.PrintWarning("\nBSplineSurface\n************\n")
        try:
            u = o.uIso(o.UKnotSequence[0])
            debug(u)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute uIso curve\n")
        try:
            v = o.vIso(o.VKnotSequence[0])
            debug(v)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute vIso curve\n")
        FreeCAD.Console.PrintWarning("************\n")
    else:
        FreeCAD.Console.PrintMessage("%s\n"%o) 
Example #2
Source File: gordonFP.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def debug(o):
    if isinstance(o,Part.BSplineCurve):
        FreeCAD.Console.PrintWarning("\nBSplineCurve\n")
        FreeCAD.Console.PrintWarning("Degree: %d\n"%(o.Degree))
        FreeCAD.Console.PrintWarning("NbPoles: %d\n"%(o.NbPoles))
        FreeCAD.Console.PrintWarning("Knots: %d (%0.2f - %0.2f)\n"%(o.NbKnots, o.FirstParameter, o.LastParameter))
        FreeCAD.Console.PrintWarning("Mults: %s\n"%(o.getMultiplicities()))
        FreeCAD.Console.PrintWarning("Periodic: %s\n"%(o.isPeriodic()))
    elif isinstance(o,Part.BSplineSurface):
        FreeCAD.Console.PrintWarning("\nBSplineSurface\n************\n")
        try:
            u = o.uIso(o.UKnotSequence[0])
            debug(u)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute uIso curve\n")
        try:
            v = o.vIso(o.VKnotSequence[0])
            debug(v)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute vIso curve\n")
        FreeCAD.Console.PrintWarning("************\n")
    else:
        FreeCAD.Console.PrintMessage("%s\n"%o) 
Example #3
Source File: nurbs_tools.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def compute(self):
        nbPoles = self.cont1 + self.cont2 + 2
        e = self.getChord()
        if not e:
            self.Curve = None
            return
        try:
            poles = e.discretize(nbPoles)
        except Part.OCCError:
            self.Curve = None
            return
        degree = nbPoles - 1
        if degree > self.maxDegree:
            degree = self.maxDegree
        knots, mults = createKnotsMults(degree, nbPoles)
        weights = [1.0 for k in range(nbPoles)]
        be = Part.BSplineCurve()
        be.buildFromPolesMultsKnots(poles, mults , knots, False, degree, weights, False)
        nc = curvematch(self.edge1, be, self.param1, self.cont1, self.scale1)
        rev = bspline_copy(nc, True, False)
        self.Curve = curvematch(self.edge2, rev, self.param2, self.cont2, self.scale2) 
Example #4
Source File: nurbs_tools.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def bspline_copy(bs, reverse = False, scale = 1.0):
    """Copy a BSplineCurve, with knotvector optionally reversed and scaled
    newbspline = bspline_copy(bspline, reverse = False, scale = 1.0)
    Part.BSplineCurve.buildFromPolesMultsKnots( poles, mults , knots, periodic, degree, weights, CheckRational )"""
    mults = bs.getMultiplicities()
    weights = bs.getWeights()
    poles = bs.getPoles()
    knots = bs.getKnots()
    perio = bs.isPeriodic()
    ratio = bs.isRational()
    if scale:
        knots = knotSeqScale(knots, scale)
    if reverse:
        mults.reverse()
        weights.reverse()
        poles.reverse()
        knots = knotSeqReverse(knots)
    bspline = Part.BSplineCurve()
    bspline.buildFromPolesMultsKnots(poles, mults , knots, perio, bs.Degree, weights, ratio)
    return bspline 
Example #5
Source File: pipeshellFP.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def getRails(self, shapes):
        nbvert = len(shapes[0].Vertexes)
        edges = []
        for i in range(nbvert):
            pts = []
            for s in shapes:
                pts.append(s.Vertexes[i].Point)
            try:
                bs = Part.BSplineCurve()
                bs.interpolate(pts)
                edges.append(bs.toShape())
                debug("Rail %d : BSpline curve"%i)
            except Part.OCCError:
                po = Part.makePolygon(pts)
                edges.append(po)
                debug("Rail %d : Polygon"%i)
        return(edges) 
Example #6
Source File: approximate.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def buildCurve(self, obj):
        pts = self.Points[obj.FirstIndex:obj.LastIndex+1]
        bs = Part.BSplineCurve()
        if (obj.Method == "Parametrization") and (obj.Parametrization == "Curvilinear") and (hasattr(obj.PointObject,"Distance")):
            params = []
            try:
                dis = obj.PointObject.Distance
            except:
                dis = 1.0
            for i in range(len(pts)):
                params.append(1.0 * i * dis)
            lv = pts[-1].sub(pts[-2])
            params[-1] = params[-2] + lv.Length
            bs.interpolate(Points = pts, Parameters = params, Tolerance = obj.ApproxTolerance)

        elif obj.Method == "Parametrization":
            bs.approximate(Points = pts, DegMin = obj.DegreeMin, DegMax = obj.DegreeMax, Tolerance = obj.ApproxTolerance, Continuity = obj.Continuity, ParamType = obj.Parametrization)
        elif obj.Method == "Smoothing Algorithm":
            bs.approximate(Points = pts, DegMin = obj.DegreeMin, DegMax = obj.DegreeMax, Tolerance = obj.ApproxTolerance, Continuity = obj.Continuity, LengthWeight = obj.LengthWeight, CurvatureWeight = obj.CurvatureWeight , TorsionWeight = obj.TorsionWeight)
        if obj.ClampEnds:
            bs.setPole(1,self.Points[0])
            bs.setPole(int(bs.NbPoles),self.Points[-1])
        self.curve = bs 
Example #7
Source File: isocurves.py    From CurvesWB with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, edge = None):
        if edge == None:
            v1 = FreeCAD.Vector(0,0,0)
            v2 = FreeCAD.Vector(1,0,0)
            b = Part.BezierCurve()
            b.setPoles([v1,v2])
            self.curve = b
        elif isinstance(edge, Part.Edge):
            c = edge.Curve
            if isinstance(c, (Part.BezierCurve, Part.BSplineCurve)):
                self.curve = c
            else:
                bs = c.toBSpline()
                self.curve = bs
        elif isinstance(edge, (Part.BezierCurve, Part.BSplineCurve)):
            self.curve = edge 
Example #8
Source File: curveOnSurface.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def curve2d_extend(curve, start=0.5, end=0.5):
    """Extends a Geom2d curve at each extremity, by a linear tangent
    "start" and "end" parameters are factors of curve length.
    Returns a BSplineCurve."""
    bs = curve.toBSpline(curve.FirstParameter, curve.LastParameter)
    t1 = mul2d(bs.tangent(bs.FirstParameter), -1.0)
    t2 = bs.tangent(bs.LastParameter)
    poles = bs.getPoles()
    mults = bs.getMultiplicities()
    knots = bs.getKnots()
    
    pre = list()
    post = list()
    for i in range(bs.Degree):
        l = bs.length() * (bs.Degree - i) / bs.Degree
        pre.append(add2d(bs.value(bs.FirstParameter), mul2d(t1,start*l)))
        post.append(add2d(bs.value(bs.LastParameter), mul2d(t2,end*l)))
    newpoles = pre + poles + post

    mults.insert(1, bs.Degree)
    mults.insert(len(mults)-2, bs.Degree)
    prange = bs.LastParameter - bs.FirstParameter
    knots.insert(0, bs.FirstParameter - prange * start)
    knots.append(bs.LastParameter + prange * end)
    try:
        bs.buildFromPolesMultsKnots(newpoles, mults, knots, bs.isPeriodic(), bs.Degree)
    except Part.OCCError:
        print(bs.Degree)
        print(len(newpoles))
        print(sum(mults))
        print(len(knots))
    return bs
    
    #ext1 = Part.Geom2d.BSplineCurve2d()
    #pts = [bs.value(bs.FirstParameter),
           #add2d(bs.value(bs.FirstParameter), mul2d(t1,start*bs.length()))]
    #ext1 
Example #9
Source File: BSplineAlgorithms.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def scale(self, c):
        res = 0
        if isinstance(c, (tuple,list)):
            for cu in c:
                res = max(res,self.scale(cu))
        elif isinstance(c, (Part.BSplineCurve, Part.BezierCurve)):
            pts = c.getPoles()
            for p in pts[1:]:
                res = max(res, p.distanceToPoint(pts[0]))
        return(res) 
Example #10
Source File: BSplineAlgorithms.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def pointsToSurface(self, points, uParams, vParams, uContinuousIfClosed, vContinuousIfClosed):
        #debug("-   pointsToSurface")
        tolerance = self.REL_TOL_CLOSED * self.scale_pt_array(points)
        makeVDirClosed = vContinuousIfClosed and self.isVDirClosed(points, tolerance)
        makeUDirClosed = uContinuousIfClosed and self.isUDirClosed(points, tolerance)

        # GeomAPI_Interpolate does not want to have the last point,
        # if the curve should be closed. It internally uses the first point
        # as the last point
        if makeUDirClosed:
            nPointsUpper = len(points)-1
        else:
            nPointsUpper = len(points) # points.UpperRow()

        # first interpolate all points by B-splines in u-direction
        uSplines = list()
        for cpVIdx in range(len(points[0])): #for (int cpVIdx = points.LowerCol(); cpVIdx <= points.UpperCol(); ++cpVIdx) {
            points_u = [0]*nPointsUpper
            for iPointU in range(nPointsUpper):#for (int iPointU = points_u->Lower(); iPointU <= points_u->Upper(); ++iPointU) {
                points_u[iPointU] = points[iPointU][cpVIdx]
            curve = Part.BSplineCurve()
            curve.interpolate(Points=points_u, Parameters=uParams, PeriodicFlag=makeUDirClosed, Tolerance=tolerance)

            if makeUDirClosed:
                self.clampBSpline(curve)
            uSplines.append(curve)

        # now create a skinned surface with these B-splines which represents the interpolating surface
        interpolatingSurf = self.curvesToSurface(uSplines, vParams, makeVDirClosed )
        return(interpolatingSurf) 
Example #11
Source File: reparametrize.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def normalized_bspline(e1, reverse=False):
    bs = None
    if isinstance(e1, Part.Wire):
        bs = e1.approximate(1e-15,1e-7,25,999)
    elif isinstance(e1, Part.Edge):
        bs = e1.Curve.toBSpline(e1.FirstParameter, e1.LastParameter)
    elif isinstance(e1, Part.BSplineCurve):
        bs = e1.copy()
    else:
        _utils.error("{} not supported".format(type(e1)))
    if reverse:
        bs.reverse()
    knots = nurbs_tools.knotSeqNormalize(bs.getKnots())
    bs.setKnots(knots)
    return bs 
Example #12
Source File: BSplineApproxInterp.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def debug(o):
    if not DEBUG:
        return()
    if isinstance(o,Part.BSplineCurve):
        FreeCAD.Console.PrintWarning("\nBSplineCurve\n")
        FreeCAD.Console.PrintWarning("Degree: %d\n"%(o.Degree))
        FreeCAD.Console.PrintWarning("NbPoles: %d\n"%(o.NbPoles))
        FreeCAD.Console.PrintWarning("Knots: %d (%0.2f - %0.2f)\n"%(o.NbKnots, o.FirstParameter, o.LastParameter))
        FreeCAD.Console.PrintWarning("Mults: %s\n"%(o.getMultiplicities()))
        FreeCAD.Console.PrintWarning("Periodic: %s\n"%(o.isPeriodic()))
    elif isinstance(o,Part.BSplineSurface):
        FreeCAD.Console.PrintWarning("\nBSplineSurface\n************\n")
        try:
            u = o.uIso(o.UKnotSequence[0])
            debug(u)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute uIso curve\n")
        try:
            v = o.vIso(o.VKnotSequence[0])
            debug(v)
        except Part.OCCError:
            FreeCAD.Console.PrintError("Failed to compute vIso curve\n")
        FreeCAD.Console.PrintWarning("************\n")
    else:
        FreeCAD.Console.PrintMessage("%s\n"%o)

# TODO is this the good SquareDistance function ??? 
Example #13
Source File: nurbs_tools.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def reparametrize(c, p1, p2):
    '''Reparametrize a BSplineCurve so that parameter p1 is moved to p2'''
    if not isinstance(p1,(list, tuple)):
        c1,c2 = move_param(c, p1, p2)
        c = join_curve(c1,c2)
        return c
    else:
        curves = move_params(c, p1, p2)
        c = join_curves(curves)
        return c 
Example #14
Source File: curveOnSurface.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def binormalFace(self, samp, dist, tol=1e-5, sym=False):
        face = None
        if sym:
            dist /=2.0
        ran = self.lastParameter - self.firstParameter
        pts = list()
        pars = list()
        for i in range(samp):
            t = self.firstParameter + float(i) * ran / (samp-1)
            pts.append(self.valueAt(t).add(self.binormalAt(t)*float(dist)))
            pars.append(t)
        #if self._closed:
            #pts = pts[:-1]
        bs = Part.BSplineCurve()
        bs.approximate(Points = pts, Parameters = pars, DegMin = 3, DegMax = 7, Tolerance = tol)
        if sym:
            pts = list()
            pars = list()
            for i in range(samp):
                t = self.firstParameter + float(i) * ran / (samp-1)
                pts.append(self.valueAt(t).sub(self.binormalAt(t)*float(dist)))
                pars.append(t)
            #if self._closed:
                #pts = pts[:-1]
            bs2 = Part.BSplineCurve()
            bs2.approximate(Points = pts, Parameters = pars, DegMin = 3, DegMax = 7, Tolerance = tol)
            face = Part.makeRuledSurface(bs2.toShape(), bs.toShape())
        else:
            face = Part.makeRuledSurface(self.edgeOnFace, bs.toShape())
        if self._closed:
            surf = face.Surface.copy()
            surf.setUPeriodic()
            face = surf.toShape()
        #nf = face.transformGeometry(self.face.Placement.toMatrix())
        return(face.transformGeometry(self.face.Placement.toMatrix())) 
Example #15
Source File: interpolate.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def execute(self, obj):
        debug("* Interpolate : execute *")
        pts = self.getPoints(obj)
        self.setParameters(obj)
        if obj.Polygonal:
            if obj.Periodic:
                pts.append(pts[0])
            poly = Part.makePolygon(pts)
            if obj.WireOutput:
                obj.Shape = poly
                return
            else:
                bs = poly.approximate(1e-8,obj.Tolerance,999,1)
        else:
            bs = Part.BSplineCurve()
            bs.interpolate(Points=pts, PeriodicFlag=obj.Periodic, Tolerance=obj.Tolerance, Parameters=obj.Parameters)
            if not (len(obj.Tangents) == len(pts) and len(obj.TangentFlags) == len(pts)): # or obj.DetectAligned:
                if obj.Periodic:
                    obj.Tangents = [bs.tangent(p)[0] for p in obj.Parameters[0:-1]]
                else:
                    obj.Tangents = [bs.tangent(p)[0] for p in obj.Parameters]
                obj.TangentFlags = [True]*len(pts)
            if obj.CustomTangents: # or obj.DetectAligned:
                #if obj.DetectAligned:
                    #self.detect_aligned_pts(obj, pts)
                bs.interpolate(Points=pts, PeriodicFlag=obj.Periodic, Tolerance=obj.Tolerance, Parameters=obj.Parameters, Tangents=obj.Tangents, TangentFlags=obj.TangentFlags) #, Scale=False)
        obj.Shape = bs.toShape() 
Example #16
Source File: features.py    From freecad.gears with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, fp):
        fp.gear.m = fp.module.Value
        fp.gear.z = fp.teeth
        fp.gear.z1 = fp.inner_diameter.Value
        fp.gear.z2 = fp.outer_diameter.Value
        fp.gear.clearance = fp.clearance
        fp.gear.backlash = fp.backlash.Value
        fp.gear._update()
        pts = fp.gear.points(num=fp.numpoints)
        rotated_pts = pts
        rot = rotation(-fp.gear.phipart)
        for i in range(fp.gear.z - 1):
            rotated_pts = list(map(rot, rotated_pts))
            pts.append(np.array([pts[-1][-1], rotated_pts[0][0]]))
            pts += rotated_pts
        pts.append(np.array([pts[-1][-1], pts[0][0]]))
        wi = []
        for i in pts:
            out = BSplineCurve()
            out.interpolate(list(map(fcvec, i)))
            wi.append(out.toShape())
        wi = Wire(wi)
        if fp.beta.Value == 0:
            sh = Face(wi)
            fp.Shape = sh.extrude(App.Vector(0, 0, fp.height.Value))
        else:
            fp.Shape = helicalextrusion(
                wi, fp.height.Value, fp.height.Value * np.tan(fp.beta.Value * np.pi / 180) * 2 / fp.gear.d, fp.double_helix) 
Example #17
Source File: features.py    From freecad.gears with GNU General Public License v3.0 5 votes vote down vote up
def makeBSplineWire(pts):
    wi = []
    for i in pts:
        out = BSplineCurve()
        out.interpolate(list(map(fcvec, i)))
        wi.append(out.toShape())
    return Wire(wi) 
Example #18
Source File: dev_BSpline.py    From NodeEditor with MIT License 5 votes vote down vote up
def run_FreeCAD_ApproximateBSpline(self):
    shin=self.getPinObject("Shape_in")
    if shin is None:
        sayErOb(self,"no Shape_in")    
        return

    say(shin)
    points=self.getData("points")

    if shin is None: 
        sf=None
    
        pp=[points[0]]
        for i in range(1,len(points)):
            if ((points[i]-points[i-1]).Length)>0.01:
                pp += [points[i]]
    
        bs = Part.BSplineCurve()
        tol=max(self.getData("tolerance"),1.)
        bs.approximate(pp,Tolerance=tol*0.001)
        self.setPinObject("Shape_out",bs.toShape())
    else:
        shin=shin.toNurbs().Face1
        sf=shin.Surface

        uvs=[]
        pts2da=[sf.parameter(p) for p in points]
    
        pts2d=[]
        for i,p in enumerate(pts2da):
            pts2d += [FreeCAD.Base.Vector2d(p[0],p[1])]

        bs2d = Part.Geom2d.BSplineCurve2d()
        tol=max(self.getData("tolerance"),1.)
        bs2d.approximate(pts2d,Tolerance=tol*0.001)

        self.setPinObject("Shape_out",bs2d.toShape(sf)) 
Example #19
Source File: dev_BSpline.py    From NodeEditor with MIT License 5 votes vote down vote up
def run_FreeCAD_InterpolateBSpline(self):
    points=self.getData("points")
    say("interpolate for {} points".format(len(points)))
    if len(points)<2:return

    shin=self.getPinObject("Shape_in")
    if shin is None:
        bs2d = Part.BSplineCurve()
        tol=max(self.getData("tolerance"),1.)
        #+# todo: problem with tolerance parameter - how to use it ?

        bs2d.interpolate(points,PeriodicFlag=False)
        self.setPinObject("Shape_out",bs2d.toShape())
    
        return

    
    
    
    shin=shin.toNurbs().Face1
    sf=shin.Surface
    
    uvs=[]
    pts2da=[sf.parameter(p) for p in points]
    pts2d=[]
    for i,p in enumerate(pts2da):
        pts2d += [FreeCAD.Base.Vector2d(p[0],p[1])]

    bs2d = Part.Geom2d.BSplineCurve2d()

    tol=max(self.getData("tolerance"),1.)
    #+# todo: problem with tolerance parameter - how to use it ?

    bs2d.interpolate(pts2d,PeriodicFlag=False)
    self.setPinObject("Shape_out",bs2d.toShape(sf)) 
Example #20
Source File: kicad.py    From fcad_pcb with MIT License 5 votes vote down vote up
def makeCurve(poles):
    return Part.BSplineCurve(poles).toShape() 
Example #21
Source File: shapes.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeSpline(cls, listOfVector):
        """
        Interpolate a spline through the provided points.
        :param cls:
        :param listOfVector: a list of Vectors that represent the points
        :return: an Edge
        """
        vecs = [v.wrapped for v in listOfVector]

        spline = FreeCADPart.BSplineCurve()
        spline.interpolate(vecs, False)
        return Edge(spline.toShape()) 
Example #22
Source File: SheetMetalUnfolder.py    From FreeCAD_SheetMetal with GNU General Public License v3.0 5 votes vote down vote up
def SMmakeSketchfromEdges (edges, name):
    precision = 0.1 # precision in Bspline to BiArcs
    quasidef = 0.01 #quasi deflection for Ellipses and Parabola
    usk = FreeCAD.activeDocument().addObject('Sketcher::SketchObject',name)
    geo=[]
    for e in edges:
        if isinstance(e.Curve,Part.BSplineCurve):
            arcs = e.Curve.toBiArcs(precision)
            for i in arcs:
                eb = Part.Edge(i)
                seg = SMGetGeoSegment(eb)
                if seg is not None:
                    geo.append(seg)
        elif isinstance(e.Curve,Part.Ellipse) or isinstance(e.Curve,Part.Parabola):
            l=e.copy().discretize(QuasiDeflection=quasidef)
            plines=Part.makePolygon(l)
            for edg in plines.Edges:
                seg = SMGetGeoSegment(edg)
                if seg is not None:
                    geo.append(seg)
        else:
            seg = SMGetGeoSegment(e)
            if seg is not None:
                geo.append(seg)
    usk.addGeometry(geo)
    return usk



#############################################################################
# Gui Part. Widget generated from UnfoldOptions.ui using pyuic
############################################################################# 
Example #23
Source File: nurbs_tools.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, e1 = None, e2 = None):
        self.param1 = 0.0
        self.param2 = 0.0
        self.cont1 = 1
        self.cont2 = 1
        self.scale1 = 1.0
        self.scale2 = 1.0
        self.Curve = None
        self.autoScale = True
        self.maxDegree = 25 # int(Part.BSplineCurve().MaxDegree)
        self.setEdges(e1,e2) 
Example #24
Source File: profile_editor.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, points=[], fp = None):
        self.points = list()
        self.curve = Part.BSplineCurve()
        self.fp = fp
        self.root_inserted = False
        self.periodic = False
        self.param_factor = 1.0
        #self.support = None # Not yet implemented
        for p in points:
            if isinstance(p,FreeCAD.Vector):
                self.points.append(MarkerOnShape([p]))
            elif isinstance(p,(tuple,list)):
                self.points.append(MarkerOnShape([p[0]],p[1]))
            elif isinstance(p,(MarkerOnShape, ConnectionMarker)):
                self.points.append(p)
            else:
                FreeCAD.Console.PrintError("InterpoCurveEditor : bad input")
        
        # Setup coin objects
        if self.fp:
            self.guidoc = self.fp.ViewObject.Document
        else:
            if not FreeCADGui.ActiveDocument:
                appdoc = FreeCAD.newDocument("New")
        self.guidoc = FreeCADGui.ActiveDocument
        self.view = self.guidoc.ActiveView
        self.rm = self.view.getViewer().getSoRenderManager()
        self.sg = self.view.getSceneGraph()
        self.setup_InteractionSeparator()
        self.update_curve() 
Example #25
Source File: curve_to_script.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def curve_to_script(i,c):
    com = ["import FreeCAD",
           "from FreeCAD import Vector",
           "import Part",""]
    if isinstance(c,Part.BSplineCurve):
        com.append("poles%d = %r"%(i,c.getPoles()))
        com.append("weights%d = %r"%(i,c.getWeights()))
        com.append("knots%d = %r"%(i,c.getKnots()))
        com.append("mults%d = %r"%(i,c.getMultiplicities()))
        com.append("periodic%d = %r"%(i,c.isPeriodic()))
        com.append("degree%d = %s"%(i,c.Degree))
        com.append("rational%d = %r"%(i,c.isRational()))
        com.append("bs%d = Part.BSplineCurve()"%i)
        #com.append("bs%d.buildFromPolesMultsKnots(poles%d, mults%d, knots%d, periodic%d, degree%d, )"%(i,i,i,i,i,i))
        com.append("bs%d.buildFromPolesMultsKnots(poles%d, mults%d, knots%d, periodic%d, degree%d, weights%d, rational%d)"%(i,i,i,i,i,i,i,i))
        com.append('obj%d = FreeCAD.ActiveDocument.addObject("Part::Spline","BSplineCurve%d")'%(i,i))
        com.append('obj%d.Shape = bs%d.toShape()'%(i,i))
    elif isinstance(c,Part.BezierCurve):
        com.append("poles%d = %r"%(i,c.getPoles()))
        #com.append("degree%d = %s"%(i,c.Degree))
        com.append("be%d = Part.BezierCurve()"%i)
        com.append("be%d.increase(%s)"%(i,c.Degree))
        com.append("be%d.setPoles(poles%d)"%(i,i))
        if c.isRational():
            w = c.getWeights()
            for j in range(len(w)):
                com.append("be%d.setWeight(%i,%f)"%(i,j+1,w[j]))
        com.append('obj%d = FreeCAD.ActiveDocument.addObject("Part::Spline","BezierCurve%d")'%(i,i))
        com.append('obj%d.Shape = be%d.toShape()'%(i,i))
    com.append("")
    
    for s in com:
        FreeCADGui.doCommand(s) 
Example #26
Source File: libS2R.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def setProfiles(self, plist):
        data = []
        self.knots1, self.knots2 = [],[]
        for pro in plist:
            pts = pro.discretize(100)
            bspline = Part.BSplineCurve()
            bspline.approximate(Points = pts, ParamType = 'Chordlength') # 'Uniform' 'Centripetal'
            bs = Part.Edge(bspline) #, pro.FirstParameter, pro.LastParameter)
            data.append(self.getContactParams(bs))
        sortedProfs = sorted(data,key=itemgetter(0)) # Sort profiles on rail1ContactParam
        self.profiles = []
        for datum in sortedProfs:
            self.knots1.append(datum[0])
            self.knots2.append(datum[1])
            p = profile(datum[2])
            p.Rail1Param = datum[0]
            p.Rail2Param = datum[1]
            p.FirstParameter = datum[3]
            p.LastParameter = datum[4]
            self.getLocalProfile(p)
            self.profiles.append(p)
            FreeCAD.Console.PrintMessage("\n Profile : %f - %f\n"%(p.Rail1Param,p.Rail2Param))
        if len(plist) == 1:
            self.extend = True
            FreeCAD.Console.PrintMessage('\n1 Profile given\n')
        FreeCAD.Console.PrintMessage('\nProfiles sorted\n') 
Example #27
Source File: libS2R.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def buildInterpoCurves(self):
        c1 = []
        c2 = []
        k = range(len(self.profiles))
        for i in range(self.profileSamples):
            pts1 = []
            pts2 = []
            for pro in self.profiles:
                fp = pro.FirstParameter
                lp = pro.LastParameter
                prange = lp-fp
                t = fp + 1.0 * prange * i / (self.profileSamples - 1)
                pts1.append(pro.localCurve1.valueAt(t))
                pts2.append(pro.localCurve2.valueAt(t))
            #k1 = self.parameterization(pts1, self.parametrization, False)
            #k2 = self.parameterization(pts2, self.parametrization, False)
            #FreeCAD.Console.PrintMessage('\nParameters : %s\n'%str(k))
            ic1 = Part.BSplineCurve()
            ic1.interpolate(Points = pts1, Parameters = k) #, Tangents = v, TangentFlags = b)
            #ic1.approximate(Points = pts1, DegMin = 1, DegMax = 1, Tolerance = 1.0, Parameters = k)
            ic2 = Part.BSplineCurve()
            #c2.buildFromPolesMultsKnots(pts[1],m,self.knots2,False,1)
            ic2.interpolate(Points = pts2, Parameters = k) #, Tangents = v, TangentFlags = b)
            #ic2.approximate(Points = pts2, DegMin = 1, DegMax = 1, Tolerance = 1.0, Parameters = k)
            c1.append(ic1)
            c2.append(ic2)
        self.interpoCurves = (c1,c2) 
Example #28
Source File: gordon_profile_FP.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def execute(self, obj):
        try:
            o = FreeCADGui.ActiveDocument.getInEdit().Object
            if o == obj:
                return
        except:
            FreeCAD.Console.PrintWarning("execute is disabled during editing\n")
        pts = self.get_points(obj)
        if pts:
            if len(pts) < 2:
                FreeCAD.Console.PrintError("%s : Not enough points\n"%obj.Label)
                return(False)
            else:
                obj.Data = pts
        else:
            pts = obj.Data

        tans = [FreeCAD.Vector()]*len(pts)
        flags = [False]*len(pts)
        for i in range(len(obj.Tangents)):
            tans[i] = obj.Tangents[i]
        for i in range(len(obj.Flags)):
            flags[i] = obj.Flags[i]
        #if not (len(obj.LinearSegments) == len(pts)-1):
            #FreeCAD.Console.PrintError("%s : Points and LinearSegments mismatch\n"%obj.Label)
        if len(obj.LinearSegments) > 0:
            for i,b in enumerate(obj.LinearSegments):
                if b:
                    tans[i] = pts[i+1]-pts[i]
                    tans[i+1] = tans[i]
                    flags[i] = True
                    flags[i+1] = True
        params = profile_editor.parameterization(pts,obj.Parametrization,obj.Periodic)
        curve = Part.BSplineCurve()
        curve.interpolate(Points=pts, Parameters=params, PeriodicFlag=obj.Periodic, Tolerance=obj.Tolerance, Tangents=tans, TangentFlags=flags)
        obj.Shape = curve.toShape() 
Example #29
Source File: approximate_extension.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def approximate(self, obj, input_shape):
        pts = False
        input_edges = None
        if isinstance(input_shape,(list, tuple)):
            #debug(isinstance(input_shape[0],Base.Vector))
            if isinstance(input_shape[0],Base.Vector):
                pts = input_shape
            elif isinstance(input_shape[0],Part.Edge):
                input_edges = input_shape
        else:
            input_edges = input_shape.Edges
        if not obj.Active:
            return Part.Compound(input_shape)
        edges = list()
        if input_edges:
            for e in input_edges:
                pts = e.discretize(obj.Samples)
                bs = Part.BSplineCurve()
                bs.approximate(Points = pts, DegMin = obj.DegreeMin, DegMax = obj.DegreeMax, Tolerance = obj.ApproxTolerance, Continuity = obj.Continuity, ParamType = obj.Parametrization)
                edges.append(bs.toShape())
            se = Part.sortEdges(edges)
            wires = []
            for el in se:
                if len(el) > 1:
                    wires.append(Part.Wire(el))
                else:
                    wires.append(el[0])
            if len(wires) > 1:
                return Part.Compound(wires)
            else:
                return wires[0]
        elif pts:
            bs = Part.BSplineCurve()
            bs.approximate(Points = pts, DegMin = obj.DegreeMin, DegMax = obj.DegreeMax, Tolerance = obj.ApproxTolerance, Continuity = obj.Continuity, ParamType = obj.Parametrization)
            return bs.toShape() 
Example #30
Source File: ribbon.py    From CurvesWB with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        self.param = list()
        self.value = list()
        self.bs = Part.BSplineCurve()
        self.must_increase = True