Optimisation des déplacements
This commit is contained in:
1 parent
99c30068fc
commit
437345c9b7
4 files changed
+229
-9
No files matched your search
@@ -36,6 +36,9 @@ résultat tient dans un seul chemin par forme.
|
|||||||
document (motif continu d'une forme à l'autre).
|
document (motif continu d'une forme à l'autre).
|
||||||
- Segments alignés fusionnés : peu de nœuds, un seul chemin par forme, pas de
|
- Segments alignés fusionnés : peu de nœuds, un seul chemin par forme, pas de
|
||||||
`transform` sur les chemins produits.
|
`transform` sur les chemins produits.
|
||||||
|
- Ordre de gravure optimisé pour la découpeuse laser : les traits qui se
|
||||||
|
touchent sont enchaînés en polylignes continues, et chaque polyligne démarre
|
||||||
|
au plus près de la fin de la précédente (trajets à vide divisés par ~10).
|
||||||
- Option : tracer aussi le contour de la forme ; option : conserver ou supprimer
|
- Option : tracer aussi le contour de la forme ; option : conserver ou supprimer
|
||||||
la forme d'origine.
|
la forme d'origine.
|
||||||
- Garde-fou : refus au-delà de 250 000 segments, avec un message d'aide.
|
- Garde-fou : refus au-delà de 250 000 segments, avec un message d'aide.
|
||||||
@@ -135,6 +138,9 @@ API du noyau (`relief_core.py`) :
|
|||||||
| `rotate_point(point, angle, center)` | Rotation (sens horaire à l'écran) |
|
| `rotate_point(point, angle, center)` | Rotation (sens horaire à l'écran) |
|
||||||
| `rings_bbox(rings)` | Boîte englobante |
|
| `rings_bbox(rings)` | Boîte englobante |
|
||||||
| `segments_to_polylines(segments)` / `polylines_to_d(polylines)` | Conversion vers les données `d` d'un chemin SVG |
|
| `segments_to_polylines(segments)` / `polylines_to_d(polylines)` | Conversion vers les données `d` d'un chemin SVG |
|
||||||
|
| `chain_segments(segments)` | Enchaîne les segments qui se touchent en polylignes |
|
||||||
|
| `order_polylines(polylines, start)` | Ordre plus-proche-voisin (sens inversé, boucles tournées) pour limiter les trajets à vide |
|
||||||
|
| `travel_length(polylines, start)` | Longueur des déplacements à vide de la tête |
|
||||||
| `parse_color(value)` | Couleur Inkscape (entier RGBA) → `#rrggbb` + opacité |
|
| `parse_color(value)` | Couleur Inkscape (entier RGBA) → `#rrggbb` + opacité |
|
||||||
|
|
||||||
## Développement
|
## Développement
|
||||||
|
|||||||
+148
@@ -293,3 +293,151 @@ def _to_world(point, angle, anchor):
|
|||||||
def segments_to_polylines(segments):
|
def segments_to_polylines(segments):
|
||||||
"""Segments -> polylines a deux points (pour polylines_to_d)."""
|
"""Segments -> polylines a deux points (pour polylines_to_d)."""
|
||||||
return [[p, q] for p, q in segments]
|
return [[p, q] for p, q in segments]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ordre de gravure
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
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 chain_segments(segments):
|
||||||
|
"""Segments -> polylignes : les segments qui se touchent sont mis bout a bout.
|
||||||
|
|
||||||
|
Le laser parcourt alors chaque polyligne d'un trait, sans lever la tete.
|
||||||
|
On part d'abord des noeuds de degre impair (bouts de branche, centres des
|
||||||
|
« Y ») : un parcours qui y commence ne peut s'arreter que sur un autre
|
||||||
|
noeud impair, ce qui limite le nombre de polylignes, donc de sauts a vide.
|
||||||
|
"""
|
||||||
|
points = {}
|
||||||
|
adjacency = {} # noeud -> [(numero du segment, voisin)]
|
||||||
|
for index, (p, q) in enumerate(segments):
|
||||||
|
a, b = _key(p), _key(q)
|
||||||
|
if a == b:
|
||||||
|
continue
|
||||||
|
points.setdefault(a, p)
|
||||||
|
points.setdefault(b, q)
|
||||||
|
adjacency.setdefault(a, []).append((index, b))
|
||||||
|
adjacency.setdefault(b, []).append((index, a))
|
||||||
|
used = [False] * len(segments)
|
||||||
|
|
||||||
|
def free_edges(node):
|
||||||
|
edges = adjacency[node]
|
||||||
|
edges[:] = [edge for edge in edges if not used[edge[0]]]
|
||||||
|
return edges
|
||||||
|
|
||||||
|
def walk(node):
|
||||||
|
line = [points[node]]
|
||||||
|
while True:
|
||||||
|
edges = free_edges(node)
|
||||||
|
if not edges:
|
||||||
|
return line
|
||||||
|
index, node = edges.pop()
|
||||||
|
used[index] = True
|
||||||
|
line.append(points[node])
|
||||||
|
|
||||||
|
polylines = []
|
||||||
|
for node in adjacency:
|
||||||
|
if len(free_edges(node)) % 2:
|
||||||
|
polylines.append(walk(node))
|
||||||
|
for node in adjacency: # reste : boucles fermees
|
||||||
|
while free_edges(node):
|
||||||
|
polylines.append(walk(node))
|
||||||
|
return polylines
|
||||||
|
|
||||||
|
|
||||||
|
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 = [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 len(line) > 2 and _key(line[0]) == _key(line[-1]):
|
||||||
|
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 k == len(line) - 1 and _key(line[0]) != _key(line[-1]):
|
||||||
|
line = line[::-1]
|
||||||
|
else: # boucle : rotation
|
||||||
|
line = line[k:-1] + line[:k] + [line[k]]
|
||||||
|
ordered.append(line)
|
||||||
|
position = line[-1]
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
+9
-3
@@ -24,8 +24,9 @@ from inkex.units import convert_unit
|
|||||||
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver relief_core.
|
# n'est pas forcement dans sys.path : on l'y ajoute pour trouver relief_core.
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
from relief_core import (fill_rings, parse_color, polylines_to_d, # noqa: E402
|
from relief_core import (chain_segments, fill_rings, # noqa: E402
|
||||||
rings_bbox, segments_to_polylines)
|
order_polylines, parse_color, polylines_to_d,
|
||||||
|
rings_bbox)
|
||||||
|
|
||||||
|
|
||||||
def use_system_language():
|
def use_system_language():
|
||||||
@@ -149,6 +150,7 @@ class ReliefFill(inkex.EffectExtension):
|
|||||||
"stroke-linejoin": "round",
|
"stroke-linejoin": "round",
|
||||||
})
|
})
|
||||||
flatness = length_to_uu(self.svg, 0.02) # 0.02 mm : invisible a l'impression
|
flatness = length_to_uu(self.svg, 0.02) # 0.02 mm : invisible a l'impression
|
||||||
|
self.head = (0.0, 0.0) # position de la tete du laser (origine)
|
||||||
|
|
||||||
for elem in elements:
|
for elem in elements:
|
||||||
shapes = [e for e in elem.descendants() if isinstance(e, SHAPE_TYPES)]
|
shapes = [e for e in elem.descendants() if isinstance(e, SHAPE_TYPES)]
|
||||||
@@ -206,8 +208,12 @@ class ReliefFill(inkex.EffectExtension):
|
|||||||
outline.style = style
|
outline.style = style
|
||||||
group.add(outline)
|
group.add(outline)
|
||||||
if segments:
|
if segments:
|
||||||
|
# Traits enchaines, puis ordonnes depuis la position de la
|
||||||
|
# tete laissee par la forme precedente : moins de trajets a vide.
|
||||||
|
polylines = order_polylines(chain_segments(segments), self.head)
|
||||||
|
self.head = polylines[-1][-1]
|
||||||
node = inkex.PathElement()
|
node = inkex.PathElement()
|
||||||
node.path = polylines_to_d(segments_to_polylines(segments), precision=3)
|
node.path = polylines_to_d(polylines, precision=3)
|
||||||
node.style = style
|
node.style = style
|
||||||
group.add(node)
|
group.add(node)
|
||||||
|
|
||||||
|
|||||||
+66
-6
@@ -9,9 +9,10 @@ import pytest
|
|||||||
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
from relief_core import (CELL_EDGES, clip_segment, fill_rings, parse_color,
|
from relief_core import (CELL_EDGES, chain_segments, clip_segment, fill_rings,
|
||||||
pattern_segments, point_in_rings, polylines_to_d,
|
order_polylines, parse_color, pattern_segments,
|
||||||
rotate_point)
|
point_in_rings, polylines_to_d, rotate_point,
|
||||||
|
travel_length)
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
SHAPES = os.path.join(HERE, "tests", "data", "shapes.svg")
|
SHAPES = os.path.join(HERE, "tests", "data", "shapes.svg")
|
||||||
@@ -168,6 +169,54 @@ def test_rotate_point_clockwise_on_screen():
|
|||||||
assert (round(x, 6), round(y, 6)) == (0, 1)
|
assert (round(x, 6), round(y, 6)) == (0, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def polyline_segments(polylines):
|
||||||
|
"""Segments (cles arrondies, sens indifferent) couverts par des polylignes."""
|
||||||
|
out = []
|
||||||
|
for line in polylines:
|
||||||
|
for p, q in zip(line, line[1:]):
|
||||||
|
out.append(min(key((p, q)), key((q, p))))
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def test_chain_segments_joins_touching_segments():
|
||||||
|
# Un « Y » (4 noeuds impairs : 2 traits au minimum) et un trait isole.
|
||||||
|
y_shape = [((0, 0), (0, -1)), ((0, 0), (1, 1)), ((0, 0), (-1, 1))]
|
||||||
|
lone = [((5, 5), (6, 5))]
|
||||||
|
polylines = chain_segments(y_shape + lone)
|
||||||
|
assert len(polylines) == 3
|
||||||
|
assert polyline_segments(polylines) == polyline_segments([[p, q] for p, q in y_shape + lone])
|
||||||
|
|
||||||
|
|
||||||
|
def test_chain_segments_closed_loop():
|
||||||
|
square = [((0, 0), (1, 0)), ((1, 0), (1, 1)), ((1, 1), (0, 1)), ((0, 1), (0, 0))]
|
||||||
|
polylines = chain_segments(square)
|
||||||
|
assert len(polylines) == 1 and len(polylines[0]) == 5
|
||||||
|
assert polylines[0][0] == polylines[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_fill_order_keeps_lines_and_cuts_travel():
|
||||||
|
segments = fill_rings(HOLED, 5.0, 17.0, (50, 50))
|
||||||
|
raw = [[p, q] for p, q in segments]
|
||||||
|
ordered = order_polylines(chain_segments(segments))
|
||||||
|
assert polyline_segments(ordered) == polyline_segments(raw)
|
||||||
|
assert len(ordered) < len(raw) / 2
|
||||||
|
assert travel_length(ordered) < travel_length(raw) / 4
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# Bout en bout (necessite inkex)
|
# Bout en bout (necessite inkex)
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
@@ -217,6 +266,17 @@ def generated_paths(svg_text):
|
|||||||
yield [(nums[k], nums[k + 1]) for k in range(0, len(nums) - 1, 2)]
|
yield [(nums[k], nums[k + 1]) for k in range(0, len(nums) - 1, 2)]
|
||||||
|
|
||||||
|
|
||||||
|
def generated_subpaths(svg_text):
|
||||||
|
"""Points (x, y) de chaque sous-chemin (polyligne) du groupe « Relief fill »."""
|
||||||
|
root = ET.fromstring(svg_text)
|
||||||
|
for group in root.iter("{http://www.w3.org/2000/svg}g"):
|
||||||
|
if "Relief fill" in group.attrib.values():
|
||||||
|
for path in group.iter("{http://www.w3.org/2000/svg}path"):
|
||||||
|
for sub in re.split(r"[Mm]", path.get("d"))[1:]:
|
||||||
|
nums = [float(n) for n in re.findall(r"-?\d+\.?\d*", sub)]
|
||||||
|
yield [(nums[k], nums[k + 1]) for k in range(0, len(nums) - 1, 2)]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("shape,box", [
|
@pytest.mark.parametrize("shape,box", [
|
||||||
("rect1", (10, 10, 60, 50)),
|
("rect1", (10, 10, 60, 50)),
|
||||||
("circle1", (78, 8, 122, 52)),
|
("circle1", (78, 8, 122, 52)),
|
||||||
@@ -234,10 +294,10 @@ def test_end_to_end_stays_in_bounding_box(tmp_path, shape, box):
|
|||||||
def test_end_to_end_hole_stays_empty(tmp_path):
|
def test_end_to_end_hole_stays_empty(tmp_path):
|
||||||
svg = run_extension(tmp_path, "--id=path2", "--edge=3")
|
svg = run_extension(tmp_path, "--id=path2", "--edge=3")
|
||||||
count = 0
|
count = 0
|
||||||
for pts in generated_paths(svg):
|
for pts in generated_subpaths(svg):
|
||||||
for k in range(0, len(pts) - 1, 2):
|
for p, q in zip(pts, pts[1:]):
|
||||||
count += 1
|
count += 1
|
||||||
mid = ((pts[k][0] + pts[k + 1][0]) / 2, (pts[k][1] + pts[k + 1][1]) / 2)
|
mid = ((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)
|
||||||
assert not (36 < mid[0] < 64 and 81 < mid[1] < 99)
|
assert not (36 < mid[0] < 64 and 81 < mid[1] < 99)
|
||||||
assert count > 20
|
assert count > 20
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user