home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Inkscape / Inkscape-0.48.2-1-win32.exe / share / extensions / dxf_input.py < prev    next >
Text File  |  2011-07-08  |  28KB  |  495 lines

  1. #!/usr/bin/env python
  2. '''
  3. dxf_input.py - input a DXF file >= (AutoCAD Release 13 == AC1012)
  4.  
  5. Copyright (C) 2008, 2009 Alvin Penner, penner@vaxxine.com
  6. Copyright (C) 2009 Christian Mayer, inkscape@christianmayer.de
  7. - thanks to Aaron Spike for inkex.py and simplestyle.py
  8. - without which this would not have been possible
  9.  
  10. This program is free software; you can redistribute it and/or modify
  11. it under the terms of the GNU General Public License as published by
  12. the Free Software Foundation; either version 2 of the License, or
  13. (at your option) any later version.
  14.  
  15. This program is distributed in the hope that it will be useful,
  16. but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18. GNU General Public License for more details.
  19.  
  20. You should have received a copy of the GNU General Public License
  21. along with this program; if not, write to the Free Software
  22. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  23. '''
  24.  
  25. import inkex, simplestyle, math
  26. from StringIO import StringIO
  27. from urllib import quote
  28.  
  29. def export_MTEXT():
  30.     # mandatory group codes : (1 or 3, 10, 20) (text, x, y)
  31.     if (vals[groups['1']] or vals[groups['3']]) and vals[groups['10']] and vals[groups['20']]:
  32.         x = vals[groups['10']][0]
  33.         y = vals[groups['20']][0]
  34.         # optional group codes : (21, 40, 50) (direction, text height mm, text angle)
  35.         size = 12                       # default fontsize in px
  36.         if vals[groups['40']]:
  37.             size = scale*vals[groups['40']][0]
  38.         attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %.1fpx; fill: %s; font-family: %s' % (size, color, options.font)}
  39.         angle = 0                       # default angle in degrees
  40.         if vals[groups['50']]:
  41.             angle = vals[groups['50']][0]
  42.             attribs.update({'transform': 'rotate (%f %f %f)' % (-angle, x, y)})
  43.         elif vals[groups['21']]:
  44.             if vals[groups['21']][0] == 1.0:
  45.                 attribs.update({'transform': 'rotate (%f %f %f)' % (-90, x, y)})
  46.             elif vals[groups['21']][0] == -1.0:
  47.                 attribs.update({'transform': 'rotate (%f %f %f)' % (90, x, y)})
  48.         attribs.update({inkex.addNS('linespacing','sodipodi'): '125%'})
  49.         node = inkex.etree.SubElement(layer, 'text', attribs)
  50.         text = ''
  51.         if vals[groups['3']]:
  52.             for i in range (0, len(vals[groups['3']])):
  53.                 text += vals[groups['3']][i]
  54.         if vals[groups['1']]:
  55.             text += vals[groups['1']][0]
  56.         found = text.find('\P')         # new line
  57.         while found > -1:
  58.             tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
  59.             tspan.text = text[:found]
  60.             text = text[(found+2):]
  61.             found = text.find('\P')
  62.         tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
  63.         tspan.text = text
  64.  
  65. def export_POINT():
  66.     # mandatory group codes : (10, 20) (x, y)
  67.     if vals[groups['10']] and vals[groups['20']]:
  68.         if options.gcodetoolspoints:
  69.             generate_gcodetools_point(vals[groups['10']][0], vals[groups['20']][0])
  70.         else:
  71.             generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], w/2, 0.0, 1.0, 0.0, 0.0)
  72.  
  73. def export_LINE():
  74.     # mandatory group codes : (10, 11, 20, 21) (x1, x2, y1, y2)
  75.     if vals[groups['10']] and vals[groups['11']] and vals[groups['20']] and vals[groups['21']]:
  76.         path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], scale*(vals[groups['11']][0] - xmin), height - scale*(vals[groups['21']][0] - ymin))
  77.         attribs = {'d': path, 'style': style}
  78.         inkex.etree.SubElement(layer, 'path', attribs)
  79.  
  80. def export_SPLINE():
  81.     # see : http://www.mactech.com/articles/develop/issue_25/schneider.html
  82.     # mandatory group codes : (10, 20, 40, 70) (x[], y[], knots[], flags)
  83.     if vals[groups['70']] and not (vals[groups['70']][0] & 3) and len(vals[groups['10']]) == len(vals[groups['20']]) and vals[groups['10']] and vals[groups['20']] and vals[groups['40']]:
  84.         knots = len(vals[groups['40']])
  85.         ctrls = len(vals[groups['10']])
  86.         if ctrls > 3 and knots == ctrls + 4:    # cubic
  87.             if ctrls > 4:
  88.                 for i in range (knots - 5, 3, -1):
  89.                     a0 = (vals[groups['40']][i] - vals[groups['40']][i-2])/(vals[groups['40']][i+1] - vals[groups['40']][i-2])
  90.                     a1 = (vals[groups['40']][i] - vals[groups['40']][i-1])/(vals[groups['40']][i+2] - vals[groups['40']][i-1])
  91.                     vals[groups['10']].insert(i-1, (1.0 - a1)*vals[groups['10']][i-2] + a1*vals[groups['10']][i-1])
  92.                     vals[groups['20']].insert(i-1, (1.0 - a1)*vals[groups['20']][i-2] + a1*vals[groups['20']][i-1])
  93.                     vals[groups['10']][i-2] = (1.0 - a0)*vals[groups['10']][i-3] + a0*vals[groups['10']][i-2]
  94.                     vals[groups['20']][i-2] = (1.0 - a0)*vals[groups['20']][i-3] + a0*vals[groups['20']][i-2]
  95.                     vals[groups['40']].insert(i, vals[groups['40']][i])
  96.                 knots = len(vals[groups['40']])
  97.                 for i in range (knots - 6, 3, -2):
  98.                     a1 = (vals[groups['40']][i] - vals[groups['40']][i-1])/(vals[groups['40']][i+2] - vals[groups['40']][i-1])
  99.                     vals[groups['10']].insert(i-1, (1.0 - a1)*vals[groups['10']][i-2] + a1*vals[groups['10']][i-1])
  100.                     vals[groups['20']].insert(i-1, (1.0 - a1)*vals[groups['20']][i-2] + a1*vals[groups['20']][i-1])
  101.             ctrls = len(vals[groups['10']])
  102.             path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0])
  103.             for i in range (0, (ctrls - 1)/3):
  104.                 path += ' C %f,%f %f,%f %f,%f' % (vals[groups['10']][3*i + 1], vals[groups['20']][3*i + 1], vals[groups['10']][3*i + 2], vals[groups['20']][3*i + 2], vals[groups['10']][3*i + 3], vals[groups['20']][3*i + 3])
  105.             attribs = {'d': path, 'style': style}
  106.             inkex.etree.SubElement(layer, 'path', attribs)
  107.         if ctrls == 3 and knots == 6:           # quadratic
  108.             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])
  109.             attribs = {'d': path, 'style': style}
  110.             inkex.etree.SubElement(layer, 'path', attribs)
  111.         if ctrls == 5 and knots == 8:           # spliced quadratic
  112.             path = 'M %f,%f Q %f,%f %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], vals[groups['10']][3], vals[groups['20']][3], vals[groups['10']][4], vals[groups['20']][4])
  113.             attribs = {'d': path, 'style': style}
  114.             inkex.etree.SubElement(layer, 'path', attribs)
  115.  
  116. def export_CIRCLE():
  117.     # mandatory group codes : (10, 20, 40) (x, y, radius)
  118.     if vals[groups['10']] and vals[groups['20']] and vals[groups['40']]:
  119.         generate_ellipse(vals[groups['10']][0], vals[groups['20']][0], scale*vals[groups['40']][0], 0.0, 1.0, 0.0, 0.0)
  120.  
  121. def export_ARC():
  122.     # mandatory group codes : (10, 20, 40, 50, 51) (x, y, radius, angle1, angle2)
  123.     if vals[groups['10']] and vals[groups['20']] and vals[groups['40']] and vals[groups['50']] and vals[groups['51']]:
  124.         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)
  125.  
  126. def export_ELLIPSE():
  127.     # mandatory group codes : (10, 11, 20, 21, 40, 41, 42) (xc, xm, yc, ym, width ratio, angle1, angle2)
  128.     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']]:
  129.         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])
  130.  
  131. def export_LEADER():
  132.     # mandatory group codes : (10, 20) (x, y)
  133.     if vals[groups['10']] and vals[groups['20']]:
  134.         if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
  135.             path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0])
  136.             for i in range (1, len(vals[groups['10']])):
  137.                 path += ' %f,%f' % (vals[groups['10']][i], vals[groups['20']][i])
  138.             attribs = {'d': path, 'style': style}
  139.             inkex.etree.SubElement(layer, 'path', attribs)
  140.  
  141. def export_LWPOLYLINE():
  142.     # mandatory group codes : (10, 20, 70) (x, y, flags)
  143.     if vals[groups['10']] and vals[groups['20']] and vals[groups['70']]:
  144.         if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
  145.             # optional group codes : (42) (bulge)
  146.             iseqs = 0
  147.             ibulge = 0
  148.             if vals[groups['70']][0]:           # closed path
  149.                 seqs.append('20')
  150.                 vals[groups['10']].append(vals[groups['10']][0])
  151.                 vals[groups['20']].append(vals[groups['20']][0])
  152.             while seqs[iseqs] != '20':
  153.                 iseqs += 1
  154.             path = 'M %f,%f' % (vals[groups['10']][0], vals[groups['20']][0])
  155.             xold = vals[groups['10']][0]
  156.             yold = vals[groups['20']][0]
  157.             for i in range (1, len(vals[groups['10']])):
  158.                 bulge = 0
  159.                 iseqs += 1
  160.                 while seqs[iseqs] != '20':
  161.                     if seqs[iseqs] == '42':
  162.                         bulge = vals[groups['42']][ibulge]
  163.                         ibulge += 1
  164.                     iseqs += 1
  165.                 if bulge:
  166.                     sweep = 0                   # sweep CCW
  167.                     if bulge < 0:
  168.                         sweep = 1               # sweep CW
  169.                         bulge = -bulge
  170.                     large = 0                   # large-arc-flag
  171.                     if bulge > 1:
  172.                         large = 1
  173.                     r = math.sqrt((vals[groups['10']][i] - xold)**2 + (vals[groups['20']][i] - yold)**2)
  174.                     r = 0.25*r*(bulge + 1.0/bulge)
  175.                     path += ' A %f,%f 0.0 %d %d %f,%f' % (r, r, large, sweep, vals[groups['10']][i], vals[groups['20']][i])
  176.                 else:
  177.                     path += ' L %f,%f' % (vals[groups['10']][i], vals[groups['20']][i])
  178.                 xold = vals[groups['10']][i]
  179.                 yold = vals[groups['20']][i]
  180.             if vals[groups['70']][0]:           # closed path
  181.                 path += ' z'
  182.             attribs = {'d': path, 'style': style}
  183.             inkex.etree.SubElement(layer, 'path', attribs)
  184.  
  185. def export_HATCH():
  186.     # mandatory group codes : (10, 20, 70, 72, 92, 93) (x, y, fill, Edge Type, Path Type, Number of edges)
  187.     if vals[groups['10']] and vals[groups['20']] and vals[groups['70']] and vals[groups['72']] and vals[groups['92']] and vals[groups['93']]:
  188.         if len(vals[groups['10']]) > 1 and len(vals[groups['20']]) == len(vals[groups['10']]):
  189.             # optional group codes : (11, 21, 40, 50, 51, 73) (x, y, r, angle1, angle2, CCW)
  190.             i10 = 1    # count start points
  191.             i11 = 0    # count line end points
  192.             i40 = 0    # count circles
  193.             i72 = 0    # count edge type flags
  194.             path = ''
  195.             for i in range (0, len(vals[groups['93']])):
  196.                 xc = vals[groups['10']][i10]
  197.                 yc = vals[groups['20']][i10]
  198.                 if vals[groups['72']][i72] == 2:            # arc
  199.                     rm = scale*vals[groups['40']][i40]
  200.                     a1 = vals[groups['50']][i40]
  201.                     path += 'M %f,%f ' % (xc + rm*math.cos(a1*math.pi/180.0), yc + rm*math.sin(a1*math.pi/180.0))
  202.                 else:
  203.                     a1 = 0
  204.                     path += 'M %f,%f ' % (xc, yc)
  205.                 for j in range(0, vals[groups['93']][i]):
  206.                     if vals[groups['92']][i] & 2:           # polyline
  207.                         if j > 0:
  208.                             path += 'L %f,%f ' % (vals[groups['10']][i10], vals[groups['20']][i10])
  209.                         if j == vals[groups['93']][i] - 1:
  210.                             i72 += 1
  211.                     elif vals[groups['72']][i72] == 2:      # arc
  212.                         xc = vals[groups['10']][i10]
  213.                         yc = vals[groups['20']][i10]
  214.                         rm = scale*vals[groups['40']][i40]
  215.                         a2 = vals[groups['51']][i40]
  216.                         diff = (a2 - a1 + 360) % (360)
  217.                         sweep = 1 - vals[groups['73']][i40] # sweep CCW
  218.                         large = 0                           # large-arc-flag
  219.                         if diff:
  220.                             path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos(a2*math.pi/180.0), yc + rm*math.sin(a2*math.pi/180.0))
  221.                         else:
  222.                             path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos((a1+180.0)*math.pi/180.0), yc + rm*math.sin((a1+180.0)*math.pi/180.0))
  223.                             path += 'A %f,%f 0.0 %d %d %f,%f ' % (rm, rm, large, sweep, xc + rm*math.cos(a1*math.pi/180.0), yc + rm*math.sin(a1*math.pi/180.0))
  224.                         i40 += 1
  225.                         i72 += 1
  226.                     elif vals[groups['72']][i72] == 1:      # line
  227.                         path += 'L %f,%f ' % (scale*(vals[groups['11']][i11] - xmin), height - scale*(vals[groups['21']][i11] - ymin))
  228.                         i11 += 1
  229.                         i72 += 1
  230.                     i10 += 1
  231.                 path += "z "
  232.             if vals[groups['70']][0]:
  233.                 style = simplestyle.formatStyle({'fill': '%s' % color})
  234.             else:
  235.                 style = simplestyle.formatStyle({'fill': 'url(#Hatch)', 'fill-opacity': '1.0'})
  236.             attribs = {'d': path, 'style': style}
  237.             inkex.etree.SubElement(layer, 'path', attribs)
  238.  
  239. def export_DIMENSION():
  240.     # mandatory group codes : (10, 11, 13, 14, 20, 21, 23, 24) (x1..4, y1..4)
  241.     if vals[groups['10']] and vals[groups['11']] and vals[groups['13']] and vals[groups['14']] and vals[groups['20']] and vals[groups['21']] and vals[groups['23']] and vals[groups['24']]:
  242.         dx = abs(vals[groups['10']][0] - vals[groups['13']][0])
  243.         dy = abs(vals[groups['20']][0] - vals[groups['23']][0])
  244.         if (vals[groups['10']][0] == vals[groups['14']][0]) and dx > 0.00001:
  245.             d = dx/scale
  246.             dy = 0
  247.             path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['13']][0], vals[groups['20']][0])
  248.         elif (vals[groups['20']][0] == vals[groups['24']][0]) and dy > 0.00001:
  249.             d = dy/scale
  250.             dx = 0
  251.             path = 'M %f,%f %f,%f' % (vals[groups['10']][0], vals[groups['20']][0], vals[groups['10']][0], vals[groups['23']][0])
  252.         else:
  253.             return
  254.         attribs = {'d': path, 'style': style + '; marker-start: url(#DistanceX); marker-end: url(#DistanceX); stroke-width: 0.25px'}
  255.         inkex.etree.SubElement(layer, 'path', attribs)
  256.         x = scale*(vals[groups['11']][0] - xmin)
  257.         y = height - scale*(vals[groups['21']][0] - ymin)
  258.         size = 12                   # default fontsize in px
  259.         if vals[groups['3']]:
  260.             if DIMTXT.has_key(vals[groups['3']][0]):
  261.                 size = scale*DIMTXT[vals[groups['3']][0]]
  262.                 if size < 2:
  263.                     size = 2
  264.         attribs = {'x': '%f' % x, 'y': '%f' % y, 'style': 'font-size: %.1fpx; fill: %s; font-family: %s; text-anchor: middle; text-align: center' % (size, color, options.font)}
  265.         if dx == 0:
  266.             attribs.update({'transform': 'rotate (%f %f %f)' % (-90, x, y)})
  267.         node = inkex.etree.SubElement(layer, 'text', attribs)
  268.         tspan = inkex.etree.SubElement(node , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
  269.         tspan.text = str(float('%.2f' % d))
  270.  
  271. def export_INSERT():
  272.     # mandatory group codes : (2, 10, 20) (block name, x, y)
  273.     if vals[groups['2']] and vals[groups['10']] and vals[groups['20']]:
  274.         x = vals[groups['10']][0] + scale*xmin
  275.         y = vals[groups['20']][0] - scale*ymin - height
  276.         attribs = {'x': '%f' % x, 'y': '%f' % y, inkex.addNS('href','xlink'): '#' + quote(vals[groups['2']][0].encode("utf-8"))}
  277.         inkex.etree.SubElement(layer, 'use', attribs)
  278.  
  279. def export_BLOCK():
  280.     # mandatory group codes : (2) (block name)
  281.     if vals[groups['2']]:
  282.         global block
  283.         block = inkex.etree.SubElement(defs, 'symbol', {'id': vals[groups['2']][0]})
  284.  
  285. def export_ENDBLK():
  286.     global block
  287.     block = defs                                    # initiallize with dummy
  288.  
  289. def export_ATTDEF():
  290.     # mandatory group codes : (1, 2) (default, tag)
  291.     if vals[groups['1']] and vals[groups['2']]:
  292.         vals[groups['1']][0] = vals[groups['2']][0]
  293.         export_MTEXT()
  294.  
  295. def generate_ellipse(xc, yc, xm, ym, w, a1, a2):
  296.     rm = math.sqrt(xm*xm + ym*ym)
  297.     a = math.atan2(ym, xm)
  298.     diff = (a2 - a1 + 2*math.pi) % (2*math.pi)
  299.     if abs(diff) > 0.0000001 and abs(diff - 2*math.pi) > 0.0000001: # open arc
  300.         large = 0                   # large-arc-flag
  301.         if diff > math.pi:
  302.             large = 1
  303.         xt = rm*math.cos(a1)
  304.         yt = w*rm*math.sin(a1)
  305.         x1 = xt*math.cos(a) - yt*math.sin(a)
  306.         y1 = xt*math.sin(a) + yt*math.cos(a)
  307.         xt = rm*math.cos(a2)
  308.         yt = w*rm*math.sin(a2)
  309.         x2 = xt*math.cos(a) - yt*math.sin(a)
  310.         y2 = xt*math.sin(a) + yt*math.cos(a)
  311.         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)
  312.     else:                           # closed arc
  313.         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)
  314.     attribs = {'d': path, 'style': style}
  315.     inkex.etree.SubElement(layer, 'path', attribs)
  316.  
  317. def generate_gcodetools_point(xc, yc):
  318.     path= 'm %s,%s 2.9375,-6.34375 0.8125,1.90625 6.84375,-6.84375 0,0 0.6875,0.6875 -6.84375,6.84375 1.90625,0.8125 z' % (xc,yc)
  319.     attribs = {'d': path, inkex.addNS('dxfpoint','inkscape'):'1', 'style': 'stroke:#ff0000;fill:#ff0000'}
  320.     inkex.etree.SubElement(layer, 'path', attribs)
  321.  
  322. def get_line():
  323.     return (stream.readline().strip(), stream.readline().strip())
  324.  
  325. def get_group(group):
  326.     line = get_line()
  327.     if line[0] == group:
  328.         return float(line[1])
  329.     else:
  330.         return 0.0
  331.  
  332. #   define DXF Entities and specify which Group Codes to monitor
  333.  
  334. 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_INSERT, 'BLOCK': export_BLOCK, 'ENDBLK': export_ENDBLK, 'ATTDEF': export_ATTDEF, 'VIEWPORT': False, 'ENDSEC': False}
  335. groups = {'1': 0, '2': 1, '3': 2, '6': 3, '8': 4, '10': 5, '11': 6, '13': 7, '14': 8, '20': 9, '21': 10, '23': 11, '24': 12, '40': 13, '41': 14, '42': 15, '50': 16, '51': 17, '62': 18, '70': 19, '72': 20, '73': 21, '92': 22, '93': 23, '370': 24}
  336. colors = {  1: '#FF0000',   2: '#FFFF00',   3: '#00FF00',   4: '#00FFFF',   5: '#0000FF',
  337.             6: '#FF00FF',   8: '#414141',   9: '#808080',  12: '#BD0000',  30: '#FF7F00',
  338.           250: '#333333', 251: '#505050', 252: '#696969', 253: '#828282', 254: '#BEBEBE', 255: '#FFFFFF'}
  339.  
  340. parser = inkex.optparse.OptionParser(usage="usage: %prog [options] SVGfile", option_class=inkex.InkOption)
  341. parser.add_option("--auto", action="store", type="inkbool", dest="auto", default=True)
  342. parser.add_option("--scale", action="store", type="string", dest="scale", default="1.0")
  343. parser.add_option("--xmin", action="store", type="string", dest="xmin", default="0.0")
  344. parser.add_option("--ymin", action="store", type="string", dest="ymin", default="0.0")
  345. parser.add_option("--gcodetoolspoints", action="store", type="inkbool", dest="gcodetoolspoints", default=True)
  346. parser.add_option("--encoding", action="store", type="string", dest="input_encode", default="latin_1")
  347. parser.add_option("--font", action="store", type="string", dest="font", default="Arial")
  348. parser.add_option("--tab", action="store", type="string", dest="tab", default="Options")
  349. parser.add_option("--inputhelp", action="store", type="string", dest="inputhelp", default="")
  350. (options, args) = parser.parse_args(inkex.sys.argv[1:])
  351. doc = inkex.etree.parse(StringIO('<svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" width="%s" height="%s"></svg>' % (210*90/25.4, 297*90/25.4)))
  352. desc = inkex.etree.SubElement(doc.getroot(), 'desc', {})
  353. defs = inkex.etree.SubElement(doc.getroot(), 'defs', {})
  354. marker = inkex.etree.SubElement(defs, 'marker', {'id': 'DistanceX', 'orient': 'auto', 'refX': '0.0', 'refY': '0.0', 'style': 'overflow:visible'})
  355. inkex.etree.SubElement(marker, 'path', {'d': 'M 3,-3 L -3,3 M 0,-5 L  0,5', 'style': 'stroke:#000000; stroke-width:0.5'})
  356. pattern = inkex.etree.SubElement(defs, 'pattern', {'id': 'Hatch', 'patternUnits': 'userSpaceOnUse', 'width': '8', 'height': '8', 'x': '0', 'y': '0'})
  357. inkex.etree.SubElement(pattern, 'path', {'d': 'M8 4 l-4,4', 'stroke': '#000000', 'stroke-width': '0.25', 'linecap': 'square'})
  358. inkex.etree.SubElement(pattern, 'path', {'d': 'M6 2 l-4,4', 'stroke': '#000000', 'stroke-width': '0.25', 'linecap': 'square'})
  359. inkex.etree.SubElement(pattern, 'path', {'d': 'M4 0 l-4,4', 'stroke': '#000000', 'stroke-width': '0.25', 'linecap': 'square'})
  360. stream = open(args[0], 'r')
  361. xmax = xmin = ymin = 0.0
  362. height = 297.0*90.0/25.4                            # default A4 height in pixels
  363. line = get_line()
  364. flag = 0                                            # (0, 1, 2, 3) = (none, LAYER, LTYPE, DIMTXT)
  365. layer_colors = {}                                   # store colors by layer
  366. layer_nodes = {}                                    # store nodes by layer
  367. linetypes = {}                                      # store linetypes by name
  368. DIMTXT = {}                                         # store DIMENSION text sizes
  369.  
  370. while line[0] and line[1] != 'BLOCKS':
  371.     line = get_line()
  372.     if options.auto:
  373.         if line[1] == '$EXTMIN':
  374.             xmin = get_group('10')
  375.             ymin = get_group('20')
  376.         if line[1] == '$EXTMAX':
  377.             xmax = get_group('10')
  378.     if flag == 1 and line[0] == '2':
  379.         layername = unicode(line[1], options.input_encode)
  380.         attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '%s' % layername}
  381.         layer_nodes[layername] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
  382.     if flag == 2 and line[0] == '2':
  383.         linename = unicode(line[1], options.input_encode)
  384.         linetypes[linename] = []
  385.     if flag == 3 and line[0] == '2':
  386.         stylename = unicode(line[1], options.input_encode)
  387.     if line[0] == '2' and line[1] == 'LAYER':
  388.         flag = 1
  389.     if line[0] == '2' and line[1] == 'LTYPE':
  390.         flag = 2
  391.     if line[0] == '2' and line[1] == 'DIMSTYLE':
  392.         flag = 3
  393.     if flag == 1 and line[0] == '62':
  394.         layer_colors[layername] = int(line[1])
  395.     if flag == 2 and line[0] == '49':
  396.         linetypes[linename].append(float(line[1]))
  397.     if flag == 3 and line[0] == '140':
  398.         DIMTXT[stylename] = float(line[1])
  399.     if line[0] == '0' and line[1] == 'ENDTAB':
  400.         flag = 0
  401.  
  402. if options.auto:
  403.     scale = 1.0
  404.     if xmax > xmin:
  405.         scale = 210.0/(xmax - xmin)                 # scale to A4 width
  406. else:
  407.     scale = float(options.scale)                    # manual scale factor
  408.     xmin = float(options.xmin)
  409.     ymin = float(options.ymin)
  410. desc.text = '%s - scale = %f' % (unicode(args[0], options.input_encode), scale)
  411. scale *= 90.0/25.4                                  # convert from mm to pixels
  412.  
  413. if not layer_nodes:
  414.     attribs = {inkex.addNS('groupmode','inkscape'): 'layer', inkex.addNS('label','inkscape'): '0'}
  415.     layer_nodes['0'] = inkex.etree.SubElement(doc.getroot(), 'g', attribs)
  416.     layer_colors['0'] = 7
  417.  
  418. for linename in linetypes.keys():                   # scale the dashed lines
  419.     linetype = ''
  420.     for length in linetypes[linename]:
  421.         if length == 0:                             # test for dot
  422.             linetype += ' 0.5,'
  423.         else:
  424.             linetype += '%.4f,' % math.fabs(length*scale)
  425.     if linetype == '':
  426.         linetypes[linename] = 'stroke-linecap: round'
  427.     else:
  428.         linetypes[linename] = 'stroke-dasharray:' + linetype
  429.  
  430. entity = ''
  431. inENTITIES = False
  432. block = defs                                        # initiallize with dummy
  433. while line[0] and (line[1] != 'ENDSEC' or not inENTITIES):
  434.     line = get_line()
  435.     if line[1] == 'ENTITIES':
  436.         inENTITIES = True
  437.     if entity and groups.has_key(line[0]):
  438.         seqs.append(line[0])                        # list of group codes
  439.         if line[0] == '1' or line[0] == '2' or line[0] == '3' or line[0] == '6' or line[0] == '8':  # text value
  440.             val = line[1].replace('\~', ' ')
  441.             val = inkex.re.sub( '\\\\A.*;', '', val)
  442.             val = inkex.re.sub( '\\\\H.*;', '', val)
  443.             val = inkex.re.sub( '\\^I', '', val)
  444.             val = inkex.re.sub( '{\\\\L', '', val)
  445.             val = inkex.re.sub( '}', '', val)
  446.             val = inkex.re.sub( '\\\\S.*;', '', val)
  447.             val = inkex.re.sub( '\\\\W.*;', '', val)
  448.             val = unicode(val, options.input_encode)
  449.             val = val.encode('unicode_escape')
  450.             val = inkex.re.sub( '\\\\\\\\U\+([0-9A-Fa-f]{4})', '\\u\\1', val)
  451.             val = val.decode('unicode_escape')
  452.         elif line[0] == '62' or line[0] == '70' or line[0] == '92' or line[0] == '93':
  453.             val = int(line[1])
  454.         elif line[0] == '10' or line[0] == '13' or line[0] == '14': # scaled float x value
  455.             val = scale*(float(line[1]) - xmin)
  456.         elif line[0] == '20' or line[0] == '23' or line[0] == '24': # scaled float y value
  457.             val = height - scale*(float(line[1]) - ymin)
  458.         else:                                       # unscaled float value
  459.             val = float(line[1])
  460.         vals[groups[line[0]]].append(val)
  461.     elif entities.has_key(line[1]):
  462.         if entities.has_key(entity):
  463.             if block != defs:                       # in a BLOCK
  464.                 layer = block
  465.             elif vals[groups['8']]:                 # use Common Layer Name
  466.                 layer = layer_nodes[vals[groups['8']][0]]
  467.             color = '#000000'                       # default color
  468.             if vals[groups['8']]:
  469.                 if layer_colors.has_key(vals[groups['8']][0]):
  470.                     if colors.has_key(layer_colors[vals[groups['8']][0]]):
  471.                         color = colors[layer_colors[vals[groups['8']][0]]]
  472.             if vals[groups['62']]:                  # Common Color Number
  473.                 if colors.has_key(vals[groups['62']][0]):
  474.                     color = colors[vals[groups['62']][0]]
  475.             style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none'})
  476.             w = 0.5                                 # default lineweight for POINT
  477.             if vals[groups['370']]:                 # Common Lineweight
  478.                 if vals[groups['370']][0] > 0:
  479.                     w = 90.0/25.4*vals[groups['370']][0]/100.0
  480.                     if w < 0.5:
  481.                         w = 0.5
  482.                     style = simplestyle.formatStyle({'stroke': '%s' % color, 'fill': 'none', 'stroke-width': '%.1f' % w})
  483.             if vals[groups['6']]:                   # Common Linetype
  484.                 if linetypes.has_key(vals[groups['6']][0]):
  485.                     style += ';' + linetypes[vals[groups['6']][0]]
  486.             if entities[entity]:
  487.                 entities[entity]()
  488.         entity = line[1]
  489.         vals = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
  490.         seqs = []
  491.  
  492. doc.write(inkex.sys.stdout)
  493.  
  494. # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99
  495.