From cdb8fdb1339476e36ad2e294283eec33d13b2d3d Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Fri, 27 Jul 2018 20:26:18 -0400 Subject: add bean stitch option --- lib/elements/stroke.py | 21 ++++++++++++++++----- lib/stitches/running_stitch.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) (limited to 'lib') diff --git a/lib/elements/stroke.py b/lib/elements/stroke.py index e8eb4783..e086ccd9 100644 --- a/lib/elements/stroke.py +++ b/lib/elements/stroke.py @@ -4,7 +4,7 @@ import shapely.geometry from .element import param, EmbroideryElement, Patch from ..i18n import _ from ..utils import cache, Point -from ..stitches import running_stitch +from ..stitches import running_stitch, bean_stitch from ..svg import parse_length_with_units warned_about_legacy_running_stitch = False @@ -27,18 +27,28 @@ class Stroke(EmbroideryElement): return self.get_style("stroke-dasharray") is not None @property - @param('running_stitch_length_mm', _('Running stitch length'), unit='mm', type='float', default=1.5) + @param('running_stitch_length_mm', _('Running stitch length'), unit='mm', type='float', default=1.5, sort_index=3) def running_stitch_length(self): return max(self.get_float_param("running_stitch_length_mm", 1.5), 0.01) @property - @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4) + @param('bean_stitch_repeats', + _('Bean stitch number of repeats'), + tooltip=_('Backtrack each stitch this many times. A value of 1 would triple each stitch (forward, back, forward). A value of 2 would quintuple each stitch, etc. Only applies to running stitch.'), + type='int', + default=0, + sort_index=2) + def bean_stitch_repeats(self): + return self.get_int_param("bean_stitch_repeats", 0) + + @property + @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4, sort_index=3) @cache def zigzag_spacing(self): return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('repeats', _('Repeats'), type='int', default="1") + @param('repeats', _('Repeats'), type='int', default="1", sort_index=1) def repeats(self): return self.get_int_param("repeats", 1) @@ -58,7 +68,7 @@ class Stroke(EmbroideryElement): return shapely.geometry.MultiLineString(line_strings) @property - @param('manual_stitch', _('Manual stitch placement'), tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), type='boolean', default=False) + @param('manual_stitch', _('Manual stitch placement'), tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), type='boolean', default=False, sort_index=0) def manual_stitch_mode(self): return self.get_boolean_param('manual_stitch') @@ -139,6 +149,7 @@ class Stroke(EmbroideryElement): repeated_path.extend(this_path) stitches = running_stitch(repeated_path, stitch_length) + stitches = bean_stitch(stitches, self.bean_stitch_repeats) return Patch(self.color, stitches) diff --git a/lib/stitches/running_stitch.py b/lib/stitches/running_stitch.py index 96075e7a..5f8ed21e 100644 --- a/lib/stitches/running_stitch.py +++ b/lib/stitches/running_stitch.py @@ -1,3 +1,6 @@ +from copy import copy + + """ Utility functions to produce running stitches. """ @@ -64,3 +67,29 @@ def running_stitch(points, stitch_length): output.append(segment_start) return output + + +def bean_stitch(stitches, repeats): + """Generate bean stitch from a set of stitches. + + "Bean" stitch is made by backtracking each stitch to make it heaver. A + simple bean stitch would be two stitches forward, one stitch back, two + stitches forward, etc. This would result in each stitch being tripled. + + We'll say that the above counts as 1 repeat. Backtracking each stitch + repeatedly will result in a heavier bean stitch. There will always be + an odd number of threads piled up for each stitch. + """ + + if len(stitches) < 2: + return stitches + + new_stitches = [stitches[0]] + + for stitch in stitches: + new_stitches.append(stitch) + + for i in xrange(repeats): + new_stitches.extend(copy(new_stitches[-2:])) + + return new_stitches -- cgit v1.2.3 From 0ab7223980d849dd732cb9572644339d5c2a6228 Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Fri, 27 Jul 2018 21:10:02 -0400 Subject: add E stitch for satin columns --- lib/elements/satin_column.py | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/lib/elements/satin_column.py b/lib/elements/satin_column.py index 2ceb38de..78275745 100644 --- a/lib/elements/satin_column.py +++ b/lib/elements/satin_column.py @@ -17,6 +17,12 @@ class SatinColumn(EmbroideryElement): def satin_column(self): return self.get_boolean_param("satin_column") + # I18N: "E" stitch is so named because it looks like the letter E. + @property + @param('e_stitch', _('"E" stitch'), type='boolean', default='false') + def e_stitch(self): + return self.get_boolean_param("e_stitch") + @property def color(self): return self.get_style("stroke") @@ -28,7 +34,7 @@ class SatinColumn(EmbroideryElement): return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('pull_compensation_mm', _('Pull compensation'), unit='mm', type='float') + @param('pull_compensation_mm', _('Pull compensation'), unit='mm', type='float', default=0) def pull_compensation(self): # In satin stitch, the stitches have a tendency to pull together and # narrow the entire column. We can compensate for this by stitching @@ -76,7 +82,7 @@ class SatinColumn(EmbroideryElement): return max(self.get_float_param("zigzag_underlay_spacing_mm", 3), 0.01) @property - @param('zigzag_underlay_inset_mm', _('Inset amount (default: half of contour underlay inset)'), unit='mm', group=_('Zig-zag Underlay'), type='float') + @param('zigzag_underlay_inset_mm', _('Inset amount (default: half of contour underlay inset)'), unit='mm', group=_('Zig-zag Underlay'), type='float', default="") def zigzag_underlay_inset(self): # how far in from the edge of the satin the points in the zigzags # should be @@ -388,6 +394,28 @@ class SatinColumn(EmbroideryElement): return patch + def do_e_stitch(self): + # e stitch: do a pattern that looks like the letter "E". It looks like + # this: + # + # _|_|_|_|_|_|_|_|_|_|_|_| + + # print >> dbg, "satin", self.zigzag_spacing, self.pull_compensation + + patch = Patch(color=self.color) + + sides = self.walk_paths(self.zigzag_spacing, self.pull_compensation) + + # "left" and "right" here are kind of arbitrary designations meaning + # a point from the first and second rail repectively + for left, right in izip(*sides): + patch.add_stitch(left) + patch.add_stitch(right) + patch.add_stitch(left) + + return patch + + def to_patches(self, last_patch): # Stitch a variable-width satin column, zig-zagging between two paths. @@ -411,6 +439,9 @@ class SatinColumn(EmbroideryElement): # zigzags sit on the contour walk underlay like rail ties on rails. patches.append(self.do_zigzag_underlay()) - patches.append(self.do_satin()) + if self.e_stitch: + patches.append(self.do_e_stitch()) + else: + patches.append(self.do_satin()) return patches -- cgit v1.2.3 From f8f108367abf71e2e8a2eb7718a2759568337c53 Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Sat, 28 Jul 2018 20:10:27 -0400 Subject: fix simple satin --- lib/elements/stroke.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/elements/stroke.py b/lib/elements/stroke.py index e086ccd9..bc2ee54c 100644 --- a/lib/elements/stroke.py +++ b/lib/elements/stroke.py @@ -149,7 +149,6 @@ class Stroke(EmbroideryElement): repeated_path.extend(this_path) stitches = running_stitch(repeated_path, stitch_length) - stitches = bean_stitch(stitches, self.bean_stitch_repeats) return Patch(self.color, stitches) @@ -163,6 +162,10 @@ class Stroke(EmbroideryElement): patch = Patch(color=self.color, stitches=path, stitch_as_is=True) elif self.is_running_stitch(): patch = self.running_stitch(path, self.running_stitch_length) + + if self.bean_stitch_repeats > 0: + patch.stitches = bean_stitch(patch.stitches, self.bean_stitch_repeats) + else: patch = self.simple_satin(path, self.zigzag_spacing, self.stroke_width) -- cgit v1.2.3 From 8d41d0f9af0e5390dacdfa2a18e213955aef8ddf Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Mon, 30 Jul 2018 14:57:54 -0400 Subject: convert to satin extension --- lib/extensions/__init__.py | 1 + lib/extensions/commands.py | 21 +------ lib/extensions/convert_to_satin.py | 119 +++++++++++++++++++++++++++++++++++++ lib/svg/__init__.py | 2 +- lib/svg/path.py | 17 ++++++ 5 files changed, 141 insertions(+), 19 deletions(-) create mode 100644 lib/extensions/convert_to_satin.py (limited to 'lib') diff --git a/lib/extensions/__init__.py b/lib/extensions/__init__.py index 8b243176..30a08c9f 100644 --- a/lib/extensions/__init__.py +++ b/lib/extensions/__init__.py @@ -8,3 +8,4 @@ from output import Output from zip import Zip from flip import Flip from commands import Commands +from convert_to_satin import ConvertToSatin diff --git a/lib/extensions/commands.py b/lib/extensions/commands.py index 2f3006ff..353c9874 100644 --- a/lib/extensions/commands.py +++ b/lib/extensions/commands.py @@ -12,7 +12,7 @@ from ..i18n import _ from ..elements import SatinColumn from ..utils import get_bundled_dir, cache from ..svg.tags import SVG_DEFS_TAG, SVG_GROUP_TAG, SVG_USE_TAG, SVG_PATH_TAG, INKSCAPE_GROUPMODE, XLINK_HREF, CONNECTION_START, CONNECTION_END, CONNECTOR_TYPE -from ..svg import get_node_transform +from ..svg import get_correction_transform class Commands(InkstitchExtension): @@ -48,21 +48,6 @@ class Commands(InkstitchExtension): if self.defs.find(path) is None: self.defs.append(deepcopy(self.symbol_defs.find(path))) - def get_correction_transform(self, node): - # if we want to place our new nodes in the same group as this node, - # then we'll need to factor in the effects of any transforms set on - # the parents of this node. - - # we can ignore the transform on the node itself since it won't apply - # to the objects we add - transform = get_node_transform(node.getparent()) - - # now invert it, so that we can position our objects in absolute - # coordinates - transform = simpletransform.invertTransform(transform) - - return simpletransform.formatTransform(transform) - def add_connector(self, symbol, element): # I'd like it if I could position the connector endpoint nicely but inkscape just # moves it to the element's center immediately after the extension runs. @@ -74,7 +59,7 @@ class Commands(InkstitchExtension): "id": self.uniqueId("connector"), "d": "M %s,%s %s,%s" % (start_pos[0], start_pos[1], end_pos.x, end_pos.y), "style": "stroke:#000000;stroke-width:1px;stroke-opacity:0.5;fill:none;", - "transform": self.get_correction_transform(symbol), + "transform": get_correction_transform(symbol), CONNECTION_START: "#%s" % symbol.get('id'), CONNECTION_END: "#%s" % element.node.get('id'), CONNECTOR_TYPE: "polyline", @@ -126,7 +111,7 @@ class Commands(InkstitchExtension): "width": "100%", "x": str(pos.x), "y": str(pos.y), - "transform": self.get_correction_transform(element.node) + "transform": get_correction_transform(element.node) } ) diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py new file mode 100644 index 00000000..715853c4 --- /dev/null +++ b/lib/extensions/convert_to_satin.py @@ -0,0 +1,119 @@ +import inkex +from shapely import geometry as shgeo +from itertools import chain + +from .base import InkstitchExtension +from ..svg.tags import SVG_PATH_TAG +from ..svg import get_correction_transform, PIXELS_PER_MM +from ..elements import Stroke +from ..utils import Point + + +class ConvertToSatin(InkstitchExtension): + """Convert a line to a satin column of the same width.""" + + def effect(self): + if not self.get_elements(): + return + + if not self.selected: + inkex.errormsg(_("Please select at least one line to convert to a satin column.")) + return + + if not all(isinstance(item, Stroke) for item in self.elements): + # L10N: Convert To Satin extension, user selected one or more objects that were not lines. + inkex.errormsg(_("Only simple lines may be converted to satin columns.")) + return + + for element in self.elements: + parent = element.node.getparent() + index = parent.index(element.node) + correction_transform = get_correction_transform(element.node) + + for path in element.paths: + try: + rails, rungs = self.path_to_satin(path, element.stroke_width) + except ValueError: + inkex.errormsg(_("Cannot convert %s to a satin column because it intersects itself. Try breaking it up into multiple paths.") % element.node.get('id')) + + parent.insert(index, self.satin_to_svg_node(rails, rungs, correction_transform)) + + parent.remove(element.node) + + def path_to_satin(self, path, stroke_width): + path = shgeo.LineString(path) + + left_rail = path.parallel_offset(stroke_width / 2.0, 'left') + right_rail = path.parallel_offset(stroke_width / 2.0, 'right') + + if not isinstance(left_rail, shgeo.LineString) or \ + not isinstance(right_rail, shgeo.LineString): + # If the parallel offsets come out as anything but a LineString, that means the + # path intersects itself, when taking its stroke width into consideration. See + # the last example for parallel_offset() in the Shapely documentation: + # https://shapely.readthedocs.io/en/latest/manual.html#object.parallel_offset + raise ValueError() + + # for whatever reason, shapely returns a right-side offset's coordinates in reverse + left_rail = list(left_rail.coords) + right_rail = list(reversed(right_rail.coords)) + + rungs = self.generate_rungs(path, stroke_width) + + return (left_rail, right_rail), rungs + + def generate_rungs(self, path, stroke_width): + rungs = [] + + # approximately 1cm between rungs, and we don't want them at the very start or end + num_rungs = int(path.length / PIXELS_PER_MM / 10) - 1 + + if num_rungs < 1 or num_rungs == 2: + # avoid 2 rungs because it can be ambiguous (which are the rails and which are the + # rungs?) + num_rungs += 1 + + distance_between_rungs = path.length / (num_rungs + 1) + + for i in xrange(num_rungs): + rung_center = path.interpolate((i + 1) * distance_between_rungs) + rung_center = Point(rung_center.x, rung_center.y) + + # TODO: use bezierslopeatt or whatever + # we need to calculate the normal at this point so grab another point just a little + # further down the path, effectively grabbing a small segment of the path + segment_end = path.interpolate((i + 1) * distance_between_rungs + 0.1) + segment_end = Point(segment_end.x, segment_end.y) + + tangent = segment_end - rung_center + normal = tangent.unit().rotate_left() + offset = normal * stroke_width * 0.75 + + rung_start = rung_center + offset + rung_end = rung_center - offset + + rungs.append((rung_start.as_tuple(), rung_end.as_tuple())) + + return rungs + import sys + print >> sys.stderr, rails, rungs + + + + def satin_to_svg_node(self, rails, rungs, correction_transform): + d = "" + for path in chain(rails, rungs): + d += "M" + for x, y in path: + d += "%s,%s " % (x, y) + d += " " + + return inkex.etree.Element(SVG_PATH_TAG, + { + "id": self.uniqueId("path"), + "style": "stroke:#000000;stroke-width:1px;fill:none", + "transform": correction_transform, + "d": d, + "embroider_satin_column": "true", + } + ) diff --git a/lib/svg/__init__.py b/lib/svg/__init__.py index 8e846555..429e6b5e 100644 --- a/lib/svg/__init__.py +++ b/lib/svg/__init__.py @@ -1,3 +1,3 @@ from .svg import color_block_to_point_lists, render_stitch_plan from .units import * -from .path import apply_transforms, get_node_transform +from .path import apply_transforms, get_node_transform, get_correction_transform diff --git a/lib/svg/path.py b/lib/svg/path.py index 2d9c0ff3..00e2c269 100644 --- a/lib/svg/path.py +++ b/lib/svg/path.py @@ -23,3 +23,20 @@ def get_node_transform(node): transform = simpletransform.composeTransform(viewbox_transform, transform) return transform + +def get_correction_transform(node): + """Get a transform to apply to new siblings of this SVG node""" + + # if we want to place our new nodes in the same group/layer as this node, + # then we'll need to factor in the effects of any transforms set on + # the parents of this node. + + # we can ignore the transform on the node itself since it won't apply + # to the objects we add + transform = get_node_transform(node.getparent()) + + # now invert it, so that we can position our objects in absolute + # coordinates + transform = simpletransform.invertTransform(transform) + + return simpletransform.formatTransform(transform) -- cgit v1.2.3 From 5f14617a029060416fcaea8247c29aa326f4b77f Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Mon, 30 Jul 2018 16:03:27 -0400 Subject: choose better rung positions --- lib/extensions/convert_to_satin.py | 79 +++++++++++++++++++++++++++----------- lib/svg/path.py | 6 ++- 2 files changed, 61 insertions(+), 24 deletions(-) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index 715853c4..8af45b3b 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -1,6 +1,10 @@ import inkex from shapely import geometry as shgeo from itertools import chain +import numpy +from numpy import diff, sign, setdiff1d +from scipy.signal import argrelmin +import math from .base import InkstitchExtension from ..svg.tags import SVG_PATH_TAG @@ -62,42 +66,73 @@ class ConvertToSatin(InkstitchExtension): return (left_rail, right_rail), rungs - def generate_rungs(self, path, stroke_width): - rungs = [] + def get_scores(self, path): + scores = numpy.zeros(101, numpy.int32) + path_length = path.length + + prev_point = None + prev_direction = None + length_so_far = 0 + for point in path.coords: + point = Point(*point) + + if prev_point is None: + prev_point = point + continue + + direction = (point - prev_point).unit() + + if prev_direction is not None: + cos_angle_between = prev_direction * direction + angle = abs(math.degrees(math.acos(cos_angle_between))) + + scores[int(round(length_so_far / path_length * 100.0))] += angle ** 2 - # approximately 1cm between rungs, and we don't want them at the very start or end - num_rungs = int(path.length / PIXELS_PER_MM / 10) - 1 + length_so_far += (point - prev_point).length() + prev_direction = direction + prev_point = point - if num_rungs < 1 or num_rungs == 2: - # avoid 2 rungs because it can be ambiguous (which are the rails and which are the - # rungs?) - num_rungs += 1 + return scores - distance_between_rungs = path.length / (num_rungs + 1) + def local_minima(self, array): + # from: https://stackoverflow.com/a/9667121/4249120 + # finds spots where the curvature (second derivative) is > 0 + return (diff(sign(diff(array))) > 0).nonzero()[0] + 1 - for i in xrange(num_rungs): - rung_center = path.interpolate((i + 1) * distance_between_rungs) + def generate_rungs(self, path, stroke_width): + scores = self.get_scores(path) + scores = numpy.convolve(scores, [1, 2, 4, 8, 16, 8, 4, 2, 1], mode='same') + rung_locations = self.local_minima(scores) + rung_locations = setdiff1d(rung_locations, [0, 100]) + + if len(rung_locations) == 0: + rung_locations = [50] + + rungs = [] + last_rung_center = None + + for location in rung_locations: + location = location / 100.0 + rung_center = path.interpolate(location, normalized=True) rung_center = Point(rung_center.x, rung_center.y) - # TODO: use bezierslopeatt or whatever - # we need to calculate the normal at this point so grab another point just a little - # further down the path, effectively grabbing a small segment of the path - segment_end = path.interpolate((i + 1) * distance_between_rungs + 0.1) - segment_end = Point(segment_end.x, segment_end.y) + if last_rung_center is not None and \ + (rung_center - last_rung_center).length() < 2 * PIXELS_PER_MM: + continue + else: + last_rung_center = rung_center - tangent = segment_end - rung_center - normal = tangent.unit().rotate_left() + tangent_end = path.interpolate(location + 0.001, normalized=True) + tangent_end = Point(tangent_end.x, tangent_end.y) + tangent = (tangent_end - rung_center).unit() + normal = tangent.rotate_left() offset = normal * stroke_width * 0.75 rung_start = rung_center + offset rung_end = rung_center - offset - rungs.append((rung_start.as_tuple(), rung_end.as_tuple())) return rungs - import sys - print >> sys.stderr, rails, rungs - def satin_to_svg_node(self, rails, rungs, correction_transform): diff --git a/lib/svg/path.py b/lib/svg/path.py index 00e2c269..52144332 100644 --- a/lib/svg/path.py +++ b/lib/svg/path.py @@ -15,8 +15,10 @@ def get_node_transform(node): # start with the identity transform transform = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] - # combine this node's transform with all parent groups' transforms - transform = simpletransform.composeParents(node, transform) + # this if is because sometimes inkscape likes to create paths outside of a layer?! + if node.getparent() is not None: + # combine this node's transform with all parent groups' transforms + transform = simpletransform.composeParents(node, transform) # add in the transform implied by the viewBox viewbox_transform = get_viewbox_transform(node.getroottree().getroot()) -- cgit v1.2.3 From 8bf478a71a49b93269da438cf1fcdb6d2e0e0942 Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Mon, 30 Jul 2018 16:29:36 -0400 Subject: add documentation --- lib/extensions/convert_to_satin.py | 82 +++++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index 8af45b3b..53930935 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -67,6 +67,17 @@ class ConvertToSatin(InkstitchExtension): return (left_rail, right_rail), rungs def get_scores(self, path): + """Generate an array of "scores" of the sharpness of corners in a path + + A higher score means that there are sharper corners in that section of + the path. We'll divide the path into boxes, with the score in each + box indicating the sharpness of corners at around that percentage of + the way through the path. For example, if scores[40] is 100 and + scores[45] is 200, then the path has sharper corners at a spot 45% + along its length than at a spot 40% along its length. + """ + + # need 101 boxes in order to encompass percentages from 0% to 100% scores = numpy.zeros(101, numpy.int32) path_length = path.length @@ -83,9 +94,19 @@ class ConvertToSatin(InkstitchExtension): direction = (point - prev_point).unit() if prev_direction is not None: + # The dot product of two vectors is |v1| * |v2| * cos(angle). + # These are unit vectors, so their magnitudes are 1. cos_angle_between = prev_direction * direction angle = abs(math.degrees(math.acos(cos_angle_between))) + # Use the square of the angle, measured in degrees. + # + # Why the square? This penalizes bigger angles more than + # smaller ones. + # + # Why degrees? This is kind of arbitrary but allows us to + # use integer math effectively and avoid taking the square + # of a fraction between 0 and 1. scores[int(round(length_so_far / path_length * 100.0))] += angle ** 2 length_so_far += (point - prev_point).length() @@ -96,40 +117,97 @@ class ConvertToSatin(InkstitchExtension): def local_minima(self, array): # from: https://stackoverflow.com/a/9667121/4249120 - # finds spots where the curvature (second derivative) is > 0 + # This finds spots where the curvature (second derivative) is > 0. + # + # This method has the convenient benefit of choosing points around + # 5% before and after a sharp corner such as in a square. return (diff(sign(diff(array))) > 0).nonzero()[0] + 1 def generate_rungs(self, path, stroke_width): + """Create rungs for a satin column. + + Where should we put the rungs along a path? We want to ensure that the + resulting satin matches the original path as closely as possible. We + want to avoid having a ton of rungs that will annoy the user. We want + to ensure that the rungs we choose actually intersect both rails. + + We'll place a few rungs perpendicular to the tangent of the path. + Things get pretty tricky at sharp corners. If we naively place a rung + perpendicular to the path just on either side of a sharp corner, the + rung may not intersect both paths: + | | + _______________| | + ______|_ + ____________________| + + It'd be best to place rungs in the straight sections before and after + the sharp corner and allow the satin column to bend the stitches around + the corner automatically. + + How can we find those spots? + + The general algorithm below is: + + * assign a "score" to each section of the path based on how sharp its + corners are (higher means a sharper corner) + * pick spots with lower scores + """ + scores = self.get_scores(path) + + # This is kind of like a 1-dimensional gaussian blur filter. We want to + # avoid the area near a sharp corner, so we spread out its effect for + # 5 buckets in either direction. scores = numpy.convolve(scores, [1, 2, 4, 8, 16, 8, 4, 2, 1], mode='same') + + # Now we'll find the spots that aren't near corners, whose scores are + # low -- the local minima. rung_locations = self.local_minima(scores) + + # Remove the start and end, because we can't stick a rung there. rung_locations = setdiff1d(rung_locations, [0, 100]) if len(rung_locations) == 0: + # Straight lines won't have local minima, so add a rung in the center. rung_locations = [50] rungs = [] last_rung_center = None for location in rung_locations: + # Convert percentage to a fraction so that we can use interpolate's + # normalized parameter. location = location / 100.0 + rung_center = path.interpolate(location, normalized=True) rung_center = Point(rung_center.x, rung_center.y) + # Avoid placing rungs too close together. This somewhat + # arbitrarily rejects the rung if there was one less than 2 + # millimeters before this one. if last_rung_center is not None and \ (rung_center - last_rung_center).length() < 2 * PIXELS_PER_MM: continue else: last_rung_center = rung_center + # We need to know the tangent of the path's curve at this point. + # Pick another point just after this one and subtract them to + # approximate a tangent vector. tangent_end = path.interpolate(location + 0.001, normalized=True) tangent_end = Point(tangent_end.x, tangent_end.y) tangent = (tangent_end - rung_center).unit() + + # Rotate 90 degrees left to make a normal vector. normal = tangent.rotate_left() - offset = normal * stroke_width * 0.75 + # Travel 75% of the stroke width left and right to make the rung's + # endpoints. This means the rung's length is 150% of the stroke + # width. + offset = normal * stroke_width * 0.75 rung_start = rung_center + offset rung_end = rung_center - offset + rungs.append((rung_start.as_tuple(), rung_end.as_tuple())) return rungs -- cgit v1.2.3 From d224b2655eb5287c132bd4b3e4bf7129b17f597f Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Mon, 30 Jul 2018 16:40:26 -0400 Subject: fix handling of self-intersection --- lib/extensions/convert_to_satin.py | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index 53930935..8ec6ab2e 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -5,6 +5,7 @@ import numpy from numpy import diff, sign, setdiff1d from scipy.signal import argrelmin import math +from copy import deepcopy from .base import InkstitchExtension from ..svg.tags import SVG_PATH_TAG @@ -40,6 +41,11 @@ class ConvertToSatin(InkstitchExtension): except ValueError: inkex.errormsg(_("Cannot convert %s to a satin column because it intersects itself. Try breaking it up into multiple paths.") % element.node.get('id')) + # revert any changes we've made + self.document = deepcopy(self.original_document) + + return + parent.insert(index, self.satin_to_svg_node(rails, rungs, correction_transform)) parent.remove(element.node) -- cgit v1.2.3 From 1480bf73dc4da9978b0092fcf7c9fed5b97d38f5 Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Tue, 31 Jul 2018 08:40:44 -0400 Subject: use line join style defined in SVG --- lib/extensions/convert_to_satin.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index 8ec6ab2e..b029b736 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -34,10 +34,11 @@ class ConvertToSatin(InkstitchExtension): parent = element.node.getparent() index = parent.index(element.node) correction_transform = get_correction_transform(element.node) + style_args = self.join_style_args(element) for path in element.paths: try: - rails, rungs = self.path_to_satin(path, element.stroke_width) + rails, rungs = self.path_to_satin(path, element.stroke_width, style_args) except ValueError: inkex.errormsg(_("Cannot convert %s to a satin column because it intersects itself. Try breaking it up into multiple paths.") % element.node.get('id')) @@ -50,11 +51,32 @@ class ConvertToSatin(InkstitchExtension): parent.remove(element.node) - def path_to_satin(self, path, stroke_width): + def join_style_args(self, element): + """Convert svg line join style to shapely parallel offset arguments.""" + + args = { + 'join_style': shgeo.JOIN_STYLE.round + } + + element_join_style = element.get_style('stroke-linejoin') + + if element_join_style is not None: + if element_join_style == "miter": + args['join_style'] = shgeo.JOIN_STYLE.mitre + + # 4 is the default per SVG spec + miter_limit = float(element.get_style('stroke-miterlimit', 4)) + args['mitre_limit'] = miter_limit + elif element_join_style == "bevel": + args['join_style'] = shgeo.JOIN_STYLE.bevel + + return args + + def path_to_satin(self, path, stroke_width, style_args): path = shgeo.LineString(path) - left_rail = path.parallel_offset(stroke_width / 2.0, 'left') - right_rail = path.parallel_offset(stroke_width / 2.0, 'right') + left_rail = path.parallel_offset(stroke_width / 2.0, 'left', **style_args) + right_rail = path.parallel_offset(stroke_width / 2.0, 'right', **style_args) if not isinstance(left_rail, shgeo.LineString) or \ not isinstance(right_rail, shgeo.LineString): -- cgit v1.2.3 From 0c74bcb81664134fd316455aa0886662c9b1f897 Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Tue, 31 Jul 2018 08:55:36 -0400 Subject: work around shapely weirdness for closed paths --- lib/extensions/convert_to_satin.py | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index b029b736..1eae69b1 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -1,6 +1,6 @@ import inkex from shapely import geometry as shgeo -from itertools import chain +from itertools import chain, groupby import numpy from numpy import diff, sign, setdiff1d from scipy.signal import argrelmin @@ -14,6 +14,10 @@ from ..elements import Stroke from ..utils import Point +class SelfIntersectionError(Exception): + pass + + class ConvertToSatin(InkstitchExtension): """Convert a line to a satin column of the same width.""" @@ -37,9 +41,17 @@ class ConvertToSatin(InkstitchExtension): style_args = self.join_style_args(element) for path in element.paths: + path = self.remove_duplicate_points(path) + + if len(path) < 2: + # ignore paths with just one point -- they're not visible to the user anyway + continue + + self.fix_loop(path) + try: rails, rungs = self.path_to_satin(path, element.stroke_width, style_args) - except ValueError: + except SelfIntersectionError: inkex.errormsg(_("Cannot convert %s to a satin column because it intersects itself. Try breaking it up into multiple paths.") % element.node.get('id')) # revert any changes we've made @@ -51,6 +63,24 @@ class ConvertToSatin(InkstitchExtension): parent.remove(element.node) + def fix_loop(self, path): + if path[0] == path[-1]: + # Looping paths seem to confuse shapely's parallel_offset(). It loses track + # of where the start and endpoint is, even if the user explicitly breaks the + # path. I suspect this is because parallel_offset() uses buffer() under the + # hood. + # + # To work around this we'll introduce a tiny gap by nudging the starting point + # toward the next point slightly. + start = Point(*path[0]) + next = Point(*path[1]) + direction = (next - start).unit() + start += 0.01 * direction + path[0] = start.as_tuple() + + def remove_duplicate_points(self, path): + return [point for point, repeats in groupby(path)] + def join_style_args(self, element): """Convert svg line join style to shapely parallel offset arguments.""" @@ -84,7 +114,7 @@ class ConvertToSatin(InkstitchExtension): # path intersects itself, when taking its stroke width into consideration. See # the last example for parallel_offset() in the Shapely documentation: # https://shapely.readthedocs.io/en/latest/manual.html#object.parallel_offset - raise ValueError() + raise SelfIntersectionError() # for whatever reason, shapely returns a right-side offset's coordinates in reverse left_rail = list(left_rail.coords) -- cgit v1.2.3 From 40cb74109222faba4eeb6cbfba2e906ddf9cdbf5 Mon Sep 17 00:00:00 2001 From: Kaalleen <36401965+kaalleen@users.noreply.github.com> Date: Thu, 9 Aug 2018 20:32:41 +0200 Subject: add tooltips to params (#262) * add tooltips to params Closes #34 --- lib/elements/auto_fill.py | 49 ++++++++++++++++++++++++++++++-------------- lib/elements/fill.py | 40 ++++++++++++++++++++++++++++++------ lib/elements/satin_column.py | 38 +++++++++++++++++++++++++++++----- lib/elements/stroke.py | 30 +++++++++++++++++++++++---- 4 files changed, 127 insertions(+), 30 deletions(-) (limited to 'lib') diff --git a/lib/elements/auto_fill.py b/lib/elements/auto_fill.py index 59816878..79220a86 100644 --- a/lib/elements/auto_fill.py +++ b/lib/elements/auto_fill.py @@ -30,7 +30,12 @@ class AutoFill(Fill): return False @property - @param('running_stitch_length_mm', _('Running stitch length (traversal between sections)'), unit='mm', type='float', default=1.5) + @param('running_stitch_length_mm', + _('Running stitch length (traversal between sections)'), + tooltip=_('Length of stitches around the outline of the fill region used when moving from section to section.'), + unit='mm', + type='float', + default=1.5) def running_stitch_length(self): return max(self.get_float_param("running_stitch_length_mm", 1.5), 0.01) @@ -40,7 +45,12 @@ class AutoFill(Fill): return self.get_boolean_param("fill_underlay", default=False) @property - @param('fill_underlay_angle', _('Fill angle (default: fill angle + 90 deg)'), unit='deg', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_angle', + _('Fill angle'), + tooltip=_('default: fill angle + 90 deg'), + unit='deg', + group=_('AutoFill Underlay'), + type='float') @cache def fill_underlay_angle(self): underlay_angle = self.get_float_param("fill_underlay_angle") @@ -51,35 +61,44 @@ class AutoFill(Fill): return self.angle + math.pi / 2.0 @property - @param('fill_underlay_row_spacing_mm', _('Row spacing (default: 3x fill row spacing)'), unit='mm', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_row_spacing_mm', + _('Row spacing'), + tooltip=_('default: 3x fill row spacing'), + unit='mm', + group=_('AutoFill Underlay'), + type='float') @cache def fill_underlay_row_spacing(self): return self.get_float_param("fill_underlay_row_spacing_mm") or self.row_spacing * 3 @property - @param('fill_underlay_max_stitch_length_mm', _('Max stitch length'), unit='mm', group=_('AutoFill Underlay'), type='float') + @param('fill_underlay_max_stitch_length_mm', + _('Max stitch length'), + tooltip=_('default: equal to fill max stitch length'), + unit='mm', + group=_('AutoFill Underlay'), type='float') @cache def fill_underlay_max_stitch_length(self): return self.get_float_param("fill_underlay_max_stitch_length_mm") or self.max_stitch_length @property @param('fill_underlay_inset_mm', - _('Inset'), - tooltip='Shrink the shape before doing underlay, to prevent underlay from showing around the outside of the fill.', - unit='mm', - group=_('AutoFill Underlay'), - type='float', - default=0) + _('Inset'), + tooltip=_('Shrink the shape before doing underlay, to prevent underlay from showing around the outside of the fill.'), + unit='mm', + group=_('AutoFill Underlay'), + type='float', + default=0) def fill_underlay_inset(self): return self.get_float_param('fill_underlay_inset_mm', 0) @property @param('expand_mm', - _('Expand'), - tooltip='Expand the shape before fill stitching, to compensate for gaps between shapes.', - unit='mm', - type='float', - default=0) + _('Expand'), + tooltip=_('Expand the shape before fill stitching, to compensate for gaps between shapes.'), + unit='mm', + type='float', + default=0) def expand(self): return self.get_float_param('expand_mm', 0) diff --git a/lib/elements/fill.py b/lib/elements/fill.py index 8d1d35f2..8018b2b4 100644 --- a/lib/elements/fill.py +++ b/lib/elements/fill.py @@ -15,12 +15,22 @@ class Fill(EmbroideryElement): super(Fill, self).__init__(*args, **kwargs) @property - @param('auto_fill', _('Manually routed fill stitching'), type='toggle', inverse=True, default=True) + @param('auto_fill', + _('Manually routed fill stitching'), + tooltip=_('AutoFill is the default method for generating fill stitching.'), + type='toggle', + inverse=True, + default=True) def auto_fill(self): return self.get_boolean_param('auto_fill', True) @property - @param('angle', _('Angle of lines of stitches'), unit='deg', type='float', default=0) + @param('angle', + _('Angle of lines of stitches'), + tooltip=_('The angle increases in a counter-clockwise direction. 0 is horizontal. Negative angles are allowed.'), + unit='deg', + type='float', + default=0) @cache def angle(self): return math.radians(self.get_float_param('angle', 0)) @@ -31,12 +41,21 @@ class Fill(EmbroideryElement): return self.get_style("fill", "#000000") @property - @param('flip', _('Flip fill (start right-to-left)'), type='boolean', default=False) + @param('flip', + _('Flip fill (start right-to-left)'), + tooltip=_('The flip option can help you with routing your stitch path. When you enable flip, stitching goes from right-to-left instead of left-to-right.'), + type='boolean', + default=False) def flip(self): return self.get_boolean_param("flip", False) @property - @param('row_spacing_mm', _('Spacing between rows'), unit='mm', type='float', default=0.25) + @param('row_spacing_mm', + _('Spacing between rows'), + tooltip=_('Distance between rows of stitches.'), + unit='mm', + type='float', + default=0.25) def row_spacing(self): return max(self.get_float_param("row_spacing_mm", 0.25), 0.1 * PIXELS_PER_MM) @@ -45,12 +64,21 @@ class Fill(EmbroideryElement): return self.get_float_param("end_row_spacing_mm") @property - @param('max_stitch_length_mm', _('Maximum fill stitch length'), unit='mm', type='float', default=3.0) + @param('max_stitch_length_mm', + _('Maximum fill stitch length'), + tooltip=_('The length of each stitch in a row. Shorter stitch may be used at the start or end of a row.'), + unit='mm', + type='float', + default=3.0) def max_stitch_length(self): return max(self.get_float_param("max_stitch_length_mm", 3.0), 0.1 * PIXELS_PER_MM) @property - @param('staggers', _('Stagger rows this many times before repeating'), type='int', default=4) + @param('staggers', + _('Stagger rows this many times before repeating'), + tooltip=_('Setting this dictates how many rows apart the stitches will be before they fall in the same column position.'), + type='int', + default=4) def staggers(self): return self.get_int_param("staggers", 4) diff --git a/lib/elements/satin_column.py b/lib/elements/satin_column.py index 78275745..834509fd 100644 --- a/lib/elements/satin_column.py +++ b/lib/elements/satin_column.py @@ -28,13 +28,23 @@ class SatinColumn(EmbroideryElement): return self.get_style("stroke") @property - @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4) + @param('zigzag_spacing_mm', + _('Zig-zag spacing (peak-to-peak)'), + tooltip=_('Peak-to-peak distance between zig-zags.'), + unit='mm', + type='float', + default=0.4) def zigzag_spacing(self): # peak-to-peak distance between zigzags return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('pull_compensation_mm', _('Pull compensation'), unit='mm', type='float', default=0) + @param('pull_compensation_mm', + _('Pull compensation'), + tooltip=_('Satin stitches pull the fabric together, resulting in a column narrower than you draw in Inkscape. This setting expands each pair of needle penetrations outward from the center of the satin column.'), + unit='mm', + type='float', + default=0) def pull_compensation(self): # In satin stitch, the stitches have a tendency to pull together and # narrow the entire column. We can compensate for this by stitching @@ -54,7 +64,13 @@ class SatinColumn(EmbroideryElement): return max(self.get_float_param("contour_underlay_stitch_length_mm", 1.5), 0.01) @property - @param('contour_underlay_inset_mm', _('Contour underlay inset amount'), unit='mm', group=_('Contour Underlay'), type='float', default=0.4) + @param('contour_underlay_inset_mm', + _('Contour underlay inset amount'), + tooltip=_('Shrink the outline, to prevent the underlay from showing around the outside of the satin column.'), + unit='mm', + group=_('Contour Underlay'), + type='float', + default=0.4) def contour_underlay_inset(self): # how far inside the edge of the column to stitch the underlay return self.get_float_param("contour_underlay_inset_mm", 0.4) @@ -77,12 +93,24 @@ class SatinColumn(EmbroideryElement): return self.get_boolean_param("zigzag_underlay") @property - @param('zigzag_underlay_spacing_mm', _('Zig-Zag spacing (peak-to-peak)'), unit='mm', group=_('Zig-zag Underlay'), type='float', default=3) + @param('zigzag_underlay_spacing_mm', + _('Zig-Zag spacing (peak-to-peak)'), + tooltip=_('Distance between peaks of the zig-zags.'), + unit='mm', + group=_('Zig-zag Underlay'), + type='float', + default=3) def zigzag_underlay_spacing(self): return max(self.get_float_param("zigzag_underlay_spacing_mm", 3), 0.01) @property - @param('zigzag_underlay_inset_mm', _('Inset amount (default: half of contour underlay inset)'), unit='mm', group=_('Zig-zag Underlay'), type='float', default="") + @param('zigzag_underlay_inset_mm', + _('Inset amount'), + tooltip=_('default: half of contour underlay inset'), + unit='mm', + group=_('Zig-zag Underlay'), + type='float', + default="") def zigzag_underlay_inset(self): # how far in from the edge of the satin the points in the zigzags # should be diff --git a/lib/elements/stroke.py b/lib/elements/stroke.py index bc2ee54c..e84d5e79 100644 --- a/lib/elements/stroke.py +++ b/lib/elements/stroke.py @@ -27,7 +27,13 @@ class Stroke(EmbroideryElement): return self.get_style("stroke-dasharray") is not None @property - @param('running_stitch_length_mm', _('Running stitch length'), unit='mm', type='float', default=1.5, sort_index=3) + @param('running_stitch_length_mm', + _('Running stitch length'), + tooltip=_('Length of stitches in running stitch mode.'), + unit='mm', + type='float', + default=1.5, + sort_index=3) def running_stitch_length(self): return max(self.get_float_param("running_stitch_length_mm", 1.5), 0.01) @@ -42,13 +48,24 @@ class Stroke(EmbroideryElement): return self.get_int_param("bean_stitch_repeats", 0) @property - @param('zigzag_spacing_mm', _('Zig-zag spacing (peak-to-peak)'), unit='mm', type='float', default=0.4, sort_index=3) + @param('zigzag_spacing_mm', + _('Zig-zag spacing (peak-to-peak)'), + tooltip=_('Length of stitches in zig-zag mode.'), + unit='mm', + type='float', + default=0.4, + sort_index=3) @cache def zigzag_spacing(self): return max(self.get_float_param("zigzag_spacing_mm", 0.4), 0.01) @property - @param('repeats', _('Repeats'), type='int', default="1", sort_index=1) + @param('repeats', + _('Repeats'), + tooltip=_('Defines how many times to run down and back along the path.'), + type='int', + default="1", + sort_index=1) def repeats(self): return self.get_int_param("repeats", 1) @@ -68,7 +85,12 @@ class Stroke(EmbroideryElement): return shapely.geometry.MultiLineString(line_strings) @property - @param('manual_stitch', _('Manual stitch placement'), tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), type='boolean', default=False, sort_index=0) + @param('manual_stitch', + _('Manual stitch placement'), + tooltip=_("Stitch every node in the path. Stitch length and zig-zag spacing are ignored."), + type='boolean', + default=False, + sort_index=0) def manual_stitch_mode(self): return self.get_boolean_param('manual_stitch') -- cgit v1.2.3 From d5e7c5e8e6ad652792fac742826b38464c97673a Mon Sep 17 00:00:00 2001 From: Lex Neva Date: Sat, 11 Aug 2018 22:57:18 -0400 Subject: get rid of superfluous scipy reference --- lib/extensions/convert_to_satin.py | 1 - 1 file changed, 1 deletion(-) (limited to 'lib') diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py index 1eae69b1..dd5a9bc2 100644 --- a/lib/extensions/convert_to_satin.py +++ b/lib/extensions/convert_to_satin.py @@ -3,7 +3,6 @@ from shapely import geometry as shgeo from itertools import chain, groupby import numpy from numpy import diff, sign, setdiff1d -from scipy.signal import argrelmin import math from copy import deepcopy -- cgit v1.2.3