Macro FCCamGroover

Description
This macro creates a groove in a cylinder for a cam to ride in.

The object created is similar to the one shown in this youtube video.

Screenshot:

Script
import FreeCAD from FreeCAD import Base from PySide import QtGui,QtCore import Part, Draft from math import * import time from DraftTools import msg as say import math __title__ = "FC Cam Groover" __author__ = "TheMarkster" __url__ = "https://www.freecadweb.org/wiki/Macro_FCCamGroover" __Wiki__ = "https://www.freecadweb.org/wiki/Macro_FCCamGroover" __date__ = "2018.07.23" __version__ = __date__ #OS: Windows 10 msg = u"""FC Cam Groover v"""+__version__+""", a macro to create a cam groove in a cylinder, Copyright (c) 2018 by 'TheMarkster' Credit to Gomez Lucio and Laurent Despeyroux for their macro, '3D Parametric Curve Macro', 2015, which provided inspiration for some of the code used herin.  Thanks also to emills2 for his invaluable feedback. All errors are mine, not theirs.  The grooved cylinder produced will be similar to the one depicted in this video: https://youtu.be/io1JL1U7kUs  Parameters supported:  cylinder height,  cylinder radius,  groove depth,  groove width,  strokes per revolution,  stroke range,  steps (precision)  This file is a supplement to the FreeCAD CAx development system.                                                                             This program is free software; you can redistribute it and/or modify   it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2 of     the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License at http://www.gnu.org/licenses for more details. For more information about the GNU Library General Public License write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ title = u"""Welcome to FC Cam Groover Macro""" icon=QtGui.QMessageBox.Information diag = QtGui.QMessageBox(icon, title, msg) diag.setWindowModality(QtCore.Qt.ApplicationModal) diag.setTextFormat(QtCore.Qt.RichText); diag.exec_ window = QtGui.QMainWindow def processEvents:      time.sleep(0.001)      QtGui.QApplication.processEvents def getDouble(txt1,txt2,default,start=0,decimals=4):     inp,ok = QtGui.QInputDialog.getDouble(window, txt1,txt2,default, start,1000000, decimals)     if ok:         return inp     else:         raise StandardError('User canceled') def getInt(txt1,txt2,default):     inp, ok = QtGui.QInputDialog.getInt(window, txt1,txt2,default, 1, 100000, 1)     if ok:         return inp     else:         raise StandardError('User canceled') def getDistance3d(x1, y1, z1, x2, y2, z2):     return math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2) radius = getDouble(u'Radius of Cylinder',u'Enter radius of cylinder (in mm).\nMake sure it\'s big enough or the operation will fail:',10) cylinderHeight = getDouble(u'Height of Cylinder', u'Enter the height of the cylinder. (in mm)\n(Can be adjusted after the macro finishes.)',10) depth = getDouble(u'Depth of Groove', u'Enter the depth of the groove to be cut into the cylinder (in mm):',2) slotHeight = getDouble(u'Height of Groove',u'Enter the height of the slot to be cut into the cylinder.\n\nNote: this is not the stroke length, which will be input below. (in mm) ',2) innerRadius = radius-depth strokeFactor = getDouble(u'Stroke Length',u'Enter the axial length of the stroke: (in mm)',5) strokeFactor /= radius strokesPerRevolution = getInt(u'Strokes per Revolution',u'Enter the number of strokes per revolution of the cylinder.\n1 or 2 seems to work okay, but anything beyond 3 could be troublesome:', 2) steps = getInt(u'Steps',u'Enter number of steps (points) in curve, the more points the more precise the curve,\nbut the longer to process. If it\'s too small the operation *will* fail.\nExperiment with this value if you are having trouble with a particular groove.\nThe default is 628:',628) def makeBSpline(strokesPerRevolution,strokeFactor,radius,steps): a = strokesPerRevolution b = strokeFactor c = radius interval = (2*math.pi)/float(steps) points=[] t = 0.0 maxT = 2*math.pi    counter=0 while t <= maxT: say(u'Step '+str(counter)+u' of '+str(steps)+u'\n') counter +=1 processEvents x = math.cos(t)*c y = math.sin(t)*c z = math.sin(t*a/2.0)*math.cos(t*a/2.0)*c*b points.append(App.Vector(x,y,z)) t += interval Draft.makeBSpline(points,closed=True,face=False) say(u'Done with BSpline\n') processEvents if not App.ActiveDocument: App.newDocument toBeRemoved=[] #temporary objects to be removed to clean up tree say(u'Making BSpline...\n') processEvents makeBSpline(strokesPerRevolution,strokeFactor,radius,steps) bs = App.ActiveDocument.ActiveObject Draft.makeCircle(slotHeight,face=False) cir = App.ActiveDocument.getObject('Circle') cir.Placement=App.Placement(App.Vector(0,0,0), App.Rotation(90,0,0), App.Vector(0,0,0)) say(u'Making a draft path array of '+str(steps)+' circles, waiting for FreeCAD...\n') processEvents Draft.makePathArray(cir,bs,count=steps,xlate=None,align=True) pa = App.ActiveDocument.getObject('PathArray') points = [] for v in pa.Shape.Vertexes: points.append(v.Point) Draft.makeBSpline(points,True,None) bs1 = App.ActiveDocument.ActiveObject say(u'Scaling bspline1...\n') processEvents Draft.scale([bs],delta=FreeCAD.Vector(innerRadius/float(radius),innerRadius/float(radius),1.0),center=FreeCAD.Vector(0.0,0.0,0.0),copy=True,legacy=True) bs2 = App.ActiveDocument.ActiveObject say(u'Scaling bspline2...\n') processEvents Draft.scale([bs1],delta=FreeCAD.Vector(innerRadius/float(radius),innerRadius/float(radius),1.0),center=FreeCAD.Vector(0.0,0.0,0.0),copy=True,legacy=True) bs3 = App.ActiveDocument.ActiveObject Draft.scale([bs],delta=FreeCAD.Vector(1.05,1.05,1.0),center=FreeCAD.Vector(0.0,0.0,0.0),copy=False,legacy=True) say(u'Scaling bspline2...\n') processEvents Draft.scale([bs1],delta=FreeCAD.Vector(1.05,1.05,1.0),center=FreeCAD.Vector(0.0,0.0,0.0),copy=False,legacy=True) say(u'Making ruled surfaces.') processEvents FreeCAD.ActiveDocument.addObject('Part::RuledSurface', 'Ruled Surface') FreeCAD.ActiveDocument.ActiveObject.Curve1=(bs1,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Curve2=(bs3,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Orientation = u"Forward" rs = FreeCAD.ActiveDocument.ActiveObject say(u'.') processEvents FreeCAD.ActiveDocument.addObject('Part::RuledSurface', 'Ruled Surface') FreeCAD.ActiveDocument.ActiveObject.Curve1=(bs2,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Curve2=(bs3,['Edge1']) rs1 = FreeCAD.ActiveDocument.ActiveObject say(u'.') processEvents FreeCAD.ActiveDocument.addObject('Part::RuledSurface', 'Ruled Surface') FreeCAD.ActiveDocument.ActiveObject.Curve1=(rs,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Curve2=(bs,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Orientation=u"Forward" rs2 = FreeCAD.ActiveDocument.ActiveObject say(u'.') processEvents FreeCAD.ActiveDocument.addObject('Part::RuledSurface', 'Ruled Surface') FreeCAD.ActiveDocument.ActiveObject.Curve1=(rs2,['Edge3']) FreeCAD.ActiveDocument.ActiveObject.Curve2=(rs1,['Edge1']) FreeCAD.ActiveDocument.ActiveObject.Orientation = u"Reversed" rs3 = FreeCAD.ActiveDocument.ActiveObject say(u'. Done.\n') processEvents toBeRemoved.extend([bs.Name,bs1.Name,bs2.Name,bs3.Name,rs.Name,rs1.Name,rs2.Name,rs3.Name,pa.Name,cir.Name]) App.ActiveDocument.recompute say(u'Building shell...\n') processEvents try: _=Part.Shell([App.ActiveDocument.getObject(rs3.Name).Shape.Faces[0], App.ActiveDocument.getObject(rs2.Name).Shape.Faces[0], App.ActiveDocument.getObject(rs.Name).Shape.Faces[0], App.ActiveDocument.getObject(rs1.Name).Shape.Faces[0], ]) except: say('Exception making shell. You might try increasing the number of steps, which sometimes helps.\n') raise StandardError('Exception creating shell object.') if _.isNull: raise RuntimeError('Failed to create shell') App.ActiveDocument.addObject('Part::Feature','Shell').Shape=_.removeSplitter del _ shell = App.ActiveDocument.ActiveObject toBeRemoved.extend([shell.Name]) App.ActiveDocument.recompute say(u'Making shell into a solid...\n') processEvents __s__=App.ActiveDocument.Shell.Shape __s__=Part.Solid(__s__) __o__=App.ActiveDocument.addObject("Part::Feature","GrooveFeature") __o__.Label="GrooveFeature" __o__.Shape=__s__ del __s__, __o__ shellSolid = App.ActiveDocument.ActiveObject App.ActiveDocument.recompute say('Building cylinder...\n') processEvents App.ActiveDocument.addObject("Part::Cylinder","Cylinder") App.ActiveDocument.ActiveObject.Label = "Cylinder" App.ActiveDocument.getObject("Cylinder").Radius = str(radius) App.ActiveDocument.getObject("Cylinder").Height = str(cylinderHeight) cylinder = App.ActiveDocument.ActiveObject shellSolid.Placement=App.Placement(App.Vector(0,0,-slotHeight/2.0), App.Rotation(0,0,0), App.Vector(0,0,0)) #center groove in cylinder cylinder.Placement=App.Placement(App.Vector(0,0,-cylinderHeight/2.0), App.Rotation(10,0,0), App.Vector(0,0,0)) #rotate slightly to move the edge lines apart App.ActiveDocument.recompute say(u'Cleaning up temporary objects.') processEvents for tbr in toBeRemoved: App.ActiveDocument.removeObject(tbr) say(u'.') processEvents say(u'. Done.\n') App.ActiveDocument.recompute Gui.SendMsgToActiveView("ViewFit") msg=u""" Done. Last thing you need to do is the boolean cut from the Part workbench, cutting Groove Feature from the cylinder,  if all looks good.  It is recommended to check the geometry via the Part workbench menu with RunBoPCheck = True enabled  in Tools -> Edit Parameters -> Preferences -> Mod -> Part -> CheckGeometry.  If the check fails, go back and do it again  with a different number of steps. """ title=u'Thanks for using FC Cam Groover' icon=QtGui.QMessageBox.Information diag = QtGui.QMessageBox(icon, title, msg) diag.setWindowModality(QtCore.Qt.ApplicationModal) diag.setTextFormat(QtCore.Qt.RichText); diag.exec_
 * 1) -*- coding: utf-8 -*-
 * 1) Word size of OS: 64-bit
 * 2) Word size of FreeCAD: 64-bit
 * 3) Version: 0.18.14061 (Git)
 * 4) Build type: Release
 * 5) Branch: master
 * 6) Hash: c4fc02cbcfff975712e977dc08f859fba71ba0ad
 * 7) Python version: 2.7.14
 * 8) Qt version: 4.8.7
 * 9) Coin version: 4.0.0a
 * 10) OCC version: 7.2.0
 * 11) Locale: English/UnitedStates (en_US)
 * 1) inspiration for this makeBSpline function is from the 3d parametric curve macro
 * 2) it is not an exact copy/paste of the code, but rather is based on the same principles
 * 3) but without overhead of the gui
 * 1) we use an array of circles aligned along the bspline to create a new
 * 2) bspline that closely follows (but is not exact copy of) original bspline
 * 3) each circle has a vertex, similar to the seam line of a cylinder
 * 4) these vertices are used to create a list of points from which the new
 * 5) bspline is created
 * 6) simply moving the original bspline along the z axis does not work because
 * 7) the groove will narrow in places and widen in others. the circles ensure
 * 8) better (though probably still not perfect) uniformity of the groove
 * 1) now make the original bsplines bigger so they extend outside the cylinder edges (to prevent issues with boolean cut later on)