Skip to content

Commit

Permalink
OpenSCAD Module: bugfixes and improvements
Browse files Browse the repository at this point in the history
if more than 14 digits are given don round in general,
but test for <eps only.
refine before extrusion
support polyhedron faces which replaces polyhedron faces
importCSG round rotations
don't call Draft.makecircle and makeprism as they trigger a recompute
use group placholder for objects with no children
move removesubtree to OpenSCADUtils
add resize and offset keywords
add OpenSCAD_ExplodeGroup command
add OpenSCAD_IncreaseToleranceFeature
change refine shape logo
  • Loading branch information
5263 committed Mar 6, 2014
1 parent 040c19b commit b58d1ca
Show file tree
Hide file tree
Showing 13 changed files with 1,286 additions and 520 deletions.
8 changes: 5 additions & 3 deletions src/Mod/OpenSCAD/InitGui.py
Expand Up @@ -95,10 +95,12 @@ class OpenSCADWorkbench ( Workbench ):
def Initialize(self):
import OpenSCAD_rc,OpenSCADCommands
commands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
'OpenSCAD_RefineShapeFeature',"OpenSCAD_Edgestofaces",\
'OpenSCAD_ExpandPlacements']
'OpenSCAD_RefineShapeFeature',\
'OpenSCAD_IncreaseToleranceFeature', 'OpenSCAD_Edgestofaces', \
'OpenSCAD_ExpandPlacements','OpenSCAD_ExplodeGroup']
toolbarcommands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
'OpenSCAD_RefineShapeFeature']
'OpenSCAD_ExplodeGroup','OpenSCAD_RefineShapeFeature']
#'OpenSCAD_IncreaseToleranceFeature' #icon still missing
import PartGui
parttoolbarcommands = ['Part_CheckGeometry',"Part_Primitives",\
"Part_Builder",'Part_Cut','Part_Fuse','Part_Common',\
Expand Down
99 changes: 74 additions & 25 deletions src/Mod/OpenSCAD/OpenSCADCommands.py
Expand Up @@ -37,6 +37,50 @@ def translate(context,text):
def utf8(unio):
return unicode(unio).encode('UTF8')

class ExplodeGroup:
"Ungroup Objects"
def IsActive(self):
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0

def Activated(self):
def isgrey(shapecolor):
defaultcolor=(float.fromhex('0x1.99999ap-1'),float.fromhex('0x1.99999ap-1'),\
float.fromhex('0x1.99999ap-1'),0.0)
return all(facecolor == defaultcolor for facecolor in shapecolor)

def randomcolor(transp=0.0):
import random
return (random.random(),random.random(),random.random(),transp)

def explode(obj,color=True):
if obj.isDerivedFrom('Part::Fuse') or obj.isDerivedFrom('Part::MultiFuse'):
plm = obj.Placement
outlist = obj.OutList[:]
if plm.isNull() or all(len(oo.InList)==1 for oo in obj.OutList):
obj.Document.removeObject(obj.Name)
for oo in outlist:
if not plm.isNull():
oo.Placement=plm.multiply(oo.Placement)
if FreeCAD.GuiUp:
import FreeCADGui
oo.ViewObject.show()
if color and isgrey(oo.ViewObject.DiffuseColor):
if color == True:
oo.ViewObject.DiffuseColor=randomcolor()
else:
oo.ViewObject.DiffuseColor=color

for obj in FreeCADGui.Selection.getSelection():
if len(obj.InList) == 0: # allowed only for for top level objects
explode(obj)

def GetResources(self):
return {'Pixmap' : 'OpenSCAD_Explode_Group', 'MenuText': \
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_ExplodeGroup',\
'Explode Group'), 'ToolTip': \
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_ExplodeGroup',\
'remove fusion, apply placement to children and color randomly')}

class ColorCodeShape:
"Change the Color of selected or all Shapes based on their validity"
def Activated(self):
Expand All @@ -57,7 +101,7 @@ def GetResources(self):

class Edgestofaces:
def IsActive(self):
return bool(FreeCADGui.Selection.getSelectionEx())
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0

def Activated(self):
from OpenSCAD2Dgeom import edgestofaces,Overlappingfaces
Expand All @@ -78,13 +122,12 @@ def GetResources(self):

class RefineShapeFeature:
def IsActive(self):
return bool(FreeCADGui.Selection.getSelectionEx())
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0

def Activated(self):
import Part,OpenSCADFeatures
selection=FreeCADGui.Selection.getSelectionEx()
for selobj in selection:
#newobj=FreeCAD.ActiveDocument.addObject("Part::FeaturePython",'refine')
newobj=selobj.Document.addObject("Part::FeaturePython",'refine')
OpenSCADFeatures.RefineShape(newobj,selobj.Object)
OpenSCADFeatures.ViewProviderTree(newobj.ViewObject)
Expand All @@ -98,13 +141,34 @@ def GetResources(self):
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_RefineShapeFeature',\
'Create Refine Shape Feature')}

class IncreaseToleranceFeature:
def IsActive(self):
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0

def Activated(self):
import Part,OpenSCADFeatures
selection=FreeCADGui.Selection.getSelectionEx()
for selobj in selection:
newobj=selobj.Document.addObject("Part::FeaturePython",'tolerance')
OpenSCADFeatures.IncreaseTolerance(newobj,selobj.Object)
OpenSCADFeatures.ViewProviderTree(newobj.ViewObject)
newobj.Label='tolerance_%s' % selobj.Object.Label
selobj.Object.ViewObject.hide()
FreeCAD.ActiveDocument.recompute()
def GetResources(self):
return {'Pixmap' : 'OpenSCAD_IncreaseToleranceFeature', 'MenuText': \
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_IncreaseToleranceFeature',\
'Increase Tolerance Feature'), 'ToolTip': \
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_IncreaseToleranceFeature',\
'Create Feature that allows to increase the tolerance')}


class ExpandPlacements:
'''This should aid interactive repair in the future
but currently it breaks extrusions, as axis, base and so on have to be
recalculated'''
def IsActive(self):
return bool(FreeCADGui.Selection.getSelectionEx())
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0

def Activated(self):
import expandplacements
Expand All @@ -119,7 +183,7 @@ def GetResources(self):

class ReplaceObject:
def IsActive(self):
return len(FreeCADGui.Selection.getSelection()) == 3
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') == 3
def Activated(self):
import replaceobj
#objs=[selobj.Object for selobj in FreeCADGui.Selection.getSelectionEx()]
Expand All @@ -139,28 +203,11 @@ def GetResources(self):

class RemoveSubtree:
def IsActive(self):
return bool(FreeCADGui.Selection.getSelectionEx())
return FreeCADGui.Selection.countObjectsOfType('Part::Feature') > 0
def Activated(self):
def addsubobjs(obj,toremoveset):
toremove.add(obj)
for subobj in obj.OutList:
addsubobjs(subobj,toremoveset)
import OpenSCADUtils,FreeCADGui
OpenSCADUtils.removesubtree(FreeCADGui.Selection.getSelection())

import FreeCAD,FreeCADGui
objs=FreeCADGui.Selection.getSelection()
toremove=set()
for obj in objs:
addsubobjs(obj,toremove)
checkinlistcomplete =False
while not checkinlistcomplete:
for obj in toremove:
if (obj not in objs) and (frozenset(obj.InList) - toremove):
toremove.remove(obj)
break
else:
checkinlistcomplete = True
for obj in toremove:
obj.Document.removeObject(obj.Name)
def GetResources(self):
return {'Pixmap' : 'OpenSCAD_RemoveSubtree', 'MenuText': \
QtCore.QT_TRANSLATE_NOOP('OpenSCAD_RemoveSubtree',\
Expand Down Expand Up @@ -368,8 +415,10 @@ def GetResources(self):
'Perform Minkowski')}

FreeCADGui.addCommand('OpenSCAD_ColorCodeShape',ColorCodeShape())
FreeCADGui.addCommand('OpenSCAD_ExplodeGroup',ExplodeGroup())
FreeCADGui.addCommand('OpenSCAD_Edgestofaces',Edgestofaces())
FreeCADGui.addCommand('OpenSCAD_RefineShapeFeature',RefineShapeFeature())
FreeCADGui.addCommand('OpenSCAD_IncreaseToleranceFeature',IncreaseToleranceFeature())
FreeCADGui.addCommand('OpenSCAD_ExpandPlacements',ExpandPlacements())
FreeCADGui.addCommand('OpenSCAD_ReplaceObject',ReplaceObject())
FreeCADGui.addCommand('OpenSCAD_RemoveSubtree',RemoveSubtree())
Expand Down
25 changes: 25 additions & 0 deletions src/Mod/OpenSCAD/OpenSCADFeatures.py
Expand Up @@ -292,6 +292,31 @@ def execute(self, fp):
sh=fp.Base.Shape.removeSplitter()
fp.Shape=sh

class IncreaseTolerance:
'''increase the tolerance of every vertex
in the current implementation its' placement is linked'''
def __init__(self,obj,child,tolerance=0):
obj.addProperty("App::PropertyLink","Base","Base",
"The base object that wire must be extracted")
obj.addProperty("App::PropertyDistance","Tolerance","Base","Tolerance")
obj.Base = child
obj.Tolerance = tolerance
obj.Proxy = self
def onChanged(self, fp, prop):
if prop in ["Tolerance"]:
self.createGeometry(fp)
def execute(self, fp):
self.createGeometry(fp)

def createGeometry(self,fp):
if fp.Base:
sh=fp.Base.Shape.copy()
for vertex in sh.Vertexes:
vertex.Tolerance = max(vertex.Tolerance,fp.Tolerance.Value)
fp.Shape = sh
fp.Placement = sh.Placement


class GetWire:
'''return the first wire from a given shape'''
def __init__(self, obj,child=None):
Expand Down
151 changes: 146 additions & 5 deletions src/Mod/OpenSCAD/OpenSCADUtils.py
Expand Up @@ -109,7 +109,7 @@ def check_output2(*args,**kwargs):
p=subprocess.Popen(*args,**kwargs)
stdoutd,stderrd = p.communicate()
if p.returncode != 0:
raise OpenSCADError('%s %s\n' % (stdoutd.strip(),stderr.strip()))
raise OpenSCADError('%s %s\n' % (stdoutd.strip(),stderrd.strip()))
#raise Exception,'stdout %s\n stderr%s' %(stdoutd,stderrd)
if stderrd.strip():
FreeCAD.Console.PrintWarning(stderrd+u'\n')
Expand Down Expand Up @@ -188,12 +188,14 @@ def multiplymat(l,r):
def isorthogonal(submatrix,precision=4):
"""checking if 3x3 Matrix is ortogonal (M*Transp(M)==I)"""
prod=multiplymat(submatrix,zip(*submatrix))
return [[round(f,precision) for f in line] for line in prod]==[[1,0,0],[0,1,0],[0,0,1]]
return [[round(f,precision) for f in line] \
for line in prod]==[[1,0,0],[0,1,0],[0,0,1]]

def detsubmatrix(s):
"""get the determinant of a 3x3 Matrix given as list of row vectors"""
return s[0][0]*s[1][1]*s[2][2]+s[0][1]*s[1][2]*s[2][0]+s[0][2]*s[1][0]*s[2][1]\
-s[2][0]*s[1][1]*s[0][2]-s[2][1]*s[1][2]*s[0][0]-s[2][2]*s[1][0]*s[0][1]
return s[0][0]*s[1][1]*s[2][2]+s[0][1]*s[1][2]*s[2][0]+\
s[0][2]*s[1][0]*s[2][1]-s[2][0]*s[1][1]*s[0][2]-\
s[2][1]*s[1][2]*s[0][0]-s[2][2]*s[1][0]*s[0][1]

def isspecialorthogonalpython(submat,precision=4):
return isorthogonal(submat,precision) and round(detsubmatrix(submat),precision)==1
Expand All @@ -202,7 +204,8 @@ def isrotoinversionpython(submat,precision=4):
return isorthogonal(submat,precision) and round(detsubmatrix(submat),precision)==-1

def isspecialorthogonal(mat,precision=4):
return abs(mat.submatrix(3).isOrthogonal(10**(-precision))-1.0) < 10**(-precision) and \
return abs(mat.submatrix(3).isOrthogonal(10**(-precision))-1.0) < \
10**(-precision) and \
abs(mat.submatrix(3).determinant()-1.0) < 10**(-precision)

def decomposerotoinversion(m,precision=4):
Expand Down Expand Up @@ -241,6 +244,123 @@ def vec2householder(nv):
nv.z*nv.x*l,nv.z*nv.y*l,nv.z*nv.z*l,0,0,0,0,0)
return FreeCAD.Matrix()-hh


def angneg(d):
return d if (d <= 180.0) else (d-360)

def shorthexfloat(f):
s=f.hex()
mantisse, exponent = f.hex().split('p',1)
return '%sp%s' % (mantisse.rstrip('0'),exponent)


def comparerotations(r1,r2):
import FreeCAD
'''compares two rotations
a value of zero means that they are identical'''
r2c=FreeCAD.Rotation(r2)
r2c.invert()
return r1.multiply(r2c).Angle

def findbestmatchingrotation(r1):
import FreeCAD
vangl = \
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 11.25, 12.0, 13.0,
14.0, 15.0, 16.0, (180.0/11.0), 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 22.5,
23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, (360.0/11.0),
33.0, 33.75, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0,
44.0, 45.0, 46.0, 47.0, 48.0, 49.0,(540.0/11.0), 50.0, 51.0, (360.0/7.0),
52.0, 53.0, 54.0, 55.0, 56.0, 56.25, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0,
63.0, 64.0, 65.0,(720.0/11.0), 66.0, 67.0, 67.5, 68.0, 69.0, 70.0, 71.0,
72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 78.75, 79.0, 80.0, 81.0,(900.0/11.0),
82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 89.0, 90.0, 91.0, 92.0, 93.0, 94.0,
95.0, 96.0, 97.0, 98.0,(1080.0/11.0), 99.0, 100.0, 101.0, 101.25, 102.0,
(720.0/7.0), 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0, 110.0, 111.0,
112.0, 112.5, 113.0, 114.0, (1260.0/11), 115.0, 116.0, 117.0, 118.0, 119.0,
120.0, 121.0, 122.0, 123.0, 123.75, 124.0, 125.0, 126.0, 127.0, 128.0,
129.0, 130.0,(1440.0/11.0), 131.0, 132.0, 133.0, 134.0, 135.0, 136.0,
137.0, 138.0, 139.0, 140.0, 141.0, 142.0, 143.0, 144.0, 145.0, 146.0, 146.25,
147.0, (1620.0/11.0), 148.0, 149.0, 150.0, 151.0, 152.0, 153.0, 154.0,
(1080.0/7.0), 155.0, 156.0, 157.0, 157.5, 158.0, 159.0, 160.0, 161.0, 162.0,
163.0, (1800.0/11.0), 164.0, 165.0, 166.0, 167.0, 168.0, 168.75, 169.0, 170.0,
171.0, 172.0, 173.0, 174.0, 175.0, 176.0, 177.0,178.0, 179.0,180.0,
-179.0, -178.0, -177.0, -176.0, -175.0, -174.0, -173.0, -172.0, -171.0, -170.0,
-169.0, -168.75, -168.0, -167.0, -166.0, -165.0, -164.0, (-1800.0/11.0),
-163.0, -162.0, -161.0, -160.0, -159.0, -158.0, -157.5, -157.0, -156.0,
-155.0, (-1080.0/7.0), -154.0, -153.0, -152.0, -151.0, -150.0, -149.0, -148.0,
(-1620.0/11.0), -147.0, -146.25, -146.0, -145.0, -144.0, -143.0, -142.0,
-141.0, -140.0, -139.0,-138.0, -137.0, -136.0, -135.0, -134.0, -133.0, -132.0,
-131.0, (-1440/11.0), -130.0, -129.0, -128.0,-127.0, -126.0, -125.0, -124.0,
-123.75, -123.0, -122.0, -121.0, -120.0, -119.0, -118.0, -117.0, -116.0,
-115.0,(-1260.0/11.0), -114.0, -113.0, -112.5, -112.0, -111.0, -110.0, -109.0,
-108.0, -107.0, -106.0, -105.0,-104.0, -103.0,(-720.0/7.0), -102.0, -101.25,
-101.0, -100.0, -99.0, (-1080.0/11.0), -98.0, -97.0, -96.0, -95.0, -94.0,
-93.0, -92.0, -91.0, -90.0, -89.0, -88.0, -87.0, -86.0, -85.0, -84.0, -83.0,
-82.0,(-900.0/11.0), -81.0, -80.0, -79.0, -78.75, -78.0, -77.0, -76.0, -75.0,
-74.0, -73.0, -72.0, -71.0, -70.0, -69.0, -68.0, -67.5, -67.0, -66.0,
(-720.0/11.0), -65.0, -64.0, -63.0, -62.0, -61.0, -60.0, -59.0, -58.0, -57.0,
-56.25, -56.0, -55.0, -54.0, -53.0, -52.0,(-360.0/7.0), -51.0, -50.0,
(-540.0/11.0), -49.0, -48.0, -47.0, -46.0, -45.0, -44.0, -43.0, -42.0, -41.0,
-40.0, -39.0, -38.0, -37.0, -36.0, -35.0, -34.0, -33.75, -33.0,(-360.0/11.0),
-32.0, -31.0, -30.0, -29.0, -28.0, -27.0, -26.0, -25.0, -24.0, -23.0, -22.5,
-22.0, -21.0, -20.0, -19.0, -18.0, -17.0,(-180.0/11.0), -16.0, -15.0, -14.0,
-13.0, -12.0, -11.25, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0,
-2.0, -1.0)
def tup2nvect(tup):
"""convert a tuple to a normalized vector"""
v=FreeCAD.Vector(*tup)
v.normalize()
return v

def wkaxes():
"""well known axes for rotations"""
vtupl=((1,0,0),(0,1,0),(0,0,1),
(1,1,0),(1,0,1),(0,1,1),(-1,1,0),(-1,0,1),(0,1,-1),
(1,1,1),(1,1,-1),(1,-1,1),(-1,1,1))
return tuple(tup2nvect(tup) for tup in vtupl)

bestrot=FreeCAD.Rotation()
dangle = comparerotations(r1,bestrot)
for axis in wkaxes():
for angle in vangl:
for axissign in (1.0,-1.0):
r2=FreeCAD.Rotation(axis*axissign,angle)
dangletest = comparerotations(r1,r2)
if dangletest < dangle:
bestrot = r2
dangle = dangletest
return (bestrot,dangle)

def roundrotation(rot,maxangulardistance=1e-5):
'''guess the rotation axis and angle for a rotation
recreated from rounded floating point values
(from a quaterion or transformation matrix)'''
def teststandardrot(r1,maxangulardistance=1e-5):
'''test a few common rotations beforehand'''
import FreeCAD,itertools
eulers = []
for angle in (90,-90,180,45,-45,135,-135):
for euler in itertools.permutations((0,0,angle)):
eulers.append(euler)
for euler in itertools.product((0,45,90,135,180,-45,-90,-135),repeat=3):
eulers.append(euler)
for euler in eulers:
r2 = FreeCAD.Rotation(*euler)
if comparerotations(r1,r2) < maxangulardistance:
return r2

if rot.isNull():
return rot
firstguess = teststandardrot(rot,maxangulardistance)
if firstguess is not None:
return firstguess
#brute force
bestguess,angulardistance = findbestmatchingrotation(rot)
if angulardistance < maxangulardistance: #use guess
return bestguess
else: #use original
return rot

def callopenscadmeshstring(scadstr):
"""Call OpenSCAD and return the result as a Mesh"""
import Mesh,os
Expand Down Expand Up @@ -414,3 +534,24 @@ def process_ObjectsViaOpenSCAD(doc,children,name):
import FreeCAD
FreeCAD.Console.PrintError( unicode(translate('OpenSCAD',\
"Error all shapes must be either 2D or both must be 3D"))+u'\n')

def removesubtree(objs):
def addsubobjs(obj,toremoveset):
toremove.add(obj)
for subobj in obj.OutList:
addsubobjs(subobj,toremoveset)

import FreeCAD
toremove=set()
for obj in objs:
addsubobjs(obj,toremove)
checkinlistcomplete =False
while not checkinlistcomplete:
for obj in toremove:
if (obj not in objs) and (frozenset(obj.InList) - toremove):
toremove.remove(obj)
break
else:
checkinlistcomplete = True
for obj in toremove:
obj.Document.removeObject(obj.Name)

0 comments on commit b58d1ca

Please sign in to comment.