Files
RoboMovel/ferramentas/scripts/cad/corte.py
T
mguinhos 6ff4800425 Projeto: suporte NEMA17 real (72 x 40, 2 oblongos por aba) e chapa da 35x35 gerada pelo modelo
- suporte_nema17.py: base 72 x 40 x 2,23, face 46 x 44,2, 4 oblongos 4,0 x 8,5
  (2 por aba) com nervurinha entre eles, conforme a peca comprada
- montagem_base_35x35.py: 4 furos e 4 parafusos M4 por motor; calcos 68 x 30;
  aberturas das nervuras redimensionadas (10 calcos saem dos miolos, 6 avulsos);
  MIOLOS, miolo() e pecas_corte() levam a regra calco-abertura para o modelo
- chapas_doc_35x35.py: exporta pecas_corte(), sem editar DXF depois
- corte.py: pecas compostas (nervura + miolos) e remocao de linhas repetidas
- DXF/SVG e documentos da 35x35 regenerados
2026-11-06 05:21:53 -03:00

240 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""Exporta as peças de MDF da montagem para corte a laser.
* planifica cada peça (face maior -> plano XY);
* gera 1 DXF (R12, mm) por peça em corte/pecas/ e chapas 900 x 600 mm
com as peças arranjadas (corte/chapa_N.dxf) + um SVG de conferência;
* camadas: CORTE (vermelho, contorno e furos).
Compensação de kerf NÃO aplicada no desenho: ajuste na máquina (tipicamente
0,08–0,12 mm por lado para MDF 3 mm) ou altere CL em montagem_base.py.
"""
import math, os, sys
sys.path.insert(0, os.path.expanduser("~/robo_movel/cad"))
import FreeCAD as App
import Part
from FreeCAD import Vector as V, Rotation, Placement
import montagem_base as MB
OUT = os.path.join(MB.CORTE)
SHEET = (900.0, 600.0)
GAP = 6.0
def flatten(shape):
faces = sorted([f for f in shape.Faces if f.Surface.__class__.__name__ == "Plane"], key=lambda f: -f.Area)
n = faces[0].normalAt(0, 0)
rot = Rotation(n, V(0, 0, 1))
s = shape.copy()
s.Placement = Placement(V(), rot).multiply(s.Placement)
bb = s.BoundBox
s.translate(V(-bb.XMin, -bb.YMin, -bb.ZMin))
# se a peça ficou "em pé" de outro jeito, garante espessura em Z
# (uma face por sólido: num composto, ex. nervura + miolos, todas as peças entram)
bots = []
for sol in (s.Solids or [s]):
fs = [f for f in sol.Faces if f.Surface.__class__.__name__ == "Plane" and abs(f.BoundBox.ZMax) < 1e-4 and abs(f.BoundBox.ZMin) < 1e-4]
if fs:
bots.append(max(fs, key=lambda f: f.Area))
bot = bots[0] if len(bots) == 1 else Part.makeCompound(bots)
# gira no plano para ficar paisagem
bb = bot.BoundBox
if bb.YLength > bb.XLength:
bot.rotate(V(0, 0, 0), V(0, 0, 1), 90)
b2 = bot.BoundBox
bot.translate(V(-b2.XMin, -b2.YMin, 0))
return bot
def edges_2d(face):
ents = []
for e in face.Edges:
c = e.Curve
cn = c.__class__.__name__
if cn == "Line" or cn == "LineSegment":
a, b = e.Vertexes[0].Point, e.Vertexes[-1].Point
ents.append(("LINE", a, b))
elif cn == "Circle" and e.isClosed():
ents.append(("CIRCLE", c.Center, c.Radius))
elif cn == "Circle":
cen = c.Center
a, b = e.Vertexes[0].Point, e.Vertexes[-1].Point
m = e.valueAt((e.FirstParameter + e.LastParameter) / 2)
ang = lambda p: math.degrees(math.atan2(p.y - cen.y, p.x - cen.x)) % 360
sa, ea, ma = ang(a), ang(b), ang(m)
# arco anti-horário de sa a ea deve conter ma
def ccw_contains(s, e_, x):
return (x - s) % 360 < (e_ - s) % 360
if not ccw_contains(sa, ea, ma):
sa, ea = ea, sa
ents.append(("ARC", cen, c.Radius, sa, ea))
else:
pts = e.discretize(Deflection=0.02)
for p, q in zip(pts[:-1], pts[1:]):
ents.append(("LINE", p, q))
return sem_repetidas(ents)
def sem_repetidas(ents, tol=1e-3):
"""Remove entidades iguais (ex.: contorno do miolo que coincide com o da abertura):
o laser não deve passar duas vezes na mesma linha."""
r = lambda v: (round(v.x / tol), round(v.y / tol))
vistos, out = set(), []
for en in ents:
if en[0] == "LINE":
chave = ("LINE",) + tuple(sorted((r(en[1]), r(en[2]))))
elif en[0] == "CIRCLE":
chave = ("CIRCLE", r(en[1]), round(en[2] / tol))
else:
chave = ("ARC", r(en[1]), round(en[2] / tol), round(en[3] % 360, 1), round(en[4] % 360, 1))
if chave not in vistos:
vistos.add(chave)
out.append(en)
return out
def dxf_write(path, groups):
"""groups: lista de (entidades, deslocamento V, rótulo)."""
L = ["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", "4", "0", "ENDSEC",
"0", "SECTION", "2", "TABLES", "0", "TABLE", "2", "LAYER", "70", "2",
"0", "LAYER", "2", "CORTE", "70", "0", "62", "1", "6", "CONTINUOUS",
"0", "LAYER", "2", "TEXTO", "70", "0", "62", "5", "6", "CONTINUOUS",
"0", "ENDTAB", "0", "ENDSEC", "0", "SECTION", "2", "ENTITIES"]
f = lambda v: "%.4f" % v
for ents, off, label in groups:
for en in ents:
if en[0] == "LINE":
a, b = en[1] + off, en[2] + off
L += ["0", "LINE", "8", "CORTE", "10", f(a.x), "20", f(a.y), "30", "0", "11", f(b.x), "21", f(b.y), "31", "0"]
elif en[0] == "CIRCLE":
c = en[1] + off
L += ["0", "CIRCLE", "8", "CORTE", "10", f(c.x), "20", f(c.y), "30", "0", "40", f(en[2])]
else:
c = en[1] + off
L += ["0", "ARC", "8", "CORTE", "10", f(c.x), "20", f(c.y), "30", "0", "40", f(en[2]), "50", f(en[3]), "51", f(en[4])]
if label:
L += ["0", "TEXT", "8", "TEXTO", "10", f(off.x + 2), "20", f(off.y + 2), "30", "0", "40", "3", "1", label]
L += ["0", "ENDSEC", "0", "EOF"]
with open(path, "w") as fh:
fh.write("\n".join(L))
def svg_write(path, sheet_items, W, H):
s = ['<svg xmlns="http://www.w3.org/2000/svg" width="%dmm" height="%dmm" viewBox="0 0 %d %d">' % (W, H, W, H),
'<rect x="0" y="0" width="%d" height="%d" fill="#f4ead9" stroke="#999"/>' % (W, H)]
for face, off, label in sheet_items:
for w in face.Wires:
pts = w.discretize(Deflection=0.2)
d = "M " + " L ".join("%.2f %.2f" % (p.x + off.x, H - (p.y + off.y)) for p in pts) + " Z"
s.append('<path d="%s" fill="none" stroke="#c00" stroke-width="0.3"/>' % d)
s.append('<text x="%.1f" y="%.1f" font-size="6" fill="#036">%s</text>' % (off.x + 3, H - off.y - 3, label))
s.append("</svg>")
open(path, "w").write("\n".join(s))
def export(parts=None):
parts = parts or MB.MDF_PARTS or MB.mdf_parts()
os.makedirs(os.path.join(OUT, "pecas"), exist_ok=True)
flat = []
for name, (shape, desc) in parts.items():
face = flatten(shape)
ents = edges_2d(face)
dxf_write(os.path.join(OUT, "pecas", name + ".dxf"), [(ents, V(0, 0, 0), None)])
flat.append((name, face, ents))
# arranjo em chapas (prateleiras, maior primeiro)
flat.sort(key=lambda t: -t[1].BoundBox.YLength * 1000 - t[1].BoundBox.XLength)
sheets, cur, x, y, row_h = [], [], GAP, GAP, 0
for name, face, ents in flat:
bb = face.BoundBox
if x + bb.XLength + GAP > SHEET[0]:
x, y, row_h = GAP, y + row_h + GAP, 0
if y + bb.YLength + GAP > SHEET[1]:
sheets.append(cur)
cur, x, y, row_h = [], GAP, GAP, 0
cur.append((name, face, ents, V(x, y, 0)))
x += bb.XLength + GAP
row_h = max(row_h, bb.YLength)
if cur:
sheets.append(cur)
for i, sh in enumerate(sheets):
dxf_write(os.path.join(OUT, "chapa_%d_900x600.dxf" % (i + 1)), [(e, o, n) for n, f, e, o in sh])
svg_write(os.path.join(OUT, "chapa_%d_900x600.svg" % (i + 1)), [(f, o, n) for n, f, e, o in sh], *SHEET)
return len(flat), len(sheets)
# ---------------------------------------------------------------- SVG para laser
def _svg_paths(ents, off, Hs):
"""Entidades -> elementos SVG (mm). Espelha Y (SVG cresce p/ baixo)."""
import math
Y = lambda y: Hs - y
out = []
for en in ents:
if en[0] == "LINE":
a, b = en[1] + off, en[2] + off
out.append('<line x1="%.4f" y1="%.4f" x2="%.4f" y2="%.4f"/>' % (a.x, Y(a.y), b.x, Y(b.y)))
elif en[0] == "CIRCLE":
c = en[1] + off
out.append('<circle cx="%.4f" cy="%.4f" r="%.4f"/>' % (c.x, Y(c.y), en[2]))
else:
c, r, sa, ea = en[1] + off, en[2], math.radians(en[3]), math.radians(en[4])
p0 = (c.x + r * math.cos(sa), Y(c.y + r * math.sin(sa)))
p1 = (c.x + r * math.cos(ea), Y(c.y + r * math.sin(ea)))
sweep = (en[4] - en[3]) % 360
large = 1 if sweep > 180 else 0
# anti-horário no plano Y-cima vira horário no SVG (sweep-flag 0)
out.append('<path d="M %.4f %.4f A %.4f %.4f 0 %d 0 %.4f %.4f"/>' % (p0[0], p0[1], r, r, large, p1[0], p1[1]))
return out
def svg_laser(path, groups, Ws, Hs, names=False):
s = ['<?xml version="1.0" encoding="UTF-8"?>',
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" '
'width="%.3fmm" height="%.3fmm" viewBox="0 0 %.3f %.3f">' % (Ws, Hs, Ws, Hs),
'<g inkscape:groupmode="layer" inkscape:label="CORTE" fill="none" stroke="#FF0000" stroke-width="0.01">']
for ents, off, label in groups:
s.append('<g id="%s">' % (label or "peca"))
s += _svg_paths(ents, off, Hs)
s.append("</g>")
s.append("</g>")
if names:
s.append('<g inkscape:groupmode="layer" inkscape:label="GRAVAR_NOMES" fill="#0000FF" stroke="none" '
'font-family="DejaVu Sans, Arial" font-size="5">')
for ents, off, label in groups:
if label:
s.append('<text x="%.2f" y="%.2f">%s</text>' % (off.x + 4, Hs - (off.y + 4), label.replace("_", " ")))
s.append("</g>")
s.append("</svg>")
open(path, "w").write("\n".join(s))
def export_svg(parts=None):
"""Gera SVGs de laser: corte/laser/chapa_N_900x600[_nomes].svg e corte/laser/pecas/*.svg"""
parts = parts or MB.MDF_PARTS or MB.mdf_parts()
L = os.path.join(OUT, "laser")
os.makedirs(os.path.join(L, "pecas"), exist_ok=True)
flat = []
for name, (shape, desc) in parts.items():
face = flatten(shape)
ents = edges_2d(face)
bb = face.BoundBox
svg_laser(os.path.join(L, "pecas", name + ".svg"), [(ents, V(0, 0, 0), name)], bb.XLength, bb.YLength)
flat.append((name, face, ents))
flat.sort(key=lambda t: -t[1].BoundBox.YLength * 1000 - t[1].BoundBox.XLength)
sheets, cur, x, y, row_h = [], [], GAP, GAP, 0
for name, face, ents in flat:
bb = face.BoundBox
if x + bb.XLength + GAP > SHEET[0]:
x, y, row_h = GAP, y + row_h + GAP, 0
if y + bb.YLength + GAP > SHEET[1]:
sheets.append(cur)
cur, x, y, row_h = [], GAP, GAP, 0
cur.append((name, ents, V(x, y, 0)))
x += bb.XLength + GAP
row_h = max(row_h, bb.YLength)
if cur:
sheets.append(cur)
for i, sh in enumerate(sheets):
g = [(e, o, n) for n, e, o in sh]
svg_laser(os.path.join(L, "chapa_%d_900x600.svg" % (i + 1)), g, *SHEET)
svg_laser(os.path.join(L, "chapa_%d_900x600_nomes.svg" % (i + 1)), g, *SHEET, names=True)
return len(flat), len(sheets)