#!/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
# « Diagram » de la boite de dialogue)
Les formes sont calculees par board_photo_core (memes fonctions que l'extension :
disposition et dessin des reperes, homographie), 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 board_photo_core as core # noqa: E402
W, H = 1400, 1080 # 4 panneaux de 700 x 540
PW, PH = 700, 540
INK = "#343a40" # element principal
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": "Zone de travail et repères",
"width": "Largeur", "height": "Hauteur",
"spacing_x": "Écart X", "spacing_y": "Écart Y",
"origin": "Origine (0, 0)",
"frame": "hors de portée de la laser",
"note1": ["Chaque pièce de papier touche un angle du nid d'abeille :",
"l'angle bas gauche est l'origine laser, l'écart vaut la",
"largeur (hauteur) + 2 × la taille des repères."],
"title2": "Repères à graver ou imprimer",
"ordinary": "Repère", "origin_marker": "Repère origine",
"size": "Taille", "light": "zone claire",
"note2": ["Gravés sur une plaque claire, ou imprimés (feuille A4),",
"découpés et collés sur leur gabarit de pose gravé."],
"title3": "Photo redressée à l'échelle",
"photo": "Photo (perspective)", "calibrated": "Page = zone de travail",
"note3": ["Les 4 repères donnent l'homographie : 1 mm sur la",
"photo = 1 mm dans le document (résolution en px/mm)."],
"title4": "Contour et trous",
"hole": "trou", "ignored": "ignoré (< aire mini)",
"note4": ["Contour et trous vectorisés (calque verrouillé),",
"pour placer les découpes sur la planche."],
},
},
"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": "Work area and markers",
"width": "Width", "height": "Height",
"spacing_x": "Spacing X", "spacing_y": "Spacing Y",
"origin": "Origin (0, 0)",
"frame": "out of the laser's reach",
"note1": ["Each paper piece touches a corner of the honeycomb:",
"bottom left = laser origin; spacing = width (height)",
"+ 2 x the marker size."],
"title2": "Markers to engrave or print",
"ordinary": "Marker", "origin_marker": "Origin marker",
"size": "Size", "light": "light area",
"note2": ["Engraved on a light plate, or printed (A4),",
"cut out and stuck on their placement guide."],
"title3": "Photo straightened to scale",
"photo": "Photo (perspective)", "calibrated": "Page = work area",
"note3": ["The 4 markers give the homography:",
"1 mm on the photo = 1 mm in the document."],
"title4": "Outline and holes",
"hole": "hole", "ignored": "ignored (< min area)",
"note4": ["Outline and holes vectorized (locked layer),",
"to place the cuts on the board."],
},
},
}
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(''.format(pts(points), color, fmt(width), extra))
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"
s = s.replace("&", "&").replace("<", "<").replace(">", ">")
out.append('{}'.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(''.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
if offset:
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 panel_title(x, y, number, title):
text(x, y, "{} {}".format(number, title), size=22, weight="bold", halo=False)
def fill_rings(rings, fill, stroke="none", width=0, extra=""):
"""Chemin plein pair-impair a partir d'anneaux (liste de points)."""
d = " ".join("M " + " L ".join("{},{}".format(fmt(x), fmt(y)) for x, y in ring) + " Z"
for ring in rings)
out.append(''.format(d, fill, stroke, fmt(width), extra))
# --------------------------------------------------------------------------
# Panneaux, numerotes 1 a 4, dessines avec les vraies fonctions de
# board_photo_core. Les reperes sont grossis pour rester lisibles.
# --------------------------------------------------------------------------
AREA = 400.0 # zone de travail du schema (mm)
ORIGIN, SPACING, SIZE = 45.0, 310.0, 40.0
BOARD = [(95.0, 110.0), (310.0, 95.0), (318.0, 300.0), (88.0, 312.0)]
HOLES = [((150.0, 170.0), 16.0), ((240.0, 215.0), 26.0), ((275.0, 140.0), 5.0)]
BOARD_FILL = "#e9d8b8"
BED = "#6c757d"
def work_area(transform, board=False, origin=ORIGIN, spacing=SPACING):
"""Zone de travail : fond, reperes (et planche) passes par `transform` (mm -> px)."""
def draw(rings, fill, stroke="none", width=0):
fill_rings([transform(ring) for ring in rings], fill, stroke, width)
draw([[(0, 0), (AREA, 0), (AREA, AREA), (0, AREA)]], BED, EDGE, 1.5)
centers = core.marker_layout(AREA, origin, origin, spacing, spacing)
for index, (cx, cy) in enumerate(centers):
draw([[(cx - SIZE, cy - SIZE), (cx + SIZE, cy - SIZE),
(cx + SIZE, cy + SIZE), (cx - SIZE, cy + SIZE)]], "#f8f9fa")
draw(core.marker_rings((cx, cy), SIZE, index == core.ORIGIN_MARKER), "#000000")
if board:
draw([BOARD] + [core.circle_ring(c, r) for c, r in HOLES], BOARD_FILL, EDGE, 1)
return centers
def affine(scale, ox, oy):
def transform(ring):
return core.scale_rings([ring], scale, (ox, oy))[0]
return transform
# Panneau 1 : reperes colles autour de la zone de travail (hors de portee de la
# laser), cas le plus courant ; le repere origine a donc des X, Y negatifs.
OUT_ORIGIN = -SIZE # piece (2 x SIZE) touchant l'angle
OUT_SPACING = AREA - 2 * OUT_ORIGIN
FRAME = "#ced4da"
def panel_1():
panel_title(30, 50, 1, T["title1"])
scale, ox, oy = 0.52, 215.0, 118.0
reach = -OUT_ORIGIN + SIZE + 6.0 # bord du cadre autour de la zone
frame = [(-reach, -reach), (AREA + reach, -reach), (AREA + reach, AREA + reach),
(-reach, AREA + reach)]
fill_rings(core.scale_rings([frame], scale, (ox, oy)), FRAME)
centers = work_area(affine(scale, ox, oy), origin=OUT_ORIGIN, spacing=OUT_SPACING)
def at(p):
return (ox + p[0] * scale, oy + p[1] * scale)
size = AREA * scale
tl, tr, br, bl = (at(c) for c in centers)
right, bottom = ox + size, oy + size
outer = reach * scale
text(ox + size / 2, oy - outer + 14, T["frame"], size=13, color=INK,
anchor="middle", halo=False)
dimension((ox, bottom), (right, bottom), outer + 46, T["width"], color=DIM2,
label_shift=10)
dimension((right, oy), (right, bottom), -outer - 16, T["height"], color=DIM2,
label_shift=44)
dimension(tl, tr, 46, T["spacing_x"], label_shift=-20)
dimension(tr, br, 46, T["spacing_y"], label_shift=52)
out.append(''.format(
fmt(ox), fmt(bottom), DIM))
text(ox + 12, bottom - 12, T["origin"], size=16, color=DIM, weight="bold")
note(30, 522, T["note1"])
def panel_2():
x0 = PW
panel_title(x0 + 30, 50, 2, T["title2"])
side = 72.0
for k, (origin, label) in enumerate(((False, T["ordinary"]),
(True, T["origin_marker"]))):
cx, cy = x0 + 190 + k * 320, 260
# Zone claire conseillee : deux fois la taille du repere.
out.append(''.format(
fmt(cx - side), fmt(cy - side), fmt(2 * side), fmt(2 * side), DIM2))
fill_rings(core.marker_rings((cx, cy), side, origin), "#000000")
text(cx, cy + side + 36, label, size=18, anchor="middle", weight="bold", halo=False)
text(cx - side + 6, cy + side - 10, T["light"], size=14, color=DIM2, halo=False)
dimension((cx - side / 2, cy - side / 2), (cx + side / 2, cy - side / 2), -24,
T["size"], label_shift=10)
note(x0 + 30, 520, T["note2"])
def panel_3():
y0 = PH
panel_title(30, y0 + 50, 3, T["title3"])
# Photo : zone de travail vue en perspective (homographie du noyau).
corners = [(0, 0), (AREA, 0), (AREA, AREA), (0, AREA)]
quad = [(62, y0 + 118), (290, y0 + 96), (306, y0 + 392), (40, y0 + 360)]
camera = core.homography(corners, quad)
work_area(lambda ring: core.apply_homography(camera, ring).tolist(), board=True)
text(172, y0 + 428, T["photo"], size=16, anchor="middle", halo=False)
polyline([(332, y0 + 250), (380, y0 + 250)], DIM, 3)
arrow_head((392, y0 + 250), (1, 0), DIM, 14)
scale = 0.66
work_area(affine(scale, 410, y0 + 110), board=True)
text(410 + AREA * scale / 2, y0 + 428, T["calibrated"], size=16, anchor="middle",
halo=False)
note(30, y0 + 520, T["note3"])
def panel_4():
x0, y0 = PW, PH
panel_title(x0 + 30, y0 + 50, 4, T["title4"])
scale = 1.5
ox, oy = x0 + 120 - 88 * scale, y0 + 80 - 95 * scale
def at(p):
return (ox + p[0] * scale, oy + p[1] * scale)
transform = affine(scale, ox, oy)
fill_rings([transform(r) for r in [BOARD] + [core.circle_ring(c, r)
for c, r in HOLES[:2]]],
BOARD_FILL, DIM2, 2.5)
# Petit trou sous l'aire minimale : ignore (bouche).
small = at(HOLES[2][0])
out.append(''.format(
fmt(small[0]), fmt(small[1]), fmt(HOLES[2][1] * scale)))
text(small[0], small[1] - 16, T["ignored"], size=14, anchor="middle")
hole = at(HOLES[1][0])
text(hole[0], hole[1] + 6, T["hole"], size=15, color=DIM2, anchor="middle",
halo=False)
note(x0 + 30, y0 + 520, 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(''.format(W, H))
for x1, y1, x2, y2 in ((PW, 20, PW, H - 20), (20, PH, W - 20, PH)):
out.append(''.format(x1, y1, x2, y2))
panel_1()
panel_2()
panel_3()
panel_4()
svg = ('\n'
'\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:])