feat: the Site's packing engine shared with the montador's real layout (front 7a.2a)
The packing engine moves verbatim from web/site-packing.js to web/packing.js, loaded by the Site and the Kanban. Montar folha packs the list with it after every change and draws the sheet, showing the real length instead of the estimate. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1204,6 +1204,7 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
<script src="/site-sheet.js"></script>
|
||||
<script src="/site-pdf.js"></script>
|
||||
<script src="/site-quality.js"></script>
|
||||
<script src="/packing.js"></script>
|
||||
<script src="/site-packing.js"></script>
|
||||
<script src="/site-cart.js"></script>
|
||||
<script src="/site-flow.js"></script>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
/* Kanban DTF: "Montar folha" (Fase 2, front 7). The stamps are the PNG files
|
||||
in Estampas/ inside the folder chosen in Integrações; the sizes are the
|
||||
table Gestão edits. Slice 1: the list and the estimate; Montar is slice 2.
|
||||
Uses the globals of kanban.js, loaded first. */
|
||||
table Gestão edits. The packing is the Site's own engine (web/packing.js).
|
||||
Montar, which creates the card, is slice 2b. Uses the globals of kanban.js
|
||||
and packing.js, loaded first. */
|
||||
const MONTAR_CODE=/^[A-Za-z0-9_-]{1,40}$/;
|
||||
// The Site's ruler (web/site-config.js): the same numbers, copied there too.
|
||||
const MONTAR_DPI_REFUSE=96, MONTAR_DPI_WARN=200;
|
||||
const MONTAR_FILM_CM=57, MONTAR_GAP_CM=0.5;
|
||||
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0};
|
||||
const MONTAR={sizes:[],lines:[],seq:0,preview:null,timer:null,dirty:false,token:0,
|
||||
layout:null,layoutTimer:null,layoutToken:0,layoutPending:false};
|
||||
|
||||
const montarFolderReady=()=>!!FOLDER.handle&&!!FOLDER.granted;
|
||||
const montarDpi=found=>found.width/(found.widthCm/2.54);
|
||||
@@ -104,9 +106,85 @@ function montarEstimate(){
|
||||
return (MONTAR_GAP_CM+total)/100;
|
||||
}
|
||||
function montarPaintTotals(){
|
||||
$('montar-total').textContent='Estimativa: '+metres(montarEstimate());
|
||||
const done=MONTAR.layout&&!MONTAR.layoutPending;
|
||||
$('montar-total').textContent=done
|
||||
? 'Montagem: '+metres(MONTAR.layout.altura/100)
|
||||
: 'Estimativa: '+metres(montarEstimate())+(MONTAR.layoutPending?' · montando…':'');
|
||||
$('montar-count').textContent=MONTAR.lines.length?plural(MONTAR.lines.length,'estampa','estampas'):'';
|
||||
$('montar-clear').disabled=!MONTAR.lines.length;
|
||||
$('montar-warning').hidden=!(MONTAR.lines.length>20||MONTAR.lines.some(line=>line.qty>200));
|
||||
}
|
||||
// The line's image, loaded once and kept for the packing and the preview.
|
||||
function montarStampImage(url){
|
||||
const img=new Image();
|
||||
const loading=new Promise(ok=>{img.onload=()=>ok(img);img.onerror=()=>ok(null);});
|
||||
img.src=url;
|
||||
return {img,loading};
|
||||
}
|
||||
// Every list change shows the estimate at once and schedules the real packing,
|
||||
// 300 ms later; a run that finishes after a newer change is thrown away.
|
||||
function montarChanged(){
|
||||
MONTAR.layoutToken+=1;
|
||||
MONTAR.layout=null;
|
||||
MONTAR.layoutPending=true;
|
||||
montarPaintLines();
|
||||
if(!MONTAR.lines.length)montarDrawPreview(null);
|
||||
clearTimeout(MONTAR.layoutTimer);
|
||||
MONTAR.layoutTimer=setTimeout(()=>montarLayout(MONTAR.layoutToken).catch(e=>say(e.message,true)),300);
|
||||
}
|
||||
async function montarLayout(token){
|
||||
if(token!==MONTAR.layoutToken)return;
|
||||
const lines=[...MONTAR.lines];
|
||||
if(!lines.length){MONTAR.layout=null;MONTAR.layoutPending=false;montarPaintTotals();montarDrawPreview(null);return;}
|
||||
const images=await Promise.all(lines.map(line=>line.loading));
|
||||
if(token!==MONTAR.layoutToken)return;
|
||||
if(images.some(image=>!image)){
|
||||
MONTAR.layoutPending=false;montarPaintTotals();
|
||||
say('A estampa não pôde ser lida.',true);return;
|
||||
}
|
||||
const cargas=lines.flatMap((line,sourceIndex)=>Array.from({length:line.qty},(_,copyIndex)=>({
|
||||
a:{sourceIndex,giro:0,esp:false},img:line.img,copyIndex,w:line.widthCm,h:line.heightCm,travado:false})));
|
||||
let enc;
|
||||
try{enc=encaixar(cargas,MONTAR_FILM_CM);}
|
||||
catch(e){
|
||||
if(token!==MONTAR.layoutToken)return;
|
||||
MONTAR.layoutPending=false;montarPaintTotals();say(e.message,true);return;
|
||||
}
|
||||
if(token!==MONTAR.layoutToken)return;
|
||||
MONTAR.layout={token,altura:enc.altura,pos:enc.pos};
|
||||
MONTAR.layoutPending=false;
|
||||
montarPaintTotals();
|
||||
montarDrawPreview(MONTAR.layout);
|
||||
}
|
||||
// The sheet's preview: 57 cm across the panel, white film and the outline.
|
||||
function montarDrawPreview(layout){
|
||||
const box=$('montar-layout'),canvas=$('montar-canvas');
|
||||
if(!layout){box.hidden=true;return;}
|
||||
box.hidden=false;
|
||||
const width=box.clientWidth-24; // the box's padding
|
||||
if(width<60)return;
|
||||
const px=width/MONTAR_FILM_CM;
|
||||
const height=Math.max(20,layout.altura*px);
|
||||
const dpr=Math.min(2,window.devicePixelRatio||1);
|
||||
canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);
|
||||
canvas.style.width=width+'px';canvas.style.height=height+'px';
|
||||
const ctx=canvas.getContext('2d');
|
||||
ctx.setTransform(dpr,0,0,dpr,0,0);
|
||||
ctx.fillStyle='#fff';ctx.fillRect(0,0,width,height);
|
||||
ctx.strokeStyle='#B4BAC5';ctx.lineWidth=1;
|
||||
ctx.strokeRect(.5,.5,width-1,height-1);
|
||||
for(const p of layout.pos){
|
||||
const c=p.ref;
|
||||
const giro=(p.rot===90?90:0)+(c.a&&c.a.giro?90:0);
|
||||
ctx.save();
|
||||
ctx.translate((p.x+p.w/2)*px,(p.y+p.h/2)*px);
|
||||
ctx.rotate(giro*Math.PI/180);
|
||||
if(c.a&&c.a.esp)ctx.scale(-1,1);
|
||||
const dw=((giro%180===90)?p.h:p.w)*px, dh=((giro%180===90)?p.w:p.h)*px;
|
||||
if(c.img)ctx.drawImage(c.img,-dw/2,-dh/2,dw,dh);
|
||||
else{ctx.fillStyle='#E7E7E3';ctx.fillRect(-dw/2,-dh/2,dw,dh);}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
function montarLine(line){
|
||||
const row=node('div',undefined,'montar-line');
|
||||
@@ -118,7 +196,7 @@ function montarLine(line){
|
||||
qty.onchange=()=>{
|
||||
const value=Math.round(Number(qty.value));
|
||||
if(!Number.isInteger(value)||value<1||value>9999){qty.value=String(line.qty);return;}
|
||||
line.qty=value;qty.value=String(value);montarPaintTotals();
|
||||
line.qty=value;qty.value=String(value);montarChanged();
|
||||
};
|
||||
const dpi=node('span',undefined,'montar-dpi');
|
||||
if(line.dpi<MONTAR_DPI_WARN)dpi.append(badge(Math.floor(line.dpi)+' DPI','warn','Abaixo de '+MONTAR_DPI_WARN+' DPI.'));
|
||||
@@ -135,12 +213,12 @@ function montarPaintLines(){
|
||||
function montarRemoveLine(line){
|
||||
URL.revokeObjectURL(line.url);
|
||||
MONTAR.lines=MONTAR.lines.filter(other=>other!==line);
|
||||
montarPaintLines();
|
||||
montarChanged();
|
||||
}
|
||||
function montarClear(){
|
||||
for(const line of MONTAR.lines)URL.revokeObjectURL(line.url);
|
||||
MONTAR.lines=[];
|
||||
montarPaintLines();
|
||||
montarChanged();
|
||||
}
|
||||
|
||||
async function montarAdd(){
|
||||
@@ -159,10 +237,11 @@ async function montarAdd(){
|
||||
const dpi=montarDpi(found);
|
||||
if(dpi<MONTAR_DPI_REFUSE)return say('A estampa tem só '+Math.floor(dpi)+' DPI em '+size.letter+': pequena demais.',true);
|
||||
const existing=MONTAR.lines.find(line=>line.code===code&&line.letter===size.letter);
|
||||
if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarPaintLines();return;}
|
||||
if(existing){existing.qty=Math.min(9999,existing.qty+qty);montarChanged();return;}
|
||||
const url=URL.createObjectURL(found.file),picture=montarStampImage(url);
|
||||
MONTAR.lines.push({id:++MONTAR.seq,code,letter:size.letter,widthCm:found.widthCm,qty,
|
||||
heightCm:montarHeight(found),dpi,url:URL.createObjectURL(found.file),file:found.file});
|
||||
montarPaintLines();
|
||||
heightCm:montarHeight(found),dpi,url,img:picture.img,loading:picture.loading,file:found.file});
|
||||
montarChanged();
|
||||
}
|
||||
|
||||
function montarPaintSelect(){
|
||||
@@ -226,8 +305,21 @@ async function loadMontador(){
|
||||
else montarPaintHint();
|
||||
}
|
||||
montarPaintLines();
|
||||
if(MONTAR.layout)montarDrawPreview(MONTAR.layout);
|
||||
}
|
||||
|
||||
// 2b splits an order that passes these limits into more than one sheet; from
|
||||
// now on it only warns, it does not block.
|
||||
const montarWarning=node('p','O pedido será dividido em mais de uma folha.','montar-warn');
|
||||
montarWarning.id='montar-warning';montarWarning.hidden=true;
|
||||
$('montar-sheet').insertBefore(montarWarning,$('montar-lines'));
|
||||
|
||||
let montarResize=null;
|
||||
addEventListener('resize',()=>{
|
||||
clearTimeout(montarResize);
|
||||
montarResize=setTimeout(()=>{if(MONTAR.layout)montarDrawPreview(MONTAR.layout);},200);
|
||||
});
|
||||
|
||||
$('montar-code').addEventListener('input',montarQueuePreview);
|
||||
$('montar-size').addEventListener('change',()=>montarPreview().catch(e=>say(e.message,true)));
|
||||
$('montar-qty').addEventListener('keydown',event=>{
|
||||
|
||||
@@ -1255,6 +1255,9 @@ dialog.viewer::backdrop{background:var(--scrim)}
|
||||
#tab-montar .montar-height{font-size:13px;color:var(--tx2);text-align:right;white-space:nowrap}
|
||||
#tab-montar #montar-lines .emptystate{padding:28px 18px}
|
||||
#tab-montar .montar-actions{display:flex;justify-content:flex-end;gap:10px;padding:12px 18px;border-top:1px solid var(--ln)}
|
||||
#tab-montar .montar-warn{margin:0;padding:10px 18px;border-bottom:1px solid var(--ln);font-size:13px;font-weight:600;color:var(--warn)}
|
||||
#tab-montar .montar-layout{height:340px;overflow:auto;scrollbar-gutter:stable;border-top:1px solid var(--ln);background:var(--sf2);padding:12px}
|
||||
#tab-montar .montar-layout canvas{display:block;margin:0 auto;background:#fff;box-shadow:0 0 0 1px var(--ln2)}
|
||||
#tab-montar .montar-sizes{display:flex;flex-direction:column;padding:8px 0}
|
||||
#tab-montar .montar-size-head,#tab-montar .montar-size-row{display:grid;grid-template-columns:90px 160px 36px;gap:12px;align-items:center;padding:6px 18px}
|
||||
#tab-montar .montar-size-head{font-size:12.5px;color:var(--tx3)}
|
||||
@@ -1273,5 +1276,7 @@ dialog.viewer::backdrop{background:var(--scrim)}
|
||||
#tab-montar .montar-line>.btn{grid-area:remove}
|
||||
#tab-montar .montar-actions{flex-wrap:wrap;padding:12px 14px}
|
||||
#tab-montar .montar-actions .btn{flex:1}
|
||||
#tab-montar .montar-warn{padding:10px 14px}
|
||||
#tab-montar .montar-layout{height:260px;padding:8px}
|
||||
#tab-montar .montar-size-head,#tab-montar .montar-size-row{grid-template-columns:70px minmax(0,1fr) 36px;padding:6px 14px}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@
|
||||
<section class="panel clip" id="montar-sheet">
|
||||
<div class="phead"><h2>Folha</h2><span class="n" id="montar-count"></span><b class="montar-total" id="montar-total"></b></div>
|
||||
<div id="montar-lines"></div>
|
||||
<div id="montar-layout" class="montar-layout" hidden><canvas id="montar-canvas"></canvas></div>
|
||||
<div class="montar-actions">
|
||||
<button class="btn ghost" id="montar-clear" type="button">Limpar lista</button>
|
||||
<button class="btn pri" id="montar-build" type="button" disabled title="Em breve">Montar</button>
|
||||
@@ -231,4 +232,4 @@
|
||||
<div class="scrim" id="scrim"></div>
|
||||
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
|
||||
</div>
|
||||
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-site.js"></script><script src="/kanban-montador.js"></script></body></html>
|
||||
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
|
||||
|
||||
213
web/packing.js
Normal file
213
web/packing.js
Normal file
@@ -0,0 +1,213 @@
|
||||
/* DTF — o encaixe da folha, compartilhado pelo Site e pelo montador do Kanban:
|
||||
máscaras, as regras de margem e a montagem em si. Script clássico: as páginas
|
||||
o carregam antes do próprio código e dividem um só escopo global. */
|
||||
const CEL=0.5; // célula da máscara, em cm = a folga de 5 mm · deve ser igual a GAP_CM em web/site-config.js
|
||||
// Dilata 1 célula para a direita e para baixo. Como toda peça é dilatada igual,
|
||||
// duas vizinhas ficam separadas por exatamente 1 célula — os 5 mm da regra.
|
||||
function dilatar(bruto,cw,ch,cheias){
|
||||
const cw2=cw+1, ch2=ch+1;
|
||||
const out=new Uint8Array(cw2*ch2);
|
||||
for(let y=0;y<ch;y++) for(let x=0;x<cw;x++){
|
||||
if(!bruto[y*cw+x]) continue;
|
||||
out[y*cw2+x]=1; out[y*cw2+x+1]=1; out[(y+1)*cw2+x]=1; out[(y+1)*cw2+x+1]=1;
|
||||
}
|
||||
return {cw:cw2,ch:ch2,bits:out,cheias}; // cheias = área de arte, sem a folga
|
||||
}
|
||||
function mascara(img,w,h,rot,esp=false){
|
||||
const cw=Math.max(1,Math.ceil(w/CEL)), ch=Math.max(1,Math.ceil(h/CEL));
|
||||
const cv=document.createElement('canvas');
|
||||
cv.width=cw; cv.height=ch;
|
||||
const ctx=cv.getContext('2d',{willReadFrequently:true});
|
||||
let bruto, cheias;
|
||||
if(!img){ // sem imagem: caixa cheia
|
||||
bruto=new Uint8Array(cw*ch).fill(1); cheias=cw*ch;
|
||||
return dilatar(bruto,cw,ch,cheias);
|
||||
}
|
||||
ctx.save();
|
||||
ctx.translate(cw/2,ch/2);
|
||||
ctx.rotate(rot*Math.PI/180);
|
||||
if(esp) ctx.scale(-1,1);
|
||||
const dw=rot%180===90?ch:cw, dh=rot%180===90?cw:ch;
|
||||
ctx.drawImage(img,-dw/2,-dh/2,dw,dh);
|
||||
ctx.restore();
|
||||
const d=ctx.getImageData(0,0,cw,ch).data;
|
||||
bruto=new Uint8Array(cw*ch); cheias=0;
|
||||
for(let i=0,j=3;i<bruto.length;i++,j+=4){ bruto[i] = d[j]>16 ? 1 : 0; cheias+=bruto[i]; }
|
||||
return dilatar(bruto,cw,ch,cheias);
|
||||
}
|
||||
|
||||
// Margens e folgas da folha (regra da Dropstar, 21/10/2026): 5 mm em cima,
|
||||
// embaixo e entre as linhas. Na largura, 5 mm nas bordas e entre as peças como
|
||||
// alvo; quando não cabem, a sobra é dividida em partes iguais, e duas peças só
|
||||
// ficam lado a lado com pelo menos 1,5 mm entre elas e nas bordas.
|
||||
const MARGEM_CM=0.5, FOLGA_MIN_CM=0.15;
|
||||
// Pela forma, as peças se aproximam (favo de mel) e as colunas se deslocam.
|
||||
// Só compensa quando a folha encurta de verdade; senão, colunas alinhadas.
|
||||
const GANHO_FORMA_CM=1;
|
||||
|
||||
// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm.
|
||||
// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor
|
||||
// usada na largura.
|
||||
function encaixar(pecas,W){
|
||||
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
||||
throw new RangeError('A largura solicitada não cabe no filme.');
|
||||
const linhas=encaixarEmLinhas(pecas,W);
|
||||
const forma=encaixarComMargens(pecas,W);
|
||||
if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma;
|
||||
// A máscara de cada peça: a área de arte que a prévia mostra como aproveitada.
|
||||
const mascaras=new Map();
|
||||
linhas.pos.forEach(p=>{
|
||||
const k=p.ref.a||p.ref, giro=p.rot+(p.ref.a?.giro||0);
|
||||
if(!mascaras.has(k)) mascaras.set(k,new Map());
|
||||
const daArte=mascaras.get(k);
|
||||
if(!daArte.has(p.rot)) daArte.set(p.rot,mascara(p.ref.img,p.w,p.h,giro,p.ref.a?.esp));
|
||||
p.m=daArte.get(p.rot);
|
||||
});
|
||||
return linhas;
|
||||
}
|
||||
|
||||
// Em linhas, com as medidas exatas: cada arte (todas as cópias juntas) fica de
|
||||
// pé ou deitada, a que der a folha mais curta. Em arte retangular, girar 90° é
|
||||
// o que mais economiza filme.
|
||||
function encaixarEmLinhas(pecas,W){
|
||||
const arteDe=p=>p.a||p;
|
||||
const artes=[...new Set(pecas.map(arteDe))];
|
||||
// Toda peça que não é quadrada é testada nos dois sentidos (Dropstar,
|
||||
// 23/10/2026): 19,5 x 18,5 cm cabe 2 por linha de pé e 3 deitada.
|
||||
const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte);
|
||||
return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W;});
|
||||
const deitadas=new Set();
|
||||
const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p))
|
||||
? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W);
|
||||
const virar=arte=>deitadas.has(arte)?deitadas.delete(arte):deitadas.add(arte);
|
||||
let melhor=montar();
|
||||
for(let volta=0;volta<2;volta++){
|
||||
let mudou=false;
|
||||
for(const arte of giraveis){
|
||||
virar(arte);
|
||||
const teste=montar();
|
||||
if(teste.altura<melhor.altura-1e-9){melhor=teste;mudou=true;}
|
||||
else virar(arte);
|
||||
}
|
||||
if(!mudou) break;
|
||||
}
|
||||
return melhor;
|
||||
}
|
||||
// As mais altas primeiro; cada uma na primeira linha onde couber.
|
||||
function emLinhas(itens,W){
|
||||
const ordem=[...itens].sort((a,b)=>b.h-a.h||b.w-a.w);
|
||||
const linhas=[];
|
||||
for(const it of ordem){
|
||||
const linha=linhas.find(l=>l.soma+it.w+(l.itens.length+2)*FOLGA_MIN_CM<=W+1e-9);
|
||||
if(linha){ linha.itens.push(it); linha.soma+=it.w; }
|
||||
else linhas.push({itens:[it],soma:it.w,h:it.h}); // sozinha, cabe sempre
|
||||
}
|
||||
const pos=[];
|
||||
let y=MARGEM_CM, folgaMin=MARGEM_CM;
|
||||
linhas.forEach((l,i)=>{
|
||||
const folga=Math.min(MARGEM_CM,(W-l.soma)/(l.itens.length+1));
|
||||
folgaMin=Math.min(folgaMin,folga);
|
||||
let x=folga;
|
||||
for(const it of l.itens){ pos.push({x,y,w:it.w,h:it.h,rot:it.rot,ref:it.ref}); x+=it.w+folga; }
|
||||
y+=l.h+(i<linhas.length-1?MARGEM_CM:0);
|
||||
});
|
||||
return {pos, altura:y+MARGEM_CM, folga:folgaMin};
|
||||
}
|
||||
// O encaixe pela forma dentro das margens: 5 mm em cima e embaixo e, dos
|
||||
// lados, 5 mm ou o que a peça mais larga deixar.
|
||||
function encaixarComMargens(pecas,W){
|
||||
const maior=Math.max(...pecas.map(p=>p.w));
|
||||
const lado=Math.max(0,Math.min(MARGEM_CM,(W-maior)/2));
|
||||
const enc=encaixarPelaForma(pecas,W-2*lado);
|
||||
return {pos:enc.pos.map(p=>({...p, x:p.x+lado, y:p.y+MARGEM_CM})),
|
||||
altura:enc.altura+2*MARGEM_CM, folga:lado};
|
||||
}
|
||||
|
||||
// Encaixe pela forma: mapa de ocupação real, máscara por arte e candidatos
|
||||
// numa grade de 5 mm ao longo da largura.
|
||||
function encaixarPelaForma(pecas,W){
|
||||
const cols=Math.ceil(W/CEL)+1; // +1 = a coluna de folga da dilatação
|
||||
let linhas=0; const mapa=[];
|
||||
function garantir(ate){ while(linhas<ate){ mapa.push(new Uint8Array(cols)); linhas++; } }
|
||||
|
||||
function colide(m,cx,cy){
|
||||
if(cx<0||cy<0||cx+m.cw>cols) return true;
|
||||
for(let y=0;y<m.ch;y++){
|
||||
const gy=cy+y;
|
||||
if(gy>=linhas) continue; // vazio abaixo do que já existe
|
||||
const L=mapa[gy], off=y*m.cw;
|
||||
for(let x=0;x<m.cw;x++)
|
||||
if(m.bits[off+x] && L[cx+x]) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function ocupar(m,cx,cy){
|
||||
garantir(cy+m.ch);
|
||||
for(let y=0;y<m.ch;y++){
|
||||
const L=mapa[cy+y], off=y*m.cw;
|
||||
for(let x=0;x<m.cw;x++) if(m.bits[off+x]) L[cx+x]=1;
|
||||
}
|
||||
}
|
||||
|
||||
const postas=[];
|
||||
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
||||
throw new RangeError('A largura solicitada não cabe no filme.');
|
||||
const ordem=[...pecas].sort((a,b)=>(b.w*b.h)-(a.w*a.h));
|
||||
|
||||
ordem.forEach(p=>{
|
||||
const oris=[{w:p.w,h:p.h,rot:0}];
|
||||
if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90});
|
||||
|
||||
let melhor=null;
|
||||
oris.forEach(o=>{
|
||||
if(o.w>W) return;
|
||||
// a máscara segue a medida da orientação escolhida · girada, largura e altura trocam
|
||||
const m = (p.mPronta && o.rot===0) ? p.mPronta : mascara(p.img, o.w, o.h,
|
||||
o.rot+(p.a?.giro||0), p.a?.esp);
|
||||
const xs=new Set([0]), ys=new Set([0]);
|
||||
postas.forEach(q=>{ xs.add(q.cx+q.m.cw); xs.add(q.cx); ys.add(q.cy+q.m.ch); ys.add(q.cy); });
|
||||
const passoX=Math.max(1,Math.round(cols/34));
|
||||
for(let x=0;x+m.cw<=cols;x+=passoX) xs.add(x);
|
||||
xs.add(cols-m.cw);
|
||||
const passoY=Math.max(1,Math.round(Math.max(linhas,1)/50));
|
||||
for(let y=0;y<=linhas;y+=passoY) ys.add(y);
|
||||
const XS=[...xs].filter(x=>x>=0 && x+m.cw<=cols && x*CEL+o.w<=W+0.01).sort((a,b)=>a-b);
|
||||
const YS=[...ys].filter(y=>y>=0).sort((a,b)=>a-b);
|
||||
|
||||
for(const cy of YS){
|
||||
if(melhor && cy*CEL > melhor.y + CEL) break;
|
||||
for(const cx of XS){
|
||||
if(cx*CEL + o.w > W + 0.01) continue; // não deixa a peça sair do filme
|
||||
if(colide(m,cx,cy)) continue;
|
||||
const cand={cx,cy,m,x:cx*CEL,y:cy*CEL,w:o.w,h:o.h,rot:o.rot,ref:p};
|
||||
// menor y, depois menor x · em empate, mantém a orientação original.
|
||||
// Desempatar por largura gira tudo, e texto deitado na prévia parece erro.
|
||||
const ganha = !melhor || cand.y<melhor.y ||
|
||||
(cand.y===melhor.y && cand.x<melhor.x) ||
|
||||
(cand.y===melhor.y && cand.x===melhor.x && cand.rot===0 && melhor.rot!==0);
|
||||
if(ganha) melhor=cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
if(!melhor){
|
||||
const m=mascara(p.img,p.w,p.h,p.a?.giro||0,p.a?.esp);
|
||||
melhor={cx:0,cy:linhas,m,x:0,y:linhas*CEL,w:p.w,h:p.h,rot:0,ref:p};
|
||||
}
|
||||
// a folga só existe entre peças, não é folha cobrada
|
||||
ocupar(melhor.m,melhor.cx,melhor.cy);
|
||||
postas.push(melhor);
|
||||
});
|
||||
|
||||
const altura=Math.max(...postas.map(p=>p.y+p.h),1);
|
||||
return {pos:postas, altura};
|
||||
}
|
||||
|
||||
// O que o encaixe entrega a quem salva a montagem: cada peça em centímetros.
|
||||
function placementsDe(pos){
|
||||
return pos.map(p=>({source_index:p.ref.a.sourceIndex,
|
||||
copy_index:p.ref.copyIndex,x_cm:+p.x.toFixed(4),y_cm:+p.y.toFixed(4),
|
||||
width_cm:+p.w.toFixed(4),length_cm:+p.h.toFixed(4),
|
||||
rotation_degrees:(p.rot+(p.ref.a.giro||0))%360,
|
||||
mirrored:!!p.ref.a.esp}));
|
||||
}
|
||||
@@ -83,208 +83,6 @@ function marcaDagua(ctx,w,h){
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
const CEL=GAP_CM; // célula da máscara, em cm = a folga de 5 mm
|
||||
// Dilata 1 célula para a direita e para baixo. Como toda peça é dilatada igual,
|
||||
// duas vizinhas ficam separadas por exatamente 1 célula — os 5 mm da regra.
|
||||
function dilatar(bruto,cw,ch,cheias){
|
||||
const cw2=cw+1, ch2=ch+1;
|
||||
const out=new Uint8Array(cw2*ch2);
|
||||
for(let y=0;y<ch;y++) for(let x=0;x<cw;x++){
|
||||
if(!bruto[y*cw+x]) continue;
|
||||
out[y*cw2+x]=1; out[y*cw2+x+1]=1; out[(y+1)*cw2+x]=1; out[(y+1)*cw2+x+1]=1;
|
||||
}
|
||||
return {cw:cw2,ch:ch2,bits:out,cheias}; // cheias = área de arte, sem a folga
|
||||
}
|
||||
function mascara(img,w,h,rot,esp=false){
|
||||
const cw=Math.max(1,Math.ceil(w/CEL)), ch=Math.max(1,Math.ceil(h/CEL));
|
||||
const cv=document.createElement('canvas');
|
||||
cv.width=cw; cv.height=ch;
|
||||
const ctx=cv.getContext('2d',{willReadFrequently:true});
|
||||
let bruto, cheias;
|
||||
if(!img){ // sem imagem: caixa cheia
|
||||
bruto=new Uint8Array(cw*ch).fill(1); cheias=cw*ch;
|
||||
return dilatar(bruto,cw,ch,cheias);
|
||||
}
|
||||
ctx.save();
|
||||
ctx.translate(cw/2,ch/2);
|
||||
ctx.rotate(rot*Math.PI/180);
|
||||
if(esp) ctx.scale(-1,1);
|
||||
const dw=rot%180===90?ch:cw, dh=rot%180===90?cw:ch;
|
||||
ctx.drawImage(img,-dw/2,-dh/2,dw,dh);
|
||||
ctx.restore();
|
||||
const d=ctx.getImageData(0,0,cw,ch).data;
|
||||
bruto=new Uint8Array(cw*ch); cheias=0;
|
||||
for(let i=0,j=3;i<bruto.length;i++,j+=4){ bruto[i] = d[j]>16 ? 1 : 0; cheias+=bruto[i]; }
|
||||
return dilatar(bruto,cw,ch,cheias);
|
||||
}
|
||||
|
||||
// Margens e folgas da folha (regra da Dropstar, 21/10/2026): 5 mm em cima,
|
||||
// embaixo e entre as linhas. Na largura, 5 mm nas bordas e entre as peças como
|
||||
// alvo; quando não cabem, a sobra é dividida em partes iguais, e duas peças só
|
||||
// ficam lado a lado com pelo menos 1,5 mm entre elas e nas bordas.
|
||||
const MARGEM_CM=0.5, FOLGA_MIN_CM=0.15;
|
||||
// Pela forma, as peças se aproximam (favo de mel) e as colunas se deslocam.
|
||||
// Só compensa quando a folha encurta de verdade; senão, colunas alinhadas.
|
||||
const GANHO_FORMA_CM=1;
|
||||
|
||||
// pecas em centímetros: {w,h,img,a,travado}. W é a largura do filme em cm.
|
||||
// Devolve {pos, altura, folga}: a altura já com as margens, a folga a menor
|
||||
// usada na largura.
|
||||
function encaixar(pecas,W){
|
||||
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
||||
throw new RangeError('A largura solicitada não cabe no filme.');
|
||||
const linhas=encaixarEmLinhas(pecas,W);
|
||||
const forma=encaixarComMargens(pecas,W);
|
||||
if(forma.altura<=linhas.altura-GANHO_FORMA_CM) return forma;
|
||||
// A máscara de cada peça: a área de arte que a prévia mostra como aproveitada.
|
||||
const mascaras=new Map();
|
||||
linhas.pos.forEach(p=>{
|
||||
const k=p.ref.a||p.ref, giro=p.rot+(p.ref.a?.giro||0);
|
||||
if(!mascaras.has(k)) mascaras.set(k,new Map());
|
||||
const daArte=mascaras.get(k);
|
||||
if(!daArte.has(p.rot)) daArte.set(p.rot,mascara(p.ref.img,p.w,p.h,giro,p.ref.a?.esp));
|
||||
p.m=daArte.get(p.rot);
|
||||
});
|
||||
return linhas;
|
||||
}
|
||||
|
||||
// Em linhas, com as medidas exatas: cada arte (todas as cópias juntas) fica de
|
||||
// pé ou deitada, a que der a folha mais curta. Em arte retangular, girar 90° é
|
||||
// o que mais economiza filme.
|
||||
function encaixarEmLinhas(pecas,W){
|
||||
const arteDe=p=>p.a||p;
|
||||
const artes=[...new Set(pecas.map(arteDe))];
|
||||
// Toda peça que não é quadrada é testada nos dois sentidos (Dropstar,
|
||||
// 23/10/2026): 19,5 x 18,5 cm cabe 2 por linha de pé e 3 deitada.
|
||||
const giraveis=artes.filter(arte=>{const p=pecas.find(q=>arteDe(q)===arte);
|
||||
return !p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W;});
|
||||
const deitadas=new Set();
|
||||
const montar=()=>emLinhas(pecas.map(p=>deitadas.has(arteDe(p))
|
||||
? {ref:p,w:p.h,h:p.w,rot:90} : {ref:p,w:p.w,h:p.h,rot:0}),W);
|
||||
const virar=arte=>deitadas.has(arte)?deitadas.delete(arte):deitadas.add(arte);
|
||||
let melhor=montar();
|
||||
for(let volta=0;volta<2;volta++){
|
||||
let mudou=false;
|
||||
for(const arte of giraveis){
|
||||
virar(arte);
|
||||
const teste=montar();
|
||||
if(teste.altura<melhor.altura-1e-9){melhor=teste;mudou=true;}
|
||||
else virar(arte);
|
||||
}
|
||||
if(!mudou) break;
|
||||
}
|
||||
return melhor;
|
||||
}
|
||||
// As mais altas primeiro; cada uma na primeira linha onde couber.
|
||||
function emLinhas(itens,W){
|
||||
const ordem=[...itens].sort((a,b)=>b.h-a.h||b.w-a.w);
|
||||
const linhas=[];
|
||||
for(const it of ordem){
|
||||
const linha=linhas.find(l=>l.soma+it.w+(l.itens.length+2)*FOLGA_MIN_CM<=W+1e-9);
|
||||
if(linha){ linha.itens.push(it); linha.soma+=it.w; }
|
||||
else linhas.push({itens:[it],soma:it.w,h:it.h}); // sozinha, cabe sempre
|
||||
}
|
||||
const pos=[];
|
||||
let y=MARGEM_CM, folgaMin=MARGEM_CM;
|
||||
linhas.forEach((l,i)=>{
|
||||
const folga=Math.min(MARGEM_CM,(W-l.soma)/(l.itens.length+1));
|
||||
folgaMin=Math.min(folgaMin,folga);
|
||||
let x=folga;
|
||||
for(const it of l.itens){ pos.push({x,y,w:it.w,h:it.h,rot:it.rot,ref:it.ref}); x+=it.w+folga; }
|
||||
y+=l.h+(i<linhas.length-1?MARGEM_CM:0);
|
||||
});
|
||||
return {pos, altura:y+MARGEM_CM, folga:folgaMin};
|
||||
}
|
||||
// O encaixe pela forma dentro das margens: 5 mm em cima e embaixo e, dos
|
||||
// lados, 5 mm ou o que a peça mais larga deixar.
|
||||
function encaixarComMargens(pecas,W){
|
||||
const maior=Math.max(...pecas.map(p=>p.w));
|
||||
const lado=Math.max(0,Math.min(MARGEM_CM,(W-maior)/2));
|
||||
const enc=encaixarPelaForma(pecas,W-2*lado);
|
||||
return {pos:enc.pos.map(p=>({...p, x:p.x+lado, y:p.y+MARGEM_CM})),
|
||||
altura:enc.altura+2*MARGEM_CM, folga:lado};
|
||||
}
|
||||
|
||||
// Encaixe pela forma: mapa de ocupação real, máscara por arte e candidatos
|
||||
// numa grade de 5 mm ao longo da largura.
|
||||
function encaixarPelaForma(pecas,W){
|
||||
const cols=Math.ceil(W/CEL)+1; // +1 = a coluna de folga da dilatação
|
||||
let linhas=0; const mapa=[];
|
||||
function garantir(ate){ while(linhas<ate){ mapa.push(new Uint8Array(cols)); linhas++; } }
|
||||
|
||||
function colide(m,cx,cy){
|
||||
if(cx<0||cy<0||cx+m.cw>cols) return true;
|
||||
for(let y=0;y<m.ch;y++){
|
||||
const gy=cy+y;
|
||||
if(gy>=linhas) continue; // vazio abaixo do que já existe
|
||||
const L=mapa[gy], off=y*m.cw;
|
||||
for(let x=0;x<m.cw;x++)
|
||||
if(m.bits[off+x] && L[cx+x]) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function ocupar(m,cx,cy){
|
||||
garantir(cy+m.ch);
|
||||
for(let y=0;y<m.ch;y++){
|
||||
const L=mapa[cy+y], off=y*m.cw;
|
||||
for(let x=0;x<m.cw;x++) if(m.bits[off+x]) L[cx+x]=1;
|
||||
}
|
||||
}
|
||||
|
||||
const postas=[];
|
||||
if(pecas.some(p=>!Number.isFinite(p.w) || p.w<=0 || p.w>W))
|
||||
throw new RangeError('A largura solicitada não cabe no filme.');
|
||||
const ordem=[...pecas].sort((a,b)=>(b.w*b.h)-(a.w*a.h));
|
||||
|
||||
ordem.forEach(p=>{
|
||||
const oris=[{w:p.w,h:p.h,rot:0}];
|
||||
if(!p.mPronta && !p.travado && Math.abs(p.w-p.h)>0.01 && p.h<=W) oris.push({w:p.h,h:p.w,rot:90});
|
||||
|
||||
let melhor=null;
|
||||
oris.forEach(o=>{
|
||||
if(o.w>W) return;
|
||||
// a máscara segue a medida da orientação escolhida · girada, largura e altura trocam
|
||||
const m = (p.mPronta && o.rot===0) ? p.mPronta : mascara(p.img, o.w, o.h,
|
||||
o.rot+(p.a?.giro||0), p.a?.esp);
|
||||
const xs=new Set([0]), ys=new Set([0]);
|
||||
postas.forEach(q=>{ xs.add(q.cx+q.m.cw); xs.add(q.cx); ys.add(q.cy+q.m.ch); ys.add(q.cy); });
|
||||
const passoX=Math.max(1,Math.round(cols/34));
|
||||
for(let x=0;x+m.cw<=cols;x+=passoX) xs.add(x);
|
||||
xs.add(cols-m.cw);
|
||||
const passoY=Math.max(1,Math.round(Math.max(linhas,1)/50));
|
||||
for(let y=0;y<=linhas;y+=passoY) ys.add(y);
|
||||
const XS=[...xs].filter(x=>x>=0 && x+m.cw<=cols && x*CEL+o.w<=W+0.01).sort((a,b)=>a-b);
|
||||
const YS=[...ys].filter(y=>y>=0).sort((a,b)=>a-b);
|
||||
|
||||
for(const cy of YS){
|
||||
if(melhor && cy*CEL > melhor.y + CEL) break;
|
||||
for(const cx of XS){
|
||||
if(cx*CEL + o.w > W + 0.01) continue; // não deixa a peça sair do filme
|
||||
if(colide(m,cx,cy)) continue;
|
||||
const cand={cx,cy,m,x:cx*CEL,y:cy*CEL,w:o.w,h:o.h,rot:o.rot,ref:p};
|
||||
// menor y, depois menor x · em empate, mantém a orientação original.
|
||||
// Desempatar por largura gira tudo, e texto deitado na prévia parece erro.
|
||||
const ganha = !melhor || cand.y<melhor.y ||
|
||||
(cand.y===melhor.y && cand.x<melhor.x) ||
|
||||
(cand.y===melhor.y && cand.x===melhor.x && cand.rot===0 && melhor.rot!==0);
|
||||
if(ganha) melhor=cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
if(!melhor){
|
||||
const m=mascara(p.img,p.w,p.h,p.a?.giro||0,p.a?.esp);
|
||||
melhor={cx:0,cy:linhas,m,x:0,y:linhas*CEL,w:p.w,h:p.h,rot:0,ref:p};
|
||||
}
|
||||
// a folga só existe entre peças, não é folha cobrada
|
||||
ocupar(melhor.m,melhor.cx,melhor.cy);
|
||||
postas.push(melhor);
|
||||
});
|
||||
|
||||
const altura=Math.max(...postas.map(p=>p.y+p.h),1);
|
||||
return {pos:postas, altura};
|
||||
}
|
||||
|
||||
function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
||||
const versao=area.montagemVersao=(area.montagemVersao||0)+1;
|
||||
const filme=larguraFilme(), PX_CM=W/filme;
|
||||
@@ -356,11 +154,7 @@ function desenhaMontagem(area,lista,mts,W,fora,aoTerminar){
|
||||
(girou>1?' artes giradas':' arte girada')+' 90°</b> para caber melhor':'');
|
||||
(fora||area).appendChild(el);
|
||||
if(aoTerminar) aoTerminar({alturaCm, uso, girou, folgaCm:enc.folga,
|
||||
placements:enc.pos.map(p=>({source_index:p.ref.a.sourceIndex,
|
||||
copy_index:p.ref.copyIndex,x_cm:+p.x.toFixed(4),y_cm:+p.y.toFixed(4),
|
||||
width_cm:+p.w.toFixed(4),length_cm:+p.h.toFixed(4),
|
||||
rotation_degrees:(p.rot+(p.ref.a.giro||0))%360,
|
||||
mirrored:!!p.ref.a.esp}))});
|
||||
placements:placementsDe(enc.pos)});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user