markuno_lib 1.2.27 → 1.2.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/markcad.js +5 -5
- package/bin/markuno.js +1 -1
- package/package.json +1 -1
- package/types/markcad.d.ts +2 -0
- package/types/markuno.d.ts +1 -0
package/bin/markcad.js
CHANGED
|
@@ -538,7 +538,7 @@ function calcoladivisioni(ff,notused,shape2,oggetti){return makedivisions(ff,sha
|
|
|
538
538
|
* @param {THREE.Material} [mat=null] - Materiale da applicare
|
|
539
539
|
* @param {number} [size=5] - Dimensione della sfera
|
|
540
540
|
* @returns {THREE.Mesh} Punto 3D
|
|
541
|
-
*/function getpoint(p,id,mat=null,size=5){const pointgeom=new THREE.SphereGeometry(size,8,8);let tm=new THREE.Mesh(pointgeom,mat||randombasemat());return tm.position.set(p.x,0,p.y),tm}async function smat(gcad,file,op={}){op||(op={});let ky=hash(file+JSON.stringify(op));return gcad.smats[ky]||(gcad.smats[ky]=await async function smat0(gcad,file,op={}){let fileini=file,paramstr="",isColore=!1;file.startsWith("#")&&(isColore=!0,/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?=$|[\[(])/.test(file)||(file=file.slice(1)));let basefile=file;const paramMatch=file.match(/^(.*)\[([^\]]+)\]$/);paramMatch&&(basefile=paramMatch[1],paramstr=paramMatch[2]);const p={};paramstr&¶mstr.split(/[,;]/).forEach((kv=>{let[k,v]=kv.split("=").map((x=>x.trim()));void 0!==v&&(["e"].includes(k)?p[k]=v.startsWith("0x")?parseInt(v):parseFloat(v):isNaN(parseFloat(v))?p[k]=v:p[k]=parseFloat(v))}));const mappaParam={s:["sx","sy"],sx:["sx"],sy:["sy"],rot:["rot"],br:["brightness"],r:["roughness"],m:["metalness"],h:["bumpScale"],n:["normalScale"],d:["bumpScale"],b:["bumpScale"],e:["emissiveIntensity"],ec:["emissive"],o:["opacity"],t:["transparent"],at:["alphaTest"]};let optot={...op};for(let k in p)if(mappaParam[k])for(let t of mappaParam[k])optot[t]=p[k];let sx=optot.sx??optot.s??p.sx??p.s??1,sy=optot.sy??optot.s??p.sy??p.s??1,rot=Number(optot.rot??0)*PIF;try{let tm={roughness:optot.roughness??.5,metalness:optot.metalness??0,side:THREE.DoubleSide,envMapIntensity:optot.env??1};if(void 0!==optot.normalScale){let ns=Number(optot.normalScale);isNaN(ns)||0===ns||(tm.normalScale=new THREE.Vector2(ns,ns))}let hasNormal=!1,hasBump=!1;if(file.includes("(")||isColore){let{base:base,files:files}=function getFilesToLoad(isColore,basefile){let files=[],m=basefile.match(/^([^(]+)\((([a-zA-Z0-9_\-\/]+)_([a-z]+)|([a-z]+))\)$/);if(!m)return{base:basefile,files:files};let base=m[1],mapalias=m[3]||base,suffstr=m[4]||m[5]||"";isColore||files.push({suff:"",file:`${base}.webp`});for(let s of suffstr)suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`});return{base:base,files:files}}(isColore,basefile);if(files.some((f=>"n"===f.suff))&&(files=files.filter((f=>"h"!==f.suff))),0===optot.roughness&&(files=files.filter((f=>"r"!==f.suff))),0===optot.metalness&&(files=files.filter((f=>"m"!==f.suff))),0===optot.emissiveIntensity&&(files=files.filter((f=>"e"!==f.suff))),files&&files.length){let textures=await Promise.all(files.map((f=>gcad.tex(f.file,sx,sy,rot).catch((()=>null)))));for(let i=0;i<files.length;i++){let t=textures[i];if(!t)continue;let suff=files[i].suff,{prop:prop,extra:extra}=suffissoMap[suff];tm[prop]=t,"normalMap"===extra?(hasNormal=!0,tm.normalMap=t,tm.normalScale=tm.normalScale??new THREE.Vector2(1,1)):"bumpScale"===extra?(hasBump=!0,tm.bumpMap=t):Array.isArray(extra)&&extra.includes("emissive")&&void 0!==optot.emissiveIntensity&&0!==optot.emissiveIntensity&&(tm.emissive=optot.emissive||16777215,tm.emissiveIntensity=optot.emissiveIntensity??1)}}isColore&&(tm.color=new THREE.Color(base))}else if(basefile.includes(".")){let tx=await gcad.tex(basefile,sx,sy,rot);if(!tx)return mwhite;tm.map=tx}if(hasNormal&&hasBump?delete tm.bumpMap:hasBump&&(tm.bumpScale=optot.bumpScale??.03),
|
|
541
|
+
*/function getpoint(p,id,mat=null,size=5){const pointgeom=new THREE.SphereGeometry(size,8,8);let tm=new THREE.Mesh(pointgeom,mat||randombasemat());return tm.position.set(p.x,0,p.y),tm}async function smat(gcad,file,op={}){op||(op={});let ky=hash(file+JSON.stringify(op));return gcad.smats[ky]||(gcad.smats[ky]=await async function smat0(gcad,file,op={}){let fileini=file,paramstr="",isColore=!1;file.startsWith("#")&&(isColore=!0,/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?=$|[\[(])/.test(file)||(file=file.slice(1)));let basefile=file;const paramMatch=file.match(/^(.*)\[([^\]]+)\]$/);paramMatch&&(basefile=paramMatch[1],paramstr=paramMatch[2]);const p={};paramstr&¶mstr.split(/[,;]/).forEach((kv=>{let[k,v]=kv.split("=").map((x=>x.trim()));void 0!==v&&(["e"].includes(k)?p[k]=v.startsWith("0x")?parseInt(v):parseFloat(v):isNaN(parseFloat(v))?p[k]=v:p[k]=parseFloat(v))}));const mappaParam={s:["sx","sy"],sx:["sx"],sy:["sy"],rot:["rot"],br:["brightness"],r:["roughness"],m:["metalness"],h:["bumpScale"],n:["normalScale"],d:["bumpScale"],b:["bumpScale"],e:["emissiveIntensity"],ec:["emissive"],o:["opacity"],t:["transparent"],at:["alphaTest"]};let optot={...op};for(let k in p)if(mappaParam[k])for(let t of mappaParam[k])optot[t]=p[k];let transparent=!!optot?.transparent,sx=optot.sx??optot.s??p.sx??p.s??1,sy=optot.sy??optot.s??p.sy??p.s??1,rot=Number(optot.rot??0)*PIF;try{let tm={roughness:optot.roughness??.5,metalness:optot.metalness??0,side:THREE.DoubleSide,envMapIntensity:optot.env??1};if(void 0!==optot.normalScale){let ns=Number(optot.normalScale);isNaN(ns)||0===ns||(tm.normalScale=new THREE.Vector2(ns,ns))}let hasNormal=!1,hasBump=!1;if(file.includes("(")||isColore){let{base:base,files:files,transparent:t2}=function getFilesToLoad(isColore,basefile){let files=[],m=basefile.match(/^([^(]+)\((([a-zA-Z0-9_\-\/]+)_([a-z]+)|([a-z]+))\)$/);if(!m)return{base:basefile,files:files};let base=m[1],transparent=!1,mapalias=m[3]||base,suffstr=m[4]||m[5]||"";isColore||files.push({suff:"",file:`${base}.webp`});for(let s of suffstr)"t"==s?(transparent=!0,m[3]&&suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`})):suffissoMap[s]&&files.push({suff:s,file:`${mapalias}_${s}.webp`});return{base:base,files:files,transparent:transparent}}(isColore,basefile);if(transparent=t2,files.some((f=>"n"===f.suff))&&(files=files.filter((f=>"h"!==f.suff))),0===optot.roughness&&(files=files.filter((f=>"r"!==f.suff))),0===optot.metalness&&(files=files.filter((f=>"m"!==f.suff))),0===optot.emissiveIntensity&&(files=files.filter((f=>"e"!==f.suff))),files&&files.length){let textures=await Promise.all(files.map((f=>gcad.tex(f.file,sx,sy,rot).catch((()=>null)))));for(let i=0;i<files.length;i++){let t=textures[i];if(!t)continue;let suff=files[i].suff,{prop:prop,extra:extra}=suffissoMap[suff];tm[prop]=t,"normalMap"===extra?(hasNormal=!0,tm.normalMap=t,tm.normalScale=tm.normalScale??new THREE.Vector2(1,1)):"bumpScale"===extra?(hasBump=!0,tm.bumpMap=t):Array.isArray(extra)&&extra.includes("emissive")&&void 0!==optot.emissiveIntensity&&0!==optot.emissiveIntensity&&(tm.emissive=optot.emissive||16777215,tm.emissiveIntensity=optot.emissiveIntensity??1)}}isColore&&(tm.color=new THREE.Color(base))}else if(basefile.includes(".")){let tx=await gcad.tex(basefile,sx,sy,rot);if(!tx)return mwhite;tm.map=tx}if(hasNormal&&hasBump?delete tm.bumpMap:hasBump&&(tm.bumpScale=optot.bumpScale??.03),tm.transparent=transparent,tm.transparent&&(tm.depthwrite=!0,tm.opacity=optot?.opacity??1),void 0!==optot.brightness){let bf=Number(optot.brightness);!isNaN(bf)&&bf>0&&1!==bf&&(tm.color||(tm.color=new THREE.Color(1,1,1)),tm.color.multiplyScalar(bf))}return new THREE.MeshStandardMaterial(tm)}catch(error){return console.log("errore mat:",error.message,fileini),mwhite}}
|
|
542
542
|
/**
|
|
543
543
|
* Estrae tutte le texture usate nella scena glb e le converte in file WEBP.
|
|
544
544
|
* @param {THREE.Object3D} root - nodo root (es: gltf.scene)
|
|
@@ -550,7 +550,7 @@ function calcoladivisioni(ff,notused,shape2,oggetti){return makedivisions(ff,sha
|
|
|
550
550
|
* @param {object} gcad - contesto CAD con funzione tex()
|
|
551
551
|
* @param {string} file - nome file o codice colore/parametri
|
|
552
552
|
* @param {object} op - opzioni aggiuntive
|
|
553
|
-
*/const suffissoMap={"":{prop:"map",extra:null},n:{prop:"normalMap",extra:null},a:{prop:"aoMap",extra:"aoMapIntensity"},r:{prop:"roughnessMap",extra:null},h:{prop:"bumpMap",extra:"bumpScale"},m:{prop:"metalnessMap",extra:null},e:{prop:"emissiveMap",extra:["emissive","emissiveIntensity"]}};async function extractTextures(root,baseName){const counters={},out=[];function getName(suffix){counters[suffix]=(counters[suffix]||0)+1;let base=baseName;return suffix&&(base+=`_${suffix}`),counters[suffix]>1&&(base+=counters[suffix]),`${base}.webp`}return root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const[suffix,{prop:prop}]of Object.entries(suffissoMap)){const tex=mat[prop];if(tex&&tex.image&&!tex._extracted){tex._extracted=!0;let promise,img=tex.image;if(img.toBlob)promise=new Promise((res=>img.toBlob(res,"image/webp")));else if(img instanceof ImageBitmap){const canvas=document.createElement("canvas");canvas.width=img.width,canvas.height=img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}else{if(!(img instanceof HTMLImageElement))continue;{const canvas=document.createElement("canvas");canvas.width=img.naturalWidth||img.width,canvas.height=img.naturalHeight||img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}}out.push(promise.then((blob=>new File([blob],getName(suffix),{type:"image/webp"}))))}}}})),root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const{prop:prop}of Object.values(suffissoMap)){const tex=mat[prop];tex&&tex._extracted&&delete tex._extracted}}})),Promise.all(out)}function getfakeshadow(gcad,shape,alfa){let ky=`fk${shape.key}${alfa}`,{p1:p1,width:width,height:height}=shape.dims();gcad.texture||(gcad.texture={});let tm=gcad.texture[ky];tm||(tm=function createBlurredShadowTextureFromPoints(mshape,size=256,blurPx=32,alpha=.2,p1,width,height){if(!width||!height||!mshape.pt||mshape.pt.length<2)return;const minX=p1.x,minY=p1.y,shapeWidth=width,shapeHeight=height,points=mshape.pt,extra=2*blurPx,canvas=document.createElement("canvas");canvas.width=size+2*extra,canvas.height=size+2*extra;const ctx=canvas.getContext("2d");ctx.save(),ctx.translate(extra,extra),ctx.scale(size/shapeWidth,size/shapeHeight),ctx.translate(-minX,-minY),ctx.filter=`blur(${blurPx}px)`,ctx.beginPath(),ctx.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)ctx.lineTo(points[i].x,points[i].y);ctx.closePath(),ctx.fillStyle=`rgba(0,0,0,${alpha})`,ctx.fill(),ctx.restore();const texture=new THREE.CanvasTexture(canvas);return texture.needsUpdate=!0,texture}(shape,256,32,alfa,p1,width,height),gcad.texture[ky]=tm);const fakeShape=function pointsToShape(points){const fakeShape=new THREE.Shape;fakeShape.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)fakeShape.lineTo(points[i].x,points[i].y);return fakeShape}(shape.pt),shadowGeometry=new THREE.ShapeGeometry(fakeShape);!function applyUVtoShapeGeometry(geometry,minX,minY,width,height){const pos=geometry.attributes.position,uv=[];for(let i=0;i<pos.count;i++){const x=pos.getX(i),y=pos.getY(i);uv.push((x-minX)/width,(y-minY)/height)}geometry.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2))}(shadowGeometry,p1.x,p1.y,width,height);const shadowMaterial=new THREE.MeshBasicMaterial({map:tm,transparent:!0,depthWrite:!1,side:THREE.DoubleSide});let ms=new THREE.Mesh(shadowGeometry,shadowMaterial);return ms.layers.set(9),ms.rotation.x=Math.PI/2,ms}function addmovpivot(gcad,grp,movimento,op={},x=0,y=0,z=0){if(movimento=clean(movimento,!0),!gcad.movs[movimento])return grp;gcad.movs[movimento];const pivotLocal=new THREE.Vector3(x,y,z),isZeroPivot=0===pivotLocal.lengthSq(),pivotGroup=new THREE.Group;pivotGroup.name=`pivot_${movimento}`;const movimentoGroup=new THREE.Group;if(movimentoGroup.name=`mov_${movimento}`,isZeroPivot)pivotGroup.position.copy(grp.position),pivotGroup.quaternion.copy(grp.quaternion),grp.position.set(0,0,0),grp.rotation.set(0,0,0);else{const pivotWorld=pivotLocal.clone().applyMatrix4(grp.matrixWorld);pivotGroup.position.copy(pivotWorld);const offset=pivotLocal.clone().negate();grp.position.add(offset),pivotGroup.quaternion.copy(grp.getWorldQuaternion(new THREE.Quaternion)),grp.rotation.set(0,0,0)}return movimentoGroup.add(grp),pivotGroup.add(movimentoGroup),op||(op={}),op.inmov=!1,op.key=movimento,op.dt=0,op.dtstart=!1,movimentoGroup.userData.mov={...op},pivotGroup}
|
|
553
|
+
*/const suffissoMap={"":{prop:"map",extra:null},n:{prop:"normalMap",extra:null},a:{prop:"aoMap",extra:"aoMapIntensity"},r:{prop:"roughnessMap",extra:null},h:{prop:"bumpMap",extra:"bumpScale"},t:{prop:"alphaMap",extra:null},m:{prop:"metalnessMap",extra:null},e:{prop:"emissiveMap",extra:["emissive","emissiveIntensity"]}};async function extractTextures(root,baseName){const counters={},out=[];function getName(suffix){counters[suffix]=(counters[suffix]||0)+1;let base=baseName;return suffix&&(base+=`_${suffix}`),counters[suffix]>1&&(base+=counters[suffix]),`${base}.webp`}return root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const[suffix,{prop:prop}]of Object.entries(suffissoMap)){const tex=mat[prop];if(tex&&tex.image&&!tex._extracted){tex._extracted=!0;let promise,img=tex.image;if(img.toBlob)promise=new Promise((res=>img.toBlob(res,"image/webp")));else if(img instanceof ImageBitmap){const canvas=document.createElement("canvas");canvas.width=img.width,canvas.height=img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}else{if(!(img instanceof HTMLImageElement))continue;{const canvas=document.createElement("canvas");canvas.width=img.naturalWidth||img.width,canvas.height=img.naturalHeight||img.height;canvas.getContext("2d").drawImage(img,0,0),promise=new Promise((res=>canvas.toBlob(res,"image/webp")))}}out.push(promise.then((blob=>new File([blob],getName(suffix),{type:"image/webp"}))))}}}})),root.traverse((obj=>{if(obj.material){const materials=Array.isArray(obj.material)?obj.material:[obj.material];for(const mat of materials)for(const{prop:prop}of Object.values(suffissoMap)){const tex=mat[prop];tex&&tex._extracted&&delete tex._extracted}}})),Promise.all(out)}function getfakeshadow2(w,h,map){const shape=(new THREE.Shape).moveTo(0,0).lineTo(w,0).lineTo(w,h).lineTo(0,h).lineTo(0,0),geometry=new THREE.ShapeGeometry(shape),pos=geometry.attributes.position,uv=new Float32Array(2*pos.count);for(let i=0;i<pos.count;i++)uv[2*i]=pos.getX(i)/w,uv[2*i+1]=pos.getY(i)/h;geometry.setAttribute("uv",new THREE.BufferAttribute(uv,2));const material=new THREE.MeshBasicMaterial({map:map,transparent:!0,alphaTest:.01,depthWrite:!1,side:THREE.DoubleSide}),mesh=new THREE.Mesh(geometry,material);return mesh.layers.set(9),mesh.rotation.x=Math.PI/2,mesh}function getfakeshadow(gcad,shape,alfa){let ky=`fk${shape.key}${alfa}`,{p1:p1,width:width,height:height}=shape.dims();gcad.texture||(gcad.texture={});let tm=gcad.texture[ky];tm||(tm=function createBlurredShadowTextureFromPoints(mshape,size=256,blurPx=32,alpha=.2,p1,width,height){if(!width||!height||!mshape.pt||mshape.pt.length<2)return;const minX=p1.x,minY=p1.y,shapeWidth=width,shapeHeight=height,points=mshape.pt,extra=2*blurPx,canvas=document.createElement("canvas");canvas.width=size+2*extra,canvas.height=size+2*extra;const ctx=canvas.getContext("2d");ctx.save(),ctx.translate(extra,extra),ctx.scale(size/shapeWidth,size/shapeHeight),ctx.translate(-minX,-minY),ctx.filter=`blur(${blurPx}px)`,ctx.beginPath(),ctx.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)ctx.lineTo(points[i].x,points[i].y);ctx.closePath(),ctx.fillStyle=`rgba(0,0,0,${alpha})`,ctx.fill(),ctx.restore();const texture=new THREE.CanvasTexture(canvas);return texture.needsUpdate=!0,texture}(shape,256,32,alfa,p1,width,height),gcad.texture[ky]=tm);const fakeShape=function pointsToShape(points){const fakeShape=new THREE.Shape;fakeShape.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;i++)fakeShape.lineTo(points[i].x,points[i].y);return fakeShape}(shape.pt),shadowGeometry=new THREE.ShapeGeometry(fakeShape);!function applyUVtoShapeGeometry(geometry,minX,minY,width,height){const pos=geometry.attributes.position,uv=[];for(let i=0;i<pos.count;i++){const x=pos.getX(i),y=pos.getY(i);uv.push((x-minX)/width,(y-minY)/height)}geometry.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2))}(shadowGeometry,p1.x,p1.y,width,height);const shadowMaterial=new THREE.MeshBasicMaterial({map:tm,transparent:!0,depthWrite:!1,side:THREE.DoubleSide});let ms=new THREE.Mesh(shadowGeometry,shadowMaterial);return ms.layers.set(9),ms.rotation.x=Math.PI/2,ms}function addmovpivot(gcad,grp,movimento,op={},x=0,y=0,z=0){if(movimento=clean(movimento,!0),!gcad.movs[movimento])return grp;gcad.movs[movimento];const pivotLocal=new THREE.Vector3(x,y,z),isZeroPivot=0===pivotLocal.lengthSq(),pivotGroup=new THREE.Group;pivotGroup.name=`pivot_${movimento}`;const movimentoGroup=new THREE.Group;if(movimentoGroup.name=`mov_${movimento}`,isZeroPivot)pivotGroup.position.copy(grp.position),pivotGroup.quaternion.copy(grp.quaternion),grp.position.set(0,0,0),grp.rotation.set(0,0,0);else{const pivotWorld=pivotLocal.clone().applyMatrix4(grp.matrixWorld);pivotGroup.position.copy(pivotWorld);const offset=pivotLocal.clone().negate();grp.position.add(offset),pivotGroup.quaternion.copy(grp.getWorldQuaternion(new THREE.Quaternion)),grp.rotation.set(0,0,0)}return movimentoGroup.add(grp),pivotGroup.add(movimentoGroup),op||(op={}),op.inmov=!1,op.key=movimento,op.dt=0,op.dtstart=!1,movimentoGroup.userData.mov={...op},pivotGroup}
|
|
554
554
|
/**
|
|
555
555
|
* Crea un gestore di movimento per animare oggetti 3D.
|
|
556
556
|
* @param {string} key - Chiave identificativa del movimento
|
|
@@ -1091,11 +1091,11 @@ constructor(data,position,debugMessage){this.data=data,this.offset=position,this
|
|
|
1091
1091
|
*
|
|
1092
1092
|
* @method readString
|
|
1093
1093
|
* @return {String} Data read from the dataview.
|
|
1094
|
-
*/readString(){let s="",c=this.readByte();for(;c;)s+=String.fromCharCode(c),c=this.readByte();return s}}const M3DMAGIC=19789,MLIBMAGIC=15786,CMAGIC=49725,M3D_VERSION=2,COLOR_F=16,COLOR_24=17,LIN_COLOR_24=18,LIN_COLOR_F=19,INT_PERCENTAGE=48,FLOAT_PERCENTAGE=49,MDATA=15677,MESH_VERSION=15678,MASTER_SCALE=256,MAT_ENTRY=45055,MAT_NAME=40960,MAT_AMBIENT=40976,MAT_DIFFUSE=40992,MAT_SPECULAR=41008,MAT_SHININESS=41024,MAT_TRANSPARENCY=41040,MAT_TWO_SIDE=41089,MAT_ADDITIVE=41091,MAT_WIRE=41093,MAT_WIRE_SIZE=41095,MAT_TEXMAP=41472,MAT_OPACMAP=41488,MAT_BUMPMAP=41520,MAT_SPECMAP=41476,MAT_MAPNAME=41728,MAT_MAP_USCALE=41812,MAT_MAP_VSCALE=41814,MAT_MAP_UOFFSET=41816,MAT_MAP_VOFFSET=41818,NAMED_OBJECT=16384,N_TRI_OBJECT=16640,POINT_ARRAY=16656,FACE_ARRAY=16672,MSH_MAT_GROUP=16688,TEX_VERTS=16704,MESH_MATRIX=16736;function newgcad(P,_cat,islog=!0){let _movs={},_textures={},_meshes={},_geometries={};const textureCache=new Map;let _smats={},_scripts={},_loadertex=new THREE.TextureLoader,_loaderGLTF=new GLTFLoader,_loader3DS=new TDSLoader;const dracoLoader=new DRACOLoader;dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.6/"),_loaderGLTF.setDRACOLoader(dracoLoader);const ktx2Loader=new KTX2Loader;ktx2Loader.setTranscoderPath("https://unpkg.com/three@0.159.0/examples/jsm/libs/basis/"),_loaderGLTF.setKTX2Loader(ktx2Loader),_loaderGLTF.setMeshoptDecoder(MeshoptDecoder);let cats=[_cat],getcat=()=>cats[cats.length-1],_gmatricole={};
|
|
1094
|
+
*/readString(){let s="",c=this.readByte();for(;c;)s+=String.fromCharCode(c),c=this.readByte();return s}}const M3DMAGIC=19789,MLIBMAGIC=15786,CMAGIC=49725,M3D_VERSION=2,COLOR_F=16,COLOR_24=17,LIN_COLOR_24=18,LIN_COLOR_F=19,INT_PERCENTAGE=48,FLOAT_PERCENTAGE=49,MDATA=15677,MESH_VERSION=15678,MASTER_SCALE=256,MAT_ENTRY=45055,MAT_NAME=40960,MAT_AMBIENT=40976,MAT_DIFFUSE=40992,MAT_SPECULAR=41008,MAT_SHININESS=41024,MAT_TRANSPARENCY=41040,MAT_TWO_SIDE=41089,MAT_ADDITIVE=41091,MAT_WIRE=41093,MAT_WIRE_SIZE=41095,MAT_TEXMAP=41472,MAT_OPACMAP=41488,MAT_BUMPMAP=41520,MAT_SPECMAP=41476,MAT_MAPNAME=41728,MAT_MAP_USCALE=41812,MAT_MAP_VSCALE=41814,MAT_MAP_UOFFSET=41816,MAT_MAP_VOFFSET=41818,NAMED_OBJECT=16384,N_TRI_OBJECT=16640,POINT_ARRAY=16656,FACE_ARRAY=16672,MSH_MAT_GROUP=16688,TEX_VERTS=16704,MESH_MATRIX=16736;function newgcad(P,_cat,islog=!0){let _movs={},_textures={},_meshes={},_geometries={};const textureCache=new Map;let _smats={},_scripts={},_loadertex=new THREE.TextureLoader,_loaderGLTF=new GLTFLoader,_loader3DS=new TDSLoader;const dracoLoader=new DRACOLoader;dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.6/"),_loaderGLTF.setDRACOLoader(dracoLoader);const ktx2Loader=new KTX2Loader;ktx2Loader.setTranscoderPath("https://unpkg.com/three@0.159.0/examples/jsm/libs/basis/"),_loaderGLTF.setKTX2Loader(ktx2Loader),_loaderGLTF.setMeshoptDecoder(MeshoptDecoder);let cats=[_cat],getcat=()=>cats[cats.length-1],_gmatricole={};
|
|
1095
1095
|
/**
|
|
1096
1096
|
* Libera tutte le risorse caricate
|
|
1097
1097
|
*/
|
|
1098
|
-
async function clear(){function destroymesh(mesh){function disposeMaterial(material){material.map&&material.map.dispose(),material.lightMap&&material.lightMap.dispose(),material.bumpMap&&material.bumpMap.dispose(),material.normalMap&&material.normalMap.dispose(),material.specularMap&&material.specularMap.dispose(),material.dispose()}mesh&&mesh.traverse((child=>{child.isMesh&&(child.geometry.dispose(),child.material&&(Array.isArray(child.material)?child.material.forEach(disposeMaterial):disposeMaterial(child.material)))}))}_gmatricole={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();for(const key in
|
|
1098
|
+
async function clearmat(){for(const key in _textures)if(_textures[key]){const texture=await _textures[key];texture?.dispose()}for(const key in _smats)_smats[key]&&_smats[key]?.dispose();for(const[key,texOrPromise]of textureCache.entries()){const texture=texOrPromise instanceof Promise?await texOrPromise:texOrPromise;texture?.dispose&&texture.dispose()}textureCache.clear(),_textures={},_smats={}}return{clearmatricole:()=>{_gmatricole={}},islog:islog,clear:async function clear(){function destroymesh(mesh){function disposeMaterial(material){material.map&&material.map.dispose(),material.lightMap&&material.lightMap.dispose(),material.bumpMap&&material.bumpMap.dispose(),material.normalMap&&material.normalMap.dispose(),material.specularMap&&material.specularMap.dispose(),material.dispose()}mesh&&mesh.traverse((child=>{child.isMesh&&(child.geometry.dispose(),child.material&&(Array.isArray(child.material)?child.material.forEach(disposeMaterial):disposeMaterial(child.material)))}))}_gmatricole={},THREE.Cache.clear();for(const c in _geometries)_geometries[c]?.dispose();for(const key in _meshes)if(_meshes[key]){destroymesh(await _meshes[key])}await clearmat(),_movs={},_textures={},_meshes={},_geometries={},_smats={},_scripts={}},clearmat:clearmat,getScript:async function getScript(file){file.endsWith(".custom")?file=file.slice(-7):file.endsWith(".js")&&(file=file.slice(-3));let key=hash(`${getcat()}|${file}`);if(!_scripts[key]){let script;try{script=await P.fetch("mufiles/customfn",{id:getcat(),name:file,ispar:1})}catch(error){script=`log('undefined ${getcat()}/${file}: ${error.message}');`}_scripts[key]=script}return _scripts[key]},checkScripts:async function checkScripts(files){let cl=[];if(!files||!Array.isArray(files))return;let ct=getcat();for(let f of files){let key=hash(`${ct}|${f}`);_scripts[key]||cl.push(f)}if(cl?.length){let scripts=await P.fetch("mufiles/customfn",{id:ct,name:cl,ispar:1});if(scripts)for(let s of scripts){let key=hash(`${ct}|${s.n}`);_scripts[key]=s.v}}},get loaderGLTF(){return _loaderGLTF},get gmats(){return _gmatricole},scripts:()=>Object.keys(_scripts),get geo(){return _geometries},get movs(){return _movs},get textures(){return _textures},get smats(){return _smats},dump(){console.log(`SMATS:\n${Object.keys(_smats).join(" - ")};\nGEOMS:\n${Object.keys(_geometries).join(" - ")};\nTEX:\n${Object.keys(_textures).join(" - ")};\nMESH:\n${Object.keys(_meshes).join(" - ")};\n`)},get cat(){return getcat()},pushcat(cat){cats.push(cat)},popcat:()=>(cats.length>1&&cats.length--,getcat()),async tex(file,sx=1,sy,rot){sy||(sy=sx),rot||(rot=0);const key=hash(`${getcat()}|${file}|${sx}|${sy}|${rot}`);return _textures[key]||(_textures[key]=new Promise(((resolve,reject)=>{let url;if(file.startsWith("https://"))url=file;else if(P._cdn)if(file.includes("/")){let v=file.split("/");url=`${P._cdn}${v[0]}/textures/${v[1]}`}else url=`${P._cdn}${getcat()}/textures/${file}`;else url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"textures",name:file,force:1});if(textureCache.has(url)){const tex=textureCache.get(url).clone();return tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.repeat.set(.001*sx,.001*sy),tex.rotation=rot,void resolve(tex)}_loadertex.load(url,(tex=>{textureCache.set(url,tex),tex.wrapS=THREE.RepeatWrapping,tex.wrapT=THREE.RepeatWrapping,tex.repeat.set(.001*sx,.001*sy),tex.rotation=rot,resolve(tex)}),void 0,(error=>{console.log(`Manca Texture ${file}!. questo rallenta molto il processo`),delete _textures[key],resolve(void 0)}))}))),_textures[key]},async get3ds(file,callback,ky=""){file.endsWith(".3ds")&&(file=file.slice(0,-4));const modifierKey=callback?hash(callback.toString()):"nomod",key=hash(`${getcat()}|${file}.3ds|${modifierKey}|${ky}`);return _meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url,urlt="";file.startsWith("https://")?(url=`${file}.3ds`,urlt=url):P._cdn?(url=`${P._cdn}${getcat()}/3d/${file}.3ds`,urlt=`${P._cdn}${getcat()}/3d/${file}/`):(url=P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:".3ds"}),urlt=url+"&tex="),_loader3DS.setResourcePath(urlt),_loader3DS.load(url,(object=>{callback&&object.traverse((child=>{child.isMesh&&(Array.isArray(child.material)?child.material=child.material.map((mat=>callback(mat,child))):child.material=callback(child.material,child))})),resolve(object)}),void 0,(error=>{delete _meshes[key],resolve(void 0)}))}))),_meshes[key]},async getglb(file,textures,callback=null,ky=""){const ext=".glb";file.endsWith(ext)&&(file=file.slice(0,-4)),file.startsWith("https://")||(file=file.replace(/\//g,"+"));let elemento=(file=file.split("+"))[1];file=file[0],Array.isArray(textures)||(textures=[]);const modifierKey=callback?hash(callback.toString()):"nomod",texturesKey=textures.map((tex=>tex?.uuid||"null")).join("|"),key=hash(`${getcat()}|${file}${ext}|${texturesKey}|${modifierKey}|${ky}`);_meshes[key]||(_meshes[key]=await new Promise(((resolve,reject)=>{let url;url=file.startsWith("https://")?`${file}.glb`:P._cdn?`${P._cdn}${getcat()}/3d/${file}.glb`:P.fullget("mufiles/getfile",{id:getcat(),subfolder:"3d",name:file,ext:ext}),_loaderGLTF.setPath(""),_loaderGLTF.setResourcePath((resource=>(console.log("risorsa",resource),`${url}&tex=${resource}`))),_loaderGLTF.load(url,(async gltf=>{gltf.scene.traverse((child=>{if(child.isMesh){child.frustumCulled=!0;(Array.isArray(child.material)?child.material:[child.material]).forEach((material=>{if(!material||!material.map)return;const originalTexName=material.map.source?.data?.src;if(!originalTexName)return;const match=originalTexName.match(/(\d{2})\.jpg$/);if(!match)return;const textureIndex=parseInt(match[1]);textures[textureIndex]&&(material.map=textures[textureIndex],material.needsUpdate=!0)})),callback&&(Array.isArray(child.material)?child.material=child.material.map((mat=>callback(mat,child))):child.material=callback(child.material,child))}})),resolve(gltf.scene)}),void 0,(error=>{console.log(error),delete _meshes[key],resolve(void 0)}))})));let tm=_meshes[key];if(elemento){let n=tm?.getObjectByName(elemento);n&&(tm=n)}return tm}}}const originalMaterials=new Map;
|
|
1099
1099
|
/**
|
|
1100
1100
|
* Salva i materiali originali di tutti i mesh nel gruppo (solo layer <= 20)
|
|
1101
1101
|
* @param {THREE.Object3D} gruppo
|
|
@@ -1115,4 +1115,4 @@ async function clear(){function destroymesh(mesh){function disposeMaterial(mater
|
|
|
1115
1115
|
* @param {THREE.Object3D} gruppo - oggetto root
|
|
1116
1116
|
* @param {Array<{ mats: string[], name?: string }>} matricole - elenco da evidenziare
|
|
1117
1117
|
* @returns {Promise<File[]>}
|
|
1118
|
-
*/async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:function addlog(...pars){const sanitized=pars.map((p=>getOggetto(p)));console.log(...sanitized)},Math:Math,clean:clean,SP:SP,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getface,getfakeshadow,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpoint,getprojectkeys,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,groupfromgeometry,hash,infoestrudi,isfn,ismacro,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scaleunit,setLineColorMode,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
|
|
1118
|
+
*/async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:function addlog(...pars){const sanitized=pars.map((p=>getOggetto(p)));console.log(...sanitized)},Math:Math,clean:clean,SP:SP,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getface,getfakeshadow,getfakeshadow2,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpoint,getprojectkeys,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,groupfromgeometry,hash,infoestrudi,isfn,ismacro,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scaleunit,setLineColorMode,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
|
package/bin/markuno.js
CHANGED
|
@@ -272,4 +272,4 @@ this.vari=new Variabile,this.ruleset={},this.fndotcallback&&this.vari.setfndot(t
|
|
|
272
272
|
/** @type {Object.<string, Macro>} */
|
|
273
273
|
this.macro={},
|
|
274
274
|
/** @type {Object.<string, Variante>} */
|
|
275
|
-
this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){let tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(let t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){var tips=fromjson(t.value);for(let tp in tips){var tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;var rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(riga.contenuto);if(!rr)return void errori.add("Macro non valida:"+riga.contenuto,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));var pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;var ky=`${cat}/${name}`;if(!this.macro[ky]){var tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){var{name:name,cat:cat}=checkmu(cod,this.cat),n2=name;let altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;var key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){var xx=new Variante(this);(await xx.load(v,this.cat,!0),xx.alias)&&((await this.getalias())[v]=xx.alias);callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){var mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);var t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){var cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(let x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(let v of info.var)await this.varcompila(v,callback);for(let v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){var tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async getheaderfromdb(name){let totale=await cbInfo("header",this.cat,name,!this.#deriva),{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(let r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(let r of rows){let nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];let vn=[],t=this.varelenco[this.cat];for(let nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){var vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(let x of vars){let{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){var getkey=n=>n.includes("/")?n:`${this.cat}/${n}`;let k,cl=[];if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){let vv=macros.split(";");for(let v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){let tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(let x of tm){let m=new Macro(this,x.name);for(let t in x.content){let contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}async setruleheader(rule,pars,ruleset){var{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));var ky=`${cat}/${name}`;if(!this.macro[ky]){let totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);var tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){let k2=this.macro[`${cat}/${head.rule}`];if(k2)for(let x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;let mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){var xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){return azzera&&mu.azzera(),mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){var mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(var p of pars){var{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){let x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
|
|
275
|
+
this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){let tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(let t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){var tips=fromjson(t.value);for(let tp in tips){var tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;var rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(riga.contenuto);if(!rr)return void errori.add("Macro non valida:"+riga.contenuto,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));var pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;var ky=`${cat}/${name}`;if(!this.macro[ky]){var tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){var{name:name,cat:cat}=checkmu(cod,this.cat),n2=name;let altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;var key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){var xx=new Variante(this);(await xx.load(v,this.cat,!0),xx.alias)&&((await this.getalias())[v]=xx.alias);callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){var mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);var t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){var cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(let x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(let v of info.var)await this.varcompila(v,callback);for(let v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){var tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);let t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);let nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&(cbGetVariante&&(vars=await cbGetVariante(cat,vn))&&vars.length))for(let x of vars){let{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}async getheaderfromdb(name){let totale=await cbInfo("header",this.cat,name,!this.#deriva),{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(let r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(let r of rows){let nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];let vn=[],t=this.varelenco[this.cat];for(let nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){var vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(let x of vars){let{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){var getkey=n=>n.includes("/")?n:`${this.cat}/${n}`;let k,cl=[];if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){let vv=macros.split(";");for(let v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){let tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(let x of tm){let m=new Macro(this,x.name);for(let t in x.content){let contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}async setruleheader(rule,pars,ruleset){var{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));var ky=`${cat}/${name}`;if(!this.macro[ky]){let totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);var tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){let k2=this.macro[`${cat}/${head.rule}`];if(k2)for(let x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;let mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){var xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){return azzera&&mu.azzera(),mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){var mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(var p of pars){var{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){let x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
|
package/package.json
CHANGED
package/types/markcad.d.ts
CHANGED
|
@@ -392,6 +392,7 @@ export function getemitter(data: any): any;
|
|
|
392
392
|
* @returns {Promise<THREE.Group>} Gruppo contenente il box
|
|
393
393
|
*/ export function getface(gcad: any, x: number, y: number, mat: THREE.Material, scaled?: boolean): Promise<THREE.Group>;
|
|
394
394
|
export function getfakeshadow(gcad: any, shape: any, alfa: any): any;
|
|
395
|
+
export function getfakeshadow2(w: any, h: any, map: any): any;
|
|
395
396
|
/**
|
|
396
397
|
* Crea una linea 3D
|
|
397
398
|
* @param {Object} l - Oggetto contenente punti p1 e p2
|
|
@@ -569,6 +570,7 @@ export function newgcad(P: any, _cat: any, islog?: boolean): {
|
|
|
569
570
|
clearmatricole: () => void;
|
|
570
571
|
islog: boolean;
|
|
571
572
|
clear: () => Promise<void>;
|
|
573
|
+
clearmat: () => Promise<void>;
|
|
572
574
|
getScript: (file: any) => Promise<any>;
|
|
573
575
|
checkScripts: (files: any) => Promise<void>;
|
|
574
576
|
readonly loaderGLTF: GLTFLoader;
|
package/types/markuno.d.ts
CHANGED
|
@@ -46,6 +46,7 @@ export class Ambiente {
|
|
|
46
46
|
barrecompila(articolibarre: any, titolibarre: any, callback: any): Promise<CodiceBarra>;
|
|
47
47
|
tojson(d: any): Promise<any>;
|
|
48
48
|
compila(info: any, callback: any): Promise<void>;
|
|
49
|
+
checkvarianti(cat: any, vars: any): Promise<void>;
|
|
49
50
|
getheaderfromdb(name: any): Promise<{
|
|
50
51
|
head: any;
|
|
51
52
|
rows: any;
|