#!/usr/bin/env python3 # coding=utf-8 # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2026 Alex """ Inkscape extension: fills the selected shapes with a Turing maze ("Dog Bandana" pattern), drawn as round-capped center lines. The pattern is computed with the Swift-Hohenberg equation on a grid covering the shape, then reduced to the center line of each band: one stroke per "noodle", ready for line engraving on a laser cutter. The logic lives in `dog_bandana_core`, which does not depend on inkex. """ import builtins import ctypes import locale import os import sys import inkex from inkex.bezier import cspsubdiv from inkex.localization import localize from inkex.units import convert_unit # The extension lives in its own subfolder of Inkscape's extensions, which is # not necessarily in sys.path: add it so that dog_bandana_core can be found. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # pylint: disable-next=wrong-import-position from dog_bandana_core import (MAX_PIXELS, grid_pixels, laser_order, # noqa: E402 parse_color, polylines_to_d, turing_pattern) def use_system_language(): """Set LANGUAGE to the system language if nothing sets it already. On Windows, Inkscape set to "system language" passes no language variable to the script: gettext would fall back to English while the dialog, translated by Inkscape itself, is in the user's language. """ if any(os.environ.get(name) for name in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")): return try: language = locale.windows_locale.get( ctypes.windll.kernel32.GetUserDefaultUILanguage()) except Exception: # pylint: disable=broad-except return # outside Windows, LANG is always set if language: os.environ["LANGUAGE"] = language # Installs _() in the builtins: "dogbandana" catalog of the interface # language (Inkscape passes domain and folder through the environment), # original English texts otherwise. use_system_language() localize() # Explicit module-level name for the function localize() installed, so that # linters do not report _ as undefined. _ = builtins.__dict__["_"] # Elements that delimit an area to fill. SHAPES = (inkex.PathElement, inkex.Rectangle, inkex.Circle, inkex.Ellipse, inkex.Polygon) def uu_per_mm(svg): """User units per millimeter, as Inkscape displays them. svg.unittouu() guesses the document unit by rounding to the nearest known unit: it is wrong as soon as the scale is not standard (resized page). We take the actual page / viewBox ratio; Inkscape applies a uniform scale (preserveAspectRatio "meet"), i.e. the smaller of the two. """ try: vb_w, vb_h = svg.viewbox_width, svg.viewbox_height page_w = svg.to_dimensional(svg.viewport_width, "mm") page_h = svg.to_dimensional(svg.viewport_height, "mm") except AttributeError: # inkex older than 1.2 return svg.unittouu("1mm") if not (vb_w and vb_h and page_w and page_h): return svg.unittouu("1mm") return 1 / min(page_w / vb_w, page_h / vb_h) def length_to_uu(svg, value, unit="mm"): """Real length (value + unit) -> document user units.""" return convert_unit("{}{}".format(value, unit), "mm") * uu_per_mm(svg) def element_rings(elem, flatness): """Outline of the element in absolute coordinates: list of rings. Curves are flattened into polylines (maximum deviation `flatness`). """ path = elem.path.transform(elem.composed_transform()) csp = path.to_superpath() cspsubdiv(csp, flatness) rings = [] for sub in csp: ring = [(node[1][0], node[1][1]) for node in sub] if len(ring) > 1 and ring[0] == ring[-1]: ring.pop() if len(ring) >= 3: rings.append(ring) return rings class DogBandana(inkex.EffectExtension): """Fills each selected shape with a Turing maze.""" def __init__(self): super().__init__() # Position of the laser head: each drawing starts where the previous # one stopped (see path_element). self.head = (0.0, 0.0) def add_arguments(self, pars): # One argument per of the .inx, same names and same defaults. pars.add_argument("--tab", default="pattern") pars.add_argument("--period", type=float, default=4.0) pars.add_argument("--line_width", type=float, default=2.0) pars.add_argument("--margin", type=float, default=0.0) pars.add_argument("--unit", default="mm") pars.add_argument("--iterations", type=int, default=60) pars.add_argument("--seed", type=int, default=1) pars.add_argument("--edge", default="cut") pars.add_argument("--stroke_color", default="255") pars.add_argument("--keep_original", type=inkex.Boolean, default=True) def effect(self): opt = self.options shapes = [] for elem in self.svg.selection.values(): if isinstance(elem, SHAPES): shapes.append(elem) elif isinstance(elem, inkex.Group): shapes.extend(e for e in elem.descendants() if isinstance(e, SHAPES)) if not shapes: inkex.errormsg(_("Select at least one closed shape (path, rectangle, " "circle, ellipse, polygon) or a group containing some.")) return period = length_to_uu(self.svg, opt.period, opt.unit) width = length_to_uu(self.svg, opt.line_width, opt.unit) margin = length_to_uu(self.svg, opt.margin, opt.unit) if period <= 0 or width <= 0: inkex.errormsg(_("The period and the line width must be strictly positive.")) return if width >= period: inkex.errormsg(_("The line width must be smaller than the period, " "otherwise neighbouring lines merge. Reduce the line " "width or increase the period.")) return color, opacity = parse_color(opt.stroke_color, ("#000000", 1.0)) style = inkex.Style({ "fill": "none", "stroke": color, "stroke-opacity": str(opacity), "stroke-width": str(width), "stroke-linecap": "round", "stroke-linejoin": "round", }) self.head = (0.0, 0.0) empty = 0 for elem in shapes: rings = element_rings(elem, period / 50) if grid_pixels(rings, period) > MAX_PIXELS: inkex.errormsg(_("The shape is too large for this period: the " "computation would take too long. Increase the " "period or split the shape.")) return if not self.process(elem, rings, period, width, margin, style): empty += 1 if empty: inkex.errormsg(_("{} shape(s) too narrow for the pattern: reduce the " "line width, the period or the margin.").format(empty)) def path_element(self, polylines, style): """SVG path of the strokes, in optimized engraving order. Touching strokes are chained, then ordered as close as possible to the head position: less idle travel for the laser. Every generated stroke goes through here. """ polylines = laser_order(polylines, self.head) if polylines: self.head = polylines[-1][-1] node = inkex.PathElement() node.path = polylines_to_d(polylines, precision=3) node.style = style return node def process(self, elem, rings, period, width, margin, style): """Fill one element; return False if the shape is too narrow.""" opt = self.options polylines = turing_pattern(rings, period, width, margin, seed=opt.seed, edge=opt.edge, steps=opt.iterations) if not polylines: return False parent = elem.getparent() group = inkex.Group() group.label = _("Dog Bandana pattern") if parent is not None: # The result is computed in absolute document coordinates: cancel # the transform inherited from the host parent. parent_transform = parent.composed_transform() if parent_transform != inkex.Transform(): group.transform = -parent_transform parent.insert(parent.index(elem) + 1, group) else: self.svg.add(group) group.add(self.path_element(polylines, style)) if not opt.keep_original: elem.delete() return True if __name__ == "__main__": DogBandana().run()