diff --git a/images/examples/InkStitch Multi Color.svg b/images/examples/InkStitch Multi Color.svg index ba8364f0f..9d4b11e07 100644 --- a/images/examples/InkStitch Multi Color.svg +++ b/images/examples/InkStitch Multi Color.svg @@ -2,6 +2,7 @@ image/svg+xml - + + + "matrix(2.23777, 0, 0, 2.23777, -204, -268)" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + id="layer1"> + style="display:inline" + id="g4808"> + + + id="path4380" + d="M 42.829942,44.938859 41.694047,41.798443" + style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.44999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:0.44999998, 0.44999998;stroke-dashoffset:0;stroke-opacity:1" /> + + + + + embroider_running_stitch_length_mm="2.5" /> + + + + d="m 40.23084,74.503832 0.02363,-7.65402 m -2.078876,7.677642 0.02363,-7.630393" + style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.44999999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" + id="path4448" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/extensions/base.py b/lib/extensions/base.py index ff587ca58..52321cfc8 100644 --- a/lib/extensions/base.py +++ b/lib/extensions/base.py @@ -63,10 +63,10 @@ class InkStitchMetadata(MutableMapping): else: item.getparent().remove(item) - def _find_item(self, name): + def _find_item(self, name, create=True): tag = inkex.addNS(name, "inkstitch") item = self.metadata.find(tag) - if item is None: + if item is None and create: item = inkex.etree.SubElement(self.metadata, tag) return item @@ -80,9 +80,9 @@ class InkStitchMetadata(MutableMapping): return None def __delitem__(self, name): - item = self._find_item(name) + item = self._find_item(name, create=False) - if item: + if item is not None: self.metadata.remove(item) def __iter__(self): diff --git a/lib/extensions/print_pdf.py b/lib/extensions/print_pdf.py index baeb7eba3..6e2eff58a 100644 --- a/lib/extensions/print_pdf.py +++ b/lib/extensions/print_pdf.py @@ -21,7 +21,7 @@ import requests from .base import InkstitchExtension from ..i18n import _, translation as inkstitch_translation from ..svg import PIXELS_PER_MM, render_stitch_plan -from ..svg.tags import SVG_GROUP_TAG +from ..svg.tags import SVG_GROUP_TAG, INKSCAPE_GROUPMODE from ..stitch_plan import patches_to_stitch_plan from ..threads import ThreadCatalog @@ -94,6 +94,8 @@ class PrintPreviewServer(Thread): self.html = kwargs.pop('html') self.metadata = kwargs.pop('metadata') self.stitch_plan = kwargs.pop('stitch_plan') + self.realistic_overview_svg = kwargs.pop('realistic_overview_svg') + self.realistic_color_block_svgs = kwargs.pop('realistic_color_block_svgs') Thread.__init__(self, *args, **kwargs) self.daemon = True self.last_request_time = None @@ -202,6 +204,14 @@ class PrintPreviewServer(Thread): return jsonify(threads) + @self.app.route('/realistic/block', methods=['GET']) + def get_realistic_block(index): + return Response(self.realistic_color_block_svgs[index], mimetype='image/svg+xml') + + @self.app.route('/realistic/overview', methods=['GET']) + def get_realistic_overview(): + return Response(self.realistic_overview_svg, mimetype='image/svg+xml') + def stop(self): # for whatever reason, shutting down only seems possible in # the context of a flask request, so we'll just make one @@ -295,38 +305,24 @@ class Print(InkstitchExtension): return env - def strip_namespaces(self): + def strip_namespaces(self, svg): # namespace prefixes seem to trip up HTML, so get rid of them - for element in self.document.iter(): + for element in svg.iter(): if element.tag[0]=='{': element.tag = element.tag[element.tag.index('}',1) + 1:] - def effect(self): - # It doesn't really make sense to print just a couple of selected - # objects. It's almost certain they meant to print the whole design. - # If they really wanted to print just a few objects, they could set - # the rest invisible temporarily. - self.selected = {} + def render_svgs(self, stitch_plan, realistic=False): + svg = deepcopy(self.document).getroot() + render_stitch_plan(svg, stitch_plan, realistic) - if not self.get_elements(): - return - - self.hide_all_layers() - - patches = self.elements_to_patches(self.elements) - stitch_plan = patches_to_stitch_plan(patches) - palette = ThreadCatalog().match_and_apply_palette(stitch_plan, self.get_inkstitch_metadata()['thread-palette']) - render_stitch_plan(self.document.getroot(), stitch_plan) - - self.strip_namespaces() + self.strip_namespaces(svg) # Now the stitch plan layer will contain a set of groups, each # corresponding to a color block. We'll create a set of SVG files # corresponding to each individual color block and a final one # for all color blocks together. - svg = self.document.getroot() - layers = svg.findall("./g[@{http://www.inkscape.org/namespaces/inkscape}groupmode='layer']") + layers = svg.findall("./g[@%s='layer']" % INKSCAPE_GROUPMODE) stitch_plan_layer = svg.find(".//*[@id='__inkstitch_stitch_plan__']") # First, delete all of the other layers. We don't need them and they'll @@ -335,9 +331,9 @@ class Print(InkstitchExtension): if layer is not stitch_plan_layer: svg.remove(layer) - overview_svg = inkex.etree.tostring(self.document) - + overview_svg = inkex.etree.tostring(svg) color_block_groups = stitch_plan_layer.getchildren() + color_block_svgs = [] for i, group in enumerate(color_block_groups): # clear the stitch plan layer @@ -347,12 +343,15 @@ class Print(InkstitchExtension): stitch_plan_layer.append(group) # save an SVG preview - stitch_plan.color_blocks[i].svg_preview = inkex.etree.tostring(self.document) + color_block_svgs.append(inkex.etree.tostring(svg)) + return overview_svg, color_block_svgs + + def render_html(self, stitch_plan, overview_svg, selected_palette): env = self.build_environment() template = env.get_template('index.html') - html = template.render( + return template.render( view = {'client_overview': False, 'client_detailedview': False, 'operator_overview': True, 'operator_detailedview': True}, logo = {'src' : '', 'title' : 'LOGO'}, date = date.today(), @@ -371,14 +370,38 @@ class Print(InkstitchExtension): svg_overview = overview_svg, color_blocks = stitch_plan.color_blocks, palettes = ThreadCatalog().palette_names(), - selected_palette = palette, + selected_palette = selected_palette, ) - # We've totally mucked with the SVG. Restore it so that we can save - # metadata into it. - self.document = deepcopy(self.original_document) + def effect(self): + # It doesn't really make sense to print just a couple of selected + # objects. It's almost certain they meant to print the whole design. + # If they really wanted to print just a few objects, they could set + # the rest invisible temporarily. + self.selected = {} - print_server = PrintPreviewServer(html=html, metadata=self.get_inkstitch_metadata(), stitch_plan=stitch_plan) + if not self.get_elements(): + return + + patches = self.elements_to_patches(self.elements) + stitch_plan = patches_to_stitch_plan(patches) + palette = ThreadCatalog().match_and_apply_palette(stitch_plan, self.get_inkstitch_metadata()['thread-palette']) + + overview_svg, color_block_svgs = self.render_svgs(stitch_plan, realistic=False) + realistic_overview_svg, realistic_color_block_svgs = self.render_svgs(stitch_plan, realistic=True) + + for i, svg in enumerate(color_block_svgs): + stitch_plan.color_blocks[i].svg_preview = svg + + html = self.render_html(stitch_plan, overview_svg, palette) + + print_server = PrintPreviewServer( + html=html, + metadata=self.get_inkstitch_metadata(), + stitch_plan=stitch_plan, + realistic_overview_svg=realistic_overview_svg, + realistic_color_block_svgs=realistic_color_block_svgs + ) print_server.start() time.sleep(1) diff --git a/lib/svg/realistic_rendering.py b/lib/svg/realistic_rendering.py new file mode 100644 index 000000000..e31534daf --- /dev/null +++ b/lib/svg/realistic_rendering.py @@ -0,0 +1,129 @@ +import simplepath +import math + +from .units import PIXELS_PER_MM +from ..utils import cache, Point + +# The stitch vector path looks like this: +# _______ +# (_______) +# +# It's 0.32mm high, which is the approximate thickness of common machine +# embroidery threads. + +# 1.216 pixels = 0.32mm +stitch_height = 1.216 + +# This vector path starts at the upper right corner of the stitch shape and +# proceeds counter-clockwise.and contains a placeholder (%s) for the stitch +# length. +# +# It contains two invisible "whiskers" of zero width that go above and below +# to ensure that the SVG renderer allocates a large enough canvas area when +# computing the gaussian blur steps. Otherwise, we'd have to expand the +# width and height attributes of the tag to add more buffer space. +# The width and height are specified in multiples of the bounding box +# size, It's the bounding box aligned with the global SVG canvas's axes, not +# the axes of the stitch itself. That means that having a big enough value +# to add enough padding on the long sides of the stitch would waste a ton +# of space on the short sides and significantly slow down rendering. +stitch_path = "M0,0c0.4,0,0.4,0.3,0.4,0.6c0,0.3,-0.1,0.6,-0.4,0.6v0.2,-0.2h-%sc-0.4,0,-0.4,-0.3,-0.4,-0.6c0,-0.3,0.1,-0.6,0.4,-0.6v-0.2,0.2z" + +# This filter makes the above stitch path look like a real stitch with lighting. +realistic_filter = """ + + + + + + + + + + + + + + + + + + +""" + +def realistic_stitch(start, end): + """Generate a stitch vector path given a start and end point.""" + + end = Point(*end) + start = Point(*start) + + stitch_length = (end - start).length() + stitch_center = (end + start) / 2.0 + stitch_direction = (end - start) + stitch_angle = math.atan2(stitch_direction.y, stitch_direction.x) + + stitch_length = max(0, stitch_length - 0.2 * PIXELS_PER_MM) + + # create the path by filling in the length in the template + path = simplepath.parsePath(stitch_path % stitch_length) + + # rotate the path to match the stitch + rotation_center_x = -stitch_length / 2.0 + rotation_center_y = stitch_height / 2.0 + simplepath.rotatePath(path, stitch_angle, cx=rotation_center_x, cy=rotation_center_y) + + # move the path to the location of the stitch + simplepath.translatePath(path, stitch_center.x - rotation_center_x, stitch_center.y - rotation_center_y) + + return simplepath.formatPath(path) diff --git a/lib/svg/svg.py b/lib/svg/svg.py index 852215f23..5552abd8d 100644 --- a/lib/svg/svg.py +++ b/lib/svg/svg.py @@ -1,7 +1,8 @@ import simpletransform, simplestyle, inkex from .units import get_viewbox_transform -from .tags import SVG_GROUP_TAG, INKSCAPE_LABEL, INKSCAPE_GROUPMODE, SVG_PATH_TAG +from .tags import SVG_GROUP_TAG, INKSCAPE_LABEL, INKSCAPE_GROUPMODE, SVG_PATH_TAG, SVG_DEFS_TAG +from .realistic_rendering import realistic_stitch, realistic_filter from ..i18n import _ from ..utils import cache @@ -32,6 +33,28 @@ def get_correction_transform(svg): return transform +def color_block_to_realistic_stitches(color_block, svg): + paths = [] + + for point_list in color_block_to_point_lists(color_block): + color = color_block.color.visible_on_white.darker.to_hex_str() + start = point_list[0] + for point in point_list[1:]: + paths.append(inkex.etree.Element( + SVG_PATH_TAG, + {'style': simplestyle.formatStyle( + { + 'fill': color, + 'stroke': 'none', + 'filter': 'url(#realistic-stitch-filter)' + }), + 'd': realistic_stitch(start, point), + 'transform': get_correction_transform(svg) + })) + start = point + + return paths + def color_block_to_paths(color_block, svg): paths = [] # We could emit just a single path with one subpath per point list, but @@ -56,8 +79,7 @@ def color_block_to_paths(color_block, svg): return paths - -def render_stitch_plan(svg, stitch_plan): +def render_stitch_plan(svg, stitch_plan, realistic=False): layer = svg.find(".//*[@id='__inkstitch_stitch_plan__']") if layer is None: layer = inkex.etree.Element(SVG_GROUP_TAG, @@ -76,6 +98,17 @@ def render_stitch_plan(svg, stitch_plan): SVG_GROUP_TAG, {'id': '__color_block_%d__' % i, INKSCAPE_LABEL: "color block %d" % (i + 1)}) - group.extend(color_block_to_paths(color_block, svg)) + if realistic: + group.extend(color_block_to_realistic_stitches(color_block, svg)) + else: + group.extend(color_block_to_paths(color_block, svg)) svg.append(layer) + + if realistic: + defs = svg.find(SVG_DEFS_TAG) + + if defs is None: + defs = inkex.etree.SubElement(svg, SVG_DEFS_TAG) + + defs.append(inkex.etree.fromstring(realistic_filter)) diff --git a/lib/threads/color.py b/lib/threads/color.py index af474127c..fede2ecc8 100644 --- a/lib/threads/color.py +++ b/lib/threads/color.py @@ -80,3 +80,18 @@ class ThreadColor(object): color = tuple(value * 255 for value in color) return ThreadColor(color, name=self.name, number=self.number, manufacturer=self.manufacturer) + + @property + def darker(self): + hls = list(colorsys.rgb_to_hls(*self.rgb_normalized)) + + # Capping lightness should make the color visible without changing it + # too much. + hls[1] *= 0.75 + + color = colorsys.hls_to_rgb(*hls) + + # convert back to values in the range of 0-255 + color = tuple(value * 255 for value in color) + + return ThreadColor(color, name=self.name, number=self.number, manufacturer=self.manufacturer) diff --git a/lib/utils/geometry.py b/lib/utils/geometry.py index 61b98bcbb..7ff9b1cd7 100644 --- a/lib/utils/geometry.py +++ b/lib/utils/geometry.py @@ -71,6 +71,12 @@ class Point: else: raise ValueError("cannot multiply Point by %s" % type(other)) + def __div__(self, other): + if isinstance(other, (int, float)): + return self * (1.0 / other) + else: + raise ValueErorr("cannot divide Point by %s" % type(other)) + def __repr__(self): return "Point(%s,%s)" % (self.x, self.y) diff --git a/print/resources/inkstitch.js b/print/resources/inkstitch.js index 67690df27..4a757d5f3 100644 --- a/print/resources/inkstitch.js +++ b/print/resources/inkstitch.js @@ -7,6 +7,10 @@ $.postJSON = function(url, data, success=null) { }); }; +var realistic_rendering = {}; +var realistic_cache = {}; +var normal_rendering = {}; + function ping() { $.get("/ping") .done(function() { setTimeout(ping, 1000) }) @@ -142,6 +146,11 @@ $(function() { setSVGTransform($(this), $(this).find('svg').css('transform')); }); + // ignore mouse events on the buttons (Fill, 100%, Apply to All) + $('figure.inksimulation div').on('mousedown mouseup', function(e) { + e.stopPropagation(); + }); + /* Apply transforms to All */ $('button.svg-apply').click(function() { var transform = $(this).parent().siblings('svg').css('transform'); @@ -190,6 +199,23 @@ $(function() { } }); }); + +// $.getJSON('/realistic', function(realistic_data) { + // realistic_rendering is global + /* + $.each(realistic_data, function(name, xml) { + var image = new Image(); + console.log("doing " + name); + image.onload = function() { + console.log("setting " + name + " = " + image); + realistic_rendering[name] = image; + } + image.src = 'data:image/svg+xml,' + xml; + }) + */ +// realistic_rendering = realistic_data; +// }); + // wait until page size is set (if they've specified one) and then scale SVGs to fit setTimeout(function() { scaleAllSvg() }, 500); }); @@ -288,16 +314,86 @@ $(function() { $('.modal').hide(); }); - //Checkbox - $(':checkbox').on('change initialize', function() { + // View selection checkboxes + $(':checkbox.view').on('change initialize', function() { var field_name = $(this).attr('data-field-name'); $('.' + field_name).toggle($(this).prop('checked')); setPageNumbers(); }).on('change', function() { + var field_name = $(this).attr('data-field-name'); $.postJSON('/settings/' + field_name, {value: $(this).prop('checked')}); }); + // Realistic rendering checkboxes + $(':checkbox.realistic').on('change', function(e) { + console.log("realistic rendering checkbox"); + + var item = $(this).data('field-name'); + var figure = $(this).closest('figure'); + var svg = figure.find('svg'); + var transform = svg.css('transform'); + var checked = $(this).prop('checked'); + + console.log("" + item + " " + transform); + + function finalize(svg_content) { + svg[0].outerHTML = svg_content; + // can't use the svg variable here because setting outerHTML created a new tag + figure.find('svg').css({transform: transform}); + } + + // do this later to allow this event handler to return now, + // which will cause the checkbox to be checked or unchecked + // immediately even if SVG rendering takes awhile + setTimeout(function() { + if (checked) { + if (!(item in normal_rendering)) { + normal_rendering[item] = svg[0].outerHTML; + } + + if (!(item in realistic_cache)) { + // pre-render the realistic SVG to a raster image to spare the poor browser + var image = document.createElement('img'); + image.onload = function() { + console.log("rendering!"); + var canvas = document.createElement('canvas'); + + // maybe make DPI configurable? for now, use 600 + canvas.width = image.width / 96 * 600; + canvas.height = image.height / 96 * 600; + + var ctx = canvas.getContext('2d'); + + // rendering slows down the browser enough that we can miss sending + // pings, so tell the server side to wait for us + $.get("/printing/start") + .done(function() { + ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height); + realistic_cache[item] = '' + + '' + + ''; + finalize(realistic_cache[item]); + $.get("/printing/end"); + }); + }; + image.src = '/realistic/' + item; + } else { + finalize(realistic_cache[item]); + } + } else { + finalize(normal_rendering[item]); + } + }, 100); + + e.stopPropagation(); + return true; + }); + + $('button.svg-realistic').click(function(e){ + $(this).find('input').click(); + }); + // Logo $('#logo-picker').change(function(e) { var file = e.originalEvent.currentTarget.files[0]; diff --git a/print/resources/style.css b/print/resources/style.css index 58ec8714b..716934a86 100644 --- a/print/resources/style.css +++ b/print/resources/style.css @@ -473,6 +473,28 @@ body { border: none; background: grey; color: white; + display: inline-block; + font-size: 16px; + font-family: "Barlow", sans-serif; + padding-left: 3px; + padding-right: 3px; + margin: 0px 1px 0px 1px; + } + + input.realistic { + position: absolute; + transform: scale(0.7); + margin-left: 2px; + } + + label.realistic { + margin-left: 20px; + } + + /* prevents Chrome from sending a double event for the checkbox + and the containing + diff --git a/print/templates/print_detail.html b/print/templates/print_detail.html index 714d33a24..e73fe918b 100644 --- a/print/templates/print_detail.html +++ b/print/templates/print_detail.html @@ -22,9 +22,12 @@ + - - +
{% include 'color_swatch.html' %}
diff --git a/print/templates/print_overview.html b/print/templates/print_overview.html index efcf5b2eb..b42ab7a99 100644 --- a/print/templates/print_overview.html +++ b/print/templates/print_overview.html @@ -32,14 +32,18 @@ + - - + +
{% for color_block in color_blocks %} {% include 'color_swatch.html' %} - {% endfor %} - + {% endfor %} +
{{ _('Client Signature') }}
diff --git a/print/templates/ui.html b/print/templates/ui.html index b09dc9414..3b11f3456 100644 --- a/print/templates/ui.html +++ b/print/templates/ui.html @@ -26,10 +26,10 @@
{{ _('Print Layouts') }} -

-

-

-

+

+

+

+