diff options
Diffstat (limited to 'lib')
30 files changed, 801 insertions, 290 deletions
diff --git a/lib/commands.py b/lib/commands.py index ec62d716..02c13b25 100644 --- a/lib/commands.py +++ b/lib/commands.py @@ -77,9 +77,6 @@ def find_commands(node): try: commands.append(Command(connector)) except ValueError: - import sys - import traceback - print >> sys.stderr, "not a Command:", connector.get('id'), traceback.format_exc() # Parsing the connector failed, meaning it's not actually an Ink/Stitch command. pass diff --git a/lib/elements/element.py b/lib/elements/element.py index 3c31f1b0..ebca90a4 100644 --- a/lib/elements/element.py +++ b/lib/elements/element.py @@ -206,6 +206,10 @@ class EmbroideryElement(object): return apply_transforms(self.path, self.node) @property + def shape(self): + raise NotImplementedError("INTERNAL ERROR: %s must implement shape()", self.__class__) + + @property @cache def commands(self): return find_commands(self.node) @@ -215,6 +219,10 @@ class EmbroideryElement(object): return [c for c in self.commands if c.command == command] @cache + def has_command(self, command): + return len(self.get_commands(command)) > 0 + + @cache def get_command(self, command): commands = self.get_commands(command) @@ -238,22 +246,10 @@ class EmbroideryElement(object): return [self.strip_control_points(subpath) for subpath in path] @property - @param('trim_after', - _('TRIM after'), - tooltip=_('Trim thread after this object (for supported machines and file formats)'), - type='boolean', - default=False, - sort_index=1000) def trim_after(self): return self.get_boolean_param('trim_after', False) @property - @param('stop_after', - _('STOP after'), - tooltip=_('Add STOP instruction after this object (for supported machines and file formats)'), - type='boolean', - default=False, - sort_index=1000) def stop_after(self): return self.get_boolean_param('stop_after', False) @@ -264,8 +260,8 @@ class EmbroideryElement(object): patches = self.to_patches(last_patch) if patches: - patches[-1].trim_after = self.trim_after - patches[-1].stop_after = self.stop_after + patches[-1].trim_after = self.has_command("trim") or self.trim_after + patches[-1].stop_after = self.has_command("stop") or self.stop_after return patches diff --git a/lib/elements/polyline.py b/lib/elements/polyline.py index 5c474237..b9ffdc0b 100644 --- a/lib/elements/polyline.py +++ b/lib/elements/polyline.py @@ -1,3 +1,5 @@ +from shapely import geometry as shgeo + from .element import param, EmbroideryElement, Patch from ..i18n import _ from ..utils.geometry import Point @@ -28,6 +30,11 @@ class Polyline(EmbroideryElement): return points @property + @cache + def shape(self): + return shgeo.LineString(self.points) + + @property def path(self): # A polyline is a series of connected line segments described by their # points. In order to make use of the existing logic for incorporating diff --git a/lib/elements/satin_column.py b/lib/elements/satin_column.py index 1d13c5e0..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 @@ -89,6 +95,17 @@ class SatinColumn(EmbroideryElement): @property @cache + def shape(self): + # This isn't used for satins at all, but other parts of the code + # may need to know the general shape of a satin column. + + flattened = self.flatten(self.parse_path()) + line_strings = [shgeo.LineString(path) for path in flattened] + + return shgeo.MultiLineString(line_strings) + + @property + @cache def csp(self): return self.parse_path() @@ -377,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. @@ -400,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 diff --git a/lib/elements/stroke.py b/lib/elements/stroke.py index eca9e0ba..bc2ee54c 100644 --- a/lib/elements/stroke.py +++ b/lib/elements/stroke.py @@ -1,9 +1,10 @@ import sys +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 @@ -26,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) @@ -51,7 +62,13 @@ class Stroke(EmbroideryElement): return self.flatten(path) @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) + @cache + def shape(self): + line_strings = [shapely.geometry.LineString(path) for path in self.paths] + 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) def manual_stitch_mode(self): return self.get_boolean_param('manual_stitch') @@ -145,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) diff --git a/lib/extensions/__init__.py b/lib/extensions/__init__.py index b11ba1a4..30a08c9f 100644 --- a/lib/extensions/__init__.py +++ b/lib/extensions/__init__.py @@ -7,3 +7,5 @@ from input import Input 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/base.py b/lib/extensions/base.py index 78f75cf1..d230f1b0 100644 --- a/lib/extensions/base.py +++ b/lib/extensions/base.py @@ -58,11 +58,7 @@ class InkStitchMetadata(MutableMapping): def __setitem__(self, name, value): item = self._find_item(name) - - if value: - item.text = json.dumps(value) - else: - item.getparent().remove(item) + item.text = json.dumps(value) def _find_item(self, name, create=True): tag = inkex.addNS(name, "inkstitch") diff --git a/lib/extensions/commands.py b/lib/extensions/commands.py new file mode 100644 index 00000000..353c9874 --- /dev/null +++ b/lib/extensions/commands.py @@ -0,0 +1,146 @@ +import os +import sys +import inkex +import simpletransform +import cubicsuperpath +from copy import deepcopy +from random import random +from shapely import geometry as shgeo + +from .base import InkstitchExtension +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_correction_transform + + +class Commands(InkstitchExtension): + COMMANDS = ["fill_start", "fill_end", "stop", "trim"] + + def __init__(self, *args, **kwargs): + InkstitchExtension.__init__(self, *args, **kwargs) + for command in self.COMMANDS: + self.OptionParser.add_option("--%s" % command, type="inkbool") + + @property + def symbols_path(self): + return os.path.join(get_bundled_dir("symbols"), "inkstitch.svg") + + @property + @cache + def symbols_svg(self): + with open(self.symbols_path) as symbols_file: + return inkex.etree.parse(symbols_file) + + @property + @cache + def symbol_defs(self): + return self.symbols_svg.find(SVG_DEFS_TAG) + + @property + @cache + def defs(self): + return self.document.find(SVG_DEFS_TAG) + + def ensure_symbol(self, command): + path = "./*[@id='inkstitch_%s']" % command + if self.defs.find(path) is None: + self.defs.append(deepcopy(self.symbol_defs.find(path))) + + 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. + start_pos = (symbol.get('x'), symbol.get('y')) + end_pos = element.shape.centroid + + path = inkex.etree.Element(SVG_PATH_TAG, + { + "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": get_correction_transform(symbol), + CONNECTION_START: "#%s" % symbol.get('id'), + CONNECTION_END: "#%s" % element.node.get('id'), + CONNECTOR_TYPE: "polyline", + } + ) + + symbol.getparent().insert(symbol.getparent().index(symbol), path) + + def get_command_pos(self, element, index, total): + # Put command symbols 30 pixels out from the shape, spaced evenly around it. + + # get a line running 30 pixels out from the shape + outline = element.shape.buffer(30).exterior + + # pick this item's spot arond the outline and perturb it a bit to avoid + # stacking up commands if they run the extension multiple times + position = index / float(total) + position += random() * 0.1 + + return outline.interpolate(position, normalized=True) + + def remove_legacy_param(self, element, command): + if command == "trim" or command == "stop": + # If they had the old "TRIM after" or "STOP after" attributes set, + # automatically delete them. THe new commands will do the same + # thing. + # + # If we didn't delete these here, then things would get confusing. + # If the user were to delete a "trim" symbol added by this extension + # but the "embroider_trim_after" attribute is still set, then the + # trim would keep happening. + + attribute = "embroider_%s_after" % command + + if attribute in element.node.attrib: + del element.node.attrib[attribute] + + def add_command(self, element, commands): + for i, command in enumerate(commands): + self.remove_legacy_param(element, command) + + pos = self.get_command_pos(element, i, len(commands)) + + symbol = inkex.etree.SubElement(element.node.getparent(), SVG_USE_TAG, + { + "id": self.uniqueId("use"), + XLINK_HREF: "#inkstitch_%s" % command, + "height": "100%", + "width": "100%", + "x": str(pos.x), + "y": str(pos.y), + "transform": get_correction_transform(element.node) + } + ) + + self.add_connector(symbol, element) + + def effect(self): + if not self.get_elements(): + return + + if not self.selected: + inkex.errormsg(_("Please select one or more objects to which to attach commands.")) + return + + self.svg = self.document.getroot() + + commands = [command for command in self.COMMANDS if getattr(self.options, command)] + + if not commands: + inkex.errormsg(_("Please choose one or more commands to attach.")) + return + + for command in commands: + self.ensure_symbol(command) + + # Each object (node) in the SVG may correspond to multiple Elements of different + # types (e.g. stroke + fill). We only want to process each one once. + seen_nodes = set() + + for element in self.elements: + if element.node not in seen_nodes: + self.add_command(element, commands) + seen_nodes.add(element.node) diff --git a/lib/extensions/convert_to_satin.py b/lib/extensions/convert_to_satin.py new file mode 100644 index 00000000..1eae69b1 --- /dev/null +++ b/lib/extensions/convert_to_satin.py @@ -0,0 +1,290 @@ +import inkex +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 + +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 SelfIntersectionError(Exception): + pass + + +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) + 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 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 + self.document = deepcopy(self.original_document) + + return + + parent.insert(index, self.satin_to_svg_node(rails, rungs, correction_transform)) + + 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.""" + + 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', **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): + # 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 SelfIntersectionError() + + # 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 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 + + 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: + # 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() + prev_direction = direction + prev_point = point + + return scores + + def local_minima(self, array): + # from: https://stackoverflow.com/a/9667121/4249120 + # 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() + + # 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 + + + 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/extensions/input.py b/lib/extensions/input.py index 21248dd9..cb5ac452 100644 --- a/lib/extensions/input.py +++ b/lib/extensions/input.py @@ -3,53 +3,29 @@ from os.path import realpath, dirname, join as path_join import sys from inkex import etree import inkex - -# help python find libembroidery when running in a local repo clone -if getattr(sys, 'frozen', None) is None: - sys.path.append(realpath(path_join(dirname(__file__), '..', '..'))) - -from libembroidery import * +import pyembroidery from ..svg import PIXELS_PER_MM, render_stitch_plan from ..svg.tags import INKSCAPE_LABEL from ..i18n import _ -from ..stitch_plan import StitchPlan +from ..stitch_plan import StitchPlan, ColorBlock from ..utils.io import save_stdout class Input(object): - def pattern_stitches(self, pattern): - stitch_pointer = pattern.stitchList - while stitch_pointer: - yield stitch_pointer.stitch - stitch_pointer = stitch_pointer.next - - def affect(self, args): - # libembroidery likes to dump a bunch of debugging stuff to stdout - save_stdout() - embroidery_file = args[0] - pattern = embPattern_create() - embPattern_read(pattern, embroidery_file) - embPattern_flipVertical(pattern) + pattern = pyembroidery.read(embroidery_file) stitch_plan = StitchPlan() color_block = None - current_color = None - - for stitch in self.pattern_stitches(pattern): - if stitch.color != current_color: - thread = embThreadList_getAt(pattern.threadList, stitch.color) - color = thread.color - color_block = stitch_plan.new_color_block((color.r, color.g, color.b)) - current_color = stitch.color - if not stitch.flags & END: - color_block.add_stitch(stitch.xx * PIXELS_PER_MM, stitch.yy * PIXELS_PER_MM, - jump=stitch.flags & JUMP, - color_change=stitch.flags & STOP, - trim=stitch.flags & TRIM) + for raw_stitches, thread in pattern.get_as_colorblocks(): + color_block = stitch_plan.new_color_block(thread) + for x, y, command in raw_stitches: + color_block.add_stitch(x * PIXELS_PER_MM / 10.0, y * PIXELS_PER_MM / 10.0, + jump=(command == pyembroidery.JUMP), + trim=(command == pyembroidery.TRIM)) extents = stitch_plan.extents svg = etree.Element("svg", nsmap=inkex.NSS, attrib= @@ -69,4 +45,4 @@ class Input(object): # Note: this is NOT the same as centering the design in the canvas! layer.set('transform', 'translate(%s,%s)' % (extents[0], extents[1])) - print >> sys.real_stdout, etree.tostring(svg) + print etree.tostring(svg) diff --git a/lib/extensions/install.py b/lib/extensions/install.py index d55b96d0..42a92113 100644 --- a/lib/extensions/install.py +++ b/lib/extensions/install.py @@ -13,7 +13,7 @@ import logging import wx import inkex -from ..utils import guess_inkscape_config_path +from ..utils import guess_inkscape_config_path, get_bundled_dir class InstallerFrame(wx.Frame): @@ -78,15 +78,9 @@ class InstallerFrame(wx.Frame): def install_addons(self, type): path = os.path.join(self.path, type) - src_dir = self.get_bundled_dir(type) + src_dir = get_bundled_dir(type) self.copy_files(glob(os.path.join(src_dir, "*")), path) - def get_bundled_dir(self, name): - if getattr(sys, 'frozen', None) is not None: - return realpath(os.path.join(sys._MEIPASS, '..', name)) - else: - return realpath(os.path.join(dirname(realpath(__file__)), '..', '..', name)) - if (sys.platform == "win32"): # If we try to just use shutil.copy it says the operation requires elevation. def copy_files(self, files, dest): diff --git a/lib/extensions/output.py b/lib/extensions/output.py index f4b153e6..1dc8d19d 100644 --- a/lib/extensions/output.py +++ b/lib/extensions/output.py @@ -29,20 +29,17 @@ class Output(InkstitchExtension): patches = self.elements_to_patches(self.elements) stitch_plan = patches_to_stitch_plan(patches, self.options.collapse_length_mm * PIXELS_PER_MM) - # libembroidery wants to write to an actual file rather than stdout temp_file = tempfile.NamedTemporaryFile(suffix=".%s" % self.options.file_extension, delete=False) # in windows, failure to close here will keep the file locked temp_file.close() - # libembroidery likes to debug log things to stdout. No way to disable it. - save_stdout() write_embroidery_file(temp_file.name, stitch_plan, self.document.getroot()) # inkscape will read the file contents from stdout and copy # to the destination file that the user chose with open(temp_file.name) as output_file: - sys.real_stdout.write(output_file.read()) + sys.stdout.write(output_file.read()) # clean up the temp file os.remove(temp_file.name) diff --git a/lib/extensions/params.py b/lib/extensions/params.py index 58fedd6b..1b8f2589 100644 --- a/lib/extensions/params.py +++ b/lib/extensions/params.py @@ -424,7 +424,7 @@ class SettingsFrame(wx.Frame): self.simulate_window.stop() self.simulate_window.load(stitch_plan=stitch_plan) else: - my_rect = self.GetRect() + my_rect = self.GetScreenRect() simulator_pos = my_rect.GetTopRight() simulator_pos.x += 5 diff --git a/lib/extensions/zip.py b/lib/extensions/zip.py index ca12efdd..02f29e8a 100644 --- a/lib/extensions/zip.py +++ b/lib/extensions/zip.py @@ -4,7 +4,7 @@ import os import inkex import tempfile from zipfile import ZipFile -from libembroidery import * +import pyembroidery from .base import InkstitchExtension from ..i18n import _ @@ -24,18 +24,11 @@ class Zip(InkstitchExtension): # it's kind of obnoxious that I have to do this... self.formats = [] - formatList = embFormatList_create() - curFormat = formatList - while(curFormat): - # extension includes the dot, so we'll remove it - extension = embFormat_extension(curFormat)[1:] - description = embFormat_description(curFormat) - writer_state = embFormat_writerState(curFormat) - - if writer_state.strip() and embFormat_type(curFormat) != EMBFORMAT_OBJECTONLY: + for format in pyembroidery.supported_formats(): + if 'writer' in format and format['category'] == 'embroidery': + extension = format['extension'] self.OptionParser.add_option('--format-%s' % extension, type="inkbool", dest=extension) self.formats.append(extension) - curFormat = curFormat.next def effect(self): if not self.get_elements(): @@ -49,19 +42,12 @@ class Zip(InkstitchExtension): files = [] - # libembroidery likes to debug log things to stdout. No way to disable it. - save_stdout() for format in self.formats: if getattr(self.options, format): output_file = os.path.join(path, "%s.%s" % (base_file_name, format)) write_embroidery_file(output_file, stitch_plan, self.document.getroot()) files.append(output_file) - # I'd love to do restore_stderr() here, but if I do, libembroidery's - # stuff still prints out and corrupts the zip! That's because it uses - # C's buffered stdout, so it hasn't actually written anything to the - # real standard output yet. - if not files: self.errormsg(_("No embroidery file formats selected.")) @@ -77,7 +63,7 @@ class Zip(InkstitchExtension): # inkscape will read the file contents from stdout and copy # to the destination file that the user chose with open(temp_file.name) as output_file: - sys.real_stdout.write(output_file.read()) + sys.stdout.write(output_file.read()) os.remove(temp_file.name) for file in files: diff --git a/lib/output.py b/lib/output.py index 84128a25..0d7f9918 100644 --- a/lib/output.py +++ b/lib/output.py @@ -1,4 +1,4 @@ -import libembroidery +import pyembroidery import inkex import simpletransform import shapely.geometry as shgeo @@ -7,36 +7,17 @@ from .utils import Point from .svg import PIXELS_PER_MM, get_doc_size, get_viewbox_transform -def make_thread(color): - thread = libembroidery.EmbThread() - thread.color = libembroidery.embColor_make(*color.rgb) - - thread.description = color.name - thread.catalogNumber = "" - - return thread - -def add_thread(pattern, thread): - """Add a thread to a pattern and return the thread's index""" - - libembroidery.embPattern_addThread(pattern, thread) - - return libembroidery.embThreadList_count(pattern.threadList) - 1 - -def get_flags(stitch): - flags = 0 - +def get_command(stitch): if stitch.jump: - flags |= libembroidery.JUMP - - if stitch.trim: - flags |= libembroidery.TRIM - - if stitch.color_change: - flags |= libembroidery.STOP - - return flags - + return pyembroidery.JUMP + elif stitch.trim: + return pyembroidery.TRIM + elif stitch.color_change: + return pyembroidery.COLOR_CHANGE + elif stitch.stop: + return pyembroidery.STOP + else: + return pyembroidery.NEEDLE_AT def _string_to_floats(string): floats = string.split(',') @@ -102,27 +83,32 @@ def get_origin(svg): def write_embroidery_file(file_path, stitch_plan, svg): origin = get_origin(svg) - pattern = libembroidery.embPattern_create() + pattern = pyembroidery.EmbPattern() for color_block in stitch_plan: - add_thread(pattern, make_thread(color_block.color)) + pattern.add_thread(color_block.color.pyembroidery_thread) for stitch in color_block: - if stitch.stop: - # This is the start of the extra color block added by the - # "STOP after" handler (see stitch_plan/stop.py). Assign it - # the same color. - add_thread(pattern, make_thread(color_block.color)) + command = get_command(stitch) + pattern.add_stitch_absolute(command, stitch.x, stitch.y) - flags = get_flags(stitch) - libembroidery.embPattern_addStitchAbs(pattern, stitch.x - origin.x, stitch.y - origin.y, flags, 1) - - libembroidery.embPattern_addStitchAbs(pattern, stitch.x - origin.x, stitch.y - origin.y, libembroidery.END, 1) + pattern.add_stitch_absolute(pyembroidery.END, stitch.x, stitch.y) # convert from pixels to millimeters - libembroidery.embPattern_scale(pattern, 1/PIXELS_PER_MM) + # also multiply by 10 to get tenths of a millimeter as required by pyembroidery + scale = 10 / PIXELS_PER_MM + + settings = { + # correct for the origin + "translate": -origin, + + # convert from pixels to millimeters + # also multiply by 10 to get tenths of a millimeter as required by pyembroidery + "scale": (scale, scale), - # SVG and embroidery disagree on the direction of the Y axis - libembroidery.embPattern_flipVertical(pattern) + # This forces a jump at the start of the design and after each trim, + # even if we're close enough not to need one. + "full_jump": True, + } - libembroidery.embPattern_write(pattern, file_path) + pyembroidery.write(pattern, file_path, settings) diff --git a/lib/simulator.py b/lib/simulator.py index c7e74353..2d2d3e08 100644 --- a/lib/simulator.py +++ b/lib/simulator.py @@ -27,6 +27,26 @@ class EmbroiderySimulator(wx.Frame): self.panel = wx.Panel(self, wx.ID_ANY) self.panel.SetFocus() + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) + + self.button_label = ( + [_("Speed up"),_('Press + or arrow up to speed up')], + [_("Slow down"),_('Press - or arrow down to slow down')], + [_("Pause"),_("Press P to pause the animation")], + [_("Restart"),_("Press R to restart the animation")], + [_("Quit"),_("Press Q to close the simulation window")]) + self.buttons = [] + for i in range(0, len(self.button_label)): + self.buttons.append(wx.Button(self, -1, self.button_label[i][0])) + self.button_sizer.Add(self.buttons[i], 1, wx.EXPAND) + self.buttons[i].Bind(wx.EVT_BUTTON, self.on_key_down) + self.buttons[i].SetToolTip(self.button_label[i][1]) + + self.sizer.Add(self.panel, 1, wx.EXPAND) + self.sizer.Add(self.button_sizer, 0, wx.EXPAND) + self.SetSizer(self.sizer) + self.load(stitch_plan) if self.target_duration: @@ -68,26 +88,30 @@ class EmbroiderySimulator(wx.Frame): self.stitches_per_frame *= 2 def on_key_down(self, event): - keycode = event.GetKeyCode() + if hasattr(event, 'GetKeyCode'): + keycode = event.GetKeyCode() + else: + keycode = event.GetEventObject().GetLabelText() + self.panel.SetFocus() - if keycode == ord("+") or keycode == ord("=") or keycode == wx.WXK_UP: + if keycode == ord("+") or keycode == ord("=") or keycode == wx.WXK_UP or keycode == "Speed up": if self.frame_period == 1: self.stitches_per_frame *= 2 else: self.frame_period = self.frame_period / 2 - elif keycode == ord("-") or keycode == ord("_") or keycode == wx.WXK_DOWN: + elif keycode == ord("-") or keycode == ord("_") or keycode == wx.WXK_DOWN or keycode == "Slow down": if self.stitches_per_frame == 1: self.frame_period *= 2 else: self.stitches_per_frame /= 2 - elif keycode == ord("Q"): + elif keycode == ord("Q") or keycode == "Quit": self.Close() - elif keycode == ord('P'): + elif keycode == ord("P") or keycode == "Pause": if self.timer.IsRunning(): self.timer.Stop() else: self.timer.Start(self.frame_period) - elif keycode == ord("R"): + elif keycode == ord("R") or keycode == "Restart": self.stop() self.clear() self.go() @@ -170,7 +194,7 @@ class EmbroiderySimulator(wx.Frame): self.width = width self.height = height - self.scale = min(float(self.max_width) / width, float(self.max_height) / height) + self.scale = min(float(self.max_width) / width, float(self.max_height - 60) / height) # make room for decorations and the margin self.scale *= 0.95 @@ -212,10 +236,15 @@ class EmbroiderySimulator(wx.Frame): client_width, client_height = self.GetClientSize() decorations_width = window_width - client_width - decorations_height = window_height - client_height + decorations_height = window_height - client_height + 40 + + setsize_window_width = self.width * self.scale + decorations_width + self.margin * 2 + setsize_window_height = (self.height) * self.scale + decorations_height + self.margin * 2 + + if setsize_window_width < 600: + setsize_window_width = 600 - self.SetSize((self.width * self.scale + decorations_width + self.margin * 2, - self.height * self.scale + decorations_height + self.margin * 2)) + self.SetSize(( setsize_window_width, setsize_window_height)) e.Skip() diff --git a/lib/stitch_plan/stitch.py b/lib/stitch_plan/stitch.py index 12642a60..5230efec 100644 --- a/lib/stitch_plan/stitch.py +++ b/lib/stitch_plan/stitch.py @@ -2,7 +2,7 @@ from ..utils.geometry import Point class Stitch(Point): - def __init__(self, x, y, color=None, jump=False, stop=False, trim=False, color_change=False, no_ties=False): + def __init__(self, x, y, color=None, jump=False, stop=False, trim=False, color_change=False, fake_color_change=False, no_ties=False): self.x = x self.y = y self.color = color @@ -10,10 +10,20 @@ class Stitch(Point): self.trim = trim self.stop = stop self.color_change = color_change + self.fake_color_change = fake_color_change self.no_ties = no_ties def __repr__(self): - return "Stitch(%s, %s, %s, %s, %s, %s, %s)" % (self.x, self.y, self.color, "JUMP" if self.jump else " ", "TRIM" if self.trim else " ", "STOP" if self.stop else " ", "NO TIES" if self.no_ties else " ") + return "Stitch(%s, %s, %s, %s, %s, %s, %s, %s%s)" % (self.x, + self.y, + self.color, + "JUMP" if self.jump else " ", + "TRIM" if self.trim else " ", + "STOP" if self.stop else " ", + "NO TIES" if self.no_ties else " ", + "FAKE " if self.fake_color_change else "", + "COLOR CHANGE" if self.color_change else " " + ) def copy(self): return Stitch(self.x, self.y, self.color, self.jump, self.stop, self.trim, self.color_change, self.no_ties) diff --git a/lib/stitch_plan/stitch_plan.py b/lib/stitch_plan/stitch_plan.py index 93bcd195..682ea09f 100644 --- a/lib/stitch_plan/stitch_plan.py +++ b/lib/stitch_plan/stitch_plan.py @@ -1,6 +1,4 @@ from .stitch import Stitch -from .stop import process_stop -from .trim import process_trim from .ties import add_ties from ..svg import PIXELS_PER_MM from ..utils.geometry import Point @@ -16,62 +14,45 @@ def patches_to_stitch_plan(patches, collapse_len=3.0 * PIXELS_PER_MM): """ stitch_plan = StitchPlan() - color_block = stitch_plan.new_color_block() - need_trim = False + if not patches: + return stitch_plan + + color_block = stitch_plan.new_color_block(color=patches[0].color) + for patch in patches: if not patch.stitches: continue - if not color_block.has_color(): - # set the color for the first color block - color_block.color = patch.color - - if color_block.color == patch.color: - if need_trim: - process_trim(color_block, patch.stitches[0]) - need_trim = False - - # add a jump stitch between patches if the distance is more - # than the collapse length - if color_block.last_stitch: - if (patch.stitches[0] - color_block.last_stitch).length() > collapse_len: - color_block.add_stitch(patch.stitches[0].x, patch.stitches[0].y, jump=True) - - else: - # add a color change (only if we didn't just do a "STOP after") - if not color_block.last_stitch.color_change: - stitch = color_block.last_stitch.copy() - stitch.color_change = True - color_block.add_stitch(stitch) + if color_block.color != patch.color: + if len(color_block) == 0: + # We just processed a stop, which created a new color block. + # We'll just claim this new block as ours: + color_block.color = patch.color + else: + # end the previous block with a color change + color_block.add_stitch(color_change=True) - color_block = stitch_plan.new_color_block() - color_block.color = patch.color + # make a new block of our color + color_block = stitch_plan.new_color_block(color=patch.color) - color_block.filter_duplicate_stitches() color_block.add_stitches(patch.stitches, no_ties=patch.stitch_as_is) if patch.trim_after: - # a trim needs to be followed by a jump to the next stitch, so - # we'll process it when we start the next patch - need_trim = True + color_block.add_stitch(trim=True) if patch.stop_after: - process_stop(color_block) - - add_jumps(stitch_plan) - add_ties(stitch_plan) - - return stitch_plan + color_block.add_stitch(stop=True) + color_block = stitch_plan.new_color_block(color_block.color) + if len(color_block) == 0: + # last block ended in a stop, so now we have an empty block + del stitch_plan.color_blocks[-1] -def add_jumps(stitch_plan): - """Add a JUMP stitch at the start of each color block.""" + stitch_plan.filter_duplicate_stitches() + stitch_plan.add_ties() - for color_block in stitch_plan: - stitch = color_block.stitches[0].copy() - stitch.jump = True - color_block.stitches.insert(0, stitch) + return stitch_plan class StitchPlan(object): @@ -85,6 +66,17 @@ class StitchPlan(object): self.color_blocks.append(color_block) return color_block + def add_color_block(self, color_block): + self.color_blocks.append(color_block) + + def filter_duplicate_stitches(self): + for color_block in self: + color_block.filter_duplicate_stitches() + + def add_ties(self): + # see ties.py + add_ties(self) + def __iter__(self): return iter(self.color_blocks) @@ -100,8 +92,12 @@ class StitchPlan(object): return len({block.color for block in self}) @property + def num_color_blocks(self): + return len(self.color_blocks) + + @property def num_stops(self): - return sum(block.num_stops for block in self) + return sum(1 for block in self if block.stop_after) @property def num_trims(self): @@ -137,6 +133,13 @@ class StitchPlan(object): dimensions = self.dimensions return (dimensions[0] / PIXELS_PER_MM, dimensions[1] / PIXELS_PER_MM) + @property + def last_color_block(self): + if self.color_blocks: + return self.color_blocks[-1] + else: + return None + class ColorBlock(object): """Holds a set of stitches, all with the same thread color.""" @@ -148,6 +151,9 @@ class ColorBlock(object): def __iter__(self): return iter(self.stitches) + def __len__(self): + return len(self.stitches) + def __repr__(self): return "ColorBlock(%s, %s)" % (self.color, self.stitches) @@ -180,20 +186,18 @@ class ColorBlock(object): return len(self.stitches) @property - def num_stops(self): - """Number of pauses in this color block.""" - - # Stops are encoded using two STOP stitches each. See the comment in - # stop.py for an explanation. - - return sum(1 for stitch in self if stitch.stop) / 2 - - @property def num_trims(self): """Number of trims in this color block.""" return sum(1 for stitch in self if stitch.trim) + @property + def stop_after(self): + if self.last_stitch is not None: + return self.last_stitch.stop + else: + return False + def filter_duplicate_stitches(self): if not self.stitches: return @@ -201,12 +205,12 @@ class ColorBlock(object): stitches = [self.stitches[0]] for stitch in self.stitches[1:]: - if stitches[-1].jump or stitch.stop or stitch.trim: - # Don't consider jumps, stops, or trims as candidates for filtering + if stitches[-1].jump or stitch.stop or stitch.trim or stitch.color_change: + # Don't consider jumps, stops, color changes, or trims as candidates for filtering pass else: l = (stitch - stitches[-1]).length() - if l <= 0.1: + if l <= 0.1 * PIXELS_PER_MM: # duplicate stitch, skip this one continue @@ -215,11 +219,21 @@ class ColorBlock(object): self.stitches = stitches def add_stitch(self, *args, **kwargs): + if not args: + # They're adding a command, e.g. `color_block.add_stitch(stop=True)``. + # Use the position from the last stitch. + if self.last_stitch: + args = (self.last_stitch.x, self.last_stitch.y) + else: + raise ValueError("internal error: can't add a command to an empty stitch block") + if isinstance(args[0], Stitch): self.stitches.append(args[0]) elif isinstance(args[0], Point): self.stitches.append(Stitch(args[0].x, args[0].y, *args[1:], **kwargs)) else: + if not args and self.last_stitch: + args = (self.last_stitch.x, self.last_stitch.y) self.stitches.append(Stitch(*args, **kwargs)) def add_stitches(self, stitches, *args, **kwargs): diff --git a/lib/stitch_plan/stop.py b/lib/stitch_plan/stop.py deleted file mode 100644 index 81dec1da..00000000 --- a/lib/stitch_plan/stop.py +++ /dev/null @@ -1,43 +0,0 @@ -def process_stop(color_block): - """Handle the "stop after" checkbox. - - The user wants the machine to pause after this patch. This can - be useful for applique and similar on multi-needle machines that - normally would not stop between colors. - - In machine embroidery files, there's no such thing as an actual - "STOP" instruction. All that exists is a "color change" command - (which libembroidery calls STOP just to be confusing). - - On multi-needle machines, the user assigns needles to the colors in - the design before starting stitching. C01, C02, etc are normal - needles, but C00 is special. For a block of stitches assigned - to C00, the machine will continue sewing with the last color it - had and pause after it completes the C00 block. - - That means we need to add an artificial color change instruction - shortly before the current stitch so that the user can set that color - block to C00. We'll go back 3 stitches and mark the start of the C00 - block: - """ - - if len(color_block.stitches) >= 3: - # make a copy of the stitch and set it as a color change - stitch = color_block.stitches[-3].copy() - stitch.color_change = True - - # mark this stitch as a "stop" so that we can avoid - # adding tie stitches in ties.py - stitch.stop = True - - # insert it after the stitch - color_block.stitches.insert(-2, stitch) - - # and also add a color change on this stitch, completing the C00 - # block: - - stitch = color_block.stitches[-1].copy() - stitch.color_change = True - color_block.add_stitch(stitch) - - # reference for the above: https://github.com/lexelby/inkstitch/pull/29#issuecomment-359175447 diff --git a/lib/stitch_plan/ties.py b/lib/stitch_plan/ties.py index 6d07ac71..573469f5 100644 --- a/lib/stitch_plan/ties.py +++ b/lib/stitch_plan/ties.py @@ -30,15 +30,16 @@ def add_tie_in(stitches, upcoming_stitches): def add_ties(stitch_plan): """Add tie-off before and after trims, jumps, and color changes.""" + need_tie_in = True for color_block in stitch_plan: - need_tie_in = True new_stitches = [] for i, stitch in enumerate(color_block.stitches): - # Tie before and after TRIMs, JUMPs, and color changes, but ignore - # the fake color change introduced by a "STOP after" (see stop.py). - is_special = stitch.trim or stitch.jump or (stitch.color_change and not stitch.stop) + is_special = stitch.trim or stitch.jump or stitch.color_change or stitch.stop - if is_special and not need_tie_in: + # see stop.py for an explanation of the fake color change + is_fake = stitch.fake_color_change + + if is_special and not is_fake and not need_tie_in: add_tie_off(new_stitches) new_stitches.append(stitch) need_tie_in = True @@ -49,7 +50,8 @@ def add_ties(stitch_plan): else: new_stitches.append(stitch) - if not need_tie_in: - add_tie_off(new_stitches) - color_block.replace_stitches(new_stitches) + + if not need_tie_in: + # tie off at the end if we haven't already + add_tie_off(color_block.stitches) diff --git a/lib/stitch_plan/trim.py b/lib/stitch_plan/trim.py deleted file mode 100644 index f692a179..00000000 --- a/lib/stitch_plan/trim.py +++ /dev/null @@ -1,23 +0,0 @@ -def process_trim(color_block, next_stitch): - """Handle the "trim after" checkbox. - - DST (and maybe other formats?) has no actual TRIM instruction. - Instead, 3 sequential JUMPs cause the machine to trim the thread. - - To support both DST and other formats, we'll add a TRIM and two - JUMPs. The TRIM will be converted to a JUMP by libembroidery - if saving to DST, resulting in the 3-jump sequence. - """ - - delta = next_stitch - color_block.last_stitch - delta = delta * (1/4.0) - - pos = color_block.last_stitch - - for i in xrange(3): - pos += delta - color_block.add_stitch(pos.x, pos.y, jump=True) - - # first one should be TRIM instead of JUMP - color_block.stitches[-3].jump = False - color_block.stitches[-3].trim = True 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 diff --git a/lib/svg/__init__.py b/lib/svg/__init__.py index 50543b1b..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 +from .path import apply_transforms, get_node_transform, get_correction_transform diff --git a/lib/svg/path.py b/lib/svg/path.py index a8012774..52144332 100644 --- a/lib/svg/path.py +++ b/lib/svg/path.py @@ -4,17 +4,41 @@ import cubicsuperpath from .units import get_viewbox_transform def apply_transforms(path, node): + transform = get_node_transform(node) + + # apply the combined transform to this node's path + simpletransform.applyTransformToPath(transform, path) + + return path + +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()) transform = simpletransform.composeTransform(viewbox_transform, transform) - # apply the combined transform to this node's path - simpletransform.applyTransformToPath(transform, path) + return transform - return path +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) diff --git a/lib/svg/svg.py b/lib/svg/svg.py index 5552abd8..48b1343a 100644 --- a/lib/svg/svg.py +++ b/lib/svg/svg.py @@ -37,6 +37,9 @@ def color_block_to_realistic_stitches(color_block, svg): paths = [] for point_list in color_block_to_point_lists(color_block): + if not point_list: + continue + color = color_block.color.visible_on_white.darker.to_hex_str() start = point_list[0] for point in point_list[1:]: diff --git a/lib/svg/tags.py b/lib/svg/tags.py index 5488608c..7eb87540 100644 --- a/lib/svg/tags.py +++ b/lib/svg/tags.py @@ -12,6 +12,7 @@ INKSCAPE_LABEL = inkex.addNS('label', 'inkscape') INKSCAPE_GROUPMODE = inkex.addNS('groupmode', 'inkscape') CONNECTION_START = inkex.addNS('connection-start', 'inkscape') CONNECTION_END = inkex.addNS('connection-end', 'inkscape') +CONNECTOR_TYPE = inkex.addNS('connector-type', 'inkscape') XLINK_HREF = inkex.addNS('href', 'xlink') EMBROIDERABLE_TAGS = (SVG_PATH_TAG, SVG_POLYLINE_TAG) diff --git a/lib/threads/color.py b/lib/threads/color.py index fede2ecc..cc6c0c48 100644 --- a/lib/threads/color.py +++ b/lib/threads/color.py @@ -1,7 +1,7 @@ import simplestyle import re import colorsys - +from pyembroidery.EmbThread import EmbThread class ThreadColor(object): hex_str_re = re.compile('#([0-9a-z]{3}|[0-9a-z]{6})', re.I) @@ -9,6 +9,12 @@ class ThreadColor(object): def __init__(self, color, name=None, number=None, manufacturer=None): if color is None: self.rgb = (0, 0, 0) + elif isinstance(color, EmbThread): + self.name = color.description + self.number = color.catalog_number + self.manufacturer = color.brand + self.rgb = (color.get_red(), color.get_green(), color.get_blue()) + return elif isinstance(color, (list, tuple)): self.rgb = tuple(color) elif self.hex_str_re.match(color): @@ -39,6 +45,15 @@ class ThreadColor(object): return "#%s" % self.hex_digits @property + def pyembroidery_thread(self): + return { + "name": self.name, + "id": self.number, + "manufacturer": self.manufacturer, + "rgb": int(self.hex_digits, 16), + } + + @property def hex_digits(self): return "%02X%02X%02X" % self.rgb diff --git a/lib/utils/__init__.py b/lib/utils/__init__.py index ff06d4a9..78d037f1 100644 --- a/lib/utils/__init__.py +++ b/lib/utils/__init__.py @@ -2,3 +2,4 @@ from geometry import * from cache import cache from io import * from inkscape import * +from paths import * diff --git a/lib/utils/geometry.py b/lib/utils/geometry.py index 7ff9b1cd..d0cb96cf 100644 --- a/lib/utils/geometry.py +++ b/lib/utils/geometry.py @@ -65,6 +65,9 @@ class Point: else: raise ValueError("cannot multiply Point by %s" % type(other)) + def __neg__(self): + return self * -1 + def __rmul__(self, other): if isinstance(other, (int, float)): return self.__mul__(other) diff --git a/lib/utils/paths.py b/lib/utils/paths.py new file mode 100644 index 00000000..863e8e69 --- /dev/null +++ b/lib/utils/paths.py @@ -0,0 +1,10 @@ +import sys +import os +from os.path import dirname, realpath + + +def get_bundled_dir(name): + if getattr(sys, 'frozen', None) is not None: + return realpath(os.path.join(sys._MEIPASS, "..", name)) + else: + return realpath(os.path.join(dirname(realpath(__file__)), '..', '..', name)) |
