Newer
Older
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
return
# 0
# SECTION
# 2
# BLOCKS
#
# 0
# BLOCK
# 5
# <handle>
# 100
# AcDbEntity
# 8
# <layer>
# 100
# AcDbBlockBegin
# 2
# <block name>
# 70
# <flag>
# 10
# <X value>
# 20
# <Y value>
# 30
# <Z value>
# 3
# <block name>
# 1
# <xref path>
#
# 0
# <entity type>
# .
# . <data>
# .
#
# 0
# ENDBLK
# 5
# <handle>
# 100
# AcDbBlockEnd
#
# 0
# ENDSEC
def parseBlocks(section, statements, handles):
while statements:
(code,data) = statements.pop()
if code == 0:
if data == 'ENDSEC':
return
return
# 0
# SECTION
# 2
# ENTITIES
#
# 0
# <entity type>
# 5
# <handle>
# 330
# <pointer to owner>
# 100
# AcDbEntity
# 8
# <layer>
# 100
# AcDb<classname>
# .
# . <data>
# .
#
# 0
# ENDSEC
Ignorables = ['DIMENSION', 'TEXT', 'VIEWPORT']
ClassCreators = {
'3DFACE': 'C3dFace()',
'3DSOLID': 'C3dSolid()',
'ACAD_PROXY_ENTITY': 'CAcadProxyEntity()',
'ACAD_ZOMBIE_ENTITY': 0,
'ARC': 'CArc()',
'ARCALIGNEDTEXT': 'CArcAlignedText()',
'ATTDEF': 'CAttdef()',
'ATTRIB': 'CAttrib()',
'BODY': 0,
'CIRCLE': 'CCircle()',
'DIMENSION': 'CDimension()',
'ELLIPSE': 'CEllipse()',
'HATCH': 'CHatch()',
'IMAGE': 'CImage()',
'INSERT': 'CInsert()',
'LEADER': 'CLeader()',
'LINE': 'CLine()',
'LWPOLYLINE': 'CLWPolyLine()',
'MLINE': 'CMLine()',
'MTEXT': 'CMText()',
'OLEFRAME': 0,
'OLE2FRAME': 0,
'POINT': 'CPoint()',
'POLYLINE': 'CPolyLine()',
'RAY': 'CRay()',
'REGION': 0,
'RTEXT': 'CRText',
'SEQEND': 0,
'SHAPE': 'CShape()',
'SOLID': 'CSolid()',
'SPLINE': 'CSpline()',
'TEXT': 'CText()',
'TOLERANCE': 'CTolerance()',
'TRACE': 'CTrace()',
'VERTEX': 'CVertex()',
'VIEWPORT': 'CViewPort()',
'WIPEOUT': 'CWipeOut()',
'XLINE': 'CXLine()',
}
def parseEntities(section, statements, handles):
entities = []
section.data = entities
while statements:
(code,data) = statements.pop()
if toggle & T_Verbose:
print("ent", code,data)
if code == 0:
known = True
if data in Ignorables:
ignore = True
else:
ignore = False
try:
creator = ClassCreators[data]
except:
creator = None
if creator:
entity = eval(creator)
elif data == 'ENDSEC':
return
else:
known = False
if data == 'POLYLINE':
verts = entity.verts
elif data == 'VERTEX':
verts.append(entity)
if data == 'SEQEND':
attributes = []
known = False
elif creator == 0:
ignore = True
elif known:
entities.append(entity)
attributes = DxfEntityAttributes[data]
else:
raise NameError("Unknown data %s" % data)
elif not known:
pass
else:
expr = getAttribute(attributes, code)
if expr:
exec(expr)
else:
expr = getAttribute(DxfCommonAttributes, code)
if expr:
exec(expr)
elif code >= 1000 or ignore:
pass
elif toggle & T_Debug:
raise NameError("Unknown code %d for %s" % (code, entity.type))
return
def getAttribute(attributes, code):
try:
ext = attributes[code]
if type(ext) == str:
expr = "entity.%s = data" % ext
else:
name = ext[0]
expr = "entity.%s" % name
except:
expr = None
return expr
# 0
# SECTION
# 2
# OBJECTS
#
# 0
# DICTIONARY
# 5
# <handle>
# 100
# AcDbDictionary
#
# 3
# <dictionary name>
# 350
# <handle of child>
#
# 0
# <object type>
# .
# . <data>
# .
#
# 0
# ENDSEC
def parseObjects(data, statements, handles):
while statements:
(code,data) = statements.pop()
if code == 0:
if data == 'ENDSEC':
return
return
#
# buildGeometry(entities):
# addMesh(name, verts, edges, faces):
#
def buildGeometry(entities):
try: bpy.ops.object.mode_set(mode='OBJECT')
except: pass
v_verts = []
v_vn = 0
e_verts = []
e_edges = []
e_vn = 0
f_verts = []
f_edges = []
f_faces = []
f_vn = 0
for ent in entities:
if ent.drawtype in ('Mesh','Curve'):
(verts, edges, faces, vn) = ent.build()
if not toggle & T_DrawOne:
drawGeometry(verts, edges, faces)
else:
if verts:
if faces:
for i,f in enumerate(faces):
#print ('face=', f)
faces[i] = tuple(it+f_vn for it in f)
for i,e in enumerate(edges):
edges[i] = tuple(it+f_vn for it in e)
f_verts.extend(verts)
f_edges.extend(edges)
f_faces.extend(faces)
f_vn += len(verts)
elif edges:
for i,e in enumerate(edges):
edges[i] = tuple(it+e_vn for it in e)
e_verts.extend(verts)
e_edges.extend(edges)
e_vn += len(verts)
else:
v_verts.extend(verts)
v_vn += len(verts)
else:
ent.draw()
if toggle & T_DrawOne:
drawGeometry(f_verts, f_edges, f_faces)
drawGeometry(e_verts, e_edges)
drawGeometry(v_verts)
def drawGeometry(verts, edges=[], faces=[]):
if verts:
if edges and (toggle & T_Curves):
print ('draw Curve')
cu = bpy.data.curves.new('DXFlines', 'CURVE')
cu.dimensions = '3D'
buildSplines(cu, verts, edges)
ob = addObject('DXFlines', cu)
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
else:
#for v in verts: print(v)
#print ('draw Mesh with %s vertices' %(len(verts)))
#for e in edges: print(e)
#print ('draw Mesh with %s edges' %(len(edges)))
#for f in faces: print(f)
#print ('draw Mesh with %s faces' %(len(faces)))
me = bpy.data.meshes.new('DXFmesh')
me.from_pydata(verts, edges, faces)
ob = addObject('DXFmesh', me)
removeDoubles(ob)
return
def buildSplines(cu, verts, edges):
if edges:
point_list = []
(v0,v1) = edges.pop()
v1_old = v1
newPoints = [tuple(verts[v0]),tuple(verts[v1])]
for (v0,v1) in edges:
if v0==v1_old:
newPoints.append(tuple(verts[v1]))
else:
#print ('newPoints=', newPoints)
point_list.append(newPoints)
newPoints = [tuple(verts[v0]),tuple(verts[v1])]
v1_old = v1
point_list.append(newPoints)
for points in point_list:
spline = cu.splines.new('POLY')
#spline = cu.splines.new('BEZIER')
#spline.use_endpoint_u = True
#spline.order_u = 2
#spline.resolution_u = 1
#spline.bezier_points.add(2)
spline.points.add(len(points)-1)
#spline.points.foreach_set('co', points)
for i,p in enumerate(points):
spline.points[i].co = (p[0],p[1],p[2],0)
#print ('spline.type=', spline.type)
#print ('spline number=', len(cu.splines))
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
def addObject(name, data):
ob = bpy.data.objects.new(name, data)
scn = bpy.context.scene
scn.objects.link(ob)
return ob
def removeDoubles(ob):
global theMergeLimit
if toggle & T_Merge:
scn = bpy.context.scene
scn.objects.active = ob
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.remove_doubles(limit=theMergeLimit)
bpy.ops.object.mode_set(mode='OBJECT')
#
# clearScene(context):
#
def clearScene():
global toggle
scn = bpy.context.scene
print("clearScene %s %s" % (toggle & T_NewScene, scn))
if not toggle & T_NewScene:
return scn
for ob in scn.objects:
if ob.type in ["MESH", "CURVE", "TEXT"]:
scn.objects.active = ob
bpy.ops.object.mode_set(mode='OBJECT')
scn.objects.unlink(ob)
del ob
return scn
#
# readAndBuildDxfFile(filepath):
#
def readAndBuildDxfFile(filepath):
fileName = os.path.expanduser(filepath)
if fileName:
(shortName, ext) = os.path.splitext(fileName)
#print("filepath: ", filepath)
#print("fileName: ", fileName)
#print("shortName: ", shortName)
if ext.lower() != ".dxf":
print("Error: Not a dxf file: " + fileName)
return
if toggle & T_NewScene:
clearScene()
if 0: # how to switch to the new scene?? (migius)
new_scn = bpy.data.scenes.new(shortName[-20:])
#new_scn.layers = (1<<20) -1
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
bpy.data.screens.scene = new_scn
#print("newScene: %s" % (new_scn))
sections = readDxfFile(fileName)
print("Building geometry")
buildGeometry(sections['ENTITIES'].data)
print("Done")
return
print("Error: Not a dxf file: " + filepath)
return
#
# User interface
#
DEBUG= False
from bpy.props import *
def tripleList(list1):
list3 = []
for elt in list1:
list3.append((elt,elt,elt))
return list3
class IMPORT_OT_autocad_dxf(bpy.types.Operator):
'''Import from DXF file format (.dxf)'''
bl_idname = "import_scene.autocad_dxf"
bl_description = 'Import from DXF file format (.dxf)'
bl_label = "Import DXF" +' v.'+ __version__
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
filepath = StringProperty(name="File Path", description="Filepath used for importing the DXF file", maxlen= 1024, default= "", subtype='FILE_PATH')
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
new_scene = BoolProperty(name="Replace scene", description="Replace scene", default=toggle&T_NewScene)
#new_scene = BoolProperty(name="New scene", description="Create new scene", default=toggle&T_NewScene)
curves = BoolProperty(name="Draw curves", description="Draw entities as curves", default=toggle&T_Curves)
thic_on = BoolProperty(name="Thic ON", description="Support THICKNESS", default=toggle&T_ThicON)
merge = BoolProperty(name="Remove doubles", description="Merge coincident vertices", default=toggle&T_Merge)
mergeLimit = FloatProperty(name="Limit", description="Merge limit", default = theMergeLimit*1e4,min=1.0, soft_min=1.0, max=100.0, soft_max=100.0)
draw_one = BoolProperty(name="Merge all", description="Draw all into one mesh-object", default=toggle&T_DrawOne)
circleResolution = IntProperty(name="Circle resolution", description="Circle/Arc are aproximated will this factor", default = theCircleRes,
min=4, soft_min=4, max=360, soft_max=360)
codecs = tripleList(['iso-8859-15', 'utf-8', 'ascii'])
codec = EnumProperty(name="Codec", description="Codec", items=codecs, default = 'ascii')
debug = BoolProperty(name="Debug", description="Unknown DXF-codes generate errors", default=toggle&T_Debug)
verbose = BoolProperty(name="Verbose", description="Print debug info", default=toggle&T_Verbose)
##### DRAW #####
def draw(self, context):
layout0 = self.layout
#layout0.enabled = False
#col = layout0.column_flow(2,align=True)
layout = layout0.box()
col = layout.column()
#col.prop(self, 'KnotType') waits for more knottypes
#col.label(text="import Parameters")
#col.prop(self, 'replace')
col.prop(self, 'new_scene')
row = layout.row(align=True)
row.prop(self, 'curves')
row.prop(self, 'circleResolution')
row = layout.row(align=True)
row.prop(self, 'merge')
if self.merge:
row.prop(self, 'mergeLimit')
row = layout.row(align=True)
#row.label('na')
row.prop(self, 'draw_one')
row.prop(self, 'thic_on')
col = layout.column()
col.prop(self, 'codec')
row = layout.row(align=True)
row.prop(self, 'debug')
if self.debug:
row.prop(self, 'verbose')
def execute(self, context):
global toggle, theMergeLimit, theCodec, theCircleRes
O_Merge = T_Merge if self.merge else 0
#O_Replace = T_Replace if self.replace else 0
O_NewScene = T_NewScene if self.new_scene else 0
O_Curves = T_Curves if self.curves else 0
O_ThicON = T_ThicON if self.thic_on else 0
O_DrawOne = T_DrawOne if self.draw_one else 0
O_Debug = T_Debug if self.debug else 0
O_Verbose = T_Verbose if self.verbose else 0
toggle = O_Merge | O_DrawOne | O_NewScene | O_Curves | O_ThicON | O_Debug | O_Verbose
theMergeLimit = self.mergeLimit*1e-4
theCircleRes = self.circleResolution
theCodec = self.codec
readAndBuildDxfFile(self.filepath)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
wm.fileselect_add(self)
return {'RUNNING_MODAL'}
def menu_func(self, context):
self.layout.operator(IMPORT_OT_autocad_dxf.bl_idname, text="Autocad (.dxf)")
Campbell Barton
committed
bpy.utils.register_module(__name__)
bpy.types.INFO_MT_file_import.append(menu_func)
Campbell Barton
committed
bpy.utils.unregister_module(__name__)
bpy.types.INFO_MT_file_import.remove(menu_func)
if __name__ == "__main__":
register()