Linter for inkscape extension
This commit is contained in:
1 parent
00e9ba3434
commit
247ecc3f5a
17 files changed
+1002
-249
No files matched your search
+105
-102
@@ -1,37 +1,40 @@
|
||||
# coding=utf-8
|
||||
# SPDX-License-Identifier: GPL-2.0-or-later
|
||||
# Copyright (C) 2026 Alex
|
||||
"""
|
||||
Noyau de calcul de l'extension « Dog Bandana », sans dependance a inkex.
|
||||
Computation core of the "Dog Bandana Pattern Fill" extension, without inkex.
|
||||
|
||||
Testable avec pytest seul et reutilisable hors Inkscape (scripts, schema
|
||||
des parametres).
|
||||
Testable with pytest alone and reusable outside Inkscape (scripts, parameter
|
||||
diagram).
|
||||
|
||||
Conventions :
|
||||
- un contour (`rings`) est une liste d'anneaux, chaque anneau etant une liste
|
||||
de points (x, y) fermee implicitement ; les trous suivent la regle pair-impair ;
|
||||
- une polyligne est une liste de points (x, y) ;
|
||||
- l'axe y est oriente vers le bas (repere SVG).
|
||||
Conventions:
|
||||
- an outline (`rings`) is a list of rings, each ring being a list of (x, y)
|
||||
points, implicitly closed; holes follow the even-odd rule;
|
||||
- a polyline is a list of (x, y) points;
|
||||
- the y axis points down (SVG coordinates).
|
||||
|
||||
Le motif est un labyrinthe de Turing (bandes de largeur constante qui
|
||||
serpentent, bifurquent et se terminent en bouts ronds) : `turing_pattern`
|
||||
renvoie la ligne centrale de chaque bande, a tracer avec un trait a bouts
|
||||
ronds. Seule dependance : numpy, fourni avec Inkscape (inkex en depend).
|
||||
The pattern is a Turing maze (bands of constant width that wind, branch and
|
||||
end in round tips): `turing_pattern` returns the center line of each band,
|
||||
to be drawn with a round-capped stroke. Only dependency: numpy, shipped with
|
||||
Inkscape (inkex depends on it).
|
||||
|
||||
Les traits produits passent par `laser_order` avant d'etre ecrits : ils sont
|
||||
enchaines et ordonnes pour limiter les deplacements a vide de la tete du laser.
|
||||
Generated strokes go through `laser_order` before being written: they are
|
||||
chained and ordered to limit the idle travel of the laser head.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
|
||||
def parse_color(value, default=("#b3b3b3", 1.0)):
|
||||
"""Couleur Inkscape (entier RGBA decimal ou 0x..., ou #rrggbb[aa]).
|
||||
"""Inkscape color (decimal RGBA integer or 0x..., or #rrggbb[aa]).
|
||||
|
||||
Renvoie (couleur CSS #rrggbb, opacite entre 0 et 1). Le parametre
|
||||
« color » d'Inkscape arrive sous forme d'entier RGBA ; on le decode
|
||||
nous-memes pour ne pas dependre de l'API couleur d'inkex, qui a change
|
||||
entre les versions 1.x.
|
||||
Returns (CSS color #rrggbb, opacity between 0 and 1). Inkscape's "color"
|
||||
parameter arrives as an RGBA integer; we decode it ourselves so as not to
|
||||
depend on inkex's color API, which changed across 1.x versions.
|
||||
"""
|
||||
text = str(value).strip()
|
||||
try:
|
||||
@@ -55,7 +58,7 @@ def parse_color(value, default=("#b3b3b3", 1.0)):
|
||||
|
||||
|
||||
def polylines_to_d(polylines, precision=4):
|
||||
"""Donnees `d` d'un chemin SVG : une polyligne par sous-chemin."""
|
||||
"""`d` data of an SVG path: one polyline per subpath."""
|
||||
fmt = "{:.%df},{:.%df}" % (precision, precision)
|
||||
parts = []
|
||||
for polyline in polylines:
|
||||
@@ -67,11 +70,11 @@ def polylines_to_d(polylines, precision=4):
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Ordre de gravure (decoupeuse laser)
|
||||
# Engraving order (laser cutter)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _key(point):
|
||||
"""Cle d'un point : deux extremites a 1e-6 pres sont le meme noeud."""
|
||||
"""Key of a point: two end points within 1e-6 are the same node."""
|
||||
return round(point[0], 6), round(point[1], 6)
|
||||
|
||||
|
||||
@@ -80,18 +83,18 @@ def _is_closed(line):
|
||||
|
||||
|
||||
def chain_polylines(polylines):
|
||||
"""Met bout a bout les polylignes qui se touchent par leurs extremites.
|
||||
"""Join end to end the polylines that touch at their end points.
|
||||
|
||||
Le laser parcourt alors chaque resultat d'un trait, sans lever la tete.
|
||||
Les polylignes sont les aretes d'un graphe dont les noeuds sont leurs
|
||||
extremites ; on part d'abord des noeuds de degre impair (bouts de
|
||||
branche) : un parcours qui y commence ne peut s'arreter que sur un autre
|
||||
noeud impair, ce qui limite le nombre de traits, donc de sauts a vide.
|
||||
Une polyligne deja fermee (boucle) est gardee telle quelle.
|
||||
The laser then follows each result in one stroke, without lifting.
|
||||
Polylines are the edges of a graph whose nodes are their end points;
|
||||
walks start from odd-degree nodes first (branch tips): a walk starting
|
||||
there can only stop on another odd node, which limits the number of
|
||||
strokes, hence of idle jumps. An already closed polyline (loop) is kept
|
||||
as is.
|
||||
"""
|
||||
out = []
|
||||
points = {}
|
||||
adjacency = {} # noeud -> [(numero de polyligne, voisin)]
|
||||
adjacency = {} # node -> [(polyline index, neighbour)]
|
||||
lines = [list(line) for line in polylines if len(line) >= 2]
|
||||
for index, line in enumerate(lines):
|
||||
a, b = _key(line[0]), _key(line[-1])
|
||||
@@ -126,25 +129,25 @@ def chain_polylines(polylines):
|
||||
for node in adjacency:
|
||||
if len(free_edges(node)) % 2:
|
||||
out.append(walk(node))
|
||||
for node in adjacency: # reste : circuits fermes
|
||||
for node in adjacency: # what remains: closed circuits
|
||||
while free_edges(node):
|
||||
out.append(walk(node))
|
||||
return out
|
||||
|
||||
|
||||
def order_polylines(polylines, start=(0.0, 0.0)):
|
||||
"""Ordonne les polylignes pour limiter les deplacements a vide du laser.
|
||||
"""Order the polylines to limit the idle travel of the laser.
|
||||
|
||||
Plus proche voisin : depuis la fin de la polyligne precedente (ou
|
||||
`start`), on enchaine sur l'entree libre la plus proche. Une polyligne
|
||||
ouverte peut etre parcourue dans les deux sens ; une boucle fermee peut
|
||||
commencer a n'importe lequel de ses sommets. Les entrees sont rangees
|
||||
dans une grille pour ne pas tout comparer a chaque pas.
|
||||
Nearest neighbour: from the end of the previous polyline (or `start`),
|
||||
continue with the closest free entry point. An open polyline can be
|
||||
followed in either direction; a closed loop can start at any of its
|
||||
vertices. Entry points are stored in a grid so that not everything is
|
||||
compared at each step.
|
||||
"""
|
||||
polylines = [list(line) for line in polylines if len(line) >= 2]
|
||||
if not polylines:
|
||||
return []
|
||||
entries = [] # (numero de polyligne, sommet d'entree)
|
||||
entries = [] # (polyline index, entry vertex)
|
||||
for index, line in enumerate(polylines):
|
||||
if _is_closed(line):
|
||||
entries.extend((index, k) for k in range(len(line) - 1))
|
||||
@@ -164,7 +167,7 @@ def order_polylines(polylines, start=(0.0, 0.0)):
|
||||
done = [False] * len(polylines)
|
||||
|
||||
def ring(cx, cy, r):
|
||||
"""Cellules de la grille a distance r (en cellules) de (cx, cy)."""
|
||||
"""Grid cells at distance r (in cells) from (cx, cy)."""
|
||||
if r == 0:
|
||||
yield cx, cy
|
||||
return
|
||||
@@ -182,7 +185,7 @@ def order_polylines(polylines, start=(0.0, 0.0)):
|
||||
def nearest(x, y):
|
||||
cx = int(math.floor((x - x0) / cell))
|
||||
cy = int(math.floor((y - y0) / cell))
|
||||
r = max(0, -cx, cx - nx, -cy, cy - ny) # premier anneau dans la grille
|
||||
r = max(0, -cx, cx - nx, -cy, cy - ny) # first ring inside the grid
|
||||
r_max = max(cx, nx - cx, cy, ny - cy, r)
|
||||
best, best_d = None, float("inf")
|
||||
while r <= r_max and (r - 1) * cell < best_d:
|
||||
@@ -209,7 +212,7 @@ def order_polylines(polylines, start=(0.0, 0.0)):
|
||||
pass
|
||||
elif not _is_closed(line):
|
||||
line = line[::-1]
|
||||
else: # boucle : rotation
|
||||
else: # loop: rotate it
|
||||
line = line[k:-1] + line[:k] + [line[k]]
|
||||
ordered.append(line)
|
||||
position = line[-1]
|
||||
@@ -217,16 +220,16 @@ def order_polylines(polylines, start=(0.0, 0.0)):
|
||||
|
||||
|
||||
def laser_order(polylines, start=(0.0, 0.0)):
|
||||
"""Enchaine puis ordonne les traits : a appliquer avant polylines_to_d.
|
||||
"""Chain then order the strokes: apply before polylines_to_d.
|
||||
|
||||
`start` : position de la tete (fin du trace precedent, ou origine).
|
||||
La position finale est le dernier point de la derniere polyligne.
|
||||
`start`: position of the head (end of the previous drawing, or origin).
|
||||
The final position is the last point of the last polyline.
|
||||
"""
|
||||
return order_polylines(chain_polylines(polylines), start)
|
||||
|
||||
|
||||
def travel_length(polylines, start=(0.0, 0.0)):
|
||||
"""Longueur totale des deplacements a vide (tete levee) entre polylignes."""
|
||||
"""Total length of idle moves (head off) between polylines."""
|
||||
total = 0.0
|
||||
position = start
|
||||
for line in polylines:
|
||||
@@ -236,30 +239,30 @@ def travel_length(polylines, start=(0.0, 0.0)):
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Motif de Turing (labyrinthe)
|
||||
# Turing pattern (maze)
|
||||
# --------------------------------------------------------------------------
|
||||
#
|
||||
# Regime « labyrinthe » de l'equation de Swift-Hohenberg :
|
||||
# du/dt = r.u - (1 + laplacien)^2 u - u^3
|
||||
# integree sur une grille de pixels couvrant la forme. Partant d'un bruit
|
||||
# aleatoire, le champ u s'organise en bandes de periode 2.pi (unites reduites).
|
||||
# Les bandes positives sont amincies en squelette d'un pixel, suivi en
|
||||
# polylignes, lisse puis simplifie.
|
||||
# "Labyrinth" regime of the Swift-Hohenberg equation:
|
||||
# du/dt = r.u - (1 + laplacian)^2 u - u^3
|
||||
# integrated on a pixel grid covering the shape. Starting from random noise,
|
||||
# the field u organizes into bands of period 2.pi (reduced units). Positive
|
||||
# bands are thinned to a one-pixel skeleton, traced as polylines, smoothed
|
||||
# and simplified.
|
||||
|
||||
PIXELS_PER_PERIOD = 8 # resolution du calcul
|
||||
STEPS = 60 # pas d'integration : plus, bandes plus longues
|
||||
SMOOTHING = 4 # passes de lissage des lignes centrales
|
||||
PIXELS_PER_PERIOD = 8 # computation resolution
|
||||
STEPS = 60 # integration steps: more, longer bands
|
||||
SMOOTHING = 4 # smoothing passes of the center lines
|
||||
EDGE_MODES = ("cut", "follow")
|
||||
MAX_PIXELS = 3000000 # au-dela, calcul trop long dans Inkscape
|
||||
MAX_PIXELS = 3000000 # beyond this, too slow inside Inkscape
|
||||
|
||||
|
||||
def rasterize(rings, x0, y0, step, nx, ny):
|
||||
"""Masque booleen (ny, nx) des centres de pixels interieurs (pair-impair).
|
||||
"""Boolean mask (ny, nx) of pixel centers inside the rings (even-odd).
|
||||
|
||||
Pixel (i, j) : centre en (x0 + (j + 0.5) * step, y0 + (i + 0.5) * step).
|
||||
Balayage par lignes : pour chaque ligne, abscisses des intersections avec
|
||||
les aretes, triees ; un pixel est dedans s'il a un nombre impair
|
||||
d'intersections a sa gauche.
|
||||
Pixel (i, j): center at (x0 + (j + 0.5) * step, y0 + (i + 0.5) * step).
|
||||
Scanline fill: for each row, sorted abscissas of the crossings with the
|
||||
edges; a pixel is inside if it has an odd number of crossings on its
|
||||
left.
|
||||
"""
|
||||
mask = np.zeros((ny, nx), dtype=bool)
|
||||
edges = [(ring[k], ring[(k + 1) % len(ring)]) for ring in rings
|
||||
@@ -271,7 +274,7 @@ def rasterize(rings, x0, y0, step, nx, ny):
|
||||
columns = x0 + (np.arange(nx) + 0.5) * step
|
||||
for i in range(ny):
|
||||
y = y0 + (i + 0.5) * step
|
||||
# Arete demi-ouverte : un sommet partage n'est compte qu'une fois.
|
||||
# Half-open edge: a shared vertex is counted only once.
|
||||
hit = (ay <= y) != (by <= y)
|
||||
if not hit.any():
|
||||
continue
|
||||
@@ -282,11 +285,11 @@ def rasterize(rings, x0, y0, step, nx, ny):
|
||||
|
||||
|
||||
def erode(mask, radius):
|
||||
"""Erosion du masque par un disque de `radius` pixels.
|
||||
"""Erosion of the mask by a disk of `radius` pixels.
|
||||
|
||||
Convolution par FFT : un pixel reste s'il n'y a aucun pixel exterieur
|
||||
dans le disque qui l'entoure. La convolution est periodique : la grille
|
||||
doit garder une bordure exterieure d'au moins `radius` pixels.
|
||||
FFT convolution: a pixel stays if there is no outside pixel in the disk
|
||||
around it. The convolution is periodic: the grid must keep an outer
|
||||
border of at least `radius` pixels.
|
||||
"""
|
||||
if radius <= 0:
|
||||
return mask.copy()
|
||||
@@ -301,18 +304,18 @@ def erode(mask, radius):
|
||||
|
||||
def swift_hohenberg(shape, pixels_per_period=PIXELS_PER_PERIOD, seed=1,
|
||||
steps=STEPS, outside=None, r=0.35, dt=0.5):
|
||||
"""Champ u (ny, nx) du regime labyrinthe.
|
||||
"""Field u (ny, nx) in the labyrinth regime.
|
||||
|
||||
Schema spectral semi-implicite : partie lineaire implicite (stable quel
|
||||
que soit le pas de temps), terme cubique explicite ; bords periodiques.
|
||||
`outside` (masque booleen, optionnel) : pixels ou u est force a -1 a
|
||||
chaque pas ; les bandes s'arretent alors avant ce masque et longent son
|
||||
bord, au lieu d'etre coupees net.
|
||||
Semi-implicit spectral scheme: implicit linear part (stable whatever the
|
||||
time step), explicit cubic term; periodic boundaries. `outside`
|
||||
(optional boolean mask): pixels where u is forced to -1 at each step;
|
||||
bands then stop before this mask and run along its edge, instead of
|
||||
being cut sharply.
|
||||
"""
|
||||
ny, nx = shape
|
||||
rng = np.random.default_rng(seed)
|
||||
u = 0.1 * rng.standard_normal((ny, nx))
|
||||
spacing = 2 * math.pi / pixels_per_period # pixel en unites reduites
|
||||
spacing = 2 * math.pi / pixels_per_period # pixel in reduced units
|
||||
kx = 2 * math.pi * np.fft.rfftfreq(nx, d=spacing)
|
||||
ky = 2 * math.pi * np.fft.fftfreq(ny, d=spacing)
|
||||
k2 = ky[:, None] ** 2 + kx[None, :] ** 2
|
||||
@@ -328,7 +331,7 @@ def swift_hohenberg(shape, pixels_per_period=PIXELS_PER_PERIOD, seed=1,
|
||||
|
||||
|
||||
def skeletonize(binary):
|
||||
"""Squelette d'un pixel d'epaisseur (Zhang-Suen), vectorise avec numpy."""
|
||||
"""One-pixel-wide skeleton (Zhang-Suen), vectorized with numpy."""
|
||||
img = np.pad(binary.astype(np.uint8), 1)
|
||||
while True:
|
||||
changed = False
|
||||
@@ -357,10 +360,10 @@ _NEIGHBOURS = ((-1, 0), (0, 1), (1, 0), (0, -1), (-1, -1), (-1, 1), (1, 1), (1,
|
||||
|
||||
|
||||
def _skeleton_graph(skeleton):
|
||||
"""Voisins de chaque pixel du squelette.
|
||||
"""Neighbours of each skeleton pixel.
|
||||
|
||||
Liaisons 8-connexes, sauf une diagonale doublee par deux liaisons droites
|
||||
(coin en « L ») : elle creerait de faux carrefours.
|
||||
8-connected links, except a diagonal doubled by two straight links
|
||||
("L" corner): it would create false junctions.
|
||||
"""
|
||||
pixels = set(zip(*(index.tolist() for index in np.nonzero(skeleton))))
|
||||
graph = {}
|
||||
@@ -378,15 +381,15 @@ def _skeleton_graph(skeleton):
|
||||
|
||||
|
||||
def trace_skeleton(skeleton, min_spur=0):
|
||||
"""Polylignes de pixels (ligne, colonne) qui suivent le squelette.
|
||||
"""Polylines of pixels (row, column) that follow the skeleton.
|
||||
|
||||
Chaque branche relie deux noeuds (bouts ou carrefours) ; les boucles sans
|
||||
noeud sont suivies a part ; un pixel isole donne une polyligne d'un point.
|
||||
Les ergots (branche libre de moins de `min_spur` pixels accrochee a un
|
||||
carrefour, artefacts de l'amincissement) sont supprimes.
|
||||
Each branch joins two nodes (tips or junctions); loops without a node
|
||||
are traced separately; an isolated pixel gives a one-point polyline.
|
||||
Spurs (free branch shorter than `min_spur` pixels attached to a junction,
|
||||
thinning artifacts) are removed.
|
||||
"""
|
||||
graph = _skeleton_graph(skeleton)
|
||||
seen = set() # liaisons deja parcourues
|
||||
seen = set() # links already followed
|
||||
|
||||
def follow(previous, current, line):
|
||||
seen.add((previous, current))
|
||||
@@ -410,7 +413,7 @@ def trace_skeleton(skeleton, min_spur=0):
|
||||
for nxt in graph[node]:
|
||||
if (node, nxt) not in seen:
|
||||
lines.append(follow(node, nxt, [node]))
|
||||
for p in sorted(graph): # boucles isolees
|
||||
for p in sorted(graph): # isolated loops
|
||||
links = graph[p]
|
||||
if len(links) == 2 and (p, links[0]) not in seen:
|
||||
lines.append(follow(p, links[0], [p]))
|
||||
@@ -428,9 +431,9 @@ def trace_skeleton(skeleton, min_spur=0):
|
||||
|
||||
|
||||
def smooth_polyline(points, passes=2):
|
||||
"""Lissage par moyenne glissante (1/4, 1/2, 1/4), extremites fixes.
|
||||
"""Moving-average smoothing (1/4, 1/2, 1/4), end points fixed.
|
||||
|
||||
Une boucle fermee (premier point = dernier) est lissee tout du long.
|
||||
A closed loop (first point = last point) is smoothed all along.
|
||||
"""
|
||||
if len(points) < 3:
|
||||
return [tuple(p) for p in points]
|
||||
@@ -449,7 +452,7 @@ def smooth_polyline(points, passes=2):
|
||||
|
||||
|
||||
def simplify_polyline(points, tolerance):
|
||||
"""Ramer-Douglas-Peucker : ne garde que les sommets utiles a `tolerance` pres."""
|
||||
"""Ramer-Douglas-Peucker: keep only the vertices needed within `tolerance`."""
|
||||
if len(points) < 3:
|
||||
return [tuple(p) for p in points]
|
||||
pts = np.asarray(points, dtype=float)
|
||||
@@ -475,10 +478,10 @@ def simplify_polyline(points, tolerance):
|
||||
|
||||
|
||||
def _grid(rings, period, pixels_per_period):
|
||||
"""Origine, pas et taille (x0, y0, step, nx, ny) de la grille de calcul.
|
||||
"""Origin, step and size (x0, y0, step, nx, ny) of the computation grid.
|
||||
|
||||
Bordure exterieure de deux periodes : le champ y vaut -1 et l'erosion
|
||||
par FFT (periodique) ne deborde pas d'un cote sur l'autre.
|
||||
Outer border of two periods: the field is -1 there and the (periodic)
|
||||
FFT erosion does not leak from one side to the other.
|
||||
"""
|
||||
xs = [x for ring in rings for x, _y in ring]
|
||||
ys = [y for ring in rings for _x, y in ring]
|
||||
@@ -490,7 +493,7 @@ def _grid(rings, period, pixels_per_period):
|
||||
|
||||
|
||||
def grid_pixels(rings, period, pixels_per_period=PIXELS_PER_PERIOD):
|
||||
"""Nombre de pixels de la grille de calcul (0 si rien a calculer)."""
|
||||
"""Number of pixels of the computation grid (0 if nothing to compute)."""
|
||||
if period <= 0 or not any(rings):
|
||||
return 0
|
||||
_x0, _y0, _step, nx, ny = _grid(rings, period, pixels_per_period)
|
||||
@@ -499,19 +502,19 @@ def grid_pixels(rings, period, pixels_per_period=PIXELS_PER_PERIOD):
|
||||
|
||||
def turing_pattern(rings, period, line_width, margin=0.0, seed=1, edge="cut",
|
||||
pixels_per_period=PIXELS_PER_PERIOD, steps=STEPS):
|
||||
"""Lignes centrales du labyrinthe de Turing qui remplit `rings`.
|
||||
"""Center lines of the Turing maze that fills `rings`.
|
||||
|
||||
- period : distance entre les lignes centrales de deux bandes voisines ;
|
||||
- line_width : epaisseur du trait (bouts ronds compris) : le trait entier
|
||||
reste dans la forme ;
|
||||
- margin : espace libre entre le bord de la forme et le trait ;
|
||||
- seed : graine du tirage aleatoire (autre nombre, autre motif) ;
|
||||
- edge : "cut", le motif est calcule sans tenir compte de la forme puis
|
||||
coupe a son bord (comme un tissu decoupe) ; "follow", les bandes
|
||||
s'arretent avant le bord et le longent.
|
||||
- period: distance between the center lines of two neighbouring bands;
|
||||
- line_width: stroke width (round tips included): the whole stroke stays
|
||||
inside the shape;
|
||||
- margin: free space between the shape edge and the stroke;
|
||||
- seed: random seed (another number, another pattern);
|
||||
- edge: "cut", the pattern is computed regardless of the shape then cut
|
||||
at its edge (like cut fabric); "follow", bands stop before the edge
|
||||
and run along it.
|
||||
|
||||
Renvoie des polylignes en coordonnees du document ; un point isole est
|
||||
une polyligne de deux points confondus (un trait a bouts ronds le dessine).
|
||||
Returns polylines in document coordinates; an isolated dot is a polyline
|
||||
of two identical points (a round-capped stroke draws it).
|
||||
"""
|
||||
if period <= 0 or not any(rings):
|
||||
return []
|
||||
|
||||
Reference in new issue
Block a user