import {createLiveEdit} from './live-edit.mjs'; import {jacquardFromImage,projectDrapeMesh} from './advanced-effects.mjs'; const $=id=>document.getElementById(id);let state,request=800000,loadedImage=null,loadEpoch=0; const dialog=document.createElement('dialog');dialog.id='advancedEffectsDialog';dialog.style.width='720px';dialog.innerHTML=`

`;document.body.append(dialog);let target,revision,pending; const explicitTool=()=>target==='jacquard'||target==='drape'; const emit=(name,detail)=>window.dispatchEvent(new CustomEvent(name,{detail})); function number(id,label,value,min,max,step='any'){const l=document.createElement('label');l.textContent=label;const input=document.createElement('input');Object.assign(input,{id,type:'number',value,min,max,step});l.append(input);$('effectFields').append(l);return input;} function select(id,label,options,value){const l=document.createElement('label');l.textContent=label;const s=document.createElement('select');s.id=id;for(const[v,text]of options)s.add(new Option(text,v));s.value=String(value);l.append(s);$('effectFields').append(l);return s;} function note(text){const p=document.createElement('p');p.className='note';p.textContent=text;$('effectFields').append(p);} function imageChooser(){ const input=document.createElement('input'); input.id='effectImage';input.type='file';input.accept='image/png,image/jpeg,image/bmp,image/webp'; $('effectFields').append(input); input.onchange=async()=>{ const file=input.files[0],epoch=++loadEpoch; loadedImage=null;$('effectApply').disabled=true; if(!file)return; try{ if(file.size>12*1024*1024)throw Error('Image exceeds 12 MB.'); const bitmap=await createImageBitmap(file); if(epoch!==loadEpoch){bitmap.close();return;} const c=$('effectCanvas'),ratio=Math.min(1,512/Math.max(bitmap.width,bitmap.height)); c.width=Math.max(1,Math.round(bitmap.width*ratio));c.height=Math.max(1,Math.round(bitmap.height*ratio)); const ctx=c.getContext('2d'); ctx.drawImage(bitmap,0,0,c.width,c.height);bitmap.close(); loadedImage={width:c.width,height:c.height,rgba:ctx.getImageData(0,0,c.width,c.height).data}; c.hidden=false;$('effectApply').disabled=false; $('effectStatus').textContent=file.name+' · '+c.width+' × '+c.height+' px'; }catch(error){if(epoch===loadEpoch)$('effectStatus').textContent=error.message;} }; } const n=id=>Number($(id).value),colour=id=>[1,3,5].map(i=>parseInt($(id).value.slice(i,i+2),16)); function commit(doc){const id=++request;pending=id;emit('cad:edit',{id,type:'replace-project',revision:state.revision,project:doc});} function open(name){if(!state)return;liveEffect.cancel();target=name;revision=state.revision;dialog.dataset.tool=name;dialog.style.width=name==='drape'?'1020px':'720px';loadEpoch++;loadedImage=null;$('effectFields').replaceChildren();$('effectCanvas').hidden=true;$('effectDownload').hidden=true;$('effectRemove').hidden=name==='jacquard';$('effectApply').hidden=!explicitTool();$('effectApply').disabled=false;$('effectSaveDrape').hidden=name!=='drape';$('effectStatus').textContent='';$('effectDescription').textContent='Independent web tool. Native finishing equivalence is not verified.';const e=state.project.webEffects||{}; if(name==='jacquard'){$('effectTitle').textContent='Jacquard image → weave';imageChooser();number('jacWidth','Warp ends',64,1,250,1);number('jacHeight','Weft picks',64,1,4096,1);for(let i=0;i<2;i++){const l=document.createElement('label');l.textContent='Image colour '+(i+1);const c=document.createElement('input');c.type='color';c.id='jacColour'+i;c.value=i?'#FFFFFF':'#000000';l.append(c);$('effectFields').append(l);select('jacWeave'+i,'Assigned weave',[['plain','Plain1/1'],['twill','Twill2/2'],['warp-satin','Warp satin4/1'],['weft-satin','Weft satin1/4']],i?'plain':'twill');}note('Nearest displayed RGB assigns each image pixel to one of your selected weave structures. This creates a new single-cloth weave; counts and yarn plans stay unchanged. Not loom-ready CAM cards. Maximum250,000cells.');} if(name==='seersucker'){$('effectTitle').textContent='Seersucker / procedural wrinkles';number('puckerAmp','Pucker amplitude · mm',e.seersucker?.amplitudeMM??.4,0,2,.05);number('puckerX','Warpwise stripe period · inch',e.seersucker?.repeatInches[0]??1,.05,100);number('puckerY','Lengthwise wave period · inch',e.seersucker?.repeatInches[1]??2,.05,100);note('Independent periodic displacement and relief shading. Flat construction dimensions stay unchanged; this is not a finished-shrinkage prediction.');} if(name==='high-quality'){$('effectTitle').textContent='High quality web simulation';select('qualityFactor','Samples',[['1','Standard1×'],['2','Supersampled2×per axis']],e.quality??1);note('Renders up to4samples per output pixel before downsampling. Uses a5million-sample frame budget and falls back to1×when exceeded.');} if(name==='illumination'){$('effectTitle').textContent='Directional illumination';number('lightAz','Light azimuth · degrees',e.lighting?.azimuth??45,0,360);number('lightAlt','Light elevation · degrees',e.lighting?.altitude??50,5,90);number('lightStrength','Relief intensity0–1',e.lighting?.strength??.4,0,1,.05);note('Image-gradient relief lighting applied to the current independent yarn simulation; not measured yarn3Dgeometry.');} if(name==='moire'){$('effectTitle').textContent='Reduce moiré';number('moireStrength','Filter strength0–1',e.moire??.35,0,1,.05);note('A3×3low-pass display filter reduces fine raster interference; it can soften very fine yarn detail. Source weave/yarn data is preserved.');} if(name==='drape'){$('effectTitle').textContent='3D drape projection';number('drapeFolds','Folds',e.drape?.folds??4,1,12,1);number('drapeDepth','Fold depth0–0.6',e.drape?.depth??.3,0,.6,.05);number('drapeTilt','Rotation · degrees',e.drape?.tilt??20,-45,45);$('effectRemove').hidden=!e.drape;$('effectApply').textContent='Render drape preview';note('Projects the current fabric onto a perspective3Dfolded mesh. Not garment fitting, measured cloth physics or native draping. Source CAD and calibrated flat view stay unchanged.');} else if(name==='jacquard')$('effectApply').textContent='Convert image to weave';dialog.showModal();} function weave(name){if(name==='plain')return[[1,0],[0,1]];if(name==='twill')return Array.from({length:4},(_,y)=>Array.from({length:4},(_,x)=>(x-y+4)%4<2?1:0));return Array.from({length:5},(_,y)=>Array.from({length:5},(_,x)=>Number(name==='warp-satin'?(x-y*2+10)%5!==0:(x-y*2+10)%5===0)));} function commitEffect(){try{if(!dialog.open)return;if([...$('effectFields').querySelectorAll('input[type=number]')].some(input=>!input.parentElement.hidden&&!input.value.trim()))return;if(state.revision!==revision)throw Error('Design changed. Reopen this tool.');if(state.raster)throw Error('Return to editable fabric simulation first');if(target==='drape'){drawDrape();return;}const doc=structuredClone(state.project),e=doc.webEffects||{};if(target==='jacquard'){if(state.indexed)throw Error('Open editable yarn CAD before changing weave');if(doc.cloth)throw Error('Jacquard conversion currently supports single cloth only');if(!loadedImage)throw Error('Choose an image first');doc.weave=jacquardFromImage(loadedImage,[0,1].map(i=>({rgb:colour('jacColour'+i),weave:weave($('jacWeave'+i).value)})),n('jacWidth'),n('jacHeight'));delete doc.interlacement;delete doc.sourceRepeatInches;doc.generatedJacquard={method:'nearest-image-colour weave assignment',imageWidth:loadedImage.width,imageHeight:loadedImage.height};}else{if(target==='seersucker')e.seersucker={amplitudeMM:n('puckerAmp'),repeatInches:[n('puckerX'),n('puckerY')]};if(target==='high-quality')e.quality=n('qualityFactor');if(target==='illumination')e.lighting={azimuth:n('lightAz'),altitude:n('lightAlt'),strength:n('lightStrength')};if(target==='moire')e.moire=n('moireStrength');doc.webEffects=e;}if(JSON.stringify(doc)!==JSON.stringify(state.project))commit(doc);}catch(e){$('effectStatus').textContent=e.message;}} const liveEffect=createLiveEdit(commitEffect); $('effectApply').onclick=commitEffect; $('effectFields').addEventListener('input',event=>{ if(!explicitTool()&&event.target.type==='number')liveEffect.schedule(); }); $('effectFields').addEventListener('change',event=>{ if(!explicitTool()&&event.target.type!=='file')liveEffect.flush(); }); dialog.addEventListener('close',()=>{ if(dialog.open)return; liveEffect.cancel(); loadEpoch++; }); $('effectRemove').onclick=()=>{liveEffect.cancel();const doc=structuredClone(state.project),key={'high-quality':'quality',illumination:'lighting',moire:'moire',seersucker:'seersucker',drape:'drape'}[target];if(doc.webEffects)delete doc.webEffects[key];if(!Object.keys(doc.webEffects||{}).length)delete doc.webEffects;commit(doc);}; function drawTriangle(ctx,img,a,b,c){const x0=a.u*img.width,y0=a.v*img.height,x1=b.u*img.width,y1=b.v*img.height,x2=c.u*img.width,y2=c.v*img.height,den=x0*(y1-y2)+x1*(y2-y0)+x2*(y0-y1);if(Math.abs(den)<1e-8)return;const affine=(p0,p1,p2)=>[(p0*(y1-y2)+p1*(y2-y0)+p2*(y0-y1))/den,(p0*(x2-x1)+p1*(x0-x2)+p2*(x1-x0))/den,(p0*(x1*y2-x2*y1)+p1*(x2*y0-x0*y2)+p2*(x0*y1-x1*y0))/den];const X=affine(a.x,b.x,c.x),Y=affine(a.y,b.y,c.y);ctx.save();ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.lineTo(c.x,c.y);ctx.closePath();ctx.clip();ctx.transform(X[0],Y[0],X[1],Y[1],X[2],Y[2]);ctx.drawImage(img,0,0);ctx.restore();const shade=(a.shade+b.shade+c.shade)/3;if(shade<1){ctx.fillStyle='rgba(0,0,0,'+(1-shade)+')';ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.lineTo(c.x,c.y);ctx.closePath();ctx.fill();}} function drawDrape(){if($('png').disabled)throw Error('Wait for the current fabric simulation');const src=$('fabric'),snapshot=document.createElement('canvas');snapshot.width=src.width;snapshot.height=src.height;snapshot.getContext('2d').drawImage(src,0,0);const c=$('effectCanvas');c.width=1000;c.height=760;c.hidden=false;const ctx=c.getContext('2d');ctx.fillStyle='#e6e3dc';ctx.fillRect(0,0,c.width,c.height);const mesh=projectDrapeMesh(c.width,c.height,{folds:n('drapeFolds'),depth:n('drapeDepth'),tilt:n('drapeTilt')});for(let y=0;y{try{const doc=structuredClone(state.project);doc.webEffects={...doc.webEffects,drape:{folds:n('drapeFolds'),depth:n('drapeDepth'),tilt:n('drapeTilt')}};commit(doc);}catch(e){$('effectStatus').textContent=e.message;}}; $('effectDownload').onclick=()=>{const a=document.createElement('a');a.download=state.article+'-drape-preview.png';a.href=$('effectCanvas').toDataURL('image/png');a.click();};$('effectClose').onclick=()=>{loadEpoch++;dialog.close();}; window.addEventListener('cad:document',e=>{state=e.detail;if(dialog.open&&target==='drape'){$('effectDownload').hidden=true;$('effectCanvas').hidden=true;$('effectStatus').textContent='Design changed; render a new preview';}});window.addEventListener('cad:advanced-tool',e=>{if(['jacquard','seersucker','high-quality','illumination','moire','drape'].includes(e.detail.target))open(e.detail.target);});window.addEventListener('cad:edit-result',e=>{if(e.detail.id!==pending)return; pending=undefined; if(!e.detail.ok){$('effectStatus').textContent=e.detail.error;return;} revision=state.revision; if(explicitTool())dialog.close(); else $('effectStatus').textContent='Fabric updated.';});emit('cad:request-state');