@maqiuyao/dxf-viewer 0.2.24 → 0.2.25
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/README.md +1 -0
- package/dist/dxf-viewer.cjs +1 -1
- package/dist/dxf-viewer.js +9 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -149,6 +149,7 @@ viewer.setRequestHeaders(undefined); // 清除
|
|
|
149
149
|
|
|
150
150
|
## 优化与完善(0.2.x)
|
|
151
151
|
|
|
152
|
+
- 0.2.25:修复部分图纸初始视图不居中——业务系统生成的图纸常用超大圆的极小弧段(半径可达数千、圆心远离图形本体)近似直线段,加载器为每个椭圆/圆挂接的圆心捕捉标记(点击吸附用交互辅助点,定位在圆心)被一并计入内容包围盒(Box3.setFromObject 全量包含子对象),圆心距主内容数千单位时初始适配框被撑大数十倍、内容挤到视图一角(对照 AutoCAD 显示居中);Model2d.getBBox 改为遍历统计时排除 isSnapObject 捕捉标记(交互辅助不属于图纸内容),正常图纸(圆心在内容内部)包围盒结果不变,初始视图/打印裁剪/全图缩放等所有包围盒消费方一并修正,捕捉吸附功能本身不受影响
|
|
152
153
|
- 0.2.24:修复部分图纸样条曲线(SPLINE)不显示及衔接处断口——① 22 个实体解析器各自持有同款贪婪版 parsePoint 副本,解析连续点序列(样条控制点/引线顶点/填充多段线边界顶点,组码 10/20/30 连续出现)时下一个点的 X 覆盖当前点并继续吞并,4 个控制点塌缩成 1 个,点数不足阶数导致全部 SPLINE 被忽略不渲染(LEADER/HATCH 同类点序列同样受损);统一改为共享的严格单点解析(x/y/z/bulge 槽位各消费一次,遇重复槽位/无关组码立即返回),单点类实体行为不变;② 填充多段线边界路径调用方在 parsePoint 返回后误把下一顶点 X 读作 bulge,由严格解析顺带消费组码 42 修复;③ B 样条采样循环 `t < 1` 永远取不到终点 t=1,曲线末端距最后控制点差一个采样步长,多段首尾相接的 SPLINE 衔接处出现可见断口,改为闭区间整数采样(含 t=0 与 t=1),曲线精确落在端点上
|
|
153
154
|
- 0.2.23:优化搜索定位视野与高亮边框样式——① focusText 定位后视野从"文字包围盒对角线 × 2"调大到"× 8"(此前小文字会放得过大、视野里只有字),并新增可选参数 zoomScale 可自控倍数(数值越大可视区域越大、文字占比越小,传 2 约等于旧版视野),视野下限防止极小文字无限放大;② 搜索定位/实体点击/双图对比的选中高亮边框由修订云线花边改为普通圆角矩形边框(8px 圆角,屏幕空间绘制不随缩放变形),CompareDrawable 新增 useCloudBorder 参数,传 true 可恢复云线样式
|
|
154
155
|
- 0.2.22:修复部分图纸点击属性字(ATTRIB)获取不到父 INSERT 块扩展数据(组码 1000)——此类文件 ATTRIB 的 owner 句柄(组码 330)不直接指向父 INSERT 而指向 SEQEND/前一实体(实测 60 个 ATTRIB 全部如此),owner 查找必然落空;父实体查找兼容两种结构:① owner 直指 INSERT 时按 handle 索引 O(1) 命中;② 否则沿实体流向前回溯最近的 INSERT(标准 DXF 流顺序:INSERT(66=1) 后紧跟其 ATTRIB 组、以 SEQEND 结束),两种结构实测均 100% 命中且互不干扰
|
package/dist/dxf-viewer.cjs
CHANGED
|
@@ -793,7 +793,7 @@ void main() {
|
|
|
793
793
|
`&&s++,i=s+1}}return e.push(t.substring(i,t.length)),e}}function qe(c,t,e){return c.code===t&&c.value===e}function wt(c){P.trace("unhandled group "+Oo(c))}function Oo(c){return c.code+":"+c.value}const _o="0.4.0",Po="VERSION",Qd=()=>window.localStorage.getItem(Po),e1=()=>{window.localStorage.setItem(Po,_o)},t1=()=>Qd()!==_o?(e1(),!0):!1,ti=class ti{constructor(){g(this,"DATABASE_NAME","x_viewer");g(this,"DEFAULT_TABLES",[{name:"dxf_data",options:{keyPath:"dxfDataId",autoIncrement:!1}},{name:"fonts",options:{keyPath:"fileName",autoIncrement:!0}}]);g(this,"db");g(this,"tables");this.db=void 0,this.tables=this.DEFAULT_TABLES}static instance(){return!ti._instance&&(ti._instance=new ti),ti._instance}setTables(t){this.tables=t}getTables(){return this.tables}async getDatabase(){let t=await this.getDB(this.DATABASE_NAME);return this.db||(t.close(),t1()&&await this.deleteDataBase(this.DATABASE_NAME),t=await this.getUpgradedDB(t)),t.onclose=()=>{this.db=void 0,P.debug("[DB] Db "+t.name+" is closed.")},t.onerror=e=>{this.db=void 0,P.debug("[DB] Db "+t.name+" encountered error.",e)},t.onabort=e=>{this.db=void 0,P.debug("[DB] Db "+t.name+" aborted.",e)},t.onversionchange=e=>{P.debug("onversionchange",e)},this.db=t,Promise.resolve(this.db)}closeDatabase(){this.db&&this.db.close()}deleteDataBase(t){return new Promise((e,i)=>{const s=window.indexedDB.deleteDatabase(t);s.onerror=n=>{P.debug(n),i(n)},s.onsuccess=n=>{const r=n.target;P.debug("[DB] Db "+t+" delete old version "+n.oldVersion+"."),e(r)}})}async getDB(t){return new Promise((e,i)=>{const s=window.indexedDB.open(t);s.onerror=i,s.onsuccess=n=>{const r=n.target.result;P.debug("[DB] Db "+r.name+" opened (version "+r.version+")."),e(r)}})}async getUpgradedDB(t){return new Promise((e,i)=>{P.debug("[DB] Upgrading db "+t.name+" (version "+t.version+")");const s=window.indexedDB.open(t.name,t.version+1);s.onerror=i,s.onblocked=n=>{P.debug("onblocked",n)},s.onupgradeneeded=n=>{const r=n.target.transaction;r.oncomplete=()=>{P.debug("[DB] Upgrade is done (new version: "+a.version+").")};const a=n.target.result,o=[];for(let l=0;l<this.tables.length;++l){const h=this.tables[l];if(!a.objectStoreNames.contains(h.name)){P.debug("[DB] Creating table "+h.name+"...");const d=this.createTable(a,h.name,h.options,h.indexArray);o.push(d)}}o.length>0&&Promise.all(o).then(()=>{P.debug("[DB] All("+o.length+") tables created.")})},s.onsuccess=n=>{const r=n.target.result;P.debug("[DB] Db "+r.name+" opened (version "+r.version+")."),e(r)}})}async createTable(t,e,i,s){return new Promise(n=>{const r=t.createObjectStore(e,i);s&&s.forEach(a=>{r.createIndex(a.name,a.fields,{unique:a.unique})}),P.debug("[DB] Table "+e+" created."),n(t)})}};g(ti,"_instance");let fe=ti;class Ao{constructor(){g(this,"db");g(this,"isCreatingTable");if(this.db=void 0,this.isCreatingTable=!1,fe.instance().getTables().findIndex(i=>i.name===this.tableName())===-1)throw new Error("Failed to find table '"+this.tableName()+"' from indexeddb!")}tableName(){throw new Error("Derived class have to override 'tableName', and set a proper table name!")}add(t,e,i){const s=this.tableName();fe.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.add(t);a.onsuccess=e,a.onerror=i}).finally(()=>{fe.instance().closeDatabase()}).catch(n=>{i&&i(n)})}save(t,e,i){const s=this.tableName();fe.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.put(t);a.onsuccess=e,a.onerror=i}).finally(()=>{fe.instance().closeDatabase()})}delete(t,e,i){const s=this.tableName();fe.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.delete(t);a.onsuccess=e,a.onerror=i}).finally(()=>{fe.instance().closeDatabase()})}update(){fe.instance().getDatabase().then(()=>{})}query(t,e){const i=this.tableName();fe.instance().getDatabase().then(s=>{const n=s.transaction([i],"readonly").objectStore(i),r=n.openCursor();r.onsuccess=a=>{const o=a.target.result;o&&o.continue(),t&&t(o)},r.onerror=e}).finally(()=>{fe.instance().closeDatabase()})}queryByIndex(t,e,i,s){const n=this.tableName();fe.instance().getDatabase().then(r=>{const a=r.transaction([n],"readonly").objectStore(n),o=a.index(t).get(e);o.onerror=s,o.onsuccess=function(l){const h=l.target?.result;i&&i(h)}}).finally(()=>{fe.instance().closeDatabase()})}queryAll(t,e){const i=this.tableName();fe.instance().getDatabase().then(s=>{const n=s.transaction([i],"readonly").objectStore(i),r=n.getAll();r.onsuccess=a=>{t&&t(a.target.result)},r.onerror=e}).finally(()=>{fe.instance().closeDatabase()})}clearAll(t,e){const i=this.tableName();fe.instance().getDatabase().then(s=>{const n=s.transaction([i],"readwrite").objectStore(i),r=n.clear();r.onsuccess=a=>{t&&t(a)},r.onerror=a=>{e&&e(a)}}).finally(()=>{fe.instance().closeDatabase()})}}const ii=class ii extends Ao{tableName(){return"dxf_data"}static instance(){return!ii._instance&&(ii._instance=new ii),ii._instance}query(t,e,i){const s=[],n=this.tableName();fe.instance().getDatabase().then(r=>{const a=r.transaction([n],"readonly").objectStore(n),o=a.get(t);o.onerror=l=>{i&&i(l),P.info("[DxfDataTable] Failed to query !",l)},o.onsuccess=()=>{o.result&&s.push(o.result),e&&e(s)}}).finally(()=>{fe.instance().closeDatabase()})}};g(ii,"_instance");let ln=ii;const We=new p.Vector3(1,0,0),zn=new p.Vector3(0,1,0),fi=new p.Vector3(0,0,1),wa=new p.Vector3(0,0,0),Lt=16777215,i1="CONTINUOUS",zs=new p.PointsMaterial({color:Lt}),ge=new p.LineBasicMaterial({color:Lt}),pi=new p.MeshBasicMaterial({color:Lt}),va=new p.BufferGeometry().setFromPoints([new p.Vector3]),Ma=new p.Matrix4,it=new p.Matrix4,ue=new p.Matrix4,H=new p.Vector3,$=new p.Vector3,st=new p.Vector3,Wi=new p.Vector2,ye=new p.Quaternion,Vs=new p.Object3D,ut=new p.Box3,Ta=new p.PointsMaterial({color:65280,size:5,depthTest:!1}),Ca=new p.PointsMaterial({color:65280,depthTest:!1}),Sa=new p.PointsMaterial({color:65280,depthTest:!1}),s1=c=>c.viewDirectionFromTarget!==void 0,n1=c=>{if(c){const t=c.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);if(t&&t.length>0){const e=t[1],i=c.replace("data:"+e+";","").split(",");if(i&&i.length===2&&i[0]==="base64"){const s=i[1];return Xl.decode(s)}}}return null},Ea=(c,t)=>{const e=new p.Vector2(c.x,c.y),i=new p.Vector2(t.x,t.y);return i.sub(e),i.normalize(),i.y<0?-Math.acos(i.x):Math.acos(i.x)},Oa=(c,t,e)=>({x:c.x+t*Math.cos(e),y:c.y+t*Math.sin(e)}),r1=(c,t,e,i)=>{const s=c?new p.Vector2(c.x,c.y):new p.Vector2(0,0),n=t?new p.Vector2(t.x,t.y):new p.Vector2(1,0);e=e||1;const r=4*Math.atan(e),a=s.distanceTo(n)/2/Math.sin(r/2),o=Oa(c,a,Ea(s,n)+(Math.PI/2-r/2));i=i||Math.max(Math.abs(Math.ceil(r/(Math.PI/18))),6);const l=Ea(o,s),h=r/i,d=[];d.push(new p.Vector3(s.x,s.y,0));for(let u=1;u<=i-1;u++){const f=Oa(o,Math.abs(a),l+h*u);d.push(new p.Vector3(f.x,f.y,0))}return d},_a=(c,t,e,i=c.length*2,s)=>{const n=[];if(!c||c.length<t+1||t<1)return n;const r=c.map(a=>[a.x,a.y]);try{const a=Math.max(2,Math.round(i));for(let o=0;o<=a;o++){const l=xo(o/a,t,r,e,s);n.push(new p.Vector3(l[0],l[1],0))}}catch{if(n.length===0)return n}return n},Vn=(c,t=!1)=>{const e=[],i=c.length;for(let s=0;s<i;s++){const n=c[s];if(n.bulge&&(s!==i-1||t)){const r=n.bulge,a=s+1<i?c[s+1]:e[0],o=r1(n,a,r);e.push(...o)}else e.push(new p.Vector3(n.x,n.y,0))}return e},a1=c=>{const t=[];return c.faceA&&t.push(c.faceA),c.faceB&&t.push(c.faceB),c.faceC&&t.push(c.faceC),c.faceD&&t.push(c.faceD),t},o1=c=>{const t=[],e=[];c.forEach(s=>{s.polyfaceMeshVertex&&(s.threeDPolylineMesh?t.push(new p.Vector3(s.x,s.y,s.z)):e.push(a1(s)))});const i=[];for(let s=0;s<e.length;s++){const n=e[s];if(n.length===0)continue;const r=[];let a=!0;for(let o=0;o<n.length;o++){const l=n[o]-1;if(l>=t.length||l<0){a=!1;break}r.push(t[l])}!a||r.length===0||(r.push(r[0]),i.push(r))}return i},N=class N extends p.Loader{constructor(e,i){super(e);g(this,"timer");g(this,"ignorePaperSpace");g(this,"font");g(this,"encoding");g(this,"overrideColor");g(this,"overrideHatchPatternLineThickness");g(this,"angBase");g(this,"angDir");g(this,"header");g(this,"pointsMaterials");g(this,"lineBasicMaterials");g(this,"lineShaderMaterials");g(this,"meshBasicMaterials");g(this,"meshTextureMaterials");g(this,"hatchShaderMaterials");g(this,"entityCount");g(this,"curveCount");g(this,"averageCurveSize");g(this,"enableRenderOrder");g(this,"enableLocalCache");g(this,"enableReleaseData");g(this,"enableMerge");g(this,"enableRTC");g(this,"enablePlineWidth");g(this,"dxfDataId");g(this,"compareContext");g(this,"statsInfo");g(this,"llbDatas");g(this,"mtextDatas");g(this,"requestHeader");g(this,"blockReferencesCache");g(this,"blockRecordsCache");g(this,"entitiesCache");g(this,"blocksCache");g(this,"dictionaryOwnerHandleAndSpatialFilterHandlesCache");g(this,"spatialFiltersCache");g(this,"entityThreejsCache");g(this,"entitiesByHandleIndex");g(this,"entitiesByHandleIndexData");g(this,"entityTypesAndTimes");g(this,"nonSnapableTypes");g(this,"layoutsSnapObjectsMap");g(this,"aborted");g(this,"entityHandlesWithRenderOrder");g(this,"addViewport");this.timer=Date.now(),this.ignorePaperSpace=!1,this.encoding="UTF-8",this.angBase=0,this.angDir=0,this.header=void 0,this.pointsMaterials={},this.lineBasicMaterials={},this.lineShaderMaterials={},this.meshBasicMaterials={},this.meshTextureMaterials={},this.hatchShaderMaterials=[],this.entityCount=0,this.curveCount=0,this.averageCurveSize=0,this.enableRenderOrder=!1,this.enableLocalCache=!1,this.enableReleaseData=!0,this.enableMerge=!0,this.enableRTC=!0,this.enablePlineWidth=!0,this.dxfDataId=void 0,this.compareContext=void 0,this.statsInfo={unsupportedEntity:{},unsupportedEntityTypes:{},unsupportedTextStyles:{},unsupportedHatchPatterns:{},unsupportedPolylineCount:0,invisibleEntities:{},ignoredFrozenLayersAndEntityCount:{},ignoredInserts:{},entityTypesAndMeshCount:{},ignoredPaperSpaceEntityTypesAndCount:{},rebasedEntityCount:0,requestHeader:{}},this.llbDatas=[],this.mtextDatas=[],this.blockReferencesCache={},this.blockRecordsCache=void 0,this.entitiesCache=void 0,this.blocksCache=void 0,this.dictionaryOwnerHandleAndSpatialFilterHandlesCache=void 0,this.spatialFiltersCache=void 0,this.entityThreejsCache=void 0,this.entityTypesAndTimes=void 0,this.nonSnapableTypes=new Set(["ATTDEF","ATTRIB","LEADER","MTEXT","MULTILEADER","OLE2FRAME","TEXT"]),this.layoutsSnapObjectsMap={},this.aborted=!1,this.entityHandlesWithRenderOrder={},this.addViewport=(s,n)=>{if(s.type==="VIEWPORT"){!n[s.ownerHandle]&&(n[s.ownerHandle]=[]);const r=s;n[s.ownerHandle].push(r)}},i&&(this.ignorePaperSpace=i.ignorePaperSpace===!0,this.enableLocalCache=i.enableLocalCache===!0,this.enableMerge=N.LOADLLDATA?!1:i.enableMerge!==!1,this.encoding=i.encoding||"UTF-8",i.requestHeaders&&(this.requestHeader=i.requestHeaders),i.overrideColor!=null&&(this.overrideColor=Bi.rgb2Hex(i.overrideColor)),i.overrideHatchPatternLineThickness!=null&&(this.overrideHatchPatternLineThickness=i.overrideHatchPatternLineThickness)),this.pointsMaterials[Lt]=zs,this.lineBasicMaterials[Lt]=ge,this.meshBasicMaterials[Lt]=pi}setRequestHeader(e){this.requestHeader=e}setFont(e){this.font=e}async download(e,i){let s=n1(e);if(!s){const n=Date.now(),r=new p.FileLoader(this.manager);this.requestHeader&&Object.keys(this.requestHeader).length>0&&r.setRequestHeader(this.requestHeader),r.setResponseType("arraybuffer"),r.setPath(this.path),s=await r.loadAsync(e,i),P.info("[Dxf] "+e+" dxf file downloaded in "+(Date.now()-n)/1e3+"s")}return s}async loadEx(e,i,s){return this.enableLocalCache&&i&&(i=i.trim()).length>0&&(this.dxfDataId=i),this.loadAsync(e,s)}async loadAsync(e,i){const s=U.getUpdateSubProgressFunc(0,50,i),n=U.getUpdateSubProgressFunc(50,100,i),r=U.getUpdateSubProgressFunc(10,100,i);if(De.isBrowser&&this.enableLocalCache&&this.dxfDataId){let l;try{if(this.timer=Date.now(),l=await this.getDxfDataFromIndexedDb(this.dxfDataId),l){this.tryFixDxfData(l),P.info("[Dxf] Loaded DxfData from indexedDb in "+(Date.now()-this.timer)/1e3+"s");const h=await this.loadEntities(l,r);return Promise.resolve(h)}}catch(h){P.warn("[Dxf] Failed to parse data from indexedDb",h)}}const a=await this.parse(e,s);return this.tryFixDxfData(a),await this.loadEntities(a,n)}async parse(e,i){const s=U.getUpdateProgressFunc(i),n=U.getUpdateSubProgressFunc(0,40,i),r=await this.download(e,n);if(!r)return Promise.reject("[Dxf] Failed to download "+e);if(this.aborted)return Promise.reject("[Dxf] Job aborted");this.timer=Date.now(),P.info("[Dxf] Start parsing...");const a=new Eo(this.encoding).parseSync(r);if(this.tryFixDxfData(a),s(80),P.info("[Dxf] Parsed in "+(Date.now()-this.timer)/1e3+"s, creating entities..."),this.aborted)return Promise.reject("[Dxf] Job aborted");if(a&&De.isBrowser&&this.enableLocalCache&&this.dxfDataId){const o=Date.now();try{await this.setDxfDataToIndexedDb(this.dxfDataId,a),P.info("[Dxf] Saved to indexedDb in "+(Date.now()-o)/1e3+"s")}catch(l){P.warn("[Dxf] Failed to save '"+this.dxfDataId+"' to indexedDb!",l)}}return s(100),a}abort(){this.aborted=!0}isAborted(){return this.aborted}parseHeader(e){if(!e){P.error("[Dxf]: Invalid header!");return}this.header=e;const i=e.$ACADVER.toString();i!=="AC1032"&&P.warn("[Dxf] Unexpected version: "+i+". But we'll try to continue."),this.angBase=e.$ANGBASE||0,this.angDir=e.$ANGDIR||0}tryFixDxfData(e){e&&(!e.objects&&(P.warn("[Dxf] No objects found, Will add one."),e.objects={}),!e.objects.LAYOUT&&(P.warn("[Dxf] No layout defined! Will add a default 'Model' layout!"),e.objects.LAYOUT=[{layoutName:N.MODEL_LAYOUT_NAME}]),!e.tables&&(P.warn("[Dxf] No tables found, Will add one."),e.tables={}),!e.tables.layer&&(e.tables.layer={}),!e.tables.layer.layers&&(e.tables.layer.layers={}))}async loadEntities(e,i){const s=Date.now();this.parseHeader(e.header),this.enableRenderOrder&&(this.initRenderOrderInfo(e),this.enableMerge=!1),this.getFontFilesFromDxf(e);let n=0;const r=e.entities.length;this.entityCount=r,Object.keys(e.blocks).forEach(x=>{this.entityCount+=e.blocks[x].entities?.length||0});const a=U.getUpdateProgressFuncForLoop(r,i);let o={};const l=x=>{const E=x.userData.layerName;let M=o[E];!M&&(M=[],o[E]=M),M.push(x)},h={},d={},u=new j;for(let x=0;x<r&&!this.aborted;x++){const E=e.entities[x];this.addViewport(E,h);const M=this.loadEntity(E,e);if(!M&&await a(x),!M)continue;const O=this.getLayout(e,E),T=O.layoutName;let v=u.children.find(C=>C.name===T);if(!v&&(v=new j,v.name=T,v.userData.isLayoutLevelObject=!0,u.add(v)),M.traverse(C=>{C.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[T]&&(this.layoutsSnapObjectsMap[T]=[]),this.layoutsSnapObjectsMap[T].push(C))}),this.enableMerge){Mt.merge(M,!1),!d[T]&&(d[T]={object:v,layerObjects:{}});const _=d[T];if(M.geometry){const A=M.userData.layerName;!_.layerObjects[A]&&(_.layerObjects[A]=[]),_.layerObjects[A].push(M),M.children.forEach(I=>{I.userData.isSnapObject&&l(I)})}else M.children.length>0&&(v.add(M),M.traverse(A=>{A.geometry&&l(A)}))}else v.add(M),M.traverse(C=>{C.geometry&&l(C)});n++,await a(x)}e.objects.LAYOUT.forEach(x=>{const E=x,M=E.layoutName;if(this.ignorePaperSpace&&M!==N.MODEL_LAYOUT_NAME)return;const O=E.associatedBlockName,T=e.blocks[O];T&&this.loadLayout(T,e,E,u,o,h)}),P.debug("[Dxf] Drew entities in "+(Date.now()-s)/1e3+"s");for(const x in this.layoutsSnapObjectsMap){const E=u.children.find(T=>T.name===x),M=new j;M.name=N.SNAP_GROUP_NAME,M.userData.isSnapGroup=!0,E.add(M);const O=this.layoutsSnapObjectsMap[x];for(let T=0;T<O.length;T++){const v=O[T],C=v.userData.layerName;this.getLayerVisible(e,C)===!1&&v.layers.disable(Ue),N.SHOW_SNAP_OBJECT&&(v.layers.enableAll(),v.material instanceof p.PointsMaterial?v.material=Ta:v.material instanceof p.LineBasicMaterial?v.material=Ca:v.material instanceof p.MeshBasicMaterial&&(v.material=Sa));let _=v;const A=ue.identity();for(;_&&_.userData.isLayoutLevelObject!==!0;)A.premultiply(_.matrix),_=_.parent;v.matrix.copy(A),M.add(v)}}if(this.enableMerge)for(const x in d){const E=d[x],M=E.object;for(const O in E.layerObjects){const T=E.layerObjects[O],v=Mt.deepMerge(T,void 0,!1,!1,!0),C=v.added,_=v.removed;if(_.length!==T.length){let A=_;_.length>=100&&(A=new Set(_));const I=B=>Array.isArray(A)?A.indexOf(B)>=0:A.has(B);for(let B=0,D=T.length;B<D;B++){const k=T[B];!I(k)&&(M.add(k),l(k))}}for(let A=0;A<C.length;A++){const I=C[A];M.add(I),l(I)}E.layerObjects[O]=[]}}this.printStatsInfo(),this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(e)),this.enableMerge&&N.mergeDxfObjects({root:u,layersAndObjects:o});const m=u.convertToThreejsObject();u.clear(),o={};const b={};e.objects.LAYOUT.forEach(x=>{const E=x;b[E.layoutName]=E});const y={},S=x=>{const E=x.userData.layerName;let M=y[E];!M&&(M=[],y[E]=M),M.push(x)};m.children.forEach(x=>{if(Q.setSharedVariablesOfObject(x),!x.userData.isLayoutLevelObject)return;const E=x.name;let M;if(E!==N.MODEL_LAYOUT_NAME){const O=b[E];!O.directAssociatedLeafObjectSet&&(O.directAssociatedLeafObjectSet=new Set),M=O.directAssociatedLeafObjectSet}x.traverse(O=>{if(Q.setSharedVariablesOfObject(O),O.userData.isSnapGroup&&(O.visible=N.SHOW_SNAP_OBJECT),O.geometry){const T=O.userData.layerName;this.getLayerVisible(e,T)===!1&&(O.visible=!1,O.userData.layerVisible=!1),S(O),M&&M.add(O)}})}),P.info("[Dxf] loadEntities() done in "+(Date.now()-s)/1e3+"s");const w=Object.assign(Object.assign({},e),{threejsObject:m,layersAndThreejsObjects:y,loadedEntityCount:n,layoutViewportsMap:h});if(N.LOADLLDATA){const x=m.children[0].children,E=[];for(let M=0;M<x.length;M++){const O=x[M];if(O?.userData?.llbData){const T=new p.Box3().setFromObject(O);T.getSize(new p.Vector3);const v=T.getCenter(new p.Vector3);E.push({...O,boundingBox:{max:T.max,min:T.min,center:v}})}else if(O.children&&O.children.some(T=>T.userData?.llbData))for(let T=0;T<O.children.length;T++){const v=O.children[T];if(v.userData?.llbData){v.updateWorldMatrix(!0,!0);const C=new p.Box3().setFromObject(v);C.getSize(new p.Vector3);const _=C.getCenter(new p.Vector3);E.push({...v,boundingBox:{max:C.max,min:C.min,center:_}})}}}w.llbMesh=E}return Promise.resolve(w)}getFontFilesFromDxf(e){const i=new Set,s=e.tables?.style?.styles;if(s)for(const n in s){const r=s[n],a=r.fontFile,o=r.bigFontFile;a&&i.add(a),o&&i.add(o)}P.info("[Dxf] Fonts used by dxf: "+Array.from(i).join())}async loadEntitiesForCompare(e,i,s,n=!0,r){const a=e.entities.length,o=i.entities.length,l=async()=>{const d=this.compareContext,u=d.isTheFirstFile,f=u?e:i,m=new j,b=u?a:o;this.entityCount=b,Object.keys(f.blocks).forEach(v=>{this.entityCount+=f.blocks[v].entities?.length||0});const y=Math.round(Math.pow(b,.5));let S=Date.now();const w=async v=>{if(r&&(v%y===0||v===b-1)){let C=v+1;!u&&(C+=a),r(new ProgressEvent("parseProgress",{loaded:C,total:a+o}));const _=500,A=Date.now();(A-S>_||v===b-1)&&(await U.sleep(0),S=A)}};this.parseHeader(f.header);let x={};for(let v=0;v<b;v++){if(this.aborted)return;const C=f.entities[v],_=this.getLayout(f,C);if(_.layoutName!==N.MODEL_LAYOUT_NAME){await w(v);continue}const A=this.loadEntity(C,f);if(!A){await w(v);continue}let I=m.children.find(B=>B.name===N.MODEL_LAYOUT_NAME);!I&&(I=new j,I.name=N.MODEL_LAYOUT_NAME,I.userData.isLayoutLevelObject=!0,m.add(I)),I.add(A),A.traverse(B=>{if(B.geometry){const D=B.userData.layerName,k=this.getLayerVisible(f,D);B.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[_.layoutName]&&(this.layoutsSnapObjectsMap[_.layoutName]=[]),this.layoutsSnapObjectsMap[_.layoutName].push(B),k===!1&&A.layers.disable(Ue));let z=x[D];!z&&(z=[],x[D]=z),z.push(B)}}),await w(v)}n&&u&&!d.preservedHandles&&(d.preservedHandles=new Set);for(const v in s){const C=s[v];u&&(C.type===je.Added||C.type===je.Modified)&&(d.preservedHandles?.add(C.handle),C.parentHandles&&C.parentHandles.forEach(A=>d.preservedHandles?.add(A)));let _=this.entityThreejsCache&&this.entityThreejsCache[C.handle];if(C.parentHandles&&(_=this.entityThreejsCache&&this.entityThreejsCache[C.parentHandles[C.parentHandles.length-1]]),_){if(_.parent&&_.parent.userData.originalType){this.setObjectColorByChange(_,{type:je.NoChange});continue}_=this.setObjectColorByChange(_,C)}if(C.type!==je.NoChange&&_){let A=_.parent;const I=ue.identity();for(;A&&A.userData.isLayoutLevelObject!==!0;)I.premultiply(A.matrix),A=A.parent;ut.makeEmpty();const B=j.getBox(_,ut);B.applyMatrix4(I),C.type===je.Added?!u&&(C.box=new p.Box3().copy(B)):C.type===je.Removed?u&&(C.box=new p.Box3().copy(B)):C.type===je.Modified&&(C.box?C.box.union(B):C.box=new p.Box3().copy(B))}}for(const v in this.layoutsSnapObjectsMap){const C=m.children.find(I=>I.name===v),_=new j;_.name=N.SNAP_GROUP_NAME,C.add(_);const A=this.layoutsSnapObjectsMap[v];for(let I=0;I<A.length;I++){const B=A[I];N.SHOW_SNAP_OBJECT&&(B.layers.enableAll(),B.material instanceof p.PointsMaterial?B.material=Ta:B.material instanceof p.LineBasicMaterial?B.material=Ca:B.material instanceof p.MeshBasicMaterial&&(B.material=Sa));let D=B;const k=ue.identity();for(;D&&D.userData.isLayoutLevelObject!==!0;)k.premultiply(D.matrix),D=D.parent;B.matrix.copy(k),_.add(B)}}this.enableMerge&&N.mergeDxfObjects({root:m,layersAndObjects:x});const E=m.convertToThreejsObject();m.clear(),x={};const M={},O=v=>{const C=v.userData.layerName;let _=M[C];!_&&(_=[],M[C]=_),_.push(v)};E.children.forEach(v=>{Q.setSharedVariablesOfObject(v),v.userData.isLayoutLevelObject&&v.traverse(C=>{if(Q.setSharedVariablesOfObject(C),C.userData.isSnapGroup&&(C.visible=N.SHOW_SNAP_OBJECT),C.geometry){const _=C.userData.layerName;this.getLayerVisible(f,_)===!1&&(C.visible=!1,C.userData.layerVisible=!1),O(C)}})});const T=f;T.threejsObject=E,T.layersAndThreejsObjects=M,T.layoutViewportsMap={}};let h=Date.now();this.compareContext={changes:s,isTheFirstFile:!0},U.printMemory("Before loading entities for first dxf"),await l(),P.info("[Dxf] loadEntities for first dxf in "+(Date.now()-h)/1e3+"s"),U.printMemory("After loading entities for first dxf"),this.releaseCachedData(!1),this.releaseDxfData(e),U.printMemory("Before loading entities for second dxf"),h=Date.now(),this.compareContext.isTheFirstFile=!1,await l(),P.info("[Dxf] loadEntities for second dxf in "+(Date.now()-h)/1e3+"s"),this.printStatsInfo();for(const d of Object.values(s))!d.box&&delete s[d.id];this.compareContext.preservedHandles=void 0,this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(i)),U.printMemory("After loading entities for second dxf")}setObjectColorByChange(e,i){const s=a=>{let o=ot.ENTITY_COLOR_NO_CHANGE;return a.type===je.Added?o=ot.ENTITY_COLOR_ADDED:a.type===je.Removed?o=ot.ENTITY_COLOR_REMOVED:a.type===je.Modified&&(o=this.compareContext?.isTheFirstFile?ot.ENTITY_COLOR_REMOVED:ot.ENTITY_COLOR_ADDED),o},n=(a,o)=>{a.traverse(l=>{if(l.material){if(l.material instanceof p.LineBasicMaterial)l.material=this.getLineBasicMaterial(o);else if(l.material instanceof p.MeshBasicMaterial)l.material=this.getMeshBasicMaterial(o);else if(l.material instanceof p.PointsMaterial)l.material=this.getPointsMaterial(o);else if(l.material instanceof p.ShaderMaterial){const h=l.material.clone();N.updateMaterialUniforms(h),h.uniforms.u_color.value.set(o),l.material=h}}})},r=s(i);return e.traverse(a=>{i.parentHandles?a.userData&&a.userData.handle&&a.userData.handle===i.handle&&(n(a,r),e=a):n(a,r)}),e}releaseCachedData(e=!0){e&&(this.pointsMaterials={},this.lineBasicMaterials={},this.lineShaderMaterials={},this.meshBasicMaterials={},this.meshTextureMaterials={},this.hatchShaderMaterials=[]),this.header=void 0,this.blockReferencesCache={},this.blockRecordsCache=void 0,this.blocksCache=void 0,this.entitiesCache=void 0,this.dictionaryOwnerHandleAndSpatialFilterHandlesCache=void 0,this.spatialFiltersCache=void 0,this.entityThreejsCache=void 0,this.entityTypesAndTimes=void 0,this.entityHandlesWithRenderOrder={},this.layoutsSnapObjectsMap={},this.statsInfo={unsupportedEntity:{},unsupportedEntityTypes:{},unsupportedTextStyles:{},unsupportedHatchPatterns:{},unsupportedPolylineCount:0,invisibleEntities:{},ignoredFrozenLayersAndEntityCount:{},ignoredInserts:{},entityTypesAndMeshCount:{},ignoredPaperSpaceEntityTypesAndCount:{},rebasedEntityCount:0}}releaseEntity(e){e.vertices&&(e.vertices=void 0),e.knotValues&&(e.knotValues=void 0),e.controlPoints&&(e.controlPoints=void 0),e.binaryData&&(e.binaryData=void 0),e.text&&(e.text=void 0),e.extendedData&&(e.extendedData=void 0),e.contextData&&(e.contextData=void 0);const i=e;i.boundaryPaths&&(i.boundaryPaths=[]),i.patternLines&&(i.patternLines=void 0)}releaseDxfData(e){delete e.objects.DICTIONARY,delete e.objects.SORTENTSTABLE,delete e.objects.XRECORD,e.tables&&(delete e.tables.dimStyle,delete e.tables.lineType,delete e.tables.style,delete e.tables.blockRecord),e.entities=[],e.blocks={}}loadEntity(e,i,s,n=!1){if(this.compareContext&&this.compareContext.preservedHandles&&this.compareContext.preservedHandles.has(e.handle)&&ts.includes(e.type)&&(n=!0),!n&&this.compareContext&&this.compareContext.preservedHandles&&!ts.includes(e.type)&&!this.compareContext.preservedHandles.has(e.handle)&&(!s||s&&!this.compareContext.preservedHandles.has(s.handle)))return;if(this.getLayerFrozen(i,e)===!0){const f=e.layer;return!this.statsInfo.ignoredFrozenLayersAndEntityCount[f]&&(this.statsInfo.ignoredFrozenLayersAndEntityCount[f]=0),this.statsInfo.ignoredFrozenLayersAndEntityCount[f]++,void 0}if(e.visible===!1||e.invisible)return!this.statsInfo.invisibleEntities[e.type]&&(this.statsInfo.invisibleEntities[e.type]=0),this.statsInfo.invisibleEntities[e.type]++,void 0;if(this.ignorePaperSpace&&e.inPaperSpace)return!this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]&&(this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]=0),this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]++,void 0;!this.entityThreejsCache&&(this.entityThreejsCache={});const a=Date.now();let o,l=!1;if(!this.compareContext&&this.entityThreejsCache[e.handle])o=this.entityThreejsCache[e.handle].clone(),l=!0;else if(!this.statsInfo.unsupportedEntity[e.handle]){const f=e.isTable;if(e.type==="CIRCLE"||e.type==="ARC")o=this.loadArc(e,i,s);else if(e.type==="LINE"||e.type==="POLYLINE")o=this.loadLine(e,i);else if(e.type==="XLINE")o=this.loadXLine(e);else if(e.type!=="SEQEND"){if(e.type==="RAY")o=this.loadRay(e);else if(e.type==="LWPOLYLINE")o=this.loadLWPolyline(e,i,s);else if(e.type==="3DFACE")o=this.load3DFace(e);else if(e.type==="TEXT")o=this.loadText(e,i,s);else if(e.type==="SOLID")o=this.loadSolid(e,i,s);else if(e.type==="POINT")o=this.loadPoint(e,i,s);else if(e.type==="IMAGE")o=this.loadImage(e,i,s);else if(e.type==="INSERT")o=this.loadInsert(e,i,s,n);else if(e.type==="SPLINE")o=this.loadSpline(e,s);else if(e.type==="MTEXT")f?o=this.loadTableMText(e,i,s):o=this.loadMText(e,i,s);else if(e.type==="ELLIPSE")o=this.loadEllipse(e,i,s);else if(e.type==="DIMENSION")o=this.loadDimension(e,i);else if(e.type!=="REGION")if(e.type==="ATTDEF")o=this.loadAttDef(e,i,s);else if(e.type==="ATTRIB"){if(!s){if(!this.entitiesByHandleIndex||this.entitiesByHandleIndexData!==i){this.entitiesByHandleIndexData=i,this.entitiesByHandleIndex=new Map;for(let m=0;m<i.entities.length;m++){const b=i.entities[m];b.handle&&this.entitiesByHandleIndex.set(b.handle,{entity:b,index:m})}}if(e.ownerHandle){const m=this.entitiesByHandleIndex.get(e.ownerHandle);m?.entity.type==="INSERT"&&(s=m.entity)}if(!s){const m=e.handle?this.entitiesByHandleIndex.get(e.handle):void 0;if(m)for(let b=m.index-1;b>=0;b--){const y=i.entities[b];if(y.type==="INSERT"){s=y;break}}}}o=this.loadAttrib(e,i,s)}else e.type==="HATCH"?o=this.loadHatch(e,i,s):e.type==="VIEWPORT"?o=this.loadViewport(e,i,s):e.type==="LEADER"?o=this.loadLeader(e,i,s):e.type==="MULTILEADER"?o=this.loadMLeader(e,i,s):e.type==="OLE2FRAME"?o=this.loadOle2frame(e,i):e.type==="ACAD_TABLE"&&(o=this.loadTable(e,i))}o&&(this.entityThreejsCache[e.handle]=o),this.enableReleaseData&&!this.compareContext&&this.releaseEntity(e)}if(o){const f=this.getLayerName(e,i,s);if(o.userData.handle=e.handle,e.type!=="INSERT"&&e.type!=="DIMENSION"&&o.traverse(m=>{m.geometry&&(m.userData.layerName=f,m.userData.handle=e.handle,m.userData.dxfType=e.type,this.setMaterial(m,e,i,s))}),!l&&(this.nonSnapableTypes.has(e.type)&&o.traverse(m=>{m.layers.disable(Ue)}),this.enableRenderOrder&&(this.entityHandlesWithRenderOrder[e.handle]?o.renderOrder=parseInt(this.entityHandlesWithRenderOrder[e.handle],16)+.1:o.renderOrder=parseInt(e.handle,16))),e.type==="INSERT"&&!s&&!this.enableRenderOrder){const m=e.block?i.blocks[e.block]?.entities:void 0;let b=!0;if(m?.length)for(const w of m){const x=w;if(x.type==="ATTDEF"||x.type==="SEQEND")continue;if(!(x.type==="LINE"||x.type==="SPLINE"||(x.type==="LWPOLYLINE"||x.type==="POLYLINE")&&!x.shape)){b=!1;break}}else b=!1;const y=Math.min(parseInt(e.handle,16)||0,3999),S=b?xe.InsertLine+y*1e-5:xe.InsertSymbol+y*1e-4;o.traverse(w=>{if(w.geometry&&w.renderOrder<xe.Text&&(w.renderOrder=S,b)){const x=w.geometry.getAttribute("position");if(x){let E=!1;for(let M=0;M<x.count;M++)x.getZ(M)!==0&&(x.setZ(M,0),E=!0);E&&(x.needsUpdate=!0,w.geometry.computeBoundingBox(),w.geometry.computeBoundingSphere())}}})}}const h=e.type,d=e.handle,u=ts.includes(h);if(!u){this.entityTypesAndTimes||(this.entityTypesAndTimes={}),this.entityTypesAndTimes[h]||(this.entityTypesAndTimes[h]={createCount:0,totalTime:0,averageTime:0});const f=this.entityTypesAndTimes[h];f.createCount++,f.totalTime+=Date.now()-a}return o?this.statsInfo.entityTypesAndMeshCount[h]?this.statsInfo.entityTypesAndMeshCount[h]++:this.statsInfo.entityTypesAndMeshCount[h]=1:(this.statsInfo.unsupportedEntityTypes[h]?this.statsInfo.unsupportedEntityTypes[h]++:this.statsInfo.unsupportedEntityTypes[h]=1,u||(this.statsInfo.unsupportedEntity[d]?this.statsInfo.unsupportedEntity[d]++:this.statsInfo.unsupportedEntity[d]=1)),o}loadEllipse(e,i,s){if(!e.majorAxisEndPoint||!e.center||e.axisRatio===void 0||e.startAngle===void 0||e.endAngle===void 0)return;let n=e.startAngle,r=e.endAngle;if(e.extrusionDirection&&e.extrusionDirection.z<0&&(n=Math.PI*2-e.endAngle,r=Math.PI*2-e.startAngle),V.areNumbersEqual(n,r,1e-5))return P.warn("[Dxf] Ellipse entity (handle '%s') contains the same start and end angle, ignored!",e.handle),void 0;let a=r-n;for(;a>Math.PI*2;)a-=Math.PI*2;Math.abs(a)<=1e-5&&(r=V.floorNumber(n+Math.PI*2,5));const o=Math.sqrt(Math.pow(e.majorAxisEndPoint.x,2)+Math.pow(e.majorAxisEndPoint.y,2)),l=o*e.axisRatio,h=Math.atan2(e.majorAxisEndPoint.y,e.majorAxisEndPoint.x),d=new p.EllipseCurve(e.center.x,e.center.y,o,l,n,r,!1,h);let u=1;const f=s;f?.xScale&&f?.yScale&&(u=Math.max(Math.abs(f.xScale),Math.abs(f.yScale)));const m=this.getDivision(n,r,Math.max(o,l)*u),b=d.getPoints(m),y=[],S=b.length;for(let T=0;T<S-1;T++)V.areVector2sEqual(b[T],b[T+1],1e-9)||y.push(b[T]);if(y.push(b[S-1]),y.length<2)return P.warn("[Dxf] Ellipse entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const w=new p.Vector3;let x=!1;this.enableRTC&&(x=G.checkAndRebasePositionsOnRTC(y,w));const E=new p.BufferGeometry().setFromPoints(y),M=new j(q.Line);M.geometry=E,M.material=ge;const O=new j(q.Point);return O.geometry=va,O.material=zs,O.matrix.setPosition(e.center.x,e.center.y,e.center.z),O.userData.isSnapObject=!0,O.userData.type="CircleCenter",O.layers.set(Ue),M.add(O),x&&(this.setRTCUserData(M),M.matrix.setPosition(w.x,w.y,0)),M.layers.enableAll(),M}loadMText(e,i,s){if(!e.text)return;if(!this.font)return P.info("[Dxf] Font file not set, ignoring text entity."),void 0;const n=this.getTextStyle(i,e),r=is(e.text,{encoding:this.getTextEncoding(n)}),a=this.getMTextGroup(r,e,n,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose($,ye,st),e.position&&($.x+=e.position.x,$.y+=e.position.y,o.matrix.compose($,ye,st)),ut.makeEmpty();const l=j.getBox(o,ut),h=l.getSize(H),d=e.width||h.x,u=e.height||h.y,f=h.y>0?h.y:u,m=e.text;let b=0,y=0;switch(document.createElement("canvas").getContext("2d"),e.attachmentPoint){case 1:b=0,y=0;break;case 2:b-=d/2,y=0;break;case 3:b-=d,y=0;break;case 4:b=0,y+=f/2;break;case 5:b-=d/2,y+=f/2;break;case 6:b-=d,y+=f/2;break;case 7:b=0,y+=f;break;case 8:b-=d/2,y+=f;break;case 9:b-=d,y+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:y+=u;break;case 4:break;case 5:const I=m.split("\\P");let B=0;I>1&&(B=I-1),B>1?y+=u*(B-1):y-=u/4;break;default:return}o.traverse(I=>{I.geometry&&I.geometry.translate(b,y,0),I.layers.enableAll()});let w=0;if(e.rotation&&(w=e.rotation*Math.PI/180),e.directionVector){const I=e.directionVector,B=new p.Vector3(I.x,I.y,I.z),D=B.clone().cross(We),k=We.angleTo(B);w=D.z>0?-k:k}G.shouldRebasePositionOnRTC($)&&this.setRTCUserData(o),o.matrix.compose($,ye,st);const x=e.position?$.clone().sub(e.position):$;it.makeTranslation(-x.x,-x.y,0),ue.makeRotationZ(w),o.matrix.multiply(it),o.matrix.multiply(ue),o.matrix.multiply(it.invert()),o.userData||(o.userData={});const E=o.matrix.elements,M=E&&E[12]||0,O=E&&E[13]||0,T=E&&E[14]||0,v=new p.Box3;j.getBox(o,v);const C=new p.Vector3;v.getCenter(C);const _=new p.Vector3;v.getSize(_),o.userData.renderArea={position:{x:M,y:O,z:T},bbox:{min:{x:v.min.x,y:v.min.y,z:v.min.z},max:{x:v.max.x,y:v.max.y,z:v.max.z},center:{x:C.x,y:C.y,z:C.z},width:_.x,height:_.y,depth:_.z},textSize:{width:d,height:u},rotation:w,attachmentPoint:e.attachmentPoint||0,drawingDirection:e.drawingDirection||0};const A=this;return o.userData.textContent=e.text||"",o.userData.cleanText=A.cleanMTextContent?A.cleanMTextContent(e.text):e.text,o.userData.dxfType="MTEXT",o.userData.isMText=!0,o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",o.traverse(I=>{I.geometry&&(I.userData.textContent=e.text||"",I.userData.dxfType="MTEXT",I.userData.layer=e.layer||"0",I.userData.handle=e.handle||"")}),o.userData.entityId=e.entityId||e.handle,o}loadTableMText(e,i,s){if(!e.text)return;if(!this.font)return P.info("[Dxf] Font file not set, ignoring text entity."),void 0;const n=this.getTextStyle(i,e),r=is(e.text,{encoding:this.getTextEncoding(n)}),a=this.getMTextGroup(r,e,n,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose($,ye,st),e.position&&($.x+=e.position.x,$.y+=e.position.y,o.matrix.compose($,ye,st)),ut.makeEmpty();const l=j.getBox(o,ut),h=l.getSize(H),d=e.width||h.x,u=e.height||h.y,f=h.y>0?h.y:u;let m=0,b=0;switch(e.attachmentPoint){case 1:m=0,b=0;break;case 2:m-=d/2,b=0;break;case 3:m-=d,b=0;break;case 4:m=0,b+=f/2;break;case 5:m-=d/2,b+=f/2;break;case 6:m-=d,b+=f/2;break;case 7:m=0,b+=f;break;case 8:m-=d/2,b+=f;break;case 9:m-=d,b+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:b+=u;break;case 4:break;case 5:break;default:return}o.traverse(w=>{w.geometry&&w.geometry.translate(m,b,0),w.layers.enableAll()});let y=0;if(e.rotation&&(y=e.rotation*Math.PI/180),e.directionVector){const w=e.directionVector,x=new p.Vector3(w.x,w.y,w.z),E=x.clone().cross(We),M=We.angleTo(x);y=E.z>0?-M:M}G.shouldRebasePositionOnRTC($)&&this.setRTCUserData(o),o.matrix.compose($,ye,st);const S=e.position?$.clone().sub(e.position):$;return it.makeTranslation(-S.x,-S.y,0),ue.makeRotationZ(y),o.matrix.multiply(it),o.matrix.multiply(ue),o.matrix.multiply(it.invert()),o}getMTextGroup(e,i,s,n,r,a=0,o=0,l=[]){if(e.length===0)return;let h=i.height||i.contextData&&i.contextData.textHeight||0;if(i.textStyle){if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const M=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[M]&&(this.statsInfo.unsupportedTextStyles[M]=0),this.statsInfo.unsupportedTextStyles[M]++}h=h||s.textHeight}let d="Left";i.width&&i.attachmentPoint&&([1,4,7].includes(i.attachmentPoint)?d="Left":[2,5,8].includes(i.attachmentPoint)?d="Center":[3,6,9].includes(i.attachmentPoint)&&(d="Right"));const u=i.width||0,f=new j;let m,b=s.fontFile,y=1,S=1,w=256,x=h*.8,E=x+h;for(let M=0;M<e.length;M++){const O=e[M];if(typeof O=="string"){const T=[],v=(A,I)=>{let B;if(A.forEach((D,k)=>{!D.boundingBox&&D.computeBoundingBox(),k===0?B=D.boundingBox:B.union(D.boundingBox)}),B)switch(d){case"Left":break;case"Center":A.forEach(D=>D.translate((u-I)/2,0,0));break;case"Right":A.forEach(D=>D.translate(u-I,0,0));break}T.push(...A)};let C;for(let A=0;A<O.length;A++){const I=O[A];if(I===`
|
|
794
794
|
`){const D=a;a=0,o-=E,l.length>0&&v(l,D),l=[];continue}if(x=h*.8,E=x+h,C=this.font?.getCharShape(I,b,h),s.bigFontFile&&!C&&(C=this.font?.getCharShape(I,s.bigFontFile,h)),!C&&(C=this.font?.getCharShape(I,"",h)),!C&&(C=this.font?.getNotFoundTextShape(h)),!C){a+=h+S*(h/3.5);continue}a>(u||1/0)&&(l.length>0&&v(l,a),a=0,o-=E,l=[]),C.translate(a,o,0),C.scale(y,1,1),C.boundingBox||C.computeBoundingBox(),O.T&&(S=O.T);const B=Wh(I,C,h,S,b);a+=B,l.push(C)}l.length>0&&(v(l,a),l=[]);const _=new j;if(T.length>0){!m&&(m=i.colorIndex),w!==void 0&&w!==256?(i.color=Ai(w),i.colorIndex=w):i.colorIndex=m;const A=this.getColor(i,n,r),I=T.filter(D=>D instanceof p.ExtrudeGeometry),B=T.filter(D=>!(D instanceof p.ExtrudeGeometry));if(I.length>0){const D=new j(q.Mesh);D.geometry=Ae.mergeGeometries(I),D.material=this.getMeshBasicMaterial(A),_.add(D)}if(B.length>0){const D=new j(q.LineSegment);D.geometry=Ae.mergeGeometries(B),D.material=this.getLineBasicMaterial(A),_.add(D)}}_.matrix.makeTranslation(0,-h,0),f.add(_),y=1,S=1,w=256}else if(Array.isArray(O)){const T=this.getMTextGroup(O,i,s,n,r,a,o,l);T&&(f.add(T.object),a=T.hOffset,o=T.vOffset)}else typeof O=="object"&&(O.f&&(b=O.f,b&&b.includes(".shx")&&P.info("[Dxf] Doesn't support custom fonts: "+b)),O.C&&(w=O.C),O.W&&(O.W[1]==="x"?y=O.W[0]*i.width:y=O.W[0]),O.H&&(O.H[1]==="x"?h=O.H[0]*i.height:h=O.H[0]),O.T&&(S=O.T))}if(f.children.length!==0)return Mt.merge(f,!1),m&&(i.colorIndex=m),f.children.length===1?{object:f.children[0],hOffset:a,vOffset:o}:{object:f,hOffset:a,vOffset:o}}mtextContentAndFormattingToTextAndStyle(e,i){const s={horizontalAlignment:"",textHeight:i.height||i.contextData&&i.contextData.textHeight},n={};let r=1;const a=[];for(let o=0;o<e.length;o++){const l=e[o];if(typeof l=="string"){if(l.startsWith("\\pxq")&&l.endsWith(";"))l.indexOf("c")!==-1?s.horizontalAlignment="center":l.indexOf("l")!==-1?s.horizontalAlignment="left":l.indexOf("r")!==-1?s.horizontalAlignment="right":l.indexOf("j")!==-1&&(s.horizontalAlignment="justify");else if(!l.startsWith("pi")){if(!l.startsWith("pxt")){if(!l.startsWith("pt")){const h=this.getTextLineNum(l);a.push({font:n.f,colorIndex:n.C,text:l,lineNum:r}),r+=h}}}}else if(Array.isArray(l)){const h=this.mtextContentAndFormattingToTextAndStyle(l,i);h.text.forEach(d=>{a.push(d)}),r=h.lineLength}else if(typeof l=="object")if(l.S&&l.S.length===3){const h=l.S[0]+"/"+l.S[2],d=this.getTextLineNum(h);a.push({text:l.S[0]+"/"+l.S[2],lineNum:r}),r+=d}else l.C!==void 0?n.C=l.C:l.W!==void 0?n.W=l.W:l.H!==void 0?n.H=l.H:l.f!==void 0&&(n.f=l.f)}return{text:a,lineLength:r,style:s}}getTextLineNum(e){const i=e.match(new RegExp("\\n","g"));return i?i.length:0}load3DFace(e){if(!e.vertices||e.vertices.length===0)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=e.vertices.map(o=>new p.Vector3(o.x,o.y,o.z));if(i.length===0)return;!V.areVector3sEqual(i[0],i[i.length-1])&&i.push(i[0]);const s=new p.Vector3;let n=!1;this.enableRTC&&(n=G.checkAndRebasePositionsOnRTC(i,s));const r=new p.BufferGeometry().setFromPoints(i),a=new j(q.Line);return a.geometry=r,a.material=ge,n&&(this.setRTCUserData(a),a.matrix.setPosition(s.x,s.y,0)),a.layers.enableAll(),a}loadSpline(e,i){if(!e.controlPoints||!e.degreeOfSplineCurve||!e.knotValues)return;if(e.controlPoints.length<e.degreeOfSplineCurve+1)return P.warn("[Dxf] Spline entity (handle '%s') has degree (%s) >= point count (%s), ignored!",e.handle,e.degreeOfSplineCurve,e.controlPoints.length),void 0;let s=1/0,n=1/0,r=-1/0,a=-1/0;for(const w of e.controlPoints)w.x<s&&(s=w.x),w.y<n&&(n=w.y),w.x>r&&(r=w.x),w.y>a&&(a=w.y);let o=1;const l=i;l?.xScale&&l?.yScale&&(o=Math.max(Math.abs(l.xScale),Math.abs(l.yScale)));const h=Math.max(r-s,a-n),d=this.getBSplineInterpolationsPerSplineSegment(e.controlPoints.length,h*o),u=_a(e.controlPoints,e.degreeOfSplineCurve,e.knotValues,d),f=new p.Vector3;let m=!1;this.enableRTC&&(m=G.checkAndRebasePositionsOnRTC(u,f));const b=G.getAdjacentNonRepeatPoints(u);if(b.length<2)return P.warn("[Dxf] Spline entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const y=new p.BufferGeometry().setFromPoints(b),S=new j(q.Line);return S.geometry=y,S.material=ge,m&&(this.setRTCUserData(S),S.matrix.setPosition(f.x,f.y,0)),S.layers.enableAll(),S}loadXLine(e){if(!e.vertices||e.vertices.length===0)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=U.arrayOrObjectToVector3(e.directionVector),s=new p.Vector3(e.vertices[0].x,e.vertices[0].y,0),n=[];if(n.push(i.clone().multiplyScalar(-1e6).add(s)),n.push(i.clone().multiplyScalar(1e6).add(s)),n.length===0)return;const r=new p.Vector3;let a=!1;this.enableRTC&&(a=G.checkAndRebasePositionsOnRTC(n,r));const o=new p.BufferGeometry().setFromPoints(n),l=new j(q.Line);return l.geometry=o,l.material=ge,a&&(this.setRTCUserData(l),l.matrix.setPosition(r.x,r.y,0)),l.layers.enableAll(),l}loadRay(e){if(!e.vertices||e.vertices.length===0)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=U.arrayOrObjectToVector3(e.directionVector),s=e.vertices.map(l=>new p.Vector3(l.x,l.y,0));if(s.push(i.multiplyScalar(1e6).add(s[0])),s.length===0)return;const n=new p.Vector3;let r=!1;this.enableRTC&&(r=G.checkAndRebasePositionsOnRTC(s,n));const a=new p.BufferGeometry().setFromPoints(s),o=new j(q.Line);return o.geometry=a,o.material=ge,r&&(this.setRTCUserData(o),o.matrix.setPosition(n.x,n.y,0)),o.layers.enableAll(),o}loadLine(e,i){if(!e.vertices||e.vertices.length===0){P.warn("[Dxf] Entity is missing vertices:",e.handle);return}let s=[];if(e.isPolyfaceMesh)s=o1(e.vertices);else{const h=Vn(e.vertices,e.shape);e.shape&&h.length>0&&h.push(h[0]),h.length>0&&(s=[h])}if(s.length===0)return;const n=[];for(let h=0;h<s.length;){const[d,u]=s[h];V.areVector3sEqual(d,u)&&s[h].length<=2?(n.push(d.clone()),s.splice(h,1)):h++}const r=new p.Vector3;let a=!1,o=0;s.forEach(h=>{h.forEach(d=>r.add(d)),o+=h.length}),o>0&&(r.divideScalar(o),a=this.enableRTC&&G.shouldRebasePositionOnRTC(r));let l=null;if(s.length>0){let h=function(w){return Array.isArray(w.pattern)&&w.pattern.length>0};const d=[],u=[];let f=0;s.forEach(w=>{w.forEach(x=>{a?d.push(new p.Vector3(x.x-r.x,x.y-r.y,x.z-r.z)):d.push(x.clone())});for(let x=1;x<w.length;x++)u.push(f+x-1,f+x);f+=w.length});const m=this.getLineType(e,i),b=i.tables?.lineType?.lineTypes?.[m],y=new p.BufferGeometry().setFromPoints(d);let S=ge;if(b&&h(b)){let w=function(O){const T=O.attributes.position,v=T.count,C=new Float32Array(v);for(let _=0;_<v;_+=2){const A=_*3,I=(_+1)*3,B=T.array[I]-T.array[A],D=T.array[I+1]-T.array[A+1],k=T.array[I+2]-T.array[A+2],z=Math.sqrt(B*B+D*D+k*k);C[_]=_===0?0:C[_-1],C[_+1]=C[_]+z}O.setAttribute("lineDistance",new p.Float32BufferAttribute(C,1))};const x=b.pattern?.[0]||.5,E=b.pattern?.[1]||.5,M=.1;S=new p.LineDashedMaterial({color:ge.color,linewidth:ge.linewidth||1,dashSize:x*M,gapSize:E*M,scale:M}),w(y)}else y.setIndex(u);l=new j(q.LineSegment),l.geometry=y,l.material=S}if(n.length>0){a&&G.checkAndRebasePositionsOnRTC(n,r);const h=new p.BufferGeometry().setFromPoints(n),d=new j(q.Point);d.geometry=h,d.material=zs,l?console.warn("Line has both segments and points – consider using a Group"):l=d}if(l)return a&&(this.setRTCUserData(l),l.matrix.setPosition(r.x,r.y,r.z)),l.layers.enableAll(),l}loadLWPolyline(e,i,s){if(!e.vertices||e.vertices.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const n=[...e.vertices];if(e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0){H.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const b=N.getOcsMatrix(H).invert(),y=e.elevation!==void 0?e.elevation:0;n.forEach(S=>{H.set(S.x,S.y,y).applyMatrix4(b),S.x=H.x,S.y=H.y})}let r=Vn(n,e.shape);if(e.shape&&r.length>0&&!V.areVector3sEqual(r[0],r[r.length-1])&&r.push(r[0]),r.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}let a=new j;const o=e.extendedData;if(o?.outlines){const b=o.outlines,y=[];b.forEach(x=>{const E=new p.Shape;x.forEach((M,O)=>{O===0?E.moveTo(M[0],M[1]):E.lineTo(M[0],M[1])}),E.closePath(),y.push(new p.ShapeGeometry(E))});const S=Ae.mergeGeometries(y),w=new j(q.Mesh);w.geometry=S,w.material=pi,w.layers.enableAll(),w.layers.disable(Ue),a.add(w)}let l=!1;const h=new p.Vector3;this.enableRTC&&(l=G.checkAndRebasePositionsOnRTC(r,h));const d=G.getAdjacentNonRepeatPoints(r);if(d.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const u=e.constantWidth,f=d.length>2&&V.areVector3sEqual(d[0],d[d.length-1]);if(this.enablePlineWidth&&!f){const b=n.some(y=>y.startWidth!==void 0||y.endWidth!==void 0);if(b||u!==void 0&&u>0){let y;const S=i.tables?.lineType?.lineTypes,w=this.getLineType(e,i,s),x=S?.[w];if(!x||!x.pattern||x.pattern.length===0)if(this.statsInfo.unsupportedPolylineCount++,b?y=this.createTaperedPolylineGeometry(n,u):y=G.convertWidthLineToMeshGeometry(d,u),!y)P.warn("[Dxf] Failed to convert line with width to mesh geometry: %s",e.handle);else{const E=new j(q.Mesh);E.geometry=y,E.material=pi,E.layers.enableAll(),E.layers.disable(Ue),a.add(E);const M=Q.createOutline(y,ge,E.matrix),O=new j(q.LineSegment);O.geometry=M.geometry,O.material=M.material,O.matrix=M.matrix,O.layers.enableAll(),O.layers.disable(Ue),a.add(O)}}}const m=new j(q.Line);return m.geometry=new p.BufferGeometry().setFromPoints(d),m.material=ge,m.layers.enableAll(),a.children.length>0?a.add(m):a=m,l&&(this.setRTCUserData(a),a.matrix.setPosition(h)),a}createTaperedPolylineGeometry(e,i){if(!e||e.length<2)return null;const s=[],n=[];for(let a=0;a<e.length-1;a++){const o=e[a],l=e[a+1],h=l.x-o.x,d=l.y-o.y,u=Math.hypot(h,d);if(u===0)continue;const f=o.startWidth??i??0,m=o.endWidth??i??0;if(f<=0&&m<=0)continue;const b=-d/u,y=h/u,S=f/2,w=m/2,x={x:o.x+b*S,y:o.y+y*S},E={x:o.x-b*S,y:o.y-y*S},M={x:l.x+b*w,y:l.y+y*w},O={x:l.x-b*w,y:l.y-y*w},T=s.length/3;s.push(x.x,x.y,0,E.x,E.y,0,M.x,M.y,0,O.x,O.y,0),n.push(T,T+1,T+2),n.push(T+1,T+3,T+2)}if(!n.length)return null;const r=new p.BufferGeometry;return r.setAttribute("position",new p.Float32BufferAttribute(s,3)),r.setIndex(n),r}loadMLeader(e,i,s){const n=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i),r=e.contextData?.defaultTextContents;if(!r)return;const a=new j,o=is(r),l=this.getTextStyle(i,e),h=this.getMTextGroup(o,e,l,i,s),d=h&&h.object;if(d){d.matrix.decompose($,ye,st),e.contextData?.textLocation&&($.x+=e.contextData.textLocation.x,$.y+=e.contextData.textLocation.y,d.matrix.compose($,ye,st)),ut.makeEmpty();const u=j.getBox(d,ut),f=u.getSize(H),m=f.x,b=f.y;let y=0,S=0;switch(e.contextData?.textAttachment){case 1:y=0,S=0;break;case 2:y-=m/2,S=0;break;case 3:y-=m,S=0;break;case 4:y=0,S+=b/2;break;case 5:y-=m/2,S+=b/2;break;case 6:y-=m,S+=b/2;break;case 7:y=0,S+=b;break;case 8:y-=m/2,S+=b;break;case 9:y-=m,S+=b;break;default:return}d.traverse(E=>{E.geometry&&E.geometry.translate(y,S,0)});let w=0;if(e.contextData?.textRotation&&(w=e.contextData.textRotation*Math.PI/180),e.contextData?.textDirection){const E=e.contextData.textDirection,M=new p.Vector3(E.x,E.y,E.z),O=M.clone().cross(We),T=We.angleTo(M);w+=O.z>0?-T:T}G.shouldRebasePositionOnRTC($)&&this.setRTCUserData(d),d.matrix.compose($,ye,st),e.contextData?.textLocation?H.set(e.contextData.textLocation.x,e.contextData.textLocation.y,0):H.set(0,0,0);const x=$.clone().sub(H);it.makeTranslation(-x.x,-x.y,0),ue.makeRotationZ(w),d.matrix.multiply(it),d.matrix.multiply(ue),d.matrix.multiply(it.invert()),d.renderOrder=xe.Text,a.add(d)}if(e.leaderLineType!==0){const u=[],f=e.contextData?.leaders[0];if(!f)return a;const m=f.lastLeaderLinePoint;if(!m)return a;if(e.enableDogLeg&&f.doglegVector){const E=new p.Vector3(m.x,m.y,m.z),M=f.doglegLength,O=new p.Vector3(f.doglegVector.x,f.doglegVector.y,f.doglegVector.z),T=O.multiplyScalar(M),v=E.clone().add(T);u.push(v,E)}const b=e.contextData?.leaders[0].leaderLines||[];for(let E=0;E<b.length;E++){const M=b[E].vertices?.[0];if(!M||M.length===0)continue;const O=M.reverse().map(B=>new p.Vector3(B.x,B.y,B.z));let T=new p.Vector3(m.x,m.y,m.z);for(let B=0;B<O.length;B++)u.push(T,O[B]),T=O[B];if(u.length<2)continue;const v=H.subVectors(u[0],u[1]).length(),C=e.arrowHeadSize||n.DIMASZ||2.5,_=e.arrowHeadScale||n.DIMSCALE||1,A=C*_;e.leaderLineType;let I="";if(e.arrowHeadId?I=e.arrowHeadId:n&&n.DIMLDRBLK&&(I=n.DIMLDRBLK),I){const B=this.getBlockByHandle(i.blocks,I);if(B&&B.entities)for(let D=0;D<B.entities.length;D++){const k=this.loadEntity(B.entities[D],i,e);if(k){const z=new p.Vector3(u[u.length-1].x,u[u.length-1].y,u[u.length-1].z),se=new p.Vector3(u[u.length-2].x,u[u.length-2].y,u[u.length-2].z),ne=Math.atan2(z.y-se.y,z.x-se.x);H.copy(z),$.setScalar(A),ye.setFromAxisAngle(fi,ne),k.matrix.compose(H,ye,$),a.add(k)}}}else this.loadDefaultLeadArrow(u[u.length-2],u[u.length-1],v/2e3,u)}const y=new p.Vector3;let S=!1;this.enableRTC&&(S=G.checkAndRebasePositionsOnRTC(u,y));const w=new p.BufferGeometry().setFromPoints(u),x=new j(q.LineSegment);x.geometry=w,x.material=ge,x.renderOrder=xe.Line,S&&(this.setRTCUserData(x),x.matrix.setPosition(y.x,y.y,0)),a.add(x)}else return d?.traverse(u=>{u.layers.enableAll()}),d;return Mt.merge(a,!1),a.traverse(u=>{u.layers.enableAll()}),a.children.length===1?a.children[0]:a}loadLeader(e,i,s){const n=[];if(!e.vertices)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;if(e.vertices.length<2)return P.warn("leader's vertices number must be greater than 2"),void 0;const r=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i);let a=e.vertices;if(e.pathType===1&&(a=new p.SplineCurve(e.vertices).getPoints(50)),e.textWidth){const S=e.textWidth,w=new p.Vector3(a[a.length-1].x,a[a.length-1].y,a[a.length-1].z);if(e.direction===0){const x=new p.Vector3(1,0,0).multiplyScalar(S);a.push(x.add(w))}else{const x=new p.Vector3(-1,0,0).multiplyScalar(S);a.push(x.add(w))}}for(let S=0;S<a.length-1;S++){const w=a[S],x=a[S+1];n.push(w,x)}const o=H.subVectors(n[0],n[1]).setZ(0).length(),l=e.arrowHeight||r.DIMASZ||2.5,h=e.arrowHeadScale||r.DIMSCALE||1,d=l*h,u=new j;if(e.arrowFlag===1){let S="";e.arrowHeadBlockHandle?S=e.arrowHeadBlockHandle:r&&r.DIMLDRBLK&&(S=r.DIMLDRBLK);const w=this.getBlockByHandle(i.blocks,S);if(w&&w.entities){r&&(e.colorIndex=r.DIMCLRD||256,e.color=Ai(e.colorIndex));for(let x=0;x<w.entities.length;x++){const E=this.loadEntity(w.entities[x],i,e);if(E){const M=new p.Vector3(n[0].x,n[0].y,n[0].z),O=new p.Vector3(n[1].x,n[1].y,n[1].z),T=Math.atan2(M.y-O.y,M.x-O.x);H.copy(M),$.setScalar(d),ye.setFromAxisAngle(fi,T),E.matrix.compose(H,ye,$),u.add(E)}}}else this.loadDefaultLeadArrow(n[1],n[0],d/o/2,n)}if(n.length===0)return;const f=new p.Vector3;let m=!1;this.enableRTC&&(m=G.checkAndRebasePositionsOnRTC(n,f));const b=new p.BufferGeometry().setFromPoints(n),y=new j(q.Line);return y.geometry=b,y.material=ge,y.renderOrder=xe.Line,m&&(this.setRTCUserData(y),y.matrix.setPosition(f.x,f.y,0)),u.children.length>0?(u.add(y),Mt.merge(u,!1),u.traverse(S=>{S.layers.enableAll()}),u.children.length===1?u.children[0]:u):(y.layers.enableAll(),y)}getTableTextOffset(e,i,s){const n=new p.Vector3;switch(e){case 1:break;case 2:n.setX(i/2);break;case 3:n.setX(i);break;case 4:n.setY(-s/2);break;case 5:n.set(i/2,-s/2,0);break;case 6:n.set(i,-s/2,0);break;case 7:n.setY(-s);break;case 8:n.set(i/2,-s,0);break;case 9:n.set(i,-s,0);break}return n}loadTable(e,i,s){if(!e.startPoint){P.warn("[Dxf] Entity is missing startPoint:",e.handle);return}if(e.cells.length===0){P.warn("[Dxf] Entity is missing cells:",e.handle);return}if(e.rowHeightArr.length===0){P.warn("[Dxf] Entity is missing rowHeightArr:",e.handle);return}if(e.columnWidthArr.length===0){P.warn("[Dxf] Entity is missing columnWidthArr:",e.handle);return}const n=new j,{cells:r,rowCount:a,columnCount:o,rowHeightArr:l,columnWidthArr:h}=e,d=[];let u=0;for(let y=0;y<a;y++){d[y]=[];for(let S=0;S<o;S++)d[y][S]=u<r.length?r[u++]:null}for(let y=0;y<a;y++)for(let S=0;S<o;S++){const w=d[y][S];if(!w||w.mergedValue!==0)continue;let x=1,E=1;for(;y+x<a&&d[y+x][S]&&d[y+x][S].mergedValue===1;)x++;for(;S+E<o&&d[y][S+E]&&d[y][S+E].mergedValue===1;)E++;w.rowSpan=x,w.colSpan=E}const f=[0];for(let y=0;y<a;y++)f.push(f[y]-l[y]);const m=[0];for(let y=0;y<o;y++)m.push(m[y]+h[y]);const b=[];for(let y=0;y<=a;y++){let S=m[0],w=!1;for(let x=0;x<o;x++){y>0&&d[y-1][x],y<a&&d[y][x];let E=!0;if(y===0||y===a)E=!0;else{const M=this._getMergeOwner(d,y-1,x,a,o),O=this._getMergeOwner(d,y,x,a,o);E=M!==O}E?w||(w=!0,S=m[x]):w&&(b.push(new p.Vector3(S,f[y],0),new p.Vector3(m[x],f[y],0)),w=!1)}w&&b.push(new p.Vector3(S,f[y],0),new p.Vector3(m[o],f[y],0))}for(let y=0;y<=o;y++){let S=f[0],w=!1;for(let x=0;x<a;x++){y>0&&d[x][y-1],y<o&&d[x][y];let E=!0;if(y===0||y===o)E=!0;else{const M=this._getMergeOwner(d,x,y-1,a,o),O=this._getMergeOwner(d,x,y,a,o);E=M!==O}E?w||(w=!0,S=f[x]):w&&(b.push(new p.Vector3(m[y],S,0),new p.Vector3(m[y],f[x],0)),w=!1)}w&&b.push(new p.Vector3(m[y],S,0),new p.Vector3(m[y],f[a],0))}if(b.length>0){const y=new p.BufferGeometry().setFromPoints(b),S=new j(q.LineSegment);S.geometry=y,S.material=ge,S.layers.enableAll(),n.add(S)}for(let y=0;y<a;y++)for(let S=0;S<o;S++){const w=d[y][S];if(!w||w.mergedValue!==0)continue;const x=m[S],E=f[y];let M=0;for(let C=0;C<(w.colSpan||1);C++)M+=h[S+C];let O=0;for(let C=0;C<(w.rowSpan||1);C++)O+=l[y+C];w.colorIndex=e.colorIndex,w.height=w.textHeight||2.5;const T=this.getTableTextOffset(w.attachmentPoint||1,M,O);H.set(x,E,0),H.add(T),w.position=H.clone();const v=this.loadMText(w,i,s);v&&n.add(v)}if(e.blockRecordHandle){const y=this.getBlockByHandle(i.blocks,e.blockRecordHandle);if(y&&y.entities)for(const S of y.entities){S.isTable=!0;const w=this.loadEntity(S,i,e);w&&n.add(w)}}return n.matrix.decompose(H,ye,st),H.x+=e.startPoint.x,H.y+=e.startPoint.y,n.matrix.compose(H,ye,st),n}_getMergeOwner(e,i,s,n,r){let a=i,o=s;for(;a>=0&&e[a][o]&&e[a][o].mergedValue===1;){if(a>0&&e[a-1][o]&&e[a-1][o].mergedValue!==1){a--;break}if(o>0&&e[a][o-1]&&e[a][o-1].mergedValue!==1){o--;break}if(a>0)a--;else if(o>0)o--;else break}return e[a]?.[o]||null}loadDefaultLeadArrow(e,i,s,n){const r=s*(e.x-i.x),a=s*(e.y-i.y),o=a,l=-r,h=new p.Vector3(i.x+r+o/6,i.y+a+l/6,0),d=new p.Vector3(i.x+r-o/6,i.y+a-l/6,0);n.push(i,h),n.push(i,d),n.push(h,d)}getBlockByHandle(e,i){if(!this.blocksCache){this.blocksCache={};for(const s in e){const n=e[s];!this.blocksCache[n.ownerHandle]&&(this.blocksCache[n.ownerHandle]=n)}}return this.blocksCache[i]}static updateMaterialUniforms(e){e instanceof p.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=N.CameraZoomUniform),e.uniforms.u_viewportScale&&(e.uniforms.u_viewportScale=N.ViewportScaleUniform))}static transformAngleByOcsMatrix(e,i){const s=H.set(Math.cos(i)*1,Math.sin(i)*1,0),n=s.applyMatrix4(e);return Math.atan2(n.y,n.x)}static getArcAnglesByOcsMatrix(e,i,s){let n=V.getArcAngleSpanInRadian(i,s);const r=N.transformAngleByOcsMatrix(e,i),a=N.transformAngleByOcsMatrix(e,s);let o;if(V.areNumbersClose(n,Math.PI)){n=1;const l=N.transformAngleByOcsMatrix(e,i+n);o=V.getArcAngleSpanInRadian(r,l)}else{if(V.areNumbersClose(n,Math.PI*2))return[r,r+Math.PI*2];o=V.getArcAngleSpanInRadian(r,a)}return V.areNumbersClose(n,o,1e-5)?[r,a]:[a,r]}loadArc(e,i,s){if(!e.radius||e.radius<.001)return P.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is undefined, ignored!"),void 0;if(!e.radius||e.radius<.001)return P.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is too small, ignored!"),void 0;const n=new p.Vector3(0,0,1);e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0&&n.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const r=N.getOcsMatrix(n);let a,o;if(e.type==="CIRCLE")a=e.startAngle||0,o=a+2*Math.PI;else{if(e.startAngle==null||e.endAngle==null||(a=e.startAngle,o=e.endAngle,V.areNumbersEqual(a,o,1e-6)))return;if(!V.areNumbersClose(V.getArcAngleSpanInRadian(a,o),Math.PI*2)){const O=N.getArcAnglesByOcsMatrix(r,a,o);a=O[0],o=O[1]}}const l=new p.ArcCurve(0,0,e.radius,a,o,this.angBase!==0);let h=1;const d=s;d?.xScale&&d?.yScale&&(h=Math.max(Math.abs(d.xScale),Math.abs(d.yScale)));const u=this.getDivision(a,o,e.radius*h),f=l.getPoints(u),m=new p.Vector3;let b=!1;this.enableRTC&&(b=G.checkAndRebasePositionsOnRTC(f,m));const y=new p.BufferGeometry().setFromPoints(f),S=new j(q.Line);S.geometry=y,S.material=ge;const w=new p.Vector3;e.center&&(w.x=e.center.x,w.y=e.center.y);const x=new p.Vector3(e.center?.x,e.center?.y,e.center?.z).applyMatrix4(r.invert());w.x=x.x,w.y=x.y;const E=w,M=new j(q.Point);return M.geometry=va,M.material=zs,M.userData.handle=e.handle,M.userData.isSnapObject=!0,M.userData.type="CircleCenter",M.layers.set(Ue),S.add(M),b?(this.setRTCUserData(S),E.x+=m.x,E.y+=m.y):G.shouldRebasePositionOnRTC(E)&&this.setRTCUserData(S),S.matrix.setPosition(E),S.layers.enableAll(),S}addTriangleFacingCamera(e,i,s,n){const r=new p.Vector3,a=new p.Vector3;r.subVectors(s,i),a.subVectors(n,i),r.cross(a);const o=new p.Vector3(i.x,i.y,i.z),l=new p.Vector3(s.x,s.y,s.z),h=new p.Vector3(n.x,n.y,n.z);r.z<0?e.push(h,l,o):e.push(o,l,h)}loadSolid(e,i,s){const n=e.points;if(!n||n.length<4)return;if(e.extrusionDirection&&e.extrusionDirection.z){H.set(0,0,e.extrusionDirection.z);const u=N.getOcsMatrix(H).invert();n.forEach(f=>{const m=H.set(f.x,f.y,0).applyMatrix4(u);f.x=m.x,f.y=m.y})}const r=[],a=[];this.addTriangleFacingCamera(r,n[0],n[1],n[2]),a.push(0,1,2),this.addTriangleFacingCamera(r,n[1],n[2],n[3]),a.push(3,4,5);const o=new p.Vector3;let l=!1;this.enableRTC&&(l=G.checkAndRebasePositionsOnRTC(r,o));const h=new p.BufferGeometry().setFromPoints(r);h.setIndex(a);const d=new j(q.Mesh);return d.geometry=h,d.material=pi,l&&(this.setRTCUserData(d),d.matrix.setPosition(o.x,o.y,0)),d.layers.enableAll(),d}getTextStyle(e,i){const s=e.tables?.style?.styles;return s?s[i.textStyle]||s.STANDARD||s.Standard||{}:{}}getDefaultDimensionStyle(e){return e.tables.dimStyle.dimStyles.STANDARD||e.tables.dimStyle.dimStyles.Standard||{}}getTextEncoding(e){return e?.bigFontFile&&e.bigFontFile.toUpperCase().startsWith("GB")?"gbk":"utf8"}getTextMesh(e,i,s,n){if(!e)return;const r=s?.styleName||"";if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const h=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[h]&&(this.statsInfo.unsupportedTextStyles[h]=0),this.statsInfo.unsupportedTextStyles[h]++}let a=.8;const o={_TCH_DIM:1.45,ROMANS:1};r&&o[r]&&(a=o[r]),n.xScale&&(a*=n.xScale),a>1&&r&&(a*=s?.xScale||1,i=i||s?.textHeight||0),i===0&&(r?i=1:i=.2);const l=this.createTextMeshByText(e,s,i,0,i/12,a);return l.traverse(h=>{h.geometry&&h.geometry.scale(a,1,1)}),l}createTextMeshByText(e,i,s=12,n=0,r=0,a=1,o=1/0,l=0){const h=new j,d=[];let u=0,f=0;i?.xScale;const m=n+s,b=i?.fontFile||"",y=typeof b=="string"&&b.toLowerCase().endsWith(".shx"),S=y?s*.06:s*.04,w=[];for(let M=0;M<e.length;M++){const O=e[M];O!==" "&&O!==`
|
|
795
795
|
`&&w.push(M)}const x=w.length;let E=0;for(let M=0;M<e.length;M++){const O=e[M];if(O===" "){u+=s*(y?.4:.33);continue}if(O===`
|
|
796
|
-
`){u=0,f-=m*.5;continue}let T=this.font?.getCharShape?.(O,i?.fontFile,s);if(!T&&i?.bigFontFile&&(T=this.font?.getCharShape?.(O,i.bigFontFile,s)),!T&&this.font?.fileNames){const v=this.font.fileNames.filter(C=>C!==i?.fontFile);for(let C=v.length-1;C>=0&&(i.fontFile=v[C],i.styleName="Standard",T=this.font?.getCharShape?.(O,i.fontFile,s),!T);C--);}if(T||(T=this.font?.getNotFoundTextShape?.(s)),!!T){if(T.translate(u,f,0),u>o)u=0,f-=m;else{!T.boundingBox&&T.computeBoundingBox();const v=T.boundingBox.getSize(H).x,C=O.charCodeAt(0),A=C>=19968&&C<=40959||C>=13312&&C<=19903||C>=63744&&C<=64255||C>=12288&&C<=12351||C>=65280&&C<=65519||[8216,8217,8220,8221].includes(C)?Math.max(v,s):v+S;E++,u+=A+(E===x?0:l)}d.push(T)}}if(d.length>0){const M=d.filter(T=>T instanceof p.ExtrudeGeometry),O=d.filter(T=>!(T instanceof p.ExtrudeGeometry));if(M.length>0){const T=new j(q.Mesh);T.geometry=Ae.mergeGeometries(M),T.material=pi,h.add(T)}if(O.length>0){const T=new j(q.LineSegment);T.geometry=Ae.mergeGeometries(O),T.material=ge,h.add(T)}}return h}transformTextMesh(e,i){ut.makeEmpty();const s=j.getBox(i,ut),n=s.getSize(H),{halign:r,valign:a}=e;i.matrix.decompose(Vs.position,Vs.quaternion,Vs.scale);const o=Vs,l=e.width||e.textWidth||n.x,h=e.height||e.textHeight||n.y;if(r===void 0&&a===void 0&&e.startPoint||[3,5].includes(r)&&e.startPoint?(o.position.x+=e.startPoint.x,o.position.y+=e.startPoint.y,o.position.z+=e.startPoint.z):e.endPoint&&(o.position.x+=e.endPoint.x,o.position.y+=e.endPoint.y,o.position.z+=e.endPoint.z),r!==3&&r!==5){if(e.rotation){const d=e.rotation*Math.PI/180;o.rotateZ(d)}e.mirrored&2&&o.rotateY(Math.PI),e.mirrored&4&&o.rotateX(Math.PI)}switch(r){case 0:break;case 1:o.translateX(-l/2);break;case 2:o.translateX(-l);break;case 3:if(e.startPoint&&e.endPoint){const d=new p.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),u=new p.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),f=new p.Vector3().subVectors(d,u),m=f.length(),b=m/l;o.scale.multiplyScalar(b);const y=f.clone().cross(We),S=f.angleTo(We);o.rotateZ(y.z>0?Math.PI-S:S-Math.PI),(e.mirrored===2||e.mirrored===4)&&o.rotateX(Math.PI)}break;case 4:o.translateX(-l/2),o.translateY(-h/12);break;case 5:if(e.startPoint&&e.endPoint){const d=new p.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),u=new p.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),f=new p.Vector3().subVectors(d,u),m=f.length(),b=m/l,S=(e.text||"").length;if(S>1){const E=(m-l)/(S-1);o.userData.letterSpacing=E}else b<3&&o.scale.setX(b);const w=f.clone().cross(We),x=f.angleTo(We);o.rotateZ(w.z>0?Math.PI-x:x-Math.PI)}break}switch(a){case 0:break;case 1:break;case 2:o.translateY(-h/2);break;case 3:o.translateY(-h);break}return o.position.z=0,o.updateMatrix(),i.matrix.copy(o.matrix),i}loadText(e,i,s){const n=e.text;if(!n)return;if(!this.font){P.info("[Dxf] Font file not set, ignoring text entity.");return}const r=this.getTextStyle(i,e),o=sn(n,{encoding:this.getTextEncoding(r)}).map(d=>d.text).join(""),l=this.getTextMesh(o,e.textHeight,r,e);if(!l||l.children.length===0)return;this.transformTextMesh(e,l),H.set(l.matrix.elements[12],l.matrix.elements[13],l.matrix.elements[14]);const h=G.shouldRebasePositionOnRTC(H);return h&&this.setRTCUserData(l),l.userData={...l.userData,textContent:n,dxfType:"TEXT",isMText:!1,layer:e.layer||"0",handle:e.handle,entityId:e.entityId||e.handle},l.traverse(d=>{const u=d.geometry;if(u){if(d.userData.textContent=n,d.userData.dxfType="TEXT",d.userData.layer=e.layer||"0",d.userData.handle=e.handle,d instanceof p.Mesh&&!u.getIndex()){const f=u.getAttribute("position"),m=[];for(let b=0;b<f.count;b+=3)m.push(b,b+1,b+2);u.setIndex(m)}if(u.hasAttribute("uv")&&u.deleteAttribute("uv"),u.hasAttribute("normal")&&u.deleteAttribute("normal"),!h){const f=G.caculateGeometryCenter(u);f&&G.shouldRebasePositionOnRTC(f)&&this.setRTCUserData(d)}}}),l.layers.enableAll(),l}loadAttDef(e,i,s){let n=e.tag||e.text||e.prompt;if(!n||!this.font)return;const r=this.getTextStyle(i,e);n=sn(n).map(h=>h.text).join();const o=this.getTextMesh(n,e.textHeight,r,e);if(!o||o.children.length===0)return;this.transformTextMesh(e,o),H.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const l=G.shouldRebasePositionOnRTC(H);return l&&this.setRTCUserData(o),o.traverse(h=>{const d=h.geometry;if(d){if(h instanceof p.Mesh&&!d.getIndex()){const u=d.getAttribute("position"),f=[];for(let m=0;m<u.count;m+=3)f.push(m,m+1,m+2);d.setIndex(f)}if(d.hasAttribute("uv")&&d.deleteAttribute("uv"),d.hasAttribute("normal")&&d.deleteAttribute("normal"),!l){const u=G.caculateGeometryCenter(d);u&&G.shouldRebasePositionOnRTC(u)&&this.setRTCUserData(h)}}}),o.layers.enableAll(),o}loadAttrib(e,i,s){let n=e.text;if(!n||!this.font)return;const r=this.getTextStyle(i,e);n=sn(n).map(u=>u.text).join("");const o=this.getTextMesh(n,e.textHeight,r,e);if(!o||o.children.length===0)return;const l=s?.zdysx;o.userData.llbData=l;let h;if(l)try{h=JSON.parse(l)}catch{h=l}o.userData.textContent=n||"",o.userData.dxfType="ATTRIB",o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",this.transformTextMesh(e,o),H.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const d=G.shouldRebasePositionOnRTC(H);return d&&this.setRTCUserData(o),o.traverse(u=>{const f=u.geometry;if(f){if(u instanceof p.Mesh&&!f.getIndex()){const m=f.getAttribute("position"),b=[];for(let y=0;y<m.count;y+=3)b.push(y,y+1,y+2);f.setIndex(b)}if(f.hasAttribute("uv")&&f.deleteAttribute("uv"),f.hasAttribute("normal")&&f.deleteAttribute("normal"),u instanceof p.Mesh&&(u.entity=e,u.userData.entity=e),u.userData.textContent=n,u.userData.dxfType="ATTRIB",u.userData.layer=e.layer||"0",u.userData.handle=e.handle||"",h!==void 0&&(u.userData.xdata=h),!d){const m=G.caculateGeometryCenter(f);m&&G.shouldRebasePositionOnRTC(m)&&this.setRTCUserData(u)}}}),o.layers.enableAll(),o}loadPoint(e,i,s){if(!e.position)return;const n=new p.BufferGeometry,r=[new p.Vector3(e.position.x,e.position.y,e.position.z)];H.set(0,0,0);const a=H;let o=!1;this.enableRTC&&(o=G.checkAndRebasePositionsOnRTC(r,a)),n.setFromPoints(r);const l=new j(q.Point);return l.geometry=n,l.material=ge,o&&(this.setRTCUserData(l),l.matrix.setPosition(a.x,a.y,0)),l.layers.enableAll(),l}loadDimension(e,i){if(!e.block)return;const s=i.blocks[e.block];if(!s||!s.entities)return;const n=i.tables.dimStyle.dimStyles[e.dimStyleName]||this.getDefaultDimensionStyle(i);n&&n.DIMCLRD>0&&(e.colorIndex=n.DIMCLRD,e.color=Ai(e.colorIndex));const r=new j;for(let o=0;o<s.entities.length;o++){const l=this.loadEntity(s.entities[o],i,e);l&&r.add(l)}if(r.children.length===0){const o=e.name||e.block;return!this.statsInfo.ignoredInserts[o]&&(this.statsInfo.ignoredInserts[o]=0),this.statsInfo.ignoredInserts[o]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const o=this.blockReferencesCache[e.block];o.referenceCount++}r.name=e.type+"<"+s.name+">",r.userData.entityType=e.type;const a=e.insertionPoint;return H.set(0,0,0),a&&H.set(a.x,a.y,0),G.shouldRebasePositionOnRTC(H)&&this.setRTCUserData(r),r.matrix.setPosition(H),r}loadImage(e,i,s){if(!e.imageSize||!i.objects.IMAGEDEF?.length)return;const n=i.objects.IMAGEDEF.filter(y=>y.handle===e.imageDefHandle)[0];if(!n)return;const r=e.imageSize.x,a=e.imageSize.y,o=new j;let l=!1;e.flags===nn.ShowImageWhenNotAlignedWithScreen||e.flags===nn.UseClippingBoundary||e.flags===nn.TransparencyIsOn||(l=!0);const h=new p.PlaneGeometry(r,a);if(l){const y=new p.TextureLoader(this.manager).load(n.filename,void 0,void 0,()=>{console.warn("Please upload the pictures in the same folder, or use url link in the dxf file.")});y.colorSpace=p.SRGBColorSpace;const S=new p.MeshBasicMaterial({transparent:!0,side:p.FrontSide,map:y}),w=new j(q.Mesh);w.geometry=h,w.material=S,o.add(w)}const d=new p.EdgesGeometry(h),u=this.getColor(e,i,s),f=new j(q.Line);f.geometry=d,f.material=this.getLineBasicMaterial(u);const m=e.uPixel?new p.Vector3(e.uPixel.x,e.uPixel.y,e.uPixel.z):new p.Vector3(n.pixelSize.x,0,0),b=e.vPixel?new p.Vector3(e.vPixel.x,e.vPixel.y,e.vPixel.z):new p.Vector3(n.pixelSize.y,0,0);if(o.add(f),$.set(m.x,b.y,1),H.set(0,0,0),e.position){const y=new p.Vector3(e.position.x,e.position.y,e.position.z);y.add(m.multiplyScalar(r/2)).add(b.multiplyScalar(a/2)),H.copy(y)}return G.shouldRebasePositionOnRTC(H)&&this.setRTCUserData(o),ye.identity(),o.matrix.compose(H,ye,$),o}loadInsert(e,i,s,n=!1){if(!e||!e.block)return;const r=i.blocks[e.block];if(!r||!r.entities)return;s&&e.layer==="0"&&(e.layer=s.layer),e.blockPosition=r.position;const a=new j,o=e.zdysx;let l;if(o)try{l=JSON.parse(o)}catch{l=o}for(let m=0;m<r.entities.length;m++){if(r.entities[m].type==="ATTDEF")continue;const b=this.loadEntity(r.entities[m],i,e,n);b&&(o&&N.LOADLLDATA&&(b.userData.llbData=o),l!==void 0&&b.traverse(y=>{y.geometry&&(y.userData.xdata=l)}),a.add(b))}if(a.children.length===0){const m=e.name||e.block;return!this.statsInfo.ignoredInserts[m]&&(this.statsInfo.ignoredInserts[m]=0),this.statsInfo.ignoredInserts[m]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const m=this.blockReferencesCache[e.block];m.referenceCount++}a.name=e.type+"<"+r.name+">",a.userData.entityType=e.type,l!==void 0&&(a.userData.xdata=l),e.extendedData?.originalType&&(a.userData.originalType=e.extendedData?.originalType),e?.blockPosition&&a.matrix.setPosition(-e.blockPosition.x,-e.blockPosition.y,0);const h=H.set(1,1,1);e.xScale&&(h.x=e.xScale),e.yScale&&(h.y=e.yScale);const d=new p.Euler;e.rotation&&(d.z=e.rotation*Math.PI/180),ye.setFromEuler(d,!1);const u=$.set(0,0,0);e.position&&(u.x=e.position.x,u.y=e.position.y),ue.compose(u,ye,h),e.extrusionDirection&&e.extrusionDirection.z<0&&ue.premultiply(Ma.identity().makeScale(-1,1,1)),it.copy(a.matrix),a.matrix.premultiply(ue),$.set(a.matrix.elements[12],a.matrix.elements[13],a.matrix.elements[14]),G.shouldRebasePositionOnRTC($)&&this.setRTCUserData(a);const f=this.findSpatialFilterByHandle(e.handle,i);if(f){this.loadSpatialFilter(f);const m=f;m&&m.clipPolylines&&m.clipPolylines.length>0&&(a.userData.spatialFilterHandle=f.handle,this.cloneMaterialsForSpatialFilter(a),P.debug("[Dxf] Spatial filter:",e.associatedSpatialFilter))}return a}loadSpatialFilter(e){const i=e;if(i.threejsObject)return i.threejsObject.clone();const s=e.invertBlockMatrix;if(!Array.isArray(s)||s.length<12)return P.warn("[Dxf] Spatial filter (handle '"+e.handle+"') has no invertBlockMatrix, ignored!"),void 0;ue.set(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],0,0,0,1);const n=[];e.vertices.forEach(o=>{n.push(new p.Vector3(o.x,o.y,0))});const r={polyline:[],bConcave:!1,bReversed:!1};if(e.numberOfPointsOnClipBoundary===2)r.polyline=n;else{const o=e.numberOfPointsOnClipBoundary,l=3;if(o<l)return P.warn("[Dxf] Invalid clipBoundary: "+e.handle+" !"),void 0;let h=[],d=-1;for(let m=0;m<o;m++){const b=n[m];for(let y=o-1;y>m;y--){const S=n[y];if(V.areVector3sEqual(b,S)&&m+1<y-1&&m+1<o-1&&V.areVector3sEqual(n[m+1],n[y-1])){h.push(b),d=y;break}}if(d>0)break;h.push(b)}if(d>0)for(let m=d+1;m<o;m++)h.push(n[m]);if(h.length<l)return P.warn("[Dxf] Invalid clipBoundary: "+e.handle+"!"),void 0;const u=[],f=[];if(h.forEach(m=>{u.push(new p.Vector2(m.x,m.y)),f.push([m.x,m.y])}),!G.isConvex(u)){P.warn("[Dxf] Concave polygon is not supported for spatial filter (handle '"+e.handle+"'), converting to convex polygon!");const m=vl(f,1/0);h=[],m.forEach(b=>{h.push(new p.Vector3(b[0],b[1],0))})}!V.areVector3sEqual(h[0],h[h.length-1])&&h.push(h[0]),r.polyline=h,r.bReversed=d>0}let a;return this.enableReleaseData&&(e.vertices=[],e.matrix=[],e.invertBlockMatrix=[]),i.localMatrix=ue.clone(),i.clipPolylines=[],i.clipPolylines.push(r),a}loadLayout(e,i,s,n,r,a){if(!e.entities)return;const o=new j;for(let d=0;d<e.entities.length;d++){const u=e.entities[d];this.addViewport(u,a);const f=this.loadEntity(u,i);f&&(this.enableMerge&&Mt.merge(f,!1),o.add(f),f.traverse(m=>{if(m.geometry){const b=m.userData.layerName;let y=r[b];!y&&(y=[],r[b]=y),y.push(m),m.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[s.layoutName]&&(this.layoutsSnapObjectsMap[s.layoutName]=[]),this.layoutsSnapObjectsMap[s.layoutName].push(m))}}))}if(o.children.length===0)return;o.userData.layerName=e.layer;const l=s.layoutName;let h=n.children.find(d=>d.name===l);!h&&(h=new j,h.name=l,h.userData.isLayoutLevelObject=!0,n.add(h)),h.add(o),e.position&&o.matrix.setPosition(e.position.x,e.position.y,e.position.z||0)}convertEdgeToPoints(e){const i=[];if(!e)return i;const s=e.type,n=r=>!!r&&Number.isFinite(r.x)&&Number.isFinite(r.y);switch(s){case Mi.Line:{const r=e;if(!n(r.startPoint)||!n(r.endPoint))break;i.push(new p.Vector2(r.startPoint.x,r.startPoint.y)),i.push(new p.Vector2(r.endPoint.x,r.endPoint.y));break}case Mi.Arc:{const r=e;if(!n(r.center)||!Number.isFinite(r.radius)||r.radius<=0||!Number.isFinite(r.startAngle)||!Number.isFinite(r.endAngle))break;let a=r.startAngle*p.MathUtils.DEG2RAD,o=r.endAngle*p.MathUtils.DEG2RAD;!r.bCounterclockwise&&(a=Math.PI*2-a,o=Math.PI*2-o);const l=new p.ArcCurve(r.center.x,r.center.y,r.radius,a,o,!r.bCounterclockwise),h=this.getDivision(a,o,r.radius),d=l.getPoints(h);e.startPoint=d[0],e.endPoint=d[d.length-1],i.push(...d);break}case Mi.Ellipse:{const r=e;if(!n(r.center)||!n(r.majorAxisEndPoint)||!Number.isFinite(r.minorRatio)||!Number.isFinite(r.startAngle)||!Number.isFinite(r.endAngle))break;const a=Math.sqrt(Math.pow(r.majorAxisEndPoint.x,2)+Math.pow(r.majorAxisEndPoint.y,2)),o=a*r.minorRatio,l=Math.atan2(r.majorAxisEndPoint.y,r.majorAxisEndPoint.x);let h=r.startAngle*p.MathUtils.DEG2RAD,d=r.endAngle*p.MathUtils.DEG2RAD;!r.bCounterclockwise&&(h=Math.PI*2-h,d=Math.PI*2-d);const u=new p.EllipseCurve(r.center.x,r.center.y,a,o,h,d,!r.bCounterclockwise,l),f=this.getDivision(h,d,Math.max(a,o)),m=u.getPoints(f);e.startPoint=m[0],e.endPoint=m[m.length-1],i.push(...m);break}case Mi.Spline:{const r=e,a=_a(r.controlPoints,r.degreeOfSplineCurve,r.knotValues);if(a.length===0)break;e.startPoint=a[0],e.endPoint=a[a.length-1],i.push(...a);break}case Mi.Polyline:{const r=e,a=Vn(r.points,r.isClosed);e.startPoint=a[0],e.endPoint=a[a.length-1],i.push(...a);break}}return i}loadHatch(e,i,s){const n=e;let r=[];function a(M,O){const{startPoint:T,endPoint:v}=M,{startPoint:C,endPoint:_}=O;if(!T||!v||!C||!_)return null;const A=v.x-T.x,I=v.y-T.y,B=_.x-C.x,D=_.y-C.y,k=A*D-I*B;if(Math.abs(k)<1e-10)return null;const z=T.x-C.x,se=T.y-C.y,ne=(B*se-D*z)/k,ze=(A*se-I*z)/k;return ne>=0&&ne<=1&&ze>=0&&ze<=1?{x:T.x+ne*A,y:T.y+ne*I}:null}function o(M){const{edges:O}=M,T=[],v=O.length;if({...M},v!==4)return[M];for(let C=0;C<v;C++)for(let _=C+2;_<v;_++){if(_===C+1||C===0&&_===v-1)continue;const A=a(O[C],O[_]);A&&T.push({edgeIndex1:C,edgeIndex2:_,point:{x:A.x,y:A.y}})}if(T.length&&T.length===1){const C=O[(T[0].edgeIndex1-1+v)%v],_={pathTypeFlag:M.pathTypeFlag,edges:[C,{startPoint:{...O[T[0].edgeIndex1].startPoint},endPoint:{x:T[0].point.x,y:T[0].point.y},type:O[T[0].edgeIndex1].type},{startPoint:{x:T[0].point.x,y:T[0].point.y},endPoint:{x:O[T[0].edgeIndex2].startPoint.x,y:O[T[0].edgeIndex2].startPoint.y},type:O[T[0].edgeIndex2].type}]},A={pathTypeFlag:M.pathTypeFlag,edges:[{startPoint:{x:T[0].point.x-1e-5,y:T[0].point.y-1e-5},endPoint:{...O[T[0].edgeIndex1].endPoint},type:O[T[0].edgeIndex1].type},{...O[T[0].edgeIndex2-1]},{startPoint:O[T[0].edgeIndex2].startPoint,endPoint:{x:T[0].point.x-1e-5,y:T[0].point.y-1e-5},type:O[T[0].edgeIndex2].type}]};return[_,A]}return[M]}if(n.boundaryPaths.length==0)return;for(let M=0;M<n.boundaryPaths.length;M++){const O=n.boundaryPaths[M],T=o(O);r=[...r,...T]}if(n.boundaryPaths=r,!n.solidFill&&!n.patternLines?.length){P.warn("[Dxf] Hatch entity(handle: '"+n.handle+"') doesn't have solid fill, nor patternLines, ignored!");return}const l=[],h=[],d=[],u=M=>{const O=[];let T=[];T.push(...this.convertEdgeToPoints(M[0]));for(let v=1;v<M.length;v++){const C=this.convertEdgeToPoints(M[v]);if(T.push(...C),T.length>2){const _=this.convertEdgeToPoints(M[v-1]);V.areVector2sEqual(_[_.length-1],C[0])?V.areVector2sEqual(T[0],C[C.length-1],1e-5)&&(O.push(T),T=[]):V.areVector2sEqual(_[0],C[C.length-1])?V.areVector2sEqual(T[1],C[0],1e-5)&&(O.push(T),T=[]):T=[]}}return O};if(n.boundaryPaths.forEach((M,O)=>{let T=[];if(this.IsfilteredByPathTypeFlag(M.pathTypeFlag)){P.info("[Dxf] The %d path type flag is filtered at the %dth boundrayPath (hatch handle '%s')",M.pathTypeFlag,O,n.handle);return}const v=M.edges;if(v.length===0)return;const C=[];for(let _=0;_<v.length;_++){const A=this.convertEdgeToPoints(v[_]);if(A.length<2){P.warn("[Dxf] The %dth edge of the %dth boundaryPath (hatch handle '%s') has less than 2 points, ignored!",_,O,n.handle);continue}C.push(...A)}if(C.length<3){P.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has less than 3 points, ignored!",O,n.handle);return}if(T.push(C),M.pathTypeFlag>So.MaxFlags&&(!(A=>{for(let I=1;I<A.length;++I){const B=A[I-1].endPoint,D=A[I].startPoint;if(!B||!D||!V.areVector2sEqual(B,D))return!1}return!0})(M.edges)||!n.associativity)&&(T=u(v),T.length<2)){P.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has unknown path, ignored!",O,n.handle);return}T.forEach(_=>{!V.areVector2sEqual(_[0],_[_.length-1])&&_.push(_[0]);const A=_.map(I=>new p.Vector2(U.roundNumber(I.x,7),U.roundNumber(I.y,7)));if(A?.length>0){l.push(A);const I=new p.Box2().setFromPoints(A);h.push(I);const B=I.getSize(Wi),D=B.x*B.y;d.push({area:D,index:l.length-1})}})}),l.length===0)return;const f=new p.Vector2,m=this.checkAndRebasePolygonsOnRTC(l,f);d.sort((M,O)=>M.area-O.area);const b=[];d.forEach(M=>{b.push(M.index)});const y=this.buildContainHierarchyTree(l,h,b),S=[];this.buildHatchGeometry(l,y,S);let w;if(S.length>0&&(w=Ae.mergeGeometries(S)),!w||!w.getIndex()||w.getIndex()?.count===0)return P.warn("[Dxf] Failed to convert hatch boundaries!"),void 0;const x=new j(q.Mesh);x.geometry=w,x.material=pi,this.setHatchMaterial(x,n,i,f,s);const E=x;return m&&(this.setRTCUserData(E),E.matrix.setPosition(f.x,f.y,0)),E.traverse(M=>{M.layers.enableAll(),M.layers.disable(Ue)}),E}loadOle2frame(e,i){const{leftUpX:s,leftUpY:n,rightDownX:r,rightDownY:a}=e;if(!s||!n||!r||!a)return;const o=[new p.Vector2(s,n),new p.Vector2(s,a),new p.Vector2(r,a),new p.Vector2(r,n),new p.Vector2(s,n)],l=new p.Vector3;let h=!1;this.enableRTC&&(h=G.checkAndRebasePositionsOnRTC(o,l));const d=new p.BufferGeometry().setFromPoints(o),u=this.getLineBasicMaterial(16777215),f=new j(q.Line);f.geometry=d,f.material=u,f.layers.enableAll(),h&&(this.setRTCUserData(f),f.matrix.setPosition(l.x,l.y,0));const m=new j;m.add(f);let b;const y=i.objects.DICTIONARY;for(const w of y)for(const x in w.entries)if(w.entries[x]===e.handle){b=x;break}let S;if(b)if(this.meshTextureMaterials[b])S=this.meshTextureMaterials[b];else for(let w=0;w<i.objects.XRECORD.length;w++){const x=i.objects.XRECORD[w];if(x.handle===b){const E=x.binaryData,M=U.hexToBase64(E),O="data:image/jpg;base64,"+M,T=new p.TextureLoader(this.manager).load(O);T.colorSpace=p.SRGBColorSpace;const v=new p.MeshBasicMaterial({transparent:!0,map:T});this.meshTextureMaterials[b]=v,S=v;break}}if(S){const w=new p.Box2().setFromPoints(o),x=w.getSize(Wi),E=new p.PlaneGeometry(x.x,x.y),M=new j(q.Mesh);M.geometry=E,M.material=S;const O=w.getCenter(Wi);H.set(O.x,O.y,0),h&&(this.setRTCUserData(M),H.x+=l.x,H.y+=l.y),M.matrix.setPosition(H),M.layers.enableAll(),m.add(M)}return m.children.length>1?m:f}static getOcsMatrix(e){let i=We,s=zn,n=fi;const r=new p.Vector3(0,1,0),a=new p.Vector3(0,0,1);return V.areVectorsClose(e,a)?ue.identity():(n=e.clone().normalize(),!V.areVectorsClose(n,a)&&(Math.abs(n.x)<1/64&&Math.abs(n.y)<1/64?i=r.cross(n).normalize():i=a.cross(n).normalize(),s=n.clone().cross(i).normalize()),ue.set(i.x,i.y,i.z,0,s.x,s.y,s.z,0,n.x,n.y,n.z,0,0,0,0,1))}static getDcs2WcsMatrix(e,i){let s;s1(e)?s=e.viewDirectionFromTarget:s=e.viewDirection,s??(s={x:0,y:0,z:1});const n=e.viewTarget??{x:0,y:0,z:0},r=new p.Vector3(V.roundNumber(s.x,7),V.roundNumber(s.y,7),s.z),a=new p.Vector3(n.x,n.y,n.z),o=e.viewTwistAngle||0;let l,h,d;d=r.clone().normalize(),l=fi.clone().cross(r),l.length()>0?(l.normalize(),h=d.clone().cross(l)):d.z<0?(l=We.clone().negate(),h=zn,d=fi.clone().negate()):(l=We,h=zn,d=fi);const u=new p.Matrix4,f=ue.identity();return f.makeBasis(l,h,d),u.premultiply(f),u.premultiply(ue.identity().compose(a.clone(),new p.Quaternion().setFromAxisAngle(new p.Vector3(0,0,1),p.MathUtils.degToRad(i?o:-o)),new p.Vector3(1,1,1))),u}getViewportMsToPsMatrix(e){const i=e.centerPoint_dcs??{x:0,y:0},s=e.centerPoint??{x:0,y:0,z:0},n=new p.Vector3(i.x,i.y,0),r=new p.Vector3(s.x,s.y,s.z),a=e.viewHeight,o=e.height_paperSpace||1,l=(a||o)/o,h=N.getDcs2WcsMatrix(e,this.angDir),d=new p.Matrix4;d.setPosition(wa.clone().sub(r));const u=Ma.identity();u.scale(H.set(l,l,l));const f=it.identity().setPosition(wa.clone().sub(r));u.premultiply(f.clone().invert()).multiply(f),d.multiply(u);const m=ue.identity();m.setPosition(n),h.multiply(m);const b=ue.identity();return d.invert().multiply(b).multiply(h.invert())}loadViewport(e,i,s){if(e.viewportId+""=="1"){e.psBBox=new p.Box3,e.msToPsMatrix=new p.Matrix4;return}const n=e.centerPoint;if(!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)){e.psBBox=new p.Box3,e.msToPsMatrix=new p.Matrix4;return}const r=e.width_paperSpace/2,a=e.height_paperSpace/2,o=[new p.Vector3(n.x-r,n.y-a,0),new p.Vector3(n.x-r,n.y+a,0),new p.Vector3(n.x+r,n.y+a,0),new p.Vector3(n.x+r,n.y-a,0)];o.push(o[0]),e.psBBox=new p.Box3().setFromPoints([o[0],o[2]]),e.msToPsMatrix=this.getViewportMsToPsMatrix(e);let l=!1;const h=new p.Vector3;this.enableRTC&&(l=G.checkAndRebasePositionsOnRTC(o,h));const d=new p.BufferGeometry().setFromPoints(o),u=new j(q.Line);u.geometry=d,u.material=ge,u.userData.entityType=e.type,u.layers.enableAll(),l&&(this.setRTCUserData(u),u.matrix.setPosition(h.x,h.y,0));const f=e.psBBox.clone();f.applyMatrix4(e.msToPsMatrix.clone().invert()),f.min.z=0,f.max.z=0;const m=[f.min,new p.Vector3(f.min.x,f.max.y,0),f.max,new p.Vector3(f.max.x,f.min.y,0)];m.push(m[0]);let b=!1;const y=new p.Vector3;this.enableRTC&&(b=G.checkAndRebasePositionsOnRTC(m,y));const S=new p.BufferGeometry().setFromPoints(m),w=new j(q.Line);w.geometry=S,w.material=ge,w.userData.entityType=e.type,w.userData.inPaperSpace=[],w.layers.enableAll(),b&&(this.setRTCUserData(w),w.matrix.setPosition(y.x,y.y,0));const x=new j;return x.add(u),x.add(w),u}getColor(e,i,s){if(this.compareContext)return ot.ENTITY_COLOR_NO_CHANGE;if(this.overrideColor!=null)return this.overrideColor;const n=e;if(n&&n.isGradientColor){const r=n.gradientColors;if(r&&r.length>=2){if(r[0]!==r[1]){const a="[Dxf] Gradient colors are not supported for hatch '"+e.handle+"', will use the first color!";P.warn(a)}return r[0]}}if(e.isTrueColor||e.colorIndex>0&&e.colorIndex<256)return e.color;if(e.colorIndex===0)return s?this.getColor(s,i):i.tables?.layer?.layers[0].color;if(e.colorIndex===256){const r=i.tables?.layer?.layers,a=r&&r[e.layer],o=r&&s&&r[s.layer];let l=Lt;return a&&a.name!=="0"?l=a.color:o?l=o.color:a?l=a.color:r&&r[0].color&&(l=r[0].color),l}return P.warn("[Dxf] Unknown colorIndex"),Lt}getLineType(e,i,s){if(s&&s.type==="DIMENSION")return this.getLineType(s,i);if(e.lineType!==Cr&&e.lineType!==hs)return e.lineType;if(e.lineType===hs)return s?this.getLineType(s,i):e.lineType;const n=i.tables?.layer?.layers,r=i1;if(e.layer!=="0"){const a=n&&n[e.layer];if(a)return a.lineType}else if(s){const a=n&&n[s.layer];if(a)return a.lineType}return r}getLayerName(e,i,s){const n=h=>{r&&h&&!r[e.layer]&&(console.warn("[Dxf] Failed to find layer object for '"+h+"', adding a default one."),r[h]={name:h,handle:"",colorIndex:256,lineType:"",visible:!0})},r=i.tables?.layer?.layers;n(e.layer);const a=r&&r[e.layer];n(s?.layer);const o=r&&s&&r[s.layer];let l=a?.name||"";return a&&a.name==="0"&&o&&(l=o.name),l}setMaterial(e,i,s,n){const r=e;if(!r.geometry||(this.setRenderOrderByObjectType(e),i.type==="OLE2FRAME"))return;if(i.type==="MTEXT"){e.renderOrder=xe.Text;return}if(i.type==="HATCH"){Wi.set(0,0),this.setHatchMaterial(e,i,s,Wi,n);return}if(i.type==="IMAGE")return;let a;const o=this.getColor(i,s,n);if(i.type==="LWPOLYLINE"&&(r.isMesh?(a=this.getMeshBasicMaterial(o),e.renderOrder=xe.LineWithWidth):e.userData.isOutline&&(a=this.getLineBasicMaterial(o),e.renderOrder=xe.LineWithPattern),a)){r.material=a;return}if(i.type==="SOLID")a=this.getMeshBasicMaterial(o);else if(i.type==="TEXT"||i.type==="ATTDEF"||i.type==="ATTRIB")a=this.getLineBasicMaterial(o),e.renderOrder=xe.Text;else if(i.type==="LEADER"||i.type==="MULTILEADER"||i.type==="VIEWPORT")a=this.getLineBasicMaterial(o);else if(i.type==="POINT")a=this.getPointsMaterial(o);else{if(e.material instanceof p.PointsMaterial){a=this.getPointsMaterial(o),r.material=a;return}const l=s.tables?.lineType?.lineTypes,h=l&&l[this.getLineType(i,s,n)];if(h&&h.pattern&&h.pattern.length!==0){const d=i.lineTypeScale||1;a=this.getLineShaderMaterial(h,o,d),e.renderOrder=xe.LineWithPattern}else a=this.getLineBasicMaterial(o)}r.material=a}setHatchMaterial(e,i,s,n,r){const a=e;if(!a.geometry)return;const o=this.getColor(i,s,r);if(a.type===q.Line||a.type===q.LineSegment){a.material=this.getLineBasicMaterial(o);return}let l=xe.Mesh,h;if(i.solidFill)h=this.getMeshBasicMaterial(o);else{if(a.material instanceof p.ShaderMaterial){h=a.material;const d=new p.Color(o);!a.material.uniforms.u_color.value.equals(d)&&(h=a.material.clone(),N.updateMaterialUniforms(h),h.uniforms.u_color.value.set(o))}else h=this.getHatchShaderMaterial(i,o,n);l=xe.MeshWithPattern}!h&&(h=this.getMeshBasicMaterial(o),l=xe.Mesh),a.material=h,a.renderOrder=l}setRenderOrderByObjectType(e){const i=e;let s=0;i.isMesh?s=xe.Mesh:i.isLine?s=xe.Line:i.isPoints&&(s=xe.Point),e.renderOrder=s}getPointsMaterial(e){return!this.pointsMaterials[e]&&(this.pointsMaterials[e]=new p.PointsMaterial({size:.2,color:e})),this.pointsMaterials[e]}getLineBasicMaterial(e){return!this.lineBasicMaterials[e]&&(this.lineBasicMaterials[e]=new p.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,i,s){const n=e.name+"_"+i+"_"+s;if(!this.lineShaderMaterials[n]){const r=this.getLineTypeScales(),a=r.ltScale*r.celtScale*s;this.lineShaderMaterials[n]=Mo.createLineShaderMaterial(e.pattern,i,a,N.ViewportScaleUniform,N.CameraZoomUniform)}return this.lineShaderMaterials[n]}getMeshBasicMaterial(e){return!this.meshBasicMaterials[e]&&(this.meshBasicMaterials[e]=new p.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getHatchShaderMaterial(e,i,s){if(!e.patternLines||e.patternLines.length<1)return;const n=this.findMatchedHatchShaderMaterial(e,i);if(n)return n;const r=.005,a=.05;let o=2;e.patternLines.forEach(f=>{o=Math.max(f.dashPattern.length,o)});let l=0;const h=[],d=new p.Vector2;for(const f of e.patternLines){const m=new p.Vector2(f.origin.x,f.origin.y).sub(s).rotateAround(d,-p.MathUtils.degToRad(e.patternAngle)),b=new p.Vector2(f.delta.x,f.delta.y).rotateAround(d,-p.MathUtils.degToRad(f.angle));if(b.y===0)return P.warn("[Dxf] delta.y is equal to zero !"),void 0;const y=f.dashPattern.length;let S=!0,w=0;for(let v=0;v<y;++v){const C=f.dashPattern[v];C>0&&(S=!1),w+=Math.abs(C)}const x=S?a:r,E=[],M=[];let O=0;M[0]=O;for(let v=0;v<y;++v)E[v]=f.dashPattern[v],E[v]===0&&(E[v]=x*w),O+=Math.abs(E[v]),M[v+1]=O;for(let v=y;v<o;++v)E[v]=0;for(let v=M.length;v<o+1;++v)M[v]=O;const T={origin:m,delta:b,angle:f.angle-e.patternAngle,pattern:E,patternSum:M,patternLength:O};if(l+=4,l+=o,l+=o+1,l>N.MaxFragmentUniforms){P.warn("[Dxf] There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}h.push(T)}const u=To(h,e.patternAngle,N.CameraZoomUniform,new p.Color(i),this.overrideHatchPatternLineThickness);return u.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:i,material:u}),u}getDivision(e,i,s){let n=Math.round(5e4/this.entityCount);n=Math.max(n,2),n=Math.min(n,10);const r=n*5;let o=n*2;if(this.averageCurveSize){const d=Math.pow(s/this.averageCurveSize,.5);o*=d,o=Math.max(o,n),o=Math.min(o,r)}let l=i-e;l<0&&(l+=Math.PI*2),o=Math.ceil(o*(l/Math.PI));let h=8;return l<.087?h=2:l<.174?h=3:l<.52?h=4:l<1.57?h=5:l<3.14?h=6:l<4.71&&(h=7),o=Math.max(o,h),this.averageCurveSize=(this.averageCurveSize*this.curveCount+s)/(this.curveCount+1),this.curveCount++,Math.max(o,12)}getBSplineInterpolationsPerSplineSegment(e,i){let s=1;this.averageCurveSize&&(s=Math.pow(i/this.averageCurveSize,.5),s=Math.max(s,.5),s=Math.min(s,2)),this.averageCurveSize=(this.averageCurveSize*this.curveCount+i)/(this.curveCount+1),this.curveCount++;let n=e*2*s;if(e>20){const r=Math.log10(e);n/=r}return n}async setDxfDataToIndexedDb(e,i){const s={dxfDataId:e,dxf:i};return new Promise((n,r)=>{ln.instance().add(s,()=>{P.info("[Dxf] Saved '"+e+"' to indexedDb"),n()},a=>{r(a)})})}async getDxfDataFromIndexedDb(e){return new Promise((i,s)=>{ln.instance().query(e,n=>{n&&n.length>0&&i(n[0].dxf),i(void 0)},()=>s())})}buildContainHierarchyTree(e,i,s){const n=new Map,r=s.length;for(let o=0;o<r;o++)n.set(s[o],{index:s[o],children:[]});const a={index:-1,children:[]};for(let o=0;o<r;o++){const l=s[o],h=e[l],d=i[l];let u=o+1;for(;u<r;u++){const f=s[u],m=e[f];if(i[f].containsBox(d)&&G.isPointInPolygon(h[U.generateRandomInt(0,h.length-1)],m)){n.get(f)?.children.push(n.get(l));break}}u===r&&a.children.push(n.get(l))}return a}buildHatchGeometry(e,i,s){if(i.children.length===0)return;const n=[],r=new Map;i.children.forEach(l=>{l.children.length===0?n.push(l.index):r.set(l.index,l.children.map(h=>h.index))});const a=l=>{try{const h=new p.ShapeGeometry(l);h.hasAttribute("uv")&&h.deleteAttribute("uv"),h.hasAttribute("normal")&&h.deleteAttribute("normal"),s.push(h)}catch{P.warn("[Dxf] triangulate shape error: "+l.getPoints().map(d=>d.toArray()).toString())}};n.forEach(l=>{const h=e[l];if(h.length===0)return;const d=new p.Shape(h);a(d)});const o=l=>l.map(h=>h.toArray());for(const l of r){const h=new p.Shape(e[l[0]]);let d={regions:[],inverted:!1};const u=this.findIntersectHole(e,l[1]);u.forEach(m=>{let b={regions:[],inverted:!1};try{m.forEach((y,S)=>{if(Yt.epsilon(V.getVector2RelativeEps(e[y][0]),1e-6),S===0)b=Yt.segments({regions:[o(e[y])],inverted:!1});else{const w=Yt.segments({regions:[o(e[y])],inverted:!1}),x=Yt.combine(b,w);d=Yt.polygon(Yt.selectUnion(x)),d.regions.length>0?d.regions.forEach(E=>{if(E.length===0)return;const M=E.map(O=>new p.Vector2(O[0],O[1]));h.holes.push(new p.Path(M))}):P.warn("[Dxf] mergedHoles.regions is empty")}})}catch(y){P.warn("[Dxf] polybooljs has error: "+y+", epsilon is "+Yt.epsilon())}});const f=u.flat(2);for(let m=0;m<l[1].length;m++){const b=l[1][m];!f.includes(b)&&h.holes.push(new p.Path(e[b]))}a(h)}i.children.forEach(l=>{l.children.forEach(h=>{this.buildHatchGeometry(e,h,s)})})}findIntersectHole(e,i){const s=i.length,n=[];for(let r=0;r<s;r++){const a=e[i[r]];let o=!1;const l=[];for(let h=r+1;h<s;h++){const d=e[i[h]];G.arePolygonsIntersect(a,d)&&(o=!0,l.push(i[h]))}o&&(l.push(i[r]),n.push(l))}return n}checkAndRebasePolygonsOnRTC(e,i){if(!this.enableRTC||e.length===0)return!1;let s=0;e.forEach(r=>{r.forEach(a=>{i.add(a),s++})}),i.divideScalar(s);let n=!1;if(this.enableRTC&&G.shouldRebasePositionOnRTC(i)){n=!0;for(let r=0;r<e.length;r++){const a=e[r];for(let o=0;o<a.length;o++){const l=a[o].x-i.x,h=a[o].y-i.y;a[o]=new p.Vector2(l,h)}}}else i.set(0,0);return n}setRTCUserData(e){e.userData.relativeToCenter=!0,this.statsInfo.rebasedEntityCount++}IsfilteredByPathTypeFlag(e){return e<0}findSpatialFilterByHandle(e,i){const s=i.objects.DICTIONARY;if(!s)return;if(!this.dictionaryOwnerHandleAndSpatialFilterHandlesCache){this.dictionaryOwnerHandleAndSpatialFilterHandlesCache={};for(const r of s){const a=r;let o="";for(const l in a.entries)if(a.entries[l]==="ACAD_FILTER"){o=l;break}o&&(this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[r.ownerHandle]&&P.warn("[Dxf] Why this.dictionaryObjectsCache[obj.ownerHandle] already exist?",r.ownerHandle),this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[r.ownerHandle]=o)}}const n=this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[e];if(n){if(!this.spatialFiltersCache){this.spatialFiltersCache={};const r=i.objects.SPATIAL_FILTER||[];for(const a of r){const o=a;o.numberOfPointsOnClipBoundary<2||(this.spatialFiltersCache[o.ownerHandle]&&P.warn("[Dxf] Why this.spatialFiltersCache[spatialFilterObj.ownerHandle] already exist?",n),this.spatialFiltersCache[o.ownerHandle]=o)}}return this.spatialFiltersCache[n]}}initRenderOrderInfo(e){const i=new Set,s=e.objects.DICTIONARY;for(const r of s){const a=r;Object.keys(a.entries).forEach(o=>{a.entries[o]&&a.entries[o]==="ACAD_SORTENTS"&&i.add(o)})}if(i.size===0)return;const n=e.objects.SORTENTSTABLE;if(n)for(let r=0;r<n.length;++r){const a=n[r];if(i.has(a.handle)){for(let o=0;o<a.sortEntsObject.entityHandles.length;++o){const l=a.sortEntsObject.entityHandles[o];l.length===2&&!this.entityHandlesWithRenderOrder[l[0]]?this.entityHandlesWithRenderOrder[l[0]]=l[1]:P.warn("[Dxf] Failed to handle sortEntsTable: "+a.handle+".")}break}}}findMatchedHatchShaderMaterial(e,i){const s=e.patternLines;if(!s||s.length<1)return;const n=(h,d)=>Math.abs(h-d)<1e-5,r=(h,d)=>{if(h.length!==d.length)return!1;for(let u=0;u<h.length;++u)if(!n(h[u],d[u]))return!1;return!0},a=(h,d)=>n(h.angle,d.angle)&&n(h.delta.x,d.delta.x)&&n(h.delta.y,d.delta.y)&&n(h.origin.x,d.origin.x)&&n(h.origin.y,d.origin.y)&&r(h.dashPattern,d.dashPattern),o=(h,d)=>{if(h.length!==d.length)return!1;for(let u=0;u<h.length;++u)if(!a(h[u],d[u]))return!1;return!0};return this.hatchShaderMaterials.find(h=>h.color===i&&h.patternAngle===e.patternAngle&&o(h.patternLines,s))?.material}getLayout(e,i){if(!this.blockRecordsCache){this.blockRecordsCache={};const r=this.blockRecordsCache,a=e.tables?.blockRecord?.blockRecords;a&&Object.values(a).forEach(o=>{r[o.handle]=o.layoutHandle})}const s=this.blockRecordsCache[i.ownerHandle];if(s){const r=e.objects.LAYOUT,a=r.find(o=>o.handle===s);if(a)return a}if(!this.entitiesCache){this.entitiesCache={};const r=this.entitiesCache;Object.values(e.entities).forEach(a=>{r[a.handle]=a})}const n=this.entitiesCache[i.ownerHandle];return n?this.getLayout(e,n):e.objects.LAYOUT.find(r=>r.layoutName===N.MODEL_LAYOUT_NAME)}getLayerVisible(e,i){const s=e.tables?.layer?.layers;return s&&s[i]?.visible}getLayerFrozen(e,i){const s=e.tables?.layer?.layers;return s&&s[i.layer]?.frozen}cloneMaterialsForSpatialFilter(e){const i=new Map,s=n=>{let r;if(Array.isArray(n)){const a=[];r=a,n.forEach(o=>{if(i.has(o.id))a.push(i.get(o.id));else{const l=o.clone();N.updateMaterialUniforms(l),i.set(o.id,l),a.push(l)}})}else n&&(i.has(n.id)?r=i.get(n.id):(r=n.clone(),N.updateMaterialUniforms(r),i.set(n.id,r)));return r};e.traverse(n=>{n.material&&(n.material=s(n.material))})}getLineTypeScales(){const e={ltScale:1,celtScale:1};return this.header&&(e.ltScale=this.header.$LTSCALE||1,e.celtScale=this.header.$CELTSCALE||1),e}static getDxfUnits(e){switch(e||0){case 0:return Ke.Unitless;case 1:return Ke.Inches;case 2:return Ke.Feet;case 4:return Ke.Millimeters;case 5:return Ke.Centimeters;case 6:return Ke.Meters;default:P.warn("[Dxf] Unsupported $INSUNITS '"+e+"'");break}return Ke.Unitless}static computeLineDistance(e){const i=e.isLineSegments===!0;let s=e.geometry;const n=e.matrixWorld;if(s.index&&(P.debug("[Dxf] Line with id '"+e.id+"' contains index buffer, going to convert it to non-indexed."),s=G.convertGeometryWithIndexedToNonIndexed(s),e.userData.batches&&e.userData.batches.length>0)){P.debug("[Dxf] This line has been merged!");let r=0;e.userData.batches.forEach(a=>{a.positionStart=r,a.positionCount=a.indexCount,a.indexStart=0,a.indexCount=0,r+=a.positionCount})}if(s.index===null){const r=s.attributes.position;if(!r||r.count===0)return;const a=[];if(i)for(let o=0,l=r.count;o<l;o+=2)H.fromBufferAttribute(r,o).applyMatrix4(n),$.fromBufferAttribute(r,o+1).applyMatrix4(n),a[o]=o===0?0:a[o-1],a[o+1]=a[o]+H.distanceTo($);else{a[0]=0;for(let o=1,l=r.count;o<l;o++)H.fromBufferAttribute(r,o-1).applyMatrix4(n),$.fromBufferAttribute(r,o).applyMatrix4(n),a[o]=a[o-1],a[o]+=H.distanceTo($)}s.setAttribute("lineDistance",new p.Float32BufferAttribute(a,1)),e.geometry=s}else P.warn("[Dxf] computeLineDistances only possible with non-indexed BufferGeometry.")}static computeLineDistances(e){const i=Date.now();e.traverse(s=>{const n=s;n.isLine&&n.material instanceof p.ShaderMaterial&&N.computeLineDistance(n)}),P.debug("[Dxf] Computed line distances in "+(Date.now()-i)/1e3+"s")}static mergeDxfObjects(e){const i=Date.now(),s={},n={},r=15e3;let a=0,o=0;const l=()=>{const d=Date.now();for(const u in s){const f=s[u];N.removeEmptyObjectsFromRemovingMarkedObjects2(f.children,f.object),f.children=[]}a=0,o+=Date.now()-d};for(const d in e.layersAndObjects){const u=e.layersAndObjects[d];if(u.length<=1)continue;const f=Date.now(),m={},b=[];for(const y of u){if(y.userData.isSnapObject){b.push(y);continue}let S,w=y;for(;w;){if(w.userData.isLayoutLevelObject){S=w;break}w=w.parent}if(!S)continue;const x=S.name;!m[x]&&(m[x]={object:S,children:[]}),m[x].children.push(y)}for(const y in m){const S=m[y],w=Mt.deepMerge(S.children,S.object,!1,!1,!0),x=w.added,E=w.removed;!s[y]&&(s[y]={object:S.object,children:[]}),!n[y]&&(n[y]={object:S.object,children:[]});const M=E.length>r;if(M){const O=Date.now();N.removeEmptyObjectsFromRemovingMarkedObjects2(E,S.object),o+=Date.now()-O}else a+=E.length;if(E.length===S.children.length)!M&&E.forEach(O=>{s[y].children.push(O)});else{let O=E;E.length>=100&&(O=new Set(E));const T=v=>Array.isArray(O)?O.indexOf(v)>=0:O.has(v);for(let v=0;v<S.children.length;v++){const C=S.children[v];T(C)?!M&&s[y].children.push(C):b.push(C)}}for(let O=0;O<x.length;O++){const T=x[O];b.push(T),n[y].children.push(T)}a>r&&l()}e.layersAndObjects[d]=b,P.debug("[Dxf] Merged layer '"+d+"' in "+(Date.now()-f)/1e3+"s")}a>0&&l();for(const d in n){const u=n[d];!e.root.children.find(m=>m.name===d)&&e.root.add(u.object),u.children.forEach(m=>{u.object.add(m)}),u.children=[]}P.debug("[Dxf] MergeUtils.deepMerge took "+pe.MergeInfo.elapsedTime/1e3+"s"),P.debug("[Dxf] The remove operation of deep merge took "+o/1e3+"s"),P.debug("[Dxf] Deep merge totally took "+(Date.now()-i)/1e3+"s");const h=pe.MergeInfo;P.debug("[Dxf] Totally merged "+h.removedObjects+" objects to "+h.mergedMeshes+"meshes, "+h.mergedLines+"lines, "+h.mergedPoints+"points, "+(h.mergedUnknownTypeObjects?h.mergedUnknownTypeObjects+" unknown type,":" ")+" ")}static async merge(e,i){const s=U.getUpdateProgressFuncAsync(i),n={};e.objects.LAYOUT.forEach(y=>{const S=y;n[S.layoutName]=S,S.directAssociatedLeafObjectSet?.clear()});const r=Date.now(),a={},o={},l=15e3;let h=0,d=0;const u=()=>{const y=Date.now();for(const S in a){const w=a[S];N.removeEmptyObjectsFromRemovingMarkedObjects(w.children,w.object),w.children=[]}h=0,d+=Date.now()-y},f=Object.keys(e.layersAndThreejsObjects).length;let m=0;for(const y in e.layersAndThreejsObjects){const S=e.layersAndThreejsObjects[y];if(S.length<=1){await s(++m/f*100);continue}const w=Date.now(),x={},E=[];for(const T of S){if(T.userData.isSnapObject){E.push(T);continue}let v,C=T;for(;C;){if(C.userData.isLayoutLevelObject){v=C;break}C=C.parent}if(!v)continue;const _=v.name;!x[_]&&(x[_]={object:v,children:[]}),x[_].children.push(T)}const M=Object.keys(x).length;let O=0;for(const T in x){let v;if(T!==N.MODEL_LAYOUT_NAME){const D=n[T];!D.directAssociatedLeafObjectSet&&(D.directAssociatedLeafObjectSet=new Set),v=D.directAssociatedLeafObjectSet}const C=x[T],_=pe.deepMerge(C.children,C.object,!1,!1,!0),A=_.added,I=_.removed;!a[T]&&(a[T]={object:C.object,children:[]}),!o[T]&&(o[T]={object:C.object,children:[]});const B=I.length>l;if(B){const D=Date.now();N.removeEmptyObjectsFromRemovingMarkedObjects(I,C.object),d+=Date.now()-D}else h+=I.length;if(I.length===C.children.length)!B&&I.forEach(D=>{a[T].children.push(D)});else{let D=I;I.length>=100&&(D=new Set(I));const k=z=>Array.isArray(D)?D.indexOf(z)>=0:D.has(z);for(let z=0;z<C.children.length;z++){const se=C.children[z];k(se)?!B&&a[T].children.push(se):(E.push(se),v&&v.add(se))}}for(let D=0;D<A.length;D++){const k=A[D];Q.setSharedVariablesOfObject(k),E.push(k),o[T].children.push(k),v&&v.add(k)}h>l&&u(),await s((m+ ++O/M)/f*100)}await s(++m/f*100),e.layersAndThreejsObjects[y]=E,P.debug("[Dxf] Merged layer '"+y+"' in "+(Date.now()-w)/1e3+"s")}h>0&&u();for(const y in o){const S=o[y],w=e.threejsObject.children.find(x=>x.name===y);if(w){const x=w.children.find(E=>E.name===N.SNAP_GROUP_NAME);if(x&&y!==N.MODEL_LAYOUT_NAME){const E=n[y];!E.directAssociatedLeafObjectSet&&(E.directAssociatedLeafObjectSet=new Set),x.children.forEach(M=>E.directAssociatedLeafObjectSet?.add(M))}}!w&&e.threejsObject.add(S.object),S.children.forEach(x=>{!x.visible&&(x.userData.layerVisible=!1),S.object.add(x),x.updateWorldMatrix(!1,!1)}),S.children=[]}P.debug("[Dxf] MergeUtils.deepMerge took "+pe.MergeInfo.elapsedTime/1e3+"s"),P.debug("[Dxf] The remove operation of deep merge took "+d/1e3+"s"),P.debug("[Dxf] Deep merge totally took "+(Date.now()-r)/1e3+"s");const b=pe.MergeInfo;P.debug("[Dxf] Totally merged "+b.removedObjects+" objects to "+b.mergedMeshes+"meshes, "+b.mergedLines+"lines, "+b.mergedPoints+"points, "+(b.mergedUnknownTypeObjects?b.mergedUnknownTypeObjects+" unknown type,":" ")+" "),s(100)}printStatsInfo(){const e=this.entityTypesAndTimes;for(const n in e)e[n].averageTime=e[n].totalTime/e[n].createCount;P.debug("[Dxf] Entity types and took how much time in ms:",e),P.debug("[Dxf] Entity types and mesh count:",this.statsInfo.entityTypesAndMeshCount);let i=0;if(Object.values(this.statsInfo.entityTypesAndMeshCount).forEach(n=>{i+=n}),this.enableRTC&&P.debug("[Dxf] Totally rebased "+this.statsInfo.rebasedEntityCount+"(out of "+i+") entities"),this.enableMerge){const n=pe.MergeInfo;P.debug("[Dxf] Inner merged "+n.removedObjects+" objects to "+n.mergedMeshes+"meshes, "+n.mergedLines+"lines, "+n.mergedPoints+"points, "+(n.mergedUnknownTypeObjects?n.mergedUnknownTypeObjects+" unknown type,":" ")+"in "+n.elapsedTime/1e3+"s")}const s=(n,r,...a)=>{Object.keys(r).length>0};s("[Dxf] Unsupported entity types and count:",this.statsInfo.unsupportedEntityTypes),s("[Dxf] Unsupported text style names and count:",this.statsInfo.unsupportedTextStyles,". Will use a default style."),s("[Dxf] Unsupported hatch pattern names and count:",this.statsInfo.unsupportedHatchPatterns,". Filling in solid lines instead."),this.statsInfo.unsupportedPolylineCount&&P.warn("[Dxf] Unsupported polyline (with both width and linetype) count: "+this.statsInfo.unsupportedPolylineCount+", linetype will be ignored."),s("[Dxf] Ignored invisible entity types and count:",this.statsInfo.invisibleEntities),s("[Dxf] Ignored frozen layers and entity count:",this.statsInfo.ignoredFrozenLayersAndEntityCount),s("[Dxf] Ignored inserts and count (may because they don't contain anything):",this.statsInfo.ignoredInserts),this.ignorePaperSpace&&s("[Dxf] Ignored paper space entity count:",this.statsInfo.ignoredPaperSpaceEntityTypesAndCount),this.font&&s("[Dxf] Unsupported chars and count:",this.font.getUnsupportedChar())}static statLayoutAndLayerObjects(e){const i=new WeakSet;let s=0;for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&(s++,i.has(l)?console.warn(l):i.add(l))});const n=new WeakSet;let r=0;if(e.threejsObject.traverse(a=>{a.geometry&&(r++,n.has(a)?console.warn(a):n.add(a))}),s!=r)for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&!n.has(l)&&console.warn(l)});P.info("[Dxf] The count of layer objects is "+s+",The count of layout objects is "+r+" ")}static removeEmptyObjectsFromRemovingMarkedObjects(e,i){if(e.length===0)return;const s=n=>{const r=[];for(const a of n){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&r.push(o))}r.length>0&&s(r)};s(e),this.removeEmptyObjectsFromMark(i)}static removeEmptyObjectsFromMark(e){if(e.userData.validCount===0||Q.isEmptyObject(e))return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark(e.children[i])&&++i;return!1}static removeEmptyObjectsFromRemovingMarkedObjects2(e,i){if(e.length===0)return;const s=n=>{const r=[];for(const a of n){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&r.push(o))}r.length>0&&s(r)};s(e),this.removeEmptyObjectsFromMark2(i)}static removeEmptyObjectsFromMark2(e){if(e.userData.validCount===0||e.type===q.Object&&e.children.length===0)return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark2(e.children[i])&&++i;return!1}};g(N,"MODEL_LAYOUT_NAME","Model"),g(N,"SNAP_GROUP_NAME","InvisibleObjectGroupForOSnap"),g(N,"SHOW_SNAP_OBJECT",!1),g(N,"CameraZoomUniform",{value:1}),g(N,"ViewportScaleUniform",{value:1}),g(N,"TransformMatrixUniform",{value:new p.Matrix4}),g(N,"ResolutionUniform",{value:new p.Vector2}),g(N,"LOADLLDATA",!1),g(N,"MaxFragmentUniforms",1024);let Z=N;class fr extends Ht{constructor(e){super();g(this,"viewer");g(this,"overlayRender");g(this,"drawableList");this.drawableList=new ps("compare"),this.viewer=e,this.overlayRender=this.viewer.getOverlayRender(),this.overlayRender?.addDrawableList(this.drawableList)}drawCompareDrawable(e){const i=[],s=[],n=[];for(const l of Object.values(e)){const h=l.box;h&&(l.type===je.Added?i.push(h):l.type===je.Removed?s.push(h):n.push(h))}const r=G.mergeBBoxes(i),a=G.mergeBBoxes(s),o=G.mergeBBoxes(n);this.drawableList.addDrawable(new bt(U.guid(),r,[.1,.9,.2,1])),this.drawableList.addDrawable(new bt(U.guid(),a,[1,.15,.15,1])),this.drawableList.addDrawable(new bt(U.guid(),o,[1,.85,.1,1])),this.viewer.enableRender()}setCompareDrawableVisible(e){this.drawableList.getDrawables().forEach(i=>i.visible=e),this.viewer.enableRender()}}class mn{}const mi=new p.Matrix4,jn=new p.Box3;class Di extends mn{constructor(e){super();g(this,"modelId");g(this,"modelData");g(this,"modelObject");g(this,"bbox");this.modelData=e,this.modelId=e.modelId,this.modelObject=e.dxfData?.threejsObject||e.pdfData?.threejsObject,this.modelObject.name=this.modelId,this.modelObject.userData.modelId=this.modelId}get pdfData(){return this.modelData.pdfData}get dxfData(){return this.modelData.dxfData}get msTransformMatrix(){return this.modelData.msTransformMatrix}set msTransformMatrix(e){this.modelData.msTransformMatrix=e}get loadedEntityCount(){return this.dxfData?.loadedEntityCount||this.pdfData?.loadedEntityCount||0}get header(){return this.dxfData?.header}get viewports(){return this.dxfData?.tables.viewport.viewports}get layers(){const e=this.dxfData||this.pdfData;return e.tables?.layer.layers||e.layers}get layoutViewportsMap(){return this.dxfData?.layoutViewportsMap}getModelObject(){const e=this.dxfData||this.pdfData;if(!e)throw new Error("Failed to find model by modelId '"+this.modelId+"'!");return e.threejsObject}getBBox(){if(!this.bbox){const e=new p.Box3,i=this.getModelObject();e.setFromObject(i),this.bbox=e}return this.bbox}getUnits(){if(!this.dxfData)return Ke.Unitless;const e=this.dxfData.header;if(!e)return P.warn("DxfData or its header is undefined!"),Ke.Unitless;const i=e.$INSUNITS;return Z.getDxfUnits(i)}getModelSpaceExtent(){const e=this.header,i=new p.Vector3,s=new p.Vector3;if(!e){P.error("Header is undefined in "+this.modelId+"!");return}const n=this.viewports;let r=e.$EXTMIN,a=e.$EXTMAX;const o=e.$ANGDIR;if(n&&n.length>0)for(let l=0;l<n.length;l++){const h=n[l];if(h.name.toLocaleUpperCase()==="*ACTIVE"){const{center:d,viewHeight:u,aspectRatio:f}=h,m=u*f,b=Z.getDcs2WcsMatrix(h,o),y=new p.Vector3(d.x,d.y,0);y.applyMatrix4(b),r={x:y.x-m/2,y:y.y-u/2,z:0},a={x:y.x+m/2,y:y.y+u/2,z:0};break}}return i.set(r.x,r.y,r.z),s.set(a.x,a.y,a.z),new p.Box3(i,s)}getLayer(e){if(this.layers)return this.layers[e]}getObjectsByLayer(e){const i=this.dxfData||this.pdfData;return i?.layersAndThreejsObjects&&i.layersAndThreejsObjects[e]}getLayouts(){const e=[];return this.dxfData?.objects.LAYOUT?.forEach(n=>{e.push(n)}),e}getLayoutByName(e){let i;const s=this.getLayouts();for(const n of s)if(n.layoutName===e){i=n;break}return i}getLayoutExtent(e){const i=this.header,s=new p.Vector3,n=new p.Vector3;if(!i)throw new Error("Header is undefined in "+this.modelId+"!");const r=this.getLayoutViewports(e);let a=i.$PEXTMIN,o=i.$PEXTMAX;const l=i.$ANGDIR;if(r&&r.length>0){const h=r.filter(S=>parseInt(S.viewportId)===1);let d;h.length>0?d=h[0]:d=r[0];const{centerPoint:u,width_paperSpace:f,height_paperSpace:m}=d,b=Z.getDcs2WcsMatrix(d,l),y=new p.Vector3(u.x,u.y,0);y.applyMatrix4(b),a={x:y.x-f/2,y:y.y-m/2,z:0},o={x:y.x+f/2,y:y.y+m/2,z:0}}return s.set(a.x,a.y,a.z),n.set(o.x,o.y,o.z),new p.Box3(s,n)}getLayoutViewports(e){const s=this.layoutViewportsMap[e.ownerHandle];return s||[]}getLayoutLevelObject(e){return this.getModelObject()?.children.find(s=>s.name===e)}setVisible(e){const i=this.getModelObject();i.visible=e}setLayerVisible(e,i,s,n){const r=this.getLayer(e);r?r.visible=i:P.warn("[Viewer] Layer '"+e+"' not found from modelData!");const a=this.getObjectsByLayer(e);if(a)for(let o=0;o<a.length;o++){const l=a[o];!(s&&i&&n&&l.userData.visibleMinZoom&&n<l.userData.visibleMinZoom)&&(l.visible=i),(i===!1||l.userData.layerVisible!=null)&&(l.userData.layerVisible=i),l.userData.isSnapObject&&(l.visible?Z.SHOW_SNAP_OBJECT?l.layers.enableAll():l.layers.set(Ue):Z.SHOW_SNAP_OBJECT?l.layers.disableAll():l.layers.disable(Ue))}else P.info("[Viewer] No object found for layer '"+e+"'")}setLayerOpacity(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const n=this.getObjectsByLayer(e);n?n.forEach(r=>{const a=r;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=we.cloneMaterial(a.material));const o=we.cloneMaterial(a.material);we.setMaterialOpacity(o,i),Z.updateMaterialUniforms(o),a.material=o}}):P.info("[Viewer] No object found for layer '"+e+"'")}setLayerColor(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const n=this.getObjectsByLayer(e);n?n.forEach(r=>{const a=r;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=we.cloneMaterial(a.material));const o=we.cloneMaterial(a.material);we.setMaterialColor(o,new p.Color(i)),Z.updateMaterialUniforms(o),a.material=o}}):P.info("[Viewer] No object found for layer '"+e+"'")}resetLayerColor(e){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const s=this.getObjectsByLayer(e);s?s.forEach(n=>{const r=n;r.material&&r.userData.originalMaterial&&(r.material.dispose(),r.material=r.userData.originalMaterial,delete r.userData.originalMaterial)}):P.info("[Viewer] No object found for layer '"+e+"'")}switchTransformMs(e){const i=this.msTransformMatrix;if(mi.identity(),!i||!U.isMatrixValid(i)||i.equals(mi))return;const s=this.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME);s&&(e===Z.MODEL_LAYOUT_NAME?s.applyMatrix4(i):s.applyMatrix4(i.clone().invert()),s.updateMatrixWorld(!0))}activateLayout(e=Z.MODEL_LAYOUT_NAME,i){this.switchTransformMs(e);const s=this.getLayoutByName(e);if(s){if(!i){const n=this.getLayoutViewports(s);let r=[];n.length>0&&(r=n[0].frozenLayerHandles);const a=e!==Z.MODEL_LAYOUT_NAME,o=this.getLayoutLevelObject(e);if(o){const d=[];o.traverse(u=>{this.addSpatialFilterSection(u,this.dxfData);const f=u;if(a&&f.material&&f.geometry){const m=f.userData.layerName;if(this.isLayerFrozenForViewport(m,r))return;d.push(f);let b=-1;const y=this.getObjectsByLayer(m);y&&(b=y.indexOf(f),b>=0&&y.splice(b,1)),b<0&&P.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+m+"', layout '"+e+"'")}}),d.forEach(u=>{u.removeFromParent()})}const l=this.getFilteredViewports(s);P.debug("[Viewer] Active layout:",e,", viewports:",l);const h=Date.now();l.forEach(d=>{this.generateObjectsByViewport(e,d,this)}),P.info("[Viewer] generateObjectsByViewport in "+(Date.now()-h)/1e3+"s")}this.showLayoutObjects(e)}}getFilteredViewports(e){const i=this.getLayoutViewports(e);let s=i.filter(n=>n.viewportId!=="1");return s.length===i.length&&(s=i.filter((n,r)=>r!==0)),s}generateObjectsByViewport(e,i,s,n=[]){const r=i;if(i.viewportId=="1")return;if(!r.psBBox||!r.msToPsMatrix)throw new Error("The bbox or matrix is invalid in the viewport!");Z.TransformMatrixUniform={value:r.msToPsMatrix},Z.ViewportScaleUniform={value:i.viewHeight/i.height_paperSpace};const a=r.psBBox.clone();a.applyMatrix4(r.msToPsMatrix.clone().invert()),a.min.setZ(-1),a.max.setZ(1);const o=this.getObjectsByBoundingBox(a);if(o.length===0)return;const l=r.psBBox.min,h=r.psBBox.max,d=new p.Box2(new p.Vector2(l.x,l.y),new p.Vector2(h.x,h.y)),u=Ft.generateSectionPlanesByBox(d),f=[],m=C=>(!f[C.id]&&(f[C.id]=C.clone(),this.setMaterialUniforms(f[C.id],s.dxfData),Ft.setMaterialSection(f[C.id],u)),f[C.id]),b=C=>{if(Array.isArray(C)){const _=[];return C.forEach(A=>{const I=m(A);_.push(I)}),_}else return m(C)},y=[...n,...i.frozenLayerHandles||[]];let S;if(e!==Z.MODEL_LAYOUT_NAME){const C=r;!C.associatedLeafObjectSet&&(C.associatedLeafObjectSet=new Set),S=C.associatedLeafObjectSet}const w=new p.Group;w.name=r.viewportId;const x=[];if(o.forEach(C=>{const _=C.clone();_.traverse(A=>{const I=A;if(I.material&&I.geometry){const B=I.userData.layerName;if(this.isLayerFrozenForViewport(B,y)){x.push(I);return}I.userData.layerVisible!==!1&&(I.visible=!0),I.material=b(I.material),S?.add(I);const D=s.getObjectsByLayer(B);D?D.push(I):P.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+B+"', layout '"+e+"'")}}),w.add(_)}),S&&S.size===0)return;const E=s.getModelObject();let M=s.getLayoutLevelObject(e);!M&&(M=new p.Group,Q.setSharedVariablesOfObject(M),M.name=e,E?.add(M)),M.add(w),w.applyMatrix4(r.msToPsMatrix),w.updateMatrixWorld(!0);let O=M.children.find(C=>C.name===Z.SNAP_GROUP_NAME);!O&&(O=new p.Group,O.visible=Z.SHOW_SNAP_OBJECT,O.name=Z.SNAP_GROUP_NAME,M.add(O));const T=s.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME),v=T?.children.find(C=>C.name===Z.SNAP_GROUP_NAME);v&&v.traverse(C=>{if(!C.geometry)return;const _=C.userData.layerName;if(this.isLayerFrozenForViewport(_,y)||(jn.makeEmpty(),jn.expandByObject(C),!a.intersectsBox(jn)))return;const A=C.clone();Q.setSharedVariablesOfObject(A);let I=A.parent;const B=mi.identity();for(;I&&I.userData.isLayoutLevelObject!==!0;)B.premultiply(I.matrix),I=I.parent;B.premultiply(r.msToPsMatrix),A.applyMatrix4(B),O?.add(A),S?.add(A);const D=s.getObjectsByLayer(_);D&&D.push(A)}),x.length>0&&Q.removeEmptyObjectsFromRemovingObjects(x,w),w.traverse(C=>{Q.setSharedVariablesOfObject(C),this.addSpatialFilterSection(C,s.dxfData,!0)})}setMaterialUniforms(e,i){e instanceof p.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=Z.CameraZoomUniform),e.uniforms.u_viewportScale&&i?.header.$PSLTSCALE===1&&(e.uniforms.u_viewportScale=Z.ViewportScaleUniform))}getObjectsByBoundingBox(e){const i=[];if(e.isEmpty())return P.warn("[Viewer] bbox is empty !"),i;const s=r=>{const a=Ot.getBoundingBox(r,!1);e.intersectsBox(a)&&i.push(r)},n=this.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME);return n&&n.children.forEach(r=>{r.name!==Z.SNAP_GROUP_NAME&&s(r)}),i}showLayoutObjects(e){let i=0,s=0;const n=this.getModelObject();n.children.forEach(r=>{const a=r.name===e;r.visible=a,a?i++:s++}),P.debug("[Viewer] showLayoutObjects('"+e+"') sets "+i+" layout level object(s) to visible and "+s+" to hidden for model '"+n?.name+"'")}isLayerFrozenForViewport(e,i){const s=this.getLayer(e);return s&&(s.flag&1)>0?!0:!i||i.length<=0?!1:s&&i.indexOf(s.handle)>=0}addSpatialFilterSection(e,i,s=!1){if(e.userData.entityType!=="INSERT"||!e.userData.spatialFilterHandle)return;const n=this.findSpatialFilter(e.userData.spatialFilterHandle,i);if(n){let r=s,a=!1;const o=this.getAnyMaterial(e);if(o&&(o.clippingPlanes&&(r=o.clippingPlanes.length>0),a=o.clipIntersection),r&&a!==n.clipPolylines[0].bReversed){P.warn("[Viewer] Material cannot set clipIntersection to different values at the same time. clipIntersection needs to be set to true here!");return}a=n.clipPolylines[0].bReversed;const l=this.generateSectionsBySpatialFilter(n,e.matrixWorld);if(l){const h=f=>{let m=0;return f.clippingPlanes&&(m=f.clippingPlanes.length),m+l.length>Z.MaxFragmentUniforms},d=new Set,u=f=>{d.has(f.id)||(d.add(f.id),!h(f)&&Ft.setMaterialSection(f,l,r,a))};e.traverse(f=>{const m=f.material;Array.isArray(m)?m.forEach(b=>{u(b)}):m&&u(m)})}}}findSpatialFilter(e,i){const s=i.objects.SPATIAL_FILTER;if(!s)return;let n;for(const r of s)if(r.handle===e){n=r;break}return n}getAnyMaterial(e){const i=e;if(i.material)return Array.isArray(i.material)?i.material[0]:i.material;let s;for(let n=0;n<e.children.length&&(s=this.getAnyMaterial(e.children[n]),!s);n++);return s}generateSectionsBySpatialFilter(e,i){const s=e.clipPolylines[0];if(s.bConcave){P.warn("[Viewer] clipPolyline.bConcave = true is not supported yet in spatialFilter !");return}mi.copy(i),e.localMatrix&&mi.multiply(e.localMatrix);const n=s.polyline,r=[];n.forEach(l=>{const h=l.clone().applyMatrix4(mi);r.push(new p.Vector2(h.x,h.y))});const a=p.ShapeUtils.isClockWise(r),o=!a&&!s.bReversed||a&&s.bReversed;return Ft.generateSectionPlanesByPoints(r,o)}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}highlightObject(e){if(!this.hasObject(e))return;const i=we.clonedHighlightMaterials(e,{depthTest:!1});i&&(e.userData.originalMaterial=e.material,e.material=i)}unHighlightObject(e){if(!this.hasObject(e))return;const i=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(i)?i.forEach(s=>s.dispose()):i instanceof p.Material&&i.dispose()}clearHighlight(){}}class Sr extends mn{constructor(e){super();g(this,"modelId");g(this,"bbox");g(this,"rootObject");g(this,"modelObject");g(this,"highlighUsage");g(this,"transparentUsage");g(this,"edges");g(this,"highlighedObject");this.modelId=e.modelId,this.bbox=e.bbox,this.modelObject=e.object,this.rootObject=new p.Group,this.rootObject.name="rootObject-"+this.modelId,this.rootObject.userData.modelId=this.modelId,this.highlighUsage=new p.Group,this.highlighUsage.name="highlighUsage-"+this.modelId,this.highlighUsage.layers.disable(jt),this.transparentUsage=new p.Group,this.transparentUsage.name="transparentUsage-"+this.modelId,this.transparentUsage.layers.disable(jt),this.rootObject.add(this.modelObject),this.rootObject.add(this.highlighUsage),this.rootObject.add(this.transparentUsage)}setDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&Q.setDoubleSidedMaterialToObject(e)})}revertDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&Q.revertDoubleSidedMaterialToObject(e)})}getModelObject(){return this.rootObject}getBBox(){return!this.bbox&&(this.bbox=new p.Box3,this.bbox.setFromObject(this.getModelObject())),this.bbox}async enableOutline(e,i){e&&!this.edges&&(this.edges=await Q.createOutlines(this.getModelObject(),void 0,i)),this.edges&&this.edges.forEach(s=>s.visible=e)}setObjectColor(e,i){this.hasObject(e)&&e.material.color.set(i)}setObjectOpacity(e,i=.5,s,n){if(this.hasObject(e)){if(e instanceof p.InstancedMesh&&n){const r=this.createInstanceMeshById(e,n,{opacity:i});r.material.opacity*=i,e.userData.instanceId=n,e.userData.transparentedMesh=r,this.transparentUsage.add(r)}else if(pe.isMergedMesh(e)&&s){const r=this.createBatchMeshById(e,s,{opacity:i});r.material.opacity*=i,e.userData.batchId=s,e.userData.transparentedMesh=r,this.transparentUsage.add(r)}else{const r=new p.MeshBasicMaterial({color:0,transparent:!0,opacity:.05});r&&(e.userData.originalMaterial=e.material,e.material=r)}e.userData.isTransparent=!0}}clearObjectOpacity(e,i,s){if(!this.isObjectTransparent(e))return;const{transparentedMesh:n,originalMaterial:r}=e.userData;n&&(this.transparentUsage.remove(n),delete e.userData.batchId,delete e.userData.instanceId,delete e.userData.transparentedMesh),r&&(e.material=r),delete e.userData.isTransparent}isObjectTransparent(e){const{isTransparent:i}=e.userData;return!!i}setOpacity(e=.5){this.getModelObject().traverse(i=>{i instanceof p.Mesh&&this.setObjectOpacity(i,e)})}clearOpacity(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&this.clearObjectOpacity(e)})}highlightObjectById(e,i,s){if(!this.hasObjectWithId(e))return;const n=this.getModelObject().getObjectById(e);n&&this.highlightObject(n,i,s)}highlightObject(e,i,s){if(!this.hasObject(e))return;const n=new p.Color(vr);if(e instanceof p.InstancedMesh&&s){const r=this.createInstanceMeshById(e,s,{depthTest:!1});r.material.opacity=.7,we.setMaterialColor(r.material,n),e.userData.instanceId=s,e.userData.clonedMesh=r,this.highlighUsage.add(r)}else if(pe.isMergedMesh(e)&&i){const r=this.createBatchMeshById(e,i,{depthTest:!1});r.material.opacity=.7,we.setMaterialColor(r.material,n),e.userData.batchId=i,e.userData.clonedMesh=r,this.highlighUsage.add(r)}else{const r=we.clonedHighlightMaterials(e,{depthTest:!1});r&&(e.userData.originalMaterial=e.material,e.material=r)}e.userData.isHighlight=!0,this.highlighedObject=e}clearHighlight(){if(this.highlighedObject&&this.highlighedObject.userData){const e=this.highlighedObject.userData,{clonedMesh:i,originalMaterial:s,instanceId:n,originalMatrix:r}=e;i&&(i.removeFromParent(),i.geometry.dispose(),delete e.clonedMesh),n&&r&&(this.highlighedObject.setMatrixAt(n,r),delete e.instanceId,delete e.originalMatrix),s&&(this.highlighedObject.material=s,delete e.originalMaterial),delete e.isHighlight}this.highlighUsage.clear(),this.highlighedObject=void 0}setObjectVisible(e,i){this.hasObject(e)&&(e.visible=i)}setVisible(e){this.getModelObject().traverse(i=>{i instanceof p.Mesh&&(i.visible=e)})}hasVisibleObject(){let e=0;return this.modelObject.traverseVisible(i=>{i instanceof p.Mesh&&e++}),e>0}hasInvisibleObject(){let e=0;return this.modelObject.traverse(i=>{i instanceof p.Mesh&&e++}),this.modelObject.traverseVisible(i=>{i instanceof p.Mesh&&e--}),e>0}createBatchMeshById(e,i,{opacity:s=1,depthTest:n=!0}){const r=pe.getBatchByBatchId(e,i);let a="[Viewer] Clicked on merged mesh(id: "+e.id+").";a+=" batchId: "+i+", object name: "+r?.name,r?.userData&&(a+=`
|
|
796
|
+
`){u=0,f-=m*.5;continue}let T=this.font?.getCharShape?.(O,i?.fontFile,s);if(!T&&i?.bigFontFile&&(T=this.font?.getCharShape?.(O,i.bigFontFile,s)),!T&&this.font?.fileNames){const v=this.font.fileNames.filter(C=>C!==i?.fontFile);for(let C=v.length-1;C>=0&&(i.fontFile=v[C],i.styleName="Standard",T=this.font?.getCharShape?.(O,i.fontFile,s),!T);C--);}if(T||(T=this.font?.getNotFoundTextShape?.(s)),!!T){if(T.translate(u,f,0),u>o)u=0,f-=m;else{!T.boundingBox&&T.computeBoundingBox();const v=T.boundingBox.getSize(H).x,C=O.charCodeAt(0),A=C>=19968&&C<=40959||C>=13312&&C<=19903||C>=63744&&C<=64255||C>=12288&&C<=12351||C>=65280&&C<=65519||[8216,8217,8220,8221].includes(C)?Math.max(v,s):v+S;E++,u+=A+(E===x?0:l)}d.push(T)}}if(d.length>0){const M=d.filter(T=>T instanceof p.ExtrudeGeometry),O=d.filter(T=>!(T instanceof p.ExtrudeGeometry));if(M.length>0){const T=new j(q.Mesh);T.geometry=Ae.mergeGeometries(M),T.material=pi,h.add(T)}if(O.length>0){const T=new j(q.LineSegment);T.geometry=Ae.mergeGeometries(O),T.material=ge,h.add(T)}}return h}transformTextMesh(e,i){ut.makeEmpty();const s=j.getBox(i,ut),n=s.getSize(H),{halign:r,valign:a}=e;i.matrix.decompose(Vs.position,Vs.quaternion,Vs.scale);const o=Vs,l=e.width||e.textWidth||n.x,h=e.height||e.textHeight||n.y;if(r===void 0&&a===void 0&&e.startPoint||[3,5].includes(r)&&e.startPoint?(o.position.x+=e.startPoint.x,o.position.y+=e.startPoint.y,o.position.z+=e.startPoint.z):e.endPoint&&(o.position.x+=e.endPoint.x,o.position.y+=e.endPoint.y,o.position.z+=e.endPoint.z),r!==3&&r!==5){if(e.rotation){const d=e.rotation*Math.PI/180;o.rotateZ(d)}e.mirrored&2&&o.rotateY(Math.PI),e.mirrored&4&&o.rotateX(Math.PI)}switch(r){case 0:break;case 1:o.translateX(-l/2);break;case 2:o.translateX(-l);break;case 3:if(e.startPoint&&e.endPoint){const d=new p.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),u=new p.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),f=new p.Vector3().subVectors(d,u),m=f.length(),b=m/l;o.scale.multiplyScalar(b);const y=f.clone().cross(We),S=f.angleTo(We);o.rotateZ(y.z>0?Math.PI-S:S-Math.PI),(e.mirrored===2||e.mirrored===4)&&o.rotateX(Math.PI)}break;case 4:o.translateX(-l/2),o.translateY(-h/12);break;case 5:if(e.startPoint&&e.endPoint){const d=new p.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),u=new p.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),f=new p.Vector3().subVectors(d,u),m=f.length(),b=m/l,S=(e.text||"").length;if(S>1){const E=(m-l)/(S-1);o.userData.letterSpacing=E}else b<3&&o.scale.setX(b);const w=f.clone().cross(We),x=f.angleTo(We);o.rotateZ(w.z>0?Math.PI-x:x-Math.PI)}break}switch(a){case 0:break;case 1:break;case 2:o.translateY(-h/2);break;case 3:o.translateY(-h);break}return o.position.z=0,o.updateMatrix(),i.matrix.copy(o.matrix),i}loadText(e,i,s){const n=e.text;if(!n)return;if(!this.font){P.info("[Dxf] Font file not set, ignoring text entity.");return}const r=this.getTextStyle(i,e),o=sn(n,{encoding:this.getTextEncoding(r)}).map(d=>d.text).join(""),l=this.getTextMesh(o,e.textHeight,r,e);if(!l||l.children.length===0)return;this.transformTextMesh(e,l),H.set(l.matrix.elements[12],l.matrix.elements[13],l.matrix.elements[14]);const h=G.shouldRebasePositionOnRTC(H);return h&&this.setRTCUserData(l),l.userData={...l.userData,textContent:n,dxfType:"TEXT",isMText:!1,layer:e.layer||"0",handle:e.handle,entityId:e.entityId||e.handle},l.traverse(d=>{const u=d.geometry;if(u){if(d.userData.textContent=n,d.userData.dxfType="TEXT",d.userData.layer=e.layer||"0",d.userData.handle=e.handle,d instanceof p.Mesh&&!u.getIndex()){const f=u.getAttribute("position"),m=[];for(let b=0;b<f.count;b+=3)m.push(b,b+1,b+2);u.setIndex(m)}if(u.hasAttribute("uv")&&u.deleteAttribute("uv"),u.hasAttribute("normal")&&u.deleteAttribute("normal"),!h){const f=G.caculateGeometryCenter(u);f&&G.shouldRebasePositionOnRTC(f)&&this.setRTCUserData(d)}}}),l.layers.enableAll(),l}loadAttDef(e,i,s){let n=e.tag||e.text||e.prompt;if(!n||!this.font)return;const r=this.getTextStyle(i,e);n=sn(n).map(h=>h.text).join();const o=this.getTextMesh(n,e.textHeight,r,e);if(!o||o.children.length===0)return;this.transformTextMesh(e,o),H.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const l=G.shouldRebasePositionOnRTC(H);return l&&this.setRTCUserData(o),o.traverse(h=>{const d=h.geometry;if(d){if(h instanceof p.Mesh&&!d.getIndex()){const u=d.getAttribute("position"),f=[];for(let m=0;m<u.count;m+=3)f.push(m,m+1,m+2);d.setIndex(f)}if(d.hasAttribute("uv")&&d.deleteAttribute("uv"),d.hasAttribute("normal")&&d.deleteAttribute("normal"),!l){const u=G.caculateGeometryCenter(d);u&&G.shouldRebasePositionOnRTC(u)&&this.setRTCUserData(h)}}}),o.layers.enableAll(),o}loadAttrib(e,i,s){let n=e.text;if(!n||!this.font)return;const r=this.getTextStyle(i,e);n=sn(n).map(u=>u.text).join("");const o=this.getTextMesh(n,e.textHeight,r,e);if(!o||o.children.length===0)return;const l=s?.zdysx;o.userData.llbData=l;let h;if(l)try{h=JSON.parse(l)}catch{h=l}o.userData.textContent=n||"",o.userData.dxfType="ATTRIB",o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",this.transformTextMesh(e,o),H.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const d=G.shouldRebasePositionOnRTC(H);return d&&this.setRTCUserData(o),o.traverse(u=>{const f=u.geometry;if(f){if(u instanceof p.Mesh&&!f.getIndex()){const m=f.getAttribute("position"),b=[];for(let y=0;y<m.count;y+=3)b.push(y,y+1,y+2);f.setIndex(b)}if(f.hasAttribute("uv")&&f.deleteAttribute("uv"),f.hasAttribute("normal")&&f.deleteAttribute("normal"),u instanceof p.Mesh&&(u.entity=e,u.userData.entity=e),u.userData.textContent=n,u.userData.dxfType="ATTRIB",u.userData.layer=e.layer||"0",u.userData.handle=e.handle||"",h!==void 0&&(u.userData.xdata=h),!d){const m=G.caculateGeometryCenter(f);m&&G.shouldRebasePositionOnRTC(m)&&this.setRTCUserData(u)}}}),o.layers.enableAll(),o}loadPoint(e,i,s){if(!e.position)return;const n=new p.BufferGeometry,r=[new p.Vector3(e.position.x,e.position.y,e.position.z)];H.set(0,0,0);const a=H;let o=!1;this.enableRTC&&(o=G.checkAndRebasePositionsOnRTC(r,a)),n.setFromPoints(r);const l=new j(q.Point);return l.geometry=n,l.material=ge,o&&(this.setRTCUserData(l),l.matrix.setPosition(a.x,a.y,0)),l.layers.enableAll(),l}loadDimension(e,i){if(!e.block)return;const s=i.blocks[e.block];if(!s||!s.entities)return;const n=i.tables.dimStyle.dimStyles[e.dimStyleName]||this.getDefaultDimensionStyle(i);n&&n.DIMCLRD>0&&(e.colorIndex=n.DIMCLRD,e.color=Ai(e.colorIndex));const r=new j;for(let o=0;o<s.entities.length;o++){const l=this.loadEntity(s.entities[o],i,e);l&&r.add(l)}if(r.children.length===0){const o=e.name||e.block;return!this.statsInfo.ignoredInserts[o]&&(this.statsInfo.ignoredInserts[o]=0),this.statsInfo.ignoredInserts[o]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const o=this.blockReferencesCache[e.block];o.referenceCount++}r.name=e.type+"<"+s.name+">",r.userData.entityType=e.type;const a=e.insertionPoint;return H.set(0,0,0),a&&H.set(a.x,a.y,0),G.shouldRebasePositionOnRTC(H)&&this.setRTCUserData(r),r.matrix.setPosition(H),r}loadImage(e,i,s){if(!e.imageSize||!i.objects.IMAGEDEF?.length)return;const n=i.objects.IMAGEDEF.filter(y=>y.handle===e.imageDefHandle)[0];if(!n)return;const r=e.imageSize.x,a=e.imageSize.y,o=new j;let l=!1;e.flags===nn.ShowImageWhenNotAlignedWithScreen||e.flags===nn.UseClippingBoundary||e.flags===nn.TransparencyIsOn||(l=!0);const h=new p.PlaneGeometry(r,a);if(l){const y=new p.TextureLoader(this.manager).load(n.filename,void 0,void 0,()=>{console.warn("Please upload the pictures in the same folder, or use url link in the dxf file.")});y.colorSpace=p.SRGBColorSpace;const S=new p.MeshBasicMaterial({transparent:!0,side:p.FrontSide,map:y}),w=new j(q.Mesh);w.geometry=h,w.material=S,o.add(w)}const d=new p.EdgesGeometry(h),u=this.getColor(e,i,s),f=new j(q.Line);f.geometry=d,f.material=this.getLineBasicMaterial(u);const m=e.uPixel?new p.Vector3(e.uPixel.x,e.uPixel.y,e.uPixel.z):new p.Vector3(n.pixelSize.x,0,0),b=e.vPixel?new p.Vector3(e.vPixel.x,e.vPixel.y,e.vPixel.z):new p.Vector3(n.pixelSize.y,0,0);if(o.add(f),$.set(m.x,b.y,1),H.set(0,0,0),e.position){const y=new p.Vector3(e.position.x,e.position.y,e.position.z);y.add(m.multiplyScalar(r/2)).add(b.multiplyScalar(a/2)),H.copy(y)}return G.shouldRebasePositionOnRTC(H)&&this.setRTCUserData(o),ye.identity(),o.matrix.compose(H,ye,$),o}loadInsert(e,i,s,n=!1){if(!e||!e.block)return;const r=i.blocks[e.block];if(!r||!r.entities)return;s&&e.layer==="0"&&(e.layer=s.layer),e.blockPosition=r.position;const a=new j,o=e.zdysx;let l;if(o)try{l=JSON.parse(o)}catch{l=o}for(let m=0;m<r.entities.length;m++){if(r.entities[m].type==="ATTDEF")continue;const b=this.loadEntity(r.entities[m],i,e,n);b&&(o&&N.LOADLLDATA&&(b.userData.llbData=o),l!==void 0&&b.traverse(y=>{y.geometry&&(y.userData.xdata=l)}),a.add(b))}if(a.children.length===0){const m=e.name||e.block;return!this.statsInfo.ignoredInserts[m]&&(this.statsInfo.ignoredInserts[m]=0),this.statsInfo.ignoredInserts[m]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const m=this.blockReferencesCache[e.block];m.referenceCount++}a.name=e.type+"<"+r.name+">",a.userData.entityType=e.type,l!==void 0&&(a.userData.xdata=l),e.extendedData?.originalType&&(a.userData.originalType=e.extendedData?.originalType),e?.blockPosition&&a.matrix.setPosition(-e.blockPosition.x,-e.blockPosition.y,0);const h=H.set(1,1,1);e.xScale&&(h.x=e.xScale),e.yScale&&(h.y=e.yScale);const d=new p.Euler;e.rotation&&(d.z=e.rotation*Math.PI/180),ye.setFromEuler(d,!1);const u=$.set(0,0,0);e.position&&(u.x=e.position.x,u.y=e.position.y),ue.compose(u,ye,h),e.extrusionDirection&&e.extrusionDirection.z<0&&ue.premultiply(Ma.identity().makeScale(-1,1,1)),it.copy(a.matrix),a.matrix.premultiply(ue),$.set(a.matrix.elements[12],a.matrix.elements[13],a.matrix.elements[14]),G.shouldRebasePositionOnRTC($)&&this.setRTCUserData(a);const f=this.findSpatialFilterByHandle(e.handle,i);if(f){this.loadSpatialFilter(f);const m=f;m&&m.clipPolylines&&m.clipPolylines.length>0&&(a.userData.spatialFilterHandle=f.handle,this.cloneMaterialsForSpatialFilter(a),P.debug("[Dxf] Spatial filter:",e.associatedSpatialFilter))}return a}loadSpatialFilter(e){const i=e;if(i.threejsObject)return i.threejsObject.clone();const s=e.invertBlockMatrix;if(!Array.isArray(s)||s.length<12)return P.warn("[Dxf] Spatial filter (handle '"+e.handle+"') has no invertBlockMatrix, ignored!"),void 0;ue.set(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],0,0,0,1);const n=[];e.vertices.forEach(o=>{n.push(new p.Vector3(o.x,o.y,0))});const r={polyline:[],bConcave:!1,bReversed:!1};if(e.numberOfPointsOnClipBoundary===2)r.polyline=n;else{const o=e.numberOfPointsOnClipBoundary,l=3;if(o<l)return P.warn("[Dxf] Invalid clipBoundary: "+e.handle+" !"),void 0;let h=[],d=-1;for(let m=0;m<o;m++){const b=n[m];for(let y=o-1;y>m;y--){const S=n[y];if(V.areVector3sEqual(b,S)&&m+1<y-1&&m+1<o-1&&V.areVector3sEqual(n[m+1],n[y-1])){h.push(b),d=y;break}}if(d>0)break;h.push(b)}if(d>0)for(let m=d+1;m<o;m++)h.push(n[m]);if(h.length<l)return P.warn("[Dxf] Invalid clipBoundary: "+e.handle+"!"),void 0;const u=[],f=[];if(h.forEach(m=>{u.push(new p.Vector2(m.x,m.y)),f.push([m.x,m.y])}),!G.isConvex(u)){P.warn("[Dxf] Concave polygon is not supported for spatial filter (handle '"+e.handle+"'), converting to convex polygon!");const m=vl(f,1/0);h=[],m.forEach(b=>{h.push(new p.Vector3(b[0],b[1],0))})}!V.areVector3sEqual(h[0],h[h.length-1])&&h.push(h[0]),r.polyline=h,r.bReversed=d>0}let a;return this.enableReleaseData&&(e.vertices=[],e.matrix=[],e.invertBlockMatrix=[]),i.localMatrix=ue.clone(),i.clipPolylines=[],i.clipPolylines.push(r),a}loadLayout(e,i,s,n,r,a){if(!e.entities)return;const o=new j;for(let d=0;d<e.entities.length;d++){const u=e.entities[d];this.addViewport(u,a);const f=this.loadEntity(u,i);f&&(this.enableMerge&&Mt.merge(f,!1),o.add(f),f.traverse(m=>{if(m.geometry){const b=m.userData.layerName;let y=r[b];!y&&(y=[],r[b]=y),y.push(m),m.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[s.layoutName]&&(this.layoutsSnapObjectsMap[s.layoutName]=[]),this.layoutsSnapObjectsMap[s.layoutName].push(m))}}))}if(o.children.length===0)return;o.userData.layerName=e.layer;const l=s.layoutName;let h=n.children.find(d=>d.name===l);!h&&(h=new j,h.name=l,h.userData.isLayoutLevelObject=!0,n.add(h)),h.add(o),e.position&&o.matrix.setPosition(e.position.x,e.position.y,e.position.z||0)}convertEdgeToPoints(e){const i=[];if(!e)return i;const s=e.type,n=r=>!!r&&Number.isFinite(r.x)&&Number.isFinite(r.y);switch(s){case Mi.Line:{const r=e;if(!n(r.startPoint)||!n(r.endPoint))break;i.push(new p.Vector2(r.startPoint.x,r.startPoint.y)),i.push(new p.Vector2(r.endPoint.x,r.endPoint.y));break}case Mi.Arc:{const r=e;if(!n(r.center)||!Number.isFinite(r.radius)||r.radius<=0||!Number.isFinite(r.startAngle)||!Number.isFinite(r.endAngle))break;let a=r.startAngle*p.MathUtils.DEG2RAD,o=r.endAngle*p.MathUtils.DEG2RAD;!r.bCounterclockwise&&(a=Math.PI*2-a,o=Math.PI*2-o);const l=new p.ArcCurve(r.center.x,r.center.y,r.radius,a,o,!r.bCounterclockwise),h=this.getDivision(a,o,r.radius),d=l.getPoints(h);e.startPoint=d[0],e.endPoint=d[d.length-1],i.push(...d);break}case Mi.Ellipse:{const r=e;if(!n(r.center)||!n(r.majorAxisEndPoint)||!Number.isFinite(r.minorRatio)||!Number.isFinite(r.startAngle)||!Number.isFinite(r.endAngle))break;const a=Math.sqrt(Math.pow(r.majorAxisEndPoint.x,2)+Math.pow(r.majorAxisEndPoint.y,2)),o=a*r.minorRatio,l=Math.atan2(r.majorAxisEndPoint.y,r.majorAxisEndPoint.x);let h=r.startAngle*p.MathUtils.DEG2RAD,d=r.endAngle*p.MathUtils.DEG2RAD;!r.bCounterclockwise&&(h=Math.PI*2-h,d=Math.PI*2-d);const u=new p.EllipseCurve(r.center.x,r.center.y,a,o,h,d,!r.bCounterclockwise,l),f=this.getDivision(h,d,Math.max(a,o)),m=u.getPoints(f);e.startPoint=m[0],e.endPoint=m[m.length-1],i.push(...m);break}case Mi.Spline:{const r=e,a=_a(r.controlPoints,r.degreeOfSplineCurve,r.knotValues);if(a.length===0)break;e.startPoint=a[0],e.endPoint=a[a.length-1],i.push(...a);break}case Mi.Polyline:{const r=e,a=Vn(r.points,r.isClosed);e.startPoint=a[0],e.endPoint=a[a.length-1],i.push(...a);break}}return i}loadHatch(e,i,s){const n=e;let r=[];function a(M,O){const{startPoint:T,endPoint:v}=M,{startPoint:C,endPoint:_}=O;if(!T||!v||!C||!_)return null;const A=v.x-T.x,I=v.y-T.y,B=_.x-C.x,D=_.y-C.y,k=A*D-I*B;if(Math.abs(k)<1e-10)return null;const z=T.x-C.x,se=T.y-C.y,ne=(B*se-D*z)/k,ze=(A*se-I*z)/k;return ne>=0&&ne<=1&&ze>=0&&ze<=1?{x:T.x+ne*A,y:T.y+ne*I}:null}function o(M){const{edges:O}=M,T=[],v=O.length;if({...M},v!==4)return[M];for(let C=0;C<v;C++)for(let _=C+2;_<v;_++){if(_===C+1||C===0&&_===v-1)continue;const A=a(O[C],O[_]);A&&T.push({edgeIndex1:C,edgeIndex2:_,point:{x:A.x,y:A.y}})}if(T.length&&T.length===1){const C=O[(T[0].edgeIndex1-1+v)%v],_={pathTypeFlag:M.pathTypeFlag,edges:[C,{startPoint:{...O[T[0].edgeIndex1].startPoint},endPoint:{x:T[0].point.x,y:T[0].point.y},type:O[T[0].edgeIndex1].type},{startPoint:{x:T[0].point.x,y:T[0].point.y},endPoint:{x:O[T[0].edgeIndex2].startPoint.x,y:O[T[0].edgeIndex2].startPoint.y},type:O[T[0].edgeIndex2].type}]},A={pathTypeFlag:M.pathTypeFlag,edges:[{startPoint:{x:T[0].point.x-1e-5,y:T[0].point.y-1e-5},endPoint:{...O[T[0].edgeIndex1].endPoint},type:O[T[0].edgeIndex1].type},{...O[T[0].edgeIndex2-1]},{startPoint:O[T[0].edgeIndex2].startPoint,endPoint:{x:T[0].point.x-1e-5,y:T[0].point.y-1e-5},type:O[T[0].edgeIndex2].type}]};return[_,A]}return[M]}if(n.boundaryPaths.length==0)return;for(let M=0;M<n.boundaryPaths.length;M++){const O=n.boundaryPaths[M],T=o(O);r=[...r,...T]}if(n.boundaryPaths=r,!n.solidFill&&!n.patternLines?.length){P.warn("[Dxf] Hatch entity(handle: '"+n.handle+"') doesn't have solid fill, nor patternLines, ignored!");return}const l=[],h=[],d=[],u=M=>{const O=[];let T=[];T.push(...this.convertEdgeToPoints(M[0]));for(let v=1;v<M.length;v++){const C=this.convertEdgeToPoints(M[v]);if(T.push(...C),T.length>2){const _=this.convertEdgeToPoints(M[v-1]);V.areVector2sEqual(_[_.length-1],C[0])?V.areVector2sEqual(T[0],C[C.length-1],1e-5)&&(O.push(T),T=[]):V.areVector2sEqual(_[0],C[C.length-1])?V.areVector2sEqual(T[1],C[0],1e-5)&&(O.push(T),T=[]):T=[]}}return O};if(n.boundaryPaths.forEach((M,O)=>{let T=[];if(this.IsfilteredByPathTypeFlag(M.pathTypeFlag)){P.info("[Dxf] The %d path type flag is filtered at the %dth boundrayPath (hatch handle '%s')",M.pathTypeFlag,O,n.handle);return}const v=M.edges;if(v.length===0)return;const C=[];for(let _=0;_<v.length;_++){const A=this.convertEdgeToPoints(v[_]);if(A.length<2){P.warn("[Dxf] The %dth edge of the %dth boundaryPath (hatch handle '%s') has less than 2 points, ignored!",_,O,n.handle);continue}C.push(...A)}if(C.length<3){P.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has less than 3 points, ignored!",O,n.handle);return}if(T.push(C),M.pathTypeFlag>So.MaxFlags&&(!(A=>{for(let I=1;I<A.length;++I){const B=A[I-1].endPoint,D=A[I].startPoint;if(!B||!D||!V.areVector2sEqual(B,D))return!1}return!0})(M.edges)||!n.associativity)&&(T=u(v),T.length<2)){P.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has unknown path, ignored!",O,n.handle);return}T.forEach(_=>{!V.areVector2sEqual(_[0],_[_.length-1])&&_.push(_[0]);const A=_.map(I=>new p.Vector2(U.roundNumber(I.x,7),U.roundNumber(I.y,7)));if(A?.length>0){l.push(A);const I=new p.Box2().setFromPoints(A);h.push(I);const B=I.getSize(Wi),D=B.x*B.y;d.push({area:D,index:l.length-1})}})}),l.length===0)return;const f=new p.Vector2,m=this.checkAndRebasePolygonsOnRTC(l,f);d.sort((M,O)=>M.area-O.area);const b=[];d.forEach(M=>{b.push(M.index)});const y=this.buildContainHierarchyTree(l,h,b),S=[];this.buildHatchGeometry(l,y,S);let w;if(S.length>0&&(w=Ae.mergeGeometries(S)),!w||!w.getIndex()||w.getIndex()?.count===0)return P.warn("[Dxf] Failed to convert hatch boundaries!"),void 0;const x=new j(q.Mesh);x.geometry=w,x.material=pi,this.setHatchMaterial(x,n,i,f,s);const E=x;return m&&(this.setRTCUserData(E),E.matrix.setPosition(f.x,f.y,0)),E.traverse(M=>{M.layers.enableAll(),M.layers.disable(Ue)}),E}loadOle2frame(e,i){const{leftUpX:s,leftUpY:n,rightDownX:r,rightDownY:a}=e;if(!s||!n||!r||!a)return;const o=[new p.Vector2(s,n),new p.Vector2(s,a),new p.Vector2(r,a),new p.Vector2(r,n),new p.Vector2(s,n)],l=new p.Vector3;let h=!1;this.enableRTC&&(h=G.checkAndRebasePositionsOnRTC(o,l));const d=new p.BufferGeometry().setFromPoints(o),u=this.getLineBasicMaterial(16777215),f=new j(q.Line);f.geometry=d,f.material=u,f.layers.enableAll(),h&&(this.setRTCUserData(f),f.matrix.setPosition(l.x,l.y,0));const m=new j;m.add(f);let b;const y=i.objects.DICTIONARY;for(const w of y)for(const x in w.entries)if(w.entries[x]===e.handle){b=x;break}let S;if(b)if(this.meshTextureMaterials[b])S=this.meshTextureMaterials[b];else for(let w=0;w<i.objects.XRECORD.length;w++){const x=i.objects.XRECORD[w];if(x.handle===b){const E=x.binaryData,M=U.hexToBase64(E),O="data:image/jpg;base64,"+M,T=new p.TextureLoader(this.manager).load(O);T.colorSpace=p.SRGBColorSpace;const v=new p.MeshBasicMaterial({transparent:!0,map:T});this.meshTextureMaterials[b]=v,S=v;break}}if(S){const w=new p.Box2().setFromPoints(o),x=w.getSize(Wi),E=new p.PlaneGeometry(x.x,x.y),M=new j(q.Mesh);M.geometry=E,M.material=S;const O=w.getCenter(Wi);H.set(O.x,O.y,0),h&&(this.setRTCUserData(M),H.x+=l.x,H.y+=l.y),M.matrix.setPosition(H),M.layers.enableAll(),m.add(M)}return m.children.length>1?m:f}static getOcsMatrix(e){let i=We,s=zn,n=fi;const r=new p.Vector3(0,1,0),a=new p.Vector3(0,0,1);return V.areVectorsClose(e,a)?ue.identity():(n=e.clone().normalize(),!V.areVectorsClose(n,a)&&(Math.abs(n.x)<1/64&&Math.abs(n.y)<1/64?i=r.cross(n).normalize():i=a.cross(n).normalize(),s=n.clone().cross(i).normalize()),ue.set(i.x,i.y,i.z,0,s.x,s.y,s.z,0,n.x,n.y,n.z,0,0,0,0,1))}static getDcs2WcsMatrix(e,i){let s;s1(e)?s=e.viewDirectionFromTarget:s=e.viewDirection,s??(s={x:0,y:0,z:1});const n=e.viewTarget??{x:0,y:0,z:0},r=new p.Vector3(V.roundNumber(s.x,7),V.roundNumber(s.y,7),s.z),a=new p.Vector3(n.x,n.y,n.z),o=e.viewTwistAngle||0;let l,h,d;d=r.clone().normalize(),l=fi.clone().cross(r),l.length()>0?(l.normalize(),h=d.clone().cross(l)):d.z<0?(l=We.clone().negate(),h=zn,d=fi.clone().negate()):(l=We,h=zn,d=fi);const u=new p.Matrix4,f=ue.identity();return f.makeBasis(l,h,d),u.premultiply(f),u.premultiply(ue.identity().compose(a.clone(),new p.Quaternion().setFromAxisAngle(new p.Vector3(0,0,1),p.MathUtils.degToRad(i?o:-o)),new p.Vector3(1,1,1))),u}getViewportMsToPsMatrix(e){const i=e.centerPoint_dcs??{x:0,y:0},s=e.centerPoint??{x:0,y:0,z:0},n=new p.Vector3(i.x,i.y,0),r=new p.Vector3(s.x,s.y,s.z),a=e.viewHeight,o=e.height_paperSpace||1,l=(a||o)/o,h=N.getDcs2WcsMatrix(e,this.angDir),d=new p.Matrix4;d.setPosition(wa.clone().sub(r));const u=Ma.identity();u.scale(H.set(l,l,l));const f=it.identity().setPosition(wa.clone().sub(r));u.premultiply(f.clone().invert()).multiply(f),d.multiply(u);const m=ue.identity();m.setPosition(n),h.multiply(m);const b=ue.identity();return d.invert().multiply(b).multiply(h.invert())}loadViewport(e,i,s){if(e.viewportId+""=="1"){e.psBBox=new p.Box3,e.msToPsMatrix=new p.Matrix4;return}const n=e.centerPoint;if(!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)){e.psBBox=new p.Box3,e.msToPsMatrix=new p.Matrix4;return}const r=e.width_paperSpace/2,a=e.height_paperSpace/2,o=[new p.Vector3(n.x-r,n.y-a,0),new p.Vector3(n.x-r,n.y+a,0),new p.Vector3(n.x+r,n.y+a,0),new p.Vector3(n.x+r,n.y-a,0)];o.push(o[0]),e.psBBox=new p.Box3().setFromPoints([o[0],o[2]]),e.msToPsMatrix=this.getViewportMsToPsMatrix(e);let l=!1;const h=new p.Vector3;this.enableRTC&&(l=G.checkAndRebasePositionsOnRTC(o,h));const d=new p.BufferGeometry().setFromPoints(o),u=new j(q.Line);u.geometry=d,u.material=ge,u.userData.entityType=e.type,u.layers.enableAll(),l&&(this.setRTCUserData(u),u.matrix.setPosition(h.x,h.y,0));const f=e.psBBox.clone();f.applyMatrix4(e.msToPsMatrix.clone().invert()),f.min.z=0,f.max.z=0;const m=[f.min,new p.Vector3(f.min.x,f.max.y,0),f.max,new p.Vector3(f.max.x,f.min.y,0)];m.push(m[0]);let b=!1;const y=new p.Vector3;this.enableRTC&&(b=G.checkAndRebasePositionsOnRTC(m,y));const S=new p.BufferGeometry().setFromPoints(m),w=new j(q.Line);w.geometry=S,w.material=ge,w.userData.entityType=e.type,w.userData.inPaperSpace=[],w.layers.enableAll(),b&&(this.setRTCUserData(w),w.matrix.setPosition(y.x,y.y,0));const x=new j;return x.add(u),x.add(w),u}getColor(e,i,s){if(this.compareContext)return ot.ENTITY_COLOR_NO_CHANGE;if(this.overrideColor!=null)return this.overrideColor;const n=e;if(n&&n.isGradientColor){const r=n.gradientColors;if(r&&r.length>=2){if(r[0]!==r[1]){const a="[Dxf] Gradient colors are not supported for hatch '"+e.handle+"', will use the first color!";P.warn(a)}return r[0]}}if(e.isTrueColor||e.colorIndex>0&&e.colorIndex<256)return e.color;if(e.colorIndex===0)return s?this.getColor(s,i):i.tables?.layer?.layers[0].color;if(e.colorIndex===256){const r=i.tables?.layer?.layers,a=r&&r[e.layer],o=r&&s&&r[s.layer];let l=Lt;return a&&a.name!=="0"?l=a.color:o?l=o.color:a?l=a.color:r&&r[0].color&&(l=r[0].color),l}return P.warn("[Dxf] Unknown colorIndex"),Lt}getLineType(e,i,s){if(s&&s.type==="DIMENSION")return this.getLineType(s,i);if(e.lineType!==Cr&&e.lineType!==hs)return e.lineType;if(e.lineType===hs)return s?this.getLineType(s,i):e.lineType;const n=i.tables?.layer?.layers,r=i1;if(e.layer!=="0"){const a=n&&n[e.layer];if(a)return a.lineType}else if(s){const a=n&&n[s.layer];if(a)return a.lineType}return r}getLayerName(e,i,s){const n=h=>{r&&h&&!r[e.layer]&&(console.warn("[Dxf] Failed to find layer object for '"+h+"', adding a default one."),r[h]={name:h,handle:"",colorIndex:256,lineType:"",visible:!0})},r=i.tables?.layer?.layers;n(e.layer);const a=r&&r[e.layer];n(s?.layer);const o=r&&s&&r[s.layer];let l=a?.name||"";return a&&a.name==="0"&&o&&(l=o.name),l}setMaterial(e,i,s,n){const r=e;if(!r.geometry||(this.setRenderOrderByObjectType(e),i.type==="OLE2FRAME"))return;if(i.type==="MTEXT"){e.renderOrder=xe.Text;return}if(i.type==="HATCH"){Wi.set(0,0),this.setHatchMaterial(e,i,s,Wi,n);return}if(i.type==="IMAGE")return;let a;const o=this.getColor(i,s,n);if(i.type==="LWPOLYLINE"&&(r.isMesh?(a=this.getMeshBasicMaterial(o),e.renderOrder=xe.LineWithWidth):e.userData.isOutline&&(a=this.getLineBasicMaterial(o),e.renderOrder=xe.LineWithPattern),a)){r.material=a;return}if(i.type==="SOLID")a=this.getMeshBasicMaterial(o);else if(i.type==="TEXT"||i.type==="ATTDEF"||i.type==="ATTRIB")a=this.getLineBasicMaterial(o),e.renderOrder=xe.Text;else if(i.type==="LEADER"||i.type==="MULTILEADER"||i.type==="VIEWPORT")a=this.getLineBasicMaterial(o);else if(i.type==="POINT")a=this.getPointsMaterial(o);else{if(e.material instanceof p.PointsMaterial){a=this.getPointsMaterial(o),r.material=a;return}const l=s.tables?.lineType?.lineTypes,h=l&&l[this.getLineType(i,s,n)];if(h&&h.pattern&&h.pattern.length!==0){const d=i.lineTypeScale||1;a=this.getLineShaderMaterial(h,o,d),e.renderOrder=xe.LineWithPattern}else a=this.getLineBasicMaterial(o)}r.material=a}setHatchMaterial(e,i,s,n,r){const a=e;if(!a.geometry)return;const o=this.getColor(i,s,r);if(a.type===q.Line||a.type===q.LineSegment){a.material=this.getLineBasicMaterial(o);return}let l=xe.Mesh,h;if(i.solidFill)h=this.getMeshBasicMaterial(o);else{if(a.material instanceof p.ShaderMaterial){h=a.material;const d=new p.Color(o);!a.material.uniforms.u_color.value.equals(d)&&(h=a.material.clone(),N.updateMaterialUniforms(h),h.uniforms.u_color.value.set(o))}else h=this.getHatchShaderMaterial(i,o,n);l=xe.MeshWithPattern}!h&&(h=this.getMeshBasicMaterial(o),l=xe.Mesh),a.material=h,a.renderOrder=l}setRenderOrderByObjectType(e){const i=e;let s=0;i.isMesh?s=xe.Mesh:i.isLine?s=xe.Line:i.isPoints&&(s=xe.Point),e.renderOrder=s}getPointsMaterial(e){return!this.pointsMaterials[e]&&(this.pointsMaterials[e]=new p.PointsMaterial({size:.2,color:e})),this.pointsMaterials[e]}getLineBasicMaterial(e){return!this.lineBasicMaterials[e]&&(this.lineBasicMaterials[e]=new p.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,i,s){const n=e.name+"_"+i+"_"+s;if(!this.lineShaderMaterials[n]){const r=this.getLineTypeScales(),a=r.ltScale*r.celtScale*s;this.lineShaderMaterials[n]=Mo.createLineShaderMaterial(e.pattern,i,a,N.ViewportScaleUniform,N.CameraZoomUniform)}return this.lineShaderMaterials[n]}getMeshBasicMaterial(e){return!this.meshBasicMaterials[e]&&(this.meshBasicMaterials[e]=new p.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getHatchShaderMaterial(e,i,s){if(!e.patternLines||e.patternLines.length<1)return;const n=this.findMatchedHatchShaderMaterial(e,i);if(n)return n;const r=.005,a=.05;let o=2;e.patternLines.forEach(f=>{o=Math.max(f.dashPattern.length,o)});let l=0;const h=[],d=new p.Vector2;for(const f of e.patternLines){const m=new p.Vector2(f.origin.x,f.origin.y).sub(s).rotateAround(d,-p.MathUtils.degToRad(e.patternAngle)),b=new p.Vector2(f.delta.x,f.delta.y).rotateAround(d,-p.MathUtils.degToRad(f.angle));if(b.y===0)return P.warn("[Dxf] delta.y is equal to zero !"),void 0;const y=f.dashPattern.length;let S=!0,w=0;for(let v=0;v<y;++v){const C=f.dashPattern[v];C>0&&(S=!1),w+=Math.abs(C)}const x=S?a:r,E=[],M=[];let O=0;M[0]=O;for(let v=0;v<y;++v)E[v]=f.dashPattern[v],E[v]===0&&(E[v]=x*w),O+=Math.abs(E[v]),M[v+1]=O;for(let v=y;v<o;++v)E[v]=0;for(let v=M.length;v<o+1;++v)M[v]=O;const T={origin:m,delta:b,angle:f.angle-e.patternAngle,pattern:E,patternSum:M,patternLength:O};if(l+=4,l+=o,l+=o+1,l>N.MaxFragmentUniforms){P.warn("[Dxf] There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}h.push(T)}const u=To(h,e.patternAngle,N.CameraZoomUniform,new p.Color(i),this.overrideHatchPatternLineThickness);return u.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:i,material:u}),u}getDivision(e,i,s){let n=Math.round(5e4/this.entityCount);n=Math.max(n,2),n=Math.min(n,10);const r=n*5;let o=n*2;if(this.averageCurveSize){const d=Math.pow(s/this.averageCurveSize,.5);o*=d,o=Math.max(o,n),o=Math.min(o,r)}let l=i-e;l<0&&(l+=Math.PI*2),o=Math.ceil(o*(l/Math.PI));let h=8;return l<.087?h=2:l<.174?h=3:l<.52?h=4:l<1.57?h=5:l<3.14?h=6:l<4.71&&(h=7),o=Math.max(o,h),this.averageCurveSize=(this.averageCurveSize*this.curveCount+s)/(this.curveCount+1),this.curveCount++,Math.max(o,12)}getBSplineInterpolationsPerSplineSegment(e,i){let s=1;this.averageCurveSize&&(s=Math.pow(i/this.averageCurveSize,.5),s=Math.max(s,.5),s=Math.min(s,2)),this.averageCurveSize=(this.averageCurveSize*this.curveCount+i)/(this.curveCount+1),this.curveCount++;let n=e*2*s;if(e>20){const r=Math.log10(e);n/=r}return n}async setDxfDataToIndexedDb(e,i){const s={dxfDataId:e,dxf:i};return new Promise((n,r)=>{ln.instance().add(s,()=>{P.info("[Dxf] Saved '"+e+"' to indexedDb"),n()},a=>{r(a)})})}async getDxfDataFromIndexedDb(e){return new Promise((i,s)=>{ln.instance().query(e,n=>{n&&n.length>0&&i(n[0].dxf),i(void 0)},()=>s())})}buildContainHierarchyTree(e,i,s){const n=new Map,r=s.length;for(let o=0;o<r;o++)n.set(s[o],{index:s[o],children:[]});const a={index:-1,children:[]};for(let o=0;o<r;o++){const l=s[o],h=e[l],d=i[l];let u=o+1;for(;u<r;u++){const f=s[u],m=e[f];if(i[f].containsBox(d)&&G.isPointInPolygon(h[U.generateRandomInt(0,h.length-1)],m)){n.get(f)?.children.push(n.get(l));break}}u===r&&a.children.push(n.get(l))}return a}buildHatchGeometry(e,i,s){if(i.children.length===0)return;const n=[],r=new Map;i.children.forEach(l=>{l.children.length===0?n.push(l.index):r.set(l.index,l.children.map(h=>h.index))});const a=l=>{try{const h=new p.ShapeGeometry(l);h.hasAttribute("uv")&&h.deleteAttribute("uv"),h.hasAttribute("normal")&&h.deleteAttribute("normal"),s.push(h)}catch{P.warn("[Dxf] triangulate shape error: "+l.getPoints().map(d=>d.toArray()).toString())}};n.forEach(l=>{const h=e[l];if(h.length===0)return;const d=new p.Shape(h);a(d)});const o=l=>l.map(h=>h.toArray());for(const l of r){const h=new p.Shape(e[l[0]]);let d={regions:[],inverted:!1};const u=this.findIntersectHole(e,l[1]);u.forEach(m=>{let b={regions:[],inverted:!1};try{m.forEach((y,S)=>{if(Yt.epsilon(V.getVector2RelativeEps(e[y][0]),1e-6),S===0)b=Yt.segments({regions:[o(e[y])],inverted:!1});else{const w=Yt.segments({regions:[o(e[y])],inverted:!1}),x=Yt.combine(b,w);d=Yt.polygon(Yt.selectUnion(x)),d.regions.length>0?d.regions.forEach(E=>{if(E.length===0)return;const M=E.map(O=>new p.Vector2(O[0],O[1]));h.holes.push(new p.Path(M))}):P.warn("[Dxf] mergedHoles.regions is empty")}})}catch(y){P.warn("[Dxf] polybooljs has error: "+y+", epsilon is "+Yt.epsilon())}});const f=u.flat(2);for(let m=0;m<l[1].length;m++){const b=l[1][m];!f.includes(b)&&h.holes.push(new p.Path(e[b]))}a(h)}i.children.forEach(l=>{l.children.forEach(h=>{this.buildHatchGeometry(e,h,s)})})}findIntersectHole(e,i){const s=i.length,n=[];for(let r=0;r<s;r++){const a=e[i[r]];let o=!1;const l=[];for(let h=r+1;h<s;h++){const d=e[i[h]];G.arePolygonsIntersect(a,d)&&(o=!0,l.push(i[h]))}o&&(l.push(i[r]),n.push(l))}return n}checkAndRebasePolygonsOnRTC(e,i){if(!this.enableRTC||e.length===0)return!1;let s=0;e.forEach(r=>{r.forEach(a=>{i.add(a),s++})}),i.divideScalar(s);let n=!1;if(this.enableRTC&&G.shouldRebasePositionOnRTC(i)){n=!0;for(let r=0;r<e.length;r++){const a=e[r];for(let o=0;o<a.length;o++){const l=a[o].x-i.x,h=a[o].y-i.y;a[o]=new p.Vector2(l,h)}}}else i.set(0,0);return n}setRTCUserData(e){e.userData.relativeToCenter=!0,this.statsInfo.rebasedEntityCount++}IsfilteredByPathTypeFlag(e){return e<0}findSpatialFilterByHandle(e,i){const s=i.objects.DICTIONARY;if(!s)return;if(!this.dictionaryOwnerHandleAndSpatialFilterHandlesCache){this.dictionaryOwnerHandleAndSpatialFilterHandlesCache={};for(const r of s){const a=r;let o="";for(const l in a.entries)if(a.entries[l]==="ACAD_FILTER"){o=l;break}o&&(this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[r.ownerHandle]&&P.warn("[Dxf] Why this.dictionaryObjectsCache[obj.ownerHandle] already exist?",r.ownerHandle),this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[r.ownerHandle]=o)}}const n=this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[e];if(n){if(!this.spatialFiltersCache){this.spatialFiltersCache={};const r=i.objects.SPATIAL_FILTER||[];for(const a of r){const o=a;o.numberOfPointsOnClipBoundary<2||(this.spatialFiltersCache[o.ownerHandle]&&P.warn("[Dxf] Why this.spatialFiltersCache[spatialFilterObj.ownerHandle] already exist?",n),this.spatialFiltersCache[o.ownerHandle]=o)}}return this.spatialFiltersCache[n]}}initRenderOrderInfo(e){const i=new Set,s=e.objects.DICTIONARY;for(const r of s){const a=r;Object.keys(a.entries).forEach(o=>{a.entries[o]&&a.entries[o]==="ACAD_SORTENTS"&&i.add(o)})}if(i.size===0)return;const n=e.objects.SORTENTSTABLE;if(n)for(let r=0;r<n.length;++r){const a=n[r];if(i.has(a.handle)){for(let o=0;o<a.sortEntsObject.entityHandles.length;++o){const l=a.sortEntsObject.entityHandles[o];l.length===2&&!this.entityHandlesWithRenderOrder[l[0]]?this.entityHandlesWithRenderOrder[l[0]]=l[1]:P.warn("[Dxf] Failed to handle sortEntsTable: "+a.handle+".")}break}}}findMatchedHatchShaderMaterial(e,i){const s=e.patternLines;if(!s||s.length<1)return;const n=(h,d)=>Math.abs(h-d)<1e-5,r=(h,d)=>{if(h.length!==d.length)return!1;for(let u=0;u<h.length;++u)if(!n(h[u],d[u]))return!1;return!0},a=(h,d)=>n(h.angle,d.angle)&&n(h.delta.x,d.delta.x)&&n(h.delta.y,d.delta.y)&&n(h.origin.x,d.origin.x)&&n(h.origin.y,d.origin.y)&&r(h.dashPattern,d.dashPattern),o=(h,d)=>{if(h.length!==d.length)return!1;for(let u=0;u<h.length;++u)if(!a(h[u],d[u]))return!1;return!0};return this.hatchShaderMaterials.find(h=>h.color===i&&h.patternAngle===e.patternAngle&&o(h.patternLines,s))?.material}getLayout(e,i){if(!this.blockRecordsCache){this.blockRecordsCache={};const r=this.blockRecordsCache,a=e.tables?.blockRecord?.blockRecords;a&&Object.values(a).forEach(o=>{r[o.handle]=o.layoutHandle})}const s=this.blockRecordsCache[i.ownerHandle];if(s){const r=e.objects.LAYOUT,a=r.find(o=>o.handle===s);if(a)return a}if(!this.entitiesCache){this.entitiesCache={};const r=this.entitiesCache;Object.values(e.entities).forEach(a=>{r[a.handle]=a})}const n=this.entitiesCache[i.ownerHandle];return n?this.getLayout(e,n):e.objects.LAYOUT.find(r=>r.layoutName===N.MODEL_LAYOUT_NAME)}getLayerVisible(e,i){const s=e.tables?.layer?.layers;return s&&s[i]?.visible}getLayerFrozen(e,i){const s=e.tables?.layer?.layers;return s&&s[i.layer]?.frozen}cloneMaterialsForSpatialFilter(e){const i=new Map,s=n=>{let r;if(Array.isArray(n)){const a=[];r=a,n.forEach(o=>{if(i.has(o.id))a.push(i.get(o.id));else{const l=o.clone();N.updateMaterialUniforms(l),i.set(o.id,l),a.push(l)}})}else n&&(i.has(n.id)?r=i.get(n.id):(r=n.clone(),N.updateMaterialUniforms(r),i.set(n.id,r)));return r};e.traverse(n=>{n.material&&(n.material=s(n.material))})}getLineTypeScales(){const e={ltScale:1,celtScale:1};return this.header&&(e.ltScale=this.header.$LTSCALE||1,e.celtScale=this.header.$CELTSCALE||1),e}static getDxfUnits(e){switch(e||0){case 0:return Ke.Unitless;case 1:return Ke.Inches;case 2:return Ke.Feet;case 4:return Ke.Millimeters;case 5:return Ke.Centimeters;case 6:return Ke.Meters;default:P.warn("[Dxf] Unsupported $INSUNITS '"+e+"'");break}return Ke.Unitless}static computeLineDistance(e){const i=e.isLineSegments===!0;let s=e.geometry;const n=e.matrixWorld;if(s.index&&(P.debug("[Dxf] Line with id '"+e.id+"' contains index buffer, going to convert it to non-indexed."),s=G.convertGeometryWithIndexedToNonIndexed(s),e.userData.batches&&e.userData.batches.length>0)){P.debug("[Dxf] This line has been merged!");let r=0;e.userData.batches.forEach(a=>{a.positionStart=r,a.positionCount=a.indexCount,a.indexStart=0,a.indexCount=0,r+=a.positionCount})}if(s.index===null){const r=s.attributes.position;if(!r||r.count===0)return;const a=[];if(i)for(let o=0,l=r.count;o<l;o+=2)H.fromBufferAttribute(r,o).applyMatrix4(n),$.fromBufferAttribute(r,o+1).applyMatrix4(n),a[o]=o===0?0:a[o-1],a[o+1]=a[o]+H.distanceTo($);else{a[0]=0;for(let o=1,l=r.count;o<l;o++)H.fromBufferAttribute(r,o-1).applyMatrix4(n),$.fromBufferAttribute(r,o).applyMatrix4(n),a[o]=a[o-1],a[o]+=H.distanceTo($)}s.setAttribute("lineDistance",new p.Float32BufferAttribute(a,1)),e.geometry=s}else P.warn("[Dxf] computeLineDistances only possible with non-indexed BufferGeometry.")}static computeLineDistances(e){const i=Date.now();e.traverse(s=>{const n=s;n.isLine&&n.material instanceof p.ShaderMaterial&&N.computeLineDistance(n)}),P.debug("[Dxf] Computed line distances in "+(Date.now()-i)/1e3+"s")}static mergeDxfObjects(e){const i=Date.now(),s={},n={},r=15e3;let a=0,o=0;const l=()=>{const d=Date.now();for(const u in s){const f=s[u];N.removeEmptyObjectsFromRemovingMarkedObjects2(f.children,f.object),f.children=[]}a=0,o+=Date.now()-d};for(const d in e.layersAndObjects){const u=e.layersAndObjects[d];if(u.length<=1)continue;const f=Date.now(),m={},b=[];for(const y of u){if(y.userData.isSnapObject){b.push(y);continue}let S,w=y;for(;w;){if(w.userData.isLayoutLevelObject){S=w;break}w=w.parent}if(!S)continue;const x=S.name;!m[x]&&(m[x]={object:S,children:[]}),m[x].children.push(y)}for(const y in m){const S=m[y],w=Mt.deepMerge(S.children,S.object,!1,!1,!0),x=w.added,E=w.removed;!s[y]&&(s[y]={object:S.object,children:[]}),!n[y]&&(n[y]={object:S.object,children:[]});const M=E.length>r;if(M){const O=Date.now();N.removeEmptyObjectsFromRemovingMarkedObjects2(E,S.object),o+=Date.now()-O}else a+=E.length;if(E.length===S.children.length)!M&&E.forEach(O=>{s[y].children.push(O)});else{let O=E;E.length>=100&&(O=new Set(E));const T=v=>Array.isArray(O)?O.indexOf(v)>=0:O.has(v);for(let v=0;v<S.children.length;v++){const C=S.children[v];T(C)?!M&&s[y].children.push(C):b.push(C)}}for(let O=0;O<x.length;O++){const T=x[O];b.push(T),n[y].children.push(T)}a>r&&l()}e.layersAndObjects[d]=b,P.debug("[Dxf] Merged layer '"+d+"' in "+(Date.now()-f)/1e3+"s")}a>0&&l();for(const d in n){const u=n[d];!e.root.children.find(m=>m.name===d)&&e.root.add(u.object),u.children.forEach(m=>{u.object.add(m)}),u.children=[]}P.debug("[Dxf] MergeUtils.deepMerge took "+pe.MergeInfo.elapsedTime/1e3+"s"),P.debug("[Dxf] The remove operation of deep merge took "+o/1e3+"s"),P.debug("[Dxf] Deep merge totally took "+(Date.now()-i)/1e3+"s");const h=pe.MergeInfo;P.debug("[Dxf] Totally merged "+h.removedObjects+" objects to "+h.mergedMeshes+"meshes, "+h.mergedLines+"lines, "+h.mergedPoints+"points, "+(h.mergedUnknownTypeObjects?h.mergedUnknownTypeObjects+" unknown type,":" ")+" ")}static async merge(e,i){const s=U.getUpdateProgressFuncAsync(i),n={};e.objects.LAYOUT.forEach(y=>{const S=y;n[S.layoutName]=S,S.directAssociatedLeafObjectSet?.clear()});const r=Date.now(),a={},o={},l=15e3;let h=0,d=0;const u=()=>{const y=Date.now();for(const S in a){const w=a[S];N.removeEmptyObjectsFromRemovingMarkedObjects(w.children,w.object),w.children=[]}h=0,d+=Date.now()-y},f=Object.keys(e.layersAndThreejsObjects).length;let m=0;for(const y in e.layersAndThreejsObjects){const S=e.layersAndThreejsObjects[y];if(S.length<=1){await s(++m/f*100);continue}const w=Date.now(),x={},E=[];for(const T of S){if(T.userData.isSnapObject){E.push(T);continue}let v,C=T;for(;C;){if(C.userData.isLayoutLevelObject){v=C;break}C=C.parent}if(!v)continue;const _=v.name;!x[_]&&(x[_]={object:v,children:[]}),x[_].children.push(T)}const M=Object.keys(x).length;let O=0;for(const T in x){let v;if(T!==N.MODEL_LAYOUT_NAME){const D=n[T];!D.directAssociatedLeafObjectSet&&(D.directAssociatedLeafObjectSet=new Set),v=D.directAssociatedLeafObjectSet}const C=x[T],_=pe.deepMerge(C.children,C.object,!1,!1,!0),A=_.added,I=_.removed;!a[T]&&(a[T]={object:C.object,children:[]}),!o[T]&&(o[T]={object:C.object,children:[]});const B=I.length>l;if(B){const D=Date.now();N.removeEmptyObjectsFromRemovingMarkedObjects(I,C.object),d+=Date.now()-D}else h+=I.length;if(I.length===C.children.length)!B&&I.forEach(D=>{a[T].children.push(D)});else{let D=I;I.length>=100&&(D=new Set(I));const k=z=>Array.isArray(D)?D.indexOf(z)>=0:D.has(z);for(let z=0;z<C.children.length;z++){const se=C.children[z];k(se)?!B&&a[T].children.push(se):(E.push(se),v&&v.add(se))}}for(let D=0;D<A.length;D++){const k=A[D];Q.setSharedVariablesOfObject(k),E.push(k),o[T].children.push(k),v&&v.add(k)}h>l&&u(),await s((m+ ++O/M)/f*100)}await s(++m/f*100),e.layersAndThreejsObjects[y]=E,P.debug("[Dxf] Merged layer '"+y+"' in "+(Date.now()-w)/1e3+"s")}h>0&&u();for(const y in o){const S=o[y],w=e.threejsObject.children.find(x=>x.name===y);if(w){const x=w.children.find(E=>E.name===N.SNAP_GROUP_NAME);if(x&&y!==N.MODEL_LAYOUT_NAME){const E=n[y];!E.directAssociatedLeafObjectSet&&(E.directAssociatedLeafObjectSet=new Set),x.children.forEach(M=>E.directAssociatedLeafObjectSet?.add(M))}}!w&&e.threejsObject.add(S.object),S.children.forEach(x=>{!x.visible&&(x.userData.layerVisible=!1),S.object.add(x),x.updateWorldMatrix(!1,!1)}),S.children=[]}P.debug("[Dxf] MergeUtils.deepMerge took "+pe.MergeInfo.elapsedTime/1e3+"s"),P.debug("[Dxf] The remove operation of deep merge took "+d/1e3+"s"),P.debug("[Dxf] Deep merge totally took "+(Date.now()-r)/1e3+"s");const b=pe.MergeInfo;P.debug("[Dxf] Totally merged "+b.removedObjects+" objects to "+b.mergedMeshes+"meshes, "+b.mergedLines+"lines, "+b.mergedPoints+"points, "+(b.mergedUnknownTypeObjects?b.mergedUnknownTypeObjects+" unknown type,":" ")+" "),s(100)}printStatsInfo(){const e=this.entityTypesAndTimes;for(const n in e)e[n].averageTime=e[n].totalTime/e[n].createCount;P.debug("[Dxf] Entity types and took how much time in ms:",e),P.debug("[Dxf] Entity types and mesh count:",this.statsInfo.entityTypesAndMeshCount);let i=0;if(Object.values(this.statsInfo.entityTypesAndMeshCount).forEach(n=>{i+=n}),this.enableRTC&&P.debug("[Dxf] Totally rebased "+this.statsInfo.rebasedEntityCount+"(out of "+i+") entities"),this.enableMerge){const n=pe.MergeInfo;P.debug("[Dxf] Inner merged "+n.removedObjects+" objects to "+n.mergedMeshes+"meshes, "+n.mergedLines+"lines, "+n.mergedPoints+"points, "+(n.mergedUnknownTypeObjects?n.mergedUnknownTypeObjects+" unknown type,":" ")+"in "+n.elapsedTime/1e3+"s")}const s=(n,r,...a)=>{Object.keys(r).length>0};s("[Dxf] Unsupported entity types and count:",this.statsInfo.unsupportedEntityTypes),s("[Dxf] Unsupported text style names and count:",this.statsInfo.unsupportedTextStyles,". Will use a default style."),s("[Dxf] Unsupported hatch pattern names and count:",this.statsInfo.unsupportedHatchPatterns,". Filling in solid lines instead."),this.statsInfo.unsupportedPolylineCount&&P.warn("[Dxf] Unsupported polyline (with both width and linetype) count: "+this.statsInfo.unsupportedPolylineCount+", linetype will be ignored."),s("[Dxf] Ignored invisible entity types and count:",this.statsInfo.invisibleEntities),s("[Dxf] Ignored frozen layers and entity count:",this.statsInfo.ignoredFrozenLayersAndEntityCount),s("[Dxf] Ignored inserts and count (may because they don't contain anything):",this.statsInfo.ignoredInserts),this.ignorePaperSpace&&s("[Dxf] Ignored paper space entity count:",this.statsInfo.ignoredPaperSpaceEntityTypesAndCount),this.font&&s("[Dxf] Unsupported chars and count:",this.font.getUnsupportedChar())}static statLayoutAndLayerObjects(e){const i=new WeakSet;let s=0;for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&(s++,i.has(l)?console.warn(l):i.add(l))});const n=new WeakSet;let r=0;if(e.threejsObject.traverse(a=>{a.geometry&&(r++,n.has(a)?console.warn(a):n.add(a))}),s!=r)for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&!n.has(l)&&console.warn(l)});P.info("[Dxf] The count of layer objects is "+s+",The count of layout objects is "+r+" ")}static removeEmptyObjectsFromRemovingMarkedObjects(e,i){if(e.length===0)return;const s=n=>{const r=[];for(const a of n){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&r.push(o))}r.length>0&&s(r)};s(e),this.removeEmptyObjectsFromMark(i)}static removeEmptyObjectsFromMark(e){if(e.userData.validCount===0||Q.isEmptyObject(e))return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark(e.children[i])&&++i;return!1}static removeEmptyObjectsFromRemovingMarkedObjects2(e,i){if(e.length===0)return;const s=n=>{const r=[];for(const a of n){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&r.push(o))}r.length>0&&s(r)};s(e),this.removeEmptyObjectsFromMark2(i)}static removeEmptyObjectsFromMark2(e){if(e.userData.validCount===0||e.type===q.Object&&e.children.length===0)return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark2(e.children[i])&&++i;return!1}};g(N,"MODEL_LAYOUT_NAME","Model"),g(N,"SNAP_GROUP_NAME","InvisibleObjectGroupForOSnap"),g(N,"SHOW_SNAP_OBJECT",!1),g(N,"CameraZoomUniform",{value:1}),g(N,"ViewportScaleUniform",{value:1}),g(N,"TransformMatrixUniform",{value:new p.Matrix4}),g(N,"ResolutionUniform",{value:new p.Vector2}),g(N,"LOADLLDATA",!1),g(N,"MaxFragmentUniforms",1024);let Z=N;class fr extends Ht{constructor(e){super();g(this,"viewer");g(this,"overlayRender");g(this,"drawableList");this.drawableList=new ps("compare"),this.viewer=e,this.overlayRender=this.viewer.getOverlayRender(),this.overlayRender?.addDrawableList(this.drawableList)}drawCompareDrawable(e){const i=[],s=[],n=[];for(const l of Object.values(e)){const h=l.box;h&&(l.type===je.Added?i.push(h):l.type===je.Removed?s.push(h):n.push(h))}const r=G.mergeBBoxes(i),a=G.mergeBBoxes(s),o=G.mergeBBoxes(n);this.drawableList.addDrawable(new bt(U.guid(),r,[.1,.9,.2,1])),this.drawableList.addDrawable(new bt(U.guid(),a,[1,.15,.15,1])),this.drawableList.addDrawable(new bt(U.guid(),o,[1,.85,.1,1])),this.viewer.enableRender()}setCompareDrawableVisible(e){this.drawableList.getDrawables().forEach(i=>i.visible=e),this.viewer.enableRender()}}class mn{}const mi=new p.Matrix4,jn=new p.Box3;class Di extends mn{constructor(e){super();g(this,"modelId");g(this,"modelData");g(this,"modelObject");g(this,"bbox");this.modelData=e,this.modelId=e.modelId,this.modelObject=e.dxfData?.threejsObject||e.pdfData?.threejsObject,this.modelObject.name=this.modelId,this.modelObject.userData.modelId=this.modelId}get pdfData(){return this.modelData.pdfData}get dxfData(){return this.modelData.dxfData}get msTransformMatrix(){return this.modelData.msTransformMatrix}set msTransformMatrix(e){this.modelData.msTransformMatrix=e}get loadedEntityCount(){return this.dxfData?.loadedEntityCount||this.pdfData?.loadedEntityCount||0}get header(){return this.dxfData?.header}get viewports(){return this.dxfData?.tables.viewport.viewports}get layers(){const e=this.dxfData||this.pdfData;return e.tables?.layer.layers||e.layers}get layoutViewportsMap(){return this.dxfData?.layoutViewportsMap}getModelObject(){const e=this.dxfData||this.pdfData;if(!e)throw new Error("Failed to find model by modelId '"+this.modelId+"'!");return e.threejsObject}getBBox(){if(!this.bbox){const e=new p.Box3,i=this.getModelObject(),s=new p.Box3;i.updateWorldMatrix(!1,!0);const n=r=>{if(r.userData?.isSnapObject)return;const a=r.geometry;a&&(a.boundingBox||a.computeBoundingBox(),s.copy(a.boundingBox).applyMatrix4(r.matrixWorld),e.union(s));for(const o of r.children)n(o)};n(i),this.bbox=e}return this.bbox}getUnits(){if(!this.dxfData)return Ke.Unitless;const e=this.dxfData.header;if(!e)return P.warn("DxfData or its header is undefined!"),Ke.Unitless;const i=e.$INSUNITS;return Z.getDxfUnits(i)}getModelSpaceExtent(){const e=this.header,i=new p.Vector3,s=new p.Vector3;if(!e){P.error("Header is undefined in "+this.modelId+"!");return}const n=this.viewports;let r=e.$EXTMIN,a=e.$EXTMAX;const o=e.$ANGDIR;if(n&&n.length>0)for(let l=0;l<n.length;l++){const h=n[l];if(h.name.toLocaleUpperCase()==="*ACTIVE"){const{center:d,viewHeight:u,aspectRatio:f}=h,m=u*f,b=Z.getDcs2WcsMatrix(h,o),y=new p.Vector3(d.x,d.y,0);y.applyMatrix4(b),r={x:y.x-m/2,y:y.y-u/2,z:0},a={x:y.x+m/2,y:y.y+u/2,z:0};break}}return i.set(r.x,r.y,r.z),s.set(a.x,a.y,a.z),new p.Box3(i,s)}getLayer(e){if(this.layers)return this.layers[e]}getObjectsByLayer(e){const i=this.dxfData||this.pdfData;return i?.layersAndThreejsObjects&&i.layersAndThreejsObjects[e]}getLayouts(){const e=[];return this.dxfData?.objects.LAYOUT?.forEach(n=>{e.push(n)}),e}getLayoutByName(e){let i;const s=this.getLayouts();for(const n of s)if(n.layoutName===e){i=n;break}return i}getLayoutExtent(e){const i=this.header,s=new p.Vector3,n=new p.Vector3;if(!i)throw new Error("Header is undefined in "+this.modelId+"!");const r=this.getLayoutViewports(e);let a=i.$PEXTMIN,o=i.$PEXTMAX;const l=i.$ANGDIR;if(r&&r.length>0){const h=r.filter(S=>parseInt(S.viewportId)===1);let d;h.length>0?d=h[0]:d=r[0];const{centerPoint:u,width_paperSpace:f,height_paperSpace:m}=d,b=Z.getDcs2WcsMatrix(d,l),y=new p.Vector3(u.x,u.y,0);y.applyMatrix4(b),a={x:y.x-f/2,y:y.y-m/2,z:0},o={x:y.x+f/2,y:y.y+m/2,z:0}}return s.set(a.x,a.y,a.z),n.set(o.x,o.y,o.z),new p.Box3(s,n)}getLayoutViewports(e){const s=this.layoutViewportsMap[e.ownerHandle];return s||[]}getLayoutLevelObject(e){return this.getModelObject()?.children.find(s=>s.name===e)}setVisible(e){const i=this.getModelObject();i.visible=e}setLayerVisible(e,i,s,n){const r=this.getLayer(e);r?r.visible=i:P.warn("[Viewer] Layer '"+e+"' not found from modelData!");const a=this.getObjectsByLayer(e);if(a)for(let o=0;o<a.length;o++){const l=a[o];!(s&&i&&n&&l.userData.visibleMinZoom&&n<l.userData.visibleMinZoom)&&(l.visible=i),(i===!1||l.userData.layerVisible!=null)&&(l.userData.layerVisible=i),l.userData.isSnapObject&&(l.visible?Z.SHOW_SNAP_OBJECT?l.layers.enableAll():l.layers.set(Ue):Z.SHOW_SNAP_OBJECT?l.layers.disableAll():l.layers.disable(Ue))}else P.info("[Viewer] No object found for layer '"+e+"'")}setLayerOpacity(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const n=this.getObjectsByLayer(e);n?n.forEach(r=>{const a=r;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=we.cloneMaterial(a.material));const o=we.cloneMaterial(a.material);we.setMaterialOpacity(o,i),Z.updateMaterialUniforms(o),a.material=o}}):P.info("[Viewer] No object found for layer '"+e+"'")}setLayerColor(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const n=this.getObjectsByLayer(e);n?n.forEach(r=>{const a=r;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=we.cloneMaterial(a.material));const o=we.cloneMaterial(a.material);we.setMaterialColor(o,new p.Color(i)),Z.updateMaterialUniforms(o),a.material=o}}):P.info("[Viewer] No object found for layer '"+e+"'")}resetLayerColor(e){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const s=this.getObjectsByLayer(e);s?s.forEach(n=>{const r=n;r.material&&r.userData.originalMaterial&&(r.material.dispose(),r.material=r.userData.originalMaterial,delete r.userData.originalMaterial)}):P.info("[Viewer] No object found for layer '"+e+"'")}switchTransformMs(e){const i=this.msTransformMatrix;if(mi.identity(),!i||!U.isMatrixValid(i)||i.equals(mi))return;const s=this.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME);s&&(e===Z.MODEL_LAYOUT_NAME?s.applyMatrix4(i):s.applyMatrix4(i.clone().invert()),s.updateMatrixWorld(!0))}activateLayout(e=Z.MODEL_LAYOUT_NAME,i){this.switchTransformMs(e);const s=this.getLayoutByName(e);if(s){if(!i){const n=this.getLayoutViewports(s);let r=[];n.length>0&&(r=n[0].frozenLayerHandles);const a=e!==Z.MODEL_LAYOUT_NAME,o=this.getLayoutLevelObject(e);if(o){const d=[];o.traverse(u=>{this.addSpatialFilterSection(u,this.dxfData);const f=u;if(a&&f.material&&f.geometry){const m=f.userData.layerName;if(this.isLayerFrozenForViewport(m,r))return;d.push(f);let b=-1;const y=this.getObjectsByLayer(m);y&&(b=y.indexOf(f),b>=0&&y.splice(b,1)),b<0&&P.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+m+"', layout '"+e+"'")}}),d.forEach(u=>{u.removeFromParent()})}const l=this.getFilteredViewports(s);P.debug("[Viewer] Active layout:",e,", viewports:",l);const h=Date.now();l.forEach(d=>{this.generateObjectsByViewport(e,d,this)}),P.info("[Viewer] generateObjectsByViewport in "+(Date.now()-h)/1e3+"s")}this.showLayoutObjects(e)}}getFilteredViewports(e){const i=this.getLayoutViewports(e);let s=i.filter(n=>n.viewportId!=="1");return s.length===i.length&&(s=i.filter((n,r)=>r!==0)),s}generateObjectsByViewport(e,i,s,n=[]){const r=i;if(i.viewportId=="1")return;if(!r.psBBox||!r.msToPsMatrix)throw new Error("The bbox or matrix is invalid in the viewport!");Z.TransformMatrixUniform={value:r.msToPsMatrix},Z.ViewportScaleUniform={value:i.viewHeight/i.height_paperSpace};const a=r.psBBox.clone();a.applyMatrix4(r.msToPsMatrix.clone().invert()),a.min.setZ(-1),a.max.setZ(1);const o=this.getObjectsByBoundingBox(a);if(o.length===0)return;const l=r.psBBox.min,h=r.psBBox.max,d=new p.Box2(new p.Vector2(l.x,l.y),new p.Vector2(h.x,h.y)),u=Ft.generateSectionPlanesByBox(d),f=[],m=C=>(!f[C.id]&&(f[C.id]=C.clone(),this.setMaterialUniforms(f[C.id],s.dxfData),Ft.setMaterialSection(f[C.id],u)),f[C.id]),b=C=>{if(Array.isArray(C)){const _=[];return C.forEach(A=>{const I=m(A);_.push(I)}),_}else return m(C)},y=[...n,...i.frozenLayerHandles||[]];let S;if(e!==Z.MODEL_LAYOUT_NAME){const C=r;!C.associatedLeafObjectSet&&(C.associatedLeafObjectSet=new Set),S=C.associatedLeafObjectSet}const w=new p.Group;w.name=r.viewportId;const x=[];if(o.forEach(C=>{const _=C.clone();_.traverse(A=>{const I=A;if(I.material&&I.geometry){const B=I.userData.layerName;if(this.isLayerFrozenForViewport(B,y)){x.push(I);return}I.userData.layerVisible!==!1&&(I.visible=!0),I.material=b(I.material),S?.add(I);const D=s.getObjectsByLayer(B);D?D.push(I):P.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+B+"', layout '"+e+"'")}}),w.add(_)}),S&&S.size===0)return;const E=s.getModelObject();let M=s.getLayoutLevelObject(e);!M&&(M=new p.Group,Q.setSharedVariablesOfObject(M),M.name=e,E?.add(M)),M.add(w),w.applyMatrix4(r.msToPsMatrix),w.updateMatrixWorld(!0);let O=M.children.find(C=>C.name===Z.SNAP_GROUP_NAME);!O&&(O=new p.Group,O.visible=Z.SHOW_SNAP_OBJECT,O.name=Z.SNAP_GROUP_NAME,M.add(O));const T=s.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME),v=T?.children.find(C=>C.name===Z.SNAP_GROUP_NAME);v&&v.traverse(C=>{if(!C.geometry)return;const _=C.userData.layerName;if(this.isLayerFrozenForViewport(_,y)||(jn.makeEmpty(),jn.expandByObject(C),!a.intersectsBox(jn)))return;const A=C.clone();Q.setSharedVariablesOfObject(A);let I=A.parent;const B=mi.identity();for(;I&&I.userData.isLayoutLevelObject!==!0;)B.premultiply(I.matrix),I=I.parent;B.premultiply(r.msToPsMatrix),A.applyMatrix4(B),O?.add(A),S?.add(A);const D=s.getObjectsByLayer(_);D&&D.push(A)}),x.length>0&&Q.removeEmptyObjectsFromRemovingObjects(x,w),w.traverse(C=>{Q.setSharedVariablesOfObject(C),this.addSpatialFilterSection(C,s.dxfData,!0)})}setMaterialUniforms(e,i){e instanceof p.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=Z.CameraZoomUniform),e.uniforms.u_viewportScale&&i?.header.$PSLTSCALE===1&&(e.uniforms.u_viewportScale=Z.ViewportScaleUniform))}getObjectsByBoundingBox(e){const i=[];if(e.isEmpty())return P.warn("[Viewer] bbox is empty !"),i;const s=r=>{const a=Ot.getBoundingBox(r,!1);e.intersectsBox(a)&&i.push(r)},n=this.getLayoutLevelObject(Z.MODEL_LAYOUT_NAME);return n&&n.children.forEach(r=>{r.name!==Z.SNAP_GROUP_NAME&&s(r)}),i}showLayoutObjects(e){let i=0,s=0;const n=this.getModelObject();n.children.forEach(r=>{const a=r.name===e;r.visible=a,a?i++:s++}),P.debug("[Viewer] showLayoutObjects('"+e+"') sets "+i+" layout level object(s) to visible and "+s+" to hidden for model '"+n?.name+"'")}isLayerFrozenForViewport(e,i){const s=this.getLayer(e);return s&&(s.flag&1)>0?!0:!i||i.length<=0?!1:s&&i.indexOf(s.handle)>=0}addSpatialFilterSection(e,i,s=!1){if(e.userData.entityType!=="INSERT"||!e.userData.spatialFilterHandle)return;const n=this.findSpatialFilter(e.userData.spatialFilterHandle,i);if(n){let r=s,a=!1;const o=this.getAnyMaterial(e);if(o&&(o.clippingPlanes&&(r=o.clippingPlanes.length>0),a=o.clipIntersection),r&&a!==n.clipPolylines[0].bReversed){P.warn("[Viewer] Material cannot set clipIntersection to different values at the same time. clipIntersection needs to be set to true here!");return}a=n.clipPolylines[0].bReversed;const l=this.generateSectionsBySpatialFilter(n,e.matrixWorld);if(l){const h=f=>{let m=0;return f.clippingPlanes&&(m=f.clippingPlanes.length),m+l.length>Z.MaxFragmentUniforms},d=new Set,u=f=>{d.has(f.id)||(d.add(f.id),!h(f)&&Ft.setMaterialSection(f,l,r,a))};e.traverse(f=>{const m=f.material;Array.isArray(m)?m.forEach(b=>{u(b)}):m&&u(m)})}}}findSpatialFilter(e,i){const s=i.objects.SPATIAL_FILTER;if(!s)return;let n;for(const r of s)if(r.handle===e){n=r;break}return n}getAnyMaterial(e){const i=e;if(i.material)return Array.isArray(i.material)?i.material[0]:i.material;let s;for(let n=0;n<e.children.length&&(s=this.getAnyMaterial(e.children[n]),!s);n++);return s}generateSectionsBySpatialFilter(e,i){const s=e.clipPolylines[0];if(s.bConcave){P.warn("[Viewer] clipPolyline.bConcave = true is not supported yet in spatialFilter !");return}mi.copy(i),e.localMatrix&&mi.multiply(e.localMatrix);const n=s.polyline,r=[];n.forEach(l=>{const h=l.clone().applyMatrix4(mi);r.push(new p.Vector2(h.x,h.y))});const a=p.ShapeUtils.isClockWise(r),o=!a&&!s.bReversed||a&&s.bReversed;return Ft.generateSectionPlanesByPoints(r,o)}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}highlightObject(e){if(!this.hasObject(e))return;const i=we.clonedHighlightMaterials(e,{depthTest:!1});i&&(e.userData.originalMaterial=e.material,e.material=i)}unHighlightObject(e){if(!this.hasObject(e))return;const i=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(i)?i.forEach(s=>s.dispose()):i instanceof p.Material&&i.dispose()}clearHighlight(){}}class Sr extends mn{constructor(e){super();g(this,"modelId");g(this,"bbox");g(this,"rootObject");g(this,"modelObject");g(this,"highlighUsage");g(this,"transparentUsage");g(this,"edges");g(this,"highlighedObject");this.modelId=e.modelId,this.bbox=e.bbox,this.modelObject=e.object,this.rootObject=new p.Group,this.rootObject.name="rootObject-"+this.modelId,this.rootObject.userData.modelId=this.modelId,this.highlighUsage=new p.Group,this.highlighUsage.name="highlighUsage-"+this.modelId,this.highlighUsage.layers.disable(jt),this.transparentUsage=new p.Group,this.transparentUsage.name="transparentUsage-"+this.modelId,this.transparentUsage.layers.disable(jt),this.rootObject.add(this.modelObject),this.rootObject.add(this.highlighUsage),this.rootObject.add(this.transparentUsage)}setDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&Q.setDoubleSidedMaterialToObject(e)})}revertDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&Q.revertDoubleSidedMaterialToObject(e)})}getModelObject(){return this.rootObject}getBBox(){return!this.bbox&&(this.bbox=new p.Box3,this.bbox.setFromObject(this.getModelObject())),this.bbox}async enableOutline(e,i){e&&!this.edges&&(this.edges=await Q.createOutlines(this.getModelObject(),void 0,i)),this.edges&&this.edges.forEach(s=>s.visible=e)}setObjectColor(e,i){this.hasObject(e)&&e.material.color.set(i)}setObjectOpacity(e,i=.5,s,n){if(this.hasObject(e)){if(e instanceof p.InstancedMesh&&n){const r=this.createInstanceMeshById(e,n,{opacity:i});r.material.opacity*=i,e.userData.instanceId=n,e.userData.transparentedMesh=r,this.transparentUsage.add(r)}else if(pe.isMergedMesh(e)&&s){const r=this.createBatchMeshById(e,s,{opacity:i});r.material.opacity*=i,e.userData.batchId=s,e.userData.transparentedMesh=r,this.transparentUsage.add(r)}else{const r=new p.MeshBasicMaterial({color:0,transparent:!0,opacity:.05});r&&(e.userData.originalMaterial=e.material,e.material=r)}e.userData.isTransparent=!0}}clearObjectOpacity(e,i,s){if(!this.isObjectTransparent(e))return;const{transparentedMesh:n,originalMaterial:r}=e.userData;n&&(this.transparentUsage.remove(n),delete e.userData.batchId,delete e.userData.instanceId,delete e.userData.transparentedMesh),r&&(e.material=r),delete e.userData.isTransparent}isObjectTransparent(e){const{isTransparent:i}=e.userData;return!!i}setOpacity(e=.5){this.getModelObject().traverse(i=>{i instanceof p.Mesh&&this.setObjectOpacity(i,e)})}clearOpacity(){this.getModelObject().traverse(e=>{e instanceof p.Mesh&&this.clearObjectOpacity(e)})}highlightObjectById(e,i,s){if(!this.hasObjectWithId(e))return;const n=this.getModelObject().getObjectById(e);n&&this.highlightObject(n,i,s)}highlightObject(e,i,s){if(!this.hasObject(e))return;const n=new p.Color(vr);if(e instanceof p.InstancedMesh&&s){const r=this.createInstanceMeshById(e,s,{depthTest:!1});r.material.opacity=.7,we.setMaterialColor(r.material,n),e.userData.instanceId=s,e.userData.clonedMesh=r,this.highlighUsage.add(r)}else if(pe.isMergedMesh(e)&&i){const r=this.createBatchMeshById(e,i,{depthTest:!1});r.material.opacity=.7,we.setMaterialColor(r.material,n),e.userData.batchId=i,e.userData.clonedMesh=r,this.highlighUsage.add(r)}else{const r=we.clonedHighlightMaterials(e,{depthTest:!1});r&&(e.userData.originalMaterial=e.material,e.material=r)}e.userData.isHighlight=!0,this.highlighedObject=e}clearHighlight(){if(this.highlighedObject&&this.highlighedObject.userData){const e=this.highlighedObject.userData,{clonedMesh:i,originalMaterial:s,instanceId:n,originalMatrix:r}=e;i&&(i.removeFromParent(),i.geometry.dispose(),delete e.clonedMesh),n&&r&&(this.highlighedObject.setMatrixAt(n,r),delete e.instanceId,delete e.originalMatrix),s&&(this.highlighedObject.material=s,delete e.originalMaterial),delete e.isHighlight}this.highlighUsage.clear(),this.highlighedObject=void 0}setObjectVisible(e,i){this.hasObject(e)&&(e.visible=i)}setVisible(e){this.getModelObject().traverse(i=>{i instanceof p.Mesh&&(i.visible=e)})}hasVisibleObject(){let e=0;return this.modelObject.traverseVisible(i=>{i instanceof p.Mesh&&e++}),e>0}hasInvisibleObject(){let e=0;return this.modelObject.traverse(i=>{i instanceof p.Mesh&&e++}),this.modelObject.traverseVisible(i=>{i instanceof p.Mesh&&e--}),e>0}createBatchMeshById(e,i,{opacity:s=1,depthTest:n=!0}){const r=pe.getBatchByBatchId(e,i);let a="[Viewer] Clicked on merged mesh(id: "+e.id+").";a+=" batchId: "+i+", object name: "+r?.name,r?.userData&&(a+=`
|
|
797
797
|
userData: `+JSON.stringify(r.userData)),r?.parentUserData&&(a+=`
|
|
798
798
|
parentUserData: `+JSON.stringify(r.parentUserData)),P.info(a);const o=we.cloneMaterial(e.material);o.opacity=s,o.transparent=s<1,!n&&(o.depthTest=n,o.depthWrite=n,o.side=p.DoubleSide);const l=pe.cloneGeometryForBatch(e,r),h=new p.Mesh(l,o);return h.applyMatrix4(e.matrixWorld),h.matrixWorldNeedsUpdate=!0,h.name="Cloned mesh for highlighting",h.layers.enableAll(),h}createInstanceMeshById(e,i,{opacity:s=1,depthTest:n=!0}){const r=e,a=new p.Matrix4,o=new p.Matrix4;o.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),r.getMatrixAt(i,a);const l=we.cloneMaterial(r.material);l.opacity=s,l.transparent=s<1,!n&&(l.depthTest=n,l.depthWrite=n,l.side=p.DoubleSide);const h=new p.Mesh(r.geometry.clone(),l);h.applyMatrix4(e.matrixWorld.multiply(a)),h.matrixWorldNeedsUpdate=!0,h.name="Cloned mesh for highlighting",h.layers.enableAll();const d=a.clone();return d.multiplyMatrices(a,o),r.setMatrixAt(i,d),r.instanceMatrix.needsUpdate=!0,r.updateMatrix(),e.userData.originalMatrix=a,h}setClipPlanes(e){this.getModelObject().traverse(i=>{const s=i.material;s&&(Array.isArray(s)?s.forEach(n=>{n.clippingPlanes=e,n.clipIntersection=!1}):(s.clippingPlanes=e,s.clipIntersection=!1))})}getObjectTree(){}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}}class Pa extends p.MeshStandardMaterial{constructor(e){super(e);g(this,"isBimTilesMaterial");g(this,"type");g(this,"uniforms");g(this,"vertexShader");g(this,"fragmentShader");g(this,"stateTexture");g(this,"defaultOutlineColor");g(this,"useBCOutline");g(this,"outlineVisible");this.isBimTilesMaterial=!0,this.type="BimTilesMaterial",this.defaultOutlineColor=new p.Color(Qs[0],Qs[1],Qs[2]),this.useBCOutline=!1,this.outlineVisible=!0;const i=e.stateTexture;this.stateTexture=i;const{uniforms:s,fragmentShader:n,vertexShader:r}=p.ShaderLib.standard;this.uniforms=p.UniformsUtils.merge([s,{uTextureWidth:{value:i.image.width},uTextureHeight:{value:i.image.height},outlineColor:{value:this.defaultOutlineColor}}]),this.uniforms.uStateTexture={value:i},this.vertexShader=r.replace("#include <common>",`
|
|
799
799
|
#include <common>
|
package/dist/dxf-viewer.js
CHANGED
|
@@ -23722,8 +23722,15 @@ class ds extends br {
|
|
|
23722
23722
|
*/
|
|
23723
23723
|
getBBox() {
|
|
23724
23724
|
if (!this.bbox) {
|
|
23725
|
-
const e = new p.Box3(), i = this.getModelObject();
|
|
23726
|
-
|
|
23725
|
+
const e = new p.Box3(), i = this.getModelObject(), s = new p.Box3();
|
|
23726
|
+
i.updateWorldMatrix(!1, !0);
|
|
23727
|
+
const n = (r) => {
|
|
23728
|
+
if (r.userData?.isSnapObject) return;
|
|
23729
|
+
const a = r.geometry;
|
|
23730
|
+
a && (a.boundingBox || a.computeBoundingBox(), s.copy(a.boundingBox).applyMatrix4(r.matrixWorld), e.union(s));
|
|
23731
|
+
for (const o of r.children) n(o);
|
|
23732
|
+
};
|
|
23733
|
+
n(i), this.bbox = e;
|
|
23727
23734
|
}
|
|
23728
23735
|
return this.bbox;
|
|
23729
23736
|
}
|