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)
{
if (PyList_Check(value)) {
Py_ssize_t nSize = PyList_Size(value);
if (PySequence_Check(value)) {
Py_ssize_t nSize = PySequence_Size(value);
std::vector<Base::Vector3d> values;
values.resize(nSize);
for (Py_ssize_t i=0; i<nSize;++i) {
PyObject* item = PyList_GetItem(value, i);
PyObject* item = PySequence_GetItem(value, i);
PropertyVector val;
val.setPyObject( item );
values[i] = val.getValue();

View File

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

View File

@ -470,7 +470,7 @@ class Component:
def processSubShapes(self,obj,base,placement=None):
"Adds additions and subtractions to a base shape"
import Draft,Part
#print "Processing subshapes of ",obj.Label, " : ",obj.Additions
#print("Processing subshapes of ",obj.Label, " : ",obj.Additions)
if placement:
if placement.isNull():
@ -520,7 +520,7 @@ class Component:
try:
base = base.fuse(s)
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:
base = s
@ -558,7 +558,7 @@ class Component:
try:
base = base.cut(s)
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
def applyShape(self,obj,shape,placement,allowinvalid=False,allownosolid=False):
@ -633,7 +633,7 @@ class Component:
except Part.OCCError:
# error in computing the areas. Better set them to zero than show a wrong value
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
if hasattr(obj,"PerimeterLength"):
if obj.PerimeterLength.Value != 0:
@ -659,7 +659,7 @@ class ViewProviderComponent:
self.Object = vobj.Object
def updateData(self,obj,prop):
#print obj.Name," : updating ",prop
#print(obj.Name," : updating ",prop)
if prop == "BaseMaterial":
if obj.BaseMaterial:
if 'DiffuseColor' in obj.BaseMaterial.Material:
@ -692,7 +692,7 @@ class ViewProviderComponent:
return ":/icons/Arch_Component.svg"
def onChanged(self,vobj,prop):
#print vobj.Object.Name, " : changing ",prop
#print(vobj.Object.Name, " : changing ",prop)
if prop == "Visibility":
#for obj in vobj.Object.Additions+vobj.Object.Subtractions:
# if (Draft.getType(obj) == "Window") or (Draft.isClone(obj,"Window",True)):

View File

@ -27,7 +27,8 @@ __title__="FreeCAD Equipment"
__author__ = "Yorik van Havre"
__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
if FreeCAD.GuiUp:
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
if largestonly:
c = cleanmesh.getSeparateComponents()
#print c
#print(c)
cleanmesh = c[0]
segs = cleanmesh.getPlanarSegments(1)
meshes = []
@ -141,7 +142,7 @@ def createMeshView(obj,direction=FreeCAD.Vector(0,0,-1),outeronly=False,largesto
shape = None
for f in cleanmesh.Facets:
p = Part.makePolygon(f.Points+[f.Points[0]])
#print p,len(p.Vertexes),p.isClosed()
#print(p,len(p.Vertexes),p.isClosed())
try:
p = Part.Face(p)
if shape:
@ -165,7 +166,7 @@ def createMeshView(obj,direction=FreeCAD.Vector(0,0,-1),outeronly=False,largesto
try:
f = Part.Face(w)
except Part.OCCError:
print "Unable to produce a face from the outer wire."
print("Unable to produce a face from the outer wire.")
else:
shape = f

View File

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

View File

@ -73,9 +73,9 @@ def readPresets():
Presets.append(r)
bid=bid+1
except ValueError:
print "Skipping bad line: "+str(row)
print("Skipping bad line: "+str(row))
except IOError:
print "Could not open ",profilefile
print("Could not open ",profilefile)
return Presets
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":
_ProfileU(obj, profile)
else :
print "Profile not supported"
print("Profile not supported")
if FreeCAD.GuiUp:
Draft._ViewProviderDraft(obj.ViewObject)
return obj

View File

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

View File

@ -647,10 +647,10 @@ class _Roof(ArchComponent.Component):
rn += 1
if obj.RidgeLength.Value != 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:
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)

View File

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

View File

@ -97,7 +97,7 @@ def getCutShapes(objs,section,showHidden):
if o.Shape.isValid():
shapes.extend(o.Shape.Solids)
else:
print section.Label,": Skipping invalid object:",o.Label
print(section.Label,": Skipping invalid object:",o.Label)
else:
shapes.append(o.Shape)
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:
svg += render.getHiddenSVG(linewidth="LWPlaceholder")
svg += '</g>\n'
# print render.info()
# print(render.info())
else:
# render using the Drawing module
@ -622,7 +622,7 @@ class _ArchDrawingView:
def getDXF(self,obj):
"returns a DXF representation of the view"
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 ""
result = []
import Drawing

View File

@ -312,7 +312,7 @@ class _Space(ArchComponent.Component):
shape = None
faces = []
#print "starting compute"
#print("starting compute")
# 1: if we have a base shape, we use it
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
if shape:
#print "got shape from base object"
#print("got shape from base object")
bb = shape.BoundBox
else:
bb = None
@ -336,7 +336,7 @@ class _Space(ArchComponent.Component):
if not bb:
return
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
goodfaces = []
@ -345,9 +345,9 @@ class _Space(ArchComponent.Component):
if "Face" in b[1]:
fn = int(b[1][4:])-1
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
cutvolumes = []
@ -356,22 +356,22 @@ class _Space(ArchComponent.Component):
f.reverse()
cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(f,shape)
if cutvolume:
#print "generated 1 cutvolume"
#print("generated 1 cutvolume")
cutvolumes.append(cutvolume.copy())
#Part.show(cutvolume)
for v in cutvolumes:
#print "cutting"
#print("cutting")
shape = shape.cut(v)
# 5: get the final shape
if shape:
if shape.Solids:
#print "setting objects shape"
#print("setting objects shape")
shape = shape.Solids[0]
obj.Shape = shape
return
print "Arch: error computing space boundary"
print("Arch: error computing space boundary")
def getArea(self,obj):
"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)
fHeight = float(h)/numberofsteps
a = math.atan(fHeight/fLength)
print "landing data:",fLength,":",fHeight
print("landing data:",fLength,":",fHeight)
# step
p1 = self.align(vBase,obj.Align,vWidth)
@ -365,7 +365,7 @@ class _Stairs(ArchComponent.Component):
vBase = edge.Vertexes[0].Point
vNose = DraftVecUtils.scaleTo(vLength,-abs(obj.Nosing.Value))
a = math.atan(vHeight.Length/vLength.Length)
#print "stair data:",vLength.Length,":",vHeight.Length
#print("stair data:",vLength.Length,":",vHeight.Length)
# steps
for i in range(numberofsteps-1):
@ -402,7 +402,7 @@ class _Stairs(ArchComponent.Component):
h = DraftVecUtils.scaleTo(vLength,-resLength)
lProfile.append(lProfile[-1].add(Vector(h.x,h.y,-resHeight2)))
lProfile.append(vBase)
#print lProfile
#print(lProfile)
pol = Part.makePolygon(lProfile)
struct = Part.Face(pol)
evec = vWidth
@ -429,7 +429,7 @@ class _Stairs(ArchComponent.Component):
v4 = DraftVecUtils.scaleTo(vLength,-l4)
lProfile.append(lProfile[-1].add(v4))
lProfile.append(lProfile[0])
#print lProfile
#print(lProfile)
pol = Part.makePolygon(lProfile)
pol = Part.Face(pol)
evec = DraftVecUtils.scaleTo(vWidth,obj.StringerWidth.Value)
@ -484,11 +484,10 @@ class _Stairs(ArchComponent.Component):
def makeCurvedStairs(self,obj,edge):
print "Not yet implemented!"
print("Not yet implemented!")
def makeCurvedStairsWithLanding(self,obj,edge):
print "Not yet implemented!"
print("Not yet implemented!")
class _ViewProviderStairs(ArchComponent.ViewProviderComponent):

View File

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

View File

@ -63,7 +63,7 @@ class Renderer:
import WorkingPlane
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):
return "Arch Renderer: " + str(len(self.faces)) + " faces projected on " + str(self.wp)
@ -91,11 +91,11 @@ class Renderer:
self.wp.setFromPlacement(wp)
else:
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)):
"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:
self.faces.append([f,color])
self.resetFlags()
@ -111,11 +111,11 @@ class Renderer:
for f in o.Shape.Faces:
self.faces.append([f,color])
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)):
"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:
if s.Faces:
self.shapes.append([s,color])
@ -149,14 +149,14 @@ class Renderer:
def isVisible(self,face):
"returns True if the given face points in the view direction"
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:
return True
return False
def reorient(self):
"reorients the faces on the WP"
#print "VRM: start reorient"
#print("VRM: start reorient")
if not self.faces:
return
self.faces = [self.projectFace(f) for f in self.faces]
@ -165,7 +165,7 @@ class Renderer:
if self.hiddenEdges:
self.hiddenEdges = [self.projectEdge(e) for e in self.hiddenEdges]
self.oriented = True
#print "VRM: end reorient"
#print("VRM: end reorient")
def removeHidden(self):
"removes faces pointing outwards"
@ -175,42 +175,42 @@ class Renderer:
for f in self.faces:
if self.isVisible(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.trimmed = True
def projectFace(self,face):
"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 = []
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
norm = face[0].normalAt(0,0)
for w in face[0].Wires:
verts = []
edges = Part.__sortEdges__(w.Edges)
#print len(edges)," edges after sorting"
#print(len(edges)," edges after sorting")
for e in edges:
v = e.Vertexes[0].Point
#print v
#print(v)
v = self.wp.getLocalCoords(v)
verts.append(v)
verts.append(verts[0])
if len(verts) > 2:
#print "new wire with ",len(verts)
#print("new wire with ",len(verts))
wires.append(Part.makePolygon(verts))
try:
sh = ArchCommands.makeFace(wires)
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
else:
# restoring flipped normals
vnorm = self.wp.getLocalCoords(norm)
if vnorm.getAngle(sh.normalAt(0,0)) > 1:
sh.reverse()
#print "VRM: projectFace end: ",len(sh.Vertexes)," verts"
#print("VRM: projectFace end: ",len(sh.Vertexes)," verts")
return [sh]+face[1:]
def projectEdge(self,edge):
@ -235,18 +235,18 @@ class Renderer:
try:
sh = Part.Face(wires)
except Part.OCCError:
if DEBUG: print "Error: Unable to flatten face"
if DEBUG: print("Error: Unable to flatten face")
return None
else:
return [sh]+face[1:]
def cut(self,cutplane,hidden=False):
"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:
return
if not self.shapes:
if DEBUG: print "No objects to make sections"
if DEBUG: print("No objects to make sections")
else:
fill = (1.0,1.0,1.0,1.0)
shps = []
@ -263,9 +263,9 @@ class Renderer:
shapes.append([c]+sh[1:])
for f in c.Faces:
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]):
print "COPLANAR"
print("COPLANAR")
sections.append([f,fill])
if hidden:
c = sol.cut(invcutvolume)
@ -273,13 +273,13 @@ class Renderer:
self.shapes = shapes
self.faces = faces
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.oriented = False
self.trimmed = False
self.sorted = 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):
"Returns True if the vert is inside the face in Z projection"
@ -328,13 +328,13 @@ class Renderer:
def compare(self,face1,face2):
"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 DEBUG: print "Warning, undefined face!"
if DEBUG: print("Warning, undefined face!")
return 31
elif not face2:
if DEBUG: print "Warning, undefined face!"
if DEBUG: print("Warning, undefined face!" )
return 32
# theory from
@ -345,7 +345,7 @@ class Renderer:
b2 = face2[0].BoundBox
# 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:
return 0
if b1.XMin > b2.XMax:
@ -354,18 +354,18 @@ class Renderer:
return 0
if b1.YMin > b2.YMax:
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
if DEBUG: print "doing test 2"
if DEBUG: print("doing test 2")
if b1.ZMax < b2.ZMin:
return 2
if b2.ZMax < b1.ZMin:
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
if DEBUG: print "doing test 3"
if DEBUG: print("doing test 3")
norm = face2[0].normalAt(0,0)
behind = 0
front = 0
@ -380,15 +380,15 @@ class Renderer:
behind += 1
else:
front += 1
if DEBUG: print "front: ",front," behind: ",behind
if DEBUG: print("front: ",front," behind: ",behind)
if behind == len(face1[0].Vertexes):
return 2
elif front == len(face1[0].Vertexes):
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
if DEBUG: print "doing test 4"
if DEBUG: print("doing test 4")
norm = face1[0].normalAt(0,0)
behind = 0
front = 0
@ -403,22 +403,22 @@ class Renderer:
behind += 1
else:
front += 1
if DEBUG: print "front: ",front," behind: ",behind
if DEBUG: print("front: ",front," behind: ",behind)
if behind == len(face2[0].Vertexes):
return 1
elif front == len(face2[0].Vertexes):
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
if DEBUG: print "doing test 5"
if DEBUG: print("doing test 5")
if not self.zOverlaps(face1,face2):
return 0
elif not self.zOverlaps(face2,face1):
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
def join(self,otype):
@ -437,7 +437,7 @@ class Renderer:
objs.append(o)
for g in [walls,structs]:
if g:
print "group:",g
print("group:",g)
col = g[0].ViewObject.DiffuseColor[0]
s = g[0].Shape
for o in g[1:]:
@ -445,7 +445,7 @@ class Renderer:
fs = s.fuse(o.Shape)
fs = fs.removeSplitter()
except Part.OCCError:
print "shape fusion failed"
print("shape fusion failed")
objs.append([o.Shape,o.ViewObject.DiffuseColor[0]])
else:
s = fs
@ -456,7 +456,7 @@ class Renderer:
l = None
h = None
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)
if r == 1:
l = faces.index(f2)
@ -475,27 +475,27 @@ class Renderer:
def sort(self):
"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:
return
if not self.trimmed:
self.removeHidden()
if DEBUG: print "Done hidden face removal"
if DEBUG: print("Done hidden face removal")
if len(self.faces) == 1:
return
if not self.oriented:
self.reorient()
if DEBUG: print "Done reorientation"
if DEBUG: print("Done reorientation")
faces = self.faces[:]
if DEBUG: print "sorting ",len(self.faces)," faces"
if DEBUG: print("sorting ",len(self.faces)," faces")
sfaces = []
loopcount = 0
notfoundstack = 0
while faces:
if DEBUG: print "loop ", loopcount
if DEBUG: print("loop ", loopcount)
f1 = faces[0]
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)
if p == None:
# no position found, we move the face to the end of the pile
@ -510,11 +510,11 @@ class Renderer:
else:
# either there is no stack, or no more face 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:]:
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)
print "comparison result:",r
print("comparison result:",r)
if r == 1:
faces.remove(f2)
sfaces.append(f2)
@ -542,13 +542,13 @@ class Renderer:
faces.append(f1)
loopcount += 1
if loopcount == MAXLOOP * len(self.faces):
if DEBUG: print "Too many loops, aborting."
if DEBUG: print("Too many loops, aborting.")
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.sorted = True
if DEBUG: print "\n\n======> Finished sort\n\n"
if DEBUG: print("\n\n======> Finished sort\n\n")
def buildDummy(self):
"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):
"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:
self.sort()
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):
"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:
self.reorient()
svg = '<g stroke="#000000" stroke-width="' + str(linewidth) + '" style="stroke-width:' + str(linewidth)
@ -630,7 +630,7 @@ class Renderer:
svg +='<path '
svg += 'd="'
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 += '" style="fill:' + fill + ';fill-rule: evenodd;"/>\n'
svg += '</g>\n'
@ -638,7 +638,7 @@ class Renderer:
def getHiddenSVG(self,linewidth=0.02):
"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:
self.reorient()
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
w = DraftGeomUtils.findWires(eds)
if len(w) == 1:
#print "found common wire"
#print("found common wire")
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)
print sh
print(sh)
return sh
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
if FreeCAD.GuiUp:
import FreeCADGui
@ -386,7 +387,7 @@ def makeWindowPreset(windowtype,width,height,h1,h2,h3,w1,w2,o1,o2,placement=None
FreeCAD.ActiveDocument.recompute()
return obj
print "Arch: Unknown window type"
print("Arch: Unknown window type")
class _CommandWindow:
@ -865,7 +866,7 @@ class _Window(ArchComponent.Component):
if not DraftGeomUtils.isNull(pl):
base.Placement = base.Placement.multiply(pl)
else:
print "Arch: Bad formatting of window parts definitions"
print("Arch: Bad formatting of window parts definitions")
base = self.processSubShapes(obj,base)
if base:
@ -1004,7 +1005,7 @@ class _ViewProviderWindow(ArchComponent.ViewProviderComponent):
if not obj.WindowParts:
return
solids = obj.Shape.copy().Solids
#print "Colorizing ", solids
#print("Colorizing ", solids)
colors = []
base = obj.ViewObject.ShapeColor
for i in range(len(solids)):
@ -1016,7 +1017,7 @@ class _ViewProviderWindow(ArchComponent.ViewProviderComponent):
ccol = ArchCommands.getDefaultColor("WindowGlass")
for f in solids[i].Faces:
colors.append(ccol)
#print "colors: ",colors
#print("colors: ",colors)
if colors:
obj.ViewObject.DiffuseColor = colors

View File

@ -120,7 +120,7 @@ def read(filename):
#for geom in col.geometries:
for prim in geom.primitives():
#for prim in geom.primitives:
#print prim, dir(prim)
#print(prim, dir(prim))
meshdata = []
if hasattr(prim,"triangles"):
tset = prim.triangles()
@ -134,9 +134,9 @@ def read(filename):
v = [x * unit for x in v]
face.append([v[0],v[1],v[2]])
meshdata.append(face)
#print meshdata
#print(meshdata)
newmesh = Mesh.Mesh(meshdata)
#print newmesh
#print(newmesh)
obj = FreeCAD.ActiveDocument.addObject("Mesh::Feature","Mesh")
obj.Mesh = newmesh
@ -161,10 +161,10 @@ def export(exportList,filename,tessellation=1):
findex = []
m = None
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))
elif obj.isDerivedFrom("Mesh::Feature"):
print "exporting object ",obj.Name, obj.Mesh
print("exporting object ",obj.Name, obj.Mesh)
m = obj.Mesh
if m:
# vertex indices
@ -178,7 +178,7 @@ def export(exportList,filename,tessellation=1):
for i in range(len(m.Topology[1])):
f = m.Topology[1][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'))
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])

View File

@ -35,7 +35,7 @@ import os,time,tempfile,uuid,FreeCAD,Part,Draft,Arch,math,DraftVecUtils
DEBUG = False
if open.__module__ == '__builtin__':
if open.__module__ in ['__builtin__','io']:
pyopen = open # because we'll redefine open below
# which IFC type must create which FreeCAD type
@ -188,7 +188,7 @@ def explore(filename=None):
filename = decode(filename,utf=True)
if not os.path.exists(filename):
print "File not found"
print("File not found")
return
ifc = ifcopenshell.open(filename)
@ -265,7 +265,7 @@ def explore(filename=None):
try:
argvalue = getattr(entity,argname)
except:
print "Error in entity ",entity
print("Error in entity ", entity)
break
else:
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")
return
if DEBUG: print "Opening ",filename,"...",
if DEBUG: print("Opening ",filename,"...",)
try:
doc = FreeCAD.getDocument(docname)
except:
doc = FreeCAD.newDocument(docname)
FreeCAD.ActiveDocument = doc
if DEBUG: print "done."
if DEBUG: print("done.")
global ROOT_ELEMENT
if root:
ROOT_ELEMENT = root
if DEBUG: print ("done.")
#global ifcfile # keeping global for debugging purposes
filename = decode(filename,utf=True)
ifcfile = ifcopenshell.open(filename)
@ -377,7 +380,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
annotations = ifcfile.by_type("IfcAnnotation")
materials = ifcfile.by_type("IfcMaterial")
if DEBUG: print "Building relationships tables...",
if DEBUG: print("Building relationships table...",)
# building relations tables
objects = {} # { id:object, ... }
@ -459,13 +462,13 @@ def insert(filename,docname,skip=[],only=[],root=None):
only.extend(additions[currentid])
products = [ifcfile[currentid] for currentid in ids]
if DEBUG: print "done."
if DEBUG: print("done.")
count = 0
from FreeCAD import Base
progressbar = Base.ProgressIndicator()
progressbar.start("Importing IFC objects...",len(products))
if DEBUG: print "Processing objects..."
if DEBUG: print("Processing objects...")
# products
for product in products:
@ -473,7 +476,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
pid = product.id()
guid = product.GlobalId
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:])
if product.Name:
name = product.Name.encode("utf8")
@ -488,20 +491,20 @@ def insert(filename,docname,skip=[],only=[],root=None):
if ptype in structuralifcobjects:
archobj = False
structobj = True
if DEBUG: print " (struct)",
if DEBUG: print(" (struct)",)
else:
if DEBUG: print " (arch)",
if DEBUG: print(" (arch)",)
if MERGE_MODE_ARCH == 4 and archobj:
if DEBUG: print " skipped."
if DEBUG: print(" skipped.")
continue
if MERGE_MODE_STRUCT == 3 and not archobj:
if DEBUG: print " skipped."
if DEBUG: print(" skipped.")
continue
if pid in skip: # user given id skip list
if DEBUG: print " skipped."
if DEBUG: print(" skipped.")
continue
if ptype in SKIP: # preferences-set type skip list
if DEBUG: print " skipped."
if DEBUG: print(" skipped.")
continue
# detect if this object is sharing its shape
@ -511,8 +514,9 @@ def insert(filename,docname,skip=[],only=[],root=None):
try:
prepr = product.Representation
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:
for s in prepr.Representations:
if s.RepresentationIdentifier.upper() == "BODY":
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
if brep:
if DEBUG: print " ",str(len(brep)/1000),"k ",
if DEBUG: print(" ",str(len(brep)/1000),"k ",)
shape = Part.Shape()
shape.importBrepFromString(brep)
@ -544,23 +548,23 @@ def insert(filename,docname,skip=[],only=[],root=None):
if not shape.isNull():
if (MERGE_MODE_ARCH > 0 and archobj) or structobj:
if ptype == "IfcSpace": # do not add spaces to compounds
if DEBUG: print "skipping space ",pid
if DEBUG: print("skipping space ",pid)
elif structobj:
structshapes[pid] = shape
if DEBUG: print shape.Solids," ",
if DEBUG: print(shape.Solids," ",)
baseobj = shape
else:
shapes[pid] = shape
if DEBUG: print shape.Solids," ",
if DEBUG: print(shape.Solids," ",)
baseobj = shape
else:
if clone:
if DEBUG: print "clone ",
if DEBUG: print("clone ",)
else:
if GET_EXTRUSIONS:
ex = Arch.getExtrusionData(shape)
if ex:
print "extrusion ",
print("extrusion ",)
baseface = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_footprint")
# bug in ifcopenshell? Some faces of a shell may have non-null placement
# 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.Shape = shape
else:
if DEBUG: print "null shape ",
if DEBUG: print("null shape ",)
if not shape.isValid():
if DEBUG: print "invalid shape ",
if DEBUG: print("invalid shape ",)
#continue
else:
if DEBUG: print " no brep ",
if DEBUG: print(" no brep ",)
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)
if obj:
sols = str(obj.Shape.Solids) if hasattr(obj,"Shape") else ""
if DEBUG: print sols
if DEBUG: print(sols)
objects[pid] = obj
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
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]
# 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 DEBUG: print "Joining Structural shapes...",
if DEBUG: print("Joining Structural shapes...")
for host,children in groups.items(): # Structural
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.Shape = Part.makeCompound(structshapes.values())
if DEBUG: print "done"
if DEBUG: print("done")
else:
if DEBUG: print "Processing Struct relationships...",
if DEBUG: print("Processing Struct relationships...")
# groups
for host,children in groups.items():
if ifcfile[host].is_a("IfcStructuralAnalysisModel"):
# print host, ' --> ', children
# print(host, ' --> ', children)
obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup","AnalysisModel")
objects[host] = obj
if host in objects.keys():
@ -784,7 +788,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
for c in childs_to_delete:
children.remove(c) # to not process the child again in remaining groups
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])
if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -813,11 +817,11 @@ def insert(filename,docname,skip=[],only=[],root=None):
if child in objects.keys():
grp.addObject(objects[child])
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 DEBUG: print "Joining Arch shapes...",
if DEBUG: print("Joining Arch shapes...")
for host,children in additions.items(): # Arch
if ifcfile[host].is_a("IfcBuildingStorey"):
@ -845,13 +849,13 @@ def insert(filename,docname,skip=[],only=[],root=None):
else:
if DEBUG: print "Processing Arch relationships..."
if DEBUG: print("Processing Arch relationships...")
# subtractions
if SEPARATE_OPENINGS:
for subtraction in subtractions:
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]])
if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -862,9 +866,9 @@ def insert(filename,docname,skip=[],only=[],root=None):
if cobs:
if DEBUG and (len(cobs) > 10) and ( not(Draft.getType(objects[host]) in ["Site","Building","Floor"])):
# avoid huge fusions
print "more than 10 shapes to add: skipping."
print("more than 10 shapes to add: skipping.")
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])
if DEBUG: FreeCAD.ActiveDocument.recompute()
@ -880,7 +884,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
# 2D elements
if DEBUG and annotations: print "Creating 2D geometry..."
if DEBUG and annotations:print("Creating 2D geometry...")
scaling = getScaling(ifcfile)
#print "scaling factor =",scaling
@ -901,7 +905,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
if shapes2d:
sh = Part.makeCompound(shapes2d)
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.Shape = sh
p = getPlacement(annotation.ObjectPlacement,scaling)
@ -914,7 +918,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
# Materials
if DEBUG and materials: print "Creating materials...",
if DEBUG and materials: print("Creating materials...")
#print "mattable:",mattable
#print "materials:",materials
fcmats = {}
@ -950,7 +954,7 @@ def insert(filename,docname,skip=[],only=[],root=None):
if FreeCAD.GuiUp:
import FreeCADGui
FreeCADGui.SendMsgToActiveView("ViewFit")
print "Finished importing."
print("Finished importing.")
return doc
@ -1025,9 +1029,9 @@ def export(exportList,filename):
b = Draft.getCloneBase(o,strict=True)
if b:
clones.setdefault(b.Name,[]).append(o.Name)
#print "clones table: ",clones
#print objectslist
#print("clones table: ",clones)
#print(objectslist)
# testing if more than one site selected (forbidden in IFC)
if len(Draft.getObjectsOfType(objectslist,"Site")) > 1:
@ -1081,7 +1085,7 @@ def export(exportList,filename):
# getting the representation
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
args = [uid,history,name,description,None,placement,representation,None]
@ -1113,7 +1117,7 @@ def export(exportList,filename):
if hasattr(obj,"Additions") and (shapetype == "extrusion"):
for o in obj.Additions:
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")
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"):
for o in obj.Subtractions:
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)
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 = 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']:
val = val.encode("utf8")
elif tp == "IfcBoolean":
@ -1273,11 +1277,11 @@ def export(exportList,filename):
treated.append(c.Name)
sites.append(products[site.Name])
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)]
ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'ProjectLink','',project,sites)
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)]
ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',sites[0],buildings)
untreated = []
@ -1396,7 +1400,7 @@ def export(exportList,filename):
rep = ifcfile.createIfcProductDefinitionShape(None,None,[shp])
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)

View File

@ -56,7 +56,7 @@ supportedIfcTypes = ["IfcSite", "IfcBuilding", "IfcBuildingStorey", "IfcBeam", "
"IfcPile", "IfcFooting", "IfcReinforcingBar", "IfcTendon"]
# TODO : shading device not supported?
if open.__module__ == '__builtin__':
if open.__module__ in ['__builtin__','io']:
pyopen = open # because we'll redefine open below
def open(filename,skip=None):
@ -157,7 +157,7 @@ def read(filename,skip=None):
IfcImport.Settings(IfcImport.USE_BREP_DATA,True)
useShapes = True
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
if IFCOPENSHELL5:
@ -167,12 +167,12 @@ def read(filename,skip=None):
num_lines = len(objects)
relations = ifc.by_type("IfcRelAggregates") + ifc.by_type("IfcRelContainedInSpatialStructure") + ifc.by_type("IfcRelVoidsElement")
if not objects:
print "Error opening IFC file"
print("Error opening IFC file")
return
else:
num_lines = sum(1 for line in pyopen(filename))
if not IfcImport.Init(filename):
print "Error opening IFC file"
print("Error opening IFC file")
return
# processing geometry
@ -208,24 +208,24 @@ def read(filename,skip=None):
objname = obj.name
objtype = obj.type
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
n = getCleanName(objname,objid,objtype)
# skip IDs
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
# skip types
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
# check if object was already processed, to workaround an ifcopenshell bug
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:
# build shape
@ -274,14 +274,14 @@ def read(filename,skip=None):
elif shape:
# 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.Label = n
nobj.Shape = shape
else:
# 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 not hasattr(obj.mesh, 'verts'):
obj = IfcImport.Get() # Get triangulated rep of same product
@ -291,7 +291,7 @@ def read(filename,skip=None):
nobj.Mesh = me
nobj.Placement = pl
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
if objparentid:
@ -312,7 +312,7 @@ def read(filename,skip=None):
# processing non-geometry and relationships
parents_temp = dict(ifcParents)
import ArchCommands
#print parents_temp
#print(parents_temp)
while parents_temp:
id, comps = parents_temp.popitem()
@ -345,7 +345,7 @@ def read(filename,skip=None):
parentid = obj.id
parentname = obj.name
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)
if parentid <= 0:
parent = None
@ -364,7 +364,7 @@ def read(filename,skip=None):
elif parenttype == "IfcProject":
parent = None
else:
if DEBUG: print "Fixme: skipping unhandled parent: ", parentid, " ", parenttype
if DEBUG: print("Fixme: skipping unhandled parent: ", parentid, " ", parenttype)
parent = None
# registering object number and parent
if not IFCOPENSHELL5:
@ -378,10 +378,10 @@ def read(filename,skip=None):
if parent and (id in ifcObjects):
if ifcObjects[id] and (ifcObjects[id].Name != parent.Name):
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)
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)
if not IFCOPENSHELL5:
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"))
schema=getSchema()
if schema:
if DEBUG: print "opening",filename,"..."
if DEBUG: print("opening",filename,"...")
ifc = IfcDocument(filename,schema=schema)
else:
FreeCAD.Console.PrintWarning(translate("Arch","IFC Schema not found, IFC import disabled.\n"))
return None
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
for w in ifc.getEnt("IfcWallStandardCase"):
@ -425,17 +425,17 @@ def read(filename,skip=None):
for s in ifc.getEnt("IfcSite"):
group(s,ifc,"Site")
if DEBUG: print "done parsing. Recomputing..."
if DEBUG: print("done parsing. Recomputing...")
FreeCAD.ActiveDocument.recompute()
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
def getCleanName(name,ifcid,ifctype):
"Get a clean name from an ifc object"
#print "getCleanName called",name,ifcid,ifctype
#print("getCleanName called",name,ifcid,ifctype)
n = name
if not n:
n = ifctype
@ -459,24 +459,24 @@ def makeWall(entity,shape=None,name="Wall"):
body.Mesh = shape
wall = Arch.makeWall(body,name=name)
wall.Label = name
if DEBUG: print " made wall object ",entity,":",wall
if DEBUG: print(" made wall object ",entity,":",wall)
return wall
# 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 = 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")
height = entity.getProperty("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:
if r.RepresentationIdentifier == "Axis":
wire = getWire(r.Items,placement)
wall = Arch.makeWall(wire,width,height,align="Center",name="Wall"+str(entity.id))
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:
if r.RepresentationIdentifier == "Body":
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.Normal = norm
if wall:
if DEBUG: print " made wall object ",entity.id,":",wall
if DEBUG: print(" made wall object ",entity.id,":",wall)
return wall
if DEBUG: print " error: skipping wall",entity.id
if DEBUG: print(" error: skipping wall",entity.id)
return None
except:
if DEBUG: print " error: skipping wall",entity
if DEBUG: print(" error: skipping wall",entity)
return None
@ -505,14 +505,14 @@ def makeWindow(entity,shape=None,name="Window"):
window = Arch.makeWindow(name=name)
window.Shape = shape
window.Label = name
if DEBUG: print " made window object ",entity,":",window
if DEBUG: print(" made window object ",entity,":",window)
return window
# 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 = 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")
height = entity.getProperty("Height")
for r in entity.Representation.Representations:
@ -522,12 +522,12 @@ def makeWindow(entity,shape=None,name="Window"):
wire = getWire(b.SweptArea,placement)
window = Arch.makeWindow(wire,width=b.Depth,name=objtype+str(entity.id))
if window:
if DEBUG: print " made window object ",entity.id,":",window
if DEBUG: print(" made window object ",entity.id,":",window)
return window
if DEBUG: print " error: skipping window",entity.id
if DEBUG: print(" error: skipping window",entity.id)
return None
except:
if DEBUG: print " error: skipping window",entity
if DEBUG: print(" error: skipping window",entity)
return None
@ -552,14 +552,14 @@ def makeStructure(entity,shape=None,ifctype=None,name="Structure"):
structure.Role = "Slab"
elif ifctype == "IfcFooting":
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
# 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 = 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")
height = entity.getProperty("Height")
for r in entity.Representation.Representations:
@ -569,12 +569,12 @@ def makeStructure(entity,shape=None,ifctype=None,name="Structure"):
wire = getWire(b.SweptArea,placement)
structure = Arch.makeStructure(wire,height=b.Depth,name=objtype+str(entity.id))
if structure:
if DEBUG: print " made structure object ",entity.id,":",structure
if DEBUG: print(" made structure object ",entity.id,":",structure)
return structure
if DEBUG: print " error: skipping structure",entity.id
if DEBUG: print(" error: skipping structure",entity.id)
return None
except:
if DEBUG: print " error: skipping structure",entity
if DEBUG: print(" error: skipping structure",entity)
return None
@ -594,7 +594,7 @@ def makeSite(entity,shape=None,name="Site"):
site.Label = name
if body:
site.Terrain = body
if DEBUG: print " made site object ",entity,":",site
if DEBUG: print(" made site object ",entity,":",site)
return site
except:
return None
@ -611,7 +611,7 @@ def makeSpace(entity,shape=None,name="Space"):
body.Shape = shape
space.Base = body
body.ViewObject.hide()
if DEBUG: print " made space object ",entity,":",space
if DEBUG: print(" made space object ",entity,":",space)
return space
except:
return None
@ -626,7 +626,7 @@ def makeRoof(entity,shape=None,name="Roof"):
roof = Arch.makeRoof(name=name)
roof.Label = name
roof.Shape = shape
if DEBUG: print " made roof object ",entity,":",roof
if DEBUG: print(" made roof object ",entity,":",roof)
return roof
except:
return None
@ -637,11 +637,11 @@ def getMesh(obj):
"gets mesh and placement from an IfcOpenShell object"
if IFCOPENSHELL5:
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
meshdata = []
print obj.mesh.faces
print obj.mesh.verts
print(obj.mesh.faces)
print(obj.mesh.verts)
f = obj.mesh.faces
v = obj.mesh.verts
for i in range(0, len(f), 3):
@ -650,7 +650,7 @@ def getMesh(obj):
vi = f[i+j]*3
face.append([v[vi],v[vi+1],v[vi+2]])
meshdata.append(face)
print meshdata
print(meshdata)
me = Mesh.Mesh(meshdata)
# get transformation matrix
m = obj.matrix
@ -663,7 +663,7 @@ def getMesh(obj):
def getShape(obj,objid):
"gets a shape from an IfcOpenShell object"
#print "retrieving shape from obj ",objid
#print("retrieving shape from obj ",objid)
import Part
sh=Part.Shape()
brep_data = None
@ -684,7 +684,7 @@ def getShape(obj,objid):
else:
brep_data = IfcImport.create_shape(obj, ss)
except:
print "Unable to retrieve shape data"
print("Unable to retrieve shape data")
else:
brep_data = obj.mesh.brep_data
if brep_data:
@ -701,7 +701,7 @@ def getShape(obj,objid):
else:
sh.importBrepFromString(brep_data)
except:
print " error: malformed shape"
print(" error: malformed shape")
return None
else:
if IFCOPENSHELL5 and SEPARATE_PLACEMENTS:
@ -712,16 +712,16 @@ def getShape(obj,objid):
# try to extract a solid shape
if sh.Faces:
try:
if DEBUG: print " malformed solid. Attempting to fix..."
if DEBUG: print(" malformed solid. Attempting to fix...")
shell = Part.makeShell(sh.Faces)
if shell:
solid = Part.makeSolid(shell)
if solid:
sh = solid
except:
if DEBUG: print " failed to retrieve solid from object ",objid
if DEBUG: print(" failed to retrieve solid from object ",objid)
else:
if DEBUG: print " object ", objid, " doesn't contain any geometry"
if DEBUG: print(" object ", objid, " doesn't contain any geometry")
if not IFCOPENSHELL5:
m = obj.matrix
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],
0, 0, 0, 1)
sh.Placement = FreeCAD.Placement(mat)
# if DEBUG: print "getting Shape from ",obj
#print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull()
#for v in sh.Vertexes: print v.Point
# if DEBUG: print("getting Shape from ",obj)
#print("getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull())
#for v in sh.Vertexes: print(v.Point)
if sh:
if not sh.isNull():
return sh
@ -741,7 +741,7 @@ def getPlacement(entity):
"returns a placement from the given entity"
if not entity:
return None
if DEBUG: print " getting placement ",entity
if DEBUG: print(" getting placement ",entity)
if IFCOPENSHELL5:
if isinstance(entity,int):
entity = ifc.by_id(entity)
@ -772,7 +772,7 @@ def getPlacement(entity):
loc = getVector(entity)
pl = FreeCAD.Placement()
pl.move(loc)
if DEBUG: print " made placement for ",entityid,":",pl
if DEBUG: print(" made placement for ",entityid,":",pl)
return pl
def getAttr(entity,attr):
@ -789,7 +789,7 @@ def getVector(entity):
"returns a vector from the given entity"
if not entity:
return None
if DEBUG: print " getting point from ",entity
if DEBUG: print(" getting point from ",entity)
if IFCOPENSHELL5:
if isinstance(entity,int):
entity = ifc.by_id(entity)
@ -829,7 +829,7 @@ def getSchema():
custom = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetString("CustomIfcSchema","")
if 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
p = None
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
try:
if DEBUG: print "=====> making group",entity.id
if DEBUG: print("=====> making group",entity.id)
placement = None
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.extend(ifc.find("IFCRELAGGREGATES","RelatingObject",entity))
elts = []
@ -866,7 +866,7 @@ def group(entity,ifc,mode=None):
s = s.RelatedObject
if not isinstance(s,list): s = [s]
elts.extend(s)
print "found dependent elements: ",elts
print("found dependent elements: ",elts)
groups = [['Wall',['IfcWallStandardCase'],[]],
['Window',['IfcWindow','IfcDoor'],[]],
@ -881,11 +881,11 @@ def group(entity,ifc,mode=None):
if e.type.upper() == t.upper():
if hasattr(FreeCAD.ActiveDocument,g[0]+str(e.id)):
g[2].append(FreeCAD.ActiveDocument.getObject(g[0]+str(e.id)))
print "groups:",groups
print("groups:",groups)
comps = []
if CREATE_IFC_GROUPS:
if DEBUG: print "creating subgroups"
if DEBUG:wprint("creating subgroups")
for g in groups:
if g[2]:
if g[0] in ['Building','Floor']:
@ -911,12 +911,12 @@ def group(entity,ifc,mode=None):
if label and cell:
cell.Label = label
except:
if DEBUG: print "error: skipping group ",entity.id
if DEBUG: print("error: skipping group ",entity.id)
def getWire(entity,placement=None):
"returns a wire (created in the freecad document) from the given entity"
# 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 entity.type == "IFCPOLYLINE":
pts = []
@ -943,16 +943,16 @@ def export(exportList,filename):
import ifc_wrapper as ifcw
except ImportError:
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
available from https://github.com/aothms/IfcOpenShell"""
available from https://github.com/aothms/IfcOpenShell""")
return
if (not hasattr(ifcw,"IfcFile")) and (not hasattr(ifcw,"file")):
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
version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell"""
version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell""")
return
import Arch,Draft
@ -994,7 +994,7 @@ def export(exportList,filename):
else:
others.append(obj)
objectslist = buildings + floors + others
if DEBUG: print "adding ", len(objectslist), " objects"
if DEBUG: print("adding ", len(objectslist), " objects")
global unprocessed
unprocessed = []
@ -1032,7 +1032,7 @@ def export(exportList,filename):
if obj.IfcAttributes["FlagForceBrep"] == "True":
brepflag = True
if DEBUG: print "Adding " + obj.Label + " as Ifc" + ifctype
if DEBUG: print("Adding " + obj.Label + " as Ifc" + ifctype)
# writing IFC data
if obj.isDerivedFrom("App::DocumentObjectGroup"):
@ -1042,7 +1042,7 @@ def export(exportList,filename):
parent = ifc.findByName("IfcBuilding",str(parent.Label))
if otype == "Site":
print " Skipping (not implemented yet)" # TODO manage sites
print(" Skipping (not implemented yet)") # TODO manage sites
elif otype == "Building":
ifc.addBuilding( name=name )
elif otype == "Floor":
@ -1061,21 +1061,21 @@ def export(exportList,filename):
# get representation
if (not forcebrep) and (not brepflag):
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:
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 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)
continue
else:
if DEBUG: print " No geometry"
if DEBUG: print(" No geometry")
else:
if DEBUG: print " Brep"
if DEBUG: print(" Brep")
else:
if DEBUG: print " Extrusion"
if DEBUG: print(" Extrusion")
if gdata:
# gdata = [ type, profile data, extrusion data, placement data ]
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":
representation = ifc.addExtrudedCompositeCurve(gdata[1], gdata[2], color=color)
else:
print "debug: unknow extrusion type"
print("debug: unknow extrusion type")
elif fdata:
representation = [ifc.addFacetedBrep(f, color=color) for f in fdata]
@ -1110,7 +1110,7 @@ def export(exportList,filename):
elif otype == "Part":
extra = ["ELEMENT"]
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"
extra = ["ELEMENT"]
@ -1120,7 +1120,7 @@ def export(exportList,filename):
# removing openings
if SEPARATE_OPENINGS and gdata:
for o in obj.Subtractions:
print "Subtracting ",o.Label
print("Subtracting ",o.Label)
fdata = getIfcBrepFacesData(o,scaling,sub=True)
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)
@ -1142,14 +1142,14 @@ def export(exportList,filename):
else:
unprocessed.append(obj)
else:
if DEBUG: print "Object type ", otype, " is not supported yet."
if DEBUG: print("Object type ", otype, " is not supported yet.")
# processing groups
for name,entities in groups.iteritems():
if entities:
o = FreeCAD.ActiveDocument.getObject(name)
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 )
ifc.write()
@ -1178,10 +1178,9 @@ def export(exportList,filename):
FreeCAD.ActiveDocument.recompute()
if unprocessed:
print ""
print "WARNING: " + str(len(unprocessed)) + " objects were not exported (stored in importIFC.unprocessed):"
print("\nWARNING: " + str(len(unprocessed)) + " objects were not exported (stored in importIFC.unprocessed):")
for o in unprocessed:
print " " + o.Label
print(" " + o.Label)
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.
t.append(t[0])
else:
print "Arch.getTuples(): Wrong profile data"
print("Arch.getTuples(): Wrong profile data")
return t
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))
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()
#print "getExtrusionData: computed placement:",r
#print("getExtrusionData: computed placement:",r)
import Part
if len(p.Edges) == 1:
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):
curves = True
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:
# Composite profile
ecurves = []
@ -1350,7 +1349,7 @@ def getIfcBrepFacesData(obj,scale=1,sub=False,tessellation=1):
dataset = shape.Solids
else:
dataset = shape.Shells
print "Warning! object contains no solids"
print("Warning! object contains no solids")
for sol in shape.Solids:
s = []
curves = False
@ -1418,7 +1417,7 @@ class IfcSchema:
self.data = self.file.read()
self.types = self.readTypes()
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):
"""
@ -1512,7 +1511,7 @@ class IfcFile:
self.file = open(self.filename)
self.entById, self.entsByName, self.header = self.read()
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):
return self.entById.get(id, None)
@ -1658,7 +1657,7 @@ class IfcEntity:
propset.extend(p.RelatingPropertyDefinition.Quantities)
for prop in propset:
if prop.Name == propName:
print "found valid",prop
print("found valid",prop)
if hasattr(prop,"LengthValue"):
return prop.LengthValue
elif hasattr(prop,"AreaValue"):
@ -1685,12 +1684,12 @@ class IfcDocument:
for k,e in self.data.iteritems():
eid = int(e['id'])
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():
if DEBUG: print "attributing entity ",ent
if DEBUG: print("attributing entity ",ent)
if hasattr(ent,"attributes"):
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):
val = self.__clean__(v)
elif isinstance(v,list):
@ -1703,7 +1702,7 @@ class IfcDocument:
else:
val = v
setattr(ent,k.strip(),val)
if DEBUG: print "Document successfully created"
if DEBUG: print("Document successfully created")
def __clean__(self,value):
"turns an attribute value into something usable"
@ -1729,18 +1728,18 @@ class IfcDocument:
for subval in val:
if '#' in subval:
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)))
val = l
else:
val = val.strip()
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))
if not val:
val = value
except:
if DEBUG: print "error parsing attribute",value
if DEBUG: print("error parsing attribute",value)
val = value
return val
@ -1815,7 +1814,7 @@ def explorer(filename,schema="IFC2X3_TC1.exp"):
bold.setWeight(75)
bold.setBold(True)
#print ifc.Entities
#print(ifc.Entities)
for i in ifc.Entities.keys():
e = ifc.Entities[i]
@ -2039,14 +2038,14 @@ class IfcWriter(object):
try:
self._fileobject.write(path)
if APPLYFIX:
print ("IfcWriter: Applying fix...")
print("IfcWriter: Applying fix...")
self._fix(path)
except:
print ("IfcWriter: Error writing to "+path)
print("IfcWriter: Error writing to "+path)
else:
print ("IfcWriter: Successfully written to "+path)
print("IfcWriter: Successfully written to "+path)
else:
print ("IfcWriter: Error: File path is not defined, unable to save")
print("IfcWriter: Error: File path is not defined, unable to save")
def _fix(self,path):
"hack to fix early bugs in ifcopenshell"
@ -2176,17 +2175,17 @@ class IfcWriter(object):
try:
elt = create(self._fileobject,elttype,[uid(),self._owner,name,description,None,placement,prd,None]+extra)
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:
if hasattr(ifcw,"Entity"):
o = ifcw.Entity(elttype)
else:
o = ifcw.entity_instance(elttype)
print "supported attributes are: "
print getPropertyNames(o)
print("supported attributes are: ")
print(getPropertyNames(o))
except:
print "unable to create an element of type '"+elttype+"'"
print "WARNING: skipping object '"+name+"' of type "+elttype
print("unable to create an element of type '"+elttype+"'")
print("WARNING: skipping object '"+name+"' of type "+elttype)
return None
self.BuildingProducts.append(elt)
if not storey:
@ -2324,17 +2323,17 @@ class IfcWriter(object):
for f in face:
pts = []
for p in f:
#print p
#print(p)
if p in self.fpoints:
#print self.fpoints.index(p)
#print self.frefs
#print(self.fpoints.index(p))
#print(self.frefs)
pts.append(self.frefs[self.fpoints.index(p)])
else:
pt = create(self._fileobject,"IfcCartesianPoint",getTuple(p))
pts.append(pt)
self.fpoints.append(p)
self.frefs.append(pt)
#print pts
#print(pts)
loop = create(self._fileobject,"IfcPolyLoop",[pts])
if idx == 0:
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)"""
self.fpoints = []
self.frefs = []
#print "adding ",len(faces)," faces"
#print faces
#print("adding ",len(faces)," faces")
#print(faces)
ifaces = [self.addFace(face) for face in faces]
sh = create(self._fileobject,"IfcClosedShell",[ifaces])
brp = create(self._fileobject,"IfcFacetedBrep",[sh])

View File

@ -40,7 +40,7 @@ else:
p = Draft.precision()
if open.__module__ == '__builtin__':
if open.__module__ in ['__builtin__','io']:
pythonopen = open
def findVert(aVertex,aList):
@ -99,7 +99,7 @@ def getIndices(shape,offset):
else:
fi = ""
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]
ind = findVert(v,shape.Vertexes)
if ind == None:

View File

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

View File

@ -116,7 +116,7 @@ template = """<!DOCTYPE html>
</html>"""
if open.__module__ == '__builtin__':
if open.__module__ in ['__builtin__','io']:
pythonopen = open
def export(exportList,filename):
@ -155,7 +155,7 @@ def getCameraData():
else:
result += "camera.position.set(0,0,1000);\n"
result += tab+"camera.lookAt( scene.position );\n"+tab
# print result
# print(result)
return result
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 Draft import makeWire
if open.__module__ == '__builtin__':
if open.__module__ in ['__builtin__','io']:
pythonopen = open
useDraftWire = True

View File

@ -65,7 +65,7 @@ dxfReader = None
dxfColorMap = 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

View File

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

View File

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

View File

@ -413,7 +413,7 @@ def importFrd(filename, analysis=None, result_name_prefix=None):
if 'Nodes' in m:
positions = []
for k, v in m['Nodes'].iteritems():
for k, v in m['Nodes'].items():
positions.append(v)
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))
@ -454,7 +454,7 @@ def importFrd(filename, analysis=None, result_name_prefix=None):
strainv = result_set['strainv']
no_of_values = len(disp)
displacement = []
for k, v in disp.iteritems():
for k, v in disp.items():
displacement.append(v)
x_max, y_max, z_max = map(max, zip(*displacement))

View File

@ -23,10 +23,15 @@
# 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 xml.etree.ElementTree import parse
try:
import io as cStringIO
except:
import cStringIO
FreeCADGui.addLanguagePath(":/translations")
FreeCADGui.updateLocale()
@ -41,10 +46,16 @@ def translate(context,text):
s = cStringIO.StringIO()
for i in u:
if ord(i) == 39:
s.write("\\'")
if sys.version_info.major > 2: #below only works correctly in python3
if i == 39:
s.write("\\'")
else:
s.write(chr(i))
else:
s.write(i)
if ord(i) == 39:
s.write(unicode("\\'"))
else:
s.write(unicode(i))
t = s.getvalue()
s.close()
return t
@ -612,7 +623,7 @@ def getFeed(url,numitems=3):
resp += item['title']
resp += '</a></li>'
resp += '</ul>'
print resp
print(resp)
return resp
def getCustomBlocks():
@ -638,7 +649,7 @@ def setColors(html):
defaults["#textcolor"] = palette.text().color().name()
defaults["#windowcolor"] = palette.window().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))
return html