git-svn-id: https://eggbotcode.googlecode.com/svn/trunk@165 72233254-1b6c-9e9c-5072-401df62706fb
pull/47/head
newman.daniel1 2010-11-14 04:45:02 +00:00
rodzic d7bc927004
commit 8d4092e144
6 zmienionych plików z 1722 dodań i 0 usunięć

Wyświetl plik

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<_name>Hatch fill</_name>
<id>command.evilmadscience.eggbot_hatch.eggbot</id>
<dependency type="extension">org.inkscape.output.svg.inkscape</dependency>
<dependency type="executable" location="extensions">eggbot_hatch.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency>
<dependency type="executable" location="extensions">simplepath.py</dependency>
<dependency type="executable" location="extensions">simpletransform.py</dependency>
<dependency type="executable" location="extensions">simplestyle.py</dependency>
<dependency type="executable" location="extensions">cubicsuperpath.py</dependency>
<dependency type="executable" location="extensions">cspsubdiv.py</dependency>
<dependency type="executable" location="extensions">bezmisc.py</dependency>
<_param name="Header" type="description" xml:space="preserve">
This extension fills each closed
figure in your drawing with straight
back and forth hatch lines. If one
or more figures are selected, then
only those figures will be filled.
Hatched figures will be grouped with
their fills.
For smoothly flowing, continuous
line fills, use the Path Effect
Editor's "Hatches (rough)" effect
and the EggBot extension "Preset
hatch for fills...". This extension
is not controlled by the "Preset
hatch for fills..." extension.
Hatch line angles are measured
from horizontal: 0 is horizontal
and 90 is vertical.
Hatch spacing is the distance
between hatch lines measured in
units of motor steps.
</_param>
<param name="hatchAngle" type="float" min="-360" max="360"
_gui-text=" Hatch angle (degrees)">90</param>
<param name="hatchSpacing" type="float" min="0" max="1000"
_gui-text=" Hatch spacing (steps)">8.0</param>
<param name="crossHatch" type="boolean"
_gui-text=" Crosshatch?">false</param>
<effect needs-live-preview="false">
<object-type>all</object-type>
<effects-menu>
<submenu _name="EggBot"/>
</effects-menu>
</effect>
<script>
<command reldir="extensions" interpreter="python">eggbot_hatch.py</command>
</script>
</inkscape-extension>

Wyświetl plik

@ -0,0 +1,917 @@
#!/usr/bin/env python
# eggbot_hatch.py
#
# Generate hatch fills for the closed paths (polygons) in the currently
# selected document elements. If no elements are selected, then all the
# polygons throughout the document are hatched. The fill rule is an odd/even
# rule: odd numbered intersections (1, 3, 5, etc.) are a hatch line entering
# a polygon while even numbered intersections (2, 4, 6, etc.) are the same
# hatch line exiting the polygon.
#
# This extension first decomposes the selected <path>, <rect>, <line>,
# <polyline>, <polygon>, <circle>, and <ellipse> elements into individual
# moveto and lineto coordinates using the same procedure that eggbot.py uses
# for plotting. These coordinates are then used to build vertex lists.
# Only the vertex lists corresponding to polygons (closed paths) are
# kept. Note that a single graphical element may be composed of several
# subpaths, each subpath potentially a polygon.
#
# Once the lists of all the vertices are built, potential hatch lines are
# "projected" through the bounding box containing all of the vertices.
# For each potential hatch line, all intersections with all the polygon
# edges are determined. These intersections are stored as decimal fractions
# indicating where along the length of the hatch line the intersection
# occurs. These values will always be in the range [0, 1]. A value of 0
# indicates that the intersection is at the start of the hatch line, a value
# of 0.5 midway, and a value of 1 at the end of the hatch line.
#
# For a given hatch line, all the fractional values are sorted and any
# duplicates removed. Duplicates occur, for instance, when the hatch
# line passes through a polygon vertex and thus intersects two edges
# segments of the polygon: the end of one edge and the start of
# another.
#
# Once sorted and duplicates removed, an odd/even rule is applied to
# determine which segments of the potential hatch line are within
# polygons. These segments found to be within polygons are then saved
# and become the hatch fill lines which will be drawn.
#
# With each saved hatch fill line, information about which SVG graphical
# element it is within is saved. This way, the hatch fill lines can
# later be grouped with the element they are associated with. This makes
# it possible to manipulate the two -- graphical element and hatch lines --
# as a single object within Inkscape.
#
# Note: we also save the transformation matrix for each graphical element.
# That way, when we group the hatch fills with the element they are
# filling, we can invert the transformation. That is, in order to compute
# the hatch fills, we first have had apply ALL applicable transforms to
# all the graphical elements. We need to do that so that we know where in
# the drawing each of the graphical elements are relative to one another.
# However, this means that the hatch lines have been computed in a setting
# where no further transforms are needed. If we then put these hatch lines
# into the same groups as the elements being hatched in the ORIGINAL
# drawing, then the hatch lines will have transforms applied again. So,
# once we compute the hatch lines, we need to invert the transforms of
# the group they will be placed in and apply this inverse transform to the
# hatch lines. Hence the need to save the transform matrix for every
# graphical element.
#
# Written by Daniel C. Newman for the Eggbot Project
# dan dot newman at mtbaldy dot us
# 15 October 2010
#
# 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
import simplepath
import simpletransform
import simplestyle
import cubicsuperpath
import cspsubdiv
import bezmisc
import math
#import time
'''
Geometry 101: Determing if two lines intersect
A line L is defined by two points in space P1 and P2. Any point P on the
line L satisfies
P = P1 + s (P2 - P1)
for some value of the real number s in the range (-infinity, infinity).
If we confine s to the range [0, 1] then we've described the line segment
with end points P1 and P2.
Consider now the line La defined by the points P1 and P2, and the line Lb
defined by the points P3 and P4. Any points Pa and Pb on the lines La and
Lb therefore satisfy
Pa = P1 + sa (P2 - P1)
Pb = P3 + sb (P4 - P3)
for some values of the real numbers sa and sb. To see if these two lines
La and Lb intersect, we wish to see if there are finite values sa and sb
for which
Pa = Pb
Or, equivalently, we ask if there exists values of sa and sb for which
the equation
P1 + sa (P2 - P1) = P3 + sb (P4 - P3)
holds. If we confine ourselves to a two-dimensional plane, and take
P1 = (x1, y1)
P2 = (x2, y2)
P3 = (x3, y3)
P4 = (x4, y4)
we then find that we have two equations in two unknowns, sa and sb,
x1 + sa ( x2 - x1 ) = x3 + sb ( x4 - x3 )
y1 + sa ( y2 - y1 ) = y3 + sb ( y4 - y3 )
Solving these two equations for sa and sb yields,
sa = [ ( y1 - y3 ) ( x4 - x3 ) - ( y4 - y3 ) ( x1 - x3 ) ] / d
sb = [ ( y1 - y3 ) ( x2 - x1 ) - ( y2 - y1 ) ( x1 - x3 ) ] / d
where the denominator, d, is given by
d = ( y4 - y3 ) ( x2 - x1 ) - ( y2 - y1 ) ( x4 - x3 )
Substituting these back for the point (x, y) of intersection gives
x = x1 + sa ( x2 - x1 )
y = y1 + sa ( y2 - y1 )
Note that
1. The lines are parallel when d = 0
2. The lines are coincident d = 0 and the numerators for sa & sb are zero
3. For line segments, sa and sb are in the range [0, 1]; any value outside
that range indicates that the line segments do not intersect.
'''
def intersect( P1, P2, P3, P4 ):
'''
Determine if two line segments defined by the four points P1 & P2 and
P3 & P4 intersect. If they do intersect, then return the fractional
point of intersection "sa" along the first line at which the
intersection occurs.
'''
# Precompute these values -- note that we're basically shifting from
#
# P = P1 + s (P2 - P1)
#
# to
#
# P = P1 + s D
#
# where D is a direction vector. The solution remains the same of
# course. We'll just be computing D once for each line rather than
# computing it a couple of times.
D21x = P2[0] - P1[0]
D21y = P2[1] - P1[1]
D43x = P4[0] - P3[0]
D43y = P4[1] - P3[1]
# Denominator
d = D21x * D43y - D21y * D43x
# Return now if the denominator is zero
if d == 0:
return float( -1 )
# For our purposes, the first line segment given
# by P1 & P2 is the LONG hatch line running through
# the entire drawing. And, P3 & P4 describe the
# usually much shorter line segment from a polygon.
# As such, we compute sb first as it's more likely
# to indicate "no intersection". That is, sa is
# more likely to indicate an intersection with a
# much a long line containing P3 & P4.
nb = ( P1[1] - P3[1] ) * D21x - ( P1[0] - P3[0] ) * D21y
# Could first check if abs(nb) > abs(d) or if
# the signs differ.
sb = float( nb ) / float( d )
if ( sb < 0 ) or ( sb > 1 ):
return float( -1 )
na = ( P1[1] - P3[1] ) * D43x - ( P1[0] - P3[0] ) * D43y
sa = float( na ) / float( d )
if ( sa < 0 ) or ( sa > 1 ):
return float( -1 )
return sa
def interstices( P1, P2, paths, hatches ):
'''
For the line L defined by the points P1 & P2, determine the segments
of L which lie within the polygons described by the paths stored in
"paths"
P1 -- (x,y) coordinate [list]
P2 -- (x,y) coordinate [list]
paths -- Dictionary of all the paths to check for intersections
When an intersection of the line L is found with a polygon edge, then
the fractional distance along the line L is saved along with the
lxml.etree node which contained the intersecting polygon edge. This
fractional distance is always in the range [0, 1].
Once all polygons have been checked, the list of fractional distances
corresponding to intersections is sorted and any duplicates removed.
It is then assumed that the first intersection is the line L entering
a polygon; the second intersection the line leaving the polygon. This
line segment defined by the first and second intersection points is
thus a hatch fill line we sought to generate. In general, our hatch
fills become the line segments described by intersection i and i+1
with i an odd value (1, 3, 5, ...). Since we know the lxml.etree node
corresponding to each intersection, we can then correlate the hatch
fill lines to the graphical elements in the original SVG document.
This enables us to group hatch lines with the elements being hatched.
The hatch line segments are returned by populating a dictionary.
The dictionary is keyed off of the lxml.etree node pointer. Each
dictionary value is a list of 4-tuples,
(x1, y1, x2, y2)
where (x1, y1) and (x2, y2) are the (x,y) coordinates of the line
segment's starting and ending points.
'''
sa = []
# P1 & P2 is the hatch line
# P3 & P4 is the polygon edge to check
for path in paths:
for subpath in paths[path]:
P3 = subpath[0]
for P4 in subpath[1:]:
s = intersect( P1, P2, P3, P4 )
if ( s >= 0.0 ) and ( s <= 1.0 ):
# Save this intersection point along the hatch line
sa.append( ( s, path ) )
P3 = P4
# Return now if there were no intersections
if len( sa ) == 0:
return None
# Sort the intersections
sa.sort()
# Remove duplicates intersections. A common case where these arise
# in when the hatch line passes through a vertex where one line segment
# ends and the next one begins.
# Having had sorted the data, it's trivial to just scan through
# removing duplicates as we go and then truncating the array
n = len( sa )
ilast = i = 1
last = sa[0]
while i < n:
if abs( sa[i][0] - last[0] ) > 0.00001:
sa[ilast] = last = sa[i]
ilast += 1
i += 1
sa = sa[:ilast]
if len( sa ) < 2:
return
# Now, entries with even valued indices into sa[] are where we start
# a hatch line and odd valued indices where we end the hatch line.
for i in range( 0, len( sa ) - 1, 2 ):
if not hatches.has_key( sa[i][1] ):
hatches[sa[i][1]] = []
x1 = P1[0] + sa[i][0] * ( P2[0] - P1[0] )
y1 = P1[1] + sa[i][0] * ( P2[1] - P1[1] )
x2 = P1[0] + sa[i+1][0] * ( P2[0] - P1[0] )
y2 = P1[1] + sa[i+1][0] * ( P2[1] - P1[1] )
hatches[sa[i][1]].append( [[x1, y1], [x2, y2]] )
def inverseTransform ( tran ):
'''
An SVG transform matrix looks like
[ a c e ]
[ b d f ]
[ 0 0 1 ]
And it's inverse is
[ d -c cf - de ]
[ -b a be - af ] * ( ad - bc ) ** -1
[ 0 0 1 ]
And, no reasonable 2d coordinate transform will have
the products ad and bc equal.
SVG represents the transform matrix column by column as
matrix(a b c d e f) while Inkscape extensions store the
transform matrix as
[[a, c, e], [b, d, f]]
To invert the transform stored Inskcape style, we wish to
produce
[[d/D, -c/D, (cf - de)/D], [-b/D, a/D, (be-af)/D]]
where
D = 1 / (ad - bc)
'''
D = tran[0][0] * tran[1][1] - tran[1][0] * tran[0][1]
if D == 0:
return None
return [[tran[1][1]/D, -tran[0][1]/D,
(tran[0][1]*tran[1][2] - tran[1][1]*tran[0][2])/D],
[-tran[1][0]/D, tran[0][0]/D,
(tran[1][0]*tran[0][2] - tran[0][0]*tran[1][2])/D]]
# Lifted with impunity from eggbot.py
def subdivideCubicPath( sp, flat, i=1 ):
"""
Break up a bezier curve into smaller curves, each of which
is approximately a straight line within a given tolerance
(the "smoothness" defined by [flat]).
This is a modified version of cspsubdiv.cspsubdiv() rewritten
to avoid recurrence.
"""
while True:
while True:
if i >= len( sp ):
return
p0 = sp[i - 1][1]
p1 = sp[i - 1][2]
p2 = sp[i][0]
p3 = sp[i][1]
b = ( p0, p1, p2, p3 )
if cspsubdiv.maxdist( b ) > flat:
break
i += 1
one, two = bezmisc.beziersplitatt( b, 0.5 )
sp[i - 1][2] = one[1]
sp[i][0] = two[2]
p = [one[2], one[3], two[1]]
sp[i:1] = [p]
def distanceSquared( P1, P2 ):
'''
Pythagorean distance formula WITHOUT the square root. Since
we just want to know if the distance is less than some fixed
fudge factor, we can just square the fudge factor once and run
with it rather than compute square roots over and over.
'''
dx = P2[0] - P1[0]
dy = P2[1] - P1[1]
return ( dx * dx + dy * dy )
class Eggbot_Hatch( inkex.Effect ):
def __init__( self ):
inkex.Effect.__init__( self )
#self.t0 = time.clock()
self.xmin, self.ymin = ( float( 0 ), float( 0 ) )
self.xmax, self.ymax = ( float( 0 ), float( 0 ) )
self.paths = {}
self.grid = []
self.hatches = {}
self.transforms = {}
self.OptionParser.add_option(
"--crossHatch", action="store", dest="crossHatch",
type="inkbool", default=False,
help="Generate a cross hatch pattern" )
self.OptionParser.add_option(
"--hatchAngle", action="store", type="float",
dest="hatchAngle", default=90.0,
help="Angle of inclination for hatch lines" )
self.OptionParser.add_option(
"--hatchSpacing", action="store", type="float",
dest="hatchSpacing", default=10.0,
help="Spacing between hatch lines" )
def addPathVertices( self, path, node=None, transform=None ):
'''
Decompose the path data from an SVG element into individual
subpaths, each starting with an absolute move-to (x, y)
coordinate followed by one or more absolute line-to (x, y)
coordinates. Each subpath is stored as a list of (x, y)
coordinates, with the first entry understood to be a
move-to coordinate and the rest line-to coordinates. A list
is then made of all the subpath lists and then stored in the
self.paths dictionary using the path's lxml.etree node pointer
as the dictionary key.
'''
if ( not path ) or ( len( path ) == 0 ):
return
# parsePath() may raise an exception. This is okay
sp = simplepath.parsePath( path )
if ( not sp ) or ( len( sp ) == 0 ):
return
# Get a cubic super duper path
p = cubicsuperpath.CubicSuperPath( sp )
if ( not p ) or ( len( p ) == 0 ):
return
# Apply any transformation
if transform:
simpletransform.applyTransformToPath( transform, p )
# Now traverse the simplified path
subpaths = []
subpath_vertices = []
for sp in p:
# We've started a new subpath
# See if there is a prior subpath and whether we should keep it
if len( subpath_vertices ):
if distanceSquared( subpath_vertices[0], subpath_vertices[-1] ) < 1:
# Keep the prior subpath: it appears to be a closed path
subpaths.append( subpath_vertices )
subpath_vertices = []
subdivideCubicPath( sp, float( 0.2 ) )
for csp in sp:
# Add this vertex to the list of vetices
subpath_vertices.append( csp[1] )
# Handle final subpath
if len( subpath_vertices ):
if distanceSquared( subpath_vertices[0], subpath_vertices[-1] ) < 1:
# Path appears to be closed so let's keep it
subpaths.append( subpath_vertices )
# Empty path?
if len( subpaths ) == 0:
return
# And add this path to our dictionary of paths
self.paths[node] = subpaths
# And save the transform for this element in a dictionary keyed
# by the element's lxml node pointer
self.transforms[node] = transform
def getBoundingBox( self ):
'''
Determine the bounding box for our collection of polygons
'''
self.xmin, self.xmax = float( 1.0E70 ), float( -1.0E70 )
self.ymin, self.ymax = float( 1.0E70 ), float( -1.0E70 )
for path in self.paths:
for subpath in self.paths[path]:
for vertex in subpath:
if vertex[0] < self.xmin:
self.xmin = vertex[0]
elif vertex[0] > self.xmax:
self.xmax = vertex[0]
if vertex[1] < self.ymin:
self.ymin = vertex[1]
elif vertex[1] > self.ymax:
self.ymax = vertex[1]
def recursivelyTraverseSvg( self, aNodeList,
matCurrent=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
parent_visibility='visible' ):
'''
Recursively walk the SVG document, building polygon vertex lists
for each graphical element we support.
Rendered SVG elements:
<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>
Supported SVG elements:
<group>, <use>
Ignored SVG elements:
<defs>, <eggbot>, <metadata>, <namedview>, <pattern>
All other SVG elements trigger an error (including <text>)
'''
for node in aNodeList:
# Ignore invisible nodes
v = node.get( 'visibility', parent_visibility )
if v == 'inherit':
v = parent_visibility
if v == 'hidden' or v == 'collapse':
pass
# first apply the current matrix transform to this node's tranform
matNew = simpletransform.composeTransform( matCurrent,
simpletransform.parseTransform( node.get( "transform" ) ) )
if node.tag == inkex.addNS( 'g', 'svg' ) or node.tag == 'g':
self.recursivelyTraverseSvg( node, matNew, parent_visibility=v )
elif node.tag == inkex.addNS( 'use', 'svg' ) or node.tag == 'use':
# A <use> element refers to another SVG element via an xlink:href="#blah"
# attribute. We will handle the element by doing an XPath search through
# the document, looking for the element with the matching id="blah"
# attribute. We then recursively process that element after applying
# any necessary (x,y) translation.
#
# Notes:
# 1. We ignore the height and width attributes as they do not apply to
# path-like elements, and
# 2. Even if the use element has visibility="hidden", SVG still calls
# for processing the referenced element. The referenced element is
# hidden only if its visibility is "inherit" or "hidden".
refid = node.get( inkex.addNS( 'href', 'xlink' ) )
if not refid:
pass
# [1:] to ignore leading '#' in reference
path = '//*[@id="%s"]' % refid[1:]
refnode = node.xpath( path )
if refnode:
x = float( node.get( 'x', '0' ) )
y = float( node.get( 'y', '0' ) )
tran = node.get( 'transform' )
if tran:
tran += ' translate(%f,%f)' % ( x, y )
else:
tran = 'translate(%f,%f)' % ( x, y )
matNew2 = simpletransform.composeTransform( matNew,
simpletransform.parseTransform( tran ) )
v = node.get( 'visibility', v )
self.recursivelyTraverseSvg( refnode, matNew2, parent_visibility=v )
elif node.tag == inkex.addNS( 'path', 'svg' ):
path_data = node.get( 'd')
if path_data:
self.addPathVertices( path_data, node, matNew )
elif node.tag == inkex.addNS( 'rect', 'svg' ) or node.tag == 'rect':
# Manually transform
#
# <rect x="X" y="Y" width="W" height="H"/>
#
# into
#
# <path d="MX,Y lW,0 l0,H l-W,0 z"/>
#
# I.e., explicitly draw three sides of the rectangle and the
# fourth side implicitly
# Create a path with the outline of the rectangle
x = float( node.get( 'x' ) )
y = float( node.get( 'y' ) )
if ( not x ) or ( not y ):
pass
w = float( node.get( 'width', '0' ) )
h = float( node.get( 'height', '0' ) )
a = []
a.append( ['M ', [x, y]] )
a.append( [' l ', [w, 0]] )
a.append( [' l ', [0, h]] )
a.append( [' l ', [-w, 0]] )
a.append( [' Z', []] )
self.addPathVertices( simplepath.formatPath( a ), node, matNew )
elif node.tag == inkex.addNS( 'line', 'svg' ) or node.tag == 'line':
# Convert
#
# <line x1="X1" y1="Y1" x2="X2" y2="Y2/>
#
# to
#
# <path d="MX1,Y1 LX2,Y2"/>
x1 = float( node.get( 'x1' ) )
y1 = float( node.get( 'y1' ) )
x2 = float( node.get( 'x2' ) )
y2 = float( node.get( 'y2' ) )
if ( not x1 ) or ( not y1 ) or ( not x2 ) or ( not y2 ):
pass
a = []
a.append( ['M ', [x1, y1]] )
a.append( [' L ', [x2, y2]] )
self.addPathVertices( simplepath.formatPath( a ), node, matNew )
elif node.tag == inkex.addNS( 'polyline', 'svg' ) or node.tag == 'polyline':
# Convert
#
# <polyline points="x1,y1 x2,y2 x3,y3 [...]"/>
#
# to
#
# <path d="Mx1,y1 Lx2,y2 Lx3,y3 [...]"/>
#
# Note: we ignore polylines with no points
pl = node.get( 'points', '' ).strip()
if pl == '':
pass
pa = pl.split()
d = "".join( ["M " + pa[i] if i == 0 else " L " + pa[i] for i in range( 0, len( pa ) )] )
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'polygon', 'svg' ) or node.tag == 'polygon':
# Convert
#
# <polygon points="x1,y1 x2,y2 x3,y3 [...]"/>
#
# to
#
# <path d="Mx1,y1 Lx2,y2 Lx3,y3 [...] Z"/>
#
# Note: we ignore polygons with no points
pl = node.get( 'points', '' ).strip()
if pl == '':
pass
pa = pl.split()
d = "".join( ["M " + pa[i] if i == 0 else " L " + pa[i] for i in range( 0, len( pa ) )] )
d += " Z"
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'ellipse', 'svg' ) or \
node.tag == 'ellipse' or \
node.tag == inkex.addNS( 'circle', 'svg' ) or \
node.tag == 'circle':
# Convert circles and ellipses to a path with two 180 degree arcs.
# In general (an ellipse), we convert
#
# <ellipse rx="RX" ry="RY" cx="X" cy="Y"/>
#
# to
#
# <path d="MX1,CY A RX,RY 0 1 0 X2,CY A RX,RY 0 1 0 X1,CY"/>
#
# where
#
# X1 = CX - RX
# X2 = CX + RX
#
# Note: ellipses or circles with a radius attribute of value 0 are ignored
if node.tag == inkex.addNS( 'ellipse', 'svg' ) or node.tag == 'ellipse':
rx = float( node.get( 'rx', '0' ) )
ry = float( node.get( 'ry', '0' ) )
else:
rx = float( node.get( 'r', '0' ) )
ry = rx
if rx == 0 or ry == 0:
pass
cx = float( node.get( 'cx', '0' ) )
cy = float( node.get( 'cy', '0' ) )
x1 = cx - rx
x2 = cx + rx
d = 'M %f,%f ' % ( x1, cy ) + \
'A %f,%f ' % ( rx, ry ) + \
'0 1 0 %f,%f ' % ( x2, cy ) + \
'A %f,%f ' % ( rx, ry ) + \
'0 1 0 %f,%f' % ( x1, cy )
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'pattern', 'svg' ) or node.tag == 'pattern':
pass
elif node.tag == inkex.addNS( 'metadata', 'svg' ) or node.tag == 'metadata':
pass
elif node.tag == inkex.addNS( 'defs', 'svg' ) or node.tag == 'defs':
pass
elif node.tag == inkex.addNS( 'namedview', 'sodipodi' ) or node.tag == 'namedview':
pass
elif node.tag == inkex.addNS( 'eggbot', 'svg' ) or node.tag == 'eggbot':
pass
elif node.tag == inkex.addNS( 'text', 'svg' ) or node.tag == 'text':
inkex.errormsg( 'Warning: unable to draw text, please convert it to a path first.' )
pass
elif not isinstance( node.tag, basestring ):
pass
else:
inkex.errormsg( 'Warning: unable to draw object <%s>, please convert it to a path first.' % node.tag )
pass
def joinFillsWithNode ( self, node, path ):
'''
Generate a SVG <path> element containing the path data "path".
Then put this new <path> element into a <group> with the supplied
node. This means making a new <group> element and moving node
under it with the new <path> as a sibling element.
'''
if ( not path ) or ( len( path ) == 0 ):
return
# Make a new SVG <group> element whose parent is the parent of node
parent = node.getparent()
if not parent:
parent = self.document.getroot()
g = inkex.etree.SubElement( parent, inkex.addNS( 'g', 'svg' ) )
# Move node to be a child of this new <g> element
g.append( node )
# Now make a <path> element which contains the hatches & is a child
# of the new <g> element
style = { 'stroke': '#000000', 'fill': 'none', 'stroke-width': '1' }
line_attribs = { 'style':simplestyle.formatStyle( style ), 'd': path }
inkex.etree.SubElement( g, inkex.addNS( 'path', 'svg' ), line_attribs )
def makeHatchGrid( self, angle, spacing, init=True ):
'''
Build a grid of hatch lines which encompasses the entire bounding
box of the graphical elements we are to hatch.
1. Figure out the bounding box for all of the graphical elements
2. Pick a rectangle larger than that bounding box so that we can
later rotate the rectangle and still have it cover the bounding
box of the graphical elements.
3. Center the rectangle of 2 on the origin (0, 0).
4. Build the hatch line grid in this rectangle.
5. Rotate the rectangle by the hatch angle.
6. Translate the center of the rotated rectangle, (0, 0), to be
the center of the bounding box for the graphical elements.
7. We now have a grid of hatch lines which overlay the graphical
elements and can now be intersected with those graphical elements.
'''
# If this is the first call, do some one time initializations
# When generating cross hatches, we may be called more than once
if init:
self.getBoundingBox()
self.grid = []
# Determine the width and height of the bounding box containing
# all the polygons to be hatched
w = self.xmax - self.xmin
h = self.ymax - self.ymin
# Nice thing about rectangles is that the diameter of the circle
# encompassing them is the length the rectangle's diagonal...
r = math.sqrt ( w * w + h * h) / 2.0
# Now generate hatch lines within the square
# centered at (0, 0) and with side length at least d
# While we could generate these lines running back and forth,
# that makes for weird behavior later when applying odd/even
# rules AND there are nested polygons. Instead, when we
# generate the SVG <path> elements with the hatch line
# segments, we can do the back and forth weaving.
# Rotation information
ca = math.cos( math.radians( 90 - angle ) )
sa = math.sin( math.radians( 90 - angle ) )
# Translation information
cx = self.xmin + ( w / 2 )
cy = self.ymin + ( h / 2 )
# Since the spacing may be fractional (e.g., 6.5), we
# don't try to use range() or other integer iterator
spacing = float( abs( spacing ) )
i = -r
while i <= r:
# Line starts at (i, -r) and goes to (i, +r)
x1 = cx + ( i * ca ) + ( r * sa ) # i * ca - (-r) * sa
y1 = cy + ( i * sa ) - ( r * ca ) # i * sa + (-r) * ca
x2 = cx + ( i * ca ) - ( r * sa ) # i * ca - (+r) * sa
y2 = cy + ( i * sa ) + ( r * ca ) # i * sa + (+r) * ca
i += spacing
# Remove any potential hatch lines which are entirely
# outside of the bounding box
if (( x1 < self.xmin ) and ( x2 < self.xmin )) or \
(( x1 > self.xmax ) and ( x2 > self.xmax )):
continue
if (( y1 < self.ymin ) and ( y2 < self.ymin )) or \
(( y1 > self.ymax ) and ( y2 > self.ymax )):
continue
self.grid.append( ( x1, y1, x2, y2 ) )
def effect( self ):
# Build a list of the vertices for the document's graphical elements
if self.options.ids:
# Traverse the selected objects
for id in self.options.ids:
self.recursivelyTraverseSvg( [self.selected[id]] )
else:
# Traverse the entire document
self.recursivelyTraverseSvg( self.document.getroot() )
# Build a grid of possible hatch lines
self.makeHatchGrid( float( self.options.hatchAngle ),
float( self.options.hatchSpacing ), True )
if self.options.crossHatch:
self.makeHatchGrid( float( self.options.hatchAngle + 90.0 ),
float( self.options.hatchSpacing ), False )
# Now loop over our hatch lines looking for intersections
for h in self.grid:
interstices( (h[0], h[1]), (h[2], h[3]), self.paths, self.hatches )
# Now, dump the hatch fills sorted by which document element
# they correspond to. This is made easy by the fact that we
# saved the information and used each element's lxml.etree node
# pointer as the dictionary key under which to save the hatch
# fills for that node.
for key in self.hatches:
path = ''
direction = True
if self.transforms.has_key( key ):
transform = inverseTransform( self.transforms[key] )
else:
transform = None
for segment in self.hatches[key]:
pt1 = segment[0]
pt2 = segment[1]
# Okay, we're going to put these hatch lines into the same
# group as the element they hatch. That element is down
# some chain of SVG elements, some of which may have
# transforms attached. But, our hatch lines have been
# computed assuming that those transforms have already
# been applied (since we had to apply them so as to know
# where this element is on the page relative to other
# elements and their transforms). So, we need to invert
# the transforms for this element and then either apply
# that inverse transform here and now or set it in a
# transform attribute of the <path> element. Having it
# set in the path element seems a bit counterintuitive
# after the fact (i.e., what's this tranform here for?).
# So, we compute the inverse transform and apply it here.
if transform != None:
simpletransform.applyTransformToPoint( transform, pt1 )
simpletransform.applyTransformToPoint( transform, pt2 )
# Now generate the path data for the <path>
if direction:
# Go this direction
path += 'M %f,%f l %f,%f ' % \
( pt1[0], pt1[1], pt2[0] - pt1[0], pt2[1] - pt1[1] )
else:
# Or go this direction
path += 'M %f,%f l %f,%f ' % \
( pt2[0], pt2[1], pt1[0] - pt2[0], pt1[1] - pt2[1] )
direction = not direction
self.joinFillsWithNode( key, path[:-1] )
#inkex.errormsg("Elapsed CPU time was %f" % (time.clock()-self.t0))
if __name__ == '__main__':
e = Eggbot_Hatch()
e.affect()

Wyświetl plik

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<_name>Eggmazing</_name>
<id>eggmazing.eggbot</id>
<dependency type="extension">org.inkscape.output.svg.inkscape</dependency>
<dependency type="executable" location="extensions">eggbot_maze.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency>
<param name="mazeSize" type="optiongroup" appearance="" _gui-text="Maze dimensions (w x h):">
<option value="SMALL">Small (32 x 6)</option>
<option value="MEDIUM">Medium (64 x 12)</option>
<option value="LARGE">Large (96 x 18)</option>
<option value="XLARGE">Extra large (128 x 24)</option>
</param>
<effect needs-live-preview="false">
<object-type>all</object-type>
<effects-menu>
<submenu _name="EggBot"/>
</effects-menu>
</effect>
<script>
<command reldir="extensions" interpreter="python">eggbot_maze.py</command>
</script>
</inkscape-extension>

Wyświetl plik

@ -0,0 +1,567 @@
#!/usr/bin/env python
# Draw a cylindrical maze suitable for plotting with the Eggbot
# The maze itself is generated using a depth first search (DFS)
# Written by Daniel C. Newman for the Eggbot Project
# Improvements and suggestions by W. Craig Trader
# 20 September 2010
# 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 sys
import array
import random
import math
import inkex
import simplestyle
# Initialize the psuedo random number generator
random.seed()
PLOT_WIDTH = int( 3200 ) # Eggbot plot width in pixels
PLOT_HEIGHT = int( 1000 ) # Eggbot plot height in pixels
TARGET_WIDTH = int( 3200 ) # Desired plot width in pixels
TARGET_HEIGHT = int( 600 ) # Desired plot height in pixels
# Add a SVG path element to the document
# We could do this just as easily as a polyline
def draw_SVG_path(pts, c, t, l, parent):
if ( not pts ) or len( pts ) == 0: # Nothing to draw
return
assert len( pts ) % 2 == 0, "pts must have an even number of entries"
d = "M %d,%d" % ( pts[0], pts[1] )
for i in range( 2, len( pts ), 2 ):
d += " L %d,%d" % ( pts[i], pts[i+1] )
style = { 'stroke':c, 'stroke-width':str( t ), 'fill': 'none' }
line_attribs = { 'style':simplestyle.formatStyle( style ),
inkex.addNS( 'label','inkscape' ):l,
'd':d }
inkex.etree.SubElement( parent, inkex.addNS( 'path','svg' ),
line_attribs )
# Add a SVG rect element to the document
def draw_SVG_rect(x, y, w, h, c, t, fill, l, parent):
style = { 'stroke':c, 'stroke-width':str( t ), 'fill':fill }
rect_attribs = { 'style':simplestyle.formatStyle( style ),
inkex.addNS( 'label','inkscape' ):l,
'x':str( x ), 'y':str( y ),
'width':str( w ), 'height':str( h ) }
inkex.etree.SubElement( parent, inkex.addNS( 'rect', 'svg' ),
rect_attribs )
class Maze(inkex.Effect):
# Each cell in the maze is represented using 9 bits:
#
# Visited -- When set, indicates that this cell has been visited during
# construction of the maze
#
# Border -- Four bits indicating which if any of this cell's walls are
# part of the maze's boundary (i.e., are unremovable walls)
#
# Walls -- Four bits indicating which if any of this cell's walls are
# still standing
#
# Visited Border Walls
# x x x x x x x x x
# W S E N W S E N
_VISITED = 0x0100
_NORTH = 0x0001
_EAST = 0x0002
_SOUTH = 0x0004
_WEST = 0x0008
def __init__(self):
inkex.Effect.__init__( self )
self.OptionParser.add_option( "--mazeSize", action="store",
type="string", dest="mazeSize",
default="MEDIUM",
help="Difficulty of maze to build" )
self.w = int( 0 )
self.h = int( 0 )
self.solved = int( 0 )
self.start_x = int( 0 )
self.start_y = int( 0 )
self.finish_x = int( 0 )
self.finish_y = int( 0 )
self.solution_x = None
self.solution_y = None
self.cells = None
# Drawing information
self.scale = float( 25.0 )
self.maze_layer = None
self.maze_color = '#000000'
self.segment_id = 0
def effect(self):
# These dimensions are chosen so as to maintain integral dimensions
# with a ratio of width to height of TARGET_WIDTH to TARGET_HEIGHT.
# Presently that's 3200 to 600 which leads to a ratio of 5 and 1/3.
if self.options.mazeSize == 'SMALL':
self.w = int( 32 )
self.h = int( 6 )
elif self.options.mazeSize == 'MEDIUM':
self.w = int( 64 )
self.h = int( 12 )
elif self.options.mazeSize == 'LARGE':
self.w = int( 96 )
self.h = int( 18 )
else:
self.w = int( 128 )
self.h = int( 24 )
# The large mazes tend to hit the recursion limit
limit = sys.getrecursionlimit()
if limit < ( 4 + self.w * self.h ):
sys.setrecursionlimit( 4 + self.w * self.h )
maze_size = self.w * self.h
self.finish_x = int( self.w - 1 )
self.finish_y = int( self.h - 1 )
self.solution_x = array.array( 'i', range( 0, maze_size ) )
self.solution_y = array.array( 'i', range( 0, maze_size ) )
self.cells = array.array( 'H', range( 0, maze_size ) )
# Remove any old maze
for node in self.document.xpath( '//svg:g[@inkscape:label="1 - Maze"]', namespaces=inkex.NSS ):
parent = node.getparent()
parent.remove( node )
# Remove any old solution
for node in self.document.xpath( '//svg:g[@inkscape:label="2 - Solution"]', namespaces=inkex.NSS ):
parent = node.getparent()
parent.remove( node )
# Remove any empty, default "Layer 1"
for node in self.document.xpath( '//svg:g[@id="layer1"]', namespaces=inkex.NSS ):
if not node.getchildren():
parent = node.getparent()
parent.remove( node )
# Start a new maze
self.solved = 0
self.start_x = random.randint( 0, self.w - 1 )
self.finish_x = random.randint( 0, self.w - 1 )
# Initialize every cell with all four walls up
for i in range( 0, maze_size ):
self.cells[i] = Maze._NORTH | Maze._EAST | Maze._SOUTH | Maze._WEST
# Now set our borders -- borders being walls which cannot be removed.
# Since we are a maze on the surface of a cylinder we only have two
# edges and hence only two borders. We consider our two edges to run
# from WEST to EAST and to be at the NORTH and SOUTH.
z = ( self.h - 1 ) * self.w
for x in range( 0, self.w ):
self.cells[x] |= Maze._NORTH << 4
self.cells[x + z] |= Maze._SOUTH << 4
# Build the maze
self.handle_cell( 0, self.start_x, self.start_y )
# Now that the maze has been built, remove the appropriate walls
# associated with the start and finish points of the maze
# Note: we have to remove these after building the maze. If we
# remove them first, then the lack of a border at the start (or
# finish) cell will allow the handle_cell() routine to wander
# outside of the maze. I.e., handle_cell() doesn't do boundary
# checking on the cell cell coordinates it generates. Instead, it
# relies upon the presence of borders to prevent it wandering
# outside the confines of the maze.
self.remove_border( self.start_x, self.start_y, Maze._NORTH )
self.remove_wall( self.start_x, self.start_y, Maze._NORTH )
self.remove_border( self.finish_x, self.finish_y, Maze._SOUTH )
self.remove_wall( self.finish_x, self.finish_y, Maze._SOUTH )
# Now draw the maze
# The following scaling and translations scale the maze's
# (width, height) to (TARGET_WIDTH, TARGET_HEIGHT), and translates
# the maze so that it centered within a document of dimensions
# (width, height) = (PLOT_WIDTH, PLOT_HEIGHT)
# Note that each cell in the maze is drawn 2 x units wide by
# 2 y units high. A width and height of 2 was chosen for
# convenience and for allowing easy identification (as the integer 1)
# of the centerline along which to draw solution paths. It is the
# abstract units which are then mapped to the TARGET_WIDTH eggbot x
# pixels by TARGET_HEIGHT eggbot y pixels rectangle.
scale_x = float( TARGET_WIDTH ) / float( 2 * self.w )
scale_y = float( TARGET_HEIGHT ) / float( 2 * self.h )
translate_x = float( PLOT_WIDTH - TARGET_WIDTH ) / 2.0
translate_y = float( PLOT_HEIGHT - TARGET_HEIGHT ) / 2.0
# And the SVG transform is thus
t = 'translate(%f,%f)' % ( translate_x, translate_y ) + \
' scale(%f,%f)' % ( scale_x, scale_y )
# For scaling line thicknesses. We'll typically draw a line of
# thickness 1 but will need to make the SVG path have a thickness
# of 1 / scale so that after our transforms are applied, the
# resulting thickness is the 1 we wanted in the first place.
if scale_x > scale_y:
self.scale = scale_x
else:
self.scale = scale_y
# Maze in layer "1 - Maze"
attribs = { inkex.addNS( 'label', 'inkscape' ):'1 - Maze',
inkex.addNS( 'groupmode', 'inkscape' ):'layer',
'transform':t }
self.maze_layer = inkex.etree.SubElement( self.document.getroot(),
'g', attribs )
self.segment_id = 0
self.maze_color = '#000000'
# Draw the horizontal walls
self.draw_horizontal( 0, Maze._NORTH, 1 )
for y in range( 0, self.h - 1 ):
self.draw_horizontal( y, Maze._SOUTH, 0 )
self.draw_horizontal( self.h - 1, Maze._SOUTH, 1 )
# Draw the vertical walls
# Since this is a maze on the surface of a cylinder, we don't need
# to draw the vertical walls at the outer edges (x = 0 & x = w - 1)
for x in range( 0, self.w ):
self.draw_vertical( x, Maze._EAST, 0 )
# Now draw the solution in red in layer "2 - Solution"
attribs = { inkex.addNS( 'label', 'inkscape' ):'2 - Solution',
inkex.addNS( 'groupmode', 'inkscape' ):'layer',
'transform':t }
self.maze_layer = inkex.etree.SubElement( self.document.getroot(),
'g', attribs )
self.maze_color = '#ff0000'
# Mark the starting and ending cells
draw_SVG_rect( 0.25 + 2 * self.start_x, 0.25 + 2 * self.start_y,
1.5, 1.5, self.maze_color, 0, self.maze_color,
'maze'+str( self.segment_id ), self.maze_layer )
self.segment_id += 1
draw_SVG_rect( 0.25 + 2*self.finish_x, 0.25 + 2 * self.finish_y,
1.5, 1.5, self.maze_color, 0, self.maze_color,
'maze'+str( self.segment_id ), self.maze_layer )
self.segment_id += 1
# And now draw the solution path itself
# To minimize the number of plotted paths (and hence pen up / pen
# down operations), we generate as few SVG paths as possible.
# However, for aesthetic reasons we stop the path and start a new
# one when it runs off the edge of the document. We could keep on
# drawing as the eggbot will handle that just fine. However, it
# doesn't look as good in Inkscape. So, we end the path and start
# a new one which is wrapped to the other edge of the document.
path = []
end_path = int( 0 )
i = int( 0 )
while i < self.solved:
x1 = self.solution_x[i]
y1 = self.solution_y[i]
i += 1
x2 = self.solution_x[i]
y2 = self.solution_y[i]
if math.fabs( x1 - x2 ) > 1:
# We wrapped horizontally...
if x1 > x2:
x2 = x1 + 1
else:
x2 = x1 - 1
end_path = 1
if i == 1:
path.extend( [ 2 * x1 + 1, 2 * y1 + 1 ] )
path.extend( [ 2 * x2 + 1, 2 * y2 + 1 ] )
if not end_path:
continue
# Draw the path
draw_SVG_path( path, self.maze_color, float( 8 / self.scale ),
'maze' + str( self.segment_id ), self.maze_layer )
self.segment_id += 1
x2 = self.solution_x[i]
y2 = self.solution_y[i]
path = [2 * x2 + 1, 2 * y2 + 1]
end_path = 0
# And finish the solution path
draw_SVG_path( path, '#ff0000', float( 8 / self.scale ),
'maze' + str( self.segment_id ), self.maze_layer )
# Restore the recursion limit
sys.setrecursionlimit( limit )
# Set some document properties
node = self.document.getroot()
node.set( 'width', '3200' )
node.set( 'height', '1000' )
# The following end up being ignored by Inkscape....
node = self.getNamedView()
node.set( 'showborder', 'false' )
node.set( inkex.addNS( 'cx', u'inkscape' ), '1600' )
node.set( inkex.addNS( 'cy', u'inkscape' ), '500' )
node.set( inkex.addNS( 'showpageshadow', u'inkscape' ), 'false' )
# Mark the cell at (x, y) as "visited"
def visit(self, x, y):
self.cells[y * self.w + x] |= Maze._VISITED
# Return a non-zero value if the cell at (x, y) has been visited
def is_visited(self, x, y):
if self.cells[y * self.w + x] & Maze._VISITED:
return -1
else:
return 0
# Return a non-zero value if the cell at (x, y) has a wall
# in the direction d
def is_wall(self, x, y, d):
if self.cells[y * self.w + x] & d:
return -1
else:
return 0
# Remove the wall in the direction d from the cell at (x, y)
def remove_wall(self, x, y, d):
self.cells[y * self.w + x] &= ~d
# Return a non-zero value if the cell at (x, y) has a border wall
# in the direction d
def is_border(self, x, y, d):
if self.cells[y * self.w + x] & ( d << 4 ):
return -1
else:
return 0
# Remove the border in the direction d from the cell at (x, y)
def remove_border(self, x, y, d):
self.cells[y * self.w + x] &= ~( d << 4 )
# This is the DFS algorithm which builds the maze. We start at depth 0
# at the starting cell (self.start_x, self.start_y). We then walk to a
# randomly selected neighboring cell which has not yet been visited (i.e.,
# previously walked into). Each step of the walk is a recursive descent
# in depth. The solution to the maze comes about when we walk into the
# finish cell at (self.finish_x, self.finish_y).
#
# Each recursive descent finishes when the currently visited cell has no
# unvisited neighboring cells.
#
# Since we don't revisit previously visited cells, each cell is visited
# no more than once. As it turns out, each cell is visited, but that's a
# little harder to show. Net, net, each cell is visited exactly once.
def handle_cell(self, depth, x, y):
# Mark the current cell as visited
self.visit( x, y )
# Save this cell's location in our solution trail / backtrace
if not self.solved:
self.solution_x[depth] = x
self.solution_y[depth] = y
if ( x == self.finish_x ) and ( y == self.finish_y ):
# Maze has been solved
self.solved = depth
# Shuffle the four compass directions: this is the primary source
# of "randomness" in the generated maze. We need to visit each
# neighboring cell which has not yet been visited. If we always
# did that in the same order, then our mazes would look very regular.
# So, we shuffle the list of directions we try in order to find an
# unvisited neighbor.
# HINT: TRY COMMENTING OUT THE shuffle() BELOW AND SEE FOR YOURSELF
directions = [Maze._NORTH, Maze._SOUTH, Maze._EAST, Maze._WEST]
random.shuffle( directions )
# Now from the cell at (x, y), look to each of the four
# directions for unvisited neighboring cells
for i in range( 0, 4 ):
# If there is a border in direction[i], then don't try
# looking for a neighboring cell in that direction. We
# Use this check and borders to prevent generating invalid
# cell coordinates.
if self.is_border( x, y, directions[i] ):
continue
# Determine the cell coordinates of a neighboring cell
# NOTE: we trust the use of maze borders to prevent us
# from generating invalid cell coordinates
if directions[i] == Maze._NORTH:
nx = x
ny = y - 1
opposite_direction = Maze._SOUTH
elif directions[i] == Maze._SOUTH:
nx = x
ny = y + 1
opposite_direction = Maze._NORTH
elif directions[i] == Maze._EAST:
nx = x + 1
ny = y
opposite_direction = Maze._WEST
else:
nx = x - 1
ny = y
opposite_direction = Maze._EAST
# Wrap in the horizontal dimension
if nx < 0:
nx += self.w
elif nx >= self.w:
nx -= self.w
# See if this neighboring cell has been visited
if self.is_visited( nx, ny ):
# Neighbor has been visited already
continue
# The neighboring cell has not been visited: remove the wall in
# the current cell leading to the neighbor. And, from the
# neighbor remove its wall leading to the current cell.
self.remove_wall( x, y, directions[i] )
self.remove_wall( nx, ny, opposite_direction )
# Now recur by "moving" to this unvisited neighboring cell
self.handle_cell( depth + 1, nx, ny )
def draw_line(self, x1, y1, x2, y2, thickness):
draw_SVG_path( [ x1, y1, x2, y2 ], self.maze_color,
float( thickness / self.scale ),
'maze' + str( self.segment_id ), self.maze_layer )
self.segment_id += 1
# Draw the horizontal walls of the maze along the row of
# cells at "height" y
def draw_horizontal(self, y, wall, isborder):
# Cater to Python 2.4 and earlier
# dy = 0 if wall == Maze._NORTH else 1
if wall == Maze._NORTH:
dy = 0
else:
dy = 1
thickness = 4 if isborder else 1
tracing = False
for x in range( 0, self.w ):
if self.is_wall( x, y, wall ):
if not tracing:
# Starting a new segment
segment = x
tracing = True
else:
if tracing:
# Reached the end of a segment
self.draw_line( 2 * segment, 2 * (y + dy),
2 * x, 2 * (y + dy), thickness )
tracing = False
if tracing:
# Draw the last wall segment
self.draw_line( 2 * segment, 2 * (y + dy),
2 * self.w, 2 * (y + dy), thickness )
# Draw the vertical walls of the maze along the column of cells at
# horizonal position x
def draw_vertical(self, x, wall, isborder):
# Cater to Python 2.4 and earlier
# dx = 0 if wall == Maze._WEST else 1
if wall == Maze._WEST:
dx = 0
else:
dx = 1
thickness = 4 if isborder else 1
# We alternate the direction in which we draw each vertical wall.
# First, from North to South and then from South to North. This
# reduces pen travel on the Eggbot
if x % 2 == 0: # North-South
y_start, y_finis, dy, offset = 0, self.h, 1, 0
else: # South-North
y_start, y_finis, dy, offset = self.h - 1, -1, -1, 2
tracing = False
for y in range( y_start, y_finis, dy ):
assert 0 <= y and y < self.h, "y (%d) is out of range" % y
if self.is_wall( x, y, wall ):
if not tracing:
# Starting a new segment
segment = y
tracing = True
else:
if tracing:
# Hit the end of a segment
self.draw_line( 2 * ( x + dx ), 2 * segment + offset,
2 * ( x + dx ), 2 * y + offset, thickness )
tracing = False
if tracing:
# complete the last wall segment
self.draw_line( 2 * ( x + dx ), 2 * segment + offset,
2 * ( x + dx ), 2 * y_finis + offset, thickness )
if __name__ == '__main__':
e = Maze()
e.affect()

Wyświetl plik

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<_name>Post process trace bitmap</_name>
<id>command.evilmadscience.eggbot_pptb.eggbot</id>
<dependency type="extension">org.inkscape.output.svg.inkscape</dependency>
<dependency type="executable" location="extensions">eggbot_pptb.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency> <dependency type="executable" location="extensions">simplestyle.py</dependency>
<_param name="Header" type="description" xml:space="preserve">
This extension is intended for use after
running the Inkscape "Trace Bitmap" tool
of the "Path" menu
Running Trace Bitmap:
1. Run the tool with the "Multiple scans"
selection of "Colors" or "Grays"
2. "Stack scans" should not be checked
3. "Remove background" may be checked
Running this extension:
1. Will move each scanned color to a
separate Inkscape layer
2. Can optionally remove the original
bitmap image from the drawing
3. Can optionally turn off the colored
fills within each traced regions
4. Can optionally outline the traced
regions
</_param>
<param name="removeImage" type="boolean" _gui-text="Remove original bitmap image?">true</param>
<param name="fillRegions" type="boolean" _gui-text="Fill each traced region with color?">true</param>
<param name="outlineRegions" type="boolean" _gui-text="Outline each traced region?">true</param>
<effect needs-live-preview="false">
<object-type>all</object-type>
<effects-menu>
<submenu _name="EggBot"/>
</effects-menu>
</effect>
<script>
<command reldir="extensions" interpreter="python">eggbot_pptb.py</command>
</script>
</inkscape-extension>

Wyświetl plik

@ -0,0 +1,110 @@
#!/usr/bin/env python
# Post Process a bitmap image traced with Inkscape's Trace Bitmap tool
# The output of Trace Bitmap is traversed and each <path> is put into
# an Inkscape layer whose name is Eggbot friendly. Owing to how the
# Trace Bitmap tool operates in Inkscape 0.48, all the traced regions
# of a given "scanned" color are put into a single <path>. This makes
# it easy to put all the traced regions of a single color into a single
# layer: just put each <path> into its own layer.
#
# 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
import gettext
import simplestyle
class EggBot_PostProcessTraceBitmap( inkex.Effect ):
def __init__(self):
inkex.Effect.__init__( self )
self.OptionParser.add_option(
"--outlineRegions", action="store", dest="outlineRegions",
type="inkbool", default=True,
help="Outline the regions with a stroked line of the same color as the region itself" )
self.OptionParser.add_option(
"--fillRegions", action="store", dest="fillRegions",
type="inkbool", default=True,
help="Fill regions with color" )
self.OptionParser.add_option(
"--removeImage", action="store", dest="removeImage",
type="inkbool", default=True,
help="Remove the traced bitmap image from the drawing" )
def effect(self):
root = self.document.getroot()
count = 0
for path in self.document.xpath( '//svg:path', namespaces=inkex.NSS ):
# Default settings for now
stroke, fill, color = ( 'none', 'none', 'unknown' )
# Get the paths style attribute
style = simplestyle.parseStyle( path.get( 'style', '' ) )
# Obtain the fill color from the path's style attribute
if 'fill' in style:
color = style['fill']
if self.options.fillRegions:
fill = color
if self.options.outlineRegions:
stroke = color
# Now add or change the fill color in the path's style
style['fill'] = fill
# Add or change the stroke behavior in the path's style
style['stroke'] = stroke
# And change the style attribute for the path
path.set( 'style', simplestyle.formatStyle( style ) )
# Create a group <g> element under the document root
layer = inkex.etree.SubElement( root, inkex.addNS( 'g', 'svg' ) )
# Add Inkscape layer attributes to this new group
count += 1
layer.set( inkex.addNS('groupmode', 'inkscape' ), 'layer' )
layer.set( inkex.addNS( 'label', 'inkscape' ), '%d - %s' % ( count, color ) )
# Now move this path from where it was to being a child
# of this new group/layer we just made
layer.append( path )
# Remove any image
# For color scans, Trace Bitmap seems to put the
# image in the same layer & group as the traced regions.
# BUT, for gray scans, it seems to leave the image by
# itself as a child of the root document
if self.options.removeImage:
for node in self.document.xpath( '//svg:image', namespaces=inkex.NSS ):
parent = node.getparent()
if ( parent.tag == 'svg' ) or \
( parent.tag == inkex.addNS( 'svg', 'svg' ) ):
parent.remove( node )
else:
gparent = parent.getparent()
try:
gparent.remove( parent )
except:
parent.remove( node)
inkex.errormsg( gettext.gettext( 'Finished. Created %d layers' ) % count )
if __name__ == '__main__':
e = EggBot_PostProcessTraceBitmap()
e.affect()