Initiale version
This commit is contained in:
commit
00e9ba3434
19 files changed
+2586
No files matched your search
+15
@@ -0,0 +1,15 @@
|
||||
# Cache Python et outils
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
|
||||
# Archives de distribution
|
||||
*.zip
|
||||
|
||||
# SVG intermediaires du schema (regeneres par docs/schema_parametres.py)
|
||||
docs/*.svg
|
||||
|
||||
# Page de presentation : hors depot (publiee sur le NAS par site/deploy.ps1 ;
|
||||
# sa configuration contient hote, compte et chemin de cle SSH)
|
||||
site/
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 208 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 362 KiB |
@@ -0,0 +1,387 @@
|
||||
#!/usr/bin/env python3
|
||||
# coding=utf-8
|
||||
"""
|
||||
Genere le schema explicatif des parametres de l'extension.
|
||||
|
||||
python docs/schema_parametres.py # les deux versions
|
||||
python docs/schema_parametres.py fr # docs/parametres.svg + .png (README)
|
||||
python docs/schema_parametres.py en # docs/parameters_en.svg
|
||||
# + images/parameters_en.png (onglet
|
||||
# « Help » de la boite de dialogue)
|
||||
|
||||
Les formes sont calculees par dog_bandana_core (memes fonctions que l'extension),
|
||||
le schema reste donc fidele au resultat reel. L'export PNG passe par
|
||||
inkscape.com, qui attend la fin de l'export (contrairement au raccourci
|
||||
Chocolatey « inkscape »).
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import dog_bandana_core # noqa: E402
|
||||
|
||||
W, H = 1400, 1280 # 4 panneaux de 700 x 640
|
||||
|
||||
INK = "#343a40" # element principal
|
||||
GHOST = "#dde1e5" # elements secondaires / voisins
|
||||
DIM = "#d9480f" # cotes
|
||||
DIM2 = "#1971c2" # cotes secondaires
|
||||
EDGE = "#212529" # contour des formes
|
||||
FONT = "font-family:Arial,Helvetica,sans-serif"
|
||||
|
||||
INKSCAPE = [r"C:\Program Files\Inkscape\bin\inkscape.com", "/usr/bin/inkscape",
|
||||
"/Applications/Inkscape.app/Contents/MacOS/inkscape"]
|
||||
|
||||
# Version par langue : textes, fichiers produits, largeur du PNG et agrandissement
|
||||
# des textes (la version anglaise est affichee reduite dans la boite de dialogue :
|
||||
# 900 px de large, textes x 1.25 pour rester lisibles).
|
||||
VERSIONS = {
|
||||
"fr": {
|
||||
"svg": os.path.join(HERE, "parametres.svg"),
|
||||
"png": os.path.join(HERE, "parametres.png"),
|
||||
"png_width": 1400,
|
||||
"font_scale": 1.0,
|
||||
"text": {
|
||||
"title1": "Période et épaisseur du trait",
|
||||
"period": "Période",
|
||||
"width": "Épaisseur",
|
||||
"note1": ["Période : d'axe en axe de deux lignes voisines.",
|
||||
"Épaisseur : celle du trait, à bouts ronds ; la moitié",
|
||||
"de la période donne autant de noir que de blanc."],
|
||||
"title2": "Itérations",
|
||||
"default": "{} (défaut)",
|
||||
"iterations": "plus d'itérations",
|
||||
"note2": ["Peu d'itérations : points et lignes courtes ; beaucoup :",
|
||||
"longues lignes régulières. La graine aléatoire change",
|
||||
"le dessin en gardant le même aspect."],
|
||||
"title3": "Au bord de la forme",
|
||||
"cut": "Couper les lignes",
|
||||
"follow": "Longer le bord",
|
||||
"note3": ["Couper : le motif est découpé comme un tissu.",
|
||||
"Longer : les lignes s'arrêtent avant le bord et le suivent."],
|
||||
"title4": "Marge",
|
||||
"margin": "Marge",
|
||||
"note4": ["Espace libre entre le bord de la forme et les traits",
|
||||
"(bouts ronds compris). À 0, les traits touchent le bord."],
|
||||
},
|
||||
},
|
||||
"en": {
|
||||
"svg": os.path.join(HERE, "parameters_en.svg"),
|
||||
"png": os.path.join(ROOT, "images", "parameters_en.png"),
|
||||
"png_width": 900,
|
||||
"font_scale": 1.25,
|
||||
"text": {
|
||||
"title1": "Period and line width",
|
||||
"period": "Period",
|
||||
"width": "Width",
|
||||
"note1": ["Period: center to center of two neighbouring lines.",
|
||||
"Width: round-capped stroke; half the period",
|
||||
"gives as much black as white."],
|
||||
"title2": "Iterations",
|
||||
"default": "{} (default)",
|
||||
"iterations": "more iterations",
|
||||
"note2": ["Few iterations: dots and short lines; many:",
|
||||
"long regular lines. The random seed changes",
|
||||
"the drawing, not its look."],
|
||||
"title3": "At the shape edge",
|
||||
"cut": "Cut the lines",
|
||||
"follow": "Follow the edge",
|
||||
"note3": ["Cut: the pattern is cut like fabric.",
|
||||
"Follow: lines stop before the edge, run along it."],
|
||||
"title4": "Margin",
|
||||
"margin": "Margin",
|
||||
"note4": ["Free space between the shape edge and the",
|
||||
"strokes (round tips included). 0: strokes touch it."],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
def _unit(angle):
|
||||
"""Vecteur unitaire, angle en degres, sens anti-horaire a l'ecran (y vers le bas)."""
|
||||
a = math.radians(angle)
|
||||
return math.cos(a), -math.sin(a)
|
||||
|
||||
|
||||
out = []
|
||||
T = {}
|
||||
FS = 1.0
|
||||
|
||||
|
||||
def fmt(v):
|
||||
return "{:.2f}".format(v).rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def pts(polyline):
|
||||
return " ".join("{},{}".format(fmt(x), fmt(y)) for x, y in polyline)
|
||||
|
||||
|
||||
def polyline(points, color, width, extra=""):
|
||||
out.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="{}" '
|
||||
'stroke-linejoin="miter" {}/>'.format(pts(points), color, fmt(width), extra))
|
||||
|
||||
|
||||
def motif(polylines, color, width):
|
||||
for pl in polylines:
|
||||
polyline(pl, color, width)
|
||||
|
||||
|
||||
def text(x, y, s, size=17, color=INK, anchor="start", weight="normal", halo=True):
|
||||
style = "{};font-size:{}px;font-weight:{};fill:{}".format(
|
||||
FONT, fmt(size * FS), weight, color)
|
||||
if halo:
|
||||
style += ";paint-order:stroke;stroke:#ffffff;stroke-width:5px;stroke-linejoin:round"
|
||||
out.append('<text x="{}" y="{}" text-anchor="{}" style="{}">{}</text>'.format(
|
||||
fmt(x), fmt(y), anchor, style, s))
|
||||
|
||||
|
||||
def note(x, y, lines):
|
||||
"""Legende de bas de panneau, derniere ligne sur la ligne de base `y`."""
|
||||
step = 22 * FS
|
||||
for k, line in enumerate(lines):
|
||||
text(x, y - (len(lines) - 1 - k) * step, line, size=16, halo=False)
|
||||
|
||||
|
||||
def arrow_head(tip, direction, color, size=9):
|
||||
ux, uy = direction
|
||||
nx, ny = -uy, ux
|
||||
base = (tip[0] - size * ux, tip[1] - size * uy)
|
||||
out.append('<polygon points="{}" fill="{}"/>'.format(pts([
|
||||
tip, (base[0] + 0.45 * size * nx, base[1] + 0.45 * size * ny),
|
||||
(base[0] - 0.45 * size * nx, base[1] - 0.45 * size * ny)]), color))
|
||||
|
||||
|
||||
def dimension(p, q, offset, label, color=DIM, label_pos=0.5, label_shift=18, size=17):
|
||||
"""Cote entre p et q, decalee de `offset` perpendiculairement."""
|
||||
dx, dy = q[0] - p[0], q[1] - p[1]
|
||||
length = math.hypot(dx, dy)
|
||||
ux, uy = dx / length, dy / length
|
||||
nx, ny = -uy, ux
|
||||
a = (p[0] + offset * nx, p[1] + offset * ny)
|
||||
b = (q[0] + offset * nx, q[1] + offset * ny)
|
||||
sign = 1 if offset >= 0 else -1
|
||||
for base, end in ((p, a), (q, b)):
|
||||
polyline([(base[0] + sign * 4 * nx, base[1] + sign * 4 * ny),
|
||||
(end[0] + sign * 6 * nx, end[1] + sign * 6 * ny)], color, 1,
|
||||
'stroke-dasharray="3,3"')
|
||||
polyline([a, b], color, 1.6)
|
||||
arrow_head(a, (-ux, -uy), color)
|
||||
arrow_head(b, (ux, uy), color)
|
||||
lx = a[0] + label_pos * (b[0] - a[0]) + sign * label_shift * FS * nx
|
||||
ly = a[1] + label_pos * (b[1] - a[1]) + sign * label_shift * FS * ny + 6 * FS
|
||||
text(lx, ly, label, size=size, color=color, anchor="middle", weight="bold")
|
||||
|
||||
|
||||
def arc(center, radius, a0, a1, color, label=None, label_radius=None, size=16):
|
||||
"""Arc de a0 a a1 degres (sens anti-horaire a l'ecran), fleche au bout."""
|
||||
steps = 40
|
||||
points = []
|
||||
for k in range(steps + 1):
|
||||
ux, uy = _unit(a0 + (a1 - a0) * k / steps)
|
||||
points.append((center[0] + radius * ux, center[1] + radius * uy))
|
||||
polyline(points[:-2], color, 1.6)
|
||||
last, before = points[-1], points[-3]
|
||||
d = math.hypot(last[0] - before[0], last[1] - before[1])
|
||||
arrow_head(last, ((last[0] - before[0]) / d, (last[1] - before[1]) / d), color, 8)
|
||||
if label:
|
||||
ux, uy = _unit((a0 + a1) / 2)
|
||||
r = label_radius or radius + 24
|
||||
text(center[0] + r * ux, center[1] + r * uy + 6 * FS, label, size=size,
|
||||
color=color, anchor="middle", weight="bold")
|
||||
|
||||
|
||||
def circle_ring(cx, cy, r, n=180):
|
||||
return [(cx + r * math.cos(2 * math.pi * k / n), cy + r * math.sin(2 * math.pi * k / n))
|
||||
for k in range(n)]
|
||||
|
||||
|
||||
def panel_title(x, y, number, title):
|
||||
text(x, y, "{} {}".format(number, title), size=22, weight="bold", halo=False)
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Panneaux : un par parametre (ou groupe de parametres), numerotes 1 a 4.
|
||||
# Motifs calcules par dog_bandana_core.turing_pattern, comme dans l'extension.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def strokes(polylines, color, width):
|
||||
"""Traits a bouts ronds, comme ceux produits par l'extension."""
|
||||
for pl in polylines:
|
||||
out.append('<polyline points="{}" fill="none" stroke="{}" stroke-width="{}" '
|
||||
'stroke-linecap="round" stroke-linejoin="round"/>'.format(
|
||||
pts(pl), color, fmt(width)))
|
||||
|
||||
|
||||
def outline(rings, color=EDGE, width=2, extra=""):
|
||||
d = " ".join("M " + " L ".join("{},{}".format(fmt(x), fmt(y)) for x, y in ring) + " Z"
|
||||
for ring in rings)
|
||||
out.append('<path d="{}" fill="none" stroke="{}" stroke-width="{}" {}/>'.format(
|
||||
d, color, fmt(width), extra))
|
||||
|
||||
|
||||
def rect_ring(x0, y0, x1, y1):
|
||||
return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
|
||||
|
||||
|
||||
def crossings(polylines, x):
|
||||
"""Intersections des polylignes avec la verticale x : (y, pente, numero)."""
|
||||
found = []
|
||||
for index, pl in enumerate(polylines):
|
||||
for (ax, ay), (bx, by) in zip(pl, pl[1:]):
|
||||
if (ax <= x) != (bx <= x):
|
||||
t = (x - ax) / (bx - ax)
|
||||
found.append((ay + t * (by - ay), abs((by - ay) / (bx - ax)), index))
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def panel_1():
|
||||
"""Periode et epaisseur : cotes sur deux lignes voisines bien paralleles."""
|
||||
period, width = 64, 28
|
||||
region = rect_ring(60, 90, 640, 530)
|
||||
|
||||
def near(cuts, index, y):
|
||||
return any(i == index and abs(cy - y) < 6 for cy, _s, i in cuts)
|
||||
|
||||
# Cherche deux lignes voisines presque horizontales sur une bonne longueur
|
||||
# (verticales x - 70, x, x + 70), espacees d'environ une periode : les
|
||||
# cotes tiennent dans l'espace blanc entre elles.
|
||||
best = None
|
||||
for seed in range(1, 9):
|
||||
lines = dog_bandana_core.turing_pattern([region], period, width, seed=seed,
|
||||
steps=150)
|
||||
for x in range(250, 480, 6):
|
||||
cuts = crossings(lines, x)
|
||||
left, right = crossings(lines, x - 70), crossings(lines, x + 70)
|
||||
for (y1, s1, i1), (y2, s2, i2) in zip(cuts, cuts[1:]):
|
||||
if not (170 < y1 < 400 and i1 != i2):
|
||||
continue
|
||||
if not all(near(c, i, y) for c in (left, right)
|
||||
for i, y in ((i1, y1), (i2, y2))):
|
||||
continue
|
||||
score = abs(y2 - y1 - period) + 30 * (s1 + s2) + abs(x - 360) / 20
|
||||
if best is None or score < best[0]:
|
||||
best = (score, lines, x, y1, y2, i1, i2)
|
||||
_score, lines, x, y1, y2, i1, i2 = best
|
||||
panel_title(30, 50, 1, T["title1"])
|
||||
strokes([pl for k, pl in enumerate(lines) if k not in (i1, i2)], GHOST, width)
|
||||
strokes([lines[i1], lines[i2]], INK, width)
|
||||
outline([region], EDGE, 2)
|
||||
# Periode : d'axe en axe ; epaisseur : bord a bord d'une meme ligne.
|
||||
for y in (y1, y2):
|
||||
polyline([(x - 25, y), (x + 25, y)], DIM, 1.4, 'stroke-dasharray="4,3"')
|
||||
dimension((x, y1), (x, y2), 0, "")
|
||||
text(x + 12, (y1 + y2) / 2 + 6, T["period"], color=DIM, weight="bold")
|
||||
# Epaisseur sur la ligne du bas, legende dessous (zone claire).
|
||||
xw = x - 70
|
||||
dimension((xw, y2 - width / 2), (xw, y2 + width / 2), 0, "", color=DIM2)
|
||||
text(xw, y2 + width / 2 + 28, T["width"], color=DIM2, anchor="middle",
|
||||
weight="bold")
|
||||
note(30, 610, T["note1"])
|
||||
|
||||
|
||||
def panel_2():
|
||||
"""Iterations : meme graine, trois durees d'evolution."""
|
||||
ox = 700
|
||||
panel_title(ox + 30, 50, 2, T["title2"])
|
||||
size, gap = 190, 25
|
||||
for k, steps in enumerate((20, 60, 300)):
|
||||
x0 = ox + 30 + k * (size + gap)
|
||||
region = rect_ring(x0, 130, x0 + size, 130 + size)
|
||||
lines = dog_bandana_core.turing_pattern([region], 20, 9, seed=5, steps=steps)
|
||||
strokes(lines, INK, 9)
|
||||
outline([region], EDGE, 2)
|
||||
label = T["default"].format(steps) if steps == 60 else str(steps)
|
||||
text(x0 + size / 2, 130 + size + 40, label, size=20, color=DIM,
|
||||
anchor="middle", weight="bold")
|
||||
arrow_y = 420
|
||||
polyline([(ox + 60, arrow_y), (ox + 630, arrow_y)], DIM2, 1.6)
|
||||
arrow_head((ox + 640, arrow_y), (1, 0), DIM2)
|
||||
text(ox + 345, arrow_y + 30, T["iterations"], color=DIM2, anchor="middle",
|
||||
weight="bold")
|
||||
note(ox + 30, 610, T["note2"])
|
||||
|
||||
|
||||
def panel_3():
|
||||
"""Bord de la forme : motif coupe (tissu decoupe) ou qui longe le bord."""
|
||||
oy = 640
|
||||
panel_title(30, oy + 50, 3, T["title3"])
|
||||
for k, edge in enumerate(("cut", "follow")):
|
||||
cx, cy, r = 190 + k * 320, oy + 270, 140
|
||||
ring = circle_ring(cx, cy, r)
|
||||
lines = dog_bandana_core.turing_pattern([ring], 24, 11, seed=2, edge=edge)
|
||||
strokes(lines, INK, 11)
|
||||
outline([ring], EDGE, 2)
|
||||
text(cx, cy + r + 40, T[edge], size=19, color=DIM, anchor="middle",
|
||||
weight="bold")
|
||||
note(30, oy + 610, T["note3"])
|
||||
|
||||
|
||||
def panel_4():
|
||||
"""Marge : espace libre entre le bord et les traits."""
|
||||
ox, oy = 700, 640
|
||||
panel_title(ox + 30, oy + 50, 4, T["title4"])
|
||||
margin, period, width = 40, 30, 14
|
||||
x0, y0, x1, y1 = ox + 70, oy + 90, ox + 630, oy + 470
|
||||
lines = dog_bandana_core.turing_pattern([rect_ring(x0, y0, x1, y1)], period, width,
|
||||
margin=margin, seed=6)
|
||||
strokes(lines, INK, width)
|
||||
outline([rect_ring(x0, y0, x1, y1)], EDGE, 2.5)
|
||||
outline([rect_ring(x0 + margin, y0 + margin, x1 - margin, y1 - margin)], DIM2, 1.5,
|
||||
'stroke-dasharray="6,4"')
|
||||
dimension((x0, y1 + 22), (x0 + margin, y1 + 22), 0, "", color=DIM)
|
||||
text(x0 + margin + 12, y1 + 29, T["margin"], color=DIM, weight="bold")
|
||||
note(ox + 30, oy + 610, T["note4"])
|
||||
|
||||
|
||||
def export_png(svg_path, png_path, width):
|
||||
exe = next((path for path in INKSCAPE if os.path.exists(path)), None)
|
||||
if exe is None:
|
||||
print("Inkscape introuvable : exporter {} a la main".format(svg_path))
|
||||
return
|
||||
os.makedirs(os.path.dirname(png_path), exist_ok=True)
|
||||
subprocess.run([exe, svg_path, "--export-type=png",
|
||||
"--export-width={}".format(width),
|
||||
"--export-filename={}".format(png_path)],
|
||||
check=True, stderr=subprocess.DEVNULL)
|
||||
print(png_path)
|
||||
|
||||
|
||||
def build(language):
|
||||
global FS
|
||||
version = VERSIONS[language]
|
||||
out.clear()
|
||||
T.clear()
|
||||
T.update(version["text"])
|
||||
FS = version["font_scale"]
|
||||
|
||||
out.append('<rect width="{}" height="{}" fill="#ffffff"/>'.format(W, H))
|
||||
for x1, y1, x2, y2 in ((700, 20, 700, H - 20), (20, 640, W - 20, 640)):
|
||||
out.append('<line x1="{}" y1="{}" x2="{}" y2="{}" stroke="#dee2e6" '
|
||||
'stroke-width="1.5"/>'.format(x1, y1, x2, y2))
|
||||
panel_1()
|
||||
panel_2()
|
||||
panel_3()
|
||||
panel_4()
|
||||
svg = ('<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}" '
|
||||
'viewBox="0 0 {0} {1}">\n{2}\n</svg>\n').format(W, H, "\n".join(out))
|
||||
with open(version["svg"], "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(svg)
|
||||
print(version["svg"])
|
||||
export_png(version["svg"], version["png"], version["png_width"])
|
||||
|
||||
|
||||
def main(argv):
|
||||
languages = argv or sorted(VERSIONS)
|
||||
for language in languages:
|
||||
build(language)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,203 @@
|
||||
# Dog Bandana — extension Inkscape
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img src="docs/apercu.png" alt="Formes de test (rectangle, cercle, forme libre, rectangle troué, ellipse) remplies d'un labyrinthe de Turing : lignes noires sinueuses à bouts ronds" width="420">
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
Extension Inkscape 1.x qui remplit les formes sélectionnées d'un **labyrinthe de
|
||||
Turing**, le motif « vermicelles » du dossier `docs/` : des lignes sinueuses
|
||||
d'épaisseur constante, qui bifurquent, se referment parfois en boucle et se
|
||||
terminent en bouts ronds.
|
||||
|
||||
Le motif est calculé (équation de Swift-Hohenberg, régime labyrinthe) sur une
|
||||
grille qui couvre la forme, puis réduit à la **ligne centrale** de chaque bande :
|
||||
un seul trait à bouts ronds par vermicelle, prêt pour la gravure laser en mode
|
||||
ligne, dans un ordre qui limite les déplacements à vide de la tête.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Sommaire
|
||||
|
||||
- [Fonctionnalités](#fonctionnalités)
|
||||
- [Installation](#installation)
|
||||
- [Utilisation](#utilisation)
|
||||
- [Paramètres](#paramètres)
|
||||
- [Structure du projet](#structure-du-projet)
|
||||
- [Développement](#développement)
|
||||
|
||||
## Fonctionnalités
|
||||
|
||||
- Remplit chemins, rectangles, cercles, ellipses et polygones, y compris dans des
|
||||
groupes (transformations comprises) ; les trous sont respectés (règle
|
||||
pair-impair). Les autres éléments (texte, images…) sont ignorés.
|
||||
- Lignes centrales seulement : un `<path>` par forme, `stroke-linecap:round`,
|
||||
épaisseur du trait = largeur des vermicelles ; le trait entier (bouts ronds
|
||||
compris) reste dans la forme, à la marge près.
|
||||
- Deux comportements au bord : lignes **coupées** comme un tissu découpé (par
|
||||
défaut), ou lignes qui **longent** le bord.
|
||||
- Aspect réglable : peu d'itérations donnent points et lignes courtes (proche de
|
||||
l'image de référence), beaucoup de longues lignes régulières ; la graine
|
||||
aléatoire change le dessin en gardant l'aspect. Même graine, même résultat.
|
||||
- Ordre de gravure optimisé pour la découpeuse laser : les traits qui se
|
||||
touchent sont enchaînés, puis ordonnés au plus proche voisin. Sur un rectangle
|
||||
de 150 × 100 mm (période 4 mm), 230 traits deviennent 131 et les trajets à vide
|
||||
passent de 9 451 mm à 1 090 mm (÷ 8,7) ; sur 300 × 200 mm, de 71 690 mm à
|
||||
4 179 mm (÷ 17). Désactiver la réoptimisation du logiciel du laser (LightBurn…)
|
||||
pour garder cet ordre.
|
||||
- Temps de calcul : environ 1 s pour 150 × 100 mm, 4 s pour 300 × 200 mm
|
||||
(période 4 mm). Au-delà de 3 millions de pixels de calcul, l'extension demande
|
||||
d'augmenter la période ou de découper la forme.
|
||||
- Interface traduite en français et en anglais, selon la langue d'Inkscape
|
||||
(anglais pour toute autre langue).
|
||||
- Script de déploiement Windows (`deploy.ps1`).
|
||||
|
||||
## Installation
|
||||
|
||||
Aucune dépendance externe : l'extension utilise `inkex` et `numpy`, fournis avec
|
||||
Inkscape.
|
||||
|
||||
### Windows (script)
|
||||
|
||||
Inkscape fermé, depuis le dossier du projet :
|
||||
|
||||
```powershell
|
||||
.\deploy.ps1 # installe dans %APPDATA%\inkscape\extensions\dogBandana
|
||||
.\deploy.ps1 -Uninstall # désinstalle
|
||||
.\deploy.ps1 -Force # installe même si Inkscape est ouvert (redémarrage requis)
|
||||
```
|
||||
|
||||
### Manuelle
|
||||
|
||||
Copier dans un sous-dossier du répertoire des extensions utilisateur :
|
||||
|
||||
- `dog_bandana.inx`, `dog_bandana.py`, `dog_bandana_core.py` ;
|
||||
- `images/parameters_en.png` ;
|
||||
- `locale/` (traductions compilées).
|
||||
|
||||
| Système | Dossier des extensions |
|
||||
| ------- | ----------------------------------------------- |
|
||||
| Windows | `%APPDATA%\inkscape\extensions` |
|
||||
| Linux | `~/.config/inkscape/extensions` |
|
||||
| macOS | `~/Library/Application Support/org.inkscape.Inkscape/config/inkscape/extensions` |
|
||||
|
||||
Redémarrer Inkscape.
|
||||
|
||||
## Utilisation
|
||||
|
||||
1. Sélectionner une ou plusieurs formes fermées (ou des groupes).
|
||||
2. Menu **Extensions › AlexDesign › Remplissage par motif Dog Bandana** (*Dog Bandana Pattern Fill* en anglais).
|
||||
3. Régler période, épaisseur, marge, itérations et bord dans l'onglet **Motif**,
|
||||
couleur et conservation de la forme dans **Style** ; l'onglet **Aide** reprend
|
||||
le schéma ci-dessous.
|
||||
4. Appliquer : le motif est placé dans un groupe « Motif Dog Bandana » juste
|
||||
au-dessus de chaque forme.
|
||||
|
||||
**Conseils**
|
||||
|
||||
| Symptôme | Réglage |
|
||||
| ----------------------------------------- | ----------------------------------------------------------- |
|
||||
| Lignes qui se touchent | Réduire l'épaisseur du trait (≈ moitié de la période) |
|
||||
| Trop de points et de petits bouts | Augmenter les itérations (100 à 300) |
|
||||
| Motif trop régulier, peu « organique » | Réduire les itérations (20 à 40) |
|
||||
| Le dessin ne plaît pas | Changer la graine aléatoire |
|
||||
| Anneaux concentriques le long du bord | Choisir « Couper les lignes » au bord de la forme |
|
||||
| « Forme trop étroite pour le motif » | Réduire épaisseur, période ou marge |
|
||||
| « Forme trop grande pour cette période » | Augmenter la période ou découper la forme |
|
||||
|
||||
## Paramètres
|
||||
|
||||

|
||||
|
||||
| Paramètre | Défaut | Rôle |
|
||||
| --------------------------------------------------- | ----------------------- | -------------------------------------------------------------------- |
|
||||
| Période (écart entre les lignes, d'axe en axe) | 4 | Distance entre les axes de deux lignes voisines |
|
||||
| Épaisseur du trait | 2 | Largeur des vermicelles ; doit rester inférieure à la période |
|
||||
| Marge au bord de la forme | 0 | Espace libre entre le bord et les traits (bouts ronds compris) |
|
||||
| Unité | mm | Unité des trois longueurs ci-dessus (mm, cm, px, pt, in) |
|
||||
| Itérations | 60 | Durée d'évolution du motif : peu = points et lignes courtes, beaucoup = longues lignes |
|
||||
| Graine aléatoire | 1 | Change le dessin, pas son aspect |
|
||||
| Au bord de la forme | Couper les lignes | Couper comme un tissu, ou longer le bord |
|
||||
| Couleur du trait | noir | Couleur et opacité des traits |
|
||||
| Conserver la forme d'origine | oui | Sinon la forme source est supprimée |
|
||||
|
||||
## Structure du projet
|
||||
|
||||
```text
|
||||
dog_bandana.inx Boîte de dialogue (textes source en anglais)
|
||||
dog_bandana.py Couche inkex : sélection, unités, contours, écriture SVG
|
||||
dog_bandana_core.py Calcul du motif et ordre de gravure, sans inkex (numpy)
|
||||
i18n.py Extraction / mise à jour / compilation des traductions
|
||||
po/ Catalogues : dogbandana.pot, en.po, fr.po
|
||||
locale/ Traductions compilées (.mo), déployées
|
||||
images/parameters_en.png Schéma de l'onglet « Help » (déployé)
|
||||
docs/schema_parametres.py Générateur du schéma (fr pour le README, en pour le dialogue)
|
||||
docs/parametres.png Schéma du README
|
||||
docs/apercu.png Aperçu du résultat (bandeau du README)
|
||||
docs/*.jpg Image de référence du motif
|
||||
tests/data/ Formes d'exemple (dont une page à l'échelle non standard)
|
||||
test_dog_bandana.py Tests pytest
|
||||
deploy.ps1 Déploiement / désinstallation Windows
|
||||
```
|
||||
|
||||
API du module `dog_bandana_core` :
|
||||
|
||||
| Fonction | Rôle |
|
||||
| -------- | ---- |
|
||||
| `turing_pattern(rings, period, line_width, margin=0, seed=1, edge="cut", pixels_per_period=8, steps=60)` | Lignes centrales du labyrinthe qui remplit les anneaux (`edge` : `"cut"` ou `"follow"`) |
|
||||
| `grid_pixels(rings, period)` | Taille de la grille de calcul (garde-fou de durée) |
|
||||
| `rasterize(rings, x0, y0, step, nx, ny)` | Masque pair-impair des pixels intérieurs |
|
||||
| `erode(mask, radius)` | Érosion par un disque (FFT) : marge et demi-épaisseur |
|
||||
| `swift_hohenberg(shape, pixels_per_period, seed, steps, outside=None)` | Champ du régime labyrinthe (schéma spectral semi-implicite) |
|
||||
| `skeletonize(binary)` | Squelette d'un pixel (Zhang-Suen) |
|
||||
| `trace_skeleton(skeleton, min_spur=0)` | Polylignes du squelette, ergots supprimés |
|
||||
| `smooth_polyline(points, passes)` / `simplify_polyline(points, tolerance)` | Lissage et simplification (Ramer-Douglas-Peucker) |
|
||||
| `laser_order(polylines, start)` | Enchaîne puis ordonne les traits pour le laser |
|
||||
| `chain_polylines(polylines)` / `order_polylines(polylines, start)` | Les deux étapes de `laser_order` |
|
||||
| `travel_length(polylines, start)` | Longueur des déplacements à vide |
|
||||
| `parse_color(value)` | Couleur Inkscape (entier RGBA) → `#rrggbb`, opacité |
|
||||
| `polylines_to_d(polylines, precision)` | Données `d` d'un chemin SVG |
|
||||
|
||||
## Développement
|
||||
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.venv\Scripts\activate
|
||||
pip install pytest numpy lxml tinycss2 cssselect
|
||||
python -m pytest -q # 30 réussis, 7 ignorés (sans inkex)
|
||||
$env:PYTHONPATH = 'C:\Program Files\Inkscape\share\inkscape\extensions'
|
||||
python -m pytest -q # 37 réussis
|
||||
```
|
||||
|
||||
Les tests couvrent les étapes du calcul (masque pair-impair, érosion, squelette,
|
||||
suivi des branches et ergots, lissage, simplification), le motif lui-même (traits
|
||||
dans la forme à la marge près dans les deux modes de bord, densité conforme à la
|
||||
période, trous respectés, reproductibilité par graine, effet des itérations, cas
|
||||
vides), l'ordre de gravure, l'extension de bout en bout (groupes, messages
|
||||
d'erreur, page à l'échelle non standard), les traductions et la cohérence `.inx`
|
||||
↔ arguments.
|
||||
|
||||
### Traductions
|
||||
|
||||
```bash
|
||||
python i18n.py # extract + update + compile ; liste les msgstr manquants
|
||||
```
|
||||
|
||||
Après modification d'un texte du `.inx` ou d'un `_("...")` : lancer
|
||||
`python i18n.py`, compléter les `msgstr` vides de `po/fr.po`, relancer. `en.po` se
|
||||
remplit seul ; ne jamais éditer les `.mo`. Pour une nouvelle langue : l'ajouter à
|
||||
`LANGUAGES` dans `i18n.py`.
|
||||
|
||||
### Schéma des paramètres
|
||||
|
||||
```bash
|
||||
python docs/schema_parametres.py # fr → docs/parametres.png (1400 px)
|
||||
# en → images/parameters_en.png (900 px)
|
||||
```
|
||||
|
||||
Les motifs du schéma sont calculés par `dog_bandana_core`, comme dans
|
||||
l'extension. L'export PNG passe par `C:\Program Files\Inkscape\bin\inkscape.com`.
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Déploie l'extension « Dog Bandana » dans Inkscape.
|
||||
|
||||
.DESCRIPTION
|
||||
Copie dog_bandana.inx, dog_bandana.py, dog_bandana_core.py, le schéma de l'onglet
|
||||
« Help » (images\parameters_en.png) et les traductions
|
||||
compilées (locale\<langue>\LC_MESSAGES\dogbandana.mo) dans un
|
||||
sous-dossier dédié du répertoire des extensions utilisateur d'Inkscape
|
||||
(Inkscape explore récursivement ce répertoire). Refuse de s'exécuter si
|
||||
Inkscape est ouvert : les extensions ne sont chargées qu'au démarrage.
|
||||
|
||||
.PARAMETER ExtensionsDir
|
||||
Répertoire des extensions Inkscape. Par défaut : %APPDATA%\inkscape\extensions
|
||||
|
||||
.PARAMETER FolderName
|
||||
Nom du sous-dossier de l'extension. Par défaut : dogBandana
|
||||
|
||||
.PARAMETER Uninstall
|
||||
Supprime le sous-dossier de l'extension au lieu de le créer.
|
||||
|
||||
.PARAMETER Force
|
||||
Déploie même si Inkscape est en cours d'exécution.
|
||||
|
||||
.EXAMPLE
|
||||
.\deploy.ps1
|
||||
.\deploy.ps1 -Uninstall
|
||||
.\deploy.ps1 -FolderName 'autre-nom'
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string] $ExtensionsDir = (Join-Path $env:APPDATA 'inkscape\extensions'),
|
||||
[string] $FolderName = 'dogBandana',
|
||||
[switch] $Uninstall,
|
||||
[switch] $Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$files = @('dog_bandana.inx', 'dog_bandana.py', 'dog_bandana_core.py', 'images\parameters_en.png')
|
||||
$localeDir = 'locale'
|
||||
$source = $PSScriptRoot
|
||||
$destination = Join-Path $ExtensionsDir $FolderName
|
||||
|
||||
# --- Inkscape doit être fermé : les extensions sont lues au démarrage ---------
|
||||
$running = Get-Process -Name 'inkscape' -ErrorAction SilentlyContinue
|
||||
if ($running -and -not $Force) {
|
||||
Write-Error "Inkscape est ouvert. Fermez-le puis relancez le script (ou utilisez -Force)."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Désinstallation ---------------------------------------------------------
|
||||
if ($Uninstall) {
|
||||
if (Test-Path -LiteralPath $destination) {
|
||||
Remove-Item -LiteralPath $destination -Recurse -Force
|
||||
Write-Host "Supprimé : $destination" -ForegroundColor Green
|
||||
}
|
||||
else {
|
||||
Write-Host "Rien à supprimer : $destination n'existe pas." -ForegroundColor Yellow
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
# --- Vérification des sources ------------------------------------------------
|
||||
$missing = $files | Where-Object { -not (Test-Path -LiteralPath (Join-Path $source $_)) }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $source $localeDir))) {
|
||||
$missing = @($missing) + "$localeDir\ (lancer : python i18n.py)"
|
||||
}
|
||||
if ($missing) {
|
||||
Write-Error "Fichier(s) introuvable(s) dans $source : $($missing -join ', ')"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Copie -------------------------------------------------------------------
|
||||
if (-not (Test-Path -LiteralPath $destination)) {
|
||||
New-Item -ItemType Directory -Path $destination -Force | Out-Null
|
||||
Write-Host "Dossier créé : $destination"
|
||||
}
|
||||
|
||||
foreach ($file in $files) {
|
||||
$from = Join-Path $source $file
|
||||
$to = Join-Path $destination $file
|
||||
$action = if (Test-Path -LiteralPath $to) { 'remplacé' } else { 'copié ' }
|
||||
New-Item -ItemType Directory -Path (Split-Path $to) -Force | Out-Null
|
||||
Copy-Item -LiteralPath $from -Destination $to -Force
|
||||
Write-Host " $action $file"
|
||||
}
|
||||
|
||||
# Traductions : le dossier est remplacé en entier (langue retirée => supprimée)
|
||||
$localeTo = Join-Path $destination $localeDir
|
||||
if (Test-Path -LiteralPath $localeTo) {
|
||||
Remove-Item -LiteralPath $localeTo -Recurse -Force
|
||||
}
|
||||
Copy-Item -LiteralPath (Join-Path $source $localeDir) -Destination $localeTo -Recurse
|
||||
$languages = Get-ChildItem -LiteralPath $localeTo -Directory | ForEach-Object Name
|
||||
Write-Host " copié $localeDir\ ($($languages -join ', '))"
|
||||
|
||||
# Le cache Python d'une version précédente peut masquer les fichiers copiés
|
||||
$pycache = Join-Path $destination '__pycache__'
|
||||
if (Test-Path -LiteralPath $pycache) {
|
||||
Remove-Item -LiteralPath $pycache -Recurse -Force
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Extension déployée dans $destination" -ForegroundColor Green
|
||||
Write-Host "Redémarrez Inkscape, puis : Extensions > AlexDesign > Dog Bandana..."
|
||||
@@ -0,0 +1,79 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Textes source en anglais, traduits par le catalogue « dogbandana »
|
||||
(locale/<langue>/LC_MESSAGES/dogbandana.mo). Après toute modification
|
||||
d'un texte : python i18n.py, puis compléter po/fr.po et relancer.
|
||||
-->
|
||||
<inkscape-extension translationdomain="dogbandana"
|
||||
xmlns="http://www.inkscape.org/namespace/inkscape/extension">
|
||||
<name>Dog Bandana Pattern Fill</name>
|
||||
<id>fr.alexp.dogbandana</id>
|
||||
|
||||
<param name="tab" type="notebook">
|
||||
<page name="pattern" gui-text="Pattern">
|
||||
<param name="period" type="float" precision="2" min="0.2" max="1000"
|
||||
gui-text="Period (line spacing, center to center):">4.0</param>
|
||||
<param name="line_width" type="float" precision="2" min="0.05" max="1000"
|
||||
gui-text="Line width:">2.0</param>
|
||||
<param name="margin" type="float" precision="2" min="0" max="1000"
|
||||
gui-text="Margin from the shape edge:">0.0</param>
|
||||
<param name="unit" type="optiongroup" appearance="combo" gui-text="Unit:">
|
||||
<!-- Les unités ne se traduisent pas -->
|
||||
<option translatable="no" value="mm">mm</option>
|
||||
<option translatable="no" value="cm">cm</option>
|
||||
<option translatable="no" value="px">px</option>
|
||||
<option translatable="no" value="pt">pt</option>
|
||||
<option translatable="no" value="in">in</option>
|
||||
</param>
|
||||
<separator/>
|
||||
<param name="iterations" type="int" min="10" max="500"
|
||||
gui-text="Iterations (more = longer, smoother lines):"
|
||||
gui-description="Few iterations leave many dots and short lines; many iterations give long, regular lines.">60</param>
|
||||
<param name="seed" type="int" min="0" max="999999"
|
||||
gui-text="Random seed (another number, another maze):">1</param>
|
||||
<param name="edge" type="optiongroup" appearance="combo" gui-text="At the shape edge:">
|
||||
<option value="cut">Cut the lines (like cut fabric)</option>
|
||||
<option value="follow">Lines follow the edge</option>
|
||||
</param>
|
||||
</page>
|
||||
|
||||
<page name="style" gui-text="Style">
|
||||
<param name="stroke_color" type="color" appearance="colorbutton"
|
||||
gui-text="Line color:">255</param>
|
||||
<param name="keep_original" type="bool"
|
||||
gui-text="Keep the original shape">true</param>
|
||||
</page>
|
||||
|
||||
<page name="help" gui-text="Help">
|
||||
<!-- Schéma généré par docs/schema_parametres.py, en anglais :
|
||||
Inkscape ne traduit pas le chemin d'une image. Affiché aux
|
||||
3/4 du PNG (900 px) pour limiter la hauteur de l'onglet. -->
|
||||
<image width="675" height="617">images/parameters_en.png</image>
|
||||
<separator/>
|
||||
<!-- Un paragraphe par ligne : Inkscape le replie à la largeur de
|
||||
l'onglet ; des retours à la ligne forcés le laisseraient étroit. -->
|
||||
<label xml:space="preserve">Select one or more closed shapes (or groups), then run the extension. Each shape is filled with a Turing maze: winding lines of constant width that branch and end in round tips.
|
||||
|
||||
Each line is drawn once, along its center, with a round-capped stroke of the chosen width: ready for line engraving on a laser cutter. The lines are chained and ordered to limit idle travel of the laser head.
|
||||
|
||||
Period: distance between the centers of two neighbouring lines. Line width: stroke thickness; keep it below the period (about half gives as much black as white). Margin: free space between the shape edge and the strokes.
|
||||
|
||||
Iterations: how long the pattern evolves. Few iterations leave dots and short lines, many give long regular lines. The seed changes the drawing while keeping the same look.
|
||||
|
||||
At the shape edge: cut the lines like a piece of fabric, or let them stop before the edge and run along it.
|
||||
|
||||
The result is placed in a group just above each shape. Large shapes with a small period take a few seconds.</label>
|
||||
</page>
|
||||
</param>
|
||||
|
||||
<effect>
|
||||
<object-type>all</object-type>
|
||||
<effects-menu>
|
||||
<submenu name="AlexDesign"/>
|
||||
</effects-menu>
|
||||
</effect>
|
||||
|
||||
<script>
|
||||
<command location="inx" interpreter="python">dog_bandana.py</command>
|
||||
</script>
|
||||
</inkscape-extension>
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
# coding=utf-8
|
||||
"""
|
||||
Extension Inkscape : remplit les formes selectionnees d'un labyrinthe de
|
||||
Turing (motif « Dog Bandana »), trace en lignes centrales a bouts ronds.
|
||||
|
||||
Le motif est calcule par l'equation de Swift-Hohenberg sur une grille qui
|
||||
couvre la forme, puis reduit a la ligne centrale de chaque bande : un trait
|
||||
par « vermicelle », pret pour la gravure laser en mode ligne.
|
||||
|
||||
La logique vit dans `dog_bandana_core`, sans dependance a inkex.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import inkex
|
||||
from inkex.bezier import cspsubdiv
|
||||
from inkex.localization import localize
|
||||
from inkex.units import convert_unit
|
||||
|
||||
# L'extension vit dans son propre sous-dossier des extensions Inkscape, qui
|
||||
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver dog_bandana_core.
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from dog_bandana_core import (MAX_PIXELS, grid_pixels, laser_order, # noqa: E402
|
||||
parse_color, polylines_to_d, turing_pattern)
|
||||
|
||||
|
||||
def use_system_language():
|
||||
"""Renseigne LANGUAGE avec la langue du systeme si rien ne la fixe.
|
||||
|
||||
Sous Windows, Inkscape regle sur « langue du systeme » ne transmet aucune
|
||||
variable de langue au script : gettext retomberait sur l'anglais alors que
|
||||
la boite de dialogue, traduite par Inkscape lui-meme, est dans la langue
|
||||
de l'utilisateur.
|
||||
"""
|
||||
if any(os.environ.get(name) for name in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")):
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
import locale
|
||||
language = locale.windows_locale.get(
|
||||
ctypes.windll.kernel32.GetUserDefaultUILanguage())
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return # hors Windows : LANG est toujours defini
|
||||
if language:
|
||||
os.environ["LANGUAGE"] = language
|
||||
|
||||
|
||||
# Installe _() dans les builtins : catalogue « dogbandana » de la langue
|
||||
# de l'interface (Inkscape transmet domaine et dossier par l'environnement),
|
||||
# textes anglais d'origine sinon.
|
||||
use_system_language()
|
||||
localize()
|
||||
|
||||
# Elements qui delimitent une surface a remplir.
|
||||
SHAPES = (inkex.PathElement, inkex.Rectangle, inkex.Circle, inkex.Ellipse,
|
||||
inkex.Polygon)
|
||||
|
||||
|
||||
def uu_per_mm(svg):
|
||||
"""Unites utilisateur par millimetre, comme Inkscape les affiche.
|
||||
|
||||
svg.unittouu() devine l'unite du document par arrondi a l'unite connue la
|
||||
plus proche : il se trompe des que l'echelle n'est pas standard (page
|
||||
redimensionnee). On prend le rapport reel page / viewBox ; Inkscape
|
||||
applique une echelle uniforme (preserveAspectRatio « meet »), soit la
|
||||
plus petite des deux.
|
||||
"""
|
||||
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 anterieur a 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"):
|
||||
"""Longueur reelle (valeur + unite) -> unites utilisateur du document."""
|
||||
return convert_unit("{}{}".format(value, unit), "mm") * uu_per_mm(svg)
|
||||
|
||||
|
||||
def element_rings(elem, flatness):
|
||||
"""Contour de l'element en coordonnees absolues : liste d'anneaux.
|
||||
|
||||
Les courbes sont aplaties en polylignes (ecart maximal `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):
|
||||
"""Remplit chaque forme selectionnee d'un labyrinthe de Turing."""
|
||||
|
||||
def add_arguments(self, pars):
|
||||
# Un argument par <param> du .inx, memes noms et memes valeurs par defaut.
|
||||
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",
|
||||
})
|
||||
|
||||
# Position de la tete du laser : chaque trace demarre la ou le
|
||||
# precedent s'est arrete (voir path_element).
|
||||
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):
|
||||
"""Chemin SVG des traits, dans l'ordre de gravure optimise.
|
||||
|
||||
Les traits qui se touchent sont enchaines, puis ordonnes au plus pres
|
||||
de la position de la tete : moins de deplacements a vide du laser.
|
||||
Tout trait genere passe par ici.
|
||||
"""
|
||||
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):
|
||||
"""Remplit un element ; renvoie False si la forme est trop etroite."""
|
||||
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:
|
||||
# Resultat calcule en coordonnees absolues du document : on
|
||||
# neutralise la transformation heritee du parent d'accueil.
|
||||
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()
|
||||
@@ -0,0 +1,537 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Noyau de calcul de l'extension « Dog Bandana », sans dependance a inkex.
|
||||
|
||||
Testable avec pytest seul et reutilisable hors Inkscape (scripts, schema
|
||||
des parametres).
|
||||
|
||||
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).
|
||||
|
||||
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).
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def parse_color(value, default=("#b3b3b3", 1.0)):
|
||||
"""Couleur Inkscape (entier RGBA decimal ou 0x..., ou #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.
|
||||
"""
|
||||
text = str(value).strip()
|
||||
try:
|
||||
if text.startswith("#"):
|
||||
digits = text[1:]
|
||||
if len(digits) == 3:
|
||||
digits = "".join(c * 2 for c in digits)
|
||||
if len(digits) == 6:
|
||||
digits += "ff"
|
||||
if len(digits) != 8:
|
||||
return default
|
||||
number = int(digits, 16)
|
||||
else:
|
||||
number = int(text, 0)
|
||||
except ValueError:
|
||||
return default
|
||||
number &= 0xFFFFFFFF
|
||||
red, green, blue = (number >> 24) & 255, (number >> 16) & 255, (number >> 8) & 255
|
||||
alpha = (number & 255) / 255.0
|
||||
return "#{:02x}{:02x}{:02x}".format(red, green, blue), round(alpha, 4)
|
||||
|
||||
|
||||
def polylines_to_d(polylines, precision=4):
|
||||
"""Donnees `d` d'un chemin SVG : une polyligne par sous-chemin."""
|
||||
fmt = "{:.%df},{:.%df}" % (precision, precision)
|
||||
parts = []
|
||||
for polyline in polylines:
|
||||
if len(polyline) < 2:
|
||||
continue
|
||||
parts.append("M " + fmt.format(*polyline[0]))
|
||||
parts.extend("L " + fmt.format(*point) for point in polyline[1:])
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Ordre de gravure (decoupeuse laser)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _key(point):
|
||||
"""Cle d'un point : deux extremites a 1e-6 pres sont le meme noeud."""
|
||||
return round(point[0], 6), round(point[1], 6)
|
||||
|
||||
|
||||
def _is_closed(line):
|
||||
return len(line) > 2 and _key(line[0]) == _key(line[-1])
|
||||
|
||||
|
||||
def chain_polylines(polylines):
|
||||
"""Met bout a bout les polylignes qui se touchent par leurs extremites.
|
||||
|
||||
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.
|
||||
"""
|
||||
out = []
|
||||
points = {}
|
||||
adjacency = {} # noeud -> [(numero de polyligne, voisin)]
|
||||
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])
|
||||
if a == b:
|
||||
out.append(line)
|
||||
continue
|
||||
points.setdefault(a, line[0])
|
||||
points.setdefault(b, line[-1])
|
||||
adjacency.setdefault(a, []).append((index, b))
|
||||
adjacency.setdefault(b, []).append((index, a))
|
||||
used = [False] * len(lines)
|
||||
|
||||
def free_edges(node):
|
||||
edges = adjacency[node]
|
||||
edges[:] = [edge for edge in edges if not used[edge[0]]]
|
||||
return edges
|
||||
|
||||
def walk(node):
|
||||
chain = [points[node]]
|
||||
while True:
|
||||
edges = free_edges(node)
|
||||
if not edges:
|
||||
return chain
|
||||
index, following = edges.pop()
|
||||
used[index] = True
|
||||
line = lines[index]
|
||||
if _key(line[0]) != node:
|
||||
line = line[::-1]
|
||||
chain.extend(line[1:])
|
||||
node = following
|
||||
|
||||
for node in adjacency:
|
||||
if len(free_edges(node)) % 2:
|
||||
out.append(walk(node))
|
||||
for node in adjacency: # reste : circuits fermes
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
polylines = [list(line) for line in polylines if len(line) >= 2]
|
||||
if not polylines:
|
||||
return []
|
||||
entries = [] # (numero de polyligne, sommet d'entree)
|
||||
for index, line in enumerate(polylines):
|
||||
if _is_closed(line):
|
||||
entries.extend((index, k) for k in range(len(line) - 1))
|
||||
else:
|
||||
entries.extend(((index, 0), (index, len(line) - 1)))
|
||||
|
||||
xs = [polylines[i][k][0] for i, k in entries]
|
||||
ys = [polylines[i][k][1] for i, k in entries]
|
||||
x0, y0 = min(xs), min(ys)
|
||||
width, height = max(xs) - x0, max(ys) - y0
|
||||
cell = math.sqrt(width * height / len(entries)) or max(width, height) / len(entries) or 1.0
|
||||
nx, ny = int(width / cell), int(height / cell)
|
||||
grid = {}
|
||||
for entry, x, y in zip(entries, xs, ys):
|
||||
grid.setdefault((int((x - x0) / cell), int((y - y0) / cell)), []).append(entry)
|
||||
|
||||
done = [False] * len(polylines)
|
||||
|
||||
def ring(cx, cy, r):
|
||||
"""Cellules de la grille a distance r (en cellules) de (cx, cy)."""
|
||||
if r == 0:
|
||||
yield cx, cy
|
||||
return
|
||||
for gx in range(max(cx - r, 0), min(cx + r, nx) + 1):
|
||||
if 0 <= cy - r <= ny:
|
||||
yield gx, cy - r
|
||||
if 0 <= cy + r <= ny:
|
||||
yield gx, cy + r
|
||||
for gy in range(max(cy - r + 1, 0), min(cy + r - 1, ny) + 1):
|
||||
if 0 <= cx - r <= nx:
|
||||
yield cx - r, gy
|
||||
if 0 <= cx + r <= nx:
|
||||
yield cx + r, gy
|
||||
|
||||
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 = max(cx, nx - cx, cy, ny - cy, r)
|
||||
best, best_d = None, float("inf")
|
||||
while r <= r_max and (r - 1) * cell < best_d:
|
||||
for key in ring(cx, cy, r):
|
||||
bucket = grid.get(key)
|
||||
if not bucket:
|
||||
continue
|
||||
bucket[:] = [e for e in bucket if not done[e[0]]]
|
||||
for index, k in bucket:
|
||||
px, py = polylines[index][k]
|
||||
d = math.hypot(px - x, py - y)
|
||||
if d < best_d:
|
||||
best, best_d = (index, k), d
|
||||
r += 1
|
||||
return best
|
||||
|
||||
ordered = []
|
||||
position = start
|
||||
for _ in range(len(polylines)):
|
||||
index, k = nearest(*position)
|
||||
done[index] = True
|
||||
line = polylines[index]
|
||||
if k == 0:
|
||||
pass
|
||||
elif not _is_closed(line):
|
||||
line = line[::-1]
|
||||
else: # boucle : rotation
|
||||
line = line[k:-1] + line[:k] + [line[k]]
|
||||
ordered.append(line)
|
||||
position = line[-1]
|
||||
return ordered
|
||||
|
||||
|
||||
def laser_order(polylines, start=(0.0, 0.0)):
|
||||
"""Enchaine puis ordonne les traits : a appliquer avant 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.
|
||||
"""
|
||||
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 = 0.0
|
||||
position = start
|
||||
for line in polylines:
|
||||
total += math.hypot(line[0][0] - position[0], line[0][1] - position[1])
|
||||
position = line[-1]
|
||||
return total
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Motif de Turing (labyrinthe)
|
||||
# --------------------------------------------------------------------------
|
||||
#
|
||||
# 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.
|
||||
|
||||
PIXELS_PER_PERIOD = 8 # resolution du calcul
|
||||
STEPS = 60 # pas d'integration : plus, bandes plus longues
|
||||
SMOOTHING = 4 # passes de lissage des lignes centrales
|
||||
EDGE_MODES = ("cut", "follow")
|
||||
MAX_PIXELS = 3000000 # au-dela, calcul trop long dans Inkscape
|
||||
|
||||
|
||||
def rasterize(rings, x0, y0, step, nx, ny):
|
||||
"""Masque booleen (ny, nx) des centres de pixels interieurs (pair-impair).
|
||||
|
||||
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.
|
||||
"""
|
||||
mask = np.zeros((ny, nx), dtype=bool)
|
||||
edges = [(ring[k], ring[(k + 1) % len(ring)]) for ring in rings
|
||||
for k in range(len(ring))]
|
||||
if not edges:
|
||||
return mask
|
||||
ax, ay, bx, by = (np.array(v, dtype=float) for v in zip(
|
||||
*[(a[0], a[1], b[0], b[1]) for a, b in edges]))
|
||||
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.
|
||||
hit = (ay <= y) != (by <= y)
|
||||
if not hit.any():
|
||||
continue
|
||||
t = (y - ay[hit]) / (by[hit] - ay[hit])
|
||||
xs = np.sort(ax[hit] + t * (bx[hit] - ax[hit]))
|
||||
mask[i] = np.searchsorted(xs, columns) % 2 == 1
|
||||
return mask
|
||||
|
||||
|
||||
def erode(mask, radius):
|
||||
"""Erosion du masque par un disque de `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.
|
||||
"""
|
||||
if radius <= 0:
|
||||
return mask.copy()
|
||||
ny, nx = mask.shape
|
||||
iy = np.minimum(np.arange(ny), ny - np.arange(ny))[:, None]
|
||||
ix = np.minimum(np.arange(nx), nx - np.arange(nx))[None, :]
|
||||
disk = (ix ** 2 + iy ** 2 <= radius ** 2).astype(float)
|
||||
hits = np.fft.irfft2(np.fft.rfft2((~mask).astype(float)) * np.fft.rfft2(disk),
|
||||
s=mask.shape)
|
||||
return mask & (hits < 0.5)
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
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
|
||||
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
|
||||
denominator = 1 - dt * (r - (1 - k2) ** 2)
|
||||
for _ in range(steps):
|
||||
if outside is not None:
|
||||
u[outside] = -1.0
|
||||
u_hat = np.fft.rfft2(u - dt * u ** 3)
|
||||
u = np.fft.irfft2(u_hat / denominator, s=(ny, nx))
|
||||
if outside is not None:
|
||||
u[outside] = -1.0
|
||||
return u
|
||||
|
||||
|
||||
def skeletonize(binary):
|
||||
"""Squelette d'un pixel d'epaisseur (Zhang-Suen), vectorise avec numpy."""
|
||||
img = np.pad(binary.astype(np.uint8), 1)
|
||||
while True:
|
||||
changed = False
|
||||
for first in (True, False):
|
||||
p2, p3, p4 = img[:-2, 1:-1], img[:-2, 2:], img[1:-1, 2:]
|
||||
p5, p6, p7 = img[2:, 2:], img[2:, 1:-1], img[2:, :-2]
|
||||
p8, p9 = img[1:-1, :-2], img[:-2, :-2]
|
||||
around = [p2, p3, p4, p5, p6, p7, p8, p9, p2]
|
||||
neighbours = sum(around[:8])
|
||||
transitions = sum(((a == 0) & (b == 1)).astype(np.uint8)
|
||||
for a, b in zip(around, around[1:]))
|
||||
if first:
|
||||
c1, c2 = p2 * p4 * p6, p4 * p6 * p8
|
||||
else:
|
||||
c1, c2 = p2 * p4 * p8, p2 * p6 * p8
|
||||
remove = ((img[1:-1, 1:-1] == 1) & (neighbours >= 2) & (neighbours <= 6)
|
||||
& (transitions == 1) & (c1 == 0) & (c2 == 0))
|
||||
if remove.any():
|
||||
img[1:-1, 1:-1][remove] = 0
|
||||
changed = True
|
||||
if not changed:
|
||||
return img[1:-1, 1:-1].astype(bool)
|
||||
|
||||
|
||||
_NEIGHBOURS = ((-1, 0), (0, 1), (1, 0), (0, -1), (-1, -1), (-1, 1), (1, 1), (1, -1))
|
||||
|
||||
|
||||
def _skeleton_graph(skeleton):
|
||||
"""Voisins de chaque pixel du squelette.
|
||||
|
||||
Liaisons 8-connexes, sauf une diagonale doublee par deux liaisons droites
|
||||
(coin en « L ») : elle creerait de faux carrefours.
|
||||
"""
|
||||
pixels = set(zip(*(index.tolist() for index in np.nonzero(skeleton))))
|
||||
graph = {}
|
||||
for (i, j) in pixels:
|
||||
links = []
|
||||
for di, dj in _NEIGHBOURS:
|
||||
q = (i + di, j + dj)
|
||||
if q not in pixels:
|
||||
continue
|
||||
if di and dj and ((i + di, j) in pixels or (i, j + dj) in pixels):
|
||||
continue
|
||||
links.append(q)
|
||||
graph[(i, j)] = links
|
||||
return graph
|
||||
|
||||
|
||||
def trace_skeleton(skeleton, min_spur=0):
|
||||
"""Polylignes de pixels (ligne, colonne) qui suivent le squelette.
|
||||
|
||||
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.
|
||||
"""
|
||||
graph = _skeleton_graph(skeleton)
|
||||
seen = set() # liaisons deja parcourues
|
||||
|
||||
def follow(previous, current, line):
|
||||
seen.add((previous, current))
|
||||
seen.add((current, previous))
|
||||
while len(graph[current]) == 2 and current != line[0]:
|
||||
line.append(current)
|
||||
a, b = graph[current]
|
||||
following = b if a == previous else a
|
||||
if (current, following) in seen:
|
||||
break
|
||||
seen.add((current, following))
|
||||
seen.add((following, current))
|
||||
previous, current = current, following
|
||||
line.append(current)
|
||||
return line
|
||||
|
||||
lines = []
|
||||
for node in sorted(p for p, links in graph.items() if len(links) != 2):
|
||||
if not graph[node]:
|
||||
lines.append([node])
|
||||
for nxt in graph[node]:
|
||||
if (node, nxt) not in seen:
|
||||
lines.append(follow(node, nxt, [node]))
|
||||
for p in sorted(graph): # boucles isolees
|
||||
links = graph[p]
|
||||
if len(links) == 2 and (p, links[0]) not in seen:
|
||||
lines.append(follow(p, links[0], [p]))
|
||||
|
||||
if min_spur <= 0:
|
||||
return lines
|
||||
degree = {p: len(links) for p, links in graph.items()}
|
||||
kept = []
|
||||
for line in lines:
|
||||
ends = sorted((degree[line[0]], degree[line[-1]]))
|
||||
if 1 < len(line) <= min_spur and ends[0] == 1 and ends[1] >= 3:
|
||||
continue
|
||||
kept.append(line)
|
||||
return kept
|
||||
|
||||
|
||||
def smooth_polyline(points, passes=2):
|
||||
"""Lissage par moyenne glissante (1/4, 1/2, 1/4), extremites fixes.
|
||||
|
||||
Une boucle fermee (premier point = dernier) est lissee tout du long.
|
||||
"""
|
||||
if len(points) < 3:
|
||||
return [tuple(p) for p in points]
|
||||
closed = tuple(points[0]) == tuple(points[-1])
|
||||
pts = np.array(points[:-1] if closed else points, dtype=float)
|
||||
for _ in range(passes):
|
||||
if closed:
|
||||
pts = 0.25 * np.roll(pts, 1, 0) + 0.5 * pts + 0.25 * np.roll(pts, -1, 0)
|
||||
else:
|
||||
inner = 0.25 * pts[:-2] + 0.5 * pts[1:-1] + 0.25 * pts[2:]
|
||||
pts = np.vstack((pts[:1], inner, pts[-1:]))
|
||||
out = [tuple(p) for p in pts.tolist()]
|
||||
if closed:
|
||||
out.append(out[0])
|
||||
return out
|
||||
|
||||
|
||||
def simplify_polyline(points, tolerance):
|
||||
"""Ramer-Douglas-Peucker : ne garde que les sommets utiles a `tolerance` pres."""
|
||||
if len(points) < 3:
|
||||
return [tuple(p) for p in points]
|
||||
pts = np.asarray(points, dtype=float)
|
||||
keep = np.zeros(len(pts), dtype=bool)
|
||||
keep[0] = keep[-1] = True
|
||||
stack = [(0, len(pts) - 1)]
|
||||
while stack:
|
||||
a, b = stack.pop()
|
||||
if b - a < 2:
|
||||
continue
|
||||
sx, sy = pts[b] - pts[a]
|
||||
rel = pts[a + 1:b] - pts[a]
|
||||
length = math.hypot(sx, sy)
|
||||
if length == 0:
|
||||
dist = np.hypot(rel[:, 0], rel[:, 1])
|
||||
else:
|
||||
dist = np.abs(rel[:, 0] * sy - rel[:, 1] * sx) / length
|
||||
k = int(np.argmax(dist))
|
||||
if dist[k] > tolerance:
|
||||
keep[a + 1 + k] = True
|
||||
stack.extend(((a, a + 1 + k), (a + 1 + k, b)))
|
||||
return [tuple(p) for p in pts[keep].tolist()]
|
||||
|
||||
|
||||
def _grid(rings, period, pixels_per_period):
|
||||
"""Origine, pas et taille (x0, y0, step, nx, ny) de la grille de calcul.
|
||||
|
||||
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.
|
||||
"""
|
||||
xs = [x for ring in rings for x, _y in ring]
|
||||
ys = [y for ring in rings for _x, y in ring]
|
||||
step = period / pixels_per_period
|
||||
pad = 2 * pixels_per_period
|
||||
nx = int(math.ceil((max(xs) - min(xs)) / step)) + 2 * pad
|
||||
ny = int(math.ceil((max(ys) - min(ys)) / step)) + 2 * pad
|
||||
return min(xs) - pad * step, min(ys) - pad * step, step, nx, ny
|
||||
|
||||
|
||||
def grid_pixels(rings, period, pixels_per_period=PIXELS_PER_PERIOD):
|
||||
"""Nombre de pixels de la grille de calcul (0 si rien a calculer)."""
|
||||
if period <= 0 or not any(rings):
|
||||
return 0
|
||||
_x0, _y0, _step, nx, ny = _grid(rings, period, pixels_per_period)
|
||||
return nx * ny
|
||||
|
||||
|
||||
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`.
|
||||
|
||||
- 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.
|
||||
|
||||
Renvoie des polylignes en coordonnees du document ; un point isole est
|
||||
une polyligne de deux points confondus (un trait a bouts ronds le dessine).
|
||||
"""
|
||||
if period <= 0 or not any(rings):
|
||||
return []
|
||||
x0, y0, step, nx, ny = _grid(rings, period, pixels_per_period)
|
||||
mask = rasterize(rings, x0, y0, step, nx, ny)
|
||||
inset = max(0.0, margin) + max(0.0, line_width) / 2
|
||||
region = erode(mask, inset / step)
|
||||
if not region.any():
|
||||
return []
|
||||
follow = edge == "follow"
|
||||
u = swift_hohenberg(region.shape, pixels_per_period, seed, steps,
|
||||
outside=~region if follow else None)
|
||||
skeleton = skeletonize(u > 0) & region
|
||||
lines = trace_skeleton(skeleton, min_spur=pixels_per_period / 2)
|
||||
|
||||
out = []
|
||||
for line in lines:
|
||||
points = [(x0 + (j + 0.5) * step, y0 + (i + 0.5) * step) for i, j in line]
|
||||
if len(points) == 1:
|
||||
out.append([points[0], points[0]])
|
||||
else:
|
||||
out.append(simplify_polyline(smooth_polyline(points, SMOOTHING), 0.1 * step))
|
||||
return out
|
||||
@@ -0,0 +1,304 @@
|
||||
#!/usr/bin/env python3
|
||||
# coding=utf-8
|
||||
"""
|
||||
Chaine de traduction de l'extension, sans dependance a gettext.
|
||||
|
||||
python i18n.py # extract + update + compile
|
||||
python i18n.py extract # po/<domaine>.pot depuis le .inx et les .py
|
||||
python i18n.py update # reporte le modele dans po/<langue>.po
|
||||
python i18n.py compile # po/<langue>.po -> locale/<langue>/LC_MESSAGES/*.mo
|
||||
|
||||
Le domaine est lu dans l'attribut translationdomain du .inx ; les sources sont
|
||||
le .inx et tous les .py du dossier (hors i18n.py et tests).
|
||||
|
||||
Les textes source (.inx et appels _() des .py) sont en anglais : c'est ce
|
||||
qu'Inkscape affiche pour une langue sans catalogue. Le catalogue anglais est
|
||||
rempli automatiquement avec les textes source ; seul fr.po se traduit a la main.
|
||||
|
||||
Les chaines retenues dans le .inx suivent les regles d'Inkscape (inx.its) :
|
||||
<name>, attributs gui-text et gui-description, contenu de <option>, <item> et
|
||||
<label>, sauf translatable="no". Les espaces sont normalises, sauf sous
|
||||
xml:space="preserve".
|
||||
"""
|
||||
|
||||
import ast
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
LANGUAGES = ["en", "fr"]
|
||||
SOURCE_LANGUAGE = "en"
|
||||
PO_DIR = os.path.join(HERE, "po")
|
||||
LOCALE_DIR = os.path.join(HERE, "locale")
|
||||
|
||||
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
|
||||
INX_NS = "{http://www.inkscape.org/namespace/inkscape/extension}"
|
||||
|
||||
|
||||
def _find_inx():
|
||||
found = sorted(name for name in os.listdir(HERE) if name.endswith(".inx"))
|
||||
if len(found) != 1:
|
||||
sys.exit("i18n.py attend un seul fichier .inx dans {} (trouve : {})".format(
|
||||
HERE, found))
|
||||
return found[0]
|
||||
|
||||
|
||||
INX = _find_inx()
|
||||
_INX_ROOT = ET.parse(os.path.join(HERE, INX)).getroot()
|
||||
DOMAIN = _INX_ROOT.get("translationdomain")
|
||||
if not DOMAIN:
|
||||
sys.exit("Attribut translationdomain absent de " + INX)
|
||||
EXTENSION_NAME = (_INX_ROOT.findtext(INX_NS + "name") or DOMAIN).strip()
|
||||
SOURCES = [INX] + sorted(
|
||||
name for name in os.listdir(HERE)
|
||||
if name.endswith(".py") and name != "i18n.py" and not name.startswith("test"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Extraction
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _local(tag):
|
||||
return tag.rsplit("}", 1)[-1]
|
||||
|
||||
|
||||
def _normalize(text, preserve):
|
||||
return text if preserve else " ".join(text.split())
|
||||
|
||||
|
||||
def extract_inx(path):
|
||||
"""Chaines traduisibles d'un fichier .inx, dans l'ordre du document."""
|
||||
messages = []
|
||||
|
||||
def walk(elem, preserve):
|
||||
preserve = elem.get(XML_SPACE, "preserve" if preserve else "default") == "preserve"
|
||||
if elem.get("translatable") != "no":
|
||||
for attr in ("gui-text", "gui-description"):
|
||||
if elem.get(attr):
|
||||
messages.append(_normalize(elem.get(attr), preserve))
|
||||
if _local(elem.tag) in ("name", "option", "item", "label") and elem.text:
|
||||
messages.append(_normalize(elem.text, preserve))
|
||||
for child in elem:
|
||||
walk(child, preserve)
|
||||
|
||||
walk(ET.parse(path).getroot(), False)
|
||||
return [m for m in messages if m]
|
||||
|
||||
|
||||
def extract_py(path):
|
||||
"""Arguments litteraux des appels _("...") d'un script Python."""
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
tree = ast.parse(handle.read(), path)
|
||||
calls = [node for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
||||
and node.func.id == "_" and len(node.args) == 1
|
||||
and isinstance(node.args[0], ast.Constant)
|
||||
and isinstance(node.args[0].value, str)]
|
||||
calls.sort(key=lambda node: (node.lineno, node.col_offset))
|
||||
return [node.args[0].value for node in calls]
|
||||
|
||||
|
||||
def extract():
|
||||
"""Liste ordonnee et sans doublon de (msgid, [fichiers sources])."""
|
||||
found = {}
|
||||
for name in SOURCES:
|
||||
path = os.path.join(HERE, name)
|
||||
strings = extract_inx(path) if name.endswith(".inx") else extract_py(path)
|
||||
for msgid in strings:
|
||||
found.setdefault(msgid, [])
|
||||
if name not in found[msgid]:
|
||||
found[msgid].append(name)
|
||||
return list(found.items())
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Lecture / ecriture des fichiers .po
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_ESCAPES = {"n": "\n", "t": "\t", '"': '"', "\\": "\\"}
|
||||
|
||||
|
||||
def _unquote(line):
|
||||
body = line.strip()[1:-1]
|
||||
return re.sub(r'\\(.)', lambda m: _ESCAPES.get(m.group(1), m.group(1)), body)
|
||||
|
||||
|
||||
def _quote(text):
|
||||
text = text.replace("\\", "\\\\").replace('"', '\\"').replace("\t", "\\t")
|
||||
lines = text.split("\n")
|
||||
parts = [line + "\\n" for line in lines[:-1]]
|
||||
if lines[-1]:
|
||||
parts.append(lines[-1])
|
||||
if len(parts) <= 1:
|
||||
return '"{}"'.format(parts[0] if parts else "")
|
||||
return '""\n' + "\n".join('"{}"'.format(part) for part in parts)
|
||||
|
||||
|
||||
def read_po(path):
|
||||
"""Dictionnaire msgid -> (msgstr, fuzzy). L'en-tete a pour cle ""."""
|
||||
entries = {}
|
||||
if not os.path.exists(path):
|
||||
return entries
|
||||
msgid = msgstr = None
|
||||
field = None
|
||||
fuzzy = False
|
||||
|
||||
def flush():
|
||||
if msgid is not None:
|
||||
entries[msgid] = (msgstr or "", fuzzy)
|
||||
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for raw in handle:
|
||||
line = raw.strip()
|
||||
if line.startswith("#,") and "fuzzy" in line:
|
||||
flush()
|
||||
msgid = msgstr = field = None
|
||||
fuzzy = True
|
||||
elif line.startswith("msgid "):
|
||||
if field == "msgstr":
|
||||
flush()
|
||||
fuzzy = False
|
||||
msgid, msgstr, field = _unquote(line[6:]), None, "msgid"
|
||||
elif line.startswith("msgstr "):
|
||||
msgstr, field = _unquote(line[7:]), "msgstr"
|
||||
elif line.startswith('"') and field == "msgid":
|
||||
msgid += _unquote(line)
|
||||
elif line.startswith('"') and field == "msgstr":
|
||||
msgstr += _unquote(line)
|
||||
elif not line and field == "msgstr":
|
||||
flush()
|
||||
msgid = msgstr = field = None
|
||||
fuzzy = False
|
||||
flush()
|
||||
return entries
|
||||
|
||||
|
||||
def _header(language):
|
||||
fields = [
|
||||
("Project-Id-Version", DOMAIN),
|
||||
("Language", language or ""),
|
||||
("MIME-Version", "1.0"),
|
||||
("Content-Type", "text/plain; charset=UTF-8"),
|
||||
("Content-Transfer-Encoding", "8bit"),
|
||||
("Plural-Forms", {"fr": "nplurals=2; plural=(n > 1);",
|
||||
"en": "nplurals=2; plural=(n != 1);"}.get(language, "")),
|
||||
]
|
||||
return "".join("{}: {}\n".format(key, value) for key, value in fields if value)
|
||||
|
||||
|
||||
def write_po(path, language, messages, translations):
|
||||
title = ("Modele de traduction" if language is None
|
||||
else "Traduction ({})".format(language))
|
||||
out = ["# {} de l'extension Inkscape « {} ».".format(title, EXTENSION_NAME),
|
||||
"# Genere par i18n.py ; ne modifier que les msgstr.",
|
||||
"msgid \"\"",
|
||||
"msgstr " + _quote(_header(language)),
|
||||
""]
|
||||
for msgid, refs in messages:
|
||||
msgstr, fuzzy = translations.get(msgid, ("", False))
|
||||
out.append("#: " + " ".join(refs))
|
||||
if fuzzy:
|
||||
out.append("#, fuzzy")
|
||||
out.append("msgid " + _quote(msgid))
|
||||
out.append("msgstr " + _quote(msgstr))
|
||||
out.append("")
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write("\n".join(out))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Compilation .mo (format GNU gettext)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def write_mo(path, catalog):
|
||||
"""Ecrit un catalogue {msgid: msgstr} au format .mo, cles triees."""
|
||||
keys = sorted(catalog)
|
||||
ids = [key.encode("utf-8") for key in keys]
|
||||
strs = [catalog[key].encode("utf-8") for key in keys]
|
||||
count = len(keys)
|
||||
ids_start = 7 * 4 + 16 * count
|
||||
strs_start = ids_start + sum(len(b) + 1 for b in ids)
|
||||
|
||||
table_ids, table_strs = [], []
|
||||
offset = ids_start
|
||||
for data in ids:
|
||||
table_ids += [len(data), offset]
|
||||
offset += len(data) + 1
|
||||
offset = strs_start
|
||||
for data in strs:
|
||||
table_strs += [len(data), offset]
|
||||
offset += len(data) + 1
|
||||
|
||||
output = struct.pack("<7I", 0x950412DE, 0, count, 7 * 4, 7 * 4 + 8 * count, 0, 0)
|
||||
output += struct.pack("<{}I".format(2 * count), *table_ids)
|
||||
output += struct.pack("<{}I".format(2 * count), *table_strs)
|
||||
output += b"".join(data + b"\0" for data in ids)
|
||||
output += b"".join(data + b"\0" for data in strs)
|
||||
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "wb") as handle:
|
||||
handle.write(output)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Commandes
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def po_path(language):
|
||||
return os.path.join(PO_DIR, "{}.po".format(language))
|
||||
|
||||
|
||||
def mo_path(language):
|
||||
return os.path.join(LOCALE_DIR, language, "LC_MESSAGES", DOMAIN + ".mo")
|
||||
|
||||
|
||||
def cmd_extract():
|
||||
os.makedirs(PO_DIR, exist_ok=True)
|
||||
messages = extract()
|
||||
write_po(os.path.join(PO_DIR, DOMAIN + ".pot"), None, messages, {})
|
||||
print("{} chaines -> po/{}.pot".format(len(messages), DOMAIN))
|
||||
|
||||
|
||||
def cmd_update():
|
||||
messages = extract()
|
||||
for language in LANGUAGES:
|
||||
translations = read_po(po_path(language))
|
||||
if language == SOURCE_LANGUAGE:
|
||||
translations = {msgid: (msgid, False) for msgid, _refs in messages}
|
||||
write_po(po_path(language), language, messages, translations)
|
||||
missing = [m for m, _r in messages if not translations.get(m, ("", False))[0]]
|
||||
print("po/{}.po : {} a traduire".format(language, len(missing)))
|
||||
for msgid in missing:
|
||||
print(" " + msgid.splitlines()[0])
|
||||
|
||||
|
||||
def cmd_compile():
|
||||
for language in LANGUAGES:
|
||||
entries = read_po(po_path(language))
|
||||
catalog = {msgid: msgstr for msgid, (msgstr, fuzzy) in entries.items()
|
||||
if msgid and msgstr and not fuzzy}
|
||||
catalog[""] = _header(language)
|
||||
write_mo(mo_path(language), catalog)
|
||||
print("{} -> {} ({} chaines)".format(
|
||||
os.path.relpath(po_path(language), HERE),
|
||||
os.path.relpath(mo_path(language), HERE), len(catalog) - 1))
|
||||
|
||||
|
||||
def main(argv):
|
||||
commands = {"extract": [cmd_extract], "update": [cmd_update],
|
||||
"compile": [cmd_compile],
|
||||
"all": [cmd_extract, cmd_update, cmd_compile]}
|
||||
name = argv[0] if argv else "all"
|
||||
if name not in commands:
|
||||
print(__doc__)
|
||||
return 1
|
||||
for command in commands[name]:
|
||||
command()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,111 @@
|
||||
# Modele de traduction de l'extension Inkscape « Dog Bandana Pattern Fill ».
|
||||
# Genere par i18n.py ; ne modifier que les msgstr.
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: dogbandana\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Dog Bandana Pattern Fill"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Pattern"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Period (line spacing, center to center):"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line width:"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Margin from the shape edge:"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Unit:"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Iterations (more = longer, smoother lines):"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Few iterations leave many dots and short lines; many iterations give long, regular lines."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Random seed (another number, another maze):"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "At the shape edge:"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Cut the lines (like cut fabric)"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Lines follow the edge"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Style"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line color:"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Keep the original shape"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Help"
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid ""
|
||||
"Select one or more closed shapes (or groups), then run the extension. Each shape is filled with a Turing maze: winding lines of constant width that branch and end in round tips.\n"
|
||||
"\n"
|
||||
"Each line is drawn once, along its center, with a round-capped stroke of the chosen width: ready for line engraving on a laser cutter. The lines are chained and ordered to limit idle travel of the laser head.\n"
|
||||
"\n"
|
||||
"Period: distance between the centers of two neighbouring lines. Line width: stroke thickness; keep it below the period (about half gives as much black as white). Margin: free space between the shape edge and the strokes.\n"
|
||||
"\n"
|
||||
"Iterations: how long the pattern evolves. Few iterations leave dots and short lines, many give long regular lines. The seed changes the drawing while keeping the same look.\n"
|
||||
"\n"
|
||||
"At the shape edge: cut the lines like a piece of fabric, or let them stop before the edge and run along it.\n"
|
||||
"\n"
|
||||
"The result is placed in a group just above each shape. Large shapes with a small period take a few seconds."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Select at least one closed shape (path, rectangle, circle, ellipse, polygon) or a group containing some."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The period and the line width must be strictly positive."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The line width must be smaller than the period, otherwise neighbouring lines merge. Reduce the line width or increase the period."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The shape is too large for this period: the computation would take too long. Increase the period or split the shape."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "{} shape(s) too narrow for the pattern: reduce the line width, the period or the margin."
|
||||
msgstr ""
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Dog Bandana pattern"
|
||||
msgstr ""
|
||||
@@ -0,0 +1,124 @@
|
||||
# Traduction (en) de l'extension Inkscape « Dog Bandana Pattern Fill ».
|
||||
# Genere par i18n.py ; ne modifier que les msgstr.
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: dogbandana\n"
|
||||
"Language: en\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Dog Bandana Pattern Fill"
|
||||
msgstr "Dog Bandana Pattern Fill"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Pattern"
|
||||
msgstr "Pattern"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Period (line spacing, center to center):"
|
||||
msgstr "Period (line spacing, center to center):"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line width:"
|
||||
msgstr "Line width:"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Margin from the shape edge:"
|
||||
msgstr "Margin from the shape edge:"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Unit:"
|
||||
msgstr "Unit:"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Iterations (more = longer, smoother lines):"
|
||||
msgstr "Iterations (more = longer, smoother lines):"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Few iterations leave many dots and short lines; many iterations give long, regular lines."
|
||||
msgstr "Few iterations leave many dots and short lines; many iterations give long, regular lines."
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Random seed (another number, another maze):"
|
||||
msgstr "Random seed (another number, another maze):"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "At the shape edge:"
|
||||
msgstr "At the shape edge:"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Cut the lines (like cut fabric)"
|
||||
msgstr "Cut the lines (like cut fabric)"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Lines follow the edge"
|
||||
msgstr "Lines follow the edge"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Style"
|
||||
msgstr "Style"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line color:"
|
||||
msgstr "Line color:"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Keep the original shape"
|
||||
msgstr "Keep the original shape"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Help"
|
||||
msgstr "Help"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid ""
|
||||
"Select one or more closed shapes (or groups), then run the extension. Each shape is filled with a Turing maze: winding lines of constant width that branch and end in round tips.\n"
|
||||
"\n"
|
||||
"Each line is drawn once, along its center, with a round-capped stroke of the chosen width: ready for line engraving on a laser cutter. The lines are chained and ordered to limit idle travel of the laser head.\n"
|
||||
"\n"
|
||||
"Period: distance between the centers of two neighbouring lines. Line width: stroke thickness; keep it below the period (about half gives as much black as white). Margin: free space between the shape edge and the strokes.\n"
|
||||
"\n"
|
||||
"Iterations: how long the pattern evolves. Few iterations leave dots and short lines, many give long regular lines. The seed changes the drawing while keeping the same look.\n"
|
||||
"\n"
|
||||
"At the shape edge: cut the lines like a piece of fabric, or let them stop before the edge and run along it.\n"
|
||||
"\n"
|
||||
"The result is placed in a group just above each shape. Large shapes with a small period take a few seconds."
|
||||
msgstr ""
|
||||
"Select one or more closed shapes (or groups), then run the extension. Each shape is filled with a Turing maze: winding lines of constant width that branch and end in round tips.\n"
|
||||
"\n"
|
||||
"Each line is drawn once, along its center, with a round-capped stroke of the chosen width: ready for line engraving on a laser cutter. The lines are chained and ordered to limit idle travel of the laser head.\n"
|
||||
"\n"
|
||||
"Period: distance between the centers of two neighbouring lines. Line width: stroke thickness; keep it below the period (about half gives as much black as white). Margin: free space between the shape edge and the strokes.\n"
|
||||
"\n"
|
||||
"Iterations: how long the pattern evolves. Few iterations leave dots and short lines, many give long regular lines. The seed changes the drawing while keeping the same look.\n"
|
||||
"\n"
|
||||
"At the shape edge: cut the lines like a piece of fabric, or let them stop before the edge and run along it.\n"
|
||||
"\n"
|
||||
"The result is placed in a group just above each shape. Large shapes with a small period take a few seconds."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Select at least one closed shape (path, rectangle, circle, ellipse, polygon) or a group containing some."
|
||||
msgstr "Select at least one closed shape (path, rectangle, circle, ellipse, polygon) or a group containing some."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The period and the line width must be strictly positive."
|
||||
msgstr "The period and the line width must be strictly positive."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The line width must be smaller than the period, otherwise neighbouring lines merge. Reduce the line width or increase the period."
|
||||
msgstr "The line width must be smaller than the period, otherwise neighbouring lines merge. Reduce the line width or increase the period."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The shape is too large for this period: the computation would take too long. Increase the period or split the shape."
|
||||
msgstr "The shape is too large for this period: the computation would take too long. Increase the period or split the shape."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "{} shape(s) too narrow for the pattern: reduce the line width, the period or the margin."
|
||||
msgstr "{} shape(s) too narrow for the pattern: reduce the line width, the period or the margin."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Dog Bandana pattern"
|
||||
msgstr "Dog Bandana pattern"
|
||||
@@ -0,0 +1,124 @@
|
||||
# Traduction (fr) de l'extension Inkscape « Dog Bandana Pattern Fill ».
|
||||
# Genere par i18n.py ; ne modifier que les msgstr.
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: dogbandana\n"
|
||||
"Language: fr\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Dog Bandana Pattern Fill"
|
||||
msgstr "Remplissage par motif Dog Bandana"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Pattern"
|
||||
msgstr "Motif"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Period (line spacing, center to center):"
|
||||
msgstr "Période (écart entre les lignes, d'axe en axe) :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line width:"
|
||||
msgstr "Épaisseur du trait :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Margin from the shape edge:"
|
||||
msgstr "Marge au bord de la forme :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Unit:"
|
||||
msgstr "Unité :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Iterations (more = longer, smoother lines):"
|
||||
msgstr "Itérations (plus = lignes plus longues et régulières) :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Few iterations leave many dots and short lines; many iterations give long, regular lines."
|
||||
msgstr "Peu d'itérations laissent beaucoup de points et de lignes courtes ; beaucoup d'itérations donnent des lignes longues et régulières."
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Random seed (another number, another maze):"
|
||||
msgstr "Graine aléatoire (autre nombre, autre labyrinthe) :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "At the shape edge:"
|
||||
msgstr "Au bord de la forme :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Cut the lines (like cut fabric)"
|
||||
msgstr "Couper les lignes (comme un tissu découpé)"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Lines follow the edge"
|
||||
msgstr "Les lignes longent le bord"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Style"
|
||||
msgstr "Style"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Line color:"
|
||||
msgstr "Couleur du trait :"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Keep the original shape"
|
||||
msgstr "Conserver la forme d'origine"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid "Help"
|
||||
msgstr "Aide"
|
||||
|
||||
#: dog_bandana.inx
|
||||
msgid ""
|
||||
"Select one or more closed shapes (or groups), then run the extension. Each shape is filled with a Turing maze: winding lines of constant width that branch and end in round tips.\n"
|
||||
"\n"
|
||||
"Each line is drawn once, along its center, with a round-capped stroke of the chosen width: ready for line engraving on a laser cutter. The lines are chained and ordered to limit idle travel of the laser head.\n"
|
||||
"\n"
|
||||
"Period: distance between the centers of two neighbouring lines. Line width: stroke thickness; keep it below the period (about half gives as much black as white). Margin: free space between the shape edge and the strokes.\n"
|
||||
"\n"
|
||||
"Iterations: how long the pattern evolves. Few iterations leave dots and short lines, many give long regular lines. The seed changes the drawing while keeping the same look.\n"
|
||||
"\n"
|
||||
"At the shape edge: cut the lines like a piece of fabric, or let them stop before the edge and run along it.\n"
|
||||
"\n"
|
||||
"The result is placed in a group just above each shape. Large shapes with a small period take a few seconds."
|
||||
msgstr ""
|
||||
"Sélectionnez une ou plusieurs formes fermées (ou des groupes), puis lancez l'extension. Chaque forme est remplie d'un labyrinthe de Turing : des lignes sinueuses d'épaisseur constante, qui bifurquent et se terminent en bouts ronds.\n"
|
||||
"\n"
|
||||
"Chaque ligne est tracée une seule fois, selon son axe, avec un trait à bouts ronds de l'épaisseur choisie : prête pour la gravure laser en mode ligne. Les lignes sont enchaînées et ordonnées pour limiter les déplacements à vide de la tête du laser.\n"
|
||||
"\n"
|
||||
"Période : distance entre les axes de deux lignes voisines. Épaisseur du trait : à garder sous la période (la moitié donne autant de noir que de blanc). Marge : espace libre entre le bord de la forme et les traits.\n"
|
||||
"\n"
|
||||
"Itérations : durée d'évolution du motif. Peu d'itérations laissent des points et des lignes courtes, beaucoup donnent de longues lignes régulières. La graine change le dessin en gardant le même aspect.\n"
|
||||
"\n"
|
||||
"Au bord de la forme : couper les lignes comme un morceau de tissu, ou les arrêter avant le bord pour qu'elles le longent.\n"
|
||||
"\n"
|
||||
"Le résultat est placé dans un groupe juste au-dessus de chaque forme. Une grande forme avec une petite période demande quelques secondes."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Select at least one closed shape (path, rectangle, circle, ellipse, polygon) or a group containing some."
|
||||
msgstr "Sélectionnez au moins une forme fermée (chemin, rectangle, cercle, ellipse, polygone) ou un groupe qui en contient."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The period and the line width must be strictly positive."
|
||||
msgstr "La période et l'épaisseur du trait doivent être strictement positives."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The line width must be smaller than the period, otherwise neighbouring lines merge. Reduce the line width or increase the period."
|
||||
msgstr "L'épaisseur du trait doit être inférieure à la période, sinon les lignes voisines se touchent. Réduisez l'épaisseur ou augmentez la période."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "The shape is too large for this period: the computation would take too long. Increase the period or split the shape."
|
||||
msgstr "La forme est trop grande pour cette période : le calcul serait trop long. Augmentez la période ou découpez la forme."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "{} shape(s) too narrow for the pattern: reduce the line width, the period or the margin."
|
||||
msgstr "{} forme(s) trop étroite(s) pour le motif : réduisez l'épaisseur du trait, la période ou la marge."
|
||||
|
||||
#: dog_bandana.py
|
||||
msgid "Dog Bandana pattern"
|
||||
msgstr "Motif Dog Bandana"
|
||||
@@ -0,0 +1,359 @@
|
||||
# coding=utf-8
|
||||
"""Tests de l'extension « Dog Bandana » (pytest)."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import pytest
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from dog_bandana_core import (chain_polylines, erode, grid_pixels, laser_order,
|
||||
order_polylines, parse_color, polylines_to_d,
|
||||
rasterize, simplify_polyline, skeletonize,
|
||||
smooth_polyline, trace_skeleton, travel_length,
|
||||
turing_pattern)
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SHAPES = os.path.join(HERE, "tests", "data", "shapes.svg")
|
||||
SCALED = os.path.join(HERE, "tests", "data", "scaled.svg")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Noyau (sans inkex)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def test_parse_color_inkscape_integer():
|
||||
assert parse_color("3014898687") == ("#b3b3b3", 1.0)
|
||||
assert parse_color(str(0xFF000080)) == ("#ff0000", round(0x80 / 255, 4))
|
||||
|
||||
|
||||
def test_parse_color_hex_and_invalid():
|
||||
assert parse_color("#123456") == ("#123456", 1.0)
|
||||
assert parse_color("#abc") == ("#aabbcc", 1.0)
|
||||
assert parse_color("pas une couleur") == ("#b3b3b3", 1.0)
|
||||
|
||||
|
||||
def test_polylines_to_d():
|
||||
d = polylines_to_d([[(0, 0), (1, 2)], [(3, 4), (5, 6)]], precision=1)
|
||||
assert d == "M 0.0,0.0 L 1.0,2.0 M 3.0,4.0 L 5.0,6.0"
|
||||
|
||||
|
||||
def covered_segments(polylines):
|
||||
"""Segments (arrondis, sens indifferent) couverts par des polylignes."""
|
||||
out = []
|
||||
for line in polylines:
|
||||
for p, q in zip(line, line[1:]):
|
||||
a, b = tuple(round(v, 6) for v in p), tuple(round(v, 6) for v in q)
|
||||
out.append(min((a, b), (b, a)))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def test_chain_polylines_joins_touching_lines():
|
||||
# Un « Y » (4 noeuds impairs : 2 traits au minimum) et un trait isole.
|
||||
y_shape = [[(0, 0), (0, -1)], [(0, 0), (1, 1)], [(-1, 1), (0, 0)]]
|
||||
lone = [[(5, 5), (6, 5), (7, 6)]]
|
||||
chained = chain_polylines(y_shape + lone)
|
||||
assert len(chained) == 3
|
||||
assert covered_segments(chained) == covered_segments(y_shape + lone)
|
||||
|
||||
|
||||
def test_chain_polylines_closed_circuit():
|
||||
square = [[(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), (0, 1)], [(0, 1), (0, 0)]]
|
||||
chained = chain_polylines(square)
|
||||
assert len(chained) == 1 and len(chained[0]) == 5
|
||||
assert chained[0][0] == chained[0][-1]
|
||||
|
||||
|
||||
def test_order_polylines_nearest_and_reversed():
|
||||
lines = [[(10, 0), (20, 0)], [(3, 0), (1, 0)], [(30, 0), (21, 0)]]
|
||||
ordered = order_polylines(lines, start=(0, 0))
|
||||
assert ordered == [[(1, 0), (3, 0)], [(10, 0), (20, 0)], [(21, 0), (30, 0)]]
|
||||
assert travel_length(ordered) == pytest.approx(1 + 7 + 1)
|
||||
|
||||
|
||||
def test_order_polylines_rotates_loops():
|
||||
loop = [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]
|
||||
ordered = order_polylines([loop], start=(11, 11))
|
||||
assert ordered[0][0] == ordered[0][-1] == (10, 10)
|
||||
assert len(ordered[0]) == 5
|
||||
|
||||
|
||||
def test_laser_order_cuts_travel_on_a_grid():
|
||||
# Quadrillage de segments unitaires dans un ordre defavorable.
|
||||
segments = [[(x, y), (x + 1, y)] for x in range(20) for y in range(0, 20, 2)]
|
||||
segments += [[(x, y), (x, y + 1)] for y in range(20) for x in range(0, 20, 2)]
|
||||
segments = segments[::2] + segments[1::2]
|
||||
ordered = laser_order(segments)
|
||||
assert covered_segments(ordered) == covered_segments(segments)
|
||||
assert travel_length(ordered) < travel_length(segments) / 4
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Motif de Turing : etapes
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def test_rasterize_square_with_hole_even_odd():
|
||||
outer = [(0, 0), (10, 0), (10, 10), (0, 10)]
|
||||
hole = [(3, 3), (7, 3), (7, 7), (3, 7)]
|
||||
mask = rasterize([outer, hole], 0, 0, 1.0, 12, 12)
|
||||
assert mask.sum() == 100 - 16
|
||||
assert mask[1, 1] and not mask[5, 5] and not mask[11, 11]
|
||||
|
||||
|
||||
def test_rasterize_vertex_on_scanline_counted_once():
|
||||
# Sommets de ce losange exactement sur les centres de lignes de pixels.
|
||||
diamond = [(5, 0.5), (9.5, 5.5), (5, 10.5), (0.5, 5.5)]
|
||||
mask = rasterize([diamond], 0, 0, 1.0, 10, 11)
|
||||
for row in mask: # chaque ligne : un seul segment
|
||||
assert np.count_nonzero(np.diff(row.astype(int))) <= 2
|
||||
|
||||
|
||||
def test_erode_shrinks_by_radius():
|
||||
mask = np.zeros((40, 40), dtype=bool)
|
||||
mask[10:30, 10:30] = True
|
||||
eroded = erode(mask, 3)
|
||||
rows = np.nonzero(eroded.any(axis=1))[0]
|
||||
assert rows[0] == 13 and rows[-1] == 26
|
||||
assert erode(mask, 0).sum() == mask.sum()
|
||||
|
||||
|
||||
def test_skeletonize_bar_to_single_line():
|
||||
bar = np.zeros((15, 40), dtype=bool)
|
||||
bar[5:10, 5:35] = True
|
||||
skeleton = skeletonize(bar)
|
||||
assert skeleton.any()
|
||||
assert skeleton.sum(axis=0).max() == 1 # un pixel par colonne
|
||||
assert (skeleton <= bar).all()
|
||||
|
||||
|
||||
def test_trace_skeleton_line_cross_dot_and_loop():
|
||||
img = np.zeros((30, 30), dtype=bool)
|
||||
img[2, 2:12] = True # segment
|
||||
img[20, 5] = True # point isole
|
||||
lines = trace_skeleton(img)
|
||||
assert sorted(len(line) for line in lines) == [1, 10]
|
||||
|
||||
cross = np.zeros((21, 21), dtype=bool)
|
||||
cross[10, :] = True
|
||||
cross[:, 10] = True
|
||||
assert len(trace_skeleton(cross)) == 4
|
||||
|
||||
loop = np.zeros((12, 12), dtype=bool)
|
||||
loop[2, 2:9] = loop[8, 2:9] = loop[2:9, 2] = loop[2:9, 8] = True
|
||||
lines = trace_skeleton(loop)
|
||||
assert len(lines) == 1 and lines[0][0] == lines[0][-1]
|
||||
|
||||
|
||||
def test_trace_skeleton_prunes_short_spurs():
|
||||
img = np.zeros((20, 30), dtype=bool)
|
||||
img[10, 2:28] = True
|
||||
img[8:10, 15] = True # ergot de 2 pixels
|
||||
assert len(trace_skeleton(img)) == 3
|
||||
assert len(trace_skeleton(img, min_spur=4)) == 2
|
||||
|
||||
|
||||
def test_smooth_keeps_ends_and_loops():
|
||||
zigzag = [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]
|
||||
smooth = smooth_polyline(zigzag, 3)
|
||||
assert smooth[0] == (0, 0) and smooth[-1] == (4, 0)
|
||||
assert max(y for _x, y in smooth[1:-1]) < 1
|
||||
loop = [(0, 0), (4, 0), (4, 4), (0, 4), (0, 0)]
|
||||
smooth = smooth_polyline(loop, 2)
|
||||
assert smooth[0] == smooth[-1] and len(smooth) == 5
|
||||
|
||||
|
||||
def test_simplify_straight_line():
|
||||
line = [(x, 0.001 * (x % 2)) for x in range(20)]
|
||||
assert simplify_polyline(line, 0.01) == [(0.0, 0.0), (19.0, 0.001)]
|
||||
corner = [(0, 0), (5, 0), (5, 5)]
|
||||
assert len(simplify_polyline(corner, 0.1)) == 3
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Motif de Turing : resultat
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
RECT = [[(0, 0), (60, 0), (60, 40), (0, 40)]]
|
||||
|
||||
|
||||
def polyline_length(line):
|
||||
return sum(math.hypot(q[0] - p[0], q[1] - p[1]) for p, q in zip(line, line[1:]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("edge", ["cut", "follow"])
|
||||
def test_pattern_stays_inside_with_margin(edge):
|
||||
period, width, margin = 4.0, 2.0, 1.5
|
||||
lines = turing_pattern(RECT, period, width, margin, seed=3, edge=edge)
|
||||
assert lines
|
||||
inset = margin + width / 2
|
||||
tolerance = period / 8 # un pixel de calcul
|
||||
for line in lines:
|
||||
for x, y in line:
|
||||
assert inset - tolerance <= x <= 60 - inset + tolerance
|
||||
assert inset - tolerance <= y <= 40 - inset + tolerance
|
||||
|
||||
|
||||
def test_pattern_density_matches_period():
|
||||
"""Longueur des lignes ~ aire / periode : bandes espacees d'une periode."""
|
||||
period = 4.0
|
||||
lines = turing_pattern(RECT, period, 2.0, seed=1)
|
||||
total = sum(polyline_length(line) for line in lines)
|
||||
ratio = total * period / (60 * 40)
|
||||
assert 0.6 < ratio < 1.2
|
||||
|
||||
|
||||
def test_pattern_reproducible_and_seeded():
|
||||
a = turing_pattern(RECT, 4.0, 2.0, seed=7)
|
||||
assert a == turing_pattern(RECT, 4.0, 2.0, seed=7)
|
||||
assert a != turing_pattern(RECT, 4.0, 2.0, seed=8)
|
||||
|
||||
|
||||
def test_more_iterations_give_fewer_longer_lines():
|
||||
few = turing_pattern(RECT, 4.0, 2.0, seed=2, steps=30)
|
||||
many = turing_pattern(RECT, 4.0, 2.0, seed=2, steps=300)
|
||||
assert len(many) < len(few)
|
||||
|
||||
|
||||
def test_pattern_respects_holes():
|
||||
outer = [(0, 0), (60, 0), (60, 60), (0, 60)]
|
||||
hole = [(20, 20), (40, 20), (40, 40), (20, 40)]
|
||||
lines = turing_pattern([outer, hole], 4.0, 2.0, seed=1)
|
||||
inside = [(x, y) for line in lines for x, y in line
|
||||
if 21.5 < x < 38.5 and 21.5 < y < 38.5]
|
||||
assert not inside
|
||||
|
||||
|
||||
def test_pattern_empty_cases():
|
||||
assert turing_pattern([], 4.0, 2.0) == []
|
||||
assert turing_pattern(RECT, 0, 2.0) == []
|
||||
# Bande plus etroite que le trait : rien a dessiner.
|
||||
assert turing_pattern([[(0, 0), (60, 0), (60, 1.5), (0, 1.5)]], 4.0, 2.0) == []
|
||||
|
||||
|
||||
def test_dots_are_two_point_polylines():
|
||||
lines = turing_pattern(RECT, 4.0, 2.0, seed=1, steps=20)
|
||||
assert all(len(line) >= 2 for line in lines)
|
||||
|
||||
|
||||
def test_grid_pixels():
|
||||
assert grid_pixels([], 4.0) == 0
|
||||
assert grid_pixels(RECT, 4.0) == (120 + 32) * (80 + 32)
|
||||
|
||||
|
||||
def test_laser_order_cuts_travel_on_pattern():
|
||||
lines = turing_pattern(RECT, 4.0, 2.0, seed=1)
|
||||
ordered = laser_order(lines)
|
||||
assert travel_length(ordered) < travel_length(lines) / 3
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Bout en bout (necessite inkex)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def run_extension(tmp_path, *args, source=SHAPES):
|
||||
pytest.importorskip("inkex")
|
||||
from dog_bandana import DogBandana
|
||||
out = tmp_path / "out.svg"
|
||||
DogBandana().run([*args, "--output={}".format(out), source])
|
||||
return out.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_end_to_end_default(tmp_path):
|
||||
svg = run_extension(tmp_path, "--id=rect1")
|
||||
assert "Dog Bandana pattern" in svg
|
||||
assert 'id="rect1"' in svg
|
||||
assert "stroke-linecap:round" in svg
|
||||
|
||||
|
||||
def test_end_to_end_group_and_holes(tmp_path):
|
||||
svg = run_extension(tmp_path, "--id=group1", "--id=path2")
|
||||
assert svg.count("Dog Bandana pattern") == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args, message", [
|
||||
(["--line_width=5", "--period=4"], "smaller than the period"),
|
||||
(["--margin=30"], "too narrow"),
|
||||
])
|
||||
def test_end_to_end_errors(tmp_path, capsys, args, message):
|
||||
# Document inchange : inkex n'ecrit pas de sortie, seul le message compte.
|
||||
pytest.importorskip("inkex")
|
||||
from dog_bandana import DogBandana
|
||||
DogBandana().run(["--id=rect1", *args,
|
||||
"--output={}".format(tmp_path / "out.svg"), SHAPES])
|
||||
assert message in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_end_to_end_non_standard_document_scale(tmp_path):
|
||||
"""Page de 400 mm pour 538,72 unites : svg.unittouu() s'y tromperait."""
|
||||
svg = run_extension(tmp_path, "--id=rect1", source=SCALED)
|
||||
width = re.search(r"stroke-width:([\d.]+)", svg)
|
||||
assert float(width.group(1)) == pytest.approx(2.0 * 538.72053 / 400, abs=0.001)
|
||||
|
||||
|
||||
def test_end_to_end_removes_original(tmp_path):
|
||||
svg = run_extension(tmp_path, "--id=rect1", "--keep_original=false")
|
||||
assert 'id="rect1"' not in svg
|
||||
|
||||
|
||||
def test_end_to_end_color(tmp_path):
|
||||
svg = run_extension(tmp_path, "--id=rect1", "--stroke_color={}".format(0x336699FF))
|
||||
assert re.search(r"stroke:#336699", svg)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Traductions
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def test_translations_up_to_date_and_complete():
|
||||
"""Chaque texte du .inx et des .py a sa traduction dans chaque catalogue."""
|
||||
import gettext
|
||||
import i18n
|
||||
|
||||
msgids = [msgid for msgid, _refs in i18n.extract()]
|
||||
assert "Dog Bandana Pattern Fill" in msgids
|
||||
assert "mm" not in msgids # unites marquees translatable="no"
|
||||
|
||||
for language in i18n.LANGUAGES:
|
||||
entries = i18n.read_po(i18n.po_path(language))
|
||||
missing = [m for m in msgids if not entries.get(m, ("", False))[0]]
|
||||
assert not missing, "{}.po incomplet : {}".format(language, missing)
|
||||
|
||||
catalog = gettext.translation(i18n.DOMAIN, i18n.LOCALE_DIR, [language])
|
||||
for msgid in msgids:
|
||||
assert catalog.gettext(msgid) == entries[msgid][0], \
|
||||
"{} : .mo a recompiler (python i18n.py)".format(language)
|
||||
|
||||
|
||||
def test_po_roundtrip(tmp_path):
|
||||
import i18n
|
||||
|
||||
messages = [("Simple", ["a"]), ('Quote "x" and \\ back', ["a"]),
|
||||
("Two\nlines", ["a"]), ("Tab\tend\n", ["a"])]
|
||||
path = str(tmp_path / "xx.po")
|
||||
i18n.write_po(path, "fr", messages,
|
||||
{m: ("<" + m + ">", False) for m, _r in messages})
|
||||
entries = i18n.read_po(path)
|
||||
for msgid, _refs in messages:
|
||||
assert entries[msgid] == ("<" + msgid + ">", False)
|
||||
|
||||
|
||||
def test_inx_matches_arguments():
|
||||
"""Chaque <param> du .inx a son add_argument, et inversement."""
|
||||
root = ET.parse(os.path.join(HERE, "dog_bandana.inx")).getroot()
|
||||
params = {elem.get("name") for elem in root.iter()
|
||||
if elem.tag.rsplit("}", 1)[-1] == "param"}
|
||||
with open(os.path.join(HERE, "dog_bandana.py"), encoding="utf-8") as handle:
|
||||
arguments = set(re.findall(r'add_argument\("--(\w+)"', handle.read()))
|
||||
assert params == arguments
|
||||
|
||||
|
||||
def test_inx_images_exist():
|
||||
"""Les images de la boite de dialogue sont presentes (chemin relatif au .inx)."""
|
||||
root = ET.parse(os.path.join(HERE, "dog_bandana.inx")).getroot()
|
||||
for elem in root.iter():
|
||||
if elem.tag.rsplit("}", 1)[-1] == "image":
|
||||
assert os.path.isfile(os.path.join(HERE, elem.text.strip())), elem.text
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Echelle non standard (page redimensionnee) : 1 mm = 1,3468 unite utilisateur -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="400mm" height="400mm"
|
||||
viewBox="0 0 538.72053 538.72054">
|
||||
<rect id="rect1" x="100" y="100" width="200" height="100" fill="#e9ecef" stroke="#212529"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 334 B |
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="200mm" height="120mm" viewBox="0 0 200 120">
|
||||
<rect id="rect1" x="10" y="10" width="50" height="40" fill="#e9ecef" stroke="#212529"/>
|
||||
<circle id="circle1" cx="100" cy="30" r="22" fill="#e9ecef" stroke="#212529"/>
|
||||
<path id="path1" d="M 140,10 C 190,0 200,60 160,55 C 130,52 120,30 140,10 Z"
|
||||
fill="#e9ecef" stroke="#212529"/>
|
||||
<!-- Forme trouee : le sous-chemin interne est un trou (pair-impair) -->
|
||||
<path id="path2" d="M 10,65 H 90 V 115 H 10 Z M 35,80 H 65 V 100 H 35 Z"
|
||||
fill="#e9ecef" fill-rule="evenodd" stroke="#212529"/>
|
||||
<g id="group1" transform="translate(100,65)">
|
||||
<ellipse id="ellipse1" cx="45" cy="25" rx="40" ry="20" fill="#e9ecef" stroke="#212529"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 790 B |
Reference in new issue
Block a user