Robo de teste em PLA (caixa_teste_ender3.py): fundo em 6 placas com grade de furos, paredes e bandejas separadas, presas pelo mesmo pino de encaixe; STL e G-codes para os bicos de 0,2 e 0,4 mm (os de 0,4 mm usam G29 no inicio). Chapas 35x35: posicao dos suportes NEMA17 em azul e DXF identificado com as camadas CORTE, SUPORTES e TEXTO para o LightBurn. Scripts CAD: caminhos relativos ao repositorio e guarda contra links vazios.
373 lines
16 KiB
Python
373 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Disposição das peças de MDF do robô 35x35 em 2 chapas de 900 x 600 mm:
|
|
uma com as peças da base e outra com as das prateleiras.
|
|
|
|
Rodar dentro do FreeCAD com interface (usa textos Draft). Gera, a partir de
|
|
montagem_base_35x35.py:
|
|
partes/mdf_35x35/dxf/pecas, dxf/chapas, svg/chapas, svg/conferencia (arquivos de corte)
|
|
partes/mdf_35x35/chapas_identificadas_35x35.FCStd (documento de conferência)
|
|
Mesmo formato de partes/mdf/chapas_identificadas.FCStd.
|
|
"""
|
|
import glob, math, os, random, shutil, sys, tempfile
|
|
|
|
import FreeCAD as App
|
|
import Part
|
|
from FreeCAD import Vector as V, Placement, Rotation
|
|
|
|
AQUI = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.abspath(os.path.join(AQUI, "..", "..", ".."))
|
|
RAIZ = os.path.join(REPO, "partes", "mdf_35x35")
|
|
DOC = "chapas_identificadas_35x35"
|
|
ANTIGO = os.path.join(REPO, "partes", "mdf", "chapas_identificadas.FCStd")
|
|
PASSO_Y = 700.0 # distância entre as chapas no documento
|
|
TENTATIVAS, SEED = 3000, 1
|
|
GRUPOS = (("base", "BASE DO ROBÔ"), ("prateleiras", "PRATELEIRAS")) # uma chapa por grupo
|
|
VERMELHO = (1.0, 0.149, 0.149)
|
|
AZUL = (0.451, 0.8, 1.0)
|
|
CINZA = (0.6, 0.6, 0.6)
|
|
|
|
for p in (AQUI, os.path.join(AQUI, "pecas")):
|
|
if p not in sys.path:
|
|
sys.path.insert(0, p)
|
|
|
|
|
|
def exportar_pecas():
|
|
"""DXF de cada peça, gerado da geometria atual de montagem_base_35x35."""
|
|
tmp = tempfile.mkdtemp()
|
|
os.environ["RM25_CORTE"] = tmp
|
|
import importlib
|
|
import montagem_base_35x35 as MB
|
|
importlib.reload(MB)
|
|
anterior = sys.modules.get("montagem_base")
|
|
sys.modules["montagem_base"] = MB
|
|
try:
|
|
import corte
|
|
importlib.reload(corte)
|
|
corte.export(MB.pecas_corte())
|
|
finally:
|
|
if anterior is None:
|
|
del sys.modules["montagem_base"]
|
|
else:
|
|
sys.modules["montagem_base"] = anterior
|
|
destino = os.path.join(RAIZ, "dxf", "pecas")
|
|
os.makedirs(destino, exist_ok=True)
|
|
for f in glob.glob(os.path.join(destino, "*.dxf")):
|
|
os.remove(f)
|
|
for f in glob.glob(os.path.join(tmp, "pecas", "*.dxf")):
|
|
shutil.copy(f, destino)
|
|
shutil.rmtree(tmp)
|
|
os.environ.pop("RM25_CORTE", None)
|
|
|
|
|
|
def grupo_de(nome):
|
|
return "prateleiras" if nome.startswith("Prat_") else "base"
|
|
|
|
|
|
def arranjo():
|
|
"""Encaixa cada grupo em uma chapa própria. Grava os arquivos de corte com
|
|
encaixe_chapas.main e repete o mesmo sorteio (mesma semente) para o documento."""
|
|
import importlib
|
|
import encaixe_chapas as EC
|
|
importlib.reload(EC)
|
|
for pasta in ("dxf/chapas", "svg/chapas", "svg/conferencia"): # arranjos anteriores
|
|
for f in glob.glob(os.path.join(RAIZ, pasta, "chapa_*")):
|
|
os.remove(f)
|
|
geo, todas = {}, {}
|
|
for f in sorted(glob.glob(os.path.join(RAIZ, "dxf", "pecas", "*.dxf"))):
|
|
nome = os.path.splitext(os.path.basename(f))[0]
|
|
geo[nome] = EC.ler_dxf(f)
|
|
x0, y0, x1, y1 = EC.bbox(geo[nome])
|
|
todas[nome] = (x1 - x0 + EC.GAP, y1 - y0 + EC.GAP)
|
|
resultado = []
|
|
for grupo, titulo in GRUPOS:
|
|
pecas = {n: v for n, v in todas.items() if grupo_de(n) == grupo}
|
|
argv = sys.argv
|
|
sys.argv = ["encaixe_chapas.py", RAIZ, "--tentativas", str(TENTATIVAS), "--seed", str(SEED),
|
|
"--so", ",".join(sorted(pecas)), "--saida", "chapa_" + grupo]
|
|
try:
|
|
EC.main()
|
|
finally:
|
|
sys.argv = argv
|
|
rnd = random.Random(SEED)
|
|
base = sorted(pecas, key=lambda n: (-pecas[n][0] * pecas[n][1], n))
|
|
melhor = None
|
|
for i in range(TENTATIVAS):
|
|
ordem = base if i == 0 else sorted(base, key=lambda n: -pecas[n][0] * pecas[n][1] * rnd.uniform(0.6, 1.4))
|
|
chapas, arr = EC.encaixar(pecas, ordem)
|
|
k = EC.custo(chapas)
|
|
if melhor is None or k < melhor[0]:
|
|
melhor = (k, arr)
|
|
if len(melhor[1]) != 1:
|
|
raise SystemExit("grupo %s não coube em uma chapa" % grupo)
|
|
resultado.append((titulo, melhor[1][0]))
|
|
return EC, geo, resultado
|
|
|
|
|
|
def rotulos():
|
|
"""Nomes das peças, reaproveitados do documento antigo (só leitura)."""
|
|
aberto = App.listDocuments().get("chapas_identificadas")
|
|
d = aberto or App.openDocument(ANTIGO, hidden=True)
|
|
r = {o.Name: o.Label.replace("(X) ", "") for o in d.Objects
|
|
if o.TypeId == "Part::Feature" and "contorno" not in o.Name}
|
|
if not aberto:
|
|
App.closeDocument(d.Name)
|
|
return r
|
|
|
|
|
|
def forma(ents, dy):
|
|
arestas = []
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
a, b = V(e[1][0], e[1][1] + dy, 0), V(e[2][0], e[2][1] + dy, 0)
|
|
if (a - b).Length > 1e-6:
|
|
arestas.append(Part.makeLine(a, b))
|
|
elif e[0] == "CIRCLE":
|
|
arestas.append(Part.makeCircle(e[2], V(e[1][0], e[1][1] + dy, 0)))
|
|
else:
|
|
a0, a1 = e[3], e[4]
|
|
if a1 <= a0:
|
|
a1 += 360.0
|
|
arestas.append(Part.makeCircle(e[2], V(e[1][0], e[1][1] + dy, 0), V(0, 0, 1), a0, a1))
|
|
return Part.makeCompound(arestas)
|
|
|
|
|
|
def anotar_suportes(doc, grupo, EC, geo, rot, ox, oy, dy):
|
|
# devolve as entidades azuis (coordenadas da chapa) para o DXF de conferência
|
|
"""Desenha em azul, sobre a Base, onde fica cada suporte NEMA17: contorno da base do
|
|
suporte, face do motor e oblongos. Só no documento de conferência (não vai para o corte).
|
|
As posições vêm de montagem_base_35x35; aborta se os furos não coincidirem com os da Base."""
|
|
import montagem_base_35x35 as MB
|
|
import suporte_nema17 as SP
|
|
base = (MB.MDF_PARTS or MB.mdf_parts())["Base"][0]
|
|
# mesma transformação de corte.flatten (world -> DXF da Base)
|
|
n = sorted([f for f in base.Faces if f.Surface.__class__.__name__ == "Plane"], key=lambda f: -f.Area)[0].normalAt(0, 0)
|
|
r3 = Rotation(n, V(0, 0, 1))
|
|
s3 = base.copy()
|
|
s3.Placement = Placement(V(), r3).multiply(s3.Placement)
|
|
bb = s3.BoundBox
|
|
cantos = EC.bbox(geo["Base"])
|
|
|
|
def plano(pl, x, y):
|
|
p = r3.multVec(pl.multVec(V(x, y, 0)))
|
|
return (p.x - bb.XMin, p.y - bb.YMin)
|
|
|
|
circulos = [e[1] for e in geo["Base"] if e[0] == "CIRCLE"]
|
|
azuis = []
|
|
for (xs, ys), _ in MB.WHEEL_HAND.items():
|
|
pl = MB.bracket_pl(xs, ys)
|
|
tag = ("D" if xs > 0 else "E") + ("F" if ys > 0 else "T")
|
|
for fx, fy in SP.FUROS: # confere com os furos M4 da Base
|
|
q = plano(pl, fx, fy)
|
|
if min(math.hypot(q[0] - c[0], q[1] - c[1]) for c in circulos) > 0.02:
|
|
raise SystemExit("furo do suporte %s não coincide com a Base" % tag)
|
|
w, d, c = SP.BASE_W / 2, SP.BASE_D, 2.5 # contorno 72 x 40, cantos r2,5
|
|
pts = []
|
|
for cx, cy, a0 in ((w - c, c, -90), (w - c, d - c, 0), (-w + c, d - c, 90), (-w + c, c, 180)):
|
|
pts += [(cx + c * math.cos(math.radians(a0 + 15 * k)), cy + c * math.sin(math.radians(a0 + 15 * k))) for k in range(7)]
|
|
segs = [(pts[i], pts[(i + 1) % len(pts)]) for i in range(len(pts))]
|
|
segs.append(((-SP.FACE_W / 2, SP.T), (SP.FACE_W / 2, SP.T))) # face do motor
|
|
for fx, fy in SP.FUROS: # oblongos 4,0 x 8,5 (ao longo da profundidade)
|
|
r_, m = SP.SLOT_W / 2, (SP.SLOT_L - SP.SLOT_W) / 2
|
|
ob = [(fx + r_ * math.cos(math.radians(a)), fy + m + r_ * math.sin(math.radians(a))) for a in range(0, 181, 20)] + \
|
|
[(fx + r_ * math.cos(math.radians(a)), fy - m + r_ * math.sin(math.radians(a))) for a in range(180, 361, 20)]
|
|
segs += [(ob[i], ob[(i + 1) % len(ob)]) for i in range(len(ob))]
|
|
ents = [("LINE", plano(pl, *a), plano(pl, *b)) for a, b in segs]
|
|
tudo = EC.transformar(geo["Base"] + ents, rot, ox, oy)
|
|
if EC.bbox(geo["Base"] + ents) != cantos:
|
|
raise SystemExit("contorno do suporte %s sai da Base" % tag)
|
|
o = doc.addObject("Part::Feature", "Posicao_Suporte_" + tag)
|
|
o.Label = "Posição suporte NEMA17 " + tag
|
|
azuis += tudo[len(geo["Base"]):]
|
|
o.Shape = forma(tudo[len(geo["Base"]):], dy)
|
|
o.ViewObject.LineColor = AZUL
|
|
o.ViewObject.PointColor = AZUL
|
|
o.ViewObject.LineWidth = 2.0
|
|
grupo.addObject(o)
|
|
b = o.Shape.BoundBox
|
|
texto(doc, grupo, "txt Suporte " + tag, ["Suporte " + tag], V(b.Center.x, b.Center.y, 0.2), 7.0)
|
|
return azuis
|
|
|
|
|
|
def texto(doc, grupo, nome, linhas, pos, tam, ang=0.0, just="Center", esp=1.1):
|
|
import Draft
|
|
t = Draft.make_text(linhas, Placement(pos, Rotation(V(0, 0, 1), ang)))
|
|
t.Label = nome
|
|
vo = t.ViewObject
|
|
vo.FontSize = "%.3f mm" % tam
|
|
vo.FontName = "Noto Sans"
|
|
vo.Justification = just
|
|
vo.TextColor = AZUL
|
|
vo.LineSpacing = esp
|
|
grupo.addObject(t)
|
|
return t
|
|
|
|
|
|
def tamanho_fonte(w, h, linhas):
|
|
longo, curto = max(w, h), min(w, h)
|
|
chars = max(len(l) for l in linhas)
|
|
return min(12.0, longo * 0.9 / (0.56 * chars), curto * 0.8 / (1.1 * len(linhas)))
|
|
|
|
|
|
# camadas do DXF identificado: o LightBurn separa pela cor (ACI 1 vermelho, 5 azul, 3 verde)
|
|
CAMADAS = {"CORTE": 1, "SUPORTES": 5, "TEXTO": 3}
|
|
|
|
|
|
def contornos_texto(o, dy, peca):
|
|
"""Texto Draft como polilinhas fechadas (coordenadas da chapa), reduzido para caber
|
|
na peça 'peca' e centrado nela."""
|
|
from lib_rm import FONT_REG as FONTE
|
|
vo = o.ViewObject
|
|
esp = vo.LineSpacing
|
|
pl = Placement(V(o.Placement.Base.x, o.Placement.Base.y - dy, 0), o.Placement.Rotation)
|
|
em_pe = abs(o.Placement.Rotation.Angle) > 1e-6
|
|
bp = peca.Shape.BoundBox
|
|
larg, alt = (bp.YLength, bp.XLength) if em_pe else (bp.XLength, bp.YLength)
|
|
|
|
def monta(tam):
|
|
linhas = []
|
|
for i, linha in enumerate(o.Text):
|
|
arames = [w for g in Part.makeWireString(linha, FONTE, tam, 0)
|
|
for w in (g if isinstance(g, (list, tuple)) else [g])]
|
|
if arames:
|
|
bb = Part.makeCompound(arames).BoundBox
|
|
linhas.append((arames, bb.Center.x, -i * tam * esp, bb))
|
|
return linhas
|
|
|
|
tam = vo.FontSize.Value
|
|
ls = monta(tam)
|
|
w = max(l[3].XLength for l in ls)
|
|
h = (ls[0][3].YMax + ls[0][2]) - (ls[-1][3].YMin + ls[-1][2])
|
|
k = min(1.0, 0.9 * larg / w, 0.8 * alt / h)
|
|
tam *= k
|
|
ls = monta(tam)
|
|
cy = ((ls[0][3].YMax + ls[0][2]) + (ls[-1][3].YMin + ls[-1][2])) / 2
|
|
polis = []
|
|
for arames, cx, y0, _ in ls:
|
|
for a in arames:
|
|
pts = [pl.multVec(V(p.x - cx, p.y + y0 - cy, 0)) for p in a.discretize(Deflection=0.02)]
|
|
polis.append(("POLY", [(p.x, p.y) for p in pts], True))
|
|
return polis
|
|
|
|
|
|
def unir_linhas(ents):
|
|
"""Junta LINEs consecutivas em polilinhas (fechadas quando o fim encontra o início)."""
|
|
polis, atual = [], []
|
|
def fecha():
|
|
if len(atual) > 1:
|
|
ok = math.hypot(atual[0][0] - atual[-1][0], atual[0][1] - atual[-1][1]) < 1e-6
|
|
polis.append(("POLY", atual[:-1] if ok else list(atual), ok))
|
|
for e in ents:
|
|
a, b = (e[1][0], e[1][1]), (e[2][0], e[2][1])
|
|
if atual and math.hypot(atual[-1][0] - a[0], atual[-1][1] - a[1]) < 1e-6:
|
|
atual.append(b)
|
|
else:
|
|
fecha()
|
|
atual = [a, b]
|
|
fecha()
|
|
return polis
|
|
|
|
|
|
def escrever_dxf(caminho, camadas):
|
|
"""DXF R12 com uma camada e uma cor por categoria."""
|
|
L = ["0", "SECTION", "2", "HEADER", "9", "$ACADVER", "1", "AC1009", "9", "$INSUNITS", "70", "4", "0", "ENDSEC",
|
|
"0", "SECTION", "2", "TABLES", "0", "TABLE", "2", "LAYER", "70", str(len(CAMADAS))]
|
|
for n, c in CAMADAS.items():
|
|
L += ["0", "LAYER", "2", n, "70", "0", "62", str(c), "6", "CONTINUOUS"]
|
|
L += ["0", "ENDTAB", "0", "ENDSEC", "0", "SECTION", "2", "ENTITIES"]
|
|
f = lambda v: "%.4f" % v
|
|
for n, ents in camadas.items():
|
|
cab = ["8", n, "62", str(CAMADAS[n])]
|
|
for e in ents:
|
|
if e[0] == "LINE":
|
|
L += ["0", "LINE"] + cab + ["10", f(e[1][0]), "20", f(e[1][1]), "30", "0", "11", f(e[2][0]), "21", f(e[2][1]), "31", "0"]
|
|
elif e[0] == "CIRCLE":
|
|
L += ["0", "CIRCLE"] + cab + ["10", f(e[1][0]), "20", f(e[1][1]), "30", "0", "40", f(e[2])]
|
|
elif e[0] == "ARC":
|
|
L += ["0", "ARC"] + cab + ["10", f(e[1][0]), "20", f(e[1][1]), "30", "0", "40", f(e[2]), "50", f(e[3]), "51", f(e[4])]
|
|
else:
|
|
L += ["0", "POLYLINE"] + cab + ["66", "1", "70", "1" if e[2] else "0", "10", "0", "20", "0", "30", "0"]
|
|
for x, y in e[1]:
|
|
L += ["0", "VERTEX", "8", n, "10", f(x), "20", f(y), "30", "0"]
|
|
L += ["0", "SEQEND", "8", n]
|
|
L += ["0", "ENDSEC", "0", "EOF"]
|
|
with open(caminho, "w", newline="\r\n") as arq:
|
|
arq.write("\n".join(L) + "\n")
|
|
|
|
|
|
def exportar_identificadas(doc, saida):
|
|
"""Uma DXF por chapa, com as camadas CORTE, SUPORTES e TEXTO (sem o contorno da chapa
|
|
e sem o título, que fica fora da área de 900 x 600)."""
|
|
pasta = os.path.join(RAIZ, "dxf", "identificadas")
|
|
os.makedirs(pasta, exist_ok=True)
|
|
arquivos = []
|
|
for i, ((grupo, _), cam) in enumerate(zip(GRUPOS, saida)):
|
|
dy = -PASSO_Y * i
|
|
camadas = {"CORTE": cam["CORTE"], "SUPORTES": unir_linhas(cam["SUPORTES"]), "TEXTO": []}
|
|
for o in doc.getObject("Chapa_%d" % (i + 1)).Group:
|
|
if not hasattr(o, "Text") or not o.Label.startswith("txt "):
|
|
continue
|
|
nome = o.Label[4:]
|
|
suporte = nome.startswith("Suporte ") # "Suporte EF" etc.; Suporte_Cam_* é peça
|
|
peca = doc.getObject("Posicao_Suporte_" + nome[8:] if suporte else nome)
|
|
camadas["SUPORTES" if suporte else "TEXTO"] += contornos_texto(o, dy, peca)
|
|
caminho = os.path.join(pasta, "chapa_%s_1_900x600_identificada.dxf" % grupo)
|
|
escrever_dxf(caminho, camadas)
|
|
arquivos.append(caminho)
|
|
return arquivos
|
|
|
|
|
|
def gerar():
|
|
os.makedirs(RAIZ, exist_ok=True)
|
|
exportar_pecas()
|
|
EC, geo, arr = arranjo()
|
|
nomes = rotulos()
|
|
if DOC in App.listDocuments():
|
|
App.closeDocument(DOC)
|
|
doc = App.newDocument(DOC)
|
|
W, H = EC.SHEET
|
|
relatorio, saida = [], []
|
|
for i, (nome_grupo, itens) in enumerate(arr):
|
|
cam = {"CORTE": [], "SUPORTES": []}
|
|
saida.append(cam)
|
|
dy = -PASSO_Y * i
|
|
g = doc.addObject("App::DocumentObjectGroup", "Chapa_%d" % (i + 1))
|
|
g.Label = "Chapa %d - %s" % (i + 1, nome_grupo.capitalize())
|
|
c = doc.addObject("Part::Feature", "Chapa_%d_contorno" % (i + 1))
|
|
c.Label = "Chapa %d contorno 900x600" % (i + 1)
|
|
c.Shape = Part.makePolygon([V(0, dy, 0), V(W, dy, 0), V(W, H + dy, 0), V(0, H + dy, 0), V(0, dy, 0)])
|
|
c.ViewObject.LineColor = CINZA
|
|
c.ViewObject.LineWidth = 2.0
|
|
g.addObject(c)
|
|
area = 0.0
|
|
for nome, x, y, rot in itens:
|
|
ox, oy = x + EC.MARGEM, y + EC.MARGEM
|
|
ents = EC.transformar(geo[nome], rot, ox, oy)
|
|
cam["CORTE"] += ents
|
|
o = doc.addObject("Part::Feature", nome)
|
|
rotulo = nomes.get(nome, nome.replace("_", " "))
|
|
o.Label = rotulo
|
|
o.Shape = forma(ents, dy)
|
|
o.ViewObject.LineColor = VERMELHO
|
|
o.ViewObject.PointColor = VERMELHO
|
|
o.ViewObject.LineWidth = 2.0
|
|
g.addObject(o)
|
|
if nome == "Base":
|
|
cam["SUPORTES"] += anotar_suportes(doc, g, EC, geo, rot, ox, oy, dy)
|
|
b = o.Shape.BoundBox
|
|
area += b.XLength * b.YLength
|
|
linhas = rotulo.split(" — ", 1)
|
|
tam = tamanho_fonte(b.XLength, b.YLength, linhas)
|
|
ang = 90.0 if b.YLength > b.XLength else 0.0
|
|
texto(doc, g, "txt " + nome, linhas, V(b.Center.x, b.Center.y, 0.2), tam, ang)
|
|
titulo = "CHAPA %d: %s (%d peças, %.0f%% ocupada)" % (i + 1, nome_grupo, len(itens), 100.0 * area / (W * H))
|
|
texto(doc, g, "Título chapa %d" % (i + 1), [titulo], V(0, H + dy + 8.0, 0), 22.0, 0.0, "Left", 1.0)
|
|
relatorio.append(titulo)
|
|
doc.recompute()
|
|
doc.saveAs(os.path.join(RAIZ, DOC + ".FCStd"))
|
|
relatorio += exportar_identificadas(doc, saida)
|
|
return doc, relatorio
|
|
|
|
|
|
if __name__ == "__main__":
|
|
gerar()
|