@flyfish-dev/cad-viewer 0.6.5 → 0.6.6
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 +13 -1
- package/README.zh-CN.md +13 -1
- package/dist/cad-viewer.es.js +2299 -2240
- package/dist/cad-viewer.es.js.map +1 -1
- package/dist/cad-viewer.umd.cjs +6 -6
- package/dist/cad-viewer.umd.cjs.map +1 -1
- package/dist/types/core/bounds.d.ts +9 -0
- package/dist/types/core/bounds.d.ts.map +1 -0
- package/dist/types/core/types.d.ts +1 -0
- package/dist/types/core/types.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/viewer/CadCanvasRenderer.d.ts +5 -4
- package/dist/types/viewer/CadCanvasRenderer.d.ts.map +1 -1
- package/dist/types/viewer/CadViewer.d.ts +2 -2
- package/dist/types/viewer/CadViewer.d.ts.map +1 -1
- package/dist/types/viewer/CadWebGLRenderer.d.ts +3 -2
- package/dist/types/viewer/CadWebGLRenderer.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/cad-viewer.umd.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
(function(v,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],M):(v=typeof globalThis<"u"?globalThis:v||self,M(v.LightweightCadViewer={},v.DwfViewerPackage))})(this,function(v,M){"use strict";var ur=Object.defineProperty;var mr=(v,M,T)=>M in v?ur(v,M,{enumerable:!0,configurable:!0,writable:!0,value:T}):v[M]=T;var u=(v,M,T)=>mr(v,typeof M!="symbol"?M+"":M,T);async function T(t){if(t.buffer instanceof Uint8Array)return t.buffer;if(t.buffer instanceof ArrayBuffer)return new Uint8Array(t.buffer);if(t.file)return new Uint8Array(await t.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function Rt(t){return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.slice().buffer}function X(t){var r;const e=t.fileName??((r=t.file)==null?void 0:r.name)??"",n=e.lastIndexOf(".");return n>=0?e.slice(n+1).toLowerCase():""}function R(t,e){const n=X(t);if(n==="dwg")return"dwg";if(n==="dxf")return"dxf";if(n==="dwfx")return"dwfx";if(n==="xps")return"xps";if(n==="dwf")return"dwf";if(e&&e.byteLength>=6){const r=Xe(e.slice(0,6));if(/^AC10/.test(r))return"dwg";if(e[0]===80&&e[1]===75)return"dwfx";const i=Xe(e.slice(0,Math.min(e.byteLength,2048))).toUpperCase();if(i.includes("SECTION")&&i.includes("ENTITIES"))return"dxf";if(i.includes("DWF"))return"dwf"}return"unknown"}function Xe(t){return Array.from(t,e=>e>=32&&e<=126?String.fromCharCode(e):" ").join("")}class je{constructor(e=[]){u(this,"loaders",[]);for(const n of e)this.register(n)}register(e){const n=this.loaders.findIndex(r=>r.id===e.id);return n>=0?this.loaders.splice(n,1,e):this.loaders.push(e),this}unregister(e){const n=this.loaders.findIndex(r=>r.id===e);return n>=0&&this.loaders.splice(n,1),this}list(){return[...this.loaders]}async detect(e){const n=await T(e),r=R(e,n),i=this.loaders.find(s=>s.formats.includes(r)&&s.accepts(e,n));if(i)return{loader:i,bytes:n,format:r};const o=this.loaders.find(s=>s.accepts(e,n));if(o)return{loader:o,bytes:n,format:r};throw new Error(`No CAD loader registered for ${r==="unknown"?"this file":r.toUpperCase()}.`)}async load(e,n={}){const{loader:r,bytes:i}=await this.detect(e);return r.load({...e,buffer:i},n)}}const Ot="wasm/dwg-worker.js";class $e{constructor(){u(this,"worker");u(this,"sequence",0);u(this,"pending",new Map)}load(e,n,r={}){var l,f;if(!ie())throw new Error("Web Worker is not available in this runtime.");const i=this.ensureWorker(r),o=++this.sequence,s=Math.max(0,Number(r.workerTimeoutMs??0)),a=r.fileName??n.fileName??((l=n.file)==null?void 0:l.name),c=zt(e,n,r);return(f=r.onProgress)==null||f.call(r,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:e.byteLength}),new Promise((h,d)=>{var g;if((g=r.signal)!=null&&g.aborted){d(oe());return}const m={resolve:h,reject:d,onProgress:r.onProgress,signal:r.signal};s>0&&(m.timer=setTimeout(()=>{this.pending.delete(o),this.resetWorker(),d(new Error(`DWG worker timed out after ${s} ms.`))},s)),r.signal&&(m.abortHandler=()=>{this.pending.delete(o),this.resetWorker(),d(oe())},r.signal.addEventListener("abort",m.abortHandler,{once:!0})),this.pending.set(o,m);try{i.postMessage({type:"load",requestId:o,bytes:c,fileName:a,options:Ge(r)},[c])}catch(S){this.pending.delete(o),se(m),d(S instanceof Error?S:new Error(String(S)))}})}preload(e={}){var o;if(!ie())return Promise.reject(new Error("Web Worker is not available in this runtime."));const n=this.ensureWorker(e),r=++this.sequence,i=Math.max(0,Number(e.workerTimeoutMs??0));return(o=e.onProgress)==null||o.call(e,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((s,a)=>{var l;if((l=e.signal)!=null&&l.aborted){a(oe());return}const c={resolve:()=>s(),reject:a,onProgress:e.onProgress,signal:e.signal};i>0&&(c.timer=setTimeout(()=>{this.pending.delete(r),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${i} ms.`))},i)),e.signal&&(c.abortHandler=()=>{this.pending.delete(r),this.resetWorker(),a(oe())},e.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(r,c);try{n.postMessage({type:"warmup",requestId:r,options:Ge(e)})}catch(f){this.pending.delete(r),se(c),a(f instanceof Error?f:new Error(String(f)))}})}terminate(){this.resetWorker()}ensureWorker(e){return this.worker||(this.worker=Wt(e),this.worker.onmessage=n=>this.handleMessage(n.data),this.worker.onerror=n=>{const r=n.message||"DWG worker failed.";this.rejectAll(new Error(r)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(e){var i,o;if(e.type==="ready")return;const n=this.pending.get(e.requestId);if(!n)return;if(e.type==="progress"){(i=n.onProgress)==null||i.call(n,e.progress);return}if(this.pending.delete(e.requestId),se(n),e.type==="result"){n.resolve(e.result);return}if(e.type==="warmup-result"){(o=n.onProgress)==null||o.call(n,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:e.elapsedMs}),n.resolve(void 0);return}const r=new Error(e.error.message);r.name=e.error.name||"DwgWorkerError",e.error.stack&&(r.stack=e.error.stack),n.reject(r)}rejectAll(e){for(const[,n]of this.pending)se(n),n.reject(e);this.pending.clear()}resetWorker(e=!0){var n;e&&this.rejectAll(new Error("DWG worker was terminated.")),(n=this.worker)==null||n.terminate(),this.worker=void 0}}function ie(){return typeof Worker<"u"&&typeof URL<"u"}function Wt(t){return t.workerFactory?t.workerFactory():new Worker(Yt(t.workerUrl),{type:"module",name:"lightweight-cad-dwg-loader"})}function Ge(t){return{wasmPath:_t(t.wasmPath),includePaperSpace:t.includePaperSpace,maxInsertDepth:t.maxInsertDepth,keepRaw:!!t.keepRaw}}function zt(t,e,n){return!!e.file||n.transferInputBuffer===!0?Rt(t):t.slice().buffer}function se(t){t.timer&&clearTimeout(t.timer),t.signal&&t.abortHandler&&t.signal.removeEventListener("abort",t.abortHandler)}function oe(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const t=new Error("DWG loading was aborted.");return t.name="AbortError",t}function _t(t){const e=((t==null?void 0:t.trim())||"/wasm").replace(/\/+$/,"");return e===""?Ze():qe(e)?e:e.startsWith("/")?`${Ze()}${e}`:new URL(e,we()).href.replace(/\/+$/,"")}function Yt(t){if(t instanceof URL)return t;const e=(t==null?void 0:t.trim())||Ot;return qe(e)?e:new URL(e,we()).href}function we(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function Ze(){return typeof location<"u"&&location.origin?location.origin:new URL(we()).origin}function qe(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)}class Ke{constructor(e={}){u(this,"id","dwg");u(this,"label","DWG / LibreDWG WebAssembly");u(this,"formats",["dwg"]);u(this,"defaults");u(this,"workerClient",new $e);this.defaults={useWorker:!0,...e}}accepts(e,n){return X(e)==="dwg"?!0:R(e,n)==="dwg"}async load(e,n={}){var s,a;const r={...this.defaults,...n};(s=r.onProgress)==null||s.call(r,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const i=await T(e),o=e.fileName??((a=e.file)==null?void 0:a.name);if(r.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!ie())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(i,e,{...r,fileName:o})}catch(c){throw Vt(c)?c:Ht(c)}}terminateWorker(){this.workerClient.terminate()}preload(e={}){const n={...this.defaults,...e};return n.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(n)}}function Vt(t){return t instanceof Error&&t.name==="AbortError"}function Ht(t){const e=t instanceof Error?t.message:String(t);return new Error(`${e} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function ae(t){return{format:t.format,sourceName:t.sourceName,units:t.units,header:t.header??{},layers:t.layers??{},lineTypes:t.lineTypes??{},blocks:t.blocks??{},entities:t.entities??[],pages:t.pages,savedView:t.savedView,metadata:t.metadata??{},warnings:t.warnings??[],raw:t.raw}}function O(t){switch(String(t??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function ce(t,e,n={}){const r=e??String(t.type??t.entityType??t.objectName??"UNKNOWN").toUpperCase(),i=n.includeUnknownProperties===!1?{type:r,kind:O(r)}:{...t,type:r,kind:O(r)};n.keepRaw&&(i.raw=t),i.handle=P(t.handle??t.id),i.layer=P(t.layer??t.layerName),i.lineType=P(t.lineType??t.linetype),i.lineTypeScale=b(t.lineTypeScale??t.linetypeScale??t.ltscale)??i.lineTypeScale,i.flag=b(t.flag??t.flags)??i.flag;const o=t.isClosed===!0||t.closed===!0||t.shape===!0,s=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D|SPLINE)$/.test(r),a=r==="LWPOLYLINE";(o||s&&(Number(i.flag??0)&1)===1||a&&(Number(i.flag??0)&512)===512)&&(i.isClosed=!0);const c=n.numericColorMode??"auto",l=b(t.color),f=b(t.colorIndex??t.colorNumber??t.aci??t.aciColor??t.color_index);i.colorIndex=f??(c!=="rgb"&&l!==void 0&&Math.abs(l)<=257?l:void 0);const h=t.trueColor??t.true_color??t.truecolor??t.colorRGB??t.colorRgb??t.rgbColor??t.rgb,d=l!==void 0&&l>=0&&l<=16777215&&(c==="rgb"||c==="auto"&&Math.abs(l)>257);i.trueColor=h??(d?l:void 0),(typeof t.color=="string"||typeof t.color=="number")&&(i.color=t.color),i.colorNumber=b(t.colorNumber)??i.colorNumber,i.colorName=P(t.colorName??t.color_name)??i.colorName,i.fillColor=t.fillColor??t.fill_color,i.fillColorIndex=b(t.fillColorIndex??t.fill_color_index??t.fillColorNumber)??i.fillColorIndex,i.opacity=b(t.opacity??t.alpha)??i.opacity,i.lineweight=b(t.lineweight??t.lineWeight),i.isVisible=!(t.isVisible===!1||t.visible===!1),i.startPoint=N(t.startPoint??t.start??t.p0??t.from)??i.startPoint,i.endPoint=N(t.endPoint??t.end??t.p1??t.to)??i.endPoint,i.center=N(t.center??t.centerPoint)??i.center,i.insertionPoint=N(t.insertionPoint??t.position??t.location??t.point??t.basePoint)??i.insertionPoint,i.radius=b(t.radius)??i.radius,i.startAngle=b(t.startAngle??t.start_angle)??i.startAngle,i.endAngle=b(t.endAngle??t.end_angle)??i.endAngle,i.majorAxisEndPoint=N(t.majorAxisEndPoint??t.majorAxis??t.major)??i.majorAxisEndPoint,i.axisRatio=b(t.axisRatio??t.ratio)??i.axisRatio,i.height=b(t.height??t.textHeight)??i.height,i.textHeight=b(t.textHeight??t.height)??i.textHeight,i.rotation=b(t.rotation??t.angle)??i.rotation,i.text=P(t.text??t.value??t.string??t.contents)??i.text,i.name=P(t.name??t.blockName)??i.name,i.blockName=P(t.blockName??t.name)??i.blockName;const m=xe(t.vertices??t.points);m.length>0&&(i.vertices=m);const g=xe(t.controlPoints??t.control_points);g.length>0&&(i.controlPoints=g);const S=xe(t.fitPoints??t.fit_points);S.length>0&&(i.fitPoints=S);const y=t.attribs??t.attributes;return Array.isArray(y)&&(i.attribs=y.filter(x=>!!x&&typeof x=="object").map(x=>ce(x,void 0,n))),i}function N(t){if(!t||typeof t!="object")return;const e=t,n=Number(e.x??e.X??e[0]),r=Number(e.y??e.Y??e[1]),i=e.z??e.Z??e[2],o=i===void 0?void 0:Number(i);if(!(!Number.isFinite(n)||!Number.isFinite(r)))return Number.isFinite(o)?{x:n,y:r,z:o}:{x:n,y:r}}function xe(t){if(!Array.isArray(t))return[];const e=[];for(const n of t){const r=N(n);if(!r)continue;const i=n,o=r,s=b(i.bulge);s!==void 0&&(o.bulge=s);const a=b(i.startWidth??i.start_width);a!==void 0&&(o.startWidth=a);const c=b(i.endWidth??i.end_width);c!==void 0&&(o.endWidth=c),e.push(o)}return e}function J(t){var n;const e={};for(const r of t.entities){const i=String(r.type??"UNKNOWN").toUpperCase();e[i]=(e[i]??0)+1}return{format:t.format,sourceName:t.sourceName,entityCount:t.entities.length,layerCount:Object.keys(t.layers).length,blockCount:Object.keys(t.blocks).length,pageCount:((n=t.pages)==null?void 0:n.length)??0,byType:e,warnings:[...t.warnings]}}function Ce(t){if(t.isClosed===!0)return!0;const e=String(t.type??"").toUpperCase(),n=Number(t.flag??0);return e==="LWPOLYLINE"?(n&512)===512:/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(e)?(n&1)===1:!1}function Pe(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function Je(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function Ut(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e,e.handle&&(t[e.handle]=e,t[e.handle.toLowerCase()]=e))}function Xt(t){return t!=null&&t.length?t.flatMap(e=>e.entities.map(n=>({...n,pageIndex:e.index}))):[]}function b(t){const e=Number(t);return Number.isFinite(e)?e:void 0}function P(t){if(typeof t!="string"&&typeof t!="number")return;const e=String(t);return e.length>0?e:void 0}function B(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function j(t){return Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&t.maxX>=t.minX&&t.maxY>=t.minY}function C(t,e){p(e)&&(t.minX=Math.min(t.minX,e.x),t.minY=Math.min(t.minY,e.y),t.maxX=Math.max(t.maxX,e.x),t.maxY=Math.max(t.maxY,e.y))}function Qe(t,e,n){if(!p(e)||!Number.isFinite(n))return;const r=Math.abs(n);C(t,{x:e.x-r,y:e.y-r}),C(t,{x:e.x+r,y:e.y+r})}function et(t,e=.02,n=1e-6){if(!j(t))return{minX:-10,minY:-10,maxX:10,maxY:10};const r=Math.max((t.maxX-t.minX)*e,n),i=Math.max((t.maxY-t.minY)*e,n);return{minX:t.minX-r,minY:t.minY-i,maxX:t.maxX+r,maxY:t.maxY+i}}function p(t){return!!t&&typeof t=="object"&&Number.isFinite(t.x)&&Number.isFinite(t.y)}function k(t){return{x:t.x,y:t.y}}function W(t){return t*Math.PI/180}function Q(t,e,n,r,i=!0,o=64){if(!p(t)||!Number.isFinite(e))return[];let s=n,a=r;if(!Number.isFinite(s)||!Number.isFinite(a))return[];(Math.abs(s)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(s=W(s),a=W(a)),i&&a<s&&(a+=Math.PI*2),!i&&s<a&&(s+=Math.PI*2);const c=a-s,l=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*o))),f=[];for(let h=0;h<=l;h++){const d=s+c*(h/l);f.push({x:t.x+Math.cos(d)*e,y:t.y+Math.sin(d)*e})}return f}function le(t,e,n=1,r=0,i=Math.PI*2,o=96){if(!p(t)||!p(e))return[];const s=Math.hypot(e.x,e.y);if(!Number.isFinite(s)||s<=0)return[];const a=s*(Number.isFinite(n)&&n>0?n:1),c=Math.atan2(e.y,e.x);let l=Number.isFinite(r)?r:0,f=Number.isFinite(i)?i:Math.PI*2;(Math.abs(l)>Math.PI*2+1e-6||Math.abs(f)>Math.PI*2+1e-6)&&(l=W(l),f=W(f)),f<l&&(f+=Math.PI*2);const h=Math.max(12,Math.min(256,Math.ceil(Math.abs(f-l)/(Math.PI*2)*o))),d=[],m=Math.cos(c),g=Math.sin(c);for(let S=0;S<=h;S++){const y=l+(f-l)*(S/h),x=Math.cos(y)*s,L=Math.sin(y)*a;d.push({x:t.x+x*m-L*g,y:t.y+x*g+L*m})}return d}function tt(t,e,n=0,r=16){if(!Number.isFinite(n)||Math.abs(n)<1e-12)return[k(t),k(e)];const i=Math.hypot(e.x-t.x,e.y-t.y);if(i<=1e-12)return[k(t),k(e)];const o=4*Math.atan(n),s=Math.abs(i/(2*Math.sin(o/2))),a={x:(t.x+e.x)/2,y:(t.y+e.y)/2},c=(e.x-t.x)/i,l=(e.y-t.y)/i,f=n>=0?1:-1,h=Math.sqrt(Math.max(s*s-(i/2)**2,0)),d={x:a.x-f*l*h,y:a.y+f*c*h},m=Math.atan2(t.y-d.y,t.x-d.x),g=Math.atan2(e.y-d.y,e.x-d.x);return Q(d,s,m,g,n>=0,r)}function nt(t){return t.replace(/\\P/g,`
|
|
2
|
-
`).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function
|
|
1
|
+
(function(v,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],M):(v=typeof globalThis<"u"?globalThis:v||self,M(v.LightweightCadViewer={},v.DwfViewerPackage))})(this,function(v,M){"use strict";var Nr=Object.defineProperty;var Mr=(v,M,A)=>M in v?Nr(v,M,{enumerable:!0,configurable:!0,writable:!0,value:A}):v[M]=A;var u=(v,M,A)=>Mr(v,typeof M!="symbol"?M+"":M,A);async function A(t){if(t.buffer instanceof Uint8Array)return t.buffer;if(t.buffer instanceof ArrayBuffer)return new Uint8Array(t.buffer);if(t.file)return new Uint8Array(await t.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function Yt(t){return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.slice().buffer}function H(t){var r;const e=t.fileName??((r=t.file)==null?void 0:r.name)??"",n=e.lastIndexOf(".");return n>=0?e.slice(n+1).toLowerCase():""}function O(t,e){const n=H(t);if(n==="dwg")return"dwg";if(n==="dxf")return"dxf";if(n==="dwfx")return"dwfx";if(n==="xps")return"xps";if(n==="dwf")return"dwf";if(e&&e.byteLength>=6){const r=$e(e.slice(0,6));if(/^AC10/.test(r))return"dwg";if(e[0]===80&&e[1]===75)return"dwfx";const i=$e(e.slice(0,Math.min(e.byteLength,2048))).toUpperCase();if(i.includes("SECTION")&&i.includes("ENTITIES"))return"dxf";if(i.includes("DWF"))return"dwf"}return"unknown"}function $e(t){return Array.from(t,e=>e>=32&&e<=126?String.fromCharCode(e):" ").join("")}class Ge{constructor(e=[]){u(this,"loaders",[]);for(const n of e)this.register(n)}register(e){const n=this.loaders.findIndex(r=>r.id===e.id);return n>=0?this.loaders.splice(n,1,e):this.loaders.push(e),this}unregister(e){const n=this.loaders.findIndex(r=>r.id===e);return n>=0&&this.loaders.splice(n,1),this}list(){return[...this.loaders]}async detect(e){const n=await A(e),r=O(e,n),i=this.loaders.find(o=>o.formats.includes(r)&&o.accepts(e,n));if(i)return{loader:i,bytes:n,format:r};const s=this.loaders.find(o=>o.accepts(e,n));if(s)return{loader:s,bytes:n,format:r};throw new Error(`No CAD loader registered for ${r==="unknown"?"this file":r.toUpperCase()}.`)}async load(e,n={}){const{loader:r,bytes:i}=await this.detect(e);return r.load({...e,buffer:i},n)}}const Xt="wasm/dwg-worker.js";class Ze{constructor(){u(this,"worker");u(this,"sequence",0);u(this,"pending",new Map)}load(e,n,r={}){var l,f;if(!ie())throw new Error("Web Worker is not available in this runtime.");const i=this.ensureWorker(r),s=++this.sequence,o=Math.max(0,Number(r.workerTimeoutMs??0)),a=r.fileName??n.fileName??((l=n.file)==null?void 0:l.name),c=Ht(e,n,r);return(f=r.onProgress)==null||f.call(r,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:e.byteLength}),new Promise((d,h)=>{var g;if((g=r.signal)!=null&&g.aborted){h(oe());return}const m={resolve:d,reject:h,onProgress:r.onProgress,signal:r.signal};o>0&&(m.timer=setTimeout(()=>{this.pending.delete(s),this.resetWorker(),h(new Error(`DWG worker timed out after ${o} ms.`))},o)),r.signal&&(m.abortHandler=()=>{this.pending.delete(s),this.resetWorker(),h(oe())},r.signal.addEventListener("abort",m.abortHandler,{once:!0})),this.pending.set(s,m);try{i.postMessage({type:"load",requestId:s,bytes:c,fileName:a,options:qe(r)},[c])}catch(k){this.pending.delete(s),se(m),h(k instanceof Error?k:new Error(String(k)))}})}preload(e={}){var s;if(!ie())return Promise.reject(new Error("Web Worker is not available in this runtime."));const n=this.ensureWorker(e),r=++this.sequence,i=Math.max(0,Number(e.workerTimeoutMs??0));return(s=e.onProgress)==null||s.call(e,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((o,a)=>{var l;if((l=e.signal)!=null&&l.aborted){a(oe());return}const c={resolve:()=>o(),reject:a,onProgress:e.onProgress,signal:e.signal};i>0&&(c.timer=setTimeout(()=>{this.pending.delete(r),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${i} ms.`))},i)),e.signal&&(c.abortHandler=()=>{this.pending.delete(r),this.resetWorker(),a(oe())},e.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(r,c);try{n.postMessage({type:"warmup",requestId:r,options:qe(e)})}catch(f){this.pending.delete(r),se(c),a(f instanceof Error?f:new Error(String(f)))}})}terminate(){this.resetWorker()}ensureWorker(e){return this.worker||(this.worker=Vt(e),this.worker.onmessage=n=>this.handleMessage(n.data),this.worker.onerror=n=>{const r=n.message||"DWG worker failed.";this.rejectAll(new Error(r)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(e){var i,s;if(e.type==="ready")return;const n=this.pending.get(e.requestId);if(!n)return;if(e.type==="progress"){(i=n.onProgress)==null||i.call(n,e.progress);return}if(this.pending.delete(e.requestId),se(n),e.type==="result"){n.resolve(e.result);return}if(e.type==="warmup-result"){(s=n.onProgress)==null||s.call(n,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:e.elapsedMs}),n.resolve(void 0);return}const r=new Error(e.error.message);r.name=e.error.name||"DwgWorkerError",e.error.stack&&(r.stack=e.error.stack),n.reject(r)}rejectAll(e){for(const[,n]of this.pending)se(n),n.reject(e);this.pending.clear()}resetWorker(e=!0){var n;e&&this.rejectAll(new Error("DWG worker was terminated.")),(n=this.worker)==null||n.terminate(),this.worker=void 0}}function ie(){return typeof Worker<"u"&&typeof URL<"u"}function Vt(t){return t.workerFactory?t.workerFactory():new Worker(jt(t.workerUrl),{type:"module",name:"lightweight-cad-dwg-loader"})}function qe(t){return{wasmPath:Ut(t.wasmPath),includePaperSpace:t.includePaperSpace,maxInsertDepth:t.maxInsertDepth,keepRaw:!!t.keepRaw}}function Ht(t,e,n){return!!e.file||n.transferInputBuffer===!0?Yt(t):t.slice().buffer}function se(t){t.timer&&clearTimeout(t.timer),t.signal&&t.abortHandler&&t.signal.removeEventListener("abort",t.abortHandler)}function oe(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const t=new Error("DWG loading was aborted.");return t.name="AbortError",t}function Ut(t){const e=((t==null?void 0:t.trim())||"/wasm").replace(/\/+$/,"");return e===""?Ke():Je(e)?e:e.startsWith("/")?`${Ke()}${e}`:new URL(e,ye()).href.replace(/\/+$/,"")}function jt(t){if(t instanceof URL)return t;const e=(t==null?void 0:t.trim())||Xt;return Je(e)?e:new URL(e,ye()).href}function ye(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function Ke(){return typeof location<"u"&&location.origin?location.origin:new URL(ye()).origin}function Je(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)}class Qe{constructor(e={}){u(this,"id","dwg");u(this,"label","DWG / LibreDWG WebAssembly");u(this,"formats",["dwg"]);u(this,"defaults");u(this,"workerClient",new Ze);this.defaults={useWorker:!0,...e}}accepts(e,n){return H(e)==="dwg"?!0:O(e,n)==="dwg"}async load(e,n={}){var o,a;const r={...this.defaults,...n};(o=r.onProgress)==null||o.call(r,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const i=await A(e),s=e.fileName??((a=e.file)==null?void 0:a.name);if(r.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!ie())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(i,e,{...r,fileName:s})}catch(c){throw $t(c)?c:Gt(c)}}terminateWorker(){this.workerClient.terminate()}preload(e={}){const n={...this.defaults,...e};return n.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(n)}}function $t(t){return t instanceof Error&&t.name==="AbortError"}function Gt(t){const e=t instanceof Error?t.message:String(t);return new Error(`${e} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function ae(t){return{format:t.format,sourceName:t.sourceName,units:t.units,header:t.header??{},layers:t.layers??{},lineTypes:t.lineTypes??{},blocks:t.blocks??{},entities:t.entities??[],pages:t.pages,savedView:t.savedView,metadata:t.metadata??{},warnings:t.warnings??[],raw:t.raw}}function U(t){switch(String(t??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function ce(t,e,n={}){const r=e??String(t.type??t.entityType??t.objectName??"UNKNOWN").toUpperCase(),i=n.includeUnknownProperties===!1?{type:r,kind:U(r)}:{...t,type:r,kind:U(r)};n.keepRaw&&(i.raw=t),i.handle=C(t.handle??t.id),i.layer=C(t.layer??t.layerName),i.lineType=C(t.lineType??t.linetype),i.lineTypeScale=b(t.lineTypeScale??t.linetypeScale??t.ltscale)??i.lineTypeScale,i.flag=b(t.flag??t.flags)??i.flag;const s=t.isClosed===!0||t.closed===!0||t.shape===!0,o=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D|SPLINE)$/.test(r),a=r==="LWPOLYLINE";(s||o&&(Number(i.flag??0)&1)===1||a&&(Number(i.flag??0)&512)===512)&&(i.isClosed=!0);const c=n.numericColorMode??"auto",l=b(t.color),f=b(t.colorIndex??t.colorNumber??t.aci??t.aciColor??t.color_index);i.colorIndex=f??(c!=="rgb"&&l!==void 0&&Math.abs(l)<=257?l:void 0);const d=t.trueColor??t.true_color??t.truecolor??t.colorRGB??t.colorRgb??t.rgbColor??t.rgb,h=l!==void 0&&l>=0&&l<=16777215&&(c==="rgb"||c==="auto"&&Math.abs(l)>257);i.trueColor=d??(h?l:void 0),(typeof t.color=="string"||typeof t.color=="number")&&(i.color=t.color),i.colorNumber=b(t.colorNumber)??i.colorNumber,i.colorName=C(t.colorName??t.color_name)??i.colorName,i.fillColor=t.fillColor??t.fill_color,i.fillColorIndex=b(t.fillColorIndex??t.fill_color_index??t.fillColorNumber)??i.fillColorIndex,i.opacity=b(t.opacity??t.alpha)??i.opacity,i.lineweight=b(t.lineweight??t.lineWeight),i.isVisible=!(t.isVisible===!1||t.visible===!1),i.startPoint=S(t.startPoint??t.start??t.p0??t.from)??i.startPoint,i.endPoint=S(t.endPoint??t.end??t.p1??t.to)??i.endPoint,i.center=S(t.center??t.centerPoint)??i.center,i.insertionPoint=S(t.insertionPoint??t.position??t.location??t.point??t.basePoint)??i.insertionPoint,i.radius=b(t.radius)??i.radius,i.startAngle=b(t.startAngle??t.start_angle)??i.startAngle,i.endAngle=b(t.endAngle??t.end_angle)??i.endAngle,i.majorAxisEndPoint=S(t.majorAxisEndPoint??t.majorAxis??t.major)??i.majorAxisEndPoint,i.axisRatio=b(t.axisRatio??t.ratio)??i.axisRatio,i.height=b(t.height??t.textHeight)??i.height,i.textHeight=b(t.textHeight??t.height)??i.textHeight,i.rotation=b(t.rotation??t.angle)??i.rotation,i.text=C(t.text??t.value??t.string??t.contents)??i.text,i.name=C(t.name??t.blockName)??i.name,i.blockName=C(t.blockName??t.name)??i.blockName;const m=ve(t.vertices??t.points);m.length>0&&(i.vertices=m);const g=ve(t.controlPoints??t.control_points);g.length>0&&(i.controlPoints=g);const k=ve(t.fitPoints??t.fit_points);k.length>0&&(i.fitPoints=k);const y=t.attribs??t.attributes;return Array.isArray(y)&&(i.attribs=y.filter(x=>!!x&&typeof x=="object").map(x=>ce(x,void 0,n))),i}function S(t){if(!t||typeof t!="object")return;const e=t,n=Number(e.x??e.X??e[0]),r=Number(e.y??e.Y??e[1]),i=e.z??e.Z??e[2],s=i===void 0?void 0:Number(i);if(!(!Number.isFinite(n)||!Number.isFinite(r)))return Number.isFinite(s)?{x:n,y:r,z:s}:{x:n,y:r}}function ve(t){if(!Array.isArray(t))return[];const e=[];for(const n of t){const r=S(n);if(!r)continue;const i=n,s=r,o=b(i.bulge);o!==void 0&&(s.bulge=o);const a=b(i.startWidth??i.start_width);a!==void 0&&(s.startWidth=a);const c=b(i.endWidth??i.end_width);c!==void 0&&(s.endWidth=c),e.push(s)}return e}function J(t){var n;const e={};for(const r of t.entities){const i=String(r.type??"UNKNOWN").toUpperCase();e[i]=(e[i]??0)+1}return{format:t.format,sourceName:t.sourceName,entityCount:t.entities.length,layerCount:Object.keys(t.layers).length,blockCount:Object.keys(t.blocks).length,pageCount:((n=t.pages)==null?void 0:n.length)??0,byType:e,warnings:[...t.warnings]}}function we(t){if(t.isClosed===!0)return!0;const e=String(t.type??"").toUpperCase(),n=Number(t.flag??0);return e==="LWPOLYLINE"?(n&512)===512:/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(e)?(n&1)===1:!1}function xe(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function et(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function Zt(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e,e.handle&&(t[e.handle]=e,t[e.handle.toLowerCase()]=e))}function qt(t){return t!=null&&t.length?t.flatMap(e=>e.entities.map(n=>({...n,pageIndex:e.index}))):[]}function b(t){const e=Number(t);return Number.isFinite(e)?e:void 0}function C(t){if(typeof t!="string"&&typeof t!="number")return;const e=String(t);return e.length>0?e:void 0}function B(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function I(t){return Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&t.maxX>=t.minX&&t.maxY>=t.minY}function N(t,e){p(e)&&(t.minX=Math.min(t.minX,e.x),t.minY=Math.min(t.minY,e.y),t.maxX=Math.max(t.maxX,e.x),t.maxY=Math.max(t.maxY,e.y))}function Kt(t,e,n){if(!p(e)||!Number.isFinite(n))return;const r=Math.abs(n);N(t,{x:e.x-r,y:e.y-r}),N(t,{x:e.x+r,y:e.y+r})}function tt(t,e){I(e)&&(N(t,{x:e.minX,y:e.minY}),N(t,{x:e.maxX,y:e.maxY}))}function nt(t,e=.02,n=1e-6){if(!I(t))return{minX:-10,minY:-10,maxX:10,maxY:10};const r=Math.max((t.maxX-t.minX)*e,n),i=Math.max((t.maxY-t.minY)*e,n);return{minX:t.minX-r,minY:t.minY-i,maxX:t.maxX+r,maxY:t.maxY+i}}function p(t){return!!t&&typeof t=="object"&&Number.isFinite(t.x)&&Number.isFinite(t.y)}function P(t){return{x:t.x,y:t.y}}function W(t){return t*Math.PI/180}function Q(t,e,n,r,i=!0,s=64){if(!p(t)||!Number.isFinite(e))return[];let o=n,a=r;if(!Number.isFinite(o)||!Number.isFinite(a))return[];(Math.abs(o)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(o=W(o),a=W(a)),i&&a<o&&(a+=Math.PI*2),!i&&o<a&&(o+=Math.PI*2);const c=a-o,l=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*s))),f=[];for(let d=0;d<=l;d++){const h=o+c*(d/l);f.push({x:t.x+Math.cos(h)*e,y:t.y+Math.sin(h)*e})}return f}function Ce(t,e,n=1,r=0,i=Math.PI*2,s=96){if(!p(t)||!p(e))return[];const o=Math.hypot(e.x,e.y);if(!Number.isFinite(o)||o<=0)return[];const a=o*(Number.isFinite(n)&&n>0?n:1),c=Math.atan2(e.y,e.x);let l=Number.isFinite(r)?r:0,f=Number.isFinite(i)?i:Math.PI*2;(Math.abs(l)>Math.PI*2+1e-6||Math.abs(f)>Math.PI*2+1e-6)&&(l=W(l),f=W(f)),f<l&&(f+=Math.PI*2);const d=Math.max(12,Math.min(256,Math.ceil(Math.abs(f-l)/(Math.PI*2)*s))),h=[],m=Math.cos(c),g=Math.sin(c);for(let k=0;k<=d;k++){const y=l+(f-l)*(k/d),x=Math.cos(y)*o,L=Math.sin(y)*a;h.push({x:t.x+x*m-L*g,y:t.y+x*g+L*m})}return h}function rt(t,e,n=0,r=16){if(!Number.isFinite(n)||Math.abs(n)<1e-12)return[P(t),P(e)];const i=Math.hypot(e.x-t.x,e.y-t.y);if(i<=1e-12)return[P(t),P(e)];const s=4*Math.atan(n),o=Math.abs(i/(2*Math.sin(s/2))),a={x:(t.x+e.x)/2,y:(t.y+e.y)/2},c=(e.x-t.x)/i,l=(e.y-t.y)/i,f=n>=0?1:-1,d=Math.sqrt(Math.max(o*o-(i/2)**2,0)),h={x:a.x-f*l*d,y:a.y+f*c*d},m=Math.atan2(t.y-h.y,t.x-h.x),g=Math.atan2(e.y-h.y,e.x-h.x);return Q(h,o,m,g,n>=0,r)}function it(t){return t.replace(/\\P/g,`
|
|
2
|
+
`).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function j(t,e,n){return Math.min(n,Math.max(e,t))}class st{constructor(e={}){u(this,"id","dxf");u(this,"label","DXF / JavaScript parser");u(this,"formats",["dxf"]);u(this,"defaults");this.defaults=e}accepts(e,n){return H(e)==="dxf"||O(e,n)==="dxf"}async load(e,n={}){var d;const r={...this.defaults,...n},i=performance.now(),s=await A(e),o=on(s,r.dxfEncoding),a=[];let c;try{c=await Jt(o)}catch(h){a.push(`dxf-parser failed, using built-in fallback parser: ${h instanceof Error?h.message:String(h)}`),c=dn(o)}const l=Qt(c,e.fileName??((d=e.file)==null?void 0:d.name),a),f=performance.now()-i;return{document:l,raw:c,bytes:s.byteLength,elapsedMs:f,format:"dxf",warnings:l.warnings}}}async function Jt(t){const e=await import("dxf-parser"),n=e.default??e.DxfParser;if(!n)throw new Error("dxf-parser did not expose a parser constructor.");return new n().parseSync(t)}function Qt(t,e,n=[]){const r=t&&typeof t=="object"?t:{},i=en(r),s=tn(r),a=(Array.isArray(r.entities)?r.entities:[]).filter(l=>!!l&&typeof l=="object").map(l=>Pe(l)),c=ae({format:"dxf",sourceName:e,header:r.header&&typeof r.header=="object"?r.header:{},layers:i,blocks:s,entities:a,metadata:{parser:"dxf-parser + cad-viewer normalizer"},warnings:n,raw:t});return a.length===0&&c.warnings.push("DXF file did not expose any ENTITIES."),c}function Pe(t){const e=String(t.type??t.entityType??"UNKNOWN").toUpperCase(),n=ce(t,e),r=b(t.colorIndex??t.colorNumber??t.aci),i=b(t.color);if(n.colorIndex=r??(i!==void 0&&Math.abs(i)<=257?i:void 0),n.trueColor=t.trueColor??t.true_color??t.colorRGB??t.trueColorValue??(i!==void 0&&Math.abs(i)>257?i:void 0),n.layer=C(t.layer??t.layerName)??"0",n.isClosed=!!(t.shape??t.closed??t.isClosed)||(Number(t.flag??t.flags??0)&1)===1,e==="LINE"&&(n.startPoint=S(t.startPoint??{x:t.x1??t.x,y:t.y1??t.y,z:t.z1??t.z})??n.startPoint,n.endPoint=S(t.endPoint??{x:t.x2,y:t.y2,z:t.z2})??n.endPoint),(e==="TEXT"||e==="MTEXT"||e==="ATTRIB"||e==="ATTDEF")&&(n.insertionPoint=S(t.startPoint??t.position??t.insertionPoint)??n.insertionPoint,n.text=hn(t.text??t.string??t.value)??n.text,n.textHeight=b(t.textHeight??t.height)??n.textHeight,n.rotation=at(t.rotation??t.angle)),(e==="ARC"||e==="ELLIPSE")&&(n.startAngle=ct(t.startAngle??t.start_angle),n.endAngle=ct(t.endAngle??t.end_angle)),e==="INSERT"){n.blockName=C(t.name??t.blockName)??n.blockName,n.insertionPoint=S(t.position??t.insertionPoint??t.point)??n.insertionPoint;const s=b(t.xScale??t.scaleX??t.xscale),o=b(t.yScale??t.scaleY??t.yscale),a=b(t.zScale??t.scaleZ??t.zscale);(s!==void 0||o!==void 0||a!==void 0)&&(n.scale={x:s??1,y:o??s??1,z:a??1}),n.rotation=at(t.rotation??t.angle)}if(e==="SPLINE"){const s=le(t.controlPoints??t.control_points??t.points);s.length&&(n.controlPoints=s);const o=le(t.fitPoints??t.fit_points);o.length&&(n.fitPoints=o)}return e==="HATCH"&&(n.loops=sn(t),n.fillColorIndex=n.colorIndex),(e==="SOLID"||e==="TRACE"||e==="3DFACE")&&(n.vertices=rn(t),n.fillColorIndex=n.colorIndex),n}function en(t){const e={},n=t.tables,r=t.layers??(n==null?void 0:n.layer)??(n==null?void 0:n.LAYER)??(n==null?void 0:n.layers),i=nn(r);for(const s of i){const o=s,a=C(o.name??o.layerName);a&&xe(e,{name:a,color:o.color??o.colorNumber??o.colorIndex,colorIndex:b(o.colorNumber??o.colorIndex??o.color),lineType:C(o.lineType??o.linetype),isVisible:Number(o.colorNumber??o.colorIndex??o.color??1)>=0,isFrozen:!!o.frozen,isLocked:!!o.locked,raw:o})}return e[0]||xe(e,{name:"0",colorIndex:7,isVisible:!0}),e}function tn(t){const e={},n=t.blocks;if(!n||typeof n!="object")return e;if(Array.isArray(n))for(const r of n)ot(e,r);else for(const[r,i]of Object.entries(n))ot(e,i,r);return e}function ot(t,e,n){if(!e||typeof e!="object")return;const r=e,i=C(r.name??r.blockName??n);if(!i)return;const o=(Array.isArray(r.entities)?r.entities:[]).filter(a=>!!a&&typeof a=="object").map(a=>Pe(a));et(t,{name:i,basePoint:S(r.basePoint??r.position)??{x:0,y:0},entities:o,raw:r})}function nn(t){if(!t)return[];if(Array.isArray(t))return t;if(typeof t!="object")return[];const e=t;return Array.isArray(e.entries)?e.entries:Array.isArray(e.records)?e.records:Array.isArray(e.layers)?e.layers:Object.values(e).filter(n=>n&&typeof n=="object")}function le(t){return Array.isArray(t)?t.map(S).filter(e=>!!e):[]}function rn(t){const e=le(t.vertices??t.points);if(e.length)return e;const n=[];for(let r=0;r<4;r++){const i=S({x:t[`x${r}`]??t[`x${r+1}`],y:t[`y${r}`]??t[`y${r+1}`],z:t[`z${r}`]??t[`z${r+1}`]});i&&n.push(i)}return n}function sn(t){const e=t.boundaryLoops??t.loops??t.paths;if(Array.isArray(e))return e.map(n=>{const r=n;return{vertices:le(r.vertices??r.points),isClosed:!0}}).filter(n=>n.vertices&&n.vertices.length>0)}function at(t){const e=b(t);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?W(e):e}function ct(t){const e=b(t);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?W(e):e}function on(t,e){const n=ke(e);if(n)return z(t,n);const r=an(t);if(r)return z(t,r);const i=ke(cn(t));if(i)return z(t,i);const s=z(t,"utf-8");return s.includes("�")?ln(t):s}const lt={ANSI_874:"windows-874",ANSI_932:"shift_jis",ANSI_936:"gb18030",ANSI_949:"euc-kr",ANSI_950:"big5",ANSI_1250:"windows-1250",ANSI_1251:"windows-1251",ANSI_1252:"windows-1252",ANSI_1253:"windows-1253",ANSI_1254:"windows-1254",ANSI_1255:"windows-1255",ANSI_1256:"windows-1256",ANSI_1257:"windows-1257",ANSI_1258:"windows-1258",BIG5:"big5",CP874:"windows-874",CP932:"shift_jis",CP936:"gb18030",CP949:"euc-kr",CP950:"big5",CP1250:"windows-1250",CP1251:"windows-1251",CP1252:"windows-1252",CP1253:"windows-1253",CP1254:"windows-1254",CP1255:"windows-1255",CP1256:"windows-1256",CP1257:"windows-1257",CP1258:"windows-1258",GB18030:"gb18030",GB2312:"gb18030",GBK:"gb18030",SHIFT_JIS:"shift_jis",SHIFTJIS:"shift_jis",SJIS:"shift_jis",UTF8:"utf-8",UTF_8:"utf-8",UTF16:"utf-16le",UTF_16:"utf-16le",UTF16LE:"utf-16le",UTF_16LE:"utf-16le",UTF16BE:"utf-16be",UTF_16BE:"utf-16be"};function an(t){if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return"utf-8";if(t.length>=2&&t[0]===255&&t[1]===254)return"utf-16le";if(t.length>=2&&t[0]===254&&t[1]===255)return"utf-16be"}function cn(t){var r,i,s,o;const n=z(t.subarray(0,Math.min(t.byteLength,131072)),"iso-8859-1").replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
4
|
`).split(`
|
|
5
|
-
`);for(let a=0;a<n.length-3;a++)if(!(((r=n[a])==null?void 0:r.trim())!=="9"||((i=n[a+1])==null?void 0:i.trim().toUpperCase())!=="$DWGCODEPAGE"))for(let c=a+2;c<Math.min(a+10,n.length-1);c+=2){const l=(
|
|
6
|
-
`)}function
|
|
5
|
+
`);for(let a=0;a<n.length-3;a++)if(!(((r=n[a])==null?void 0:r.trim())!=="9"||((i=n[a+1])==null?void 0:i.trim().toUpperCase())!=="$DWGCODEPAGE"))for(let c=a+2;c<Math.min(a+10,n.length-1);c+=2){const l=(s=n[c])==null?void 0:s.trim(),f=(o=n[c+1])==null?void 0:o.trim();if(l==="3"&&f)return f}}function ke(t){const e=t==null?void 0:t.trim();if(!e)return;const n=e.replace(/[-\s]+/g,"_").toUpperCase();if(lt[n])return lt[n];const r=/^ANSI_(\d{3,4})$/.exec(n);if(r)return ke(`cp${r[1]}`);const i=/^CP(\d{3,4})$/.exec(n);return i?i[1]==="936"?"gb18030":i[1]==="950"?"big5":i[1]==="932"?"shift_jis":i[1]==="949"?"euc-kr":`windows-${i[1]}`:e}function z(t,e){try{return new TextDecoder(e,{fatal:!1}).decode(t)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode(t)}}function ln(t){const e=["windows-1252","gb18030","big5","shift_jis","euc-kr","iso-8859-1"];let n="",r=Number.POSITIVE_INFINITY;for(const i of e){const s=z(t,i),o=fn(s,i);o<r&&(r=o,n=s)}return n||z(t,"utf-8")}function fn(t,e){const n=Se(t,/\uFFFD/g),r=Se(t,/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g),i=Se(t,/[\u3400-\u9FFF\uF900-\uFAFF]/g),s=t.includes("SECTION")&&(t.includes("ENTITIES")||t.includes("HEADER"));let o=n*1e4+r*1e3;return s&&(o-=500),e==="windows-1252"&&(o-=2),e==="gb18030"&&i>=2&&(o-=50+Math.min(i,200)*2),o}function Se(t,e){var n;return((n=t.match(e))==null?void 0:n.length)??0}function hn(t){const e=C(t);if(e!==void 0)return e.replace(/\\U\+([0-9a-fA-F]{4,6})/g,(n,r)=>{const i=Number.parseInt(r,16);return Number.isFinite(i)&&i>=0&&i<=1114111?String.fromCodePoint(i):n}).replace(/%%[cC]/g,"∅").replace(/%%[dD]/g,"°").replace(/%%[pP]/g,"±").replace(/\\P/g,`
|
|
6
|
+
`)}function dn(t){var l,f;const e=t.replace(/\r\n/g,`
|
|
7
7
|
`).replace(/\r/g,`
|
|
8
8
|
`).split(`
|
|
9
|
-
`),n=[];for(let h=0;h<e.length-1;h+=2){const d=Number((l=e[h])==null?void 0:l.trim()),m=e[h+1]??"";Number.isFinite(d)&&n.push({code:d,value:m.trimEnd()})}const r=[],i={};let o="",s=[],a;for(let h=0;h<n.length;h++){const d=n[h];if(d.code===0&&d.value==="SECTION"){o=((f=n[h+1])==null?void 0:f.code)===2?n[h+1].value.toUpperCase():"",h++;continue}if(d.code===0&&d.value==="ENDSEC"){c(),o="";continue}o==="ENTITIES"&&(d.code===0?(c(),s=[d]):s.push(d))}return c(),{header:{},tables:{},entities:r,blocks:i};function c(){var m;if(!s.length)return;const h=(m=s[0])==null?void 0:m.value.toUpperCase();if(h==="VERTEX"&&a){const g=E(s,10,20,30);g&&(a.vertices??(a.vertices=[])).push({...g,bulge:w(s,42)}),s=[];return}if(h==="SEQEND"){a&&r.push(a),a=void 0,s=[];return}if(a&&(r.push(a),a=void 0),!h||h==="EOF"){s=[];return}const d=an(h,s);h==="POLYLINE"?a=d:r.push(d),s=[]}}function an(t,e){const n={type:t,handle:ee(e,5),layer:ee(e,8)??"0",colorIndex:w(e,62),trueColor:w(e,420),lineType:ee(e,6),lineweight:w(e,370)};switch(t){case"LINE":Object.assign(n,{startPoint:E(e,10,20,30),endPoint:E(e,11,21,31)});break;case"CIRCLE":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40)});break;case"ARC":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40),startAngle:he(w(e,50)),endAngle:he(w(e,51))});break;case"POINT":Object.assign(n,{point:E(e,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(n,{insertionPoint:E(e,10,20,30),text:fn(e),textHeight:w(e,40),rotation:he(w(e,50))});break;case"LWPOLYLINE":Object.assign(n,{vertices:ln(e),flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"POLYLINE":Object.assign(n,{vertices:[],flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(n,{center:E(e,10,20,30),majorAxisEndPoint:E(e,11,21,31),axisRatio:w(e,40),startAngle:w(e,41),endAngle:w(e,42)});break;case"SPLINE":Object.assign(n,{controlPoints:cn(e,10,20,30),degree:w(e,71),isClosed:(Number(w(e,70)??0)&1)===1});break;case"INSERT":Object.assign(n,{name:ee(e,2),blockName:ee(e,2),insertionPoint:E(e,10,20,30),rotation:he(w(e,50)),scale:{x:w(e,41)??1,y:w(e,42)??w(e,41)??1,z:w(e,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(n,{vertices:[E(e,10,20,30),E(e,11,21,31),E(e,12,22,32),E(e,13,23,33)].filter(Boolean)});break}return ke(n)}function w(t,e){var i;const n=(i=t.find(o=>o.code===e))==null?void 0:i.value,r=Number(n);return Number.isFinite(r)?r:void 0}function ee(t,e){var r;const n=(r=t.find(i=>i.code===e))==null?void 0:r.value;return n&&n.length>0?n:void 0}function E(t,e,n,r){const i=w(t,e),o=w(t,n),s=w(t,r);if(!(i===void 0||o===void 0))return s===void 0?{x:i,y:o}:{x:i,y:o,z:s}}function cn(t,e,n,r){const i=[];for(let o=0;o<t.length;o++){if(t[o].code!==e)continue;const s=Number(t[o].value),a=t.slice(o+1).find(h=>h.code===n),c=t.slice(o+1).find(h=>h.code===r),l=Number(a==null?void 0:a.value),f=Number(c==null?void 0:c.value);Number.isFinite(s)&&Number.isFinite(l)&&i.push(Number.isFinite(f)?{x:s,y:l,z:f}:{x:s,y:l})}return i}function ln(t){const e=[];for(let n=0;n<t.length;n++){if(t[n].code!==10)continue;const r=Number(t[n].value);let i,o;for(let s=n+1;s<t.length&&t[s].code!==10;s++)t[s].code===20&&(i=Number(t[s].value)),t[s].code===42&&(o=Number(t[s].value));Number.isFinite(r)&&Number.isFinite(i)&&e.push({x:r,y:i,bulge:Number.isFinite(o)?o:void 0})}return e}function fn(t){const e=t.filter(n=>n.code===1||n.code===3).map(n=>n.value);return e.length?e.join(""):void 0}function he(t){return typeof t=="number"&&Number.isFinite(t)?W(t):void 0}class ct{constructor(e={}){u(this,"id","dwf");u(this,"label","DWF/DWFx native viewer powered by dwf-viewer");u(this,"formats",["dwf","dwfx","xps"]);u(this,"nativeRenderer",!0);u(this,"defaults");u(this,"native");u(this,"host");u(this,"lastStats");this.defaults=e}accepts(e,n){const r=X(e);if(r==="dwf"||r==="dwfx"||r==="xps")return!0;const i=R(e,n);return i==="dwf"||i==="dwfx"||i==="xps"}async load(e,n={}){var h,d,m,g;const r={...this.defaults,...n},i=performance.now(),o=e.fileName??((h=e.file)==null?void 0:h.name),s=await T(e),a=ht(R(e,s),X(e));(d=r.onProgress)==null||d.call(r,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await M.openDwfDocument(s,{fileName:o});(m=r.onProgress)==null||m.call(r,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const l=lt(c,o,a,r.keepRaw===!0),f=performance.now()-i;return(g=r.onProgress)==null||g.call(r,{phase:"done",format:l.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:f}),{document:l,raw:r.keepRaw?c:void 0,bytes:s.byteLength,elapsedMs:f,format:l.format,warnings:l.warnings}}async mount(e,n,r={}){var y,x,L,D,A;const i={...this.defaults,...r},o=performance.now(),s=e.fileName??((y=e.file)==null?void 0:y.name),a=await T(e),c=ht(R(e,a),X(e)),l=pn(i),f=dt(i),h=gn(i,l,f),d=ut(i,l,f);(x=i.onProgress)==null||x.call(i,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=n,n.replaceChildren(),this.native=new M.DwfViewer(n,h),(L=i.onProgress)==null||L.call(i,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:s,...d}),(D=i.onProgress)==null||D.call(i,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const m=this.native.getDocument(),g=lt(m,s,c,i.keepRaw===!0);g.metadata.loaderMode="Native DWF",g.metadata.nativeRenderer="dwf-viewer",g.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const S=performance.now()-o;return(A=i.onProgress)==null||A.call(i,{phase:"done",format:g.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:S}),{document:g,raw:i.keepRaw?m:void 0,bytes:a.byteLength,elapsedMs:S,format:g.format,warnings:g.warnings}}unmount(){var e;(e=this.native)==null||e.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var e;(e=this.native)==null||e.fit()}zoomIn(){var n;const e=(n=this.native)==null?void 0:n.zoomInButton;e==null||e.click()}zoomOut(){var n;const e=(n=this.native)==null?void 0:n.zoomOutButton;e==null||e.click()}resize(){var e;(e=this.native)==null||e.render()}setNativeOptions(e){var r,i,o,s;const n=this.native;if(n){if(typeof e.dwfBackground=="string")n.background=e.dwfBackground;else{const a=dt(e);a&&(n.background=a)}typeof e.dwfPreferWebgl=="boolean"&&((r=n.setPreferWebgl)==null||r.call(n,e.dwfPreferWebgl)),typeof e.dwfPreferWasm=="boolean"&&((i=n.setPreferWasm)==null||i.call(n,e.dwfPreferWasm)),e.dwfLineWeightMode&&((o=n.setLineWeightMode)==null||o.call(n,e.dwfLineWeightMode)),de(n,"minStrokeCssPx",e.dwfMinStrokeCssPx),de(n,"maxOverviewStrokeCssPx",e.dwfMaxOverviewStrokeCssPx),de(n,"minTextCssPx",e.dwfMinTextCssPx),de(n,"minFilledAreaCssPx",e.dwfMinFilledAreaCssPx),(s=n.render)==null||s.call(n)}}getLastNativeStats(){return this.lastStats}}function lt(t,e,n,r){var a,c;const i=ft((t==null?void 0:t.diagnostics)??[]),o=((t==null?void 0:t.pageData)??[]).map((l,f)=>hn(l,f));for(const l of(t==null?void 0:t.pageData)??[])i.push(...ft(l.diagnostics));const s={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:t==null?void 0:t.kind,packageEntries:((a=t==null?void 0:t.packageEntries)==null?void 0:a.length)??0,resources:((c=t==null?void 0:t.resources)==null?void 0:c.length)??0,pageKinds:vn(((t==null?void 0:t.pageData)??[]).map(l=>l.kind)),pageNames:((t==null?void 0:t.pages)??[]).map(l=>l.name)};return ae({format:n,sourceName:e,layers:{},blocks:{},pages:o,entities:Xt(o),metadata:s,warnings:wn(i),raw:r?t:void 0})}function hn(t,e){const n=dn(t,e);return{index:e,name:t.name||t.sourcePath||`${e+1}`,width:t.width||1e3,height:t.height||1e3,entities:n}}function dn(t,e){return t.kind==="w2d-text"?t.primitives.flatMap((n,r)=>un(n,e,r)):t.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:e,width:t.width,height:t.height,imageSource:t.sourcePath}]:t.kind==="w3d-model"?t.model.meshes.map((n,r)=>({id:n.id,type:"W3D_MESH",kind:"solid",pageIndex:e,color:n.color?yn(n.color):void 0,name:n.name||`mesh-${r+1}`,raw:{vertexCount:n.vertexCount,triangleCount:n.triangleCount,materialId:n.materialId}})):t.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]}function un(t,e,n){const r={id:`dwf-${e}-${n}`,pageIndex:e,color:t.stroke,fillColor:t.fill,lineweight:t.lineWidth,raw:{matrix:t.matrix}};if(t.type==="polyline"||t.type==="polygon")return[{...r,type:t.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:mn(t.points),isClosed:t.type==="polygon"}];if(t.type==="path")return[{...r,type:"DWF_PATH",kind:"path",commands:t.commands}];if(t.type==="text")return[{...r,type:"DWF_TEXT",kind:"text",insertionPoint:{x:t.x,y:t.y,z:0},text:t.text,textHeight:t.size}];if(t.type==="rect"){const i=t.x,o=t.y,s=t.width,a=t.height;return[{...r,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:i,y:o,z:0},{x:i+s,y:o,z:0},{x:i+s,y:o+a,z:0},{x:i,y:o+a,z:0}]}]}return[]}function mn(t){const e=[];for(let n=0;n+1<t.length;n+=2)e.push({x:t[n],y:t[n+1],z:0});return e}function ft(t){return t.filter(e=>e.level!=="info").map(e=>`${e.code}: ${e.message}${e.source?` (${e.source})`:""}`)}function ht(t,e){return e==="dwf"||e==="dwfx"||e==="xps"?e:t==="dwf"||t==="dwfx"||t==="xps"?t:"dwf"}function pn(t){if(t.dwfWasmUrl)return t.dwfWasmUrl;if(typeof document>"u")return;const e=t.wasmPath?new URL(bn(t.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",e).href}function dt(t){if(t.dwfBackground)return t.dwfBackground;const e=t.canvasOptions;return(e==null?void 0:e.background)??"#05070d"}function gn(t,e,n){return{...ut(t,e,n),maxDevicePixelRatio:t.dwfMaxDevicePixelRatio??2,maxCanvasPixels:t.dwfMaxCanvasPixels??16777216}}function ut(t,e,n){return{wasmUrl:e,preferWebgl:t.dwfPreferWebgl??!0,preferWasm:t.dwfPreferWasm??!0,background:n,maxGpuCacheBytes:t.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:t.dwfMaxCachedScenes??2,lineWeightMode:t.dwfLineWeightMode??"adaptive",minStrokeCssPx:t.dwfMinStrokeCssPx,maxOverviewStrokeCssPx:t.dwfMaxOverviewStrokeCssPx,minTextCssPx:t.dwfMinTextCssPx,minFilledAreaCssPx:t.dwfMinFilledAreaCssPx}}function de(t,e,n){typeof n=="number"&&Number.isFinite(n)&&(t[e]=n)}function bn(t){return t.endsWith("/")?t:`${t}/`}function yn(t){const[e,n,r]=t.map(i=>Math.max(0,Math.min(255,Math.round(i*255))));return`#${Me(e)}${Me(n)}${Me(r)}`}function Me(t){return t.toString(16).padStart(2,"0")}function vn(t){const e={};for(const n of t)e[n]=(e[n]??0)+1;return e}function wn(t){return Array.from(new Set(t))}function mt(t={}){return new je([new Ke(t),new rt(t),new ct(t)])}function pt(t){const e=t;return e.nativeRenderer===!0&&typeof e.mount=="function"}const xn={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function F(t,e="#ffffff",n=e){if(typeof t!="number"||Number.isNaN(t))return e;const r=Math.abs(Math.trunc(t));return r===0||r===256||r===257?e:r===7?n:xn[r]??e}function G(t,e="rgb"){const n=Math.max(0,Math.trunc(t))&16777215,r=n>>16&255,i=n>>8&255,o=n&255;return`rgb(${e==="rgb"?r:o}, ${i}, ${e==="rgb"?o:r})`}function Z(t){if(typeof t=="string"){const e=t.trim();return e?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(e)?Cn(e)??e:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[e.toLowerCase()]:void 0}if(t&&typeof t=="object"){const e=t,n=Number(e.r??e.red),r=Number(e.g??e.green),i=Number(e.b??e.blue),o=Number(e.a??e.alpha??1);if([n,r,i].every(Number.isFinite))return Number.isFinite(o)&&o>=0&&o<1?`rgba(${n}, ${r}, ${i}, ${o})`:`rgb(${n}, ${r}, ${i})`}}function Cn(t){if(!t)return;const e=t.trim();if(/^#[0-9a-f]{8}$/i.test(e)){const n=parseInt(e.slice(1,3),16)/255,r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),o=parseInt(e.slice(7,9),16);return n>=.999?`rgb(${r}, ${i}, ${o})`:`rgba(${r}, ${i}, ${o}, ${Ae(n)})`}if(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e))return e;if(/^sc#/i.test(e)){const n=e.slice(3).split(",").map(a=>Number(a.trim())),[r,i,o,s]=n.length===4?n:[1,...n];if([r,i,o,s].every(Number.isFinite))return`rgba(${Math.round(i*255)}, ${Math.round(o*255)}, ${Math.round(s*255)}, ${Ae(r)})`}}function _(t,e,n={}){const r=n.foreground??"#ffffff",i=r;let o;const s=Z(t.trueColor)??Z(t.color)??Z(t.colorName);if(s&&(o=s),!o){const a=En(t,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(o=G(a,n.trueColorByteOrder??"rgb"))}if(!o){const a=vt(t.colorIndex,t.colorNumber,t.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(o=F(a,i,r))}if(!o&&typeof t.color=="number"){const a=Number(t.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(o=F(a,i,r)):o=G(a,n.trueColorByteOrder??"rgb")}if(!o){const a=Mn(e,t.layer);o=kn(a,n)}return gt(o??i,n)}function Ee(t,e,n={}){let r;const i=Z(t.fillColor);if(i&&(r=i),!r&&typeof t.fillColor=="number"){const o=t.fillColor;r=Math.abs(o)<=257?F(o,n.foreground??"#ffffff",n.foreground??"#ffffff"):G(o,n.trueColorByteOrder??"rgb")}return!r&&typeof t.fillColorIndex=="number"&&(r=F(t.fillColorIndex,n.foreground??"#ffffff",n.foreground??"#ffffff")),r?gt(r,n):void 0}function gt(t,e={}){if(e.contrastMode!=="adaptive")return t;const n=e.background??"#0b1020",r=e.foreground??"#ffffff";return Pn(t,n,r,e.minColorContrast??2.4)}function Pn(t,e,n,r=2.4){const i=Le(n)??{r:255,g:255,b:255,a:1},o=Le(e)??{r:11,g:16,b:32,a:1},s=Le(t);if(!s)return t;const a=wt(s,o);if(Te(a,o)>=r)return t;const c=Ie(o),l=c<.5?{r:255,g:255,b:255,a:s.a}:{r:0,g:0,b:0,a:s.a};for(const f of[.25,.4,.55,.7,.85,1]){const h=Ln(s,l,f);if(Te(wt(h,o),o)>=r)return xt(h)}return Te(i,o)>=r?xt(i):c<.5?"#ffffff":"#000000"}function bt(t){return t?t.isVisible!==!1&&t.isFrozen!==!0:!0}function kn(t,e){if(!t)return;const n=e.foreground??"#ffffff",r=Z(t.trueColor);if(r)return r;if(typeof t.trueColor=="number"&&t.trueColor>=0&&t.trueColor<=16777215)return G(t.trueColor,e.trueColorByteOrder??"rgb");const i=Z(t.color);if(i)return i;if(Nn(t.colorIndex))return F(t.colorIndex,n,n);if(typeof t.color=="number"){const o=Number(t.color);return Math.abs(o)<=257?F(o,n,n):G(o,e.trueColorByteOrder??"rgb")}if(typeof t.colorIndex=="number")return F(t.colorIndex,n,n)}function Sn(t){return vt(t.colorIndex,t.colorNumber,t.aci)===0?!0:t.trueColor===void 0&&t.color===0}function yt(t,e,n,r={}){if(!Sn(t))return t;const i=_(e,n,r);return{...t,color:i,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function Nn(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function Mn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function vt(...t){for(const e of t)if(typeof e=="number"&&Number.isFinite(e))return e}function En(t,e){const n=t;for(const r of e){const i=n[r];if(typeof i=="number"&&Number.isFinite(i))return i}}function Le(t){const e=t.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1};const n=e.match(/^rgba?\(([^)]+)\)$/i);if(n){const r=n[1].split(/[,\s/]+/).filter(Boolean).map(i=>Number(i.replace("%","")));if(r.length>=3&&r.slice(0,3).every(Number.isFinite)){const i=/%/.test(n[1]);return{r:q(i?r[0]*2.55:r[0]),g:q(i?r[1]*2.55:r[1]),b:q(i?r[2]*2.55:r[2]),a:Number.isFinite(r[3])?Math.max(0,Math.min(1,r[3])):1}}}}function wt(t,e){const n=t.a+e.a*(1-t.a);return n<=0?{r:0,g:0,b:0,a:0}:{r:(t.r*t.a+e.r*e.a*(1-t.a))/n,g:(t.g*t.a+e.g*e.a*(1-t.a))/n,b:(t.b*t.a+e.b*e.a*(1-t.a))/n,a:n}}function Ln(t,e,n){const r=Math.max(0,Math.min(1,n));return{r:t.r+(e.r-t.r)*r,g:t.g+(e.g-t.g)*r,b:t.b+(e.b-t.b)*r,a:t.a}}function Ie(t){const e=[t.r,t.g,t.b].map(n=>{const r=n/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Te(t,e){const n=Ie(t),r=Ie(e),i=Math.max(n,r),o=Math.min(n,r);return(i+.05)/(o+.05)}function xt(t){const e=q(t.r),n=q(t.g),r=q(t.b);return t.a<.999?`rgba(${e}, ${n}, ${r}, ${Ae(t.a)})`:`rgb(${e}, ${n}, ${r})`}function q(t){return Math.max(0,Math.min(255,Math.round(t)))}function Ae(t){return Math.round(t*1e3)/1e3}const Ct=1e5,Pt=new Set(["","bylayer","15"]),Be=new Set(["byblock","14"]),In=new Set(["continuous","16"]),K=t=>String(t??"").trim().toLowerCase();function Tn(t){return Be.has(K(t))}function Fe(t,e,n){if(!Tn(t.lineType))return t;const r=De(e,n);return{...t,lineType:r||"Continuous",lineTypeScale:te(t.lineTypeScale,1)*te(e.lineTypeScale,1)}}function De(t,e){var i;let n=String(t.lineType??"").trim();const r=K(n);return Pt.has(r)?n=((i=Rn(e,t.layer))==null?void 0:i.lineType)??"Continuous":Be.has(r)&&(n="Continuous"),n||"Continuous"}function ue(t,e){var h,d;if(!e)return;const n=De(t,e),r=K(n);if(In.has(r)||Pt.has(r)||Be.has(r))return;const i=Dn(e,n);if(!(i!=null&&i.pattern.length))return;const o=te(t.lineTypeScale,te((h=e.header)==null?void 0:h.CELTSCALE,1)),s=te((d=e.header)==null?void 0:d.LTSCALE,1)*o,a=Bn(i,s),c=a.reduce((m,g)=>m+g.length,0);if(!Number.isFinite(c)||c<=1e-9)return;const l=a.some(m=>!m.draw&&m.length>1e-12),f=a.some(m=>m.marker);if(!(!l&&!f))return{name:i.name,segments:Fn(a,l),runs:a,period:c}}function An(t,e,n){return me(t,e,n).segments}function me(t,e,n,r=Ct){const i=t.filter(y=>Number.isFinite(y.x)&&Number.isFinite(y.y));if(i.length<2||n.runs.length===0)return{segments:[],dots:[]};const o=[];for(let y=0;y<i.length-1;y++)o.push([i[y],i[y+1]]);e&&o.push([i[i.length-1],i[0]]);const s=Number.isFinite(r)?Math.max(1,Math.floor(r)):Ct,a=o.reduce((y,[x,L])=>y+Math.hypot(L.x-x.x,L.y-x.y),0),l=(n.period>1e-12?a/n.period:Number.POSITIVE_INFINITY)*Math.max(1,n.runs.length);if(!Number.isFinite(l)||l>s)return{segments:o,dots:[]};const f={segments:[],dots:[]};let h=0,d=n.runs[0].length,m=!0;const g=y=>{const x=f.dots[f.dots.length-1];x&&Math.hypot(x.x-y.x,x.y-y.y)<=1e-10||f.dots.push(y)},S=()=>{h=(h+1)%n.runs.length,d=n.runs[h].length,m=!0};for(const[y,x]of o){const L=x.x-y.x,D=x.y-y.y,A=Math.hypot(L,D);if(A<=1e-14)continue;let H=0;for(;H<A-1e-12;){let Ft=0;for(;d<=1e-12&&Ft<n.runs.length;){const U=n.runs[h];if(m&&U.marker){const re=H/A;g({x:y.x+L*re,y:y.y+D*re})}S(),Ft++}if(d<=1e-12)break;const Dt=n.runs[h];if(m){if(Dt.marker){const U=H/A;g({x:y.x+L*U,y:y.y+D*U})}m=!1}const ve=Math.min(d,A-H);if(Dt.draw&&ve>1e-12){const U=H/A,re=(H+ve)/A;f.segments.push([{x:y.x+L*U,y:y.y+D*U},{x:y.x+L*re,y:y.y+D*re}])}H+=ve,d-=ve,d<=1e-12&&S()}}return f}function Bn(t,e){const n=[];for(const r of t.pattern){const i=Number(r.length),o=Number(r.elementTypeFlag??0)!==0;Number.isFinite(i)&&n.push({draw:i>=0,length:Math.abs(i)*e,marker:i>=0&&(i===0||o)})}return n}function Fn(t,e){if(!e)return[];const n=[];for(const i of t){if(i.length<=1e-12)continue;const o=n[n.length-1];(o==null?void 0:o.draw)===i.draw?o.length+=i.length:n.push({draw:i.draw,length:i.length})}const r=[];for(const i of n){const o=r.length%2===0;i.draw!==o&&r.push(1e-9),r.push(i.length)}return r.length%2===1&&r.push(1e-9),r}function Dn(t,e){const n=K(e),r=t.lineTypes??{};return r[e]??r[n]??Object.values(r).find(i=>K(i.name)===n||K(i.handle)===n)}function Rn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function te(t,e){const n=Number(t);return Number.isFinite(n)&&n>0?n:e}const On={a:1,b:0,c:0,d:1,e:0,f:0};function pe(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function kt(t,e){return{a:1,b:0,c:0,d:1,e:t,f:e}}function St(t){const e=Math.cos(t),n=Math.sin(t);return{a:e,b:n,c:-n,d:e,e:0,f:0}}function Wn(t,e=t){return{a:t,b:0,c:0,d:e,e:0,f:0}}function I(t,e){return{x:t.x*e.a+t.y*e.c+e.e,y:t.x*e.b+t.y*e.d+e.f,z:"z"in t?t.z:void 0}}function Nt(t,e){if(t)return t.map(n=>({cmd:n.cmd,points:n.points.map(r=>I(r,e))}))}function ge(t,e={x:0,y:0}){const n=t.insertionPoint??{x:0,y:0},r=t.scale,i=Number(typeof r=="object"&&r?r.x??1:t.scaleX??1),o=Number(typeof r=="object"&&r?r.y??i:t.scaleY??i),s=Number(t.rotation??0);let a=kt(n.x,n.y);return a=pe(a,St(Number.isFinite(s)?s:0)),a=pe(a,Wn(Number.isFinite(i)?i:1,Number.isFinite(o)?o:1)),a=pe(a,kt(-e.x,-e.y)),a}function Y(t,e){const n={...t};if(t.startPoint&&(n.startPoint=I(t.startPoint,e)),t.endPoint&&(n.endPoint=I(t.endPoint,e)),t.center&&(n.center=I(t.center,e)),t.insertionPoint&&(n.insertionPoint=I(t.insertionPoint,e)),t.majorAxisEndPoint){const s=I({x:0,y:0},e),a=I(t.majorAxisEndPoint,e);n.majorAxisEndPoint={x:a.x-s.x,y:a.y-s.y,z:a.z}}t.vertices&&(n.vertices=t.vertices.map(s=>({...I(s,e),bulge:s.bulge,startWidth:s.startWidth,endWidth:s.endWidth}))),t.points&&(n.points=t.points.map(s=>I(s,e))),t.controlPoints&&(n.controlPoints=t.controlPoints.map(s=>I(s,e))),t.fitPoints&&(n.fitPoints=t.fitPoints.map(s=>I(s,e))),t.attribs&&(n.attribs=t.attribs.map(s=>Y(s,e))),t.commands&&(n.commands=Nt(t.commands,e)),t.loops&&(n.loops=t.loops.map(s=>{var a;return{...s,vertices:(a=s.vertices)==null?void 0:a.map(c=>I(c,e)),commands:Nt(s.commands,e)}}));const r=Math.sqrt(Math.abs(e.a*e.d-e.b*e.c));typeof t.radius=="number"&&Number.isFinite(r)&&(n.radius=t.radius*r);const i=Math.atan2(e.b,e.a),o=t.kind==="ellipse"||String(t.type??"").toUpperCase()==="ELLIPSE";return Number.isFinite(i)&&Math.abs(i)>1e-14&&((typeof t.rotation=="number"||t.kind==="text"||t.kind==="insert")&&(n.rotation=Number(t.rotation??0)+i),!o&&typeof t.startAngle=="number"&&(n.startAngle=t.startAngle+i),!o&&typeof t.endAngle=="number"&&(n.endAngle=t.endAngle+i)),e.a*e.d-e.b*e.c<0&&n.vertices&&(n.vertices=n.vertices.map(s=>({...s,bulge:typeof s.bulge=="number"?-s.bulge:void 0}))),n}const zn=t=>Math.abs(t.a-1)<1e-12&&Math.abs(t.b)<1e-12&&Math.abs(t.c)<1e-12&&Math.abs(t.d-1)<1e-12&&Math.abs(t.e)<1e-9&&Math.abs(t.f)<1e-9;function Re(t){var n,r,i;if(t.metadata.sceneTransformApplied===!0||((n=t.savedView)==null?void 0:n.sceneTransformApplied)===!1)return t;const e=((r=t.savedView)==null?void 0:r.sceneTransform)??On;return zn(e)?t:{...t,entities:t.entities.map(o=>Y(o,e)),pages:(i=t.pages)==null?void 0:i.map(o=>({...o,entities:o.entities.map(s=>Y(s,e))})),metadata:{...t.metadata,sceneTransformApplied:!0}}}const _n={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class Oe{constructor(e,n={}){u(this,"canvas");u(this,"ctx");u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"imageCache",new Map);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});u(this,"onStats");u(this,"onViewChange");const r=e.getContext("2d");if(!r)throw new Error("Canvas 2D context is not available.");this.canvas=e,this.ctx=r,this.opts={..._n,...n},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}destroy(){var e;(e=this.resizeObserver)==null||e.disconnect()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=Re(e),this.bounds=this.computeBounds(this.document),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){Object.assign(this.opts,e),this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92){if(!j(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const n=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),i=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),o=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),s=this.clampScale(Math.min(n/i,r/o)*e);this.fitScale=s,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:s},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const o=this.screenToWorld(r);this.view.centerX+=i.x-o.x,this.view.centerY+=i.y-o.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.render(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Yn(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){var n,r;const e=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((n=this.document.pages)!=null&&n.length)&&this.drawPageBounds(this.document);for(const i of this.document.entities)this.drawEntityTracked(i,0)}return this.stats.renderElapsedMs=performance.now()-e,(r=this.onStats)==null||r.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",n=>{n.preventDefault();const r=n.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(r,{x:n.offsetX,y:n.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",n=>{this.canvas.setPointerCapture(n.pointerId),this.isDragging=!0,this.lastPointer={x:n.clientX,y:n.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",n=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(n.clientX-this.lastPointer.x,n.clientY-this.lastPointer.y),this.lastPointer={x:n.clientX,y:n.clientY})});const e=n=>{n&&this.canvas.hasPointerCapture(n.pointerId)&&this.canvas.releasePointerCapture(n.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",e),this.canvas.addEventListener("pointercancel",()=>e())}clearCanvas(){const e=this.ctx;e.save(),e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,this.cssWidth,this.cssHeight),e.fillStyle=this.opts.background,e.fillRect(0,0,this.cssWidth,this.cssHeight),e.restore()}drawPageBounds(e){const n=this.ctx;n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.strokeStyle="rgba(148, 163, 184, 0.35)",n.lineWidth=1,n.setLineDash([8,6]);for(const r of e.pages??[]){const i=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:r.width,y:r.height});n.strokeRect(Math.min(i.x,o.x),Math.min(i.y,o.y),Math.abs(o.x-i.x),Math.abs(o.y-i.y))}n.restore()}drawEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!bt(i)){this.stats.skipped++;return}this.drawEntity(e,r,n)}drawEntity(e,n,r){switch(e.kind??O(n)){case"line":return this.drawLine(e);case"circle":return this.drawCircle(e);case"arc":return this.drawArc(e);case"polyline":return this.drawPolyline(e);case"ellipse":return this.drawEllipse(e);case"text":return this.drawText(e);case"point":return this.drawPoint(e);case"insert":return this.drawInsert(e,r);case"solid":return this.drawSolid(e);case"hatch":return this.drawHatch(e);case"spline":return this.drawSpline(e);case"path":return this.drawPath(e);case"image":return this.drawImage(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(e)}}beginStyledPath(e,n=!1,r=!0){const i=this.ctx;i.save(),i.setTransform(this.dpr,0,0,this.dpr,0,0);const o=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),s=Ee(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??o;i.strokeStyle=o,i.fillStyle=n?s:o,i.globalAlpha=$(Number(e.opacity??1),0,1),i.lineCap="round",i.lineJoin="round";const a=typeof e.lineweight=="number"&&e.lineweight>0?e.lineweight:0;i.lineWidth=Math.max(1,Math.min(12,a>0?a/30:1));const c=r?ue(e,this.document):void 0;i.setLineDash(c?c.segments.map(l=>Math.max(.05,l*this.view.scale)):[]),i.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(e=!1){e&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(e){const n=e.startPoint,r=e.endPoint;if(!p(n)||!p(r))return this.markSkipped("LINE");this.strokeWorldPolyline(e,[n,r],!1)}drawCircle(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");this.strokeWorldPolyline(e,Q(k(n),r,0,Math.PI*2,!0),!0)}drawArc(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),o=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o))return this.markSkipped("ARC");this.strokeWorldPolyline(e,Q(k(n),r,i,o,!0),!1)}drawPolyline(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=Ce(e),i=[],o=r?n.length:n.length-1;for(let s=0;s<o;s++){const a=n[s],c=n[(s+1)%n.length];if(!p(a)||!p(c))continue;const l=tt(a,c,Number(a.bulge??0));i.length>0&&l.shift(),i.push(...l)}this.strokeWorldPolyline(e,i,r)}drawEllipse(e){const n=e.center,r=e.majorAxisEndPoint,i=Number(e.axisRatio??1);if(!p(n)||!p(r))return this.markSkipped("ELLIPSE");const o=le(n,r,i,Number(e.startAngle??0),Number(e.endAngle??Math.PI*2)),s=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(e,o,s)}drawPoint(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-3,r.y),this.ctx.lineTo(r.x+3,r.y),this.ctx.moveTo(r.x,r.y-3),this.ctx.lineTo(r.x,r.y+3),this.finishStroke()}drawText(e){const n=e.insertionPoint??e.startPoint??e.center,r=nt(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r)return this.markSkipped(String(e.type));this.drawTextAt(e,n,r,i,Number(e.rotation??0))}drawInsert(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const a=ge(e,r.basePoint??{x:0,y:0});for(const c of r.entities){const l=yt(c,e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),f=Fe(l,e,this.document);this.drawEntityTracked(Y(f,a),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");const o=this.worldToScreen(i);this.beginStyledPath(e);const s=5;if(this.ctx.rect(o.x-s,o.y-s,s*2,s*2),this.finishStroke(),Array.isArray(e.attribs))for(const a of e.attribs)this.drawText(a)}drawSolid(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));this.beginStyledPath(e,!0);const r=this.worldToScreen(n[0]);this.ctx.moveTo(r.x,r.y);for(const i of n.slice(1)){if(!p(i))continue;const o=this.worldToScreen(i);this.ctx.lineTo(o.x,o.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(e){var r,i;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");this.beginStyledPath(e,!0);for(const o of n)if((r=o.commands)!=null&&r.length)this.addPathCommands(o.commands);else if((i=o.vertices)!=null&&i.length){const s=this.worldToScreen(o.vertices[0]);this.ctx.moveTo(s.x,s.y);for(const a of o.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!Ee(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(e,n,!!e.isClosed)}drawPath(e){var n;if(!((n=e.commands)!=null&&n.length))return this.markSkipped(String(e.type));this.beginStyledPath(e,!!e.fillColor),this.addPathCommands(e.commands),this.finishFillStroke(!!e.fillColor)}addPathCommands(e){for(const n of e)if(n.cmd==="M"){const r=this.worldToScreen(n.points[0]);this.ctx.moveTo(r.x,r.y)}else if(n.cmd==="L"){const r=this.worldToScreen(n.points[0]);this.ctx.lineTo(r.x,r.y)}else if(n.cmd==="C"){const[r,i,o]=n.points.map(s=>this.worldToScreen(s));this.ctx.bezierCurveTo(r.x,r.y,i.x,i.y,o.x,o.y)}else if(n.cmd==="Q"){const[r,i]=n.points.map(o=>this.worldToScreen(o));this.ctx.quadraticCurveTo(r.x,r.y,i.x,i.y)}else n.cmd==="Z"&&this.ctx.closePath()}drawImage(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32),o=this.worldToScreen(n),s=this.worldToScreen({x:n.x+r,y:n.y-i}),a=Math.min(o.x,s.x),c=Math.min(o.y,s.y),l=Math.abs(s.x-o.x),f=Math.abs(s.y-o.y),h=e.imageDataUrl;if(h){const d=this.getImage(h);if(d.complete&&d.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(d,a,c,l,f),this.ctx.restore(),this.stats.drawn++;return}d.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(e.type));this.beginStyledPath(e),this.ctx.rect(a,c,l,f),this.ctx.moveTo(a,c),this.ctx.lineTo(a+l,c+f),this.ctx.moveTo(a+l,c),this.ctx.lineTo(a,c+f),this.finishStroke()}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}drawUnsupportedMarker(e){const n=this.entityAnchor(e);if(!n)return;const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-4,r.y-4),this.ctx.lineTo(r.x+4,r.y+4),this.ctx.moveTo(r.x+4,r.y-4),this.ctx.lineTo(r.x-4,r.y+4),this.finishStroke()}drawTextAt(e,n,r,i,o){const s=this.ctx,a=this.worldToScreen(n);s.save(),s.setTransform(this.dpr,0,0,this.dpr,0,0),s.translate(a.x,a.y),s.rotate(-o);const c=Math.max(4,Math.min(256,Math.abs(i)*this.view.scale));s.font=`${c}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,s.fillStyle=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),s.globalAlpha=$(Number(e.opacity??1),0,1),s.textBaseline="alphabetic";for(const[l,f]of r.split(/\r?\n/g).entries())s.fillText(f,0,l*c*1.22);s.restore(),this.stats.drawn++}strokeWorldPolyline(e,n,r){const i=n.filter(p);if(i.length<2)return this.markSkipped(String(e.type));const o=ue(e,this.document);if(o){const a=me(i,r,o);this.beginStyledPath(e,!1,!1);for(const[c,l]of a.segments){const f=this.worldToScreen(c),h=this.worldToScreen(l);this.ctx.moveTo(f.x,f.y),this.ctx.lineTo(h.x,h.y)}if(this.ctx.stroke(),a.dots.length>0){this.ctx.setLineDash([]),this.ctx.beginPath();const c=Math.max(.5,this.ctx.lineWidth/2);for(const l of a.dots){const f=this.worldToScreen(l);this.ctx.moveTo(f.x+c,f.y),this.ctx.arc(f.x,f.y,c,0,Math.PI*2)}this.ctx.fillStyle=this.ctx.strokeStyle,this.ctx.fill()}this.ctx.restore(),this.stats.drawn++;return}this.beginStyledPath(e);const s=this.worldToScreen(i[0]);this.ctx.moveTo(s.x,s.y);for(const a of i.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}r&&this.ctx.closePath(),this.finishStroke()}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}entityAnchor(e){for(const n of["startPoint","insertionPoint","center","point","location"]){const r=e[n];if(p(r))return k(r)}if(Array.isArray(e.vertices)&&p(e.vertices[0]))return k(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const n=e.commands.find(r=>r.points.length>0);if(n)return k(n.points[0])}}computeBounds(e){var r;const n=B();if((r=e.pages)!=null&&r.length)for(const i of e.pages)C(n,{x:0,y:0}),C(n,{x:i.width,y:i.height});for(const i of e.entities)this.includeEntityBounds(n,i,0);return et(n)}includeEntityBounds(e,n,r){const i=String(n.type??"").toUpperCase(),o=n.kind??O(i);if(o==="insert"){const s=this.lookupBlock(n.blockName??n.name);if(s&&r<this.opts.maxInsertDepth){const a=ge(n,s.basePoint??{x:0,y:0});for(const c of s.entities)this.includeEntityBounds(e,Y(c,a),r+1);return}}if(o==="line")p(n.startPoint)&&C(e,n.startPoint),p(n.endPoint)&&C(e,n.endPoint);else if(o==="circle"||o==="arc")p(n.center)&&Number.isFinite(n.radius)&&Qe(e,n.center,Number(n.radius));else if(o==="polyline"||o==="solid"||o==="spline")for(const s of[...n.vertices??[],...n.points??[],...n.controlPoints??[],...n.fitPoints??[]])p(s)&&C(e,s);else if(o==="ellipse")p(n.center)&&p(n.majorAxisEndPoint)&&le(n.center,n.majorAxisEndPoint,Number(n.axisRatio??1),Number(n.startAngle??0),Number(n.endAngle??Math.PI*2)).forEach(s=>C(e,s));else if(o==="path")for(const s of n.commands??[])for(const a of s.points)C(e,a);else if(o==="hatch")for(const s of n.loops??[]){for(const a of s.vertices??[])C(e,a);for(const a of s.commands??[])for(const c of a.points)C(e,c)}else{const s=this.entityAnchor(n);s&&C(e,s)}}lookupLayer(e){if(!(!this.document||!e))return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(!(!this.document||!e))return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function Yn(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}const Vn={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class We{constructor(e,n={}){u(this,"canvas");u(this,"backend","webgl");u(this,"gl");u(this,"program");u(this,"eventController",new AbortController);u(this,"imageCache",new Map);u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"overlayCanvas");u(this,"overlayCtx");u(this,"scene");u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"rafHandle",0);u(this,"onStats");u(this,"onViewChange");const r=Hn(e,n);if(!r)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=e,this.gl=r,this.program=Un(r),this.opts={...Vn,...n},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}static isSupported(){return ze()}destroy(){var e,n;this.eventController.abort(),(e=this.resizeObserver)==null||e.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(n=this.overlayCanvas)==null||n.remove()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=Re(e),this.bounds=qn(this.document,this.opts),this.disposeScene();const n=jn(this.document,this.opts,this.bounds);this.scene=Xn(this.gl,n),this.stats=Jn(this.scene,0),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const n=Kn(this.opts,e);if(this.opts={...this.opts,...e},n&&(this.sourceDocument??this.document)){this.setDocument(this.sourceDocument??this.document);return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92){if(!j(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const n=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),i=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),o=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),s=this.clampScale(Math.min(n/i,r/o)*e);this.fitScale=s,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:s},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.resizeOverlay(e,n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const o=this.screenToWorld(r);this.view.centerX+=i.x-o.x,this.view.centerY+=i.y-o.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Qn(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var l;const e=performance.now(),n=this.gl;n.viewport(0,0,this.canvas.width,this.canvas.height);const r=Ve(this.opts.background,[11,16,32,255]);n.clearColor(r[0]/255,r[1]/255,r[2]/255,r[3]/255),n.clear(n.COLOR_BUFFER_BIT),n.disable(n.DEPTH_TEST),n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);let i=0,o=0;const s=this.scene,a=this.visibleWorldBounds();if(s){n.useProgram(this.program.program),n.uniform2f(this.program.uViewCenter,this.view.centerX-s.origin.x,this.view.centerY-s.origin.y),n.uniform1f(this.program.uScale,this.view.scale*this.dpr),n.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),n.uniform1f(this.program.uPointSize,Math.max(1,this.dpr));const f=this.drawBatches(s.lineBatches,n.LINES,a);i+=f.visible,o+=f.culled;const h=this.drawBatches(s.triangleBatches,n.TRIANGLES,a);i+=h.visible,o+=h.culled;const d=this.drawBatches(s.lineTypePointBatches,n.POINTS,a);i+=d.visible,o+=d.culled,n.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const m=this.drawBatches(s.pointBatches,n.POINTS,a);i+=m.visible,o+=m.culled}this.renderOverlay(a);const c=performance.now()-e;return this.stats=s?{...s.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:s.primitiveCount,visiblePrimitiveCount:i,culledPrimitiveCount:o,gpuMemoryBytes:s.gpuMemoryBytes,buildElapsedMs:s.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(l=this.onStats)==null||l.call(this,this.getStats()),this.getStats()}drawBatches(e,n,r){const i=this.gl;let o=0,s=0;for(const a of e){if(!Ye(a.bounds,r)){s+=a.primitiveCount;continue}i.bindBuffer(i.ARRAY_BUFFER,a.positionBuffer),i.enableVertexAttribArray(this.program.aPosition),i.vertexAttribPointer(this.program.aPosition,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,a.colorBuffer),i.enableVertexAttribArray(this.program.aColor),i.vertexAttribPointer(this.program.aColor,4,i.UNSIGNED_BYTE,!0,0,0),i.drawArrays(n,0,a.vertexCount),o+=a.primitiveCount}return{visible:o,culled:s}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(e){var i,o;const n=this.overlayCtx,r=this.overlayCanvas;!n||!r||(n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((o=(i=this.document)==null?void 0:i.pages)!=null&&o.length)&&this.drawPageBoundsOverlay(n),this.scene&&(this.drawImagesOverlay(n,this.scene.imageItems,e),this.drawTextOverlay(n,this.scene.textItems,e)),n.restore())}drawPageBoundsOverlay(e){var n,r;if((r=(n=this.document)==null?void 0:n.pages)!=null&&r.length){e.save(),e.strokeStyle="rgba(148, 163, 184, 0.34)",e.lineWidth=1,e.setLineDash([8,6]);for(const i of this.document.pages){const o=this.worldToScreen({x:0,y:0}),s=this.worldToScreen({x:i.width,y:i.height});e.strokeRect(Math.min(o.x,s.x),Math.min(o.y,s.y),Math.abs(s.x-o.x),Math.abs(s.y-o.y))}e.restore()}}drawTextOverlay(e,n,r){const i=this.opts.maxVisibleTextLabels;let o=0;for(const s of n){if(o>=i)break;if(!Ye(s.bounds,r))continue;const a=Math.abs(s.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(s.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;e.save(),e.translate(c.x,c.y),e.rotate(-s.rotation);const l=Math.max(4,Math.min(256,a));e.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.fillStyle=s.color,e.globalAlpha=s.opacity,e.textBaseline="alphabetic";for(const[f,h]of s.text.split(/\r?\n/g).entries())e.fillText(h,0,f*l*1.22);e.restore(),o++}}drawImagesOverlay(e,n,r){for(const i of n){if(!Ye(i.bounds,r))continue;const o=this.worldToScreen(i.point),s=this.worldToScreen({x:i.point.x+i.width,y:i.point.y-i.height}),a=Math.min(o.x,s.x),c=Math.min(o.y,s.y),l=Math.abs(s.x-o.x),f=Math.abs(s.y-o.y);if(!(l<1||f<1)){if(i.source){const h=this.getImage(i.source);if(h.complete&&h.naturalWidth>0){e.save(),e.globalAlpha=i.opacity,e.drawImage(h,a,c,l,f),e.restore();continue}h.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(e.save(),e.strokeStyle=i.color,e.globalAlpha=i.opacity,e.lineWidth=1,e.strokeRect(a,c,l,f),e.beginPath(),e.moveTo(a,c),e.lineTo(a+l,c+f),e.moveTo(a+l,c),e.lineTo(a,c+f),e.stroke(),e.restore())}}}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}createOverlayCanvas(){const e=this.canvas.parentElement;if(!e||typeof document>"u")return;window.getComputedStyle(e).position==="static"&&(e.style.position="relative");const r=document.createElement("canvas");r.className="cad-viewer-text-overlay",r.setAttribute("aria-hidden","true"),r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.zIndex="1";const i=r.getContext("2d");i&&(e.appendChild(r),this.overlayCanvas=r,this.overlayCtx=i)}resizeOverlay(e,n){this.overlayCanvas&&(this.overlayCanvas.width!==e||this.overlayCanvas.height!==n)&&(this.overlayCanvas.width=e,this.overlayCanvas.height=n)}bindEvents(){const e=this.eventController.signal;this.canvas.addEventListener("wheel",r=>{r.preventDefault();const i=r.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:r.offsetX,y:r.offsetY})},{passive:!1,signal:e}),this.canvas.addEventListener("pointerdown",r=>{this.canvas.setPointerCapture(r.pointerId),this.isDragging=!0,this.lastPointer={x:r.clientX,y:r.clientY},this.canvas.classList.add("is-dragging")},{signal:e}),this.canvas.addEventListener("pointermove",r=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(r.clientX-this.lastPointer.x,r.clientY-this.lastPointer.y),this.lastPointer={x:r.clientX,y:r.clientY})},{signal:e});const n=r=>{r&&this.canvas.hasPointerCapture(r.pointerId)&&this.canvas.releasePointerCapture(r.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",n,{signal:e}),this.canvas.addEventListener("pointercancel",()=>n(),{signal:e}),this.canvas.addEventListener("webglcontextlost",r=>{r.preventDefault(),this.cancelScheduledRender()},{signal:e})}visibleWorldBounds(){const e=this.cssWidth/Math.max(this.view.scale,1e-12)/2,n=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-e,maxX:this.view.centerX+e,minY:this.view.centerY-n,maxY:this.view.centerY+n}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}disposeScene(){if(!this.scene)return;const e=this.gl;for(const n of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.lineTypePointBatches,...this.scene.pointBatches])e.deleteBuffer(n.positionBuffer),e.deleteBuffer(n.colorBuffer);this.scene=void 0}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function ze(){if(typeof document>"u")return!1;const t=document.createElement("canvas");return!!(t.getContext("webgl2")??t.getContext("webgl")??t.getContext("experimental-webgl"))}function Hn(t,e){const n={alpha:!1,antialias:e.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"high-performance"};return t.getContext("webgl2",n)??t.getContext("webgl",n)??t.getContext("experimental-webgl",n)??void 0}function Un(t){const e=`
|
|
9
|
+
`),n=[];for(let d=0;d<e.length-1;d+=2){const h=Number((l=e[d])==null?void 0:l.trim()),m=e[d+1]??"";Number.isFinite(h)&&n.push({code:h,value:m.trimEnd()})}const r=[],i={};let s="",o=[],a;for(let d=0;d<n.length;d++){const h=n[d];if(h.code===0&&h.value==="SECTION"){s=((f=n[d+1])==null?void 0:f.code)===2?n[d+1].value.toUpperCase():"",d++;continue}if(h.code===0&&h.value==="ENDSEC"){c(),s="";continue}s==="ENTITIES"&&(h.code===0?(c(),o=[h]):o.push(h))}return c(),{header:{},tables:{},entities:r,blocks:i};function c(){var m;if(!o.length)return;const d=(m=o[0])==null?void 0:m.value.toUpperCase();if(d==="VERTEX"&&a){const g=E(o,10,20,30);g&&(a.vertices??(a.vertices=[])).push({...g,bulge:w(o,42)}),o=[];return}if(d==="SEQEND"){a&&r.push(a),a=void 0,o=[];return}if(a&&(r.push(a),a=void 0),!d||d==="EOF"){o=[];return}const h=un(d,o);d==="POLYLINE"?a=h:r.push(h),o=[]}}function un(t,e){const n={type:t,handle:ee(e,5),layer:ee(e,8)??"0",colorIndex:w(e,62),trueColor:w(e,420),lineType:ee(e,6),lineweight:w(e,370)};switch(t){case"LINE":Object.assign(n,{startPoint:E(e,10,20,30),endPoint:E(e,11,21,31)});break;case"CIRCLE":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40)});break;case"ARC":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40),startAngle:fe(w(e,50)),endAngle:fe(w(e,51))});break;case"POINT":Object.assign(n,{point:E(e,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(n,{insertionPoint:E(e,10,20,30),text:gn(e),textHeight:w(e,40),rotation:fe(w(e,50))});break;case"LWPOLYLINE":Object.assign(n,{vertices:pn(e),flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"POLYLINE":Object.assign(n,{vertices:[],flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(n,{center:E(e,10,20,30),majorAxisEndPoint:E(e,11,21,31),axisRatio:w(e,40),startAngle:w(e,41),endAngle:w(e,42)});break;case"SPLINE":Object.assign(n,{controlPoints:mn(e,10,20,30),degree:w(e,71),isClosed:(Number(w(e,70)??0)&1)===1});break;case"INSERT":Object.assign(n,{name:ee(e,2),blockName:ee(e,2),insertionPoint:E(e,10,20,30),rotation:fe(w(e,50)),scale:{x:w(e,41)??1,y:w(e,42)??w(e,41)??1,z:w(e,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(n,{vertices:[E(e,10,20,30),E(e,11,21,31),E(e,12,22,32),E(e,13,23,33)].filter(Boolean)});break}return Pe(n)}function w(t,e){var i;const n=(i=t.find(s=>s.code===e))==null?void 0:i.value,r=Number(n);return Number.isFinite(r)?r:void 0}function ee(t,e){var r;const n=(r=t.find(i=>i.code===e))==null?void 0:r.value;return n&&n.length>0?n:void 0}function E(t,e,n,r){const i=w(t,e),s=w(t,n),o=w(t,r);if(!(i===void 0||s===void 0))return o===void 0?{x:i,y:s}:{x:i,y:s,z:o}}function mn(t,e,n,r){const i=[];for(let s=0;s<t.length;s++){if(t[s].code!==e)continue;const o=Number(t[s].value),a=t.slice(s+1).find(d=>d.code===n),c=t.slice(s+1).find(d=>d.code===r),l=Number(a==null?void 0:a.value),f=Number(c==null?void 0:c.value);Number.isFinite(o)&&Number.isFinite(l)&&i.push(Number.isFinite(f)?{x:o,y:l,z:f}:{x:o,y:l})}return i}function pn(t){const e=[];for(let n=0;n<t.length;n++){if(t[n].code!==10)continue;const r=Number(t[n].value);let i,s;for(let o=n+1;o<t.length&&t[o].code!==10;o++)t[o].code===20&&(i=Number(t[o].value)),t[o].code===42&&(s=Number(t[o].value));Number.isFinite(r)&&Number.isFinite(i)&&e.push({x:r,y:i,bulge:Number.isFinite(s)?s:void 0})}return e}function gn(t){const e=t.filter(n=>n.code===1||n.code===3).map(n=>n.value);return e.length?e.join(""):void 0}function fe(t){return typeof t=="number"&&Number.isFinite(t)?W(t):void 0}class ft{constructor(e={}){u(this,"id","dwf");u(this,"label","DWF/DWFx native viewer powered by dwf-viewer");u(this,"formats",["dwf","dwfx","xps"]);u(this,"nativeRenderer",!0);u(this,"defaults");u(this,"native");u(this,"host");u(this,"lastStats");this.defaults=e}accepts(e,n){const r=H(e);if(r==="dwf"||r==="dwfx"||r==="xps")return!0;const i=O(e,n);return i==="dwf"||i==="dwfx"||i==="xps"}async load(e,n={}){var d,h,m,g;const r={...this.defaults,...n},i=performance.now(),s=e.fileName??((d=e.file)==null?void 0:d.name),o=await A(e),a=ut(O(e,o),H(e));(h=r.onProgress)==null||h.call(r,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await M.openDwfDocument(o,{fileName:s});(m=r.onProgress)==null||m.call(r,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const l=ht(c,s,a,r.keepRaw===!0),f=performance.now()-i;return(g=r.onProgress)==null||g.call(r,{phase:"done",format:l.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:f}),{document:l,raw:r.keepRaw?c:void 0,bytes:o.byteLength,elapsedMs:f,format:l.format,warnings:l.warnings}}async mount(e,n,r={}){var y,x,L,R,D;const i={...this.defaults,...r},s=performance.now(),o=e.fileName??((y=e.file)==null?void 0:y.name),a=await A(e),c=ut(O(e,a),H(e)),l=xn(i),f=mt(i),d=Cn(i,l,f),h=pt(i,l,f);(x=i.onProgress)==null||x.call(i,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=n,n.replaceChildren(),this.native=new M.DwfViewer(n,d),(L=i.onProgress)==null||L.call(i,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:o,...h}),(R=i.onProgress)==null||R.call(i,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const m=this.native.getDocument(),g=ht(m,o,c,i.keepRaw===!0);g.metadata.loaderMode="Native DWF",g.metadata.nativeRenderer="dwf-viewer",g.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const k=performance.now()-s;return(D=i.onProgress)==null||D.call(i,{phase:"done",format:g.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:k}),{document:g,raw:i.keepRaw?m:void 0,bytes:a.byteLength,elapsedMs:k,format:g.format,warnings:g.warnings}}unmount(){var e;(e=this.native)==null||e.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var e;(e=this.native)==null||e.fit()}zoomIn(){var n;const e=(n=this.native)==null?void 0:n.zoomInButton;e==null||e.click()}zoomOut(){var n;const e=(n=this.native)==null?void 0:n.zoomOutButton;e==null||e.click()}resize(){var e;(e=this.native)==null||e.render()}setNativeOptions(e){var r,i,s,o;const n=this.native;if(n){if(typeof e.dwfBackground=="string")n.background=e.dwfBackground;else{const a=mt(e);a&&(n.background=a)}typeof e.dwfPreferWebgl=="boolean"&&((r=n.setPreferWebgl)==null||r.call(n,e.dwfPreferWebgl)),typeof e.dwfPreferWasm=="boolean"&&((i=n.setPreferWasm)==null||i.call(n,e.dwfPreferWasm)),e.dwfLineWeightMode&&((s=n.setLineWeightMode)==null||s.call(n,e.dwfLineWeightMode)),he(n,"minStrokeCssPx",e.dwfMinStrokeCssPx),he(n,"maxOverviewStrokeCssPx",e.dwfMaxOverviewStrokeCssPx),he(n,"minTextCssPx",e.dwfMinTextCssPx),he(n,"minFilledAreaCssPx",e.dwfMinFilledAreaCssPx),(o=n.render)==null||o.call(n)}}getLastNativeStats(){return this.lastStats}}function ht(t,e,n,r){var a,c;const i=dt((t==null?void 0:t.diagnostics)??[]),s=((t==null?void 0:t.pageData)??[]).map((l,f)=>bn(l,f));for(const l of(t==null?void 0:t.pageData)??[])i.push(...dt(l.diagnostics));const o={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:t==null?void 0:t.kind,packageEntries:((a=t==null?void 0:t.packageEntries)==null?void 0:a.length)??0,resources:((c=t==null?void 0:t.resources)==null?void 0:c.length)??0,pageKinds:Sn(((t==null?void 0:t.pageData)??[]).map(l=>l.kind)),pageNames:((t==null?void 0:t.pages)??[]).map(l=>l.name)};return ae({format:n,sourceName:e,layers:{},blocks:{},pages:s,entities:qt(s),metadata:o,warnings:Nn(i),raw:r?t:void 0})}function bn(t,e){const n=yn(t,e);return{index:e,name:t.name||t.sourcePath||`${e+1}`,width:t.width||1e3,height:t.height||1e3,entities:n}}function yn(t,e){return t.kind==="w2d-text"?t.primitives.flatMap((n,r)=>vn(n,e,r)):t.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:e,width:t.width,height:t.height,imageSource:t.sourcePath}]:t.kind==="w3d-model"?t.model.meshes.map((n,r)=>({id:n.id,type:"W3D_MESH",kind:"solid",pageIndex:e,color:n.color?kn(n.color):void 0,name:n.name||`mesh-${r+1}`,raw:{vertexCount:n.vertexCount,triangleCount:n.triangleCount,materialId:n.materialId}})):t.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]}function vn(t,e,n){const r={id:`dwf-${e}-${n}`,pageIndex:e,color:t.stroke,fillColor:t.fill,lineweight:t.lineWidth,raw:{matrix:t.matrix}};if(t.type==="polyline"||t.type==="polygon")return[{...r,type:t.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:wn(t.points),isClosed:t.type==="polygon"}];if(t.type==="path")return[{...r,type:"DWF_PATH",kind:"path",commands:t.commands}];if(t.type==="text")return[{...r,type:"DWF_TEXT",kind:"text",insertionPoint:{x:t.x,y:t.y,z:0},text:t.text,textHeight:t.size}];if(t.type==="rect"){const i=t.x,s=t.y,o=t.width,a=t.height;return[{...r,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:i,y:s,z:0},{x:i+o,y:s,z:0},{x:i+o,y:s+a,z:0},{x:i,y:s+a,z:0}]}]}return[]}function wn(t){const e=[];for(let n=0;n+1<t.length;n+=2)e.push({x:t[n],y:t[n+1],z:0});return e}function dt(t){return t.filter(e=>e.level!=="info").map(e=>`${e.code}: ${e.message}${e.source?` (${e.source})`:""}`)}function ut(t,e){return e==="dwf"||e==="dwfx"||e==="xps"?e:t==="dwf"||t==="dwfx"||t==="xps"?t:"dwf"}function xn(t){if(t.dwfWasmUrl)return t.dwfWasmUrl;if(typeof document>"u")return;const e=t.wasmPath?new URL(Pn(t.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",e).href}function mt(t){if(t.dwfBackground)return t.dwfBackground;const e=t.canvasOptions;return(e==null?void 0:e.background)??"#05070d"}function Cn(t,e,n){return{...pt(t,e,n),maxDevicePixelRatio:t.dwfMaxDevicePixelRatio??2,maxCanvasPixels:t.dwfMaxCanvasPixels??16777216}}function pt(t,e,n){return{wasmUrl:e,preferWebgl:t.dwfPreferWebgl??!0,preferWasm:t.dwfPreferWasm??!0,background:n,maxGpuCacheBytes:t.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:t.dwfMaxCachedScenes??2,lineWeightMode:t.dwfLineWeightMode??"adaptive",minStrokeCssPx:t.dwfMinStrokeCssPx,maxOverviewStrokeCssPx:t.dwfMaxOverviewStrokeCssPx,minTextCssPx:t.dwfMinTextCssPx,minFilledAreaCssPx:t.dwfMinFilledAreaCssPx}}function he(t,e,n){typeof n=="number"&&Number.isFinite(n)&&(t[e]=n)}function Pn(t){return t.endsWith("/")?t:`${t}/`}function kn(t){const[e,n,r]=t.map(i=>Math.max(0,Math.min(255,Math.round(i*255))));return`#${Ne(e)}${Ne(n)}${Ne(r)}`}function Ne(t){return t.toString(16).padStart(2,"0")}function Sn(t){const e={};for(const n of t)e[n]=(e[n]??0)+1;return e}function Nn(t){return Array.from(new Set(t))}function gt(t={}){return new Ge([new Qe(t),new st(t),new ft(t)])}function bt(t){const e=t;return e.nativeRenderer===!0&&typeof e.mount=="function"}const Mn={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function F(t,e="#ffffff",n=e){if(typeof t!="number"||Number.isNaN(t))return e;const r=Math.abs(Math.trunc(t));return r===0||r===256||r===257?e:r===7?n:Mn[r]??e}function $(t,e="rgb"){const n=Math.max(0,Math.trunc(t))&16777215,r=n>>16&255,i=n>>8&255,s=n&255;return`rgb(${e==="rgb"?r:s}, ${i}, ${e==="rgb"?s:r})`}function G(t){if(typeof t=="string"){const e=t.trim();return e?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(e)?En(e)??e:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[e.toLowerCase()]:void 0}if(t&&typeof t=="object"){const e=t,n=Number(e.r??e.red),r=Number(e.g??e.green),i=Number(e.b??e.blue),s=Number(e.a??e.alpha??1);if([n,r,i].every(Number.isFinite))return Number.isFinite(s)&&s>=0&&s<1?`rgba(${n}, ${r}, ${i}, ${s})`:`rgb(${n}, ${r}, ${i})`}}function En(t){if(!t)return;const e=t.trim();if(/^#[0-9a-f]{8}$/i.test(e)){const n=parseInt(e.slice(1,3),16)/255,r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),s=parseInt(e.slice(7,9),16);return n>=.999?`rgb(${r}, ${i}, ${s})`:`rgba(${r}, ${i}, ${s}, ${Te(n)})`}if(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e))return e;if(/^sc#/i.test(e)){const n=e.slice(3).split(",").map(a=>Number(a.trim())),[r,i,s,o]=n.length===4?n:[1,...n];if([r,i,s,o].every(Number.isFinite))return`rgba(${Math.round(i*255)}, ${Math.round(s*255)}, ${Math.round(o*255)}, ${Te(r)})`}}function _(t,e,n={}){const r=n.foreground??"#ffffff",i=r;let s;const o=G(t.trueColor)??G(t.color)??G(t.colorName);if(o&&(s=o),!s){const a=Dn(t,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(s=$(a,n.trueColorByteOrder??"rgb"))}if(!s){const a=xt(t.colorIndex,t.colorNumber,t.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(s=F(a,i,r))}if(!s&&typeof t.color=="number"){const a=Number(t.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(s=F(a,i,r)):s=$(a,n.trueColorByteOrder??"rgb")}if(!s){const a=Bn(e,t.layer);s=In(a,n)}return yt(s??i,n)}function Me(t,e,n={}){let r;const i=G(t.fillColor);if(i&&(r=i),!r&&typeof t.fillColor=="number"){const s=t.fillColor;r=Math.abs(s)<=257?F(s,n.foreground??"#ffffff",n.foreground??"#ffffff"):$(s,n.trueColorByteOrder??"rgb")}return!r&&typeof t.fillColorIndex=="number"&&(r=F(t.fillColorIndex,n.foreground??"#ffffff",n.foreground??"#ffffff")),r?yt(r,n):void 0}function yt(t,e={}){if(e.contrastMode!=="adaptive")return t;const n=e.background??"#0b1020",r=e.foreground??"#ffffff";return Ln(t,n,r,e.minColorContrast??2.4)}function Ln(t,e,n,r=2.4){const i=Ee(n)??{r:255,g:255,b:255,a:1},s=Ee(e)??{r:11,g:16,b:32,a:1},o=Ee(t);if(!o)return t;const a=Ct(o,s);if(Ie(a,s)>=r)return t;const c=Le(s),l=c<.5?{r:255,g:255,b:255,a:o.a}:{r:0,g:0,b:0,a:o.a};for(const f of[.25,.4,.55,.7,.85,1]){const d=Fn(o,l,f);if(Ie(Ct(d,s),s)>=r)return Pt(d)}return Ie(i,s)>=r?Pt(i):c<.5?"#ffffff":"#000000"}function vt(t){return t?t.isVisible!==!1&&t.isFrozen!==!0:!0}function In(t,e){if(!t)return;const n=e.foreground??"#ffffff",r=G(t.trueColor);if(r)return r;if(typeof t.trueColor=="number"&&t.trueColor>=0&&t.trueColor<=16777215)return $(t.trueColor,e.trueColorByteOrder??"rgb");const i=G(t.color);if(i)return i;if(An(t.colorIndex))return F(t.colorIndex,n,n);if(typeof t.color=="number"){const s=Number(t.color);return Math.abs(s)<=257?F(s,n,n):$(s,e.trueColorByteOrder??"rgb")}if(typeof t.colorIndex=="number")return F(t.colorIndex,n,n)}function Tn(t){return xt(t.colorIndex,t.colorNumber,t.aci)===0?!0:t.trueColor===void 0&&t.color===0}function wt(t,e,n,r={}){if(!Tn(t))return t;const i=_(e,n,r);return{...t,color:i,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function An(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function Bn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function xt(...t){for(const e of t)if(typeof e=="number"&&Number.isFinite(e))return e}function Dn(t,e){const n=t;for(const r of e){const i=n[r];if(typeof i=="number"&&Number.isFinite(i))return i}}function Ee(t){const e=t.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1};const n=e.match(/^rgba?\(([^)]+)\)$/i);if(n){const r=n[1].split(/[,\s/]+/).filter(Boolean).map(i=>Number(i.replace("%","")));if(r.length>=3&&r.slice(0,3).every(Number.isFinite)){const i=/%/.test(n[1]);return{r:Z(i?r[0]*2.55:r[0]),g:Z(i?r[1]*2.55:r[1]),b:Z(i?r[2]*2.55:r[2]),a:Number.isFinite(r[3])?Math.max(0,Math.min(1,r[3])):1}}}}function Ct(t,e){const n=t.a+e.a*(1-t.a);return n<=0?{r:0,g:0,b:0,a:0}:{r:(t.r*t.a+e.r*e.a*(1-t.a))/n,g:(t.g*t.a+e.g*e.a*(1-t.a))/n,b:(t.b*t.a+e.b*e.a*(1-t.a))/n,a:n}}function Fn(t,e,n){const r=Math.max(0,Math.min(1,n));return{r:t.r+(e.r-t.r)*r,g:t.g+(e.g-t.g)*r,b:t.b+(e.b-t.b)*r,a:t.a}}function Le(t){const e=[t.r,t.g,t.b].map(n=>{const r=n/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Ie(t,e){const n=Le(t),r=Le(e),i=Math.max(n,r),s=Math.min(n,r);return(i+.05)/(s+.05)}function Pt(t){const e=Z(t.r),n=Z(t.g),r=Z(t.b);return t.a<.999?`rgba(${e}, ${n}, ${r}, ${Te(t.a)})`:`rgb(${e}, ${n}, ${r})`}function Z(t){return Math.max(0,Math.min(255,Math.round(t)))}function Te(t){return Math.round(t*1e3)/1e3}const Rn={a:1,b:0,c:0,d:1,e:0,f:0};function de(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function kt(t,e){return{a:1,b:0,c:0,d:1,e:t,f:e}}function St(t){const e=Math.cos(t),n=Math.sin(t);return{a:e,b:n,c:-n,d:e,e:0,f:0}}function On(t,e=t){return{a:t,b:0,c:0,d:e,e:0,f:0}}function T(t,e){return{x:t.x*e.a+t.y*e.c+e.e,y:t.x*e.b+t.y*e.d+e.f,z:"z"in t?t.z:void 0}}function Nt(t,e){if(t)return t.map(n=>({cmd:n.cmd,points:n.points.map(r=>T(r,e))}))}function Ae(t,e={x:0,y:0}){const n=t.insertionPoint??{x:0,y:0},r=t.scale,i=Number(typeof r=="object"&&r?r.x??1:t.scaleX??1),s=Number(typeof r=="object"&&r?r.y??i:t.scaleY??i),o=Number(t.rotation??0);let a=kt(n.x,n.y);return a=de(a,St(Number.isFinite(o)?o:0)),a=de(a,On(Number.isFinite(i)?i:1,Number.isFinite(s)?s:1)),a=de(a,kt(-e.x,-e.y)),a}function q(t,e){const n={...t};if(t.startPoint&&(n.startPoint=T(t.startPoint,e)),t.endPoint&&(n.endPoint=T(t.endPoint,e)),t.center&&(n.center=T(t.center,e)),t.insertionPoint&&(n.insertionPoint=T(t.insertionPoint,e)),t.majorAxisEndPoint){const o=T({x:0,y:0},e),a=T(t.majorAxisEndPoint,e);n.majorAxisEndPoint={x:a.x-o.x,y:a.y-o.y,z:a.z}}t.vertices&&(n.vertices=t.vertices.map(o=>({...T(o,e),bulge:o.bulge,startWidth:o.startWidth,endWidth:o.endWidth}))),t.points&&(n.points=t.points.map(o=>T(o,e))),t.controlPoints&&(n.controlPoints=t.controlPoints.map(o=>T(o,e))),t.fitPoints&&(n.fitPoints=t.fitPoints.map(o=>T(o,e))),t.attribs&&(n.attribs=t.attribs.map(o=>q(o,e))),t.commands&&(n.commands=Nt(t.commands,e)),t.loops&&(n.loops=t.loops.map(o=>{var a;return{...o,vertices:(a=o.vertices)==null?void 0:a.map(c=>T(c,e)),commands:Nt(o.commands,e)}}));const r=Math.sqrt(Math.abs(e.a*e.d-e.b*e.c));typeof t.radius=="number"&&Number.isFinite(r)&&(n.radius=t.radius*r);const i=Math.atan2(e.b,e.a),s=t.kind==="ellipse"||String(t.type??"").toUpperCase()==="ELLIPSE";return Number.isFinite(i)&&Math.abs(i)>1e-14&&((typeof t.rotation=="number"||t.kind==="text"||t.kind==="insert")&&(n.rotation=Number(t.rotation??0)+i),!s&&typeof t.startAngle=="number"&&(n.startAngle=t.startAngle+i),!s&&typeof t.endAngle=="number"&&(n.endAngle=t.endAngle+i)),e.a*e.d-e.b*e.c<0&&n.vertices&&(n.vertices=n.vertices.map(o=>({...o,bulge:typeof o.bulge=="number"?-o.bulge:void 0}))),n}const Wn=16,zn=96,_n=.01;function Be(t,e={}){const n=B();for(const i of t.pages??[])N(n,{x:0,y:0}),N(n,{x:i.width,y:i.height});const r=Et(t,e);for(const i of t.entities)tt(n,Lt(i,r));return nt(n)}function De(t,e,n="auto",r={}){if(n==="extents")return e;const i=Mt(t);if(!i)return e;if(n==="saved-view")return i;const s=B(),o=Et(t,r);let a=0;for(const c of t.entities){const l=Vn(Lt(c,o),i);l&&(a++,tt(s,l))}return a===0||!Hn(s,i)?i:nt(s)}function Mt(t){const e=t.savedView;if(!e||e.source!=="vport"||e.sceneTransformApplied!==!0||!p(e.center))return;const n=Number(e.viewHeight),r=Number(e.aspectRatio);if(!Number.isFinite(n)||n<=1e-9||!Number.isFinite(r)||r<=1e-9)return;const i=n*r;return{minX:e.center.x-i/2,minY:e.center.y-n/2,maxX:e.center.x+i/2,maxY:e.center.y+n/2}}function Et(t,e){return{document:t,maxInsertDepth:Math.max(0,Math.floor(e.maxInsertDepth??Wn)),maxCurveSegments:Math.max(12,Math.floor(e.maxCurveSegments??zn))}}function Lt(t,e,n=0){const r=B();return It(r,t,e,n),r}function It(t,e,n,r){const i=String(e.type??"").toUpperCase(),s=e.kind??U(i);if(s==="insert"){const o=Xn(n.document,e.blockName??e.name);if(o&&r<n.maxInsertDepth){const a=Ae(e,o.basePoint??{x:0,y:0});for(const c of o.entities)It(t,q(c,a),n,r+1);return}}if(s==="line")p(e.startPoint)&&N(t,e.startPoint),p(e.endPoint)&&N(t,e.endPoint);else if(s==="circle"||s==="arc")p(e.center)&&Number.isFinite(e.radius)&&Kt(t,e.center,Number(e.radius));else if(s==="polyline"||s==="solid"||s==="spline")for(const o of[...e.vertices??[],...e.points??[],...e.controlPoints??[],...e.fitPoints??[]])p(o)&&N(t,o);else if(s==="ellipse"){if(p(e.center)&&p(e.majorAxisEndPoint))for(const o of Ce(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),n.maxCurveSegments))N(t,o)}else if(s==="path")for(const o of e.commands??[])for(const a of o.points)N(t,a);else if(s==="hatch")for(const o of e.loops??[]){for(const a of o.vertices??[])N(t,a);for(const a of o.commands??[])for(const c of a.points)N(t,c)}else{const o=Yn(e);o&&N(t,o)}}function Yn(t){for(const e of["startPoint","insertionPoint","center","point","location"]){const n=t[e];if(p(n))return n}if(Array.isArray(t.vertices)&&p(t.vertices[0]))return t.vertices[0];if(Array.isArray(t.commands)){const e=t.commands.find(n=>n.points.length>0);if(e)return e.points[0]}}function Xn(t,e){if(e)return t.blocks[e]??t.blocks[e.toLowerCase()]??Object.values(t.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}function Vn(t,e){if(!I(t)||!I(e))return;const n={minX:Math.max(t.minX,e.minX),minY:Math.max(t.minY,e.minY),maxX:Math.min(t.maxX,e.maxX),maxY:Math.min(t.maxY,e.maxY)};return I(n)?n:void 0}function Hn(t,e){if(!I(t)||!I(e))return!1;const n=Math.hypot(t.maxX-t.minX,t.maxY-t.minY),r=Math.hypot(e.maxX-e.minX,e.maxY-e.minY);return r>1e-9&&n/r>=_n}const Tt=1e5,At=new Set(["","bylayer","15"]),Fe=new Set(["byblock","14"]),Un=new Set(["continuous","16"]),K=t=>String(t??"").trim().toLowerCase();function jn(t){return Fe.has(K(t))}function Re(t,e,n){if(!jn(t.lineType))return t;const r=Oe(e,n);return{...t,lineType:r||"Continuous",lineTypeScale:te(t.lineTypeScale,1)*te(e.lineTypeScale,1)}}function Oe(t,e){var i;let n=String(t.lineType??"").trim();const r=K(n);return At.has(r)?n=((i=Kn(e,t.layer))==null?void 0:i.lineType)??"Continuous":Fe.has(r)&&(n="Continuous"),n||"Continuous"}function ue(t,e){var d,h;if(!e)return;const n=Oe(t,e),r=K(n);if(Un.has(r)||At.has(r)||Fe.has(r))return;const i=qn(e,n);if(!(i!=null&&i.pattern.length))return;const s=te(t.lineTypeScale,te((d=e.header)==null?void 0:d.CELTSCALE,1)),o=te((h=e.header)==null?void 0:h.LTSCALE,1)*s,a=Gn(i,o),c=a.reduce((m,g)=>m+g.length,0);if(!Number.isFinite(c)||c<=1e-9)return;const l=a.some(m=>!m.draw&&m.length>1e-12),f=a.some(m=>m.marker);if(!(!l&&!f))return{name:i.name,segments:Zn(a,l),runs:a,period:c}}function $n(t,e,n){return me(t,e,n).segments}function me(t,e,n,r=Tt){const i=t.filter(y=>Number.isFinite(y.x)&&Number.isFinite(y.y));if(i.length<2||n.runs.length===0)return{segments:[],dots:[]};const s=[];for(let y=0;y<i.length-1;y++)s.push([i[y],i[y+1]]);e&&s.push([i[i.length-1],i[0]]);const o=Number.isFinite(r)?Math.max(1,Math.floor(r)):Tt,a=s.reduce((y,[x,L])=>y+Math.hypot(L.x-x.x,L.y-x.y),0),l=(n.period>1e-12?a/n.period:Number.POSITIVE_INFINITY)*Math.max(1,n.runs.length);if(!Number.isFinite(l)||l>o)return{segments:s,dots:[]};const f={segments:[],dots:[]};let d=0,h=n.runs[0].length,m=!0;const g=y=>{const x=f.dots[f.dots.length-1];x&&Math.hypot(x.x-y.x,x.y-y.y)<=1e-10||f.dots.push(y)},k=()=>{d=(d+1)%n.runs.length,h=n.runs[d].length,m=!0};for(const[y,x]of s){const L=x.x-y.x,R=x.y-y.y,D=Math.hypot(L,R);if(D<=1e-14)continue;let X=0;for(;X<D-1e-12;){let zt=0;for(;h<=1e-12&&zt<n.runs.length;){const V=n.runs[d];if(m&&V.marker){const re=X/D;g({x:y.x+L*re,y:y.y+R*re})}k(),zt++}if(h<=1e-12)break;const _t=n.runs[d];if(m){if(_t.marker){const V=X/D;g({x:y.x+L*V,y:y.y+R*V})}m=!1}const be=Math.min(h,D-X);if(_t.draw&&be>1e-12){const V=X/D,re=(X+be)/D;f.segments.push([{x:y.x+L*V,y:y.y+R*V},{x:y.x+L*re,y:y.y+R*re}])}X+=be,h-=be,h<=1e-12&&k()}}return f}function Gn(t,e){const n=[];for(const r of t.pattern){const i=Number(r.length),s=Number(r.elementTypeFlag??0)!==0;Number.isFinite(i)&&n.push({draw:i>=0,length:Math.abs(i)*e,marker:i>=0&&(i===0||s)})}return n}function Zn(t,e){if(!e)return[];const n=[];for(const i of t){if(i.length<=1e-12)continue;const s=n[n.length-1];(s==null?void 0:s.draw)===i.draw?s.length+=i.length:n.push({draw:i.draw,length:i.length})}const r=[];for(const i of n){const s=r.length%2===0;i.draw!==s&&r.push(1e-9),r.push(i.length)}return r.length%2===1&&r.push(1e-9),r}function qn(t,e){const n=K(e),r=t.lineTypes??{};return r[e]??r[n]??Object.values(r).find(i=>K(i.name)===n||K(i.handle)===n)}function Kn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function te(t,e){const n=Number(t);return Number.isFinite(n)&&n>0?n:e}const Jn=t=>Math.abs(t.a-1)<1e-12&&Math.abs(t.b)<1e-12&&Math.abs(t.c)<1e-12&&Math.abs(t.d-1)<1e-12&&Math.abs(t.e)<1e-9&&Math.abs(t.f)<1e-9;function We(t){var n,r,i;if(t.metadata.sceneTransformApplied===!0||((n=t.savedView)==null?void 0:n.sceneTransformApplied)===!1)return t;const e=((r=t.savedView)==null?void 0:r.sceneTransform)??Rn;return Jn(e)?t:{...t,entities:t.entities.map(s=>q(s,e)),pages:(i=t.pages)==null?void 0:i.map(s=>({...s,entities:s.entities.map(o=>q(o,e))})),metadata:{...t.metadata,sceneTransformApplied:!0}}}const Qn={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,fitMode:"auto",contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class ze{constructor(e,n={}){u(this,"canvas");u(this,"ctx");u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"imageCache",new Map);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});u(this,"onStats");u(this,"onViewChange");const r=e.getContext("2d");if(!r)throw new Error("Canvas 2D context is not available.");this.canvas=e,this.ctx=r,this.opts={...Qn,...n},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}destroy(){var e;(e=this.resizeObserver)==null||e.disconnect()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=We(e),this.bounds=Be(this.document,this.boundsOptions()),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const n=e.fitMode!==void 0&&e.fitMode!==this.opts.fitMode;if(Object.assign(this.opts,e),n&&this.document){this.fitToView();return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92,n=this.opts.fitMode){const r=this.document?De(this.document,this.bounds,n,this.boundsOptions()):this.bounds;if(!I(r)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const i=Math.max(1,this.cssWidth),s=Math.max(1,this.cssHeight),o=Math.max(r.maxX-r.minX,1e-9),a=Math.max(r.maxY-r.minY,1e-9),c=this.clampScale(Math.min(i/o,s/a)*e);this.fitScale=c,this.view={centerX:(r.minX+r.maxX)/2,centerY:(r.minY+r.maxY)/2,scale:c},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const s=this.screenToWorld(r);this.view.centerX+=i.x-s.x,this.view.centerY+=i.y-s.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.render(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return er(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){var n,r;const e=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((n=this.document.pages)!=null&&n.length)&&this.drawPageBounds(this.document);for(const i of this.document.entities)this.drawEntityTracked(i,0)}return this.stats.renderElapsedMs=performance.now()-e,(r=this.onStats)==null||r.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",n=>{n.preventDefault();const r=n.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(r,{x:n.offsetX,y:n.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",n=>{this.canvas.setPointerCapture(n.pointerId),this.isDragging=!0,this.lastPointer={x:n.clientX,y:n.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",n=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(n.clientX-this.lastPointer.x,n.clientY-this.lastPointer.y),this.lastPointer={x:n.clientX,y:n.clientY})});const e=n=>{n&&this.canvas.hasPointerCapture(n.pointerId)&&this.canvas.releasePointerCapture(n.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",e),this.canvas.addEventListener("pointercancel",()=>e())}clearCanvas(){const e=this.ctx;e.save(),e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,this.cssWidth,this.cssHeight),e.fillStyle=this.opts.background,e.fillRect(0,0,this.cssWidth,this.cssHeight),e.restore()}drawPageBounds(e){const n=this.ctx;n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.strokeStyle="rgba(148, 163, 184, 0.35)",n.lineWidth=1,n.setLineDash([8,6]);for(const r of e.pages??[]){const i=this.worldToScreen({x:0,y:0}),s=this.worldToScreen({x:r.width,y:r.height});n.strokeRect(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.abs(s.x-i.x),Math.abs(s.y-i.y))}n.restore()}drawEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!vt(i)){this.stats.skipped++;return}this.drawEntity(e,r,n)}drawEntity(e,n,r){switch(e.kind??U(n)){case"line":return this.drawLine(e);case"circle":return this.drawCircle(e);case"arc":return this.drawArc(e);case"polyline":return this.drawPolyline(e);case"ellipse":return this.drawEllipse(e);case"text":return this.drawText(e);case"point":return this.drawPoint(e);case"insert":return this.drawInsert(e,r);case"solid":return this.drawSolid(e);case"hatch":return this.drawHatch(e);case"spline":return this.drawSpline(e);case"path":return this.drawPath(e);case"image":return this.drawImage(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(e)}}beginStyledPath(e,n=!1,r=!0){const i=this.ctx;i.save(),i.setTransform(this.dpr,0,0,this.dpr,0,0);const s=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o=Me(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??s;i.strokeStyle=s,i.fillStyle=n?o:s,i.globalAlpha=j(Number(e.opacity??1),0,1),i.lineCap="round",i.lineJoin="round";const a=typeof e.lineweight=="number"&&e.lineweight>0?e.lineweight:0;i.lineWidth=Math.max(1,Math.min(12,a>0?a/30:1));const c=r?ue(e,this.document):void 0;i.setLineDash(c?c.segments.map(l=>Math.max(.05,l*this.view.scale)):[]),i.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(e=!1){e&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(e){const n=e.startPoint,r=e.endPoint;if(!p(n)||!p(r))return this.markSkipped("LINE");this.strokeWorldPolyline(e,[n,r],!1)}drawCircle(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");this.strokeWorldPolyline(e,Q(P(n),r,0,Math.PI*2,!0),!0)}drawArc(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),s=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(s))return this.markSkipped("ARC");this.strokeWorldPolyline(e,Q(P(n),r,i,s,!0),!1)}drawPolyline(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=we(e),i=[],s=r?n.length:n.length-1;for(let o=0;o<s;o++){const a=n[o],c=n[(o+1)%n.length];if(!p(a)||!p(c))continue;const l=rt(a,c,Number(a.bulge??0));i.length>0&&l.shift(),i.push(...l)}this.strokeWorldPolyline(e,i,r)}drawEllipse(e){const n=e.center,r=e.majorAxisEndPoint,i=Number(e.axisRatio??1);if(!p(n)||!p(r))return this.markSkipped("ELLIPSE");const s=Ce(n,r,i,Number(e.startAngle??0),Number(e.endAngle??Math.PI*2)),o=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(e,s,o)}drawPoint(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-3,r.y),this.ctx.lineTo(r.x+3,r.y),this.ctx.moveTo(r.x,r.y-3),this.ctx.lineTo(r.x,r.y+3),this.finishStroke()}drawText(e){const n=e.insertionPoint??e.startPoint??e.center,r=it(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r)return this.markSkipped(String(e.type));this.drawTextAt(e,n,r,i,Number(e.rotation??0))}drawInsert(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const a=Ae(e,r.basePoint??{x:0,y:0});for(const c of r.entities){const l=wt(c,e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),f=Re(l,e,this.document);this.drawEntityTracked(q(f,a),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");const s=this.worldToScreen(i);this.beginStyledPath(e);const o=5;if(this.ctx.rect(s.x-o,s.y-o,o*2,o*2),this.finishStroke(),Array.isArray(e.attribs))for(const a of e.attribs)this.drawText(a)}drawSolid(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));this.beginStyledPath(e,!0);const r=this.worldToScreen(n[0]);this.ctx.moveTo(r.x,r.y);for(const i of n.slice(1)){if(!p(i))continue;const s=this.worldToScreen(i);this.ctx.lineTo(s.x,s.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(e){var r,i;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");this.beginStyledPath(e,!0);for(const s of n)if((r=s.commands)!=null&&r.length)this.addPathCommands(s.commands);else if((i=s.vertices)!=null&&i.length){const o=this.worldToScreen(s.vertices[0]);this.ctx.moveTo(o.x,o.y);for(const a of s.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!Me(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(e,n,!!e.isClosed)}drawPath(e){var n;if(!((n=e.commands)!=null&&n.length))return this.markSkipped(String(e.type));this.beginStyledPath(e,!!e.fillColor),this.addPathCommands(e.commands),this.finishFillStroke(!!e.fillColor)}addPathCommands(e){for(const n of e)if(n.cmd==="M"){const r=this.worldToScreen(n.points[0]);this.ctx.moveTo(r.x,r.y)}else if(n.cmd==="L"){const r=this.worldToScreen(n.points[0]);this.ctx.lineTo(r.x,r.y)}else if(n.cmd==="C"){const[r,i,s]=n.points.map(o=>this.worldToScreen(o));this.ctx.bezierCurveTo(r.x,r.y,i.x,i.y,s.x,s.y)}else if(n.cmd==="Q"){const[r,i]=n.points.map(s=>this.worldToScreen(s));this.ctx.quadraticCurveTo(r.x,r.y,i.x,i.y)}else n.cmd==="Z"&&this.ctx.closePath()}drawImage(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32),s=this.worldToScreen(n),o=this.worldToScreen({x:n.x+r,y:n.y-i}),a=Math.min(s.x,o.x),c=Math.min(s.y,o.y),l=Math.abs(o.x-s.x),f=Math.abs(o.y-s.y),d=e.imageDataUrl;if(d){const h=this.getImage(d);if(h.complete&&h.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(h,a,c,l,f),this.ctx.restore(),this.stats.drawn++;return}h.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(e.type));this.beginStyledPath(e),this.ctx.rect(a,c,l,f),this.ctx.moveTo(a,c),this.ctx.lineTo(a+l,c+f),this.ctx.moveTo(a+l,c),this.ctx.lineTo(a,c+f),this.finishStroke()}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}drawUnsupportedMarker(e){const n=this.entityAnchor(e);if(!n)return;const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-4,r.y-4),this.ctx.lineTo(r.x+4,r.y+4),this.ctx.moveTo(r.x+4,r.y-4),this.ctx.lineTo(r.x-4,r.y+4),this.finishStroke()}drawTextAt(e,n,r,i,s){const o=this.ctx,a=this.worldToScreen(n);o.save(),o.setTransform(this.dpr,0,0,this.dpr,0,0),o.translate(a.x,a.y),o.rotate(-s);const c=Math.max(4,Math.min(256,Math.abs(i)*this.view.scale));o.font=`${c}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,o.fillStyle=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o.globalAlpha=j(Number(e.opacity??1),0,1),o.textBaseline="alphabetic";for(const[l,f]of r.split(/\r?\n/g).entries())o.fillText(f,0,l*c*1.22);o.restore(),this.stats.drawn++}strokeWorldPolyline(e,n,r){const i=n.filter(p);if(i.length<2)return this.markSkipped(String(e.type));const s=ue(e,this.document);if(s){const a=me(i,r,s);this.beginStyledPath(e,!1,!1);for(const[c,l]of a.segments){const f=this.worldToScreen(c),d=this.worldToScreen(l);this.ctx.moveTo(f.x,f.y),this.ctx.lineTo(d.x,d.y)}if(this.ctx.stroke(),a.dots.length>0){this.ctx.setLineDash([]),this.ctx.beginPath();const c=Math.max(.5,this.ctx.lineWidth/2);for(const l of a.dots){const f=this.worldToScreen(l);this.ctx.moveTo(f.x+c,f.y),this.ctx.arc(f.x,f.y,c,0,Math.PI*2)}this.ctx.fillStyle=this.ctx.strokeStyle,this.ctx.fill()}this.ctx.restore(),this.stats.drawn++;return}this.beginStyledPath(e);const o=this.worldToScreen(i[0]);this.ctx.moveTo(o.x,o.y);for(const a of i.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}r&&this.ctx.closePath(),this.finishStroke()}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}entityAnchor(e){for(const n of["startPoint","insertionPoint","center","point","location"]){const r=e[n];if(p(r))return P(r)}if(Array.isArray(e.vertices)&&p(e.vertices[0]))return P(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const n=e.commands.find(r=>r.points.length>0);if(n)return P(n.points[0])}}lookupLayer(e){if(!(!this.document||!e))return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(!(!this.document||!e))return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}boundsOptions(){return{maxInsertDepth:this.opts.maxInsertDepth,maxCurveSegments:this.opts.maxCurveSegments}}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function er(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}const tr={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,fitMode:"auto",contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class _e{constructor(e,n={}){u(this,"canvas");u(this,"backend","webgl");u(this,"gl");u(this,"program");u(this,"eventController",new AbortController);u(this,"imageCache",new Map);u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"overlayCanvas");u(this,"overlayCtx");u(this,"scene");u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"rafHandle",0);u(this,"onStats");u(this,"onViewChange");const r=nr(e,n);if(!r)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=e,this.gl=r,this.program=rr(r),this.opts={...tr,...n},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}static isSupported(){return Ye()}destroy(){var e,n;this.eventController.abort(),(e=this.resizeObserver)==null||e.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(n=this.overlayCanvas)==null||n.remove()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=We(e),this.bounds=Be(this.document,this.boundsOptions()),this.disposeScene();const n=sr(this.document,this.opts,this.bounds);this.scene=ir(this.gl,n),this.stats=hr(this.scene,0),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const n=fr(this.opts,e),r=e.fitMode!==void 0&&e.fitMode!==this.opts.fitMode;if(this.opts={...this.opts,...e},n&&(this.sourceDocument??this.document)){this.setDocument(this.sourceDocument??this.document);return}if(r&&this.document){this.fitToView();return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92,n=this.opts.fitMode){const r=this.document?De(this.document,this.bounds,n,this.boundsOptions()):this.bounds;if(!I(r)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const i=Math.max(1,this.cssWidth),s=Math.max(1,this.cssHeight),o=Math.max(r.maxX-r.minX,1e-9),a=Math.max(r.maxY-r.minY,1e-9),c=this.clampScale(Math.min(i/o,s/a)*e);this.fitScale=c,this.view={centerX:(r.minX+r.maxX)/2,centerY:(r.minY+r.maxY)/2,scale:c},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.resizeOverlay(e,n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const s=this.screenToWorld(r);this.view.centerX+=i.x-s.x,this.view.centerY+=i.y-s.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return dr(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var l;const e=performance.now(),n=this.gl;n.viewport(0,0,this.canvas.width,this.canvas.height);const r=He(this.opts.background,[11,16,32,255]);n.clearColor(r[0]/255,r[1]/255,r[2]/255,r[3]/255),n.clear(n.COLOR_BUFFER_BIT),n.disable(n.DEPTH_TEST),n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);let i=0,s=0;const o=this.scene,a=this.visibleWorldBounds();if(o){n.useProgram(this.program.program),n.uniform2f(this.program.uViewCenter,this.view.centerX-o.origin.x,this.view.centerY-o.origin.y),n.uniform1f(this.program.uScale,this.view.scale*this.dpr),n.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),n.uniform1f(this.program.uPointSize,Math.max(1,this.dpr));const f=this.drawBatches(o.lineBatches,n.LINES,a);i+=f.visible,s+=f.culled;const d=this.drawBatches(o.triangleBatches,n.TRIANGLES,a);i+=d.visible,s+=d.culled;const h=this.drawBatches(o.lineTypePointBatches,n.POINTS,a);i+=h.visible,s+=h.culled,n.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const m=this.drawBatches(o.pointBatches,n.POINTS,a);i+=m.visible,s+=m.culled}this.renderOverlay(a);const c=performance.now()-e;return this.stats=o?{...o.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:o.primitiveCount,visiblePrimitiveCount:i,culledPrimitiveCount:s,gpuMemoryBytes:o.gpuMemoryBytes,buildElapsedMs:o.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(l=this.onStats)==null||l.call(this,this.getStats()),this.getStats()}drawBatches(e,n,r){const i=this.gl;let s=0,o=0;for(const a of e){if(!Ve(a.bounds,r)){o+=a.primitiveCount;continue}i.bindBuffer(i.ARRAY_BUFFER,a.positionBuffer),i.enableVertexAttribArray(this.program.aPosition),i.vertexAttribPointer(this.program.aPosition,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,a.colorBuffer),i.enableVertexAttribArray(this.program.aColor),i.vertexAttribPointer(this.program.aColor,4,i.UNSIGNED_BYTE,!0,0,0),i.drawArrays(n,0,a.vertexCount),s+=a.primitiveCount}return{visible:s,culled:o}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(e){var i,s;const n=this.overlayCtx,r=this.overlayCanvas;!n||!r||(n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((s=(i=this.document)==null?void 0:i.pages)!=null&&s.length)&&this.drawPageBoundsOverlay(n),this.scene&&(this.drawImagesOverlay(n,this.scene.imageItems,e),this.drawTextOverlay(n,this.scene.textItems,e)),n.restore())}drawPageBoundsOverlay(e){var n,r;if((r=(n=this.document)==null?void 0:n.pages)!=null&&r.length){e.save(),e.strokeStyle="rgba(148, 163, 184, 0.34)",e.lineWidth=1,e.setLineDash([8,6]);for(const i of this.document.pages){const s=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:i.width,y:i.height});e.strokeRect(Math.min(s.x,o.x),Math.min(s.y,o.y),Math.abs(o.x-s.x),Math.abs(o.y-s.y))}e.restore()}}drawTextOverlay(e,n,r){const i=this.opts.maxVisibleTextLabels;let s=0;for(const o of n){if(s>=i)break;if(!Ve(o.bounds,r))continue;const a=Math.abs(o.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(o.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;e.save(),e.translate(c.x,c.y),e.rotate(-o.rotation);const l=Math.max(4,Math.min(256,a));e.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.fillStyle=o.color,e.globalAlpha=o.opacity,e.textBaseline="alphabetic";for(const[f,d]of o.text.split(/\r?\n/g).entries())e.fillText(d,0,f*l*1.22);e.restore(),s++}}drawImagesOverlay(e,n,r){for(const i of n){if(!Ve(i.bounds,r))continue;const s=this.worldToScreen(i.point),o=this.worldToScreen({x:i.point.x+i.width,y:i.point.y-i.height}),a=Math.min(s.x,o.x),c=Math.min(s.y,o.y),l=Math.abs(o.x-s.x),f=Math.abs(o.y-s.y);if(!(l<1||f<1)){if(i.source){const d=this.getImage(i.source);if(d.complete&&d.naturalWidth>0){e.save(),e.globalAlpha=i.opacity,e.drawImage(d,a,c,l,f),e.restore();continue}d.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(e.save(),e.strokeStyle=i.color,e.globalAlpha=i.opacity,e.lineWidth=1,e.strokeRect(a,c,l,f),e.beginPath(),e.moveTo(a,c),e.lineTo(a+l,c+f),e.moveTo(a+l,c),e.lineTo(a,c+f),e.stroke(),e.restore())}}}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}createOverlayCanvas(){const e=this.canvas.parentElement;if(!e||typeof document>"u")return;window.getComputedStyle(e).position==="static"&&(e.style.position="relative");const r=document.createElement("canvas");r.className="cad-viewer-text-overlay",r.setAttribute("aria-hidden","true"),r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.zIndex="1";const i=r.getContext("2d");i&&(e.appendChild(r),this.overlayCanvas=r,this.overlayCtx=i)}resizeOverlay(e,n){this.overlayCanvas&&(this.overlayCanvas.width!==e||this.overlayCanvas.height!==n)&&(this.overlayCanvas.width=e,this.overlayCanvas.height=n)}bindEvents(){const e=this.eventController.signal;this.canvas.addEventListener("wheel",r=>{r.preventDefault();const i=r.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:r.offsetX,y:r.offsetY})},{passive:!1,signal:e}),this.canvas.addEventListener("pointerdown",r=>{this.canvas.setPointerCapture(r.pointerId),this.isDragging=!0,this.lastPointer={x:r.clientX,y:r.clientY},this.canvas.classList.add("is-dragging")},{signal:e}),this.canvas.addEventListener("pointermove",r=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(r.clientX-this.lastPointer.x,r.clientY-this.lastPointer.y),this.lastPointer={x:r.clientX,y:r.clientY})},{signal:e});const n=r=>{r&&this.canvas.hasPointerCapture(r.pointerId)&&this.canvas.releasePointerCapture(r.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",n,{signal:e}),this.canvas.addEventListener("pointercancel",()=>n(),{signal:e}),this.canvas.addEventListener("webglcontextlost",r=>{r.preventDefault(),this.cancelScheduledRender()},{signal:e})}visibleWorldBounds(){const e=this.cssWidth/Math.max(this.view.scale,1e-12)/2,n=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-e,maxX:this.view.centerX+e,minY:this.view.centerY-n,maxY:this.view.centerY+n}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}boundsOptions(){return{maxInsertDepth:this.opts.maxInsertDepth,maxCurveSegments:this.opts.maxCurveSegments}}disposeScene(){if(!this.scene)return;const e=this.gl;for(const n of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.lineTypePointBatches,...this.scene.pointBatches])e.deleteBuffer(n.positionBuffer),e.deleteBuffer(n.colorBuffer);this.scene=void 0}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function Ye(){if(typeof document>"u")return!1;const t=document.createElement("canvas");return!!(t.getContext("webgl2")??t.getContext("webgl")??t.getContext("experimental-webgl"))}function nr(t,e){const n={alpha:!1,antialias:e.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"high-performance"};return t.getContext("webgl2",n)??t.getContext("webgl",n)??t.getContext("experimental-webgl",n)??void 0}function rr(t){const e=`
|
|
10
10
|
attribute vec2 a_position;
|
|
11
11
|
attribute vec4 a_color;
|
|
12
12
|
uniform vec2 u_viewCenter;
|
|
@@ -30,5 +30,5 @@
|
|
|
30
30
|
void main() {
|
|
31
31
|
gl_FragColor = v_color;
|
|
32
32
|
}
|
|
33
|
-
`,r=Mt(t,t.VERTEX_SHADER,e),i=Mt(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw new Error("Failed to create WebGL program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const f=t.getProgramInfoLog(o)??"Unknown WebGL program link error.";throw t.deleteProgram(o),new Error(f)}t.deleteShader(r),t.deleteShader(i);const s=t.getUniformLocation(o,"u_viewCenter"),a=t.getUniformLocation(o,"u_scale"),c=t.getUniformLocation(o,"u_viewport"),l=t.getUniformLocation(o,"u_pointSize");if(!s||!a||!c||!l)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:o,aPosition:t.getAttribLocation(o,"a_position"),aColor:t.getAttribLocation(o,"a_color"),uViewCenter:s,uScale:a,uViewport:c,uPointSize:l}}function Mt(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create WebGL shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r)??"Unknown WebGL shader compile error.";throw t.deleteShader(r),new Error(i)}return r}function Xn(t,e){let n=0;const r=c=>c.map(l=>{const f=Et(t,l.positions),h=Et(t,l.colors),d=l.positions.byteLength+l.colors.byteLength;return n+=d,{positionBuffer:f,colorBuffer:h,vertexCount:l.positions.length/2,primitiveCount:l.primitiveCount,bounds:l.bounds,gpuBytes:d}}),i=r(e.lineBatches),o=r(e.triangleBatches),s=r(e.lineTypePointBatches),a=r(e.pointBatches);return{origin:e.origin,lineBatches:i,triangleBatches:o,lineTypePointBatches:s,pointBatches:a,textItems:e.textItems,imageItems:e.imageItems,stats:e.stats,primitiveCount:e.primitiveCount,gpuMemoryBytes:n,buildElapsedMs:e.buildElapsedMs}}function Et(t,e){const n=t.createBuffer();if(!n)throw new Error("Failed to create WebGL buffer.");return t.bindBuffer(t.ARRAY_BUFFER,n),t.bufferData(t.ARRAY_BUFFER,e,t.STATIC_DRAW),n}function jn(t,e,n){const r=performance.now(),i=j(n)?{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2}:{x:0,y:0},o=new $n(t,e,n,i);for(const a of t.entities)o.addEntityTracked(a,0);const s=o.finalize();return s.buildElapsedMs=performance.now()-r,s}class $n{constructor(e,n,r,i){u(this,"lineBuckets",new Map);u(this,"triangleBuckets",new Map);u(this,"lineTypePointBuckets",new Map);u(this,"pointBuckets",new Map);u(this,"textItems",[]);u(this,"imageItems",[]);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"tileSize");u(this,"maxVerticesPerBatch");u(this,"primitiveCount",0);this.document=e,this.opts=n,this.bounds=r,this.origin=i;const o=j(r)?Math.max(r.maxX-r.minX,r.maxY-r.minY,1e-9):1;this.tileSize=n.enableSpatialIndex?o/Math.max(8,n.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(n.maxVerticesPerBatch))}addEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!bt(i)){this.stats.skipped++;return}this.addEntity(e,r,n)}finalize(){const e=be(this.lineBuckets,this.maxVerticesPerBatch),n=be(this.triangleBuckets,this.maxVerticesPerBatch),r=be(this.lineTypePointBuckets,this.maxVerticesPerBatch),i=be(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:e,triangleBatches:n,lineTypePointBatches:r,pointBatches:i,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(e,n,r){switch(e.kind??O(n)){case"line":return this.addLineEntity(e);case"circle":return this.addCircleEntity(e);case"arc":return this.addArcEntity(e);case"polyline":return this.addPolylineEntity(e);case"ellipse":return this.addEllipseEntity(e);case"text":return this.addTextEntity(e);case"point":return this.addPointEntity(e);case"insert":return this.addInsertEntity(e,r);case"solid":return this.addSolidEntity(e);case"hatch":return this.addHatchEntity(e);case"spline":return this.addSplineEntity(e);case"path":return this.addPathEntity(e);case"image":return this.addImageEntity(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(e)}}addLineEntity(e){if(!p(e.startPoint)||!p(e.endPoint))return this.markSkipped("LINE");this.addPolyline([e.startPoint,e.endPoint],!1,this.strokeBytes(e),e),this.stats.drawn++}addCircleEntity(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");const i=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(r))*12))),o=Q(n,r,0,Math.PI*2,!0,i);this.addPolyline(o,!0,this.strokeBytes(e),e),this.stats.drawn++}addArcEntity(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),o=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o))return this.markSkipped("ARC");this.addPolyline(Q(n,r,i,o,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(e),e),this.stats.drawn++}addPolylineEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=Ce(e),i=[],o=r?n.length:n.length-1;for(let s=0;s<o;s++){const a=n[s],c=n[(s+1)%n.length];if(!p(a)||!p(c))continue;const l=tt(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));i.length>0&&l.shift(),i.push(...l)}if(i.length<2)return this.markSkipped(String(e.type));this.addPolyline(i,r,this.strokeBytes(e),e),this.stats.drawn++}addEllipseEntity(e){if(!p(e.center)||!p(e.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const n=le(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),this.opts.maxCurveSegments),r=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(n,r,this.strokeBytes(e),e),this.stats.drawn++}addTextEntity(e){const n=e.insertionPoint??e.startPoint??e.center,r=nt(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r||!Number.isFinite(i))return this.markSkipped(String(e.type));const o=k(n),s=Math.max(1,r.split(/\r?\n/g).reduce((c,l)=>Math.max(c,l.length),0))*Math.abs(i)*.62,a=Math.max(1,r.split(/\r?\n/g).length)*Math.abs(i)*1.22;this.textItems.push({point:o,text:r,height:i,rotation:Number(e.rotation??0),color:_(e,this.document,this.colorOptions()),opacity:$(Number(e.opacity??1),0,1),bounds:{minX:o.x-s*.1,minY:o.y-a,maxX:o.x+s,maxY:o.y+a}}),this.stats.drawn++}addPointEntity(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");this.addPoint(n,this.strokeBytes(e)),this.stats.drawn++}addInsertEntity(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const o=ge(e,r.basePoint??{x:0,y:0});for(const s of r.entities){const a=yt(s,e,this.document,this.colorOptions()),c=Fe(a,e,this.document);this.addEntityTracked(Y(c,o),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");if(this.addPoint(i,this.strokeBytes(e)),Array.isArray(e.attribs))for(const o of e.attribs)this.addTextEntity(o);this.stats.drawn++}addSolidEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));const r=n.filter(p).map(k);if(r.length<3)return this.markSkipped(String(e.type));const i=this.fillBytes(e)??this.strokeBytes(e);this.addTriangleFan(r,i),this.addPolyline(r,!0,this.strokeBytes(e),e),this.stats.drawn++}addHatchEntity(e){var s;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");const r=this.strokeBytes(e),i=this.fillBytes(e);let o=!1;for(const a of n){const c=(s=a.commands)!=null&&s.length?Lt(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(p).map(k);c.length<2||(this.addPolyline(c,!0,r,e),i&&c.length>=3&&this.addTriangleFan(c,i),o=!0)}if(!o)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.addPolyline(n.filter(p).map(k),!!e.isClosed,this.strokeBytes(e),e),this.stats.drawn++}addPathEntity(e){var i;if(!((i=e.commands)!=null&&i.length))return this.markSkipped(String(e.type));const n=Lt(e.commands,this.opts.maxCurveSegments);if(n.length<2)return this.markSkipped(String(e.type));this.addPolyline(n,!1,this.strokeBytes(e),e);const r=this.fillBytes(e);r&&n.length>=3&&this.addTriangleFan(n,r),this.stats.drawn++}addImageEntity(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32);if(!Number.isFinite(r)||!Number.isFinite(i))return this.markSkipped(String(e.type));const o=k(n),s=_e([o,{x:o.x+r,y:o.y-i}]);this.imageItems.push({point:o,width:r,height:i,source:e.imageDataUrl??e.imageSource,color:_(e,this.document,this.colorOptions()),opacity:$(Number(e.opacity??1),0,1),bounds:s}),this.stats.drawn++}addUnsupportedMarker(e){const n=It(e);n&&this.addPoint(n,this.strokeBytes(e))}addPolyline(e,n,r,i){const o=e.filter(p).map(k);if(o.length<2)return;const s=i?ue(i,this.document):void 0;if(s){const a=me(o,n,s);for(const[c,l]of a.segments)this.addSegment(c,l,r);for(const c of a.dots)this.addLineTypePoint(c,r);return}for(let a=0;a<o.length-1;a++)this.addSegment(o[a],o[a+1],r);n&&this.addSegment(o[o.length-1],o[0],r)}addSegment(e,n,r){if(!p(e)||!p(n)||Math.hypot(e.x-n.x,e.y-n.y)<=1e-14)return;const i=this.batchFor(this.lineBuckets,_e([e,n]));V(i,e,r,this.origin),V(i,n,r,this.origin),i.primitiveCount++,this.primitiveCount++}addPoint(e,n){const r=this.batchFor(this.pointBuckets,Tt(e));V(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addLineTypePoint(e,n){const r=this.batchFor(this.lineTypePointBuckets,Tt(e));V(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addTriangleFan(e,n){const r=e.filter(p).map(k);if(r.length<3)return;const i=_e(r),o=this.batchFor(this.triangleBuckets,i);for(let s=1;s<r.length-1;s++)V(o,r[0],n,this.origin),V(o,r[s],n,this.origin),V(o,r[s+1],n,this.origin),o.primitiveCount++,this.primitiveCount++}batchFor(e,n){const r=this.bucketKey(n);let i=e.get(r);return i||(i=Gn(),e.set(r,i)),C(i.bounds,{x:n.minX,y:n.minY}),C(i.bounds,{x:n.maxX,y:n.maxY}),i}bucketKey(e){if(!Number.isFinite(this.tileSize))return"all";const n=(e.minX+e.maxX)/2,r=(e.minY+e.maxY)/2,i=Math.floor((n-this.bounds.minX)/this.tileSize),o=Math.floor((r-this.bounds.minY)/this.tileSize);return`${i}:${o}`}strokeBytes(e){return Ve(_(e,this.document,this.colorOptions()),[255,255,255,255],$(Number(e.opacity??1),0,1))}fillBytes(e){const n=Ee(e,this.document,this.colorOptions());return n?Ve(n,[255,255,255,255],$(Number(e.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}lookupLayer(e){if(e)return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(e)return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}}function Gn(){return{positions:[],colors:[],bounds:B(),primitiveCount:0}}function V(t,e,n,r){t.positions.push(e.x-r.x,e.y-r.y),t.colors.push(n[0],n[1],n[2],n[3])}function be(t,e){const n=[];for(const r of t.values()){const i=r.positions.length/2;if(i<=0||!j(r.bounds))continue;if(i<=e){n.push({positions:new Float32Array(r.positions),colors:new Uint8Array(r.colors),bounds:{...r.bounds},primitiveCount:r.primitiveCount});continue}const o=Zn(r),s=Math.max(o,Math.floor(e/o)*o);for(let a=0;a<i;a+=s){const c=Math.min(i,a+s),l=r.positions.slice(a*2,c*2),f=r.colors.slice(a*4,c*4),h=B();for(let d=0;d<l.length;d+=2)C(h,{x:l[d],y:l[d+1]});n.push({positions:new Float32Array(l),colors:new Uint8Array(f),bounds:{...r.bounds},primitiveCount:Math.floor((c-a)/o)})}}return n}function Zn(t){const e=t.positions.length/2;return e===t.primitiveCount?1:e===t.primitiveCount*3?3:2}function qn(t,e){var o;const n=B();if((o=t.pages)!=null&&o.length)for(const s of t.pages)C(n,{x:0,y:0}),C(n,{x:s.width,y:s.height});const r=s=>{if(s)return t.blocks[s]??t.blocks[s.toLowerCase()]??Object.values(t.blocks).find(a=>a.name.toLowerCase()===s.toLowerCase())},i=(s,a)=>{const c=String(s.type??"").toUpperCase(),l=s.kind??O(c);if(l==="insert"){const f=r(s.blockName??s.name);if(f&&a<e.maxInsertDepth){const h=ge(s,f.basePoint??{x:0,y:0});for(const d of f.entities)i(Y(d,h),a+1);return}}if(l==="line")p(s.startPoint)&&C(n,s.startPoint),p(s.endPoint)&&C(n,s.endPoint);else if(l==="circle"||l==="arc")p(s.center)&&Number.isFinite(s.radius)&&Qe(n,s.center,Number(s.radius));else if(l==="polyline"||l==="solid"||l==="spline")for(const f of[...s.vertices??[],...s.points??[],...s.controlPoints??[],...s.fitPoints??[]])p(f)&&C(n,f);else if(l==="ellipse")p(s.center)&&p(s.majorAxisEndPoint)&&le(s.center,s.majorAxisEndPoint,Number(s.axisRatio??1),Number(s.startAngle??0),Number(s.endAngle??Math.PI*2),e.maxCurveSegments).forEach(f=>C(n,f));else if(l==="path")for(const f of s.commands??[])for(const h of f.points)C(n,h);else if(l==="hatch")for(const f of s.loops??[]){for(const h of f.vertices??[])C(n,h);for(const h of f.commands??[])for(const d of h.points)C(n,d)}else{const f=It(s);f&&C(n,f)}};for(const s of t.entities)i(s,0);return et(n)}function Lt(t,e){const n=[];let r,i;const o=s=>{(!n.length||Math.hypot(n[n.length-1].x-s.x,n[n.length-1].y-s.y)>1e-12)&&n.push(k(s)),r=k(s)};for(const s of t)if(s.cmd==="M")r=k(s.points[0]),i=r,o(r);else if(s.cmd==="L")o(s.points[0]);else if(s.cmd==="Q"&&r&&s.points.length>=2){const a=r,[c,l]=s.points,f=Math.max(4,Math.min(e,24));for(let h=1;h<=f;h++){const d=h/f,m=1-d;o({x:m*m*a.x+2*m*d*c.x+d*d*l.x,y:m*m*a.y+2*m*d*c.y+d*d*l.y})}}else if(s.cmd==="C"&&r&&s.points.length>=3){const a=r,[c,l,f]=s.points,h=Math.max(6,Math.min(e,32));for(let d=1;d<=h;d++){const m=d/h,g=1-m;o({x:g**3*a.x+3*g*g*m*c.x+3*g*m*m*l.x+m**3*f.x,y:g**3*a.y+3*g*g*m*c.y+3*g*m*m*l.y+m**3*f.y})}}else s.cmd==="Z"&&i&&o(i);return n}function It(t){for(const e of["startPoint","insertionPoint","center","point","location"]){const n=t[e];if(p(n))return k(n)}if(Array.isArray(t.vertices)&&p(t.vertices[0]))return k(t.vertices[0]);if(Array.isArray(t.commands)&&t.commands.length){const e=t.commands.find(n=>n.points.length>0);if(e)return k(e.points[0])}}function _e(t){const e=B();for(const n of t)C(e,n);return e}function Tt(t){return{minX:t.x,minY:t.y,maxX:t.x,maxY:t.y}}function Ye(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Kn(t,e){return e.trueColorByteOrder!==void 0&&e.trueColorByteOrder!==t.trueColorByteOrder||e.contrastMode!==void 0&&e.contrastMode!==t.contrastMode||e.minColorContrast!==void 0&&e.minColorContrast!==t.minColorContrast||e.foreground!==void 0&&e.foreground!==t.foreground||e.background!==void 0&&e.background!==t.background||e.maxInsertDepth!==void 0&&e.maxInsertDepth!==t.maxInsertDepth||e.maxCurveSegments!==void 0&&e.maxCurveSegments!==t.maxCurveSegments||e.spatialIndexCellCount!==void 0&&e.spatialIndexCellCount!==t.spatialIndexCellCount||e.maxVerticesPerBatch!==void 0&&e.maxVerticesPerBatch!==t.maxVerticesPerBatch||e.enableSpatialIndex!==void 0&&e.enableSpatialIndex!==t.enableSpatialIndex}function Jn(t,e){return{...t.stats,renderElapsedMs:e,backend:"webgl",primitiveCount:t.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function Qn(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function Ve(t,e,n=1){const r=t.trim().toLowerCase();let i;if(/^#[0-9a-f]{3}$/i.test(r))i=[parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16),parseInt(r[3]+r[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(r))i=[parseInt(r.slice(1,3),16),parseInt(r.slice(3,5),16),parseInt(r.slice(5,7),16),255];else{const s=r.match(/^rgba?\(([^)]+)\)$/i);if(s){const a=s[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(f=>f.includes("%")),l=a.map(f=>Number(f.replace("%","")));l.length>=3&&l.slice(0,3).every(Number.isFinite)&&(i=[ne(c?l[0]*2.55:l[0]),ne(c?l[1]*2.55:l[1]),ne(c?l[2]*2.55:l[2]),ne((Number.isFinite(l[3])?l[3]:1)*255)])}}const o=i??e;return[o[0],o[1],o[2],ne(o[3]*n)]}function ne(t){return Math.max(0,Math.min(255,Math.round(t)))}class At{constructor(e={}){u(this,"canvas");u(this,"renderer");u(this,"registry");u(this,"nativeHost");u(this,"options");u(this,"lastResult");u(this,"activeNativeLoader");var n;if(this.options={autoFit:!0,...e},this.registry=e.registry??mt(e),e.loaders)for(const r of e.loaders)this.registry.register(r);if(this.canvas=e.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),e.container)e.container.classList.add("cad-viewer-container"),e.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",e.container.appendChild(this.canvas)),this.nativeHost=e.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),e.nativeHost||e.container.appendChild(this.nativeHost);else if(e.nativeHost)this.nativeHost=e.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((n=e.canvas)!=null&&n.parentElement){e.canvas.parentElement.classList.add("cad-viewer-container");const r=document.createElement("div");r.classList.add("cad-viewer-native-host"),e.canvas.parentElement.appendChild(r),this.nativeHost=r}this.renderer=nr(e.renderer??"auto",this.canvas,e.canvasOptions),this.renderer.onStats=r=>{var i,o;return(o=(i=this.options).onRenderStats)==null?void 0:o.call(i,r)},this.renderer.onViewChange=r=>{var i,o;return(o=(i=this.options).onViewChange)==null?void 0:o.call(i,r)}}registerLoader(e){return this.registry.register(e),this}async loadFile(e,n={}){var r,i;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry({file:e,fileName:e.name},n,e.name)}async loadBuffer(e,n,r={}){var i,o;return(o=(i=this.options).onLoadStart)==null||o.call(i,e),this.loadThroughRegistry({buffer:e,fileName:n},r,n)}async load(e,n={}){var r,i,o;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry(e,n,e.fileName??((o=e.file)==null?void 0:o.name))}setDocument(e,n){var i,o;this.deactivateNativeRenderer();const r={document:e,raw:e.raw,bytes:0,elapsedMs:0,format:e.format,warnings:e.warnings,summary:J(e),fileName:n};return this.renderer.setDocument(e),this.options.autoFit||this.renderer.render(),this.lastResult=r,(o=(i=this.options).onLoad)==null||o.call(i,r),r}fit(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).fit)==null||n.call(e):this.renderer.fitToView()}zoomIn(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomIn)==null||n.call(e):this.renderer.zoomIn()}zoomOut(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomOut)==null||n.call(e):this.renderer.zoomOut()}resize(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).resize)==null||n.call(e):this.renderer.resize()}setCanvasOptions(e){var n,r;this.options.canvasOptions={...this.options.canvasOptions??{},...e},this.renderer.setOptions(e),this.activeNativeLoader&&((r=(n=this.activeNativeLoader).setNativeOptions)==null||r.call(n,{...this.mergeLoadOptions({}),dwfBackground:e.background??this.options.dwfBackground}))}async preloadDwg(e={}){const n=this.registry.list().find(r=>r.id==="dwg");if(!(n!=null&&n.preload))throw new Error("The registered DWG loader does not support preload().");return n.preload(this.mergeLoadOptions(e))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear()}destroy(){var e,n,r;this.deactivateNativeRenderer();for(const i of this.registry.list()){const o=i;(e=o.terminateWorker)==null||e.call(o),(n=o.unmount)==null||n.call(o),(r=o.destroy)==null||r.call(o)}this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getDocument()}getSourceDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getSourceDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(e,n,r){var i,o;try{const s=this.mergeLoadOptions(n);He(s.signal);const a=await this.registry.detect(e),c={...e,buffer:a.bytes};if(pt(a.loader))return await this.applyNativeLoadResult(a.loader,c,s,r);const l=await a.loader.load(c,s);return this.applyLoadResult(l,r)}catch(s){const a=tr(s);throw(o=(i=this.options).onError)==null||o.call(i,a),a}}applyLoadResult(e,n){var i,o,s,a;this.deactivateNativeRenderer(),(o=(i=this.options).onLoadProgress)==null||o.call(i,{phase:"render",format:e.format,message:"Rendering normalized CAD scene…",percent:96}),this.renderer.setDocument(e.document),this.options.autoFit||this.renderer.render();const r={...e,fileName:n,summary:J(e.document)};return this.lastResult=r,(a=(s=this.options).onLoad)==null||a.call(s,r),r}async applyNativeLoadResult(e,n,r,i){var o,s,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");He(r.signal),this.renderer.clear(),(o=this.activeNativeLoader)==null||o.unmount(),this.activeNativeLoader=e,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await e.mount(n,this.nativeHost,r);He(r.signal);const l={...c,fileName:i,summary:J(c.document)};return this.lastResult=l,this.emitNativeRenderStats(c),(a=(s=this.options).onLoad)==null||a.call(s,l),l}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var e,n;if(!this.activeNativeLoader&&!((e=this.nativeHost)!=null&&e.classList.contains("is-active"))){this.canvas.style.display="";return}(n=this.activeNativeLoader)==null||n.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(e){var s,a,c,l;const n=e.document.metadata,r=Number(((s=n.nativeRenderStats)==null?void 0:s.commands)??e.document.entities.length??0),o=String(((a=n.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(l=(c=this.options).onRenderStats)==null||l.call(c,{total:r,drawn:r,skipped:0,byType:J(e.document).byType,unsupported:{},renderElapsedMs:e.elapsedMs,backend:o,primitiveCount:r,visiblePrimitiveCount:r,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:e.elapsedMs})}mergeLoadOptions(e){const n=this.options.onProgress,r=e.onProgress;return{...this.options,...e,onProgress:i=>{var o,s;(s=(o=this.options).onLoadProgress)==null||s.call(o,i),n==null||n(i),r&&r!==n&&r(i)}}}}function er(t={}){return new At(t)}function tr(t){return t instanceof Error?t:new Error(String(t))}function He(t){if(t!=null&&t.aborted)throw new DOMException("Loading cancelled.","AbortError")}function nr(t,e,n={}){if(t==="canvas2d")return new Oe(e,n);if(t==="webgl")return new We(e,n);if(ze())try{return new We(e,n)}catch{}return new Oe(e,n)}function rr(t,e,n,r={}){const i=t&&typeof t=="object"?t:{},o=or(i,r),s=ar(i,r),a=dr(i,r),c=sr(i.header,n),l=cr(i,c),f=l.view,h=Array.isArray(i.entities)?i.entities:[],d={keepRaw:!!r.keepRaw,includeUnknownProperties:!!r.keepRaw},m=h.filter(y=>!!y&&typeof y=="object").map(y=>Bt(y,d)),g=ae({format:"dwg",sourceName:e,header:c,layers:o,lineTypes:s,blocks:a,entities:m,savedView:f,metadata:{parser:"@mlightcad/libredwg-web",parserMode:"wasm",version:n,savedView:f},warnings:l.warning?[l.warning]:[],raw:r.keepRaw?t:void 0});return m.length===0&&g.warnings.push("DWG parsed successfully but no model-space entities were exposed by the converter. Check layout/paper-space content or unsupported proxy objects."),[...new Set(Object.values(s))].some(y=>y.pattern.some(x=>Number(x.elementTypeFlag??0)!==0))&&g.warnings.push("Complex SHX linetype glyphs are preserved in the normalized LTYPE definition and rendered as a dash/dot approximation; embedded shape glyph fidelity is not available yet."),g}function Bt(t,e){const n=ce(t,void 0,{...e,numericColorMode:"rgb"}),r=b(t.color);r!==void 0&&r>=0&&r<=16777215&&(n.color=r,n.trueColor=r),n.colorIndex=b(t.colorIndex??t.colorNumber??t.aci)??n.colorIndex,n.colorName=P(t.colorName??t.color_name)??n.colorName;const i=b(t.flag??t.flags);i!==void 0&&(n.flag=i);const o=String(t.type??t.entityType??"").toUpperCase(),s=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(o);return(t.isClosed===!0||t.closed===!0||s&&(Number(i??0)&1)===1||o==="LWPOLYLINE"&&(Number(i??0)&512)===512)&&(n.isClosed=!0),n}function ir(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function sr(t,e){const n=t&&typeof t=="object"?{...t}:{};return e&&(n.dwgVersion=e),n}function or(t,e){const n={},r=[],i=t.tables;for(const o of["LAYER","layer","layers"]){const s=t[o]??(i==null?void 0:i[o]);s&&r.push(s)}for(const o of r)for(const s of ye(o)){const a=s,c=P(a.name??a.layerName??a.entryName);if(!c)continue;const l=b(a.colorIndex??a.colorNumber),f=b(a.trueColor??a.true_color??a.truecolor??a.colorRGB??a.colorRgb??a.rgbColor??a.rgb),h=b(a.color),d=ir(l),m=f??(!d&&h!==void 0&&h>=0&&h<=16777215?h:void 0),g={name:c,color:d?void 0:a.color??a.colorName,colorIndex:l??(h!==void 0&&Math.abs(h)<=257?h:void 0),trueColor:m,lineType:P(a.lineType??a.linetype),lineweight:b(a.lineweight??a.lineWeight),isVisible:!(a.isVisible===!1||a.off===!0||Number(l??a.color??1)<0),isFrozen:!!(a.isFrozen??a.frozen),isLocked:!!(a.isLocked??a.locked),raw:e.keepRaw?a:void 0};Pe(n,g)}return n}function ar(t,e){const n={},r=t.tables,i=[t.LTYPE,t.ltype,t.lineTypes,r==null?void 0:r.LTYPE,r==null?void 0:r.ltype,r==null?void 0:r.lineTypes];for(const o of i)for(const s of ye(o)){const a=s,c=P(a.name??a.lineTypeName??a.entryName);if(!c)continue;const f=(Array.isArray(a.pattern)?a.pattern:Array.isArray(a.dashes)?a.dashes:[]).flatMap(h=>{if(typeof h=="number")return[{length:h}];if(!h||typeof h!="object")return[];const d=h,m=b(d.elementLength??d.length??d.dashLength);if(m===void 0)return[];const g=b(d.elementTypeFlag),S=b(d.shapeNumber),y=g!==void 0&&S!==void 0;return[{length:m,elementTypeFlag:y?S:b(d.typeFlag??d.elementTypeFlag),shapeNumber:y?g:b(d.shapeCode??d.shapeNumber),scale:b(d.scale),rotation:b(d.rotation),offsetX:b(d.offsetX),offsetY:b(d.offsetY),text:P(d.text)}]});Ut(n,{name:c,handle:P(a.handle??a.id),description:P(a.description),totalPatternLength:b(a.totalPatternLength??a.patternLength),pattern:f,raw:e.keepRaw?a:void 0})}return n}function cr(t,e){const n=t.tables,i=ye(t.VPORT??t.vports??(n==null?void 0:n.VPORT)??(n==null?void 0:n.vports)).filter(x=>!!x&&typeof x=="object").find(x=>String(x.name??"").trim().toLowerCase()==="*active"),o=i?"vport":"header-ucs",s=i??e,a=N(s.ucsOrigin??s.UCSORG??e.UCSORG),c=N(s.ucsXAxis??s.UCSXDIR??e.UCSXDIR),l=N(s.ucsYAxis??s.UCSYDIR??e.UCSYDIR),f=b(s.viewTwistAngle??s.twistAngle??s.VIEWTWIST)??0,h=N(s.viewDirectionFromTarget??s.viewDirection??s.direction??s.VIEWDIR),d=!hr(a,c,l);if(!(!!i||!!h||d||Math.abs(f)>1e-12))return{};const g=fr(h),S=g?lr(a,c,l,f):{a:1,b:0,c:0,d:1,e:0,f:0},y={source:o,name:P(s.name),handle:P(s.handle),center:N(s.center??s.VIEWCTR),target:N(s.viewTarget??s.target??s.TARGET),direction:h,viewHeight:b(s.viewHeight??s.height??s.VIEWSIZE),aspectRatio:b(s.aspectRatio),twistAngle:f,ucsOrigin:a,ucsXAxis:c,ucsYAxis:l,sceneTransformApplied:g,sceneTransform:S};return g?{view:y}:{view:y,warning:"The saved CAD view has a missing, non-finite, or tilted VIEWDIR. File Viewer kept world coordinates instead of applying an unsafe 2D UCS/PLAN rotation."}}function lr(t,e,n,r){const i=Ue(e)??{x:1,y:0},o=Ue(n)??{x:-i.y,y:i.x},s=i.x*o.x+i.y*o.y,a=Ue({x:o.x-i.x*s,y:o.y-i.y*s})??{x:-i.y,y:i.x},c={a:i.x,b:a.x,c:i.y,d:a.y,e:t?-(t.x*i.x+t.y*i.y):0,f:t?-(t.x*a.x+t.y*a.y):0};return pe(St(Number.isFinite(r)?r:0),c)}function Ue(t){if(!t||Math.abs(Number(t.z??0))>1e-6)return;const e=Math.hypot(t.x,t.y);if(!(!Number.isFinite(e)||e<1e-12))return{x:t.x/e,y:t.y/e}}function fr(t){if(!t||!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z))return!1;const e=Math.hypot(t.x,t.y,Number(t.z));return!Number.isFinite(e)||e<1e-12?!1:Math.hypot(t.x,t.y)/e<=1e-4&&Math.abs(Number(t.z))/e>=1-1e-8}function hr(t,e,n){const r=(a,c)=>Number.isFinite(a)&&Math.abs(Number(a)-c)<=1e-10,i=!t||r(t.x,0)&&r(t.y,0)&&r(t.z??0,0),o=!e||r(e.x,1)&&r(e.y,0)&&r(e.z??0,0),s=!n||r(n.x,0)&&r(n.y,1)&&r(n.z??0,0);return i&&o&&s}function dr(t,e){const n={},r=[t.blocks,t.blockHeaders,t.block_records,t.blockRecords],i=t.tables;r.push(i==null?void 0:i.BLOCK,i==null?void 0:i.BLOCK_RECORD,i==null?void 0:i.blocks);const o={keepRaw:!!e.keepRaw,includeUnknownProperties:!!e.keepRaw};for(const s of r)for(const a of ye(s)){const c=a,l=P(c.name??c.blockName??c.name2);if(!l)continue;const h=(Array.isArray(c.entities)?c.entities:Array.isArray(c.ownedObjects)?c.ownedObjects:[]).filter(d=>!!d&&typeof d=="object").map(d=>Bt(d,o));Je(n,{name:l,basePoint:N(c.basePoint??c.origin)??{x:0,y:0},entities:h,raw:e.keepRaw?c:void 0})}return n}function ye(t){if(!t)return[];if(Array.isArray(t))return t;if(typeof t!="object")return[];const e=t,n=Object.values(e).filter(i=>i&&typeof i=="object"),r=["entries","records","items","values","layers","blocks"].flatMap(i=>Array.isArray(e[i])?e[i]:[]);return r.length>0?r:n}v.CadCanvasRenderer=Oe,v.CadLoaderRegistry=je,v.CadViewer=At,v.CadWebGLRenderer=We,v.DwfLoader=ct,v.DwgLoader=Ke,v.DwgWorkerClient=$e,v.DxfLoader=rt,v.applyByBlockLineTypeInheritance=Fe,v.colorFromAci=F,v.colorFromTrueColor=G,v.createCadDocument=ae,v.createCadSceneDocument=Re,v.createCadViewer=er,v.createDashedCadPrimitives=me,v.createDashedCadSegments=An,v.createDefaultLoaderRegistry=mt,v.detectCadFormat=R,v.inferEntityKind=O,v.isCadNativeRenderableLoader=pt,v.isCadPolylineClosed=Ce,v.isWebGLAvailable=ze,v.normalizeCadEntity=ce,v.normalizeDwgDatabase=rr,v.readInputBytes=T,v.resolveCadColor=_,v.resolveCadLinePattern=ue,v.resolveCadLineTypeReference=De,v.summarizeCadDocument=J,v.supportsDwgWorker=ie,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
|
|
33
|
+
`,r=Bt(t,t.VERTEX_SHADER,e),i=Bt(t,t.FRAGMENT_SHADER,n),s=t.createProgram();if(!s)throw new Error("Failed to create WebGL program.");if(t.attachShader(s,r),t.attachShader(s,i),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS)){const f=t.getProgramInfoLog(s)??"Unknown WebGL program link error.";throw t.deleteProgram(s),new Error(f)}t.deleteShader(r),t.deleteShader(i);const o=t.getUniformLocation(s,"u_viewCenter"),a=t.getUniformLocation(s,"u_scale"),c=t.getUniformLocation(s,"u_viewport"),l=t.getUniformLocation(s,"u_pointSize");if(!o||!a||!c||!l)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:s,aPosition:t.getAttribLocation(s,"a_position"),aColor:t.getAttribLocation(s,"a_color"),uViewCenter:o,uScale:a,uViewport:c,uPointSize:l}}function Bt(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create WebGL shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r)??"Unknown WebGL shader compile error.";throw t.deleteShader(r),new Error(i)}return r}function ir(t,e){let n=0;const r=c=>c.map(l=>{const f=Dt(t,l.positions),d=Dt(t,l.colors),h=l.positions.byteLength+l.colors.byteLength;return n+=h,{positionBuffer:f,colorBuffer:d,vertexCount:l.positions.length/2,primitiveCount:l.primitiveCount,bounds:l.bounds,gpuBytes:h}}),i=r(e.lineBatches),s=r(e.triangleBatches),o=r(e.lineTypePointBatches),a=r(e.pointBatches);return{origin:e.origin,lineBatches:i,triangleBatches:s,lineTypePointBatches:o,pointBatches:a,textItems:e.textItems,imageItems:e.imageItems,stats:e.stats,primitiveCount:e.primitiveCount,gpuMemoryBytes:n,buildElapsedMs:e.buildElapsedMs}}function Dt(t,e){const n=t.createBuffer();if(!n)throw new Error("Failed to create WebGL buffer.");return t.bindBuffer(t.ARRAY_BUFFER,n),t.bufferData(t.ARRAY_BUFFER,e,t.STATIC_DRAW),n}function sr(t,e,n){const r=performance.now(),i=I(n)?{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2}:{x:0,y:0},s=new or(t,e,n,i);for(const a of t.entities)s.addEntityTracked(a,0);const o=s.finalize();return o.buildElapsedMs=performance.now()-r,o}class or{constructor(e,n,r,i){u(this,"lineBuckets",new Map);u(this,"triangleBuckets",new Map);u(this,"lineTypePointBuckets",new Map);u(this,"pointBuckets",new Map);u(this,"textItems",[]);u(this,"imageItems",[]);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"tileSize");u(this,"maxVerticesPerBatch");u(this,"primitiveCount",0);this.document=e,this.opts=n,this.bounds=r,this.origin=i;const s=I(r)?Math.max(r.maxX-r.minX,r.maxY-r.minY,1e-9):1;this.tileSize=n.enableSpatialIndex?s/Math.max(8,n.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(n.maxVerticesPerBatch))}addEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!vt(i)){this.stats.skipped++;return}this.addEntity(e,r,n)}finalize(){const e=pe(this.lineBuckets,this.maxVerticesPerBatch),n=pe(this.triangleBuckets,this.maxVerticesPerBatch),r=pe(this.lineTypePointBuckets,this.maxVerticesPerBatch),i=pe(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:e,triangleBatches:n,lineTypePointBatches:r,pointBatches:i,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(e,n,r){switch(e.kind??U(n)){case"line":return this.addLineEntity(e);case"circle":return this.addCircleEntity(e);case"arc":return this.addArcEntity(e);case"polyline":return this.addPolylineEntity(e);case"ellipse":return this.addEllipseEntity(e);case"text":return this.addTextEntity(e);case"point":return this.addPointEntity(e);case"insert":return this.addInsertEntity(e,r);case"solid":return this.addSolidEntity(e);case"hatch":return this.addHatchEntity(e);case"spline":return this.addSplineEntity(e);case"path":return this.addPathEntity(e);case"image":return this.addImageEntity(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(e)}}addLineEntity(e){if(!p(e.startPoint)||!p(e.endPoint))return this.markSkipped("LINE");this.addPolyline([e.startPoint,e.endPoint],!1,this.strokeBytes(e),e),this.stats.drawn++}addCircleEntity(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");const i=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(r))*12))),s=Q(n,r,0,Math.PI*2,!0,i);this.addPolyline(s,!0,this.strokeBytes(e),e),this.stats.drawn++}addArcEntity(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),s=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(s))return this.markSkipped("ARC");this.addPolyline(Q(n,r,i,s,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(e),e),this.stats.drawn++}addPolylineEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=we(e),i=[],s=r?n.length:n.length-1;for(let o=0;o<s;o++){const a=n[o],c=n[(o+1)%n.length];if(!p(a)||!p(c))continue;const l=rt(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));i.length>0&&l.shift(),i.push(...l)}if(i.length<2)return this.markSkipped(String(e.type));this.addPolyline(i,r,this.strokeBytes(e),e),this.stats.drawn++}addEllipseEntity(e){if(!p(e.center)||!p(e.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const n=Ce(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),this.opts.maxCurveSegments),r=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(n,r,this.strokeBytes(e),e),this.stats.drawn++}addTextEntity(e){const n=e.insertionPoint??e.startPoint??e.center,r=it(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r||!Number.isFinite(i))return this.markSkipped(String(e.type));const s=P(n),o=Math.max(1,r.split(/\r?\n/g).reduce((c,l)=>Math.max(c,l.length),0))*Math.abs(i)*.62,a=Math.max(1,r.split(/\r?\n/g).length)*Math.abs(i)*1.22;this.textItems.push({point:s,text:r,height:i,rotation:Number(e.rotation??0),color:_(e,this.document,this.colorOptions()),opacity:j(Number(e.opacity??1),0,1),bounds:{minX:s.x-o*.1,minY:s.y-a,maxX:s.x+o,maxY:s.y+a}}),this.stats.drawn++}addPointEntity(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");this.addPoint(n,this.strokeBytes(e)),this.stats.drawn++}addInsertEntity(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const s=Ae(e,r.basePoint??{x:0,y:0});for(const o of r.entities){const a=wt(o,e,this.document,this.colorOptions()),c=Re(a,e,this.document);this.addEntityTracked(q(c,s),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");if(this.addPoint(i,this.strokeBytes(e)),Array.isArray(e.attribs))for(const s of e.attribs)this.addTextEntity(s);this.stats.drawn++}addSolidEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));const r=n.filter(p).map(P);if(r.length<3)return this.markSkipped(String(e.type));const i=this.fillBytes(e)??this.strokeBytes(e);this.addTriangleFan(r,i),this.addPolyline(r,!0,this.strokeBytes(e),e),this.stats.drawn++}addHatchEntity(e){var o;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");const r=this.strokeBytes(e),i=this.fillBytes(e);let s=!1;for(const a of n){const c=(o=a.commands)!=null&&o.length?Ft(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(p).map(P);c.length<2||(this.addPolyline(c,!0,r,e),i&&c.length>=3&&this.addTriangleFan(c,i),s=!0)}if(!s)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.addPolyline(n.filter(p).map(P),!!e.isClosed,this.strokeBytes(e),e),this.stats.drawn++}addPathEntity(e){var i;if(!((i=e.commands)!=null&&i.length))return this.markSkipped(String(e.type));const n=Ft(e.commands,this.opts.maxCurveSegments);if(n.length<2)return this.markSkipped(String(e.type));this.addPolyline(n,!1,this.strokeBytes(e),e);const r=this.fillBytes(e);r&&n.length>=3&&this.addTriangleFan(n,r),this.stats.drawn++}addImageEntity(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32);if(!Number.isFinite(r)||!Number.isFinite(i))return this.markSkipped(String(e.type));const s=P(n),o=Xe([s,{x:s.x+r,y:s.y-i}]);this.imageItems.push({point:s,width:r,height:i,source:e.imageDataUrl??e.imageSource,color:_(e,this.document,this.colorOptions()),opacity:j(Number(e.opacity??1),0,1),bounds:o}),this.stats.drawn++}addUnsupportedMarker(e){const n=lr(e);n&&this.addPoint(n,this.strokeBytes(e))}addPolyline(e,n,r,i){const s=e.filter(p).map(P);if(s.length<2)return;const o=i?ue(i,this.document):void 0;if(o){const a=me(s,n,o);for(const[c,l]of a.segments)this.addSegment(c,l,r);for(const c of a.dots)this.addLineTypePoint(c,r);return}for(let a=0;a<s.length-1;a++)this.addSegment(s[a],s[a+1],r);n&&this.addSegment(s[s.length-1],s[0],r)}addSegment(e,n,r){if(!p(e)||!p(n)||Math.hypot(e.x-n.x,e.y-n.y)<=1e-14)return;const i=this.batchFor(this.lineBuckets,Xe([e,n]));Y(i,e,r,this.origin),Y(i,n,r,this.origin),i.primitiveCount++,this.primitiveCount++}addPoint(e,n){const r=this.batchFor(this.pointBuckets,Rt(e));Y(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addLineTypePoint(e,n){const r=this.batchFor(this.lineTypePointBuckets,Rt(e));Y(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addTriangleFan(e,n){const r=e.filter(p).map(P);if(r.length<3)return;const i=Xe(r),s=this.batchFor(this.triangleBuckets,i);for(let o=1;o<r.length-1;o++)Y(s,r[0],n,this.origin),Y(s,r[o],n,this.origin),Y(s,r[o+1],n,this.origin),s.primitiveCount++,this.primitiveCount++}batchFor(e,n){const r=this.bucketKey(n);let i=e.get(r);return i||(i=ar(),e.set(r,i)),N(i.bounds,{x:n.minX,y:n.minY}),N(i.bounds,{x:n.maxX,y:n.maxY}),i}bucketKey(e){if(!Number.isFinite(this.tileSize))return"all";const n=(e.minX+e.maxX)/2,r=(e.minY+e.maxY)/2,i=Math.floor((n-this.bounds.minX)/this.tileSize),s=Math.floor((r-this.bounds.minY)/this.tileSize);return`${i}:${s}`}strokeBytes(e){return He(_(e,this.document,this.colorOptions()),[255,255,255,255],j(Number(e.opacity??1),0,1))}fillBytes(e){const n=Me(e,this.document,this.colorOptions());return n?He(n,[255,255,255,255],j(Number(e.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}lookupLayer(e){if(e)return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(e)return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}}function ar(){return{positions:[],colors:[],bounds:B(),primitiveCount:0}}function Y(t,e,n,r){t.positions.push(e.x-r.x,e.y-r.y),t.colors.push(n[0],n[1],n[2],n[3])}function pe(t,e){const n=[];for(const r of t.values()){const i=r.positions.length/2;if(i<=0||!I(r.bounds))continue;if(i<=e){n.push({positions:new Float32Array(r.positions),colors:new Uint8Array(r.colors),bounds:{...r.bounds},primitiveCount:r.primitiveCount});continue}const s=cr(r),o=Math.max(s,Math.floor(e/s)*s);for(let a=0;a<i;a+=o){const c=Math.min(i,a+o),l=r.positions.slice(a*2,c*2),f=r.colors.slice(a*4,c*4),d=B();for(let h=0;h<l.length;h+=2)N(d,{x:l[h],y:l[h+1]});n.push({positions:new Float32Array(l),colors:new Uint8Array(f),bounds:{...r.bounds},primitiveCount:Math.floor((c-a)/s)})}}return n}function cr(t){const e=t.positions.length/2;return e===t.primitiveCount?1:e===t.primitiveCount*3?3:2}function Ft(t,e){const n=[];let r,i;const s=o=>{(!n.length||Math.hypot(n[n.length-1].x-o.x,n[n.length-1].y-o.y)>1e-12)&&n.push(P(o)),r=P(o)};for(const o of t)if(o.cmd==="M")r=P(o.points[0]),i=r,s(r);else if(o.cmd==="L")s(o.points[0]);else if(o.cmd==="Q"&&r&&o.points.length>=2){const a=r,[c,l]=o.points,f=Math.max(4,Math.min(e,24));for(let d=1;d<=f;d++){const h=d/f,m=1-h;s({x:m*m*a.x+2*m*h*c.x+h*h*l.x,y:m*m*a.y+2*m*h*c.y+h*h*l.y})}}else if(o.cmd==="C"&&r&&o.points.length>=3){const a=r,[c,l,f]=o.points,d=Math.max(6,Math.min(e,32));for(let h=1;h<=d;h++){const m=h/d,g=1-m;s({x:g**3*a.x+3*g*g*m*c.x+3*g*m*m*l.x+m**3*f.x,y:g**3*a.y+3*g*g*m*c.y+3*g*m*m*l.y+m**3*f.y})}}else o.cmd==="Z"&&i&&s(i);return n}function lr(t){for(const e of["startPoint","insertionPoint","center","point","location"]){const n=t[e];if(p(n))return P(n)}if(Array.isArray(t.vertices)&&p(t.vertices[0]))return P(t.vertices[0]);if(Array.isArray(t.commands)&&t.commands.length){const e=t.commands.find(n=>n.points.length>0);if(e)return P(e.points[0])}}function Xe(t){const e=B();for(const n of t)N(e,n);return e}function Rt(t){return{minX:t.x,minY:t.y,maxX:t.x,maxY:t.y}}function Ve(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function fr(t,e){return e.trueColorByteOrder!==void 0&&e.trueColorByteOrder!==t.trueColorByteOrder||e.contrastMode!==void 0&&e.contrastMode!==t.contrastMode||e.minColorContrast!==void 0&&e.minColorContrast!==t.minColorContrast||e.foreground!==void 0&&e.foreground!==t.foreground||e.background!==void 0&&e.background!==t.background||e.maxInsertDepth!==void 0&&e.maxInsertDepth!==t.maxInsertDepth||e.maxCurveSegments!==void 0&&e.maxCurveSegments!==t.maxCurveSegments||e.spatialIndexCellCount!==void 0&&e.spatialIndexCellCount!==t.spatialIndexCellCount||e.maxVerticesPerBatch!==void 0&&e.maxVerticesPerBatch!==t.maxVerticesPerBatch||e.enableSpatialIndex!==void 0&&e.enableSpatialIndex!==t.enableSpatialIndex}function hr(t,e){return{...t.stats,renderElapsedMs:e,backend:"webgl",primitiveCount:t.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function dr(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function He(t,e,n=1){const r=t.trim().toLowerCase();let i;if(/^#[0-9a-f]{3}$/i.test(r))i=[parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16),parseInt(r[3]+r[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(r))i=[parseInt(r.slice(1,3),16),parseInt(r.slice(3,5),16),parseInt(r.slice(5,7),16),255];else{const o=r.match(/^rgba?\(([^)]+)\)$/i);if(o){const a=o[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(f=>f.includes("%")),l=a.map(f=>Number(f.replace("%","")));l.length>=3&&l.slice(0,3).every(Number.isFinite)&&(i=[ne(c?l[0]*2.55:l[0]),ne(c?l[1]*2.55:l[1]),ne(c?l[2]*2.55:l[2]),ne((Number.isFinite(l[3])?l[3]:1)*255)])}}const s=i??e;return[s[0],s[1],s[2],ne(s[3]*n)]}function ne(t){return Math.max(0,Math.min(255,Math.round(t)))}class Ot{constructor(e={}){u(this,"canvas");u(this,"renderer");u(this,"registry");u(this,"nativeHost");u(this,"options");u(this,"lastResult");u(this,"activeNativeLoader");var n;if(this.options={autoFit:!0,...e},this.registry=e.registry??gt(e),e.loaders)for(const r of e.loaders)this.registry.register(r);if(this.canvas=e.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),e.container)e.container.classList.add("cad-viewer-container"),e.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",e.container.appendChild(this.canvas)),this.nativeHost=e.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),e.nativeHost||e.container.appendChild(this.nativeHost);else if(e.nativeHost)this.nativeHost=e.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((n=e.canvas)!=null&&n.parentElement){e.canvas.parentElement.classList.add("cad-viewer-container");const r=document.createElement("div");r.classList.add("cad-viewer-native-host"),e.canvas.parentElement.appendChild(r),this.nativeHost=r}this.renderer=pr(e.renderer??"auto",this.canvas,e.canvasOptions),this.renderer.onStats=r=>{var i,s;return(s=(i=this.options).onRenderStats)==null?void 0:s.call(i,r)},this.renderer.onViewChange=r=>{var i,s;return(s=(i=this.options).onViewChange)==null?void 0:s.call(i,r)}}registerLoader(e){return this.registry.register(e),this}async loadFile(e,n={}){var r,i;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry({file:e,fileName:e.name},n,e.name)}async loadBuffer(e,n,r={}){var i,s;return(s=(i=this.options).onLoadStart)==null||s.call(i,e),this.loadThroughRegistry({buffer:e,fileName:n},r,n)}async load(e,n={}){var r,i,s;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry(e,n,e.fileName??((s=e.file)==null?void 0:s.name))}setDocument(e,n){var i,s;this.deactivateNativeRenderer();const r={document:e,raw:e.raw,bytes:0,elapsedMs:0,format:e.format,warnings:e.warnings,summary:J(e),fileName:n};return this.renderer.setDocument(e),this.options.autoFit||this.renderer.render(),this.lastResult=r,(s=(i=this.options).onLoad)==null||s.call(i,r),r}fit(e){var n,r;this.activeNativeLoader?(r=(n=this.activeNativeLoader).fit)==null||r.call(n):this.renderer.fitToView(.92,e)}zoomIn(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomIn)==null||n.call(e):this.renderer.zoomIn()}zoomOut(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomOut)==null||n.call(e):this.renderer.zoomOut()}resize(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).resize)==null||n.call(e):this.renderer.resize()}setCanvasOptions(e){var n,r;this.options.canvasOptions={...this.options.canvasOptions??{},...e},this.renderer.setOptions(e),this.activeNativeLoader&&((r=(n=this.activeNativeLoader).setNativeOptions)==null||r.call(n,{...this.mergeLoadOptions({}),dwfBackground:e.background??this.options.dwfBackground}))}async preloadDwg(e={}){const n=this.registry.list().find(r=>r.id==="dwg");if(!(n!=null&&n.preload))throw new Error("The registered DWG loader does not support preload().");return n.preload(this.mergeLoadOptions(e))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear()}destroy(){var e,n,r;this.deactivateNativeRenderer();for(const i of this.registry.list()){const s=i;(e=s.terminateWorker)==null||e.call(s),(n=s.unmount)==null||n.call(s),(r=s.destroy)==null||r.call(s)}this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getDocument()}getSourceDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getSourceDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(e,n,r){var i,s;try{const o=this.mergeLoadOptions(n);Ue(o.signal);const a=await this.registry.detect(e),c={...e,buffer:a.bytes};if(bt(a.loader))return await this.applyNativeLoadResult(a.loader,c,o,r);const l=await a.loader.load(c,o);return this.applyLoadResult(l,r)}catch(o){const a=mr(o);throw(s=(i=this.options).onError)==null||s.call(i,a),a}}applyLoadResult(e,n){var i,s,o,a;this.deactivateNativeRenderer(),(s=(i=this.options).onLoadProgress)==null||s.call(i,{phase:"render",format:e.format,message:"Rendering normalized CAD scene…",percent:96}),this.renderer.setDocument(e.document),this.options.autoFit||this.renderer.render();const r={...e,fileName:n,summary:J(e.document)};return this.lastResult=r,(a=(o=this.options).onLoad)==null||a.call(o,r),r}async applyNativeLoadResult(e,n,r,i){var s,o,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");Ue(r.signal),this.renderer.clear(),(s=this.activeNativeLoader)==null||s.unmount(),this.activeNativeLoader=e,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await e.mount(n,this.nativeHost,r);Ue(r.signal);const l={...c,fileName:i,summary:J(c.document)};return this.lastResult=l,this.emitNativeRenderStats(c),(a=(o=this.options).onLoad)==null||a.call(o,l),l}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var e,n;if(!this.activeNativeLoader&&!((e=this.nativeHost)!=null&&e.classList.contains("is-active"))){this.canvas.style.display="";return}(n=this.activeNativeLoader)==null||n.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(e){var o,a,c,l;const n=e.document.metadata,r=Number(((o=n.nativeRenderStats)==null?void 0:o.commands)??e.document.entities.length??0),s=String(((a=n.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(l=(c=this.options).onRenderStats)==null||l.call(c,{total:r,drawn:r,skipped:0,byType:J(e.document).byType,unsupported:{},renderElapsedMs:e.elapsedMs,backend:s,primitiveCount:r,visiblePrimitiveCount:r,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:e.elapsedMs})}mergeLoadOptions(e){const n=this.options.onProgress,r=e.onProgress;return{...this.options,...e,onProgress:i=>{var s,o;(o=(s=this.options).onLoadProgress)==null||o.call(s,i),n==null||n(i),r&&r!==n&&r(i)}}}}function ur(t={}){return new Ot(t)}function mr(t){return t instanceof Error?t:new Error(String(t))}function Ue(t){if(t!=null&&t.aborted)throw new DOMException("Loading cancelled.","AbortError")}function pr(t,e,n={}){if(t==="canvas2d")return new ze(e,n);if(t==="webgl")return new _e(e,n);if(Ye())try{return new _e(e,n)}catch{}return new ze(e,n)}function gr(t,e,n,r={}){const i=t&&typeof t=="object"?t:{},s=vr(i,r),o=wr(i,r),a=Sr(i,r),c=yr(i.header,n),l=xr(i,c),f=l.view,d=Array.isArray(i.entities)?i.entities:[],h={keepRaw:!!r.keepRaw,includeUnknownProperties:!!r.keepRaw},m=d.filter(y=>!!y&&typeof y=="object").map(y=>Wt(y,h)),g=ae({format:"dwg",sourceName:e,header:c,layers:s,lineTypes:o,blocks:a,entities:m,savedView:f,metadata:{parser:"@mlightcad/libredwg-web",parserMode:"wasm",version:n,savedView:f},warnings:l.warning?[l.warning]:[],raw:r.keepRaw?t:void 0});return m.length===0&&g.warnings.push("DWG parsed successfully but no model-space entities were exposed by the converter. Check layout/paper-space content or unsupported proxy objects."),[...new Set(Object.values(o))].some(y=>y.pattern.some(x=>Number(x.elementTypeFlag??0)!==0))&&g.warnings.push("Complex SHX linetype glyphs are preserved in the normalized LTYPE definition and rendered as a dash/dot approximation; embedded shape glyph fidelity is not available yet."),g}function Wt(t,e){const n=ce(t,void 0,{...e,numericColorMode:"rgb"}),r=b(t.color);r!==void 0&&r>=0&&r<=16777215&&(n.color=r,n.trueColor=r),n.colorIndex=b(t.colorIndex??t.colorNumber??t.aci)??n.colorIndex,n.colorName=C(t.colorName??t.color_name)??n.colorName;const i=b(t.flag??t.flags);i!==void 0&&(n.flag=i);const s=String(t.type??t.entityType??"").toUpperCase(),o=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(s);return(t.isClosed===!0||t.closed===!0||o&&(Number(i??0)&1)===1||s==="LWPOLYLINE"&&(Number(i??0)&512)===512)&&(n.isClosed=!0),n}function br(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function yr(t,e){const n=t&&typeof t=="object"?{...t}:{};return e&&(n.dwgVersion=e),n}function vr(t,e){const n={},r=[],i=t.tables;for(const s of["LAYER","layer","layers"]){const o=t[s]??(i==null?void 0:i[s]);o&&r.push(o)}for(const s of r)for(const o of ge(s)){const a=o,c=C(a.name??a.layerName??a.entryName);if(!c)continue;const l=b(a.colorIndex??a.colorNumber),f=b(a.trueColor??a.true_color??a.truecolor??a.colorRGB??a.colorRgb??a.rgbColor??a.rgb),d=b(a.color),h=br(l),m=f??(!h&&d!==void 0&&d>=0&&d<=16777215?d:void 0),g={name:c,color:h?void 0:a.color??a.colorName,colorIndex:l??(d!==void 0&&Math.abs(d)<=257?d:void 0),trueColor:m,lineType:C(a.lineType??a.linetype),lineweight:b(a.lineweight??a.lineWeight),isVisible:!(a.isVisible===!1||a.off===!0||Number(l??a.color??1)<0),isFrozen:!!(a.isFrozen??a.frozen),isLocked:!!(a.isLocked??a.locked),raw:e.keepRaw?a:void 0};xe(n,g)}return n}function wr(t,e){const n={},r=t.tables,i=[t.LTYPE,t.ltype,t.lineTypes,r==null?void 0:r.LTYPE,r==null?void 0:r.ltype,r==null?void 0:r.lineTypes];for(const s of i)for(const o of ge(s)){const a=o,c=C(a.name??a.lineTypeName??a.entryName);if(!c)continue;const f=(Array.isArray(a.pattern)?a.pattern:Array.isArray(a.dashes)?a.dashes:[]).flatMap(d=>{if(typeof d=="number")return[{length:d}];if(!d||typeof d!="object")return[];const h=d,m=b(h.elementLength??h.length??h.dashLength);if(m===void 0)return[];const g=b(h.elementTypeFlag),k=b(h.shapeNumber),y=g!==void 0&&k!==void 0;return[{length:m,elementTypeFlag:y?k:b(h.typeFlag??h.elementTypeFlag),shapeNumber:y?g:b(h.shapeCode??h.shapeNumber),scale:b(h.scale),rotation:b(h.rotation),offsetX:b(h.offsetX),offsetY:b(h.offsetY),text:C(h.text)}]});Zt(n,{name:c,handle:C(a.handle??a.id),description:C(a.description),totalPatternLength:b(a.totalPatternLength??a.patternLength),pattern:f,raw:e.keepRaw?a:void 0})}return n}function xr(t,e){const n=t.tables,i=ge(t.VPORT??t.vports??(n==null?void 0:n.VPORT)??(n==null?void 0:n.vports)).filter(x=>!!x&&typeof x=="object").find(x=>String(x.name??"").trim().toLowerCase()==="*active"),s=i?"vport":"header-ucs",o=i??e,a=S(o.ucsOrigin??o.UCSORG??e.UCSORG),c=S(o.ucsXAxis??o.UCSXDIR??e.UCSXDIR),l=S(o.ucsYAxis??o.UCSYDIR??e.UCSYDIR),f=b(o.viewTwistAngle??o.twistAngle??o.VIEWTWIST)??0,d=S(o.viewDirectionFromTarget??o.viewDirection??o.direction??o.VIEWDIR),h=!kr(a,c,l);if(!(!!i||!!d||h||Math.abs(f)>1e-12))return{};const g=Pr(d),k=g?Cr(a,c,l,f):{a:1,b:0,c:0,d:1,e:0,f:0},y={source:s,name:C(o.name),handle:C(o.handle),center:S(o.center??o.VIEWCTR),target:S(o.viewTarget??o.target??o.TARGET),direction:d,viewHeight:b(o.viewHeight??o.height??o.VIEWSIZE),aspectRatio:b(o.aspectRatio),twistAngle:f,ucsOrigin:a,ucsXAxis:c,ucsYAxis:l,sceneTransformApplied:g,sceneTransform:k};return g?{view:y}:{view:y,warning:"The saved CAD view has a missing, non-finite, or tilted VIEWDIR. File Viewer kept world coordinates instead of applying an unsafe 2D UCS/PLAN rotation."}}function Cr(t,e,n,r){const i=je(e)??{x:1,y:0},s=je(n)??{x:-i.y,y:i.x},o=i.x*s.x+i.y*s.y,a=je({x:s.x-i.x*o,y:s.y-i.y*o})??{x:-i.y,y:i.x},c={a:i.x,b:a.x,c:i.y,d:a.y,e:t?-(t.x*i.x+t.y*i.y):0,f:t?-(t.x*a.x+t.y*a.y):0};return de(St(Number.isFinite(r)?r:0),c)}function je(t){if(!t||Math.abs(Number(t.z??0))>1e-6)return;const e=Math.hypot(t.x,t.y);if(!(!Number.isFinite(e)||e<1e-12))return{x:t.x/e,y:t.y/e}}function Pr(t){if(!t||!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z))return!1;const e=Math.hypot(t.x,t.y,Number(t.z));return!Number.isFinite(e)||e<1e-12?!1:Math.hypot(t.x,t.y)/e<=1e-4&&Math.abs(Number(t.z))/e>=1-1e-8}function kr(t,e,n){const r=(a,c)=>Number.isFinite(a)&&Math.abs(Number(a)-c)<=1e-10,i=!t||r(t.x,0)&&r(t.y,0)&&r(t.z??0,0),s=!e||r(e.x,1)&&r(e.y,0)&&r(e.z??0,0),o=!n||r(n.x,0)&&r(n.y,1)&&r(n.z??0,0);return i&&s&&o}function Sr(t,e){const n={},r=[t.blocks,t.blockHeaders,t.block_records,t.blockRecords],i=t.tables;r.push(i==null?void 0:i.BLOCK,i==null?void 0:i.BLOCK_RECORD,i==null?void 0:i.blocks);const s={keepRaw:!!e.keepRaw,includeUnknownProperties:!!e.keepRaw};for(const o of r)for(const a of ge(o)){const c=a,l=C(c.name??c.blockName??c.name2);if(!l)continue;const d=(Array.isArray(c.entities)?c.entities:Array.isArray(c.ownedObjects)?c.ownedObjects:[]).filter(h=>!!h&&typeof h=="object").map(h=>Wt(h,s));et(n,{name:l,basePoint:S(c.basePoint??c.origin)??{x:0,y:0},entities:d,raw:e.keepRaw?c:void 0})}return n}function ge(t){if(!t)return[];if(Array.isArray(t))return t;if(typeof t!="object")return[];const e=t,n=Object.values(e).filter(i=>i&&typeof i=="object"),r=["entries","records","items","values","layers","blocks"].flatMap(i=>Array.isArray(e[i])?e[i]:[]);return r.length>0?r:n}v.CadCanvasRenderer=ze,v.CadLoaderRegistry=Ge,v.CadViewer=Ot,v.CadWebGLRenderer=_e,v.DwfLoader=ft,v.DwgLoader=Qe,v.DwgWorkerClient=Ze,v.DxfLoader=st,v.applyByBlockLineTypeInheritance=Re,v.colorFromAci=F,v.colorFromTrueColor=$,v.computeCadDocumentBounds=Be,v.createCadDocument=ae,v.createCadSceneDocument=We,v.createCadViewer=ur,v.createDashedCadPrimitives=me,v.createDashedCadSegments=$n,v.createDefaultLoaderRegistry=gt,v.detectCadFormat=O,v.inferEntityKind=U,v.isCadNativeRenderableLoader=bt,v.isCadPolylineClosed=we,v.isWebGLAvailable=Ye,v.normalizeCadEntity=ce,v.normalizeDwgDatabase=gr,v.readInputBytes=A,v.resolveCadColor=_,v.resolveCadFitBounds=De,v.resolveCadLinePattern=ue,v.resolveCadLineTypeReference=Oe,v.resolveCadSavedViewBounds=Mt,v.summarizeCadDocument=J,v.supportsDwgWorker=ie,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
|
|
34
34
|
//# sourceMappingURL=cad-viewer.umd.cjs.map
|