Merge pull request #449 from looooo/python3-arch

Python3 Arch
This commit is contained in:
wwmayer 2017-01-17 13:39:24 +01:00 committed by GitHub
commit c0ec75eb5a
28 changed files with 345 additions and 330 deletions

View File

@ -265,13 +265,13 @@ PyObject *PropertyVectorList::getPyObject(void)
void PropertyVectorList::setPyObject(PyObject *value) void PropertyVectorList::setPyObject(PyObject *value)
{ {
if (PyList_Check(value)) { if (PySequence_Check(value)) {
Py_ssize_t nSize = PyList_Size(value); Py_ssize_t nSize = PySequence_Size(value);
std::vector<Base::Vector3d> values; std::vector<Base::Vector3d> values;
values.resize(nSize); values.resize(nSize);
for (Py_ssize_t i=0; i<nSize;++i) { for (Py_ssize_t i=0; i<nSize;++i) {
PyObject* item = PyList_GetItem(value, i); PyObject* item = PySequence_GetItem(value, i);
PropertyVector val; PropertyVector val;
val.setPyObject( item ); val.setPyObject( item );
values[i] = val.getValue(); values[i] = val.getValue();

View File

@ -293,7 +293,7 @@ def splitMesh(obj,mark=True):
def makeFace(wires,method=2,cleanup=False): def makeFace(wires,method=2,cleanup=False):
'''makeFace(wires): makes a face from a list of wires, finding which ones are holes''' '''makeFace(wires): makes a face from a list of wires, finding which ones are holes'''
#print "makeFace: start:", wires #print("makeFace: start:", wires)
import Part import Part
if not isinstance(wires,list): if not isinstance(wires,list):
@ -308,21 +308,21 @@ def makeFace(wires,method=2,cleanup=False):
wires = wires[:] wires = wires[:]
#print "makeFace: inner wires found" #print("makeFace: inner wires found")
ext = None ext = None
max_length = 0 max_length = 0
# cleaning up rubbish in wires # cleaning up rubbish in wires
if cleanup: if cleanup:
for i in range(len(wires)): for i in range(len(wires)):
wires[i] = DraftGeomUtils.removeInterVertices(wires[i]) wires[i] = DraftGeomUtils.removeInterVertices(wires[i])
#print "makeFace: garbage removed" #print("makeFace: garbage removed")
for w in wires: for w in wires:
# we assume that the exterior boundary is that one with # we assume that the exterior boundary is that one with
# the biggest bounding box # the biggest bounding box
if w.BoundBox.DiagonalLength > max_length: if w.BoundBox.DiagonalLength > max_length:
max_length = w.BoundBox.DiagonalLength max_length = w.BoundBox.DiagonalLength
ext = w ext = w
#print "makeFace: exterior wire",ext #print("makeFace: exterior wire", ext)
wires.remove(ext) wires.remove(ext)
if method == 1: if method == 1:
@ -330,22 +330,22 @@ def makeFace(wires,method=2,cleanup=False):
# all interior wires mark a hole and must reverse # all interior wires mark a hole and must reverse
# their orientation, otherwise Part.Face fails # their orientation, otherwise Part.Face fails
for w in wires: for w in wires:
#print "makeFace: reversing",w #print("makeFace: reversing", w)
w.reverse() w.reverse()
# make sure that the exterior wires comes as first in the list # make sure that the exterior wires comes as first in the list
wires.insert(0, ext) wires.insert(0, ext)
#print "makeFace: done sorting", wires #print("makeFace: done sorting", wires)
if wires: if wires:
return Part.Face(wires) return Part.Face(wires)
else: else:
# method 2: use the cut method # method 2: use the cut method
mf = Part.Face(ext) mf = Part.Face(ext)
#print "makeFace: external face:",mf #print("makeFace: external face:", mf)
for w in wires: for w in wires:
f = Part.Face(w) f = Part.Face(w)
#print "makeFace: internal face:",f #print("makeFace: internal face:", f)
mf = mf.cut(f) mf = mf.cut(f)
#print "makeFace: final face:",mf.Faces #print("makeFace: final face:", mf.Faces)
return mf.Faces[0] return mf.Faces[0]
def closeHole(shape): def closeHole(shape):
@ -475,7 +475,7 @@ def getShapeFromMesh(mesh,fast=True,tolerance=0.001,flat=False,cut=True):
# print "getShapeFromMesh: non-solid mesh, using slow method" # print "getShapeFromMesh: non-solid mesh, using slow method"
faces = [] faces = []
segments = mesh.getPlanarSegments(tolerance) segments = mesh.getPlanarSegments(tolerance)
#print len(segments) #print(len(segments))
for i in segments: for i in segments:
if len(i) > 0: if len(i) > 0:
wires = MeshPart.wireFromSegment(mesh, i) wires = MeshPart.wireFromSegment(mesh, i)
@ -581,7 +581,7 @@ def removeShape(objs,mark=True):
if dims: if dims:
name = obj.Name name = obj.Name
tp = Draft.getType(obj) tp = Draft.getType(obj)
print tp print(tp)
if tp == "Structure": if tp == "Structure":
FreeCAD.ActiveDocument.removeObject(name) FreeCAD.ActiveDocument.removeObject(name)
import ArchStructure import ArchStructure
@ -900,7 +900,7 @@ def makeCompoundFromSelected(objects=None):
Part.show(c) Part.show(c)
def cleanArchSplitter(objets=None): def cleanArchSplitter(objects=None):
"""cleanArchSplitter([objects]): removes the splitters from the base shapes """cleanArchSplitter([objects]): removes the splitters from the base shapes
of the given Arch objects or selected Arch objects if objects is None""" of the given Arch objects or selected Arch objects if objects is None"""
import FreeCAD,FreeCADGui import FreeCAD,FreeCADGui
@ -912,7 +912,7 @@ def cleanArchSplitter(objets=None):
if obj.isDerivedFrom("Part::Feature"): if obj.isDerivedFrom("Part::Feature"):
if hasattr(obj,"Base"): if hasattr(obj,"Base"):
if obj.Base: if obj.Base:
print "Attempting to clean splitters from ",obj.Label print("Attempting to clean splitters from ", obj.Label)
if obj.Base.isDerivedFrom("Part::Feature"): if obj.Base.isDerivedFrom("Part::Feature"):
if not obj.Base.Shape.isNull(): if not obj.Base.Shape.isNull():
obj.Base.Shape = obj.Base.Shape.removeSplitter() obj.Base.Shape = obj.Base.Shape.removeSplitter()
@ -933,31 +933,31 @@ def rebuildArchShape(objects=None):
if hasattr(obj,"Base"): if hasattr(obj,"Base"):
if obj.Base: if obj.Base:
try: try:
print "Attempting to rebuild ",obj.Label print("Attempting to rebuild ", obj.Label)
if obj.Base.isDerivedFrom("Part::Feature"): if obj.Base.isDerivedFrom("Part::Feature"):
if not obj.Base.Shape.isNull(): if not obj.Base.Shape.isNull():
faces = [] faces = []
for f in obj.Base.Shape.Faces: for f in obj.Base.Shape.Faces:
f2 = Part.Face(f.Wires) f2 = Part.Face(f.Wires)
#print "rebuilt face: isValid is ",f2.isValid() #print("rebuilt face: isValid is ", f2.isValid())
faces.append(f2) faces.append(f2)
if faces: if faces:
shell = Part.Shell(faces) shell = Part.Shell(faces)
if shell: if shell:
#print "rebuilt shell: isValid is ",shell.isValid() #print("rebuilt shell: isValid is ", shell.isValid())
solid = Part.Solid(shell) solid = Part.Solid(shell)
if solid: if solid:
if not solid.isValid(): if not solid.isValid():
solid.sewShape() solid.sewShape()
solid = Part.Solid(solid) solid = Part.Solid(solid)
#print "rebuilt solid: isValid is ",solid.isValid() #print("rebuilt solid: isValid is ",solid.isValid())
if solid.isValid(): if solid.isValid():
obj.Base.Shape = solid obj.Base.Shape = solid
success = True success = True
except: except:
pass pass
if not success: if not success:
print "Failed to rebuild a valid solid for object ",obj.Name print ("Failed to rebuild a valid solid for object ",obj.Name)
FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.recompute()

View File

@ -470,7 +470,7 @@ class Component:
def processSubShapes(self,obj,base,placement=None): def processSubShapes(self,obj,base,placement=None):
"Adds additions and subtractions to a base shape" "Adds additions and subtractions to a base shape"
import Draft,Part import Draft,Part
#print "Processing subshapes of ",obj.Label, " : ",obj.Additions #print("Processing subshapes of ",obj.Label, " : ",obj.Additions)
if placement: if placement:
if placement.isNull(): if placement.isNull():
@ -520,7 +520,7 @@ class Component:
try: try:
base = base.fuse(s) base = base.fuse(s)
except Part.OCCError: except Part.OCCError:
print "Arch: unable to fuse object ",obj.Name, " with ", o.Name print("Arch: unable to fuse object ", obj.Name, " with ", o.Name)
else: else:
base = s base = s
@ -558,7 +558,7 @@ class Component:
try: try:
base = base.cut(s) base = base.cut(s)
except Part.OCCError: except Part.OCCError:
print "Arch: unable to cut object ",o.Name, " from ", obj.Name print("Arch: unable to cut object ",o.Name, " from ", obj.Name)
return base return base
def applyShape(self,obj,shape,placement,allowinvalid=False,allownosolid=False): def applyShape(self,obj,shape,placement,allowinvalid=False,allownosolid=False):
@ -633,7 +633,7 @@ class Component:
except Part.OCCError: except Part.OCCError:
# error in computing the areas. Better set them to zero than show a wrong value # error in computing the areas. Better set them to zero than show a wrong value
if obj.HorizontalArea.Value != 0: if obj.HorizontalArea.Value != 0:
print "Debug: Error computing areas for ",obj.Label,": unable to project face: ",str([v.Point for v in f.Vertexes])," (face normal:",f.normalAt(0,0),")" print("Debug: Error computing areas for ",obj.Label,": unable to project face: ",str([v.Point for v in f.Vertexes])," (face normal:",f.normalAt(0,0),")")
obj.HorizontalArea = 0 obj.HorizontalArea = 0
if hasattr(obj,"PerimeterLength"): if hasattr(obj,"PerimeterLength"):
if obj.PerimeterLength.Value != 0: if obj.PerimeterLength.Value != 0:
@ -659,7 +659,7 @@ class ViewProviderComponent:
self.Object = vobj.Object self.Object = vobj.Object
def updateData(self,obj,prop): def updateData(self,obj,prop):
#print obj.Name," : updating ",prop #print(obj.Name," : updating ",prop)
if prop == "BaseMaterial": if prop == "BaseMaterial":
if obj.BaseMaterial: if obj.BaseMaterial:
if 'DiffuseColor' in obj.BaseMaterial.Material: if 'DiffuseColor' in obj.BaseMaterial.Material:
@ -692,7 +692,7 @@ class ViewProviderComponent:
return ":/icons/Arch_Component.svg" return ":/icons/Arch_Component.svg"
def onChanged(self,vobj,prop): def onChanged(self,vobj,prop):
#print vobj.Object.Name, " : changing ",prop #print(vobj.Object.Name, " : changing ",prop)
if prop == "Visibility": if prop == "Visibility":
#for obj in vobj.Object.Additions+vobj.Object.Subtractions: #for obj in vobj.Object.Additions+vobj.Object.Subtractions:
# if (Draft.getType(obj) == "Window") or (Draft.isClone(obj,"Window",True)): # if (Draft.getType(obj) == "Window") or (Draft.isClone(obj,"Window",True)):

View File

@ -27,7 +27,8 @@ __title__="FreeCAD Equipment"
__author__ = "Yorik van Havre" __author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org" __url__ = "http://www.freecadweb.org"
import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands,Units import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands
from FreeCAD import Units
from FreeCAD import Vector from FreeCAD import Vector
if FreeCAD.GuiUp: if FreeCAD.GuiUp:
import FreeCADGui import FreeCADGui
@ -121,7 +122,7 @@ def createMeshView(obj,direction=FreeCAD.Vector(0,0,-1),outeronly=False,largesto
# 3. Getting the bigger mesh from the planar segments # 3. Getting the bigger mesh from the planar segments
if largestonly: if largestonly:
c = cleanmesh.getSeparateComponents() c = cleanmesh.getSeparateComponents()
#print c #print(c)
cleanmesh = c[0] cleanmesh = c[0]
segs = cleanmesh.getPlanarSegments(1) segs = cleanmesh.getPlanarSegments(1)
meshes = [] meshes = []
@ -141,7 +142,7 @@ def createMeshView(obj,direction=FreeCAD.Vector(0,0,-1),outeronly=False,largesto
shape = None shape = None
for f in cleanmesh.Facets: for f in cleanmesh.Facets:
p = Part.makePolygon(f.Points+[f.Points[0]]) p = Part.makePolygon(f.Points+[f.Points[0]])
#print p,len(p.Vertexes),p.isClosed() #print(p,len(p.Vertexes),p.isClosed())
try: try:
p = Part.Face(p) p = Part.Face(p)
if shape: if shape:
@ -165,7 +166,7 @@ def createMeshView(obj,direction=FreeCAD.Vector(0,0,-1),outeronly=False,largesto
try: try:
f = Part.Face(w) f = Part.Face(w)
except Part.OCCError: except Part.OCCError:
print "Unable to produce a face from the outer wire." print("Unable to produce a face from the outer wire.")
else: else:
shape = f shape = f

View File

@ -147,7 +147,7 @@ class _Floor:
else: else:
pl = obj.Placement.copy() pl = obj.Placement.copy()
if not DraftVecUtils.equals(pl.Base,self.OldPlacement.Base): if not DraftVecUtils.equals(pl.Base,self.OldPlacement.Base):
print "placement moved" print("placement moved")
delta = pl.Base.sub(self.OldPlacement.Base) delta = pl.Base.sub(self.OldPlacement.Base)
for o in obj.Group: for o in obj.Group:
if hasattr(o,"Placement"): if hasattr(o,"Placement"):

View File

@ -73,9 +73,9 @@ def readPresets():
Presets.append(r) Presets.append(r)
bid=bid+1 bid=bid+1
except ValueError: except ValueError:
print "Skipping bad line: "+str(row) print("Skipping bad line: "+str(row))
except IOError: except IOError:
print "Could not open ",profilefile print("Could not open ",profilefile)
return Presets return Presets
def makeProfile(profile=[0,'REC','REC100x100','R',100,100]): def makeProfile(profile=[0,'REC','REC100x100','R',100,100]):
@ -93,7 +93,7 @@ def makeProfile(profile=[0,'REC','REC100x100','R',100,100]):
elif profile[3]=="U": elif profile[3]=="U":
_ProfileU(obj, profile) _ProfileU(obj, profile)
else : else :
print "Profile not supported" print("Profile not supported")
if FreeCAD.GuiUp: if FreeCAD.GuiUp:
Draft._ViewProviderDraft(obj.ViewObject) Draft._ViewProviderDraft(obj.ViewObject)
return obj return obj

View File

@ -136,7 +136,7 @@ class _CommandRebar:
if len(obj.Support) != 0: if len(obj.Support) != 0:
sup = obj.Support[0][0] sup = obj.Support[0][0]
else: else:
print "Arch: error: couldn't extract a base object" print("Arch: error: couldn't extract a base object")
return return
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Rebar")) FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Rebar"))
FreeCADGui.addModule("Arch") FreeCADGui.addModule("Arch")
@ -145,7 +145,7 @@ class _CommandRebar:
FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.recompute()
return return
else: else:
print "Arch: error: couldn't extract a base object" print("Arch: error: couldn't extract a base object")
return return
FreeCAD.Console.PrintMessage(translate("Arch","Please select a base face on a structural object\n")) FreeCAD.Console.PrintMessage(translate("Arch","Please select a base face on a structural object\n"))
@ -208,7 +208,7 @@ class _Rebar(ArchComponent.Component):
father = obj.InList[0] father = obj.InList[0]
wire = obj.Base.Shape.Wires[0] wire = obj.Base.Shape.Wires[0]
if hasattr(obj,"Rounding"): if hasattr(obj,"Rounding"):
#print obj.Rounding #print(obj.Rounding)
if obj.Rounding: if obj.Rounding:
radius = obj.Rounding * obj.Diameter.Value radius = obj.Rounding * obj.Diameter.Value
import DraftGeomUtils import DraftGeomUtils
@ -223,8 +223,8 @@ class _Rebar(ArchComponent.Component):
axis = FreeCAD.Vector(obj.Direction) #.normalize() axis = FreeCAD.Vector(obj.Direction) #.normalize()
# don't normalize so the vector can also be used to determine the distance # don't normalize so the vector can also be used to determine the distance
size = axis.Length size = axis.Length
#print axis #print(axis)
#print size #print(size)
if (obj.OffsetStart.Value + obj.OffsetEnd.Value) > size: if (obj.OffsetStart.Value + obj.OffsetEnd.Value) > size:
return return
@ -236,7 +236,7 @@ class _Rebar(ArchComponent.Component):
try: try:
bar = wire.makePipeShell([circle],True,False,2) bar = wire.makePipeShell([circle],True,False,2)
except Part.OCCError: except Part.OCCError:
print "Arch: error sweeping rebar profile along the base sketch" print("Arch: error sweeping rebar profile along the base sketch")
return return
# building final shape # building final shape
shapes = [] shapes = []

View File

@ -647,10 +647,10 @@ class _Roof(ArchComponent.Component):
rn += 1 rn += 1
if obj.RidgeLength.Value != rl: if obj.RidgeLength.Value != rl:
obj.RidgeLength = rl obj.RidgeLength = rl
print str(rn)+" ridge edges in roof "+obj.Name print(str(rn)+" ridge edges in roof "+obj.Name)
if obj.BorderLength.Value != bl: if obj.BorderLength.Value != bl:
obj.BorderLength = bl obj.BorderLength = bl
print str(bn)+" border edges in roof "+obj.Name print(str(bn)+" border edges in roof "+obj.Name)
ArchComponent.Component.computeAreas(self,obj) ArchComponent.Component.computeAreas(self,obj)

View File

@ -112,8 +112,8 @@ class _ArchSchedule:
obj.Result.set("A"+str(i+2),obj.Description[i].encode("utf8")) obj.Result.set("A"+str(i+2),obj.Description[i].encode("utf8"))
if verbose: if verbose:
l= "OPERATION: "+obj.Description[i] l= "OPERATION: "+obj.Description[i]
print l print (l)
print len(l)*"=" print (len(l)*"=")
# get list of objects # get list of objects
objs = obj.Objects[i] objs = obj.Objects[i]
val = obj.Value[i] val = obj.Value[i]
@ -172,7 +172,7 @@ class _ArchSchedule:
if val.upper() == "COUNT": if val.upper() == "COUNT":
val = len(objs) val = len(objs)
if verbose: if verbose:
print val, ",".join([o.Label for o in objs]) print (val, ",".join([o.Label for o in objs]))
obj.Result.set("B"+str(i+2),str(val)) obj.Result.set("B"+str(i+2),str(val))
else: else:
vals = val.split(".") vals = val.split(".")
@ -180,13 +180,13 @@ class _ArchSchedule:
for o in objs: for o in objs:
if verbose: if verbose:
l = o.Name+" ("+o.Label+"):" l = o.Name+" ("+o.Label+"):"
print l+(40-len(l))*" ", print (l+(40-len(l))*" ",)
try: try:
d = o d = o
for v in vals[1:]: for v in vals[1:]:
d = getattr(d,v) d = getattr(d,v)
if verbose: if verbose:
print d print (d)
if hasattr(d,"Value"): if hasattr(d,"Value"):
d = d.Value d = d.Value
except: except:
@ -216,7 +216,7 @@ class _ArchSchedule:
else: else:
obj.Result.set("B"+str(i+2),str(val)) obj.Result.set("B"+str(i+2),str(val))
if verbose: if verbose:
print "TOTAL:"+34*" "+str(val) print ("TOTAL:"+34*" "+str(val))
def __getstate__(self): def __getstate__(self):
return self.Type return self.Type

View File

@ -97,7 +97,7 @@ def getCutShapes(objs,section,showHidden):
if o.Shape.isValid(): if o.Shape.isValid():
shapes.extend(o.Shape.Solids) shapes.extend(o.Shape.Solids)
else: else:
print section.Label,": Skipping invalid object:",o.Label print(section.Label,": Skipping invalid object:",o.Label)
else: else:
shapes.append(o.Shape) shapes.append(o.Shape)
cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(section.Shape.copy(),shapes) cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(section.Shape.copy(),shapes)
@ -188,7 +188,7 @@ def getSVG(section,allOn=False,renderMode="Wireframe",showHidden=False,showFill=
if showHidden: if showHidden:
svg += render.getHiddenSVG(linewidth="LWPlaceholder") svg += render.getHiddenSVG(linewidth="LWPlaceholder")
svg += '</g>\n' svg += '</g>\n'
# print render.info() # print(render.info())
else: else:
# render using the Drawing module # render using the Drawing module
@ -622,7 +622,7 @@ class _ArchDrawingView:
def getDXF(self,obj): def getDXF(self,obj):
"returns a DXF representation of the view" "returns a DXF representation of the view"
if obj.RenderingMode == "Solid": if obj.RenderingMode == "Solid":
print "Unable to get DXF from Solid mode: ",obj.Label print("Unable to get DXF from Solid mode: ",obj.Label)
return "" return ""
result = [] result = []
import Drawing import Drawing

View File

@ -312,7 +312,7 @@ class _Space(ArchComponent.Component):
shape = None shape = None
faces = [] faces = []
#print "starting compute" #print("starting compute")
# 1: if we have a base shape, we use it # 1: if we have a base shape, we use it
if obj.Base: if obj.Base:
@ -323,7 +323,7 @@ class _Space(ArchComponent.Component):
# 2: if not, add all bounding boxes of considered objects and build a first shape # 2: if not, add all bounding boxes of considered objects and build a first shape
if shape: if shape:
#print "got shape from base object" #print("got shape from base object")
bb = shape.BoundBox bb = shape.BoundBox
else: else:
bb = None bb = None
@ -336,7 +336,7 @@ class _Space(ArchComponent.Component):
if not bb: if not bb:
return return
shape = Part.makeBox(bb.XLength,bb.YLength,bb.ZLength,FreeCAD.Vector(bb.XMin,bb.YMin,bb.ZMin)) shape = Part.makeBox(bb.XLength,bb.YLength,bb.ZLength,FreeCAD.Vector(bb.XMin,bb.YMin,bb.ZMin))
#print "created shape from boundbox" #print("created shape from boundbox")
# 3: identifing boundary faces # 3: identifing boundary faces
goodfaces = [] goodfaces = []
@ -345,9 +345,9 @@ class _Space(ArchComponent.Component):
if "Face" in b[1]: if "Face" in b[1]:
fn = int(b[1][4:])-1 fn = int(b[1][4:])-1
faces.append(b[0].Shape.Faces[fn]) faces.append(b[0].Shape.Faces[fn])
#print "adding face ",fn," of object ",b[0].Name #print("adding face ",fn," of object ",b[0].Name)
#print "total: ", len(faces), " faces" #print("total: ", len(faces), " faces")
# 4: get cutvolumes from faces # 4: get cutvolumes from faces
cutvolumes = [] cutvolumes = []
@ -356,22 +356,22 @@ class _Space(ArchComponent.Component):
f.reverse() f.reverse()
cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(f,shape) cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(f,shape)
if cutvolume: if cutvolume:
#print "generated 1 cutvolume" #print("generated 1 cutvolume")
cutvolumes.append(cutvolume.copy()) cutvolumes.append(cutvolume.copy())
#Part.show(cutvolume) #Part.show(cutvolume)
for v in cutvolumes: for v in cutvolumes:
#print "cutting" #print("cutting")
shape = shape.cut(v) shape = shape.cut(v)
# 5: get the final shape # 5: get the final shape
if shape: if shape:
if shape.Solids: if shape.Solids:
#print "setting objects shape" #print("setting objects shape")
shape = shape.Solids[0] shape = shape.Solids[0]
obj.Shape = shape obj.Shape = shape
return return
print "Arch: error computing space boundary" print("Arch: error computing space boundary")
def getArea(self,obj): def getArea(self,obj):
"returns the horizontal area at the center of the space" "returns the horizontal area at the center of the space"

View File

@ -258,7 +258,7 @@ class _Stairs(ArchComponent.Component):
fLength = float(l-obj.Width.Value)/(numberofsteps-2) fLength = float(l-obj.Width.Value)/(numberofsteps-2)
fHeight = float(h)/numberofsteps fHeight = float(h)/numberofsteps
a = math.atan(fHeight/fLength) a = math.atan(fHeight/fLength)
print "landing data:",fLength,":",fHeight print("landing data:",fLength,":",fHeight)
# step # step
p1 = self.align(vBase,obj.Align,vWidth) p1 = self.align(vBase,obj.Align,vWidth)
@ -365,7 +365,7 @@ class _Stairs(ArchComponent.Component):
vBase = edge.Vertexes[0].Point vBase = edge.Vertexes[0].Point
vNose = DraftVecUtils.scaleTo(vLength,-abs(obj.Nosing.Value)) vNose = DraftVecUtils.scaleTo(vLength,-abs(obj.Nosing.Value))
a = math.atan(vHeight.Length/vLength.Length) a = math.atan(vHeight.Length/vLength.Length)
#print "stair data:",vLength.Length,":",vHeight.Length #print("stair data:",vLength.Length,":",vHeight.Length)
# steps # steps
for i in range(numberofsteps-1): for i in range(numberofsteps-1):
@ -402,7 +402,7 @@ class _Stairs(ArchComponent.Component):
h = DraftVecUtils.scaleTo(vLength,-resLength) h = DraftVecUtils.scaleTo(vLength,-resLength)
lProfile.append(lProfile[-1].add(Vector(h.x,h.y,-resHeight2))) lProfile.append(lProfile[-1].add(Vector(h.x,h.y,-resHeight2)))
lProfile.append(vBase) lProfile.append(vBase)
#print lProfile #print(lProfile)
pol = Part.makePolygon(lProfile) pol = Part.makePolygon(lProfile)
struct = Part.Face(pol) struct = Part.Face(pol)
evec = vWidth evec = vWidth
@ -429,7 +429,7 @@ class _Stairs(ArchComponent.Component):
v4 = DraftVecUtils.scaleTo(vLength,-l4) v4 = DraftVecUtils.scaleTo(vLength,-l4)
lProfile.append(lProfile[-1].add(v4)) lProfile.append(lProfile[-1].add(v4))
lProfile.append(lProfile[0]) lProfile.append(lProfile[0])
#print lProfile #print(lProfile)
pol = Part.makePolygon(lProfile) pol = Part.makePolygon(lProfile)
pol = Part.Face(pol) pol = Part.Face(pol)
evec = DraftVecUtils.scaleTo(vWidth,obj.StringerWidth.Value) evec = DraftVecUtils.scaleTo(vWidth,obj.StringerWidth.Value)
@ -484,11 +484,10 @@ class _Stairs(ArchComponent.Component):
def makeCurvedStairs(self,obj,edge): def makeCurvedStairs(self,obj,edge):
print "Not yet implemented!" print("Not yet implemented!")
def makeCurvedStairsWithLanding(self,obj,edge): def makeCurvedStairsWithLanding(self,obj,edge):
print "Not yet implemented!" print("Not yet implemented!")
class _ViewProviderStairs(ArchComponent.ViewProviderComponent): class _ViewProviderStairs(ArchComponent.ViewProviderComponent):

View File

@ -103,7 +103,7 @@ def makeStructuralSystem(objects=[],axes=[],name="StructuralSystem"):
based on the given objects and axes''' based on the given objects and axes'''
result = [] result = []
if not axes: if not axes:
print "At least one axis must be given" print("At least one axis must be given")
return return
if objects: if objects:
if not isinstance(objects,list): if not isinstance(objects,list):

View File

@ -63,7 +63,7 @@ class Renderer:
import WorkingPlane import WorkingPlane
self.wp = WorkingPlane.plane() self.wp = WorkingPlane.plane()
if DEBUG: print "Renderer initialized on " + str(self.wp) if DEBUG: print("Renderer initialized on " + str(self.wp))
def __str__(self): def __str__(self):
return "Arch Renderer: " + str(len(self.faces)) + " faces projected on " + str(self.wp) return "Arch Renderer: " + str(len(self.faces)) + " faces projected on " + str(self.wp)
@ -91,11 +91,11 @@ class Renderer:
self.wp.setFromPlacement(wp) self.wp.setFromPlacement(wp)
else: else:
self.wp = wp self.wp = wp
if DEBUG: print "Renderer set on " + str(self.wp) if DEBUG: print("Renderer set on " + str(self.wp))
def addFaces(self,faces,color=(0.9,0.9,0.9,1.0)): def addFaces(self,faces,color=(0.9,0.9,0.9,1.0)):
"add individual faces to this renderer, optionally with a color" "add individual faces to this renderer, optionally with a color"
if DEBUG: print "adding ", len(faces), " faces. Warning, these will get lost if using cut() or join()" if DEBUG: print("adding ", len(faces), " faces. Warning, these will get lost if using cut() or join()")
for f in faces: for f in faces:
self.faces.append([f,color]) self.faces.append([f,color])
self.resetFlags() self.resetFlags()
@ -111,11 +111,11 @@ class Renderer:
for f in o.Shape.Faces: for f in o.Shape.Faces:
self.faces.append([f,color]) self.faces.append([f,color])
self.resetFlags() self.resetFlags()
if DEBUG: print "adding ", len(self.objects), " objects, ", len(self.faces), " faces" if DEBUG: print("adding ", len(self.objects), " objects, ", len(self.faces), " faces")
def addShapes(self,shapes,color=(0.9,0.9,0.9,1.0)): def addShapes(self,shapes,color=(0.9,0.9,0.9,1.0)):
"add shapes to this renderer, optionally with a color. Warning, these will get lost if using join()" "add shapes to this renderer, optionally with a color. Warning, these will get lost if using join()"
if DEBUG: print "adding ", len(shapes), " shapes" if DEBUG: print("adding ", len(shapes), " shapes")
for s in shapes: for s in shapes:
if s.Faces: if s.Faces:
self.shapes.append([s,color]) self.shapes.append([s,color])
@ -149,14 +149,14 @@ class Renderer:
def isVisible(self,face): def isVisible(self,face):
"returns True if the given face points in the view direction" "returns True if the given face points in the view direction"
normal = face[0].normalAt(0,0) normal = face[0].normalAt(0,0)
if DEBUG: print "checking face normal ", normal, " against ", self.wp.axis, " : ", math.degrees(normal.getAngle(self.wp.axis)) if DEBUG: print("checking face normal ", normal, " against ", self.wp.axis, " : ", math.degrees(normal.getAngle(self.wp.axis)))
if normal.getAngle(self.wp.axis) < math.pi/2: if normal.getAngle(self.wp.axis) < math.pi/2:
return True return True
return False return False
def reorient(self): def reorient(self):
"reorients the faces on the WP" "reorients the faces on the WP"
#print "VRM: start reorient" #print("VRM: start reorient")
if not self.faces: if not self.faces:
return return
self.faces = [self.projectFace(f) for f in self.faces] self.faces = [self.projectFace(f) for f in self.faces]
@ -165,7 +165,7 @@ class Renderer:
if self.hiddenEdges: if self.hiddenEdges:
self.hiddenEdges = [self.projectEdge(e) for e in self.hiddenEdges] self.hiddenEdges = [self.projectEdge(e) for e in self.hiddenEdges]
self.oriented = True self.oriented = True
#print "VRM: end reorient" #print("VRM: end reorient")
def removeHidden(self): def removeHidden(self):
"removes faces pointing outwards" "removes faces pointing outwards"
@ -175,42 +175,42 @@ class Renderer:
for f in self.faces: for f in self.faces:
if self.isVisible(f): if self.isVisible(f):
faces.append(f) faces.append(f)
if DEBUG: print len(self.faces)-len(faces) , " faces removed, ", len(faces), " faces retained" if DEBUG: print(len(self.faces)-len(faces) , " faces removed, ", len(faces), " faces retained")
self.faces = faces self.faces = faces
self.trimmed = True self.trimmed = True
def projectFace(self,face): def projectFace(self,face):
"projects a single face on the WP" "projects a single face on the WP"
#print "VRM: projectFace start: ",len(face[0].Vertexes)," verts, ",len(face[0].Edges)," edges" #print("VRM: projectFace start: ",len(face[0].Vertexes)," verts, ",len(face[0].Edges)," edges")
wires = [] wires = []
if not face[0].Wires: if not face[0].Wires:
if DEBUG: print "Error: Unable to project face on the WP" if DEBUG: print("Error: Unable to project face on the WP")
return None return None
norm = face[0].normalAt(0,0) norm = face[0].normalAt(0,0)
for w in face[0].Wires: for w in face[0].Wires:
verts = [] verts = []
edges = Part.__sortEdges__(w.Edges) edges = Part.__sortEdges__(w.Edges)
#print len(edges)," edges after sorting" #print(len(edges)," edges after sorting")
for e in edges: for e in edges:
v = e.Vertexes[0].Point v = e.Vertexes[0].Point
#print v #print(v)
v = self.wp.getLocalCoords(v) v = self.wp.getLocalCoords(v)
verts.append(v) verts.append(v)
verts.append(verts[0]) verts.append(verts[0])
if len(verts) > 2: if len(verts) > 2:
#print "new wire with ",len(verts) #print("new wire with ",len(verts))
wires.append(Part.makePolygon(verts)) wires.append(Part.makePolygon(verts))
try: try:
sh = ArchCommands.makeFace(wires) sh = ArchCommands.makeFace(wires)
except: except:
if DEBUG: print "Error: Unable to project face on the WP" if DEBUG: print("Error: Unable to project face on the WP")
return None return None
else: else:
# restoring flipped normals # restoring flipped normals
vnorm = self.wp.getLocalCoords(norm) vnorm = self.wp.getLocalCoords(norm)
if vnorm.getAngle(sh.normalAt(0,0)) > 1: if vnorm.getAngle(sh.normalAt(0,0)) > 1:
sh.reverse() sh.reverse()
#print "VRM: projectFace end: ",len(sh.Vertexes)," verts" #print("VRM: projectFace end: ",len(sh.Vertexes)," verts")
return [sh]+face[1:] return [sh]+face[1:]
def projectEdge(self,edge): def projectEdge(self,edge):
@ -235,18 +235,18 @@ class Renderer:
try: try:
sh = Part.Face(wires) sh = Part.Face(wires)
except Part.OCCError: except Part.OCCError:
if DEBUG: print "Error: Unable to flatten face" if DEBUG: print("Error: Unable to flatten face")
return None return None
else: else:
return [sh]+face[1:] return [sh]+face[1:]
def cut(self,cutplane,hidden=False): def cut(self,cutplane,hidden=False):
"Cuts through the shapes with a given cut plane and builds section faces" "Cuts through the shapes with a given cut plane and builds section faces"
if DEBUG: print "\n\n======> Starting cut\n\n" if DEBUG: print("\n\n======> Starting cut\n\n")
if self.iscut: if self.iscut:
return return
if not self.shapes: if not self.shapes:
if DEBUG: print "No objects to make sections" if DEBUG: print("No objects to make sections")
else: else:
fill = (1.0,1.0,1.0,1.0) fill = (1.0,1.0,1.0,1.0)
shps = [] shps = []
@ -263,9 +263,9 @@ class Renderer:
shapes.append([c]+sh[1:]) shapes.append([c]+sh[1:])
for f in c.Faces: for f in c.Faces:
faces.append([f]+sh[1:]) faces.append([f]+sh[1:])
#print "iscoplanar:",f.Vertexes[0].Point,f.normalAt(0,0),cutface.Vertexes[0].Point,cutface.normalAt(0,0) #print("iscoplanar:",f.Vertexes[0].Point,f.normalAt(0,0),cutface.Vertexes[0].Point,cutface.normalAt(0,0))
if DraftGeomUtils.isCoplanar([f,cutface]): if DraftGeomUtils.isCoplanar([f,cutface]):
print "COPLANAR" print("COPLANAR")
sections.append([f,fill]) sections.append([f,fill])
if hidden: if hidden:
c = sol.cut(invcutvolume) c = sol.cut(invcutvolume)
@ -273,13 +273,13 @@ class Renderer:
self.shapes = shapes self.shapes = shapes
self.faces = faces self.faces = faces
self.sections = sections self.sections = sections
if DEBUG: print "Built ",len(self.sections)," sections, ", len(self.faces), " faces retained" if DEBUG: print("Built ",len(self.sections)," sections, ", len(self.faces), " faces retained")
self.iscut = True self.iscut = True
self.oriented = False self.oriented = False
self.trimmed = False self.trimmed = False
self.sorted = False self.sorted = False
self.joined = False self.joined = False
if DEBUG: print "\n\n======> Finished cut\n\n" if DEBUG: print("\n\n======> Finished cut\n\n")
def isInside(self,vert,face): def isInside(self,vert,face):
"Returns True if the vert is inside the face in Z projection" "Returns True if the vert is inside the face in Z projection"
@ -328,13 +328,13 @@ class Renderer:
def compare(self,face1,face2): def compare(self,face1,face2):
"zsorts two faces. Returns 1 if face1 is closer, 2 if face2 is closer, 0 otherwise" "zsorts two faces. Returns 1 if face1 is closer, 2 if face2 is closer, 0 otherwise"
#print face1,face2 #print(face1,face2)
if not face1: if not face1:
if DEBUG: print "Warning, undefined face!" if DEBUG: print("Warning, undefined face!")
return 31 return 31
elif not face2: elif not face2:
if DEBUG: print "Warning, undefined face!" if DEBUG: print("Warning, undefined face!" )
return 32 return 32
# theory from # theory from
@ -345,7 +345,7 @@ class Renderer:
b2 = face2[0].BoundBox b2 = face2[0].BoundBox
# test 1: if faces don't overlap, no comparison possible # test 1: if faces don't overlap, no comparison possible
if DEBUG: print "doing test 1" if DEBUG: print("doing test 1")
if b1.XMax < b2.XMin: if b1.XMax < b2.XMin:
return 0 return 0
if b1.XMin > b2.XMax: if b1.XMin > b2.XMax:
@ -354,18 +354,18 @@ class Renderer:
return 0 return 0
if b1.YMin > b2.YMax: if b1.YMin > b2.YMax:
return 0 return 0
if DEBUG: print "failed, faces bboxes are not distinct" if DEBUG: print("failed, faces bboxes are not distinct")
# test 2: if Z bounds dont overlap, it's easy to know the closest # test 2: if Z bounds dont overlap, it's easy to know the closest
if DEBUG: print "doing test 2" if DEBUG: print("doing test 2")
if b1.ZMax < b2.ZMin: if b1.ZMax < b2.ZMin:
return 2 return 2
if b2.ZMax < b1.ZMin: if b2.ZMax < b1.ZMin:
return 1 return 1
if DEBUG: print "failed, faces Z are not distinct" if DEBUG: print("failed, faces Z are not distinct")
# test 3: all verts of face1 are in front or behind the plane of face2 # test 3: all verts of face1 are in front or behind the plane of face2
if DEBUG: print "doing test 3" if DEBUG: print("doing test 3")
norm = face2[0].normalAt(0,0) norm = face2[0].normalAt(0,0)
behind = 0 behind = 0
front = 0 front = 0
@ -380,15 +380,15 @@ class Renderer:
behind += 1 behind += 1
else: else:
front += 1 front += 1
if DEBUG: print "front: ",front," behind: ",behind if DEBUG: print("front: ",front," behind: ",behind)
if behind == len(face1[0].Vertexes): if behind == len(face1[0].Vertexes):
return 2 return 2
elif front == len(face1[0].Vertexes): elif front == len(face1[0].Vertexes):
return 1 return 1
if DEBUG: print "failed, cannot say if face 1 is in front or behind" if DEBUG: print("failed, cannot say if face 1 is in front or behind")
# test 4: all verts of face2 are in front or behind the plane of face1 # test 4: all verts of face2 are in front or behind the plane of face1
if DEBUG: print "doing test 4" if DEBUG: print("doing test 4")
norm = face1[0].normalAt(0,0) norm = face1[0].normalAt(0,0)
behind = 0 behind = 0
front = 0 front = 0
@ -403,22 +403,22 @@ class Renderer:
behind += 1 behind += 1
else: else:
front += 1 front += 1
if DEBUG: print "front: ",front," behind: ",behind if DEBUG: print("front: ",front," behind: ",behind)
if behind == len(face2[0].Vertexes): if behind == len(face2[0].Vertexes):
return 1 return 1
elif front == len(face2[0].Vertexes): elif front == len(face2[0].Vertexes):
return 2 return 2
if DEBUG: print "failed, cannot say if face 2 is in front or behind" if DEBUG: print("failed, cannot say if face 2 is in front or behind")
# test 5: see if faces projections don't overlap, vertexwise # test 5: see if faces projections don't overlap, vertexwise
if DEBUG: print "doing test 5" if DEBUG: print("doing test 5")
if not self.zOverlaps(face1,face2): if not self.zOverlaps(face1,face2):
return 0 return 0
elif not self.zOverlaps(face2,face1): elif not self.zOverlaps(face2,face1):
return 0 return 0
if DEBUG: print "failed, faces are overlapping" if DEBUG: print("failed, faces are overlapping")
if DEBUG: print "Houston, all tests passed, and still no results" if DEBUG: print("Houston, all tests passed, and still no results")
return 0 return 0
def join(self,otype): def join(self,otype):
@ -437,7 +437,7 @@ class Renderer:
objs.append(o) objs.append(o)
for g in [walls,structs]: for g in [walls,structs]:
if g: if g:
print "group:",g print("group:",g)
col = g[0].ViewObject.DiffuseColor[0] col = g[0].ViewObject.DiffuseColor[0]
s = g[0].Shape s = g[0].Shape
for o in g[1:]: for o in g[1:]:
@ -445,7 +445,7 @@ class Renderer:
fs = s.fuse(o.Shape) fs = s.fuse(o.Shape)
fs = fs.removeSplitter() fs = fs.removeSplitter()
except Part.OCCError: except Part.OCCError:
print "shape fusion failed" print("shape fusion failed")
objs.append([o.Shape,o.ViewObject.DiffuseColor[0]]) objs.append([o.Shape,o.ViewObject.DiffuseColor[0]])
else: else:
s = fs s = fs
@ -456,7 +456,7 @@ class Renderer:
l = None l = None
h = None h = None
for f2 in faces: for f2 in faces:
if DEBUG: print "comparing face",str(self.faces.index(f1))," with face",str(self.faces.index(f2)) if DEBUG: print("comparing face",str(self.faces.index(f1))," with face",str(self.faces.index(f2)))
r = self.compare(f1,f2) r = self.compare(f1,f2)
if r == 1: if r == 1:
l = faces.index(f2) l = faces.index(f2)
@ -475,27 +475,27 @@ class Renderer:
def sort(self): def sort(self):
"projects a shape on the WP" "projects a shape on the WP"
if DEBUG: print "\n\n======> Starting sort\n\n" if DEBUG: print("\n\n======> Starting sort\n\n")
if len(self.faces) <= 1: if len(self.faces) <= 1:
return return
if not self.trimmed: if not self.trimmed:
self.removeHidden() self.removeHidden()
if DEBUG: print "Done hidden face removal" if DEBUG: print("Done hidden face removal")
if len(self.faces) == 1: if len(self.faces) == 1:
return return
if not self.oriented: if not self.oriented:
self.reorient() self.reorient()
if DEBUG: print "Done reorientation" if DEBUG: print("Done reorientation")
faces = self.faces[:] faces = self.faces[:]
if DEBUG: print "sorting ",len(self.faces)," faces" if DEBUG: print("sorting ",len(self.faces)," faces")
sfaces = [] sfaces = []
loopcount = 0 loopcount = 0
notfoundstack = 0 notfoundstack = 0
while faces: while faces:
if DEBUG: print "loop ", loopcount if DEBUG: print("loop ", loopcount)
f1 = faces[0] f1 = faces[0]
if sfaces and (notfoundstack < len(faces)): if sfaces and (notfoundstack < len(faces)):
if DEBUG: print "using ordered stack, notfound = ",notfoundstack if DEBUG: print("using ordered stack, notfound = ",notfoundstack)
p = self.findPosition(f1,sfaces) p = self.findPosition(f1,sfaces)
if p == None: if p == None:
# no position found, we move the face to the end of the pile # no position found, we move the face to the end of the pile
@ -510,11 +510,11 @@ class Renderer:
else: else:
# either there is no stack, or no more face can be compared # either there is no stack, or no more face can be compared
# find a root, 2 faces that can be compared # find a root, 2 faces that can be compared
if DEBUG: print "using unordered stack, notfound = ",notfoundstack if DEBUG: print("using unordered stack, notfound = ",notfoundstack)
for f2 in faces[1:]: for f2 in faces[1:]:
if DEBUG: print "comparing face",str(self.faces.index(f1))," with face",str(self.faces.index(f2)) if DEBUG: print("comparing face",str(self.faces.index(f1))," with face",str(self.faces.index(f2)))
r = self.compare(f1,f2) r = self.compare(f1,f2)
print "comparison result:",r print("comparison result:",r)
if r == 1: if r == 1:
faces.remove(f2) faces.remove(f2)
sfaces.append(f2) sfaces.append(f2)
@ -542,13 +542,13 @@ class Renderer:
faces.append(f1) faces.append(f1)
loopcount += 1 loopcount += 1
if loopcount == MAXLOOP * len(self.faces): if loopcount == MAXLOOP * len(self.faces):
if DEBUG: print "Too many loops, aborting." if DEBUG: print("Too many loops, aborting.")
break break
if DEBUG: print "done Z sorting. ", len(sfaces), " faces retained, ", len(self.faces)-len(sfaces), " faces lost." if DEBUG: print("done Z sorting. ", len(sfaces), " faces retained, ", len(self.faces)-len(sfaces), " faces lost.")
self.faces = sfaces self.faces = sfaces
self.sorted = True self.sorted = True
if DEBUG: print "\n\n======> Finished sort\n\n" if DEBUG: print("\n\n======> Finished sort\n\n")
def buildDummy(self): def buildDummy(self):
"Builds a dummy object with faces spaced on the Z axis, for visual check" "Builds a dummy object with faces spaced on the Z axis, for visual check"
@ -595,7 +595,7 @@ class Renderer:
def getViewSVG(self,linewidth=0.01): def getViewSVG(self,linewidth=0.01):
"Returns a SVG fragment from viewed faces" "Returns a SVG fragment from viewed faces"
if DEBUG: print "Printing ", len(self.faces), " faces" if DEBUG: print("Printing ", len(self.faces), " faces")
if not self.sorted: if not self.sorted:
self.sort() self.sort()
svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth) svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth)
@ -613,7 +613,7 @@ class Renderer:
def getSectionSVG(self,linewidth=0.02,fillpattern=None): def getSectionSVG(self,linewidth=0.02,fillpattern=None):
"Returns a SVG fragment from cut faces" "Returns a SVG fragment from cut faces"
if DEBUG: print "Printing ", len(self.sections), " sections" if DEBUG: print("Printing ", len(self.sections), " sections")
if not self.oriented: if not self.oriented:
self.reorient() self.reorient()
svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth) svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth)
@ -630,7 +630,7 @@ class Renderer:
svg +='<path ' svg +='<path '
svg += 'd="' svg += 'd="'
for w in f[0].Wires: for w in f[0].Wires:
#print "wire with ",len(w.Vertexes)," verts" #print("wire with ",len(w.Vertexes)," verts")
svg += self.getPathData(w) svg += self.getPathData(w)
svg += '" style="fill:' + fill + ';fill-rule: evenodd;"/>\n' svg += '" style="fill:' + fill + ';fill-rule: evenodd;"/>\n'
svg += '</g>\n' svg += '</g>\n'
@ -638,7 +638,7 @@ class Renderer:
def getHiddenSVG(self,linewidth=0.02): def getHiddenSVG(self,linewidth=0.02):
"Returns a SVG fragment from cut geometry" "Returns a SVG fragment from cut geometry"
if DEBUG: print "Printing ", len(self.sections), " hidden faces" if DEBUG: print("Printing ", len(self.sections), " hidden faces")
if not self.oriented: if not self.oriented:
self.reorient() self.reorient()
svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth) svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth)

View File

@ -135,11 +135,11 @@ def mergeShapes(w1,w2):
import DraftGeomUtils import DraftGeomUtils
w = DraftGeomUtils.findWires(eds) w = DraftGeomUtils.findWires(eds)
if len(w) == 1: if len(w) == 1:
#print "found common wire" #print("found common wire")
normal,length,width,height = w1.Proxy.getDefaultValues(w1) normal,length,width,height = w1.Proxy.getDefaultValues(w1)
print w[0].Edges print(w[0].Edges)
sh = w1.Proxy.getBase(w1,w[0],normal,width,height) sh = w1.Proxy.getBase(w1,w[0],normal,width,height)
print sh print(sh)
return sh return sh
return None return None

View File

@ -21,7 +21,8 @@
#* * #* *
#*************************************************************************** #***************************************************************************
import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands,Units import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands
from FreeCAD import Units
from FreeCAD import Vector from FreeCAD import Vector
if FreeCAD.GuiUp: if FreeCAD.GuiUp:
import FreeCADGui import FreeCADGui
@ -386,7 +387,7 @@ def makeWindowPreset(windowtype,width,height,h1,h2,h3,w1,w2,o1,o2,placement=None
FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.recompute()
return obj return obj
print "Arch: Unknown window type" print("Arch: Unknown window type")
class _CommandWindow: class _CommandWindow:
@ -865,7 +866,7 @@ class _Window(ArchComponent.Component):
if not DraftGeomUtils.isNull(pl): if not DraftGeomUtils.isNull(pl):
base.Placement = base.Placement.multiply(pl) base.Placement = base.Placement.multiply(pl)
else: else:
print "Arch: Bad formatting of window parts definitions" print("Arch: Bad formatting of window parts definitions")
base = self.processSubShapes(obj,base) base = self.processSubShapes(obj,base)
if base: if base:
@ -1004,7 +1005,7 @@ class _ViewProviderWindow(ArchComponent.ViewProviderComponent):
if not obj.WindowParts: if not obj.WindowParts:
return return
solids = obj.Shape.copy().Solids solids = obj.Shape.copy().Solids
#print "Colorizing ", solids #print("Colorizing ", solids)
colors = [] colors = []
base = obj.ViewObject.ShapeColor base = obj.ViewObject.ShapeColor
for i in range(len(solids)): for i in range(len(solids)):
@ -1016,7 +1017,7 @@ class _ViewProviderWindow(ArchComponent.ViewProviderComponent):
ccol = ArchCommands.getDefaultColor("WindowGlass") ccol = ArchCommands.getDefaultColor("WindowGlass")
for f in solids[i].Faces: for f in solids[i].Faces:
colors.append(ccol) colors.append(ccol)
#print "colors: ",colors #print("colors: ",colors)
if colors: if colors:
obj.ViewObject.DiffuseColor = colors obj.ViewObject.DiffuseColor = colors

View File

@ -120,7 +120,7 @@ def read(filename):
#for geom in col.geometries: #for geom in col.geometries:
for prim in geom.primitives(): for prim in geom.primitives():
#for prim in geom.primitives: #for prim in geom.primitives:
#print prim, dir(prim) #print(prim, dir(prim))
meshdata = [] meshdata = []
if hasattr(prim,"triangles"): if hasattr(prim,"triangles"):
tset = prim.triangles() tset = prim.triangles()
@ -134,9 +134,9 @@ def read(filename):
v = [x * unit for x in v] v = [x * unit for x in v]
face.append([v[0],v[1],v[2]]) face.append([v[0],v[1],v[2]])
meshdata.append(face) meshdata.append(face)
#print meshdata #print(meshdata)
newmesh = Mesh.Mesh(meshdata) newmesh = Mesh.Mesh(meshdata)
#print newmesh #print(newmesh)
obj = FreeCAD.ActiveDocument.addObject("Mesh::Feature","Mesh") obj = FreeCAD.ActiveDocument.addObject("Mesh::Feature","Mesh")
obj.Mesh = newmesh obj.Mesh = newmesh
@ -161,10 +161,10 @@ def export(exportList,filename,tessellation=1):
findex = [] findex = []
m = None m = None
if obj.isDerivedFrom("Part::Feature"): if obj.isDerivedFrom("Part::Feature"):
print "exporting object ",obj.Name, obj.Shape print("exporting object ",obj.Name, obj.Shape)
m = Mesh.Mesh(triangulate(obj.Shape)) m = Mesh.Mesh(triangulate(obj.Shape))
elif obj.isDerivedFrom("Mesh::Feature"): elif obj.isDerivedFrom("Mesh::Feature"):
print "exporting object ",obj.Name, obj.Mesh print("exporting object ",obj.Name, obj.Mesh)
m = obj.Mesh m = obj.Mesh
if m: if m:
# vertex indices # vertex indices
@ -178,7 +178,7 @@ def export(exportList,filename,tessellation=1):
for i in range(len(m.Topology[1])): for i in range(len(m.Topology[1])):
f = m.Topology[1][i] f = m.Topology[1][i]
findex.extend([f[0],i,f[1],i,f[2],i]) findex.extend([f[0],i,f[1],i,f[2],i])
print len(vindex), " vert indices, ", len(nindex), " norm indices, ", len(findex), " face indices." print(len(vindex), " vert indices, ", len(nindex), " norm indices, ", len(findex), " face indices.")
vert_src = collada.source.FloatSource("cubeverts-array"+str(objind), numpy.array(vindex), ('X', 'Y', 'Z')) vert_src = collada.source.FloatSource("cubeverts-array"+str(objind), numpy.array(vindex), ('X', 'Y', 'Z'))
normal_src = collada.source.FloatSource("cubenormals-array"+str(objind), numpy.array(nindex), ('X', 'Y', 'Z')) normal_src = collada.source.FloatSource("cubenormals-array"+str(objind), numpy.array(nindex), ('X', 'Y', 'Z'))
geom = collada.geometry.Geometry(colmesh, "geometry"+str(objind), obj.Name, [vert_src, normal_src]) geom = collada.geometry.Geometry(colmesh, "geometry"+str(objind), obj.Name, [vert_src, normal_src])

View File

@ -35,7 +35,7 @@ import os,time,tempfile,uuid,FreeCAD,Part,Draft,Arch,math,DraftVecUtils
DEBUG = False DEBUG = False
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pyopen = open # because we'll redefine open below pyopen = open # because we'll redefine open below
# which IFC type must create which FreeCAD type # which IFC type must create which FreeCAD type
@ -188,7 +188,7 @@ def explore(filename=None):
filename = decode(filename,utf=True) filename = decode(filename,utf=True)
if not os.path.exists(filename): if not os.path.exists(filename):
print "File not found" print("File not found")
return return
ifc = ifcopenshell.open(filename) ifc = ifcopenshell.open(filename)
@ -265,7 +265,7 @@ def explore(filename=None):
try: try:
argvalue = getattr(entity,argname) argvalue = getattr(entity,argname)
except: except:
print "Error in entity ",entity print("Error in entity ", entity)
break break
else: else:
if not argname in ["Id", "GlobalId"]: if not argname in ["Id", "GlobalId"]:
@ -344,19 +344,22 @@ def insert(filename,docname,skip=[],only=[],root=None):
FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n") FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
return return
if DEBUG: print "Opening ",filename,"...", if DEBUG: print("Opening ",filename,"...",)
try: try:
doc = FreeCAD.getDocument(docname) doc = FreeCAD.getDocument(docname)
except: except:
doc = FreeCAD.newDocument(docname) doc = FreeCAD.newDocument(docname)
FreeCAD.ActiveDocument = doc FreeCAD.ActiveDocument = doc
if DEBUG: print "done." if DEBUG: print("done.")
global ROOT_ELEMENT global ROOT_ELEMENT
if root: if root:
ROOT_ELEMENT = root ROOT_ELEMENT = root
if DEBUG: print ("done.")
#global ifcfile # keeping global for debugging purposes #global ifcfile # keeping global for debugging purposes
filename = decode(filename,utf=True) filename = decode(filename,utf=True)
ifcfile = ifcopenshell.open(filename) ifcfile = ifcopenshell.open(filename)
@ -377,7 +380,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
annotations = ifcfile.by_type("IfcAnnotation") annotations = ifcfile.by_type("IfcAnnotation")
materials = ifcfile.by_type("IfcMaterial") materials = ifcfile.by_type("IfcMaterial")
if DEBUG: print "Building relationships tables...", if DEBUG: print("Building relationships table...",)
# building relations tables # building relations tables
objects = {} # { id:object, ... } objects = {} # { id:object, ... }
@ -459,13 +462,13 @@ def insert(filename,docname,skip=[],only=[],root=None):
only.extend(additions[currentid]) only.extend(additions[currentid])
products = [ifcfile[currentid] for currentid in ids] products = [ifcfile[currentid] for currentid in ids]
if DEBUG: print "done." if DEBUG: print("done.")
count = 0 count = 0
from FreeCAD import Base from FreeCAD import Base
progressbar = Base.ProgressIndicator() progressbar = Base.ProgressIndicator()
progressbar.start("Importing IFC objects...",len(products)) progressbar.start("Importing IFC objects...",len(products))
if DEBUG: print "Processing objects..." if DEBUG: print("Processing objects...")
# products # products
for product in products: for product in products:
@ -473,7 +476,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
pid = product.id() pid = product.id()
guid = product.GlobalId guid = product.GlobalId
ptype = product.is_a() ptype = product.is_a()
if DEBUG: print count+1,"/",len(products)," creating object #",pid," : ",ptype, if DEBUG: print(count+1,"/",len(products)," creating object #",pid," : ",ptype,)
name = str(ptype[3:]) name = str(ptype[3:])
if product.Name: if product.Name:
name = product.Name.encode("utf8") name = product.Name.encode("utf8")
@ -488,20 +491,20 @@ def insert(filename,docname,skip=[],only=[],root=None):
if ptype in structuralifcobjects: if ptype in structuralifcobjects:
archobj = False archobj = False
structobj = True structobj = True
if DEBUG: print " (struct)", if DEBUG: print(" (struct)",)
else: else:
if DEBUG: print " (arch)", if DEBUG: print(" (arch)",)
if MERGE_MODE_ARCH == 4 and archobj: if MERGE_MODE_ARCH == 4 and archobj:
if DEBUG: print " skipped." if DEBUG: print(" skipped.")
continue continue
if MERGE_MODE_STRUCT == 3 and not archobj: if MERGE_MODE_STRUCT == 3 and not archobj:
if DEBUG: print " skipped." if DEBUG: print(" skipped.")
continue continue
if pid in skip: # user given id skip list if pid in skip: # user given id skip list
if DEBUG: print " skipped." if DEBUG: print(" skipped.")
continue continue
if ptype in SKIP: # preferences-set type skip list if ptype in SKIP: # preferences-set type skip list
if DEBUG: print " skipped." if DEBUG: print(" skipped.")
continue continue
# detect if this object is sharing its shape # detect if this object is sharing its shape
@ -511,8 +514,9 @@ def insert(filename,docname,skip=[],only=[],root=None):
try: try:
prepr = product.Representation prepr = product.Representation
except: except:
if DEBUG: print " ERROR unable to get object representation", if DEBUG: print(" ERROR unable to get object representation",)
if prepr and (MERGE_MODE_ARCH == 0) and archobj and CREATE_CLONES: if prepr and (MERGE_MODE_ARCH == 0) and archobj and CREATE_CLONES:
for s in prepr.Representations: for s in prepr.Representations:
if s.RepresentationIdentifier.upper() == "BODY": if s.RepresentationIdentifier.upper() == "BODY":
if s.Items[0].is_a("IfcMappedItem"): if s.Items[0].is_a("IfcMappedItem"):
@ -534,7 +538,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
pass # IfcOpenShell will yield an error if a given product has no shape, but we don't care pass # IfcOpenShell will yield an error if a given product has no shape, but we don't care
if brep: if brep:
if DEBUG: print " ",str(len(brep)/1000),"k ", if DEBUG: print(" ",str(len(brep)/1000),"k ",)
shape = Part.Shape() shape = Part.Shape()
shape.importBrepFromString(brep) shape.importBrepFromString(brep)
@ -544,23 +548,23 @@ def insert(filename,docname,skip=[],only=[],root=None):
if not shape.isNull(): if not shape.isNull():
if (MERGE_MODE_ARCH > 0 and archobj) or structobj: if (MERGE_MODE_ARCH > 0 and archobj) or structobj:
if ptype == "IfcSpace": # do not add spaces to compounds if ptype == "IfcSpace": # do not add spaces to compounds
if DEBUG: print "skipping space ",pid if DEBUG: print("skipping space ",pid)
elif structobj: elif structobj:
structshapes[pid] = shape structshapes[pid] = shape
if DEBUG: print shape.Solids," ", if DEBUG: print(shape.Solids," ",)
baseobj = shape baseobj = shape
else: else:
shapes[pid] = shape shapes[pid] = shape
if DEBUG: print shape.Solids," ", if DEBUG: print(shape.Solids," ",)
baseobj = shape baseobj = shape
else: else:
if clone: if clone:
if DEBUG: print "clone ", if DEBUG: print("clone ",)
else: else:
if GET_EXTRUSIONS: if GET_EXTRUSIONS:
ex = Arch.getExtrusionData(shape) ex = Arch.getExtrusionData(shape)
if ex: if ex:
print "extrusion ", print("extrusion ",)
baseface = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_footprint") baseface = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_footprint")
# bug in ifcopenshell? Some faces of a shell may have non-null placement # bug in ifcopenshell? Some faces of a shell may have non-null placement
# workaround to remove the bad placement: exporting/reimporting as step # workaround to remove the bad placement: exporting/reimporting as step
@ -583,13 +587,13 @@ def insert(filename,docname,skip=[],only=[],root=None):
baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body") baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body")
baseobj.Shape = shape baseobj.Shape = shape
else: else:
if DEBUG: print "null shape ", if DEBUG: print("null shape ",)
if not shape.isValid(): if not shape.isValid():
if DEBUG: print "invalid shape ", if DEBUG: print("invalid shape ",)
#continue #continue
else: else:
if DEBUG: print " no brep ", if DEBUG: print(" no brep ",)
if MERGE_MODE_ARCH == 0 and archobj: if MERGE_MODE_ARCH == 0 and archobj:
@ -652,7 +656,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
obj = Arch.makeComponent(baseobj,name=name) obj = Arch.makeComponent(baseobj,name=name)
if obj: if obj:
sols = str(obj.Shape.Solids) if hasattr(obj,"Shape") else "" sols = str(obj.Shape.Solids) if hasattr(obj,"Shape") else ""
if DEBUG: print sols if DEBUG: print(sols)
objects[pid] = obj objects[pid] = obj
elif (MERGE_MODE_ARCH == 1 and archobj) or (MERGE_MODE_STRUCT == 0 and not archobj): elif (MERGE_MODE_ARCH == 1 and archobj) or (MERGE_MODE_STRUCT == 0 and not archobj):
@ -722,7 +726,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
# color # color
if FreeCAD.GuiUp and (pid in colors) and hasattr(obj.ViewObject,"ShapeColor"): if FreeCAD.GuiUp and (pid in colors) and hasattr(obj.ViewObject,"ShapeColor"):
#if DEBUG: print " setting color: ",int(colors[pid][0]*255),"/",int(colors[pid][1]*255),"/",int(colors[pid][2]*255) #if DEBUG: print(" setting color: ",int(colors[pid][0]*255),"/",int(colors[pid][1]*255),"/",int(colors[pid][2]*255))
obj.ViewObject.ShapeColor = colors[pid] obj.ViewObject.ShapeColor = colors[pid]
# if DEBUG is on, recompute after each shape # if DEBUG is on, recompute after each shape
@ -743,7 +747,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
if MERGE_MODE_STRUCT == 2: if MERGE_MODE_STRUCT == 2:
if DEBUG: print "Joining Structural shapes...", if DEBUG: print("Joining Structural shapes...")
for host,children in groups.items(): # Structural for host,children in groups.items(): # Structural
if ifcfile[host].is_a("IfcStructuralAnalysisModel"): if ifcfile[host].is_a("IfcStructuralAnalysisModel"):
@ -762,16 +766,16 @@ def insert(filename,docname,skip=[],only=[],root=None):
obj = FreeCAD.ActiveDocument.addObject("Part::Feature","UnclaimedStruct") obj = FreeCAD.ActiveDocument.addObject("Part::Feature","UnclaimedStruct")
obj.Shape = Part.makeCompound(structshapes.values()) obj.Shape = Part.makeCompound(structshapes.values())
if DEBUG: print "done" if DEBUG: print("done")
else: else:
if DEBUG: print "Processing Struct relationships...", if DEBUG: print("Processing Struct relationships...")
# groups # groups
for host,children in groups.items(): for host,children in groups.items():
if ifcfile[host].is_a("IfcStructuralAnalysisModel"): if ifcfile[host].is_a("IfcStructuralAnalysisModel"):
# print host, ' --> ', children # print(host, ' --> ', children)
obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup","AnalysisModel") obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup","AnalysisModel")
objects[host] = obj objects[host] = obj
if host in objects.keys(): if host in objects.keys():
@ -784,7 +788,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
for c in childs_to_delete: for c in childs_to_delete:
children.remove(c) # to not process the child again in remaining groups children.remove(c) # to not process the child again in remaining groups
if cobs: if cobs:
if DEBUG: print "adding ",len(cobs), " object(s) to ", objects[host].Label if DEBUG: print("adding ",len(cobs), " object(s) to ", objects[host].Label)
Arch.addComponents(cobs,objects[host]) Arch.addComponents(cobs,objects[host])
if DEBUG: FreeCAD.ActiveDocument.recompute() if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -813,11 +817,11 @@ def insert(filename,docname,skip=[],only=[],root=None):
if child in objects.keys(): if child in objects.keys():
grp.addObject(objects[child]) grp.addObject(objects[child])
else: else:
if DEBUG: print "unable to add object: #", child, " to group: #", ifcfile[host].id(), ", ", grp_name if DEBUG: print("unable to add object: #", child, " to group: #", ifcfile[host].id(), ", ", grp_name)
if MERGE_MODE_ARCH == 3: if MERGE_MODE_ARCH == 3:
if DEBUG: print "Joining Arch shapes...", if DEBUG: print("Joining Arch shapes...")
for host,children in additions.items(): # Arch for host,children in additions.items(): # Arch
if ifcfile[host].is_a("IfcBuildingStorey"): if ifcfile[host].is_a("IfcBuildingStorey"):
@ -845,13 +849,13 @@ def insert(filename,docname,skip=[],only=[],root=None):
else: else:
if DEBUG: print "Processing Arch relationships..." if DEBUG: print("Processing Arch relationships...")
# subtractions # subtractions
if SEPARATE_OPENINGS: if SEPARATE_OPENINGS:
for subtraction in subtractions: for subtraction in subtractions:
if (subtraction[0] in objects.keys()) and (subtraction[1] in objects.keys()): if (subtraction[0] in objects.keys()) and (subtraction[1] in objects.keys()):
if DEBUG: print "subtracting ",objects[subtraction[0]].Label, " from ", objects[subtraction[1]].Label if DEBUG: print("subtracting ",objects[subtraction[0]].Label, " from ", objects[subtraction[1]].Label)
Arch.removeComponents(objects[subtraction[0]],objects[subtraction[1]]) Arch.removeComponents(objects[subtraction[0]],objects[subtraction[1]])
if DEBUG: FreeCAD.ActiveDocument.recompute() if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -862,9 +866,9 @@ def insert(filename,docname,skip=[],only=[],root=None):
if cobs: if cobs:
if DEBUG and (len(cobs) > 10) and ( not(Draft.getType(objects[host]) in ["Site","Building","Floor"])): if DEBUG and (len(cobs) > 10) and ( not(Draft.getType(objects[host]) in ["Site","Building","Floor"])):
# avoid huge fusions # avoid huge fusions
print "more than 10 shapes to add: skipping." print("more than 10 shapes to add: skipping.")
else: else:
if DEBUG: print "adding ",len(cobs), " object(s) to ", objects[host].Label if DEBUG: print("adding ",len(cobs), " object(s) to ", objects[host].Label)
Arch.addComponents(cobs,objects[host]) Arch.addComponents(cobs,objects[host])
if DEBUG: FreeCAD.ActiveDocument.recompute() if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -880,7 +884,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
# 2D elements # 2D elements
if DEBUG and annotations: print "Creating 2D geometry..." if DEBUG and annotations:print("Creating 2D geometry...")
scaling = getScaling(ifcfile) scaling = getScaling(ifcfile)
#print "scaling factor =",scaling #print "scaling factor =",scaling
@ -901,7 +905,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
if shapes2d: if shapes2d:
sh = Part.makeCompound(shapes2d) sh = Part.makeCompound(shapes2d)
pc = str(int((float(count)/(len(products)+len(annotations))*100)))+"% " pc = str(int((float(count)/(len(products)+len(annotations))*100)))+"% "
if DEBUG: print pc,"creating object ",aid," : Annotation with shape: ",sh if DEBUG: print(pc,"creating object ",aid," : Annotation with shape: ",sh)
o = FreeCAD.ActiveDocument.addObject("Part::Feature",name) o = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
o.Shape = sh o.Shape = sh
p = getPlacement(annotation.ObjectPlacement,scaling) p = getPlacement(annotation.ObjectPlacement,scaling)
@ -914,7 +918,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
# Materials # Materials
if DEBUG and materials: print "Creating materials...", if DEBUG and materials: print("Creating materials...")
#print "mattable:",mattable #print "mattable:",mattable
#print "materials:",materials #print "materials:",materials
fcmats = {} fcmats = {}
@ -950,7 +954,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
if FreeCAD.GuiUp: if FreeCAD.GuiUp:
import FreeCADGui import FreeCADGui
FreeCADGui.SendMsgToActiveView("ViewFit") FreeCADGui.SendMsgToActiveView("ViewFit")
print "Finished importing." print("Finished importing.")
return doc return doc
@ -1026,8 +1030,8 @@ def export(exportList,filename):
if b: if b:
clones.setdefault(b.Name,[]).append(o.Name) clones.setdefault(b.Name,[]).append(o.Name)
#print "clones table: ",clones #print("clones table: ",clones)
#print objectslist #print(objectslist)
# testing if more than one site selected (forbidden in IFC) # testing if more than one site selected (forbidden in IFC)
if len(Draft.getObjectsOfType(objectslist,"Site")) > 1: if len(Draft.getObjectsOfType(objectslist,"Site")) > 1:
@ -1081,7 +1085,7 @@ def export(exportList,filename):
# getting the representation # getting the representation
representation,placement,shapetype = getRepresentation(ifcfile,context,obj,forcebrep=(brepflag or FORCE_BREP)) representation,placement,shapetype = getRepresentation(ifcfile,context,obj,forcebrep=(brepflag or FORCE_BREP))
if DEBUG: print str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name if DEBUG: print(str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name)
# setting the arguments # setting the arguments
args = [uid,history,name,description,None,placement,representation,None] args = [uid,history,name,description,None,placement,representation,None]
@ -1113,7 +1117,7 @@ def export(exportList,filename):
if hasattr(obj,"Additions") and (shapetype == "extrusion"): if hasattr(obj,"Additions") and (shapetype == "extrusion"):
for o in obj.Additions: for o in obj.Additions:
r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True) r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True)
if DEBUG: print " adding ",c2," : ",o.Label if DEBUG: print(" adding ",c2," : ",o.Label)
prod2 = ifcfile.createIfcBuildingElementProxy(ifcopenshell.guid.compress(uuid.uuid1().hex),history,o.Label.encode("utf8"),None,None,p2,r2,None,"ELEMENT") prod2 = ifcfile.createIfcBuildingElementProxy(ifcopenshell.guid.compress(uuid.uuid1().hex),history,o.Label.encode("utf8"),None,None,p2,r2,None,"ELEMENT")
ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Addition','',product,[prod2]) ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Addition','',product,[prod2])
@ -1121,7 +1125,7 @@ def export(exportList,filename):
if hasattr(obj,"Subtractions") and (shapetype == "extrusion"): if hasattr(obj,"Subtractions") and (shapetype == "extrusion"):
for o in obj.Subtractions: for o in obj.Subtractions:
r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True,subtraction=True) r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True,subtraction=True)
if DEBUG: print " subtracting ",c2," : ",o.Label if DEBUG: print(" subtracting ",c2," : ",o.Label)
prod2 = ifcfile.createIfcOpeningElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,o.Label.encode("utf8"),None,None,p2,r2,None) prod2 = ifcfile.createIfcOpeningElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,o.Label.encode("utf8"),None,None,p2,r2,None)
ifcfile.createIfcRelVoidsElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Subtraction','',product,prod2) ifcfile.createIfcRelVoidsElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Subtraction','',product,prod2)
@ -1198,7 +1202,7 @@ def export(exportList,filename):
val = "(".join(r[1:]) val = "(".join(r[1:])
val = val.strip("'") val = val.strip("'")
val = val.strip('"') val = val.strip('"')
if DEBUG: print " property ",key," : ",val.encode("utf8"), " (", str(tp), ")" if DEBUG: print(" property ",key," : ",val.encode("utf8"), " (", str(tp), ")")
if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']: if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
val = val.encode("utf8") val = val.encode("utf8")
elif tp == "IfcBoolean": elif tp == "IfcBoolean":
@ -1273,11 +1277,11 @@ def export(exportList,filename):
treated.append(c.Name) treated.append(c.Name)
sites.append(products[site.Name]) sites.append(products[site.Name])
if not sites: if not sites:
if DEBUG: print "No site found. Adding default site" if DEBUG: print ("No site found. Adding default site")
sites = [ifcfile.createIfcSite(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Site",'',None,None,None,None,"ELEMENT",None,None,None,None,None)] sites = [ifcfile.createIfcSite(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Site",'',None,None,None,None,"ELEMENT",None,None,None,None,None)]
ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'ProjectLink','',project,sites) ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'ProjectLink','',project,sites)
if not buildings: if not buildings:
if DEBUG: print "No building found. Adding default building" if DEBUG: print ("No building found. Adding default building")
buildings = [ifcfile.createIfcBuilding(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Building",'',None,None,None,None,"ELEMENT",None,None,None)] buildings = [ifcfile.createIfcBuilding(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Building",'',None,None,None,None,"ELEMENT",None,None,None)]
ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',sites[0],buildings) ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',sites[0],buildings)
untreated = [] untreated = []
@ -1396,7 +1400,7 @@ def export(exportList,filename):
rep = ifcfile.createIfcProductDefinitionShape(None,None,[shp]) rep = ifcfile.createIfcProductDefinitionShape(None,None,[shp])
ann = ifcfile.createIfcAnnotation(ifcopenshell.guid.compress(uuid.uuid1().hex),history,anno.Label.encode('utf8'),'',None,gpl,rep) ann = ifcfile.createIfcAnnotation(ifcopenshell.guid.compress(uuid.uuid1().hex),history,anno.Label.encode('utf8'),'',None,gpl,rep)
if DEBUG: print "writing ",filename,"..." if DEBUG: print("writing ",filename,"...")
filename = decode(filename) filename = decode(filename)

View File

@ -56,7 +56,7 @@ supportedIfcTypes = ["IfcSite", "IfcBuilding", "IfcBuildingStorey", "IfcBeam", "
"IfcPile", "IfcFooting", "IfcReinforcingBar", "IfcTendon"] "IfcPile", "IfcFooting", "IfcReinforcingBar", "IfcTendon"]
# TODO : shading device not supported? # TODO : shading device not supported?
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pyopen = open # because we'll redefine open below pyopen = open # because we'll redefine open below
def open(filename,skip=None): def open(filename,skip=None):
@ -157,7 +157,7 @@ def read(filename,skip=None):
IfcImport.Settings(IfcImport.USE_BREP_DATA,True) IfcImport.Settings(IfcImport.USE_BREP_DATA,True)
useShapes = True useShapes = True
else: else:
if DEBUG: print "Warning: IfcOpenShell version very old, unable to handle Brep data" if DEBUG: print("Warning: IfcOpenShell version very old, unable to handle Brep data")
# opening file # opening file
if IFCOPENSHELL5: if IFCOPENSHELL5:
@ -167,12 +167,12 @@ def read(filename,skip=None):
num_lines = len(objects) num_lines = len(objects)
relations = ifc.by_type("IfcRelAggregates") + ifc.by_type("IfcRelContainedInSpatialStructure") + ifc.by_type("IfcRelVoidsElement") relations = ifc.by_type("IfcRelAggregates") + ifc.by_type("IfcRelContainedInSpatialStructure") + ifc.by_type("IfcRelVoidsElement")
if not objects: if not objects:
print "Error opening IFC file" print("Error opening IFC file")
return return
else: else:
num_lines = sum(1 for line in pyopen(filename)) num_lines = sum(1 for line in pyopen(filename))
if not IfcImport.Init(filename): if not IfcImport.Init(filename):
print "Error opening IFC file" print("Error opening IFC file")
return return
# processing geometry # processing geometry
@ -208,24 +208,24 @@ def read(filename,skip=None):
objname = obj.name objname = obj.name
objtype = obj.type objtype = obj.type
objparentid.append(obj.parent_id) objparentid.append(obj.parent_id)
if DEBUG: print "["+str(int((float(idx)/num_lines)*100))+"%] parsing ",objid,": ",objname," of type ",objtype if DEBUG: print("["+str(int((float(idx)/num_lines)*100))+"%] parsing ",objid,": ",objname," of type ",objtype)
# retrieving name # retrieving name
n = getCleanName(objname,objid,objtype) n = getCleanName(objname,objid,objtype)
# skip IDs # skip IDs
if objid in skipIds: if objid in skipIds:
if DEBUG: print " skipping because object ID is in skip list" if DEBUG: print(" skipping because object ID is in skip list")
nobj = None nobj = None
# skip types # skip types
elif objtype in SKIP: elif objtype in SKIP:
if DEBUG: print " skipping because type is in skip list" if DEBUG: print(" skipping because type is in skip list")
nobj = None nobj = None
# check if object was already processed, to workaround an ifcopenshell bug # check if object was already processed, to workaround an ifcopenshell bug
elif objid in processedIds: elif objid in processedIds:
if DEBUG: print " skipping because this object was already processed" if DEBUG: print(" skipping because this object was already processed")
else: else:
# build shape # build shape
@ -274,14 +274,14 @@ def read(filename,skip=None):
elif shape: elif shape:
# treat as dumb parts # treat as dumb parts
if DEBUG: print "Fixme: Shape-containing object not handled: ",objid, " ", objtype if DEBUG: print("Fixme: Shape-containing object not handled: ",objid, " ", objtype)
nobj = FreeCAD.ActiveDocument.addObject("Part::Feature",n) nobj = FreeCAD.ActiveDocument.addObject("Part::Feature",n)
nobj.Label = n nobj.Label = n
nobj.Shape = shape nobj.Shape = shape
else: else:
# treat as meshes # treat as meshes
if DEBUG: print "Warning: Object without shape: ",objid, " ", objtype if DEBUG: print("Warning: Object without shape: ",objid, " ", objtype)
if hasattr(obj,"mesh"): if hasattr(obj,"mesh"):
if not hasattr(obj.mesh, 'verts'): if not hasattr(obj.mesh, 'verts'):
obj = IfcImport.Get() # Get triangulated rep of same product obj = IfcImport.Get() # Get triangulated rep of same product
@ -291,7 +291,7 @@ def read(filename,skip=None):
nobj.Mesh = me nobj.Mesh = me
nobj.Placement = pl nobj.Placement = pl
else: else:
if DEBUG: print "Error: Skipping object without mesh: ",objid, " ", objtype if DEBUG: print("Error: Skipping object without mesh: ",objid, " ", objtype)
# registering object number and parent # registering object number and parent
if objparentid: if objparentid:
@ -312,7 +312,7 @@ def read(filename,skip=None):
# processing non-geometry and relationships # processing non-geometry and relationships
parents_temp = dict(ifcParents) parents_temp = dict(ifcParents)
import ArchCommands import ArchCommands
#print parents_temp #print(parents_temp)
while parents_temp: while parents_temp:
id, comps = parents_temp.popitem() id, comps = parents_temp.popitem()
@ -345,7 +345,7 @@ def read(filename,skip=None):
parentid = obj.id parentid = obj.id
parentname = obj.name parentname = obj.name
parenttype = obj.type parenttype = obj.type
#if DEBUG: print "["+str(int((float(idx)/num_lines)*100))+"%] parsing ",parentid,": ",parentname," of type ",parenttype #if DEBUG: print("["+str(int((float(idx)/num_lines)*100))+"%] parsing ",parentid,": ",parentname," of type ",parenttype)
n = getCleanName(parentname,parentid,parenttype) n = getCleanName(parentname,parentid,parenttype)
if parentid <= 0: if parentid <= 0:
parent = None parent = None
@ -364,7 +364,7 @@ def read(filename,skip=None):
elif parenttype == "IfcProject": elif parenttype == "IfcProject":
parent = None parent = None
else: else:
if DEBUG: print "Fixme: skipping unhandled parent: ", parentid, " ", parenttype if DEBUG: print("Fixme: skipping unhandled parent: ", parentid, " ", parenttype)
parent = None parent = None
# registering object number and parent # registering object number and parent
if not IFCOPENSHELL5: if not IFCOPENSHELL5:
@ -378,10 +378,10 @@ def read(filename,skip=None):
if parent and (id in ifcObjects): if parent and (id in ifcObjects):
if ifcObjects[id] and (ifcObjects[id].Name != parent.Name): if ifcObjects[id] and (ifcObjects[id].Name != parent.Name):
if additive: if additive:
if DEBUG: print "adding ",ifcObjects[id].Name, " to ",parent.Name if DEBUG: print("adding ",ifcObjects[id].Name, " to ",parent.Name)
ArchCommands.addComponents(ifcObjects[id],parent) ArchCommands.addComponents(ifcObjects[id],parent)
else: else:
if DEBUG: print "removing ",ifcObjects[id].Name, " from ",parent.Name if DEBUG: print("removing ",ifcObjects[id].Name, " from ",parent.Name)
ArchCommands.removeComponents(ifcObjects[id],parent) ArchCommands.removeComponents(ifcObjects[id],parent)
if not IFCOPENSHELL5: if not IFCOPENSHELL5:
IfcImport.CleanUp() IfcImport.CleanUp()
@ -392,13 +392,13 @@ def read(filename,skip=None):
FreeCAD.Console.PrintWarning(translate("Arch","IfcOpenShell not found or disabled, falling back on internal parser.\n")) FreeCAD.Console.PrintWarning(translate("Arch","IfcOpenShell not found or disabled, falling back on internal parser.\n"))
schema=getSchema() schema=getSchema()
if schema: if schema:
if DEBUG: print "opening",filename,"..." if DEBUG: print("opening",filename,"...")
ifc = IfcDocument(filename,schema=schema) ifc = IfcDocument(filename,schema=schema)
else: else:
FreeCAD.Console.PrintWarning(translate("Arch","IFC Schema not found, IFC import disabled.\n")) FreeCAD.Console.PrintWarning(translate("Arch","IFC Schema not found, IFC import disabled.\n"))
return None return None
t2 = time.time() t2 = time.time()
if DEBUG: print "Successfully loaded",ifc,"in %s s" % ((t2-t1)) if DEBUG: print("Successfully loaded",ifc,"in %s s" % ((t2-t1)))
# getting walls # getting walls
for w in ifc.getEnt("IfcWallStandardCase"): for w in ifc.getEnt("IfcWallStandardCase"):
@ -425,17 +425,17 @@ def read(filename,skip=None):
for s in ifc.getEnt("IfcSite"): for s in ifc.getEnt("IfcSite"):
group(s,ifc,"Site") group(s,ifc,"Site")
if DEBUG: print "done parsing. Recomputing..." if DEBUG: print("done parsing. Recomputing...")
FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.recompute()
t3 = time.time() t3 = time.time()
if DEBUG: print "done processing IFC file in %s s" % ((t3-t1)) if DEBUG: print("done processing IFC file in %s s" % ((t3-t1)))
return None return None
def getCleanName(name,ifcid,ifctype): def getCleanName(name,ifcid,ifctype):
"Get a clean name from an ifc object" "Get a clean name from an ifc object"
#print "getCleanName called",name,ifcid,ifctype #print("getCleanName called",name,ifcid,ifctype)
n = name n = name
if not n: if not n:
n = ifctype n = ifctype
@ -459,24 +459,24 @@ def makeWall(entity,shape=None,name="Wall"):
body.Mesh = shape body.Mesh = shape
wall = Arch.makeWall(body,name=name) wall = Arch.makeWall(body,name=name)
wall.Label = name wall.Label = name
if DEBUG: print " made wall object ",entity,":",wall if DEBUG: print(" made wall object ",entity,":",wall)
return wall return wall
# use internal parser # use internal parser
if DEBUG: print "=====> making wall",entity.id if DEBUG: print("=====> making wall",entity.id)
placement = wall = wire = body = width = height = None placement = wall = wire = body = width = height = None
placement = getPlacement(entity.ObjectPlacement) placement = getPlacement(entity.ObjectPlacement)
if DEBUG: print " got wall placement",entity.id,":",placement if DEBUG: print(" got wall placement",entity.id,":",placement)
width = entity.getProperty("Width") width = entity.getProperty("Width")
height = entity.getProperty("Height") height = entity.getProperty("Height")
if width and height: if width and height:
if DEBUG: print " got width, height ",entity.id,":",width,"/",height if DEBUG: print(" got width, height ",entity.id,":",width,"/",height)
for r in entity.Representation.Representations: for r in entity.Representation.Representations:
if r.RepresentationIdentifier == "Axis": if r.RepresentationIdentifier == "Axis":
wire = getWire(r.Items,placement) wire = getWire(r.Items,placement)
wall = Arch.makeWall(wire,width,height,align="Center",name="Wall"+str(entity.id)) wall = Arch.makeWall(wire,width,height,align="Center",name="Wall"+str(entity.id))
else: else:
if DEBUG: print " no height or width properties found..." if DEBUG: print(" no height or width properties found...")
for r in entity.Representation.Representations: for r in entity.Representation.Representations:
if r.RepresentationIdentifier == "Body": if r.RepresentationIdentifier == "Body":
for b in r.Items: for b in r.Items:
@ -487,12 +487,12 @@ def makeWall(entity,shape=None,name="Wall"):
wall = Arch.makeWall(wire,width=0,height=b.Depth,name="Wall"+str(entity.id)) wall = Arch.makeWall(wire,width=0,height=b.Depth,name="Wall"+str(entity.id))
wall.Normal = norm wall.Normal = norm
if wall: if wall:
if DEBUG: print " made wall object ",entity.id,":",wall if DEBUG: print(" made wall object ",entity.id,":",wall)
return wall return wall
if DEBUG: print " error: skipping wall",entity.id if DEBUG: print(" error: skipping wall",entity.id)
return None return None
except: except:
if DEBUG: print " error: skipping wall",entity if DEBUG: print(" error: skipping wall",entity)
return None return None
@ -505,14 +505,14 @@ def makeWindow(entity,shape=None,name="Window"):
window = Arch.makeWindow(name=name) window = Arch.makeWindow(name=name)
window.Shape = shape window.Shape = shape
window.Label = name window.Label = name
if DEBUG: print " made window object ",entity,":",window if DEBUG: print(" made window object ",entity,":",window)
return window return window
# use internal parser # use internal parser
if DEBUG: print "=====> making window",entity.id if DEBUG: print("=====> making window",entity.id)
placement = window = wire = body = width = height = None placement = window = wire = body = width = height = None
placement = getPlacement(entity.ObjectPlacement) placement = getPlacement(entity.ObjectPlacement)
if DEBUG: print "got window placement",entity.id,":",placement if DEBUG: print("got window placement",entity.id,":",placement)
width = entity.getProperty("Width") width = entity.getProperty("Width")
height = entity.getProperty("Height") height = entity.getProperty("Height")
for r in entity.Representation.Representations: for r in entity.Representation.Representations:
@ -522,12 +522,12 @@ def makeWindow(entity,shape=None,name="Window"):
wire = getWire(b.SweptArea,placement) wire = getWire(b.SweptArea,placement)
window = Arch.makeWindow(wire,width=b.Depth,name=objtype+str(entity.id)) window = Arch.makeWindow(wire,width=b.Depth,name=objtype+str(entity.id))
if window: if window:
if DEBUG: print " made window object ",entity.id,":",window if DEBUG: print(" made window object ",entity.id,":",window)
return window return window
if DEBUG: print " error: skipping window",entity.id if DEBUG: print(" error: skipping window",entity.id)
return None return None
except: except:
if DEBUG: print " error: skipping window",entity if DEBUG: print(" error: skipping window",entity)
return None return None
@ -552,14 +552,14 @@ def makeStructure(entity,shape=None,ifctype=None,name="Structure"):
structure.Role = "Slab" structure.Role = "Slab"
elif ifctype == "IfcFooting": elif ifctype == "IfcFooting":
structure.Role = "Foundation" structure.Role = "Foundation"
if DEBUG: print " made structure object ",entity,":",structure," (type: ",ifctype,")" if DEBUG: print(" made structure object ",entity,":",structure," (type: ",ifctype,")")
return structure return structure
# use internal parser # use internal parser
if DEBUG: print "=====> making struct",entity.id if DEBUG: print("=====> making struct",entity.id)
placement = structure = wire = body = width = height = None placement = structure = wire = body = width = height = None
placement = getPlacement(entity.ObjectPlacement) placement = getPlacement(entity.ObjectPlacement)
if DEBUG: print "got window placement",entity.id,":",placement if DEBUG: print("got window placement",entity.id,":",placement)
width = entity.getProperty("Width") width = entity.getProperty("Width")
height = entity.getProperty("Height") height = entity.getProperty("Height")
for r in entity.Representation.Representations: for r in entity.Representation.Representations:
@ -569,12 +569,12 @@ def makeStructure(entity,shape=None,ifctype=None,name="Structure"):
wire = getWire(b.SweptArea,placement) wire = getWire(b.SweptArea,placement)
structure = Arch.makeStructure(wire,height=b.Depth,name=objtype+str(entity.id)) structure = Arch.makeStructure(wire,height=b.Depth,name=objtype+str(entity.id))
if structure: if structure:
if DEBUG: print " made structure object ",entity.id,":",structure if DEBUG: print(" made structure object ",entity.id,":",structure)
return structure return structure
if DEBUG: print " error: skipping structure",entity.id if DEBUG: print(" error: skipping structure",entity.id)
return None return None
except: except:
if DEBUG: print " error: skipping structure",entity if DEBUG: print(" error: skipping structure",entity)
return None return None
@ -594,7 +594,7 @@ def makeSite(entity,shape=None,name="Site"):
site.Label = name site.Label = name
if body: if body:
site.Terrain = body site.Terrain = body
if DEBUG: print " made site object ",entity,":",site if DEBUG: print(" made site object ",entity,":",site)
return site return site
except: except:
return None return None
@ -611,7 +611,7 @@ def makeSpace(entity,shape=None,name="Space"):
body.Shape = shape body.Shape = shape
space.Base = body space.Base = body
body.ViewObject.hide() body.ViewObject.hide()
if DEBUG: print " made space object ",entity,":",space if DEBUG: print(" made space object ",entity,":",space)
return space return space
except: except:
return None return None
@ -626,7 +626,7 @@ def makeRoof(entity,shape=None,name="Roof"):
roof = Arch.makeRoof(name=name) roof = Arch.makeRoof(name=name)
roof.Label = name roof.Label = name
roof.Shape = shape roof.Shape = shape
if DEBUG: print " made roof object ",entity,":",roof if DEBUG: print(" made roof object ",entity,":",roof)
return roof return roof
except: except:
return None return None
@ -637,11 +637,11 @@ def getMesh(obj):
"gets mesh and placement from an IfcOpenShell object" "gets mesh and placement from an IfcOpenShell object"
if IFCOPENSHELL5: if IFCOPENSHELL5:
return None,None return None,None
print "fixme: mesh data not yet supported" # TODO implement this with OCC tessellate print("fixme: mesh data not yet supported") # TODO implement this with OCC tessellate
import Mesh import Mesh
meshdata = [] meshdata = []
print obj.mesh.faces print(obj.mesh.faces)
print obj.mesh.verts print(obj.mesh.verts)
f = obj.mesh.faces f = obj.mesh.faces
v = obj.mesh.verts v = obj.mesh.verts
for i in range(0, len(f), 3): for i in range(0, len(f), 3):
@ -650,7 +650,7 @@ def getMesh(obj):
vi = f[i+j]*3 vi = f[i+j]*3
face.append([v[vi],v[vi+1],v[vi+2]]) face.append([v[vi],v[vi+1],v[vi+2]])
meshdata.append(face) meshdata.append(face)
print meshdata print(meshdata)
me = Mesh.Mesh(meshdata) me = Mesh.Mesh(meshdata)
# get transformation matrix # get transformation matrix
m = obj.matrix m = obj.matrix
@ -663,7 +663,7 @@ def getMesh(obj):
def getShape(obj,objid): def getShape(obj,objid):
"gets a shape from an IfcOpenShell object" "gets a shape from an IfcOpenShell object"
#print "retrieving shape from obj ",objid #print("retrieving shape from obj ",objid)
import Part import Part
sh=Part.Shape() sh=Part.Shape()
brep_data = None brep_data = None
@ -684,7 +684,7 @@ def getShape(obj,objid):
else: else:
brep_data = IfcImport.create_shape(obj, ss) brep_data = IfcImport.create_shape(obj, ss)
except: except:
print "Unable to retrieve shape data" print("Unable to retrieve shape data")
else: else:
brep_data = obj.mesh.brep_data brep_data = obj.mesh.brep_data
if brep_data: if brep_data:
@ -701,7 +701,7 @@ def getShape(obj,objid):
else: else:
sh.importBrepFromString(brep_data) sh.importBrepFromString(brep_data)
except: except:
print " error: malformed shape" print(" error: malformed shape")
return None return None
else: else:
if IFCOPENSHELL5 and SEPARATE_PLACEMENTS: if IFCOPENSHELL5 and SEPARATE_PLACEMENTS:
@ -712,16 +712,16 @@ def getShape(obj,objid):
# try to extract a solid shape # try to extract a solid shape
if sh.Faces: if sh.Faces:
try: try:
if DEBUG: print " malformed solid. Attempting to fix..." if DEBUG: print(" malformed solid. Attempting to fix...")
shell = Part.makeShell(sh.Faces) shell = Part.makeShell(sh.Faces)
if shell: if shell:
solid = Part.makeSolid(shell) solid = Part.makeSolid(shell)
if solid: if solid:
sh = solid sh = solid
except: except:
if DEBUG: print " failed to retrieve solid from object ",objid if DEBUG: print(" failed to retrieve solid from object ",objid)
else: else:
if DEBUG: print " object ", objid, " doesn't contain any geometry" if DEBUG: print(" object ", objid, " doesn't contain any geometry")
if not IFCOPENSHELL5: if not IFCOPENSHELL5:
m = obj.matrix m = obj.matrix
mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9],
@ -729,9 +729,9 @@ def getShape(obj,objid):
m[2], m[5], m[8], m[11], m[2], m[5], m[8], m[11],
0, 0, 0, 1) 0, 0, 0, 1)
sh.Placement = FreeCAD.Placement(mat) sh.Placement = FreeCAD.Placement(mat)
# if DEBUG: print "getting Shape from ",obj # if DEBUG: print("getting Shape from ",obj)
#print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull() #print("getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull())
#for v in sh.Vertexes: print v.Point #for v in sh.Vertexes: print(v.Point)
if sh: if sh:
if not sh.isNull(): if not sh.isNull():
return sh return sh
@ -741,7 +741,7 @@ def getPlacement(entity):
"returns a placement from the given entity" "returns a placement from the given entity"
if not entity: if not entity:
return None return None
if DEBUG: print " getting placement ",entity if DEBUG: print(" getting placement ",entity)
if IFCOPENSHELL5: if IFCOPENSHELL5:
if isinstance(entity,int): if isinstance(entity,int):
entity = ifc.by_id(entity) entity = ifc.by_id(entity)
@ -772,7 +772,7 @@ def getPlacement(entity):
loc = getVector(entity) loc = getVector(entity)
pl = FreeCAD.Placement() pl = FreeCAD.Placement()
pl.move(loc) pl.move(loc)
if DEBUG: print " made placement for ",entityid,":",pl if DEBUG: print(" made placement for ",entityid,":",pl)
return pl return pl
def getAttr(entity,attr): def getAttr(entity,attr):
@ -789,7 +789,7 @@ def getVector(entity):
"returns a vector from the given entity" "returns a vector from the given entity"
if not entity: if not entity:
return None return None
if DEBUG: print " getting point from ",entity if DEBUG: print(" getting point from ",entity)
if IFCOPENSHELL5: if IFCOPENSHELL5:
if isinstance(entity,int): if isinstance(entity,int):
entity = ifc.by_id(entity) entity = ifc.by_id(entity)
@ -829,7 +829,7 @@ def getSchema():
custom = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetString("CustomIfcSchema","") custom = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetString("CustomIfcSchema","")
if custom: if custom:
if os.path.exists(custom): if os.path.exists(custom):
if DEBUG: print "Using custom schema: ",custom.split(os.sep)[-1] if DEBUG: print("Using custom schema: ",custom.split(os.sep)[-1])
return custom return custom
p = None p = None
p = os.path.join(FreeCAD.ConfigGet("UserAppData"),SCHEMA.split(os.sep)[-1]) p = os.path.join(FreeCAD.ConfigGet("UserAppData"),SCHEMA.split(os.sep)[-1])
@ -846,10 +846,10 @@ def group(entity,ifc,mode=None):
# only used by the internal parser # only used by the internal parser
try: try:
if DEBUG: print "=====> making group",entity.id if DEBUG: print("=====> making group",entity.id)
placement = None placement = None
placement = getPlacement(entity.ObjectPlacement) placement = getPlacement(entity.ObjectPlacement)
if DEBUG: print "got cell placement",entity.id,":",placement if DEBUG: print("got cell placement",entity.id,":",placement)
subelements = ifc.find("IFCRELCONTAINEDINSPATIALSTRUCTURE","RelatingStructure",entity) subelements = ifc.find("IFCRELCONTAINEDINSPATIALSTRUCTURE","RelatingStructure",entity)
subelements.extend(ifc.find("IFCRELAGGREGATES","RelatingObject",entity)) subelements.extend(ifc.find("IFCRELAGGREGATES","RelatingObject",entity))
elts = [] elts = []
@ -866,7 +866,7 @@ def group(entity,ifc,mode=None):
s = s.RelatedObject s = s.RelatedObject
if not isinstance(s,list): s = [s] if not isinstance(s,list): s = [s]
elts.extend(s) elts.extend(s)
print "found dependent elements: ",elts print("found dependent elements: ",elts)
groups = [['Wall',['IfcWallStandardCase'],[]], groups = [['Wall',['IfcWallStandardCase'],[]],
['Window',['IfcWindow','IfcDoor'],[]], ['Window',['IfcWindow','IfcDoor'],[]],
@ -881,11 +881,11 @@ def group(entity,ifc,mode=None):
if e.type.upper() == t.upper(): if e.type.upper() == t.upper():
if hasattr(FreeCAD.ActiveDocument,g[0]+str(e.id)): if hasattr(FreeCAD.ActiveDocument,g[0]+str(e.id)):
g[2].append(FreeCAD.ActiveDocument.getObject(g[0]+str(e.id))) g[2].append(FreeCAD.ActiveDocument.getObject(g[0]+str(e.id)))
print "groups:",groups print("groups:",groups)
comps = [] comps = []
if CREATE_IFC_GROUPS: if CREATE_IFC_GROUPS:
if DEBUG: print "creating subgroups" if DEBUG:wprint("creating subgroups")
for g in groups: for g in groups:
if g[2]: if g[2]:
if g[0] in ['Building','Floor']: if g[0] in ['Building','Floor']:
@ -911,12 +911,12 @@ def group(entity,ifc,mode=None):
if label and cell: if label and cell:
cell.Label = label cell.Label = label
except: except:
if DEBUG: print "error: skipping group ",entity.id if DEBUG: print("error: skipping group ",entity.id)
def getWire(entity,placement=None): def getWire(entity,placement=None):
"returns a wire (created in the freecad document) from the given entity" "returns a wire (created in the freecad document) from the given entity"
# only used by the internal parser # only used by the internal parser
if DEBUG: print "making Wire from :",entity if DEBUG: print("making Wire from :",entity)
if not entity: return None if not entity: return None
if entity.type == "IFCPOLYLINE": if entity.type == "IFCPOLYLINE":
pts = [] pts = []
@ -943,16 +943,16 @@ def export(exportList,filename):
import ifc_wrapper as ifcw import ifc_wrapper as ifcw
except ImportError: except ImportError:
FreeCAD.Console.PrintError(translate("Arch","Error: IfcOpenShell is not installed\n")) FreeCAD.Console.PrintError(translate("Arch","Error: IfcOpenShell is not installed\n"))
print """importIFC: ifcOpenShell is not installed. IFC export is unavailable. print("""importIFC: ifcOpenShell is not installed. IFC export is unavailable.
Note: IFC export currently requires an experimental version of IfcOpenShell Note: IFC export currently requires an experimental version of IfcOpenShell
available from https://github.com/aothms/IfcOpenShell""" available from https://github.com/aothms/IfcOpenShell""")
return return
if (not hasattr(ifcw,"IfcFile")) and (not hasattr(ifcw,"file")): if (not hasattr(ifcw,"IfcFile")) and (not hasattr(ifcw,"file")):
FreeCAD.Console.PrintError(translate("Arch","Error: your IfcOpenShell version is too old\n")) FreeCAD.Console.PrintError(translate("Arch","Error: your IfcOpenShell version is too old\n"))
print """importIFC: The version of ifcOpenShell installed on this system doesn't print("""importIFC: The version of ifcOpenShell installed on this system doesn't
have IFC export capabilities. IFC export currently requires an experimental have IFC export capabilities. IFC export currently requires an experimental
version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell""" version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell""")
return return
import Arch,Draft import Arch,Draft
@ -994,7 +994,7 @@ def export(exportList,filename):
else: else:
others.append(obj) others.append(obj)
objectslist = buildings + floors + others objectslist = buildings + floors + others
if DEBUG: print "adding ", len(objectslist), " objects" if DEBUG: print("adding ", len(objectslist), " objects")
global unprocessed global unprocessed
unprocessed = [] unprocessed = []
@ -1032,7 +1032,7 @@ def export(exportList,filename):
if obj.IfcAttributes["FlagForceBrep"] == "True": if obj.IfcAttributes["FlagForceBrep"] == "True":
brepflag = True brepflag = True
if DEBUG: print "Adding " + obj.Label + " as Ifc" + ifctype if DEBUG: print("Adding " + obj.Label + " as Ifc" + ifctype)
# writing IFC data # writing IFC data
if obj.isDerivedFrom("App::DocumentObjectGroup"): if obj.isDerivedFrom("App::DocumentObjectGroup"):
@ -1042,7 +1042,7 @@ def export(exportList,filename):
parent = ifc.findByName("IfcBuilding",str(parent.Label)) parent = ifc.findByName("IfcBuilding",str(parent.Label))
if otype == "Site": if otype == "Site":
print " Skipping (not implemented yet)" # TODO manage sites print(" Skipping (not implemented yet)") # TODO manage sites
elif otype == "Building": elif otype == "Building":
ifc.addBuilding( name=name ) ifc.addBuilding( name=name )
elif otype == "Floor": elif otype == "Floor":
@ -1061,21 +1061,21 @@ def export(exportList,filename):
# get representation # get representation
if (not forcebrep) and (not brepflag): if (not forcebrep) and (not brepflag):
gdata = getIfcExtrusionData(obj,scaling,SEPARATE_OPENINGS) gdata = getIfcExtrusionData(obj,scaling,SEPARATE_OPENINGS)
#if DEBUG: print " extrusion data for ",obj.Label," : ",gdata #if DEBUG: print(" extrusion data for ",obj.Label," : ",gdata)
if not gdata: if not gdata:
fdata = getIfcBrepFacesData(obj,scaling) fdata = getIfcBrepFacesData(obj,scaling)
#if DEBUG: print " brep data for ",obj.Label," : ",fdata #if DEBUG: print(" brep data for ",obj.Label," : ",fdata)
if not fdata: if not fdata:
if obj.isDerivedFrom("Part::Feature"): if obj.isDerivedFrom("Part::Feature"):
print " Error retrieving the shape of object ", obj.Label print(" Error retrieving the shape of object ", obj.Label)
unprocessed.append(obj) unprocessed.append(obj)
continue continue
else: else:
if DEBUG: print " No geometry" if DEBUG: print(" No geometry")
else: else:
if DEBUG: print " Brep" if DEBUG: print(" Brep")
else: else:
if DEBUG: print " Extrusion" if DEBUG: print(" Extrusion")
if gdata: if gdata:
# gdata = [ type, profile data, extrusion data, placement data ] # gdata = [ type, profile data, extrusion data, placement data ]
placement = ifc.addPlacement(origin=gdata[3][0],xaxis=gdata[3][1],zaxis=gdata[3][2]) placement = ifc.addPlacement(origin=gdata[3][0],xaxis=gdata[3][1],zaxis=gdata[3][2])
@ -1088,7 +1088,7 @@ def export(exportList,filename):
elif gdata[0] == "composite": elif gdata[0] == "composite":
representation = ifc.addExtrudedCompositeCurve(gdata[1], gdata[2], color=color) representation = ifc.addExtrudedCompositeCurve(gdata[1], gdata[2], color=color)
else: else:
print "debug: unknow extrusion type" print("debug: unknow extrusion type")
elif fdata: elif fdata:
representation = [ifc.addFacetedBrep(f, color=color) for f in fdata] representation = [ifc.addFacetedBrep(f, color=color) for f in fdata]
@ -1110,7 +1110,7 @@ def export(exportList,filename):
elif otype == "Part": elif otype == "Part":
extra = ["ELEMENT"] extra = ["ELEMENT"]
if not ifctype in supportedIfcTypes: if not ifctype in supportedIfcTypes:
if DEBUG: print " Type ",ifctype," is not supported yet. Exporting as IfcBuildingElementProxy instead" if DEBUG: print(" Type ",ifctype," is not supported yet. Exporting as IfcBuildingElementProxy instead")
ifctype = "IfcBuildingElementProxy" ifctype = "IfcBuildingElementProxy"
extra = ["ELEMENT"] extra = ["ELEMENT"]
@ -1120,7 +1120,7 @@ def export(exportList,filename):
# removing openings # removing openings
if SEPARATE_OPENINGS and gdata: if SEPARATE_OPENINGS and gdata:
for o in obj.Subtractions: for o in obj.Subtractions:
print "Subtracting ",o.Label print("Subtracting ",o.Label)
fdata = getIfcBrepFacesData(o,scaling,sub=True) fdata = getIfcBrepFacesData(o,scaling,sub=True)
representation = [ifc.addFacetedBrep(f, color=color) for f in fdata] representation = [ifc.addFacetedBrep(f, color=color) for f in fdata]
p2 = ifc.addProduct( "IfcOpeningElement", representation, storey=product, placement=None, name=str(o.Label), description=None) p2 = ifc.addProduct( "IfcOpeningElement", representation, storey=product, placement=None, name=str(o.Label), description=None)
@ -1142,14 +1142,14 @@ def export(exportList,filename):
else: else:
unprocessed.append(obj) unprocessed.append(obj)
else: else:
if DEBUG: print "Object type ", otype, " is not supported yet." if DEBUG: print("Object type ", otype, " is not supported yet.")
# processing groups # processing groups
for name,entities in groups.iteritems(): for name,entities in groups.iteritems():
if entities: if entities:
o = FreeCAD.ActiveDocument.getObject(name) o = FreeCAD.ActiveDocument.getObject(name)
if o: if o:
if DEBUG: print "Adding group ", o.Label, " with ",len(entities)," elements" if DEBUG: print("Adding group ", o.Label, " with ",len(entities)," elements")
grp = ifc.addGroup( entities, o.Label ) grp = ifc.addGroup( entities, o.Label )
ifc.write() ifc.write()
@ -1178,10 +1178,9 @@ def export(exportList,filename):
FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.recompute()
if unprocessed: if unprocessed:
print "" print("\nWARNING: " + str(len(unprocessed)) + " objects were not exported (stored in importIFC.unprocessed):")
print "WARNING: " + str(len(unprocessed)) + " objects were not exported (stored in importIFC.unprocessed):"
for o in unprocessed: for o in unprocessed:
print " " + o.Label print(" " + o.Label)
def getTuples(data,scale=1,placement=None,normal=None,close=True): def getTuples(data,scale=1,placement=None,normal=None,close=True):
@ -1222,7 +1221,7 @@ def getTuples(data,scale=1,placement=None,normal=None,close=True):
if close: # faceloops must not be closed, but ifc profiles must. if close: # faceloops must not be closed, but ifc profiles must.
t.append(t[0]) t.append(t[0])
else: else:
print "Arch.getTuples(): Wrong profile data" print("Arch.getTuples(): Wrong profile data")
return t return t
def getIfcExtrusionData(obj,scale=1,nosubs=False): def getIfcExtrusionData(obj,scale=1,nosubs=False):
@ -1252,7 +1251,7 @@ def getIfcExtrusionData(obj,scale=1,nosubs=False):
#r.Rotation = DraftVecUtils.getRotation(v,FreeCAD.Vector(0,0,1)) #r.Rotation = DraftVecUtils.getRotation(v,FreeCAD.Vector(0,0,1))
d = [r.Base,DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(1,0,0))),DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(0,0,1)))] d = [r.Base,DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(1,0,0))),DraftVecUtils.rounded(r.Rotation.multVec(FreeCAD.Vector(0,0,1)))]
#r = r.inverse() #r = r.inverse()
#print "getExtrusionData: computed placement:",r #print("getExtrusionData: computed placement:",r)
import Part import Part
if len(p.Edges) == 1: if len(p.Edges) == 1:
if isinstance(p.Edges[0].Curve,Part.Circle): if isinstance(p.Edges[0].Curve,Part.Circle):
@ -1269,7 +1268,7 @@ def getIfcExtrusionData(obj,scale=1,nosubs=False):
if isinstance(e.Curve,Part.Circle): if isinstance(e.Curve,Part.Circle):
curves = True curves = True
elif not isinstance(e.Curve,Part.LineSegment): elif not isinstance(e.Curve,Part.LineSegment):
print "Arch.getIfcExtrusionData: Warning: unsupported edge type in profile" print("Arch.getIfcExtrusionData: Warning: unsupported edge type in profile")
if curves: if curves:
# Composite profile # Composite profile
ecurves = [] ecurves = []
@ -1350,7 +1349,7 @@ def getIfcBrepFacesData(obj,scale=1,sub=False,tessellation=1):
dataset = shape.Solids dataset = shape.Solids
else: else:
dataset = shape.Shells dataset = shape.Shells
print "Warning! object contains no solids" print("Warning! object contains no solids")
for sol in shape.Solids: for sol in shape.Solids:
s = [] s = []
curves = False curves = False
@ -1418,7 +1417,7 @@ class IfcSchema:
self.data = self.file.read() self.data = self.file.read()
self.types = self.readTypes() self.types = self.readTypes()
self.entities = self.readEntities() self.entities = self.readEntities()
if DEBUG: print "Parsed from schema %s: %s entities and %s types" % (self.filename, len(self.entities), len(self.types)) if DEBUG: print("Parsed from schema %s: %s entities and %s types" % (self.filename, len(self.entities), len(self.types)))
def readTypes(self): def readTypes(self):
""" """
@ -1512,7 +1511,7 @@ class IfcFile:
self.file = open(self.filename) self.file = open(self.filename)
self.entById, self.entsByName, self.header = self.read() self.entById, self.entsByName, self.header = self.read()
self.file.close() self.file.close()
if DEBUG: print "Parsed from file %s: %s entities" % (self.filename, len(self.entById)) if DEBUG: print("Parsed from file %s: %s entities" % (self.filename, len(self.entById)))
def getEntityById(self, id): def getEntityById(self, id):
return self.entById.get(id, None) return self.entById.get(id, None)
@ -1658,7 +1657,7 @@ class IfcEntity:
propset.extend(p.RelatingPropertyDefinition.Quantities) propset.extend(p.RelatingPropertyDefinition.Quantities)
for prop in propset: for prop in propset:
if prop.Name == propName: if prop.Name == propName:
print "found valid",prop print("found valid",prop)
if hasattr(prop,"LengthValue"): if hasattr(prop,"LengthValue"):
return prop.LengthValue return prop.LengthValue
elif hasattr(prop,"AreaValue"): elif hasattr(prop,"AreaValue"):
@ -1685,12 +1684,12 @@ class IfcDocument:
for k,e in self.data.iteritems(): for k,e in self.data.iteritems():
eid = int(e['id']) eid = int(e['id'])
self.Entities[eid] = IfcEntity(e,self) self.Entities[eid] = IfcEntity(e,self)
if DEBUG: print len(self.Entities),"entities created. Creating attributes..." if DEBUG: print(len(self.Entities),"entities created. Creating attributes...")
for k,ent in self.Entities.iteritems(): for k,ent in self.Entities.iteritems():
if DEBUG: print "attributing entity ",ent if DEBUG: print("attributing entity ",ent)
if hasattr(ent,"attributes"): if hasattr(ent,"attributes"):
for k,v in ent.attributes.iteritems(): for k,v in ent.attributes.iteritems():
if DEBUG: print "parsing attribute: ",k," value ",v if DEBUG: print("parsing attribute: ",k," value ",v)
if isinstance(v,str): if isinstance(v,str):
val = self.__clean__(v) val = self.__clean__(v)
elif isinstance(v,list): elif isinstance(v,list):
@ -1703,7 +1702,7 @@ class IfcDocument:
else: else:
val = v val = v
setattr(ent,k.strip(),val) setattr(ent,k.strip(),val)
if DEBUG: print "Document successfully created" if DEBUG: print("Document successfully created")
def __clean__(self,value): def __clean__(self,value):
"turns an attribute value into something usable" "turns an attribute value into something usable"
@ -1729,18 +1728,18 @@ class IfcDocument:
for subval in val: for subval in val:
if '#' in subval: if '#' in subval:
s = subval.strip(" #") s = subval.strip(" #")
if DEBUG: print "referencing ",s," : ",self.getEnt(int(s)) if DEBUG: print("referencing ",s," : ",self.getEnt(int(s)))
l.append(self.getEnt(int(s))) l.append(self.getEnt(int(s)))
val = l val = l
else: else:
val = val.strip() val = val.strip()
val = val.replace("#","") val = val.replace("#","")
if DEBUG: print "referencing ",val," : ",self.getEnt(int(val)) if DEBUG: print("referencing ",val," : ",self.getEnt(int(val)))
val = self.getEnt(int(val)) val = self.getEnt(int(val))
if not val: if not val:
val = value val = value
except: except:
if DEBUG: print "error parsing attribute",value if DEBUG: print("error parsing attribute",value)
val = value val = value
return val return val
@ -1815,7 +1814,7 @@ def explorer(filename,schema="IFC2X3_TC1.exp"):
bold.setWeight(75) bold.setWeight(75)
bold.setBold(True) bold.setBold(True)
#print ifc.Entities #print(ifc.Entities)
for i in ifc.Entities.keys(): for i in ifc.Entities.keys():
e = ifc.Entities[i] e = ifc.Entities[i]
@ -2176,17 +2175,17 @@ class IfcWriter(object):
try: try:
elt = create(self._fileobject,elttype,[uid(),self._owner,name,description,None,placement,prd,None]+extra) elt = create(self._fileobject,elttype,[uid(),self._owner,name,description,None,placement,prd,None]+extra)
except: except:
print "unable to create an ",elttype, " with attributes: ",[uid(),self._owner,str(name),description,None,placement,prd,None]+extra print("unable to create an ",elttype, " with attributes: ",[uid(),self._owner,str(name),description,None,placement,prd,None]+extra)
try: try:
if hasattr(ifcw,"Entity"): if hasattr(ifcw,"Entity"):
o = ifcw.Entity(elttype) o = ifcw.Entity(elttype)
else: else:
o = ifcw.entity_instance(elttype) o = ifcw.entity_instance(elttype)
print "supported attributes are: " print("supported attributes are: ")
print getPropertyNames(o) print(getPropertyNames(o))
except: except:
print "unable to create an element of type '"+elttype+"'" print("unable to create an element of type '"+elttype+"'")
print "WARNING: skipping object '"+name+"' of type "+elttype print("WARNING: skipping object '"+name+"' of type "+elttype)
return None return None
self.BuildingProducts.append(elt) self.BuildingProducts.append(elt)
if not storey: if not storey:
@ -2324,17 +2323,17 @@ class IfcWriter(object):
for f in face: for f in face:
pts = [] pts = []
for p in f: for p in f:
#print p #print(p)
if p in self.fpoints: if p in self.fpoints:
#print self.fpoints.index(p) #print(self.fpoints.index(p))
#print self.frefs #print(self.frefs)
pts.append(self.frefs[self.fpoints.index(p)]) pts.append(self.frefs[self.fpoints.index(p)])
else: else:
pt = create(self._fileobject,"IfcCartesianPoint",getTuple(p)) pt = create(self._fileobject,"IfcCartesianPoint",getTuple(p))
pts.append(pt) pts.append(pt)
self.fpoints.append(p) self.fpoints.append(p)
self.frefs.append(pt) self.frefs.append(pt)
#print pts #print(pts)
loop = create(self._fileobject,"IfcPolyLoop",[pts]) loop = create(self._fileobject,"IfcPolyLoop",[pts])
if idx == 0: if idx == 0:
fb = create(self._fileobject,"IfcFaceOuterBound",[loop,True]) fb = create(self._fileobject,"IfcFaceOuterBound",[loop,True])
@ -2350,8 +2349,8 @@ class IfcWriter(object):
of faces (each face is a list of lists of points, inner wires are reversed)""" of faces (each face is a list of lists of points, inner wires are reversed)"""
self.fpoints = [] self.fpoints = []
self.frefs = [] self.frefs = []
#print "adding ",len(faces)," faces" #print("adding ",len(faces)," faces")
#print faces #print(faces)
ifaces = [self.addFace(face) for face in faces] ifaces = [self.addFace(face) for face in faces]
sh = create(self._fileobject,"IfcClosedShell",[ifaces]) sh = create(self._fileobject,"IfcClosedShell",[ifaces])
brp = create(self._fileobject,"IfcFacetedBrep",[sh]) brp = create(self._fileobject,"IfcFacetedBrep",[sh])

View File

@ -40,7 +40,7 @@ else:
p = Draft.precision() p = Draft.precision()
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open pythonopen = open
def findVert(aVertex,aList): def findVert(aVertex,aList):
@ -99,7 +99,7 @@ def getIndices(shape,offset):
else: else:
fi = "" fi = ""
for e in f.OuterWire.OrderedEdges: for e in f.OuterWire.OrderedEdges:
#print e.Vertexes[0].Point,e.Vertexes[1].Point #print(e.Vertexes[0].Point,e.Vertexes[1].Point)
v = e.Vertexes[0] v = e.Vertexes[0]
ind = findVert(v,shape.Vertexes) ind = findVert(v,shape.Vertexes)
if ind == None: if ind == None:

View File

@ -34,7 +34,7 @@ import os,zipfile,xml.sax,FreeCAD,Part,Draft,Arch,Mesh,tempfile,math,Sketcher
DEBUG = True DEBUG = True
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pyopen = open # because we'll redefine open below pyopen = open # because we'll redefine open below

View File

@ -116,7 +116,7 @@ template = """<!DOCTYPE html>
</html>""" </html>"""
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open pythonopen = open
def export(exportList,filename): def export(exportList,filename):
@ -155,7 +155,7 @@ def getCameraData():
else: else:
result += "camera.position.set(0,0,1000);\n" result += "camera.position.set(0,0,1000);\n"
result += tab+"camera.lookAt( scene.position );\n"+tab result += tab+"camera.lookAt( scene.position );\n"+tab
# print result # print(result)
return result return result
def getObjectData(obj,wireframeMode=wireframeStyle): def getObjectData(obj,wireframeMode=wireframeStyle):

View File

@ -34,7 +34,7 @@ import re, FreeCAD, FreeCADGui, Part, cProfile, os, string
from FreeCAD import Vector, Base from FreeCAD import Vector, Base
from Draft import makeWire from Draft import makeWire
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open pythonopen = open
useDraftWire = True useDraftWire = True

View File

@ -65,7 +65,7 @@ dxfReader = None
dxfColorMap = None dxfColorMap = None
dxfLibrary = None dxfLibrary = None
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open # to distinguish python built-in open function from the one declared here pythonopen = open # to distinguish python built-in open function from the one declared here

View File

@ -45,7 +45,7 @@ try: import FreeCADGui
except ValueError: gui = False except ValueError: gui = False
else: gui = True else: gui = True
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open pythonopen = open
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft") params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")

View File

@ -55,7 +55,7 @@ else: gui = True
try: draftui = FreeCADGui.draftToolBar try: draftui = FreeCADGui.draftToolBar
except AttributeError: draftui = None except AttributeError: draftui = None
if open.__module__ == '__builtin__': if open.__module__ in ['__builtin__','io']:
pythonopen = open pythonopen = open
svgcolors = { svgcolors = {

View File

@ -413,7 +413,7 @@ def importFrd(filename, analysis=None, result_name_prefix=None):
if 'Nodes' in m: if 'Nodes' in m:
positions = [] positions = []
for k, v in m['Nodes'].iteritems(): for k, v in m['Nodes'].items():
positions.append(v) positions.append(v)
p_x_max, p_y_max, p_z_max = map(max, zip(*positions)) p_x_max, p_y_max, p_z_max = map(max, zip(*positions))
p_x_min, p_y_min, p_z_min = map(min, zip(*positions)) p_x_min, p_y_min, p_z_min = map(min, zip(*positions))
@ -454,7 +454,7 @@ def importFrd(filename, analysis=None, result_name_prefix=None):
strainv = result_set['strainv'] strainv = result_set['strainv']
no_of_values = len(disp) no_of_values = len(disp)
displacement = [] displacement = []
for k, v in disp.iteritems(): for k, v in disp.items():
displacement.append(v) displacement.append(v)
x_max, y_max, z_max = map(max, zip(*displacement)) x_max, y_max, z_max = map(max, zip(*displacement))

View File

@ -23,10 +23,15 @@
# This is the start page template # This is the start page template
import os,FreeCAD,FreeCADGui,tempfile,time,zipfile,urllib,re,cStringIO import os,FreeCAD,FreeCADGui,tempfile,time,zipfile,urllib,re,sys
from PySide import QtGui from PySide import QtGui
from xml.etree.ElementTree import parse from xml.etree.ElementTree import parse
try:
import io as cStringIO
except:
import cStringIO
FreeCADGui.addLanguagePath(":/translations") FreeCADGui.addLanguagePath(":/translations")
FreeCADGui.updateLocale() FreeCADGui.updateLocale()
@ -41,10 +46,16 @@ def translate(context,text):
s = cStringIO.StringIO() s = cStringIO.StringIO()
for i in u: for i in u:
if ord(i) == 39: if sys.version_info.major > 2: #below only works correctly in python3
if i == 39:
s.write("\\'") s.write("\\'")
else: else:
s.write(i) s.write(chr(i))
else:
if ord(i) == 39:
s.write(unicode("\\'"))
else:
s.write(unicode(i))
t = s.getvalue() t = s.getvalue()
s.close() s.close()
return t return t
@ -612,7 +623,7 @@ def getFeed(url,numitems=3):
resp += item['title'] resp += item['title']
resp += '</a></li>' resp += '</a></li>'
resp += '</ul>' resp += '</ul>'
print resp print(resp)
return resp return resp
def getCustomBlocks(): def getCustomBlocks():
@ -638,7 +649,7 @@ def setColors(html):
defaults["#textcolor"] = palette.text().color().name() defaults["#textcolor"] = palette.text().color().name()
defaults["#windowcolor"] = palette.window().color().name() defaults["#windowcolor"] = palette.window().color().name()
defaults["#windowtextcolor"] = palette.windowText().color().name() defaults["#windowtextcolor"] = palette.windowText().color().name()
for k,v in defaults.iteritems(): for k,v in defaults.items():
html = html.replace(k,str(v)) html = html.replace(k,str(v))
return html return html