diff --git a/release/scripts/export_dxf.py b/release/scripts/export_dxf.py index 061e29b81c7..99c6acaceab 100644 --- a/release/scripts/export_dxf.py +++ b/release/scripts/export_dxf.py @@ -1,14 +1,14 @@ #!BPY """ - Name: 'Autodesk DXF (.dxf)' + Name: 'Autodesk (.dxf .dwg)' Blender: 247 Group: 'Export' - Tooltip: 'Export geometry to DXF-r12 (Drawing eXchange Format).' + Tooltip: 'Export geometry to Autocad DXF/DWG-r12 (Drawing eXchange Format).' """ -__version__ = "v1.27beta - 2008.10.07" -__author__ = "Remigiusz Fiedler (AKA migius)" +__version__ = "v1.29 - 2009.04.11" +__author__ = "Remigiusz Fiedler (AKA migius), Alexandros Sigalas (AKA alxarch), Stani Michiels" __license__ = "GPL" __url__ = "http://wiki.blender.org/index.php/Scripts/Manual/Export/autodesk_dxf" __bpydoc__ ="""The script exports Blender geometry to DXF format r12 version. @@ -25,8 +25,9 @@ url: %s IDEAs: - correct normals for POLYLINE-POLYFACE via proper point-order - HPGL output for 2d and flattened 3d content - + TODO: +- export dupligroups and dupliverts as blocks ( option for the user to decide ) - optimize back-faces removal (probably needs matrix transform) - optimize POLYFACE routine: remove double-vertices - optimize POLYFACE routine: remove unused vertices @@ -36,6 +37,11 @@ TODO: - write drawing extends for automatic view positioning in CAD History +v1.29 - 2009.04.11 by migius +- added DWG support, Stani Michiels idea for binding an extern DXF-DWG-converter +v1.28 - 2009.02.05 by alxarch +- added option to apply modifiers on exported meshes +- added option to also export duplicates (from dupliverts etc) v1.27 - 2008.10.07 by migius - exclude Stani's DXF-Library to extern module v1.26 - 2008.10.05 by migius @@ -86,14 +92,95 @@ ______________________________________________________________ import Blender -from Blender import Mathutils, Window, Scene, sys, Draw +from Blender import Mathutils, Window, Scene, sys, Draw, Mesh import BPyMessages +import os +import subprocess + +#print os.sys.platform +#print dir(os.sys.version) #import dxfLibrary #reload(dxfLibrary) from dxfLibrary import * +#-------- DWG support ------------------------------------------ +extCONV_OK = True +extCONV = 'DConvertCon.exe' +extCONV_PATH = os.path.join(Blender.Get('scriptsdir'),extCONV) +if not os.path.isfile(extCONV_PATH): + extCONV_OK = False + extCONV_TEXT = 'DWG-Exporter: Abort, nothing done!|\ +Copy first %s into Blender script directory.|\ +More details in online Help.' %extCONV +else: + if not os.sys.platform.startswith('win'): + # check if Wine installed: + if subprocess.Popen(('which', 'winepath'), stdout=subprocess.PIPE).stdout.read().strip(): + extCONV_PATH = 'wine %s'%extCONV_PATH + else: + extCONV_OK = False + extCONV_TEXT = 'DWG-Exporter: Abort, nothing done!|\ +The external DWG-converter (%s) needs Wine installed on your system.|\ +More details in online Help.' %extCONV +#print 'extCONV_PATH = ', extCONV_PATH + + + +#----------------------------------------------------- +def dupTest(object): + """ + Checks objects for duplicates enabled (any type) + object: Blender Object. + Returns: Boolean - True if object has any kind of duplicates enabled. + """ + if (object.enableDupFrames or \ + object.enableDupGroup or \ + object.enableDupVerts): + return True + else: + return False + +def getObjectsAndDuplis(oblist,MATRICES=False,HACK=False): + """ + Return a list of real objects and duplicates and optionally their matrices + oblist: List of Blender Objects + MATRICES: Boolean - Check to also get the objects matrices default=False + HACK: Boolean - See note default=False + Returns: List of objects or + List of tuples of the form:(ob,matrix) if MATRICES is set to True + NOTE: There is an ugly hack here that excludes all objects whose name + starts with "dpl_" to exclude objects that are parented to a duplicating + object, User must name objects properly if hack is used. + """ + + result = [] + for ob in oblist: + if dupTest(ob): + dup_obs=ob.DupObjects + if len(dup_obs): + for dup_ob, dup_mx in dup_obs: + if MATRICES: + result.append((dup_ob,dup_mx)) + else: + result.append(dup_ob) + else: + if HACK: + if ob.getName()[0:4] != "dpl_": + if MATRICES: + mx = ob.mat + result.append((ob,mx)) + else: + result.append(ob) + else: + if MATRICES: + mx = ob.mat + result.append((ob,mx)) + else: + result.append(ob) + return result + #----------------------------------------------------- def hidden_status(faces, mx_n): #print 'HIDDEN_MODE: caution! not full implemented yet' @@ -146,9 +233,13 @@ def flatten(points, mw): return points #----------------------------------------------------- -def exportMesh(ob, mx, mx_n): +def exportMesh(ob, mx, mx_n,me=None): entities = [] - me = ob.getData(mesh=1) + global APPLY_MODIFIERS + if me is None: + me = ob.getData(mesh=1) + else: + me.getFromObject(ob) #me.transform(mx) # above is eventualy faster, but bad, cause # directly transforms origin geometry and write back rounding errors @@ -209,7 +300,7 @@ def exportMesh(ob, mx, mx_n): points = [ me_verts[key].co[:3] for key in e] dxfLINE = Line(points) entities.append(dxfLINE) - + else: for e in me.edges: #print 'deb: edge=', e #--------- @@ -257,7 +348,7 @@ def exportCurve(ob, mx): return entities #----------------------------------------------------- -def do_export(sel_group, filepath): +def do_export(export_list, filepath): Window.WaitCursor(1) t = sys.time() @@ -281,22 +372,27 @@ def do_export(sel_group, filepath): m0[2][2]=0.0 mw *= m0 #flatten ViewMatrix - for ob in sel_group: + if APPLY_MODIFIERS: + tmp_me = Mesh.New('tmp') + else: + tmp_me = None + + for ob,mx in export_list: entities = [] - mx = ob.matrix.copy() + #mx = ob.matrix.copy() mb = mx.copy() #print 'deb: mb =\n', mb #--------- #print 'deb: mw0 =\n', mw0 #--------- mx_n = mx.rotationPart() * mw0.rotationPart() #trans-matrix for normal_vectors if SCALE_FACTOR!=1.0: mx *= SCALE_FACTOR if FLATTEN: mx *= mw - + #mx_inv = mx.copy().invert() #print 'deb: mx =\n', mx #--------- #print 'deb: mx_inv=\n', mx_inv #--------- if (ob.type == 'Mesh'): - entities = exportMesh(ob, mx, mx_n) + entities = exportMesh(ob, mx, mx_n,tmp_me) elif (ob.type == 'Curve'): entities = exportCurve(ob, mx) @@ -305,11 +401,30 @@ def do_export(sel_group, filepath): something_ready = True if something_ready: - d.saveas(filepath) - Window.WaitCursor(0) - #Draw.PupMenu('DXF Exporter: job finished') - print 'exported to %s' % filepath - print 'finished in %.2f seconds' % (sys.time()-t) + if not OUTPUT_DWG: + print 'exporting to %s' % filepath + d.saveas(filepath) + Window.WaitCursor(0) + #Draw.PupMenu('DXF Exporter: job finished') + print ' finished in %.2f seconds. -----DONE-----' % (sys.time()-t) + else: + if not extCONV_OK: + Draw.PupMenu(extCONV_TEXT) + Window.WaitCursor(False) + else: + print 'temp. exporting to %s' % filepath + d.saveas(filepath) + #Draw.PupMenu('DXF Exporter: job finished') + #print 'exported to %s' % filepath + #print 'finished in %.2f seconds' % (sys.time()-t) + filedwg = filepath[:-3]+'dwg' + print 'exporting to %s' % filedwg + os.system('%s %s -acad13 -dwg' %(extCONV_PATH,filepath)) + #os.chdir(cwd) + os.remove(filepath) + Window.WaitCursor(0) + print ' finished in %.2f seconds. -----DONE-----' % (sys.time()-t) + else: Window.WaitCursor(0) print "Abort: selected objects dont mach choosen export option, nothing exported!" @@ -323,8 +438,9 @@ POLYFACES = 1 FLATTEN = 0 HIDDEN_MODE = False #filter out hidden lines SCALE_FACTOR = 1.0 #optional, can be done later in CAD too - - +APPLY_MODIFIERS = True +INCLUDE_DUPLIS = False +OUTPUT_DWG = False #optional save to DWG with extern converter #----------------------------------------------------- def dxf_export_ui(filepath): @@ -334,9 +450,12 @@ def dxf_export_ui(filepath): POLYFACES,\ FLATTEN,\ HIDDEN_MODE,\ - SCALE_FACTOR + SCALE_FACTOR,\ + APPLY_MODIFIERS,\ + OUTPUT_DWG,\ + INCLUDE_DUPLIS - print '\n\nDXF-Export %s -----------------------' %__version__ + print '\n\nDXF-Export %s -----------START-----------' %__version__ #filepath = 'blend_test.dxf' # Dont overwrite if not BPyMessages.Warning_SaveOver(filepath): @@ -352,19 +471,26 @@ def dxf_export_ui(filepath): PREF_FLATTEN= Draw.Create(FLATTEN) PREF_HIDDEN_MODE= Draw.Create(HIDDEN_MODE) PREF_SCALE_FACTOR= Draw.Create(SCALE_FACTOR) + PREF_APPLY_MODIFIERS= Draw.Create(APPLY_MODIFIERS) + PREF_INCLUDE_DUPLIS= Draw.Create(INCLUDE_DUPLIS) PREF_HELP= Draw.Create(0) + PREF_DWG= Draw.Create(OUTPUT_DWG) block = [\ ("only selected", PREF_ONLYSELECTED, "export only selected geometry"),\ + ("Apply Modifiers", PREF_APPLY_MODIFIERS, "Apply modifier stack to mesh objects before export"),\ + ("Include Duplis", PREF_INCLUDE_DUPLIS, "Export also Duplicates (dupliverts, dupliframes etc)"),\ ("global Scale:", PREF_SCALE_FACTOR, 0.001, 1000, "set global Scale factor for exporting geometry"),\ - ("only faces", PREF_ONLYFACES, "from mesh-objects export only faces, otherwise only edges"),\ - ("write POLYFACE", PREF_POLYFACES, "export mesh to POLYFACE, otherwise to 3DFACEs"),\ - ("write POLYLINEs", PREF_POLYLINES, "export curve to POLYLINE, otherwise to LINEs"),\ + (''),\ + ("export to 3DFaces", PREF_ONLYFACES, "from mesh-objects export only faces, otherwise only edges"),\ + ("mesh to POLYFACE", PREF_POLYFACES, "export mesh to POLYFACE, otherwise to 3DFACEs"),\ + ("curves to POLYLINEs", PREF_POLYLINES, "export curve to POLYLINE, otherwise to LINEs"),\ ("3D-View to Flat", PREF_FLATTEN, "flatten geometry according current 3d-View"),\ ("Hidden Mode", PREF_HIDDEN_MODE, "filter out hidden lines"),\ - #(''),\ ("online Help", PREF_HELP, "calls DXF-Exporter Manual Page on Wiki.Blender.org"),\ + (''),\ + ("DXF->DWG", PREF_DWG, "writes DWG with extern converter"),\ ] - + if not Draw.PupBlock("DXF-Exporter %s" %__version__[:10], block): return if PREF_HELP.val!=0: @@ -372,7 +498,7 @@ def dxf_export_ui(filepath): import webbrowser webbrowser.open('http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf') except: - Draw.PupMenu('DXF Exporter: %t|no connection to manual-page on Blender-Wiki! try:|\ + Draw.PupMenu('DXF Exporter: %t|no connection to manual-page on Blender-Wiki! try:|\ http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf') return @@ -383,12 +509,14 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Export/autodesk_dxf') FLATTEN = PREF_FLATTEN.val HIDDEN_MODE = PREF_HIDDEN_MODE.val SCALE_FACTOR = PREF_SCALE_FACTOR.val - + OUTPUT_DWG = PREF_DWG.val + sce = Scene.GetCurrent() if ONLYSELECTED: sel_group = sce.objects.selected else: sel_group = sce.objects + export_list = getObjectsAndDuplis(sel_group,MATRICES=True) - if sel_group: do_export(sel_group, filepath) + if export_list: do_export(export_list, filepath) else: print "Abort: selection was empty, no object to export!" Draw.PupMenu('DXF Exporter: nothing exported!|empty selection!') @@ -401,7 +529,4 @@ if __name__=='__main__': #main() if not copy: Draw.PupMenu('Error%t|This script requires a full python install') - Window.FileSelector(dxf_export_ui, 'EXPORT DXF', sys.makename(ext='.dxf')) - - - \ No newline at end of file + else: Window.FileSelector(dxf_export_ui, 'EXPORT DXF', sys.makename(ext='.dxf')) \ No newline at end of file diff --git a/release/scripts/import_dxf.py b/release/scripts/import_dxf.py index c3203891c60..ceb4dd56722 100644 --- a/release/scripts/import_dxf.py +++ b/release/scripts/import_dxf.py @@ -1,20 +1,21 @@ #!BPY """ -Name: 'Autodesk DXF (.dxf)' +Name: 'Autodesk DXF (.dxf .dwg)' Blender: 246 Group: 'Import' -Tooltip: 'Import for DXF geometry data (Drawing eXchange Format).' +Tooltip: 'Import for DWG/DXF geometry data.' """ __author__ = 'Kitsu(Ed Blake) & migius(Remigiusz Fiedler)' -__version__ = '1.12 - 2009.03.14 by migius' +__version__ = '1.12 - 2009.04.11 by migius' __url__ = ["http://blenderartists.org/forum/showthread.php?t=84319", "http://wiki.blender.org/index.php/Scripts/Manual/Import/DXF-3D"] __email__ = ["migius(at)4d-vectors.de","Kitsune_e(at)yahoo.com"] __bpydoc__ = """\ -This script imports objects from DXF (2d/3d) into Blender. +This script imports objects from DWG/DXF (2d/3d) into Blender. This script imports 2d and 3d geometery from DXF files. +It supports DWG format too, with help of an external converter. Supported DXF format versions: from (r2.5) r12 up to r2008. Enhanced features are: - configurable object filtering and geometry manipulation, @@ -111,6 +112,8 @@ History: -- support ortho mode for VIEWs and VPORTs as cameras + v1.12 - 2009.04.11 by migius + d4 added DWG support, Stani Michiels idea for binding an extern DXF-DWG-converter v1.12 - 2009.03.14 by migius d3 removed all set()functions (problem with osx/python<2.4 reported by Blinkozo) d3 code-cleaning @@ -305,7 +308,8 @@ History: # -------------------------------------------------------------------------- import Blender -from Blender import * +from Blender import Mathutils, BezTriple, Draw, Registry, sys,\ +Text3d, Window, Mesh, Material, Group #from Blender.Mathutils import Vector, Matrix #import bpy #not used yet #import BPyMessages @@ -314,7 +318,7 @@ from dxfReader import readDXF #from dxfReader import get_name, get_layer from dxfReader import Object as dxfObject from dxfColorMap import color_map -from math import * +from math import log10, sqrt, radians, degrees, atan, cos, sin # osx-patch by Blinkozo #todo: avoid additional modules, prefer Blender-build-in test routines @@ -325,9 +329,10 @@ from math import * #ver = '%s.%s' % version_info[0:2] # end osx-patch -try: - import os - if os.name != 'mac': +import subprocess +import os +if os.name != 'mac': + try: import psyco psyco.log(Blender.Get('tempdir')+"/blender.log-psyco") #psyco.log() @@ -335,14 +340,13 @@ try: psyco.profile(0.05, memory=100) psyco.profile(0.2) #print 'psyco imported' -except ImportError: - print 'psyco not imported' - pass + except ImportError: + print 'psyco not imported' #try: Curve.orderU print '\n\n\n' -print 'DXF-Importer v%s *** start ***' %(__version__) #--------------------- +print 'DXF/DWG-Importer v%s *** start ***' %(__version__) #--------------------- SCENE = None WORLDX = Mathutils.Vector((1,0,0)) @@ -386,6 +390,29 @@ FREE = BezTriple.HandleTypes.FREE VECT = BezTriple.HandleTypes.VECT ALIGN = BezTriple.HandleTypes.ALIGN +UI_MODE = True #activates UI-popup-print, if not multiple files imported + + +#-------- DWG support ------------------------------------------ +extCONV_OK = True +extCONV = 'DConvertCon.exe' +extCONV_PATH = os.path.join(Blender.Get('scriptsdir'),extCONV) +if not os.path.isfile(extCONV_PATH): + extCONV_OK = False + extCONV_TEXT = 'DWG-Importer cant find external DWG-converter (%s) in Blender script directory.|\ +More details in online Help.' %extCONV +else: + if not os.sys.platform.startswith('win'): + # check if Wine installed: + if subprocess.Popen(('which', 'winepath'), stdout=subprocess.PIPE).stdout.read().strip(): + extCONV_PATH = 'wine %s'%extCONV_PATH + else: + extCONV_OK = False + extCONV_TEXT = 'The external DWG-converter (%s) needs Wine installed on your system.|\ +More details in online Help.' %extCONV +#print 'extCONV_PATH = ', extCONV_PATH + + class View: #----------------------------------------------------------------- """Class for objects representing dxf VIEWs. @@ -754,7 +781,7 @@ class Solid: #----------------------------------------------------------------- if settings.var['vGroup_on'] and not M_OBJ: # each MeshSide becomes vertexGroup for easier material assignment --------------------- - replace = Blender.Mesh.AssignModes.ADD #or .AssignModes.ADD/REPLACE + replace = Mesh.AssignModes.ADD #or .AssignModes.ADD/REPLACE if vg_left: me.addVertGroup('side.left') ; me.assignVertsToGroup('side.left', vg_left, 1.0, replace) if vg_right:me.addVertGroup('side.right') ; me.assignVertsToGroup('side.right', vg_right, 1.0, replace) if vg_top: me.addVertGroup('side.top') ; me.assignVertsToGroup('side.top', vg_top, 1.0, replace) @@ -899,7 +926,7 @@ class Line: #----------------------------------------------------------------- ob.link(me) # link mesh to that object vG_name = 'color_%s' %self.color_index if edges: faces = edges - replace = Blender.Mesh.AssignModes.ADD #or .AssignModes.REPLACE or ADD + replace = Mesh.AssignModes.ADD #or .AssignModes.REPLACE or ADD try: me.assignVertsToGroup(vG_name, faces[0], 1.0, replace) #print 'deb: existed vGroup:', vG_name #--------------------- @@ -1792,7 +1819,7 @@ class Polyline: #-------------------------------------------------------------- # which may be linked to more than one object. if settings.var['vGroup_on'] and not M_OBJ: # each MeshSide becomes vertexGroup for easier material assignment --------------------- - replace = Blender.Mesh.AssignModes.REPLACE #or .AssignModes.ADD + replace = Mesh.AssignModes.REPLACE #or .AssignModes.ADD vg_left, vg_right, vg_top, vg_bottom = [], [], [], [] for v in f_left: vg_left.extend(v) for v in f_right: vg_right.extend(v) @@ -2640,7 +2667,7 @@ class Circle: #---------------------------------------------------------------- # each MeshSide becomes vertexGroup for easier material assignment --------------------- if settings.var['vGroup_on'] and not M_OBJ: # each MeshSide becomes vertexGroup for easier material assignment --------------------- - replace = Blender.Mesh.AssignModes.REPLACE #or .AssignModes.ADD + replace = Mesh.AssignModes.REPLACE #or .AssignModes.ADD vg_band, vg_top, vg_bottom = [], [], [] for v in f_band: vg_band.extend(v) me.addVertGroup('side.band') ; me.assignVertsToGroup('side.band', vg_band, 1.0, replace) @@ -2820,7 +2847,7 @@ class Arc: #----------------------------------------------------------------- # each MeshSide becomes vertexGroup for easier material assignment --------------------- if settings.var['vGroup_on'] and not M_OBJ: # each MeshSide becomes vertexGroup for easier material assignment --------------------- - replace = Blender.Mesh.AssignModes.REPLACE #or .AssignModes.ADD + replace = Mesh.AssignModes.REPLACE #or .AssignModes.ADD vg_left, vg_right, vg_top, vg_bottom = [], [], [], [] for v in f_left: vg_left.extend(v) for v in f_right: vg_right.extend(v) @@ -3364,7 +3391,7 @@ class Ellipse: #--------------------------------------------------------------- me.faces[i].smooth = True if settings.var['vGroup_on'] and not M_OBJ: # each MeshSide becomes vertexGroup for easier material assignment --------------------- - replace = Blender.Mesh.AssignModes.REPLACE #or .AssignModes.ADD + replace = Mesh.AssignModes.REPLACE #or .AssignModes.ADD vg_left, vg_right, vg_top, vg_bottom = [], [], [], [] for v in f_left: vg_left.extend(v) for v in f_right: vg_right.extend(v) @@ -3517,7 +3544,7 @@ class Face: #----------------------------------------------------------------- ob.link(me) # link mesh to that object vG_name = 'color_%s' %self.color_index if edges: faces = edges - replace = Blender.Mesh.AssignModes.ADD #or .AssignModes.REPLACE or ADD + replace = Mesh.AssignModes.ADD #or .AssignModes.REPLACE or ADD try: me.assignVertsToGroup(vG_name, faces[0], 1.0, replace) #print 'deb: existed vGroup:', vG_name #--------------------- @@ -4022,10 +4049,8 @@ class Settings: #-------------------------------------------------------------- """Wraps the built-in print command in a optimization check. """ if self.var['optimization'] <= self.MID: - if newline: - print text - else: - print text, + if newline: print text + else: print text, def redraw(self): @@ -4067,9 +4092,9 @@ def analyzeDXF(dxfFile): #--------------------------------------- """ Window.WaitCursor(True) # Let the user know we are thinking print 'reading DXF file: %s.' % dxfFile - time1 = Blender.sys.time() #time marker1 + time1 = sys.time() #time marker1 drawing = readDXF(dxfFile, objectify) - print 'finish reading in %.4f sec.' % (Blender.sys.time()-time1) + print 'finish reading in %.4f sec.' % (sys.time()-time1) # First sort out all the section_items sections = dict([(item.name, item) for item in drawing.data]) @@ -4282,10 +4307,45 @@ def main(dxfFile): #---------------#############################----------- if dxfFile.lower().endswith('.dxf') and sys.exists(dxfFile): Window.WaitCursor(True) # Let the user know we are thinking print 'reading file: %s.' % dxfFile - time1 = Blender.sys.time() #time marker1 + time1 = sys.time() #time marker1 drawing = readDXF(dxfFile, objectify) - print 'reading finished in %.4f sec.' % (Blender.sys.time()-time1) + print 'reading finished in %.4f sec.' % (sys.time()-time1) Window.WaitCursor(False) + elif dxfFile.lower().endswith('.dwg') and sys.exists(dxfFile): + if not extCONV_OK: + Draw.PupMenu(extCONV_TEXT) + Window.WaitCursor(False) + if editmode: Window.EditMode(1) # and put things back how we fond them + return None + else: + Window.WaitCursor(True) # Let the user know we are thinking + #todo: issue: in DConvertCon.exe the output filename is fixed to dwg_name.dxf + + if 0: # works only for Windows + dwgTemp = 'temp_01.dwg' + dxfTemp = 'temp_01.dxf' + os.system('copy %s %s' %(dxfFile,dwgTemp)) + else: + dwgTemp = dxfFile + dxfTemp = dxfFile[:-3]+'dxf' + #print 'temp. converting: %s\n to: %s' %(dxfFile, dxfTemp) + #os.system('%s %s -acad11 -dxf' %(extCONV_PATH, dxfFile)) + os.system('%s %s -dxf' %(extCONV_PATH, dwgTemp)) + #os.system('%s %s -dxf' %(extCONV_PATH, dxfFile_temp)) + if sys.exists(dxfTemp): + print 'reading file: %s.' % dxfTemp + time1 = sys.time() #time marker1 + drawing = readDXF(dxfTemp, objectify) + #os.remove(dwgTemp) + os.remove(dxfTemp) # clean up + print 'reading finished in %.4f sec.' % (sys.time()-time1) + Window.WaitCursor(False) + else: + if UI_MODE: Draw.PupMenu('DWG importer: nothing imported!%t|No valid DXF-representation found!') + print 'DWG importer: nothing imported. No valid DXF-representation found.' + Window.WaitCursor(False) + if editmode: Window.EditMode(1) # and put things back how we fond them + return None else: if UI_MODE: Draw.PupMenu('DXF importer: Alert!%t| no valid DXF-file selected!') print "DXF importer: Alert! - no valid DXF-file selected." @@ -4295,7 +4355,7 @@ def main(dxfFile): #---------------#############################----------- # Draw all the know entity types in the current scene oblist = [] # a list of all created AND linked objects for final f_globalScale - time2 = Blender.sys.time() #time marker2 + time2 = sys.time() #time marker2 Window.WaitCursor(True) # Let the user know we are thinking settings.write("\n\nDrawing entities...") @@ -4322,7 +4382,7 @@ def main(dxfFile): #---------------#############################----------- #SCENE.objects.selected = SCENE.objects #select all objects in current scene Blender.Redraw() - time_text = Blender.sys.time() - time2 + time_text = sys.time() - time2 Window.WaitCursor(False) if settings.var['paper_space_on']: space = 'from paper space' else: space = 'from model space' @@ -4571,7 +4631,7 @@ def drawer(_type, entities, settings, block_def): #---------------------------- activObjectLayer = '' activObjectName = '' - message = "Drawing dxf\'%ss\'..." %_type + message = "Drawing dxf \'%ss\'..." %_type cur_COUNTER += len_temp - len(entities) settings.write(message, False) settings.progress(cur_COUNTER, message) @@ -5078,7 +5138,7 @@ def drawCurveArc(self): #---- only for ELLIPSE -------------------------------- # GUI STUFF -----#################################################----------------- -from Blender.BGL import * +from Blender.BGL import glColor3f, glRecti, glClear, glRasterPos2d EVENT_NONE = 1 EVENT_START = 2 @@ -5577,7 +5637,7 @@ def draw_UI(): #--------------------------------------------------------------- y += 30 colorbox(x, y+20, x+menu_w+menu_margin*2, menu_margin) - Draw.Label("DXF-Importer v" + __version__, but0c, y, menu_w, 20) + Draw.Label("DXF/DWG-Importer v" + __version__, but0c, y, menu_w, 20) if config_UI.val: b0, b0_ = but0c, but_0c + butt_margin @@ -5853,9 +5913,9 @@ def draw_UI(): #--------------------------------------------------------------- #y -= 10 Draw.BeginAlign() - Draw.PushButton('DXFfile >', EVENT_CHOOSE_DXF, but0c, y, but_0c, 20, 'Select DXF-file from project directory') - dxfFileName = Draw.String(' :', EVENT_NONE, but1c, y, but_1c+but_2c+but_3c-20, 20, dxfFileName.val, FILENAME_MAX, "type the name of DXF-file or type *.dxf for multi-import") - Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'import all dxf files from this directory') + Draw.PushButton('DXFfile >', EVENT_CHOOSE_DXF, but0c, y, but_0c, 20, 'Select DXF/DWG-file for import') + dxfFileName = Draw.String(' :', EVENT_NONE, but1c, y, but_1c+but_2c+but_3c-20, 20, dxfFileName.val, FILENAME_MAX, "type the name of DXF/DWG-file or type *.dxf/*.dwg for multiple files") + Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'set filter for import all files from this directory') Draw.EndAlign() y -= 30 @@ -5902,8 +5962,9 @@ def colorbox(x,y,xright,bottom): def dxf_callback(input_filename): global dxfFileName - dxfFileName.val=input_filename -# dirname == Blender.sys.dirname(Blender.Get('filename')) + if input_filename.lower()[-3:] in ('dwg','dxf'): + dxfFileName.val=input_filename +# dirname == sys.dirname(Blender.Get('filename')) # update_RegistryKey('DirName', dirname) # update_RegistryKey('dxfFileName', input_filename) @@ -5913,17 +5974,17 @@ def ini_callback(input_filename): def event(evt, val): if evt in (Draw.QKEY, Draw.ESCKEY) and not val: - Blender.Draw.Exit() + Draw.Exit() def bevent(evt): # global EVENT_NONE,EVENT_LOAD_DXF,EVENT_LOAD_INI,EVENT_SAVE_INI,EVENT_EXIT global config_UI, user_preset - global GUI_A + global GUI_A, UI_MODE ######### Manages GUI events if (evt==EVENT_EXIT): - Blender.Draw.Exit() - print 'DXF-Importer *** exit ***' #--------------------- + Draw.Exit() + print 'DXF/DWG-Importer *** exit ***' #--------------------- elif (evt==EVENT_CHOOSE_INI): Window.FileSelector(ini_callback, "INI-file Selection", '*.ini') elif (evt==EVENT_REDRAW): @@ -5980,13 +6041,14 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D') Draw.Redraw() elif (evt==EVENT_DXF_DIR): dxfFile = dxfFileName.val + dxfFileExt = '*'+dxfFile.lower()[-4:] #can be .dxf or .dwg dxfPathName = '' if '/' in dxfFile: dxfPathName = '/'.join(dxfFile.split('/')[:-1]) + '/' elif '\\' in dxfFile: dxfPathName = '\\'.join(dxfFile.split('\\')[:-1]) + '\\' - dxfFileName.val = dxfPathName + '*.dxf' -# dirname == Blender.sys.dirname(Blender.Get('filename')) + dxfFileName.val = dxfPathName + dxfFileExt +# dirname == sys.dirname(Blender.Get('filename')) # update_RegistryKey('DirName', dirname) # update_RegistryKey('dxfFileName', dxfFileName.val) GUI_A['newScene_on'].val = 1 @@ -5994,45 +6056,55 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D') elif (evt==EVENT_CHOOSE_DXF): filename = '' # '*.dxf' if dxfFileName.val: filename = dxfFileName.val - Window.FileSelector(dxf_callback, "DXF-file Selection", filename) + Window.FileSelector(dxf_callback, "DXF/DWG-file Selection", filename) elif (evt==EVENT_START): dxfFile = dxfFileName.val #print 'deb: dxfFile file: ', dxfFile #---------------------- if E_M: dxfFileName.val, dxfFile = e_mode(dxfFile) #evaluation mode update_RegistryKey('dxfFileName', dxfFileName.val) if dxfFile.lower().endswith('*.dxf'): - if Draw.PupMenu('DXF importer: OK?|will import all DXF-files from:|%s' % dxfFile) == 1: - global UI_MODE + if Draw.PupMenu('DXF importer will import all DXF-files from:|%s|OK?' % dxfFile) != -1: UI_MODE = False - multi_import(dxfFile[:-5]) # cut last 5 characters '*.dxf' + multi_import(dxfFile) + UI_MODE = True Draw.Redraw() - #Draw.Exit() - else: + + elif dxfFile.lower().endswith('*.dwg'): + if not extCONV_OK: Draw.PupMenu(extCONV_TEXT) + elif Draw.PupMenu('DWG importer will import all DWG-files from:|%s|OK?' % dxfFile) != -1: + #elif Draw.PupMenu('DWG importer will import all DWG-files from:|%s|Caution! overwrites existing DXF-files!| OK?' % dxfFile) != -1: + UI_MODE = False + multi_import(dxfFile) + UI_MODE = True Draw.Redraw() - elif dxfFile.lower().endswith('.dxf') and sys.exists(dxfFile): - print '\nStandard Mode: active' - if GUI_A['newScene_on'].val: - _dxf_file = dxfFile.split('/')[-1].split('\\')[-1] - _dxf_file = _dxf_file[:-4] # cut last char:'.dxf' - _dxf_file = _dxf_file[:MAX_NAMELENGTH] #? [-MAX_NAMELENGTH:]) - global SCENE - SCENE = Blender.Scene.New(_dxf_file) - SCENE.makeCurrent() - Blender.Redraw() - #or so? Blender.Scene.makeCurrent(_dxf_file) - #sce = bpy.data.scenes.new(_dxf_file) - #bpy.data.scenes.active = sce + + elif sys.exists(dxfFile) and dxfFile.lower()[-4:] in ('.dxf','.dwg'): + if dxfFile.lower().endswith('.dwg') and (not extCONV_OK): + Draw.PupMenu(extCONV_TEXT) else: - SCENE = Blender.Scene.GetCurrent() - SCENE.objects.selected = [] # deselect all - main(dxfFile) - #SCENE.objects.selected = SCENE.objects - #Window.RedrawAll() - #Blender.Redraw() - #Draw.Redraw() + #print '\nStandard Mode: active' + if GUI_A['newScene_on'].val: + _dxf_file = dxfFile.split('/')[-1].split('\\')[-1] + _dxf_file = _dxf_file[:-4] # cut last char:'.dxf' + _dxf_file = _dxf_file[:MAX_NAMELENGTH] #? [-MAX_NAMELENGTH:]) + global SCENE + SCENE = Blender.Scene.New(_dxf_file) + SCENE.makeCurrent() + Blender.Redraw() + #or so? Blender.Scene.makeCurrent(_dxf_file) + #sce = bpy.data.scenes.new(_dxf_file) + #bpy.data.scenes.active = sce + else: + SCENE = Blender.Scene.GetCurrent() + SCENE.objects.selected = [] # deselect all + main(dxfFile) + #SCENE.objects.selected = SCENE.objects + #Window.RedrawAll() + #Blender.Redraw() + #Draw.Redraw() else: - Draw.PupMenu('DXF importer: Alert!%t|no valid DXF-file selected!') - print "DXF importer: error, no valid DXF-file selected! try again" + Draw.PupMenu('DXF importer: nothing imported!%t|no valid DXF-file selected!') + print "DXF importer: nothing imported, no valid DXF-file selected! try again" Draw.Redraw() @@ -6043,20 +6115,25 @@ def multi_import(DIR): """ global SCENE - batchTIME = Blender.sys.time() + batchTIME = sys.time() #if #DIR == "": DIR = os.path.curdir - if DIR == "": DIR = Blender.sys.dirname(Blender.Get('filename')) - print 'Multifiles Import from %s' %DIR + if DIR == "": + DIR = sys.dirname(Blender.Get('filename')) + EXT = '.dxf' + else: + EXT = DIR[-4:] # get last 4 characters '.dxf' + DIR = DIR[:-5] # cut last 5 characters '*.dxf' + print 'importing multiple %s files from %s' %(EXT,DIR) files = \ - [sys.join(DIR, f) for f in os.listdir(DIR) if f.lower().endswith('.dxf')] + [sys.join(DIR, f) for f in os.listdir(DIR) if f.lower().endswith(EXT)] if not files: - print '...None DXF-files found. Abort!' + print '...None %s-files found. Abort!' %EXT return i = 0 for dxfFile in files: i += 1 - print '\nDXF-file', i, 'of', len(files) #,'\nImporting', dxfFile + print '\n%s-file' %EXT, i, 'of', len(files) #,'\nImporting', dxfFile if GUI_A['newScene_on'].val: _dxf_file = dxfFile.split('/')[-1].split('\\')[-1] _dxf_file = _dxf_file[:-4] # cut last char:'.dxf' @@ -6072,13 +6149,11 @@ def multi_import(DIR): main(dxfFile) #Blender.Redraw() - print 'TOTAL TIME: %.6f' % (Blender.sys.time() - batchTIME) + print 'TOTAL TIME: %.6f' % (sys.time() - batchTIME) print '\a\r', # beep when done + Draw.PupMenu('DXF importer: Done!|finished in %.4f sec.' % (sys.time() - batchTIME)) - -UI_MODE = True - if __name__ == "__main__": UI_MODE = True # recall last used DXF-file and INI-file names @@ -6086,7 +6161,7 @@ if __name__ == "__main__": #print 'deb:start dxffilename:', dxffilename #---------------- if dxffilename: dxfFileName.val = dxffilename else: - dirname = Blender.sys.dirname(Blender.Get('filename')) + dirname = sys.dirname(Blender.Get('filename')) #print 'deb:start dirname:', dirname #---------------- dxfFileName.val = sys.join(dirname, '') inifilename = check_RegistryKey('iniFileName') @@ -6099,7 +6174,7 @@ if __name__ == "__main__": if 1: # DEBUG ONLY UI_MODE = False - TIME= Blender.sys.time() + TIME= sys.time() #DIR = '/dxf_r12_testfiles/' DIR = '/metavr/' import os @@ -6128,5 +6203,5 @@ if 1: dxfFileName.val = _dxf main(_dxf) - print 'TOTAL TIME: %.6f' % (Blender.sys.time() - TIME) + print 'TOTAL TIME: %.6f' % (sys.time() - TIME) """ \ No newline at end of file