#!/usr/bin/env python ''' dxf_input.py - input a DXF file >= (AutoCAD Release 13 == AC1012) Copyright (C) 2008, 2009 Alvin Penner, penner@vaxxine.com and Christian Mayer, inkscape@christianmayer.de - thanks to Aaron Spike for inkex.py and simplestyle.py - without which this would not have been possible This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ''' import inkex, simplestyle, math, re from StringIO import StringIO def export_MTEXT(): # mandatory group codes : (1, 10, 20) (text, x, y) if vals[groups['1']] and vals[groups['10']] and vals[groups['20']]: x = vals[groups['10']][0] y = vals[groups['20']][0] # optional group codes : (40, 50) (text height mm, text angle) size = 12 # default fontsize in px if vals[groups['40']]: size = scale*vals[groups['40']][0] attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %dpx; fill: %s' % (size, color), 'id': vals[groups['5']][0]} angle = 0 # default angle in degrees if vals[groups['50']]: angle = vals[groups['50']][0] attribs.update({'transform': 'rotate (%f %f %f)' % (-angle, x, y)}) attribs.update({inkex.addNS('linespacing','sodipodi'): '125%'}) node = inkex.etree.SubElement(layer, 'text', attribs) text = '' for i in range (0, len(vals[groups['3']])): text += vals[groups['3']][i] text += vals[groups['1']][0] found = text.find('\P') # new line while found > -1: tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'}) tspan.text = text[:found] text = text[(found+2):] found = text.find('\P') tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'}) tspan.text = text def export_POINT(): # mandatory group codes : (10, 20) (x, y) if vals[groups['10']] and vals[groups['20']]: generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], w/2, 0.0, 1.0, 0.0, 0.0, vals[groups['5']][0]) def export_LINE(): # mandatory group codes : (10, 11, 20, 21) (x1, x2, y1, y2) if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']]: path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], scale*(vals[groups['11']][0] - xmin), - scale*(vals[groups['21']][0] - ymax)) linestyle = style #if vals[groups['6']] and linetypes.has_key( vals[groups['6']][0] ): # linestyle += ';' + linetypes[vals[groups['6']][0]] attribs = {'d': path, 'style': linestyle, 'id': vals[groups['5']][0]} inkex.etree.SubElement(layer, 'path', attribs) def export_SPLINE(): # mandatory group codes : (10, 20, 70) (x, y, flags) if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]: if not (vals[groups['70']][0] & 3) and len(vals[groups['10']]) == 4 and len(vals[groups['20']]) == 4: path = 'M %f,%f C %f,%f %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][1], vals[groups['20']][1], vals[groups['10']][2], vals[groups['20']][2], vals[groups['10']][3], vals[groups['20']][3]) attribs = {'d': path, 'style': style} inkex.etree.SubElement(layer, 'path', attribs) if not (vals[groups['70']][0] & 3) and len(vals[groups['10']]) == 3 and len(vals[groups['20']]) == 3: path = 'M %f,%f Q %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][1], vals[groups['20']][1], vals[groups['10']][2], vals[groups['20']][2]) attribs = {'d': path, 'style': style, 'id': vals[groups['5']][0]} inkex.etree.SubElement(layer, 'path', attribs) def export_CIRCLE(): # mandatory group codes : (10, 20, 40) (x, y, radius) if vals[groups['10']] and vals[groups['20']] and vals[groups['40']]: generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['40']][0], 0.0, 1.0, 0.0, 0.0, vals[groups['5']][0]) def export_ARC(): # mandatory group codes : (10, 20, 40, 50, 51) (x, y, radius, angle1, angle2) if vals[groups['10']] and vals[groups['20']] and vals[groups['40']] and vals[groups['50']] and vals[groups['51']]: generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['40']][0], 0.0, 1.0, vals[groups['50']][0]*math.pi/180.0, vals[groups['51']][0]*math.pi/180.0, vals[groups['5']][0]) def export_ELLIPSE(): # mandatory group codes : (10, 11, 20, 21, 40, 41, 42) (xc, xm, yc, ym, width ratio, angle1, angle2) if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']] and vals[groups['40']] and vals[groups['41']] and vals[groups['42']]: generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['11']][0], scale*vals[groups['21']][0], vals[groups['40']][0], vals[groups['41']][0], vals[groups['42']][0], vals[groups['5']][0]) def export_LEADER(): # mandatory group codes : (10, 20) (x, y) if vals[groups['10']] and vals[groups['20']]: if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]): path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0]) for i in range (1, len(vals[groups['10']])): path += ' %f,%f' % (vals[groups['10']][i], vals[groups['20']][i]) attribs = {'d': path, 'style': style, 'id': vals[groups['5']][0]} inkex.etree.SubElement(layer, 'path', attribs) def export_LWPOLYLINE(): # mandatory group codes : (10, 20, 70) (x, y, flags) if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]: if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]): # optional group codes : (42) (bulge) iseqs = 0 ibulge = 0 while seqs[iseqs] != '20': iseqs += 1 path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0]) xold = vals[groups['10']][0] yold = vals[groups['20']][0] for i in range (1, len(vals[groups['10']])): bulge = 0 iseqs += 1 while seqs[iseqs] != '20': if seqs[iseqs] == '42': bulge = vals[groups['42']][ibulge] ibulge += 1 iseqs += 1 if bulge: sweep = 0 # sweep CCW if bulge < 0: sweep = 1 # sweep CW bulge = -bulge large = 0 # large-arc-flag if bulge > 1: large = 1 r = math.sqrt((vals[groups['10']][i] - xold)**2 + (vals[groups['20']][i] - yold)**2) r = 0.25*r*(bulge + 1.0/bulge) path += ' A %f,%f 0.0 %d %d %f,%f' % (r, r, large, sweep, vals[groups['10']][i], vals[groups['20']][i]) else: path += ' L %f,%f' % (vals[groups['10']][i], vals[groups['20']][i]) xold = vals[groups['10']][i] yold = vals[groups['20']][i] if vals[groups['70']][0] == 1: # closed path path += ' z' attribs = {'d': path, 'style': style, 'id': vals[groups['5']][0]} inkex.etree.SubElement(layer, 'path', attribs) def export_HATCH(): # FIXME: this feature was added as a quick fix by being totally based on the LWPOLYLINE # mandatory group codes : (10, 20, 70) (x, y, flags) if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]: if len(vals[groups['10']]) > 2 and len(vals[groups['20']]) == len(vals[groups['10']]): # optional group codes : (42) (bulge) iseqs = 0 ibulge = 0 icount = 0 count = vals[groups['93']][icount] while seqs[iseqs] != '20': iseqs += 1 path = 'M %f,%f' % (vals[groups['10']][1], vals[groups['20']][1]) xold = vals[groups['10']][1] yold = vals[groups['20']][1] for i in range (2, len(vals[groups['10']])): bulge = 0 iseqs += 1 while seqs[iseqs] != '20': if seqs[iseqs] == '42': bulge = vals[groups['42']][ibulge] ibulge += 1 iseqs += 1 if i == count + 1: # use these lines to generate sperarated hatches instead of one combined one #id = '%s'%vals[groups['5']][0] + '_%i'%icount #attribs = {'d': path, 'style': style+';fill:#000000', 'id': id} # FIXME: use the pattern and color of the HATCH instead #inkex.etree.SubElement(layer, 'path', attribs) icount += 1 if len(vals[groups['93']]) > icount: count += vals[groups['93']][icount] path += ' M %f,%f' % (vals[groups['10']][i], vals[groups['20']][i]) else: break # the remaining ponints are only definig the seed of the fill else: if bulge: sweep = 0 # sweep CCW if bulge < 0: sweep = 1 # sweep CW bulge = -bulge large = 0 # large-arc-flag if bulge > 1: large = 1 r = math.sqrt((vals[groups['10']][i] - xold)**2 + (vals[groups['20']][i] - yold)**2) r = 0.25*r*(bulge + 1.0/bulge) path += ' A %f,%f 0.0 %d %d %f,%f' % (r, r, large, sweep, vals[groups['10']][i], vals[groups['20']][i]) else: path += ' L %f,%f' % (vals[groups['10']][i], vals[groups['20']][i]) xold = vals[groups['10']][i] yold = vals[groups['20']][i] if vals[groups['70']][0] == 1: # closed path path += ' z' attribs = {'d': path, 'style': style+';fill:#000000', 'id': vals[groups['5']][0]} # FIXME: use the pattern and color of the HATCH instead inkex.etree.SubElement(layer, 'path', attribs) def export_DIMENSION(): # mandatory group codes : (10, 11, 20, 21) (x_dim, x_text, y_dim, y_text) if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']]: if not (vals[groups['70']][0] & 1) and vals[groups['13']] and vals[groups['14']] and vals[groups['23']] and vals[groups['24']]: # so far only rotated, horizontal, or vertical is supported if vals[groups['50']] and vals[groups['50']][0]==90: path = 'M %f,%f %f,%f' % ( vals[groups['10']][0] , - scale*(vals[groups['23']][0] - ymax), vals[groups['10']][0] , - scale*(vals[groups['24']][0] - ymax)) measure = abs( vals[groups['23']][0] - vals[groups['24']][0] ) else: path = 'M %f,%f %f,%f' % (scale*(vals[groups['13']][0] - xmin), vals[groups['20']][0] , scale*(vals[groups['14']][0] - xmin), vals[groups['20']][0] ) measure = abs( vals[groups['13']][0] - vals[groups['14']][0] ) attribs = {'d': path, 'style': style+';marker-start:url(#DistanceStart);marker-end:url(#DistanceEnd)', 'id': vals[groups['5']][0]} inkex.etree.SubElement(layer_dim, 'path', attribs) x = scale*(vals[groups['11']][0] - xmin) y = - scale*(vals[groups['21']][0] - ymax) # optional group codes : (40, 50) (text height mm, text angle) size = 12 # default fontsize in px attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %dpx; fill: %s' % (size, color), 'id': vals[groups['5']][0]} angle = 0 # default angle in degrees if vals[groups['50']]: angle = vals[groups['50']][0] attribs.update({'transform': 'rotate (%f %f %f)' % (-angle, x, y)}) attribs.update({inkex.addNS('linespacing','sodipodi'): '125%'}) node = inkex.etree.SubElement(layer_dim, 'text', attribs) text = vals[groups['1']][0] found = text.find('\X') # new line remaining_text = '' if found > -1: remaining_text = text[(found+2):] super = '0' if len(text)>1 and text[0:2]=='<>': #full = float( '%.2f' % measure ) #half = float( '%.3f' % measure ) scaled = 0 if measure < 1.0: measure *= 100.0 # assuming we are in a scale of meters and centimeters scaled = 1 text = '%f' % (float('%.2f' % (2.0*measure))*0.5) if scaled == 0: if re.sub( '.*\\...(.).*', '\\1', text )=='5': super = '5' text = re.sub( '(.*\\...).*', '\\1', text ) else: if re.sub( '.*\\.(.).*', '\\1', text )=='5': super = '5' text = re.sub( '(.*)\\..*', '\\1', text ) node.text = text #if 'super'=='5': tspan = inkex.etree.SubElement(node , 'tspan', {'dy': '-100%'}) tspan.text = super if remaining_text != '': tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'}) tspan.text = remaining_text def export_NULL(): return # do nothing def generate_ellipse(xc, yc, xm, ym, w, a1, a2, id): rm = math.sqrt(xm*xm + ym*ym) a = math.atan2(ym, xm) if xm < 0: a += math.pi diff = (a2 - a1 + 2*math.pi) % (2*math.pi) if diff: # open arc large = 0 # large-arc-flag if diff > math.pi: large = 1 xt = rm*math.cos(a1) yt = w*rm*math.sin(a1) x1 = xt*math.cos(a) - yt*math.sin(a) y1 = xt*math.sin(a) + yt*math.cos(a) xt = rm*math.cos(a2) yt = w*rm*math.sin(a2) x2 = xt*math.cos(a) - yt*math.sin(a) y2 = xt*math.sin(a) + yt*math.cos(a) path = 'M %f,%f A %f,%f %f %d 0 %f,%f' % (xc+x1, yc-y1, rm, w*rm, -180.0*a/math.pi, large, xc+x2, yc-y2) else: # closed arc path = 'M %f,%f A %f,%f %f 1 0 %f,%f %f,%f %f 1 0 %f,%f z' % (xc+xm, yc-ym, rm, w*rm, -180.0*a/math.pi, xc-xm, yc+ym, rm, w*rm, -180.0*a/math.pi, xc+xm, yc-ym) attribs = {'d': path, 'style': style, 'id': id} inkex.etree.SubElement(layer, 'path', attribs) def get_line(): return (stream.readline().strip(), stream.readline().strip()) def get_group(group): line = get_line() if line[0] == group: return float(line[1]) else: return 0.0 def convert_unicode_escape(matchobj): return unichr( int( matchobj.group(1), 16 ) ) # define DXF Entities and specify which Group Codes to monitor entities = {'MTEXT': export_MTEXT, 'TEXT': export_MTEXT, 'POINT': export_POINT, 'LINE': export_LINE, 'SPLINE': export_SPLINE, 'CIRCLE': export_CIRCLE, 'ARC': export_ARC, 'ELLIPSE': export_ELLIPSE, 'LEADER': export_LEADER, 'LWPOLYLINE': export_LWPOLYLINE, 'HATCH': export_HATCH, 'DIMENSION': export_DIMENSION, 'INSERT': export_NULL, 'ENDSEC': '', 'IMAGE': export_NULL} groups = { '1': 0, '5': 1, '8': 2, '10': 3, '11': 4, '12': 5, '13': 6, '14': 7, '20': 8, '21': 9, '22': 10, '23': 11, '24': 12, '40': 13, '41': 14, '42': 15, '50': 16, '51': 17, '62': 18, '70': 19, '370': 20, '6': 21, '49': 22, '93': 23, '3': 24} colors = { 1: '#FF0000', 2: '#FFFF00', 3: '#00FF00', 4: '#00FFFF', 5: '#0000FF', 6: '#FF00FF', 8: '#414141', 9: '#808080', 30: '#FF7F00', 250: '#333333', 251: '#505050', 252: '#696969', 253: '#828282', 254: '#BEBEBE', 255: '#FFFFFF'} linetypes = {} doc = inkex.etree.parse(StringIO('')) stream = open(inkex.sys.argv[1], 'r') xmax = xmin = 0.0 ymax = 297.0 # default A4 height in mm line = get_line() flag = 0 layer_colors = {} # store colors by layer layer_nodes = {} # store nodes by layer linename = '' linetype = '' defs = inkex.etree.SubElement(doc.getroot(), 'defs', {} ) distance_start = inkex.etree.SubElement(defs, 'marker', {'id': 'DistanceStart', 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'overflow:visible'} ) distance_start_g = inkex.etree.SubElement(distance_start, 'g', {'style':'stroke:#000000;stroke-width:1'} ) inkex.etree.SubElement(distance_start_g, 'path', {'d': 'M 3,-3 L -3,3'} ) inkex.etree.SubElement(distance_start_g, 'path', {'d': 'M 0,-5 L 0,5'} ) distance_end = inkex.etree.SubElement(defs, 'marker', {'id': 'DistanceEnd', 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'overflow:visible'} ) distance_end_g = inkex.etree.SubElement(distance_end , 'g', {'style':'stroke:#000000;stroke-width:1'} ) inkex.etree.SubElement(distance_end_g , 'path', {'d': 'M 3,-3 L -3,3'} ) inkex.etree.SubElement(distance_end_g , 'path', {'d': 'M 0,-5 L 0,5'} ) while line[0] and line[1] != 'ENTITIES': line = get_line() if line[1] == '$EXTMIN': xmin = get_group('10') if line[1] == '$EXTMAX': xmax = get_group('10') ymax = get_group('20') if flag == 1 and line[0] == '2': name = unicode(line[1], "iso-8859-1") # FIXME: use codepage defined in DXF attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '%s' % name} layer_nodes[name] = inkex.etree.SubElement(doc.getroot(), 'g', attribs) name += '_dimensions' attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '%s' % name} layer_nodes[name] = inkex.etree.SubElement(doc.getroot(), 'g', attribs) if flag == 2 and line[0] == '2': if linetype != '': linetypes[linename] = 'stroke-dasharray:' + linetype + ';stroke-dashoffset:0' inkex.etree.SubElement(defs, 'marker', {'id': linename, 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'stroke-dasharray:'+linetype} ) linetype = '' linename = unicode(line[1], "iso-8859-1") # FIXME: use codepage defined in DXF if flag == 2 and line[0] == '49': if linetype != '': linetype += ',' linetype += '%.2f' % math.fabs( float(line[1]) ) if line[0] == '2' and line[1] == 'LAYER': flag = 1 if line[0] == '2' and line[1] == 'LTYPE': if linetype != '': linetypes[linename] = 'stroke-dasharray:' + linetype + ';stroke-dashoffset:0' inkex.etree.SubElement(defs, 'marker', {'id': linename, 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'stroke-dasharray:'+linetype} ) linetype = '' flag = 2 if flag and line[0] == '62': layer_colors[name] = int(line[1]) if line[0] == '0' and line[1] == 'ENDTAB': if linetype != '': linetypes[linename] = 'stroke-dasharray:' + linetype + ';stroke-dashoffset:0' inkex.etree.SubElement(defs, 'marker', {'id': linename, 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'stroke-dasharray:'+linetype} ) linetype = '' flag = 0 scale = 90.0/25.4 # default convert from mm to pixels if xmax > xmin: scale *= 210.0/(xmax - xmin) # scale to A4 width entity = '' handle = '' while line[0] and line[1] != 'ENDSEC': line = get_line() if entity and groups.has_key(line[0]): seqs.append(line[0]) # list of group codes if line[0] == '1' or line[0] == '3' or line[0] == '8': # text value val = line[1].replace('\~', ' ') # FIXME: Unimplemented text like "\S..^..;" val = re.sub( '\\\\W.*;', '', val ) # FIXME: Unimplemented text like "\W..;" => ignore val = val.replace('\A0;', '') # Unimplemented: VAlignBottom => ignore val = val.replace('\A1;', '') # Unimplemented: VAlignMiddle => ignore val = val.replace('\A2;', '') # Unimplemented: VAlignTop => ignore val = unicode(val, "iso-8859-1") # FIXME: use codepage defined in DXF val = re.sub( '\\\\U\+([0-9A-Fa-f]{4})', convert_unicode_escape, val ) elif line[0] == '62' or line[0] == '70': # unscaled integer value val = int(line[1]) elif line[0] == '10': # scaled float x value val = scale*(float(line[1]) - xmin) elif line[0] == '20': # scaled float y value val = - scale*(float(line[1]) - ymax) elif line[0] == '5': # handle; relate dxf-handle to the svn-id val = line[1] elif line[0] == '6': # linetype val = line[1] else: # unscaled float value val = float(line[1]) vals[groups[line[0]]].append(val) elif line[0] == '0': if entities.has_key(entity): color = '#000000' # default color if vals[groups['8']]: # Common Layer Name layer = layer_nodes[vals[groups['8']][0]] layer_dim = layer_nodes[vals[groups['8']][0]+'_dimensions'] if layer_colors.has_key(vals[groups['8']][0]): if colors.has_key(layer_colors[vals[groups['8']][0]]): color = colors[layer_colors[vals[groups['8']][0]]] if vals[groups['62']]: # Common Color Number if colors.has_key(vals[groups['62']][0]): color = colors[vals[groups['62']][0]] style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none'}) w = 0.5 # default lineweight for POINT if vals[groups['370']]: # Common Lineweight if vals[groups['370']][0] > 0: w = scale*vals[groups['370']][0]/100.0 if w < 0.001: w = 0.001 style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none', 'stroke-width': '%.3f' % w}) if vals[groups['6']] and linetypes.has_key( vals[groups['6']][0] ): style += ';' + linetypes[vals[groups['6']][0]] entities[entity]() else: inkex.etree.SubElement(defs, 'marker', {'id': entity, 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'stroke-dasharray:0'} ) entity = line[1] vals = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] seqs = [] doc.write(inkex.sys.stdout) # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99