rm-build-dxf 0.1.261 → 0.1.263
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/package.json +1 -1
- package/src/EventInput.js +1 -1
- package/src/build.js +1 -1
- package/src/components/NumberEditor.vue.d.ts +1 -1
- package/src/dxf-system/build.d.ts +11 -0
- package/src/dxf-system/plugins/editor/Command/ClippingLine.d.ts +1 -0
- package/src/dxf-system/plugins/editor/Command/Command.d.ts +1 -0
- package/src/dxf-system/plugins/editor/Command/DefaultCommand/SelectRender.d.ts +8 -5
- package/src/dxf-system/plugins/editor/Command/DrawBezierCurveLine.d.ts +48 -0
- package/src/dxf-system/plugins/editor/Command/DrawByWindow.d.ts +1 -0
- package/src/dxf-system/plugins/editor/Command/DrawDoorLine.d.ts +1 -0
- package/src/dxf-system/plugins/editor/Command/DrawHole.d.ts +12 -1
- package/src/dxf-system/plugins/editor/Command/DrawWindow.d.ts +1 -0
- package/src/dxf-system/plugins/editor/Command/Preview.d.ts +1 -1
- package/src/dxf-system/plugins/editor/Command/Sever.d.ts +8 -0
- package/src/dxf-system/plugins/editor/DrawingManager.d.ts +6 -6
- package/src/dxf-system/plugins/editor/pages/{ContextualToolbar.vue.d.ts → ContextualToolbar/ContextualToolbar.vue.d.ts} +4 -2
- package/src/dxf-system/plugins/editor/pages/components/PropertySelectPopup.vue.d.ts +3 -3
- package/src/dxf-system/plugins/editor/ui-service/DragControlPoint.d.ts +6 -2
- package/src/dxf-system/plugins/editor/ui-service/LineSelector.d.ts +2 -2
- package/src/dxf-system/plugins/editor/ui-service/PointerFollowMove.d.ts +4 -4
- package/src/dxf-system/plugins/editor/ui-service/SnapController.d.ts +22 -4
- package/src/dxf-system/plugins/editor/utils/CombQueryTool.d.ts +74 -0
- package/src/dxf-system/plugins/editor/utils/ContextualToolbarObject3D.d.ts +574 -26
- package/src/dxf-system/plugins/editor/utils/LineShape.d.ts +8 -0
- package/src/dxf-system/plugins/editor/utils/Wall2D.d.ts +2 -1
- package/src/dxf-system/type.d.ts +13 -1
- package/src/dxf-system/utils/BezierCurveKernel.d.ts +136 -0
- package/src/dxf-system/utils/DimensionLine.d.ts +1 -0
- package/src/dxf-system/utils/WallGroupManager.d.ts +2 -2
- package/src/dxf-system/utils/WallHole.d.ts +11 -10
- package/src/dxf-system/utils/cad/DxfDataPlugin.d.ts +16 -0
- package/src/dxf-system/utils/line-pipeline/builtin/double-wall-alignment.d.ts +1 -1
- package/src/dxf-system/utils/line-pipeline/builtin/split-collinear-walls-and-beams.d.ts +1 -1
- package/src/dxf-system/utils/tools.d.ts +1 -0
- package/src/i18n/locales/en.d.ts +4 -0
- package/src/i18n/locales/zh-CN.d.ts +4 -0
- package/src/i18n/locales/zh-TW.d.ts +4 -0
- package/src/index.css +1 -1
- package/src/index.js +1 -1
- package/src/index3.js +1 -1
- package/src/utils/algorithms/Box2.d.ts +9 -2
- package/src/utils/algorithms/LineSegment.d.ts +7 -1
- package/src/utils/algorithms/LineSegmentSpatialHash.d.ts +4 -2
- package/src/utils/algorithms/LineSegmentUtils.d.ts +2 -0
- package/src/utils/algorithms/Map.d.ts +1 -1
- package/src/utils/algorithms/Point.d.ts +4 -0
- package/src/utils/algorithms/Polygon.d.ts +4 -0
- package/src/utils/algorithms/cubicBezierCurve.d.ts +25 -0
- package/src/utils/three-object-3d/LineAlignmentGuide.d.ts +1 -0
- package/src/utils/three-object-3d/Lines.d.ts +2 -0
- package/src/utils/three-object-3d/Vector3Pool.d.ts +16 -0
- package/src/utils/tools/Heartbeat.d.ts +25 -0
package/src/build.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as THREE from"three";import{EventDispatcher as EventDispatcher$1,Vector3,Matrix3,MathUtils,Box3,Matrix4,Ray,Group as Group$1,Shape,BufferGeometry,BufferAttribute,TrianglesDrawMode,TriangleFanDrawMode,TriangleStripDrawMode}from"three";import ClipperLib from"clipper-lib";import{GLTFLoader}from"three/addons/loaders/GLTFLoader.js";import{GLTFExporter}from"three/addons/exporters/GLTFExporter.js";import init$1,{dxf_to_dwg}from"rm-rust-dxf-lib";import Drawing from"dxf-writer";import{Brush,Evaluator,SUBTRACTION}from"three-bvh-csg";import{OBJExporter}from"three/examples/jsm/exporters/OBJExporter.js";import{effectScope,computed,watch,isRef,ref,shallowRef,defineComponent,h,getCurrentInstance as getCurrentInstance$1,getCurrentScope,onScopeDispose,Fragment,inject,onMounted,onUnmounted,createVNode,Text}from"vue";function uuid(){return"xxxx-xxxx-4xxx-yxxx-xxxx".replace(/[xy]/g,function(c){var r2=16*Math.random()|0;return("x"==c?r2:3&r2|8).toString(16)})}class EventDispatcher extends EventDispatcher$1{uuid=uuid();addEventListener(type,listener,option){const{once:once=!1}=option??{},callBack=event=>{listener(event),once&&canceCallBack()},canceCallBack=()=>this.removeEventListener(type,callBack);return super.addEventListener(type,callBack),canceCallBack}eventRecordStack=/* @__PURE__ */new Map;addEventRecord(name,...cancels){if(Array.isArray(name)){const list=name.map(n=>this.addEventRecord(n,...cancels)),add2=cancel=>(list.forEach(({add:add3})=>add3(cancel)),{add:add2});return{add:add2}}this.eventRecordStack.has(name)||this.eventRecordStack.set(name,[]),cancels.forEach(cancel=>{this.eventRecordStack.get(name)?.push(cancel)});const add=cancel=>(this.addEventRecord(name,cancel),{add:add});return{add:add}}cancelEventRecord(name){if(Array.isArray(name))return name.forEach(name2=>this.cancelEventRecord(name2));const list=this.eventRecordStack.get(name);list&&(list.reverse().forEach(cancel=>cancel()),this.eventRecordStack.delete(name))}eventLock=!1;dispatchEvent(event){this.eventLock||(super.dispatchEvent(event),super.dispatchEvent({type:"EVENT_TRIGGER",event:event}))}static EVENT_TRIGGER="EVENT_TRIGGER"}class Component extends EventDispatcher{parent;destroyed=!1;constructor(...arg){super(),this.addEventListener("addFromParent",e=>{this.parent=e.parent,this.onAddFromParent(e.parent)}),this.addEventListener("removeFromParent",e=>{this.parent=void 0,this.onRemoveFromParent(e.parent)})}onAddFromParent(parent){}onRemoveFromParent(parent){}destroy(){this.destroyed=!0}}class ComponentContainer extends EventDispatcher{static EventType={ADD_COMPONENT:"addComponent"};components=[];addComponent(component){return component&&(this.components.push(component),this.dispatchEvent({type:"addComponent",component:component}),component.dispatchEvent({type:"addFromParent",parent:this})),this}removeComponent(component){if(component instanceof Component){const index2=this.components.indexOf(component);index2>-1&&(this.components.splice(index2,1),this.dispatchEvent({type:"removeComponent",component:component}),component.dispatchEvent({type:"removeFromParent",parent:this}))}}findComponent(predicate){for(let i=0;i<this.components.length;i++){const component=this.components[i];if(predicate(component,i))return component}}findComponents(predicate){return this.components.filter(predicate)}findComponentByType(type){const component=this.findComponent(c=>c instanceof type);return component||null}findComponentByName(name){const component=this.findComponent(c=>c.constructor.name===name);return component||null}}function cloneUserData(userData){if(!userData||"object"!=typeof userData)return userData;const cloned=Array.isArray(userData)?[]:{},keys=Object.keys(userData);for(const key of keys){const value=userData[key];null!==value&&"object"==typeof value?Array.isArray(value)?cloned[key]=value.map(item=>cloneUserData(item)):Object.getPrototypeOf(value)!==Object.prototype||(cloned[key]=cloneUserData(value)):cloned[key]=value}return cloned}class Rectangle{points=[Point.zero(),Point.zero(),Point.zero(),Point.zero()];get p0(){return this.points[0]}get p1(){return this.points[1]}get p2(){return this.points[2]}get p3(){return this.points[3]}get path(){return this.points.flatMap((p2,i)=>{const np=this.points[(i+1)%this.points.length];return[p2.x,p2.y,0,np.x,np.y,0]})}constructor(points){points&&points.forEach((p2,i)=>this.points[i].copy(p2))}path2D(callback){return this.points.flatMap((p2,i)=>{const np=this.points[(i+1)%this.points.length];return callback&&callback(new Point(p2.x,p2.y),new Point(np.x,np.y)),[p2.x,p2.y,np.x,np.y]})}toLines(){return this.points.map((p2,i)=>{const np=this.points[(i+1)%this.points.length];return new LineSegment(new Point(p2.x,p2.y),new Point(np.x,np.y))})}createGeometry(){const data=[this.p0,this.p2,this.p1,this.p2,this.p0,this.p3].flatMap(p2=>[p2.x,p2.y,0]);return new Float32Array(data)}intersectLineSegment(line){if(2!==line.points.length)throw new Error("LineSegment must have exactly 2 points");const[p1,p2]=line.points,rdx=p2.x-p1.x,rdy=p2.y-p1.y;for(let i=0;i<4;i++){const a2=this.points[i],b4=this.points[(i+1)%4],sdx=b4.x-a2.x,sdy=b4.y-a2.y,denom=rdx*sdy-rdy*sdx;if(0===denom){if(0!==(p1.x-a2.x)*sdy-(p1.y-a2.y)*sdx)continue;const edgeLenSq=sdx*sdx+sdy*sdy,t0=((p1.x-a2.x)*sdx+(p1.y-a2.y)*sdy)/edgeLenSq,t1=((p2.x-a2.x)*sdx+(p2.y-a2.y)*sdy)/edgeLenSq;if(Math.max(t0,t1)>=0&&Math.min(t0,t1)<=1)return!0}else{const t2=((a2.x-p1.x)*sdy-(a2.y-p1.y)*sdx)/denom,u2=((a2.x-p1.x)*rdy-(a2.y-p1.y)*rdx)/denom;if(t2>=0&&t2<=1&&u2>=0&&u2<=1)return!0}}return!!this.containsLineSegment(line)}containsLineSegment(line){if(2!==line.points.length)throw new Error("LineSegment must have exactly 2 points");const isPointInRectangle=point2=>{let sign=0;for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4],edge={x:p2.x-p1.x,y:p2.y-p1.y},toPoint={x:point2.x-p1.x,y:point2.y-p1.y},cross2=edge.x*toPoint.y-edge.y*toPoint.x;if(0===cross2){const t2=0!==edge.x?(point2.x-p1.x)/edge.x:(point2.y-p1.y)/edge.y;if(t2>=0&&t2<=1)return!0}else{const currentSign=cross2>0?1:-1;if(0===sign&&(sign=currentSign),sign!==currentSign)return!1}}return!0};return isPointInRectangle(line.points[0])&&isPointInRectangle(line.points[1])}projectRectangle(rect,axis){const projections=rect.points.map(point2=>point2.dot(axis));return[Math.min(...projections),Math.max(...projections)]}isProjectionOverlap(proj1,proj2){return proj1[0]<proj2[1]&&proj2[0]<proj1[1]}intersectRectangle(rectangle){const axes=[];for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4];axes.push(p1.leftNormal(p2))}for(let i=0;i<4;i++){const p1=rectangle.points[i],p2=rectangle.points[(i+1)%4];axes.push(p1.leftNormal(p2))}for(const axis of axes){const proj1=this.projectRectangle(this,axis),proj2=this.projectRectangle(rectangle,axis);if(!this.isProjectionOverlap(proj1,proj2))return!1}return!0}containsPoint(point2){let positiveCount=0,negativeCount=0;for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4],cross2=(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x);if(cross2>0)positiveCount++;else{if(!(cross2<0))return!1;negativeCount++}}return 4===positiveCount||4===negativeCount}toBox(out=new Box2){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return this.points.forEach(p2=>{maxX=Math.max(p2.x,maxX),minX=Math.min(p2.x,minX),maxY=Math.max(p2.y,maxY),minY=Math.min(p2.y,minY)}),out.set(minX,minY,maxX,maxY)}static fromByLineSegment(line,width=.1,horizontal=!1,hScale=.5){const p1=line.points[0],p2=line.points[1],normal=p2.leftNormal(p1),pDirect=horizontal?p2.directionFrom(p1).multiplyScalar(width*hScale):Point.zero(),nDirect=horizontal?p1.directionFrom(p2).multiplyScalar(width*hScale):Point.zero(),offsetX=normal.x*width*.5,offsetY=normal.y*width*.5;return new Rectangle([new Point(p1.x+offsetX,p1.y+offsetY).add(nDirect),new Point(p2.x+offsetX,p2.y+offsetY).add(pDirect),new Point(p2.x-offsetX,p2.y-offsetY).add(pDirect),new Point(p1.x-offsetX,p1.y-offsetY).add(nDirect)])}}function lazy(fn2){let value,type,cached=!1;return Object.freeze({get isValueCreated(){return cached},get value(){return cached||(value=fn2(),cached=!0),value},get cachedValue(){return cached?value:void 0},get valueType(){return void 0===type&&(type=typeof this.value),type},reset(){cached=!1,type=void 0,value=void 0}})}const hasFinalizationRegistry="undefined"!=typeof FinalizationRegistry;class GCHandler{static map=/* @__PURE__ */new Map;static registry=hasFinalizationRegistry?new FinalizationRegistry(({value:value,onGc:onGc})=>{onGc(value)}):null;static add(target,opt){if(!hasFinalizationRegistry)return;const token=/* @__PURE__ */Symbol(),{key:key=token,value:value,onGc:onGc}=opt;this.remove(key),this.map.set(key,token),this.registry.register(target,{key:key,value:value,onGc:onGc},token)}static remove(key){if(!hasFinalizationRegistry)return;const token=this.map.get(key);token&&(this.registry.unregister(token),this.map.delete(key))}}class PointSpatialHash{map=/* @__PURE__ */new Map;gridSize;id;constructor(gridSize=.5){this.gridSize=gridSize,this.id=/* @__PURE__ */Symbol("id"),GCHandler.add(this,{value:{map:this.map,id:this.id},onGc:value=>{value.map.forEach(nodeSet=>{nodeSet.forEach(target=>{delete target.point.currentData?.pointVirtualGridMap,delete target.point.currentData[value.id]}),nodeSet.clear()}),value.map.clear()}})}insert(point2,userData){if(!point2||isNaN(point2.x)||isNaN(point2.y))return console.error("无效的点坐标"),this;point2.currentData[this.id]&&this.remove(point2);const id=this.getGridIdByPoint(point2);this.map.has(id)||this.map.set(id,/* @__PURE__ */new Set);const set2=this.map.get(id),target={point:point2,userData:userData};set2.add(target);const opt={set:set2,target:target,id:id};return point2.currentData.pointVirtualGrid=opt,point2.currentData[this.id]=opt,this}insertBatch(points){for(const{point:point2,userData:userData}of points)this.insert(point2,userData)}remove(point2){if(point2.currentData[this.id]){const{target:target,set:set2,id:id}=point2.currentData[this.id];set2&&(set2.delete(target),delete point2?.currentData?.pointVirtualGridMap,delete point2.currentData[this.id],0===set2.size&&this.map.delete(id))}return this}removes(points){return points.forEach(this.remove.bind(this)),this}update(point2){const{target:target,set:set2}=point2.currentData[this.id];if(!target)return!1;const id=this.getGridIdByPoint(point2);let newSet=this.map.get(id);return newSet!==set2&&(set2.delete(target),newSet||(newSet=/* @__PURE__ */new Set,this.map.set(id,newSet)),newSet.add(target),point2.currentData[this.id].set=newSet,point2.currentData[this.id].id=id,!0)}updates(point2){point2.forEach(p2=>this.update(p2))}getGridIdByPoint(point2){const i=Math.ceil(point2.x/this.gridSize),j=Math.ceil(point2.y/this.gridSize);return this.getGridId(i,j)}getGridId(i,j){return`${i}.${j}`}clear(){for(const set2 of this.map.values())for(const target of set2)delete target.point.currentData[this.id],delete target.point.currentData.pointVirtualGrid;this.map.clear()}forEachGrid(minI,maxI,minJ,maxJ,fn2){for(let i=minI;i<=maxI;i++)for(let j=minJ;j<=maxJ;j++){const id=this.getGridId(i,j),set2=this.map.get(id);set2&&fn2(set2)}}queryRect(rectangle){const box2=rectangle.toBox(),minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[];return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{rectangle.containsPoint(item.point)&&list.push(item)})}),list}queryCircle(pos,radius,excludeOneself=!1){const box2=new Box2(pos.x-radius,pos.x+radius,pos.y-radius,pos.y+radius),minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[],radius2=radius*radius;return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{if(excludeOneself&&pos===item.point)return;const dx=pos.x-item.point.x,dy=pos.y-item.point.y;dx*dx+dy*dy<=radius2&&list.push(item)})}),list}queryBox(box2){const minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[];return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{box2.containsPoint(item.point)&&list.push(item)})}),list}queryPoint(point2,excludeOneself=!1){const list=[];let set2;if(point2.currentData[this.id])set2=point2.currentData[this.id]?.set;else{const id=this.getGridIdByPoint(point2);set2=this.map.get(id)}return set2?.forEach(item=>{if(point2.equal(item.point)){if(excludeOneself&&point2===item.point)return;list.push(item)}}),list}queryPoints(points,excludeOneself=!1){const result=[];for(const p2 of points)result.push(...this.queryPoint(p2,excludeOneself));return result}queryPolygon(polygon2,position="all"){const box2=polygon2.getBox2();return this.queryBox(box2).filter(result=>{const m=polygon2.getPointSideOfLine(result.point);return"inside"==m&&("inside"==position||"all"==position)||"on"==m&&("on"==position||"all"==position)})}queryPointSelf(point2){if(point2.currentData[this.id]){const{target:target}=point2.currentData[this.id];return target}return null}searchByRing(point2,fn2,maxRing=1e3){let gridCount=this.map.size;const centerI=Math.floor(point2.x/this.gridSize),centerJ=Math.floor(point2.y/this.gridSize),currentCircle=[],appendGrid=(i,j)=>{const set2=this.map.get(this.getGridId(i,j));if(set2){gridCount--;for(const target of set2)currentCircle.push({point:target.point,userData:target.userData,distanceSq:point2.distanceSquared(target.point)})}};if(appendGrid(centerI,centerJ),fn2(currentCircle,0))return currentCircle;if(0===gridCount)return null;for(let r2=1;r2<=maxRing;r2++){currentCircle.length=0;const minI=centerI-r2,maxI=centerI+r2,minJ=centerJ-r2,maxJ=centerJ+r2;for(let i=minI;i<=maxI;i++)appendGrid(i,minJ),appendGrid(i,maxJ);for(let j=minJ+1;j<maxJ;j++)appendGrid(minI,j),appendGrid(maxI,j);if(fn2(currentCircle,r2))return currentCircle;if(0===gridCount)return null}return null}findNearest(point2,excludeSelf=!0){let nearest=null;return this.searchByRing(point2,circle=>{for(const item of circle)excludeSelf&&item.point===point2||(!nearest||item.distanceSq<nearest.distanceSq)&&(nearest=item);return null!==nearest}),nearest}isFreePoint(point2){return 0===this.queryPoint(point2,!0).length}getFreePoint(){const targets=[];for(const list of this.map.values())1===list.size&&targets.push(...list);return targets}getFreePointFirst(){for(const list of this.map.values())if(1===list.size)return[...list][0]}static from(points,gridSize=.5){const psh=new PointSpatialHash(gridSize);return points.forEach((p2,index2)=>psh.insert(p2,index2)),psh}static fromByLines(lines){const psh=new PointSpatialHash;return lines.forEach(line=>psh.insert(line.start,line).insert(line.end,line)),psh}}class PointUtils{static _globalPoint=lazy(()=>new Point);static get globalPoint(){return this._globalPoint.value}static getCenter(points){let area2=0,cx=0,cy=0;for(let i=0,n=points.length;i<n;i++){const p1=points[i],p2=points[(i+1)%n],cross2=p1.x*p2.y-p2.x*p1.y;area2+=cross2,cx+=(p1.x+p2.x)*cross2,cy+=(p1.y+p2.y)*cross2}return area2*=.5,new Point(cx/(6*area2),cy/(6*area2))}static quantize(points,tolerance=.002){const gridSize=tolerance;for(const p2 of points)p2.x=Math.round(p2.x/gridSize)*gridSize,p2.y=Math.round(p2.y/gridSize)*gridSize;return points}static precision(points,count){for(const p2 of points)p2.precision(count);return points}static precision4(points){for(const p2 of points)p2.precision4();return points}static adsorb(points,tolerance=1e-4,mode="average"){const grid=new PointSpatialHash;points.forEach(p2=>grid.insert(p2));const visited=/* @__PURE__ */new Set;for(let i=0;i<points.length;i++){const point2=points[i];if(visited.has(point2))continue;const results=grid.queryCircle(point2,tolerance).map(item=>item.point);let x=0,y=0;if("average"===mode){let countX=0,countY=0;results.forEach(point22=>(countX+=point22.x,countY+=point22.y)),x=countX/results.length,y=countY/results.length}else x=point2.x,y=point2.y;results.forEach(p2=>{p2.set(x,y),visited.add(p2),grid.remove(p2)})}return visited.clear(),points}static _baseNormalLine=lazy(()=>new LineSegment);static get baseNormalLine(){return this._baseNormalLine.value}static constrainPointToAxis(point2,baseLine,normalStartPoint,baseNormalLine){if(!baseNormalLine&&normalStartPoint){const normal=baseLine.normal();baseNormalLine=this.baseNormalLine.set(normalStartPoint.clone().add(normal.clone().multiplyScalar(10)),normalStartPoint.clone().add(normal.multiplyScalar(-10)))}const point1=baseLine.projectPoint(point2,!1);if(!baseNormalLine)return point1&&point2.copy(point1),point2;const point22=baseNormalLine.projectPoint(point2,!1);return point1&&point22?point2.distance(point1)<point2.distance(point22)?point2.copy(point1):point2.copy(point22):point1?point2.copy(point1):point22&&point2.copy(point22),point2}static toArray(points){const array=new Float32Array(2*points.length);for(let i=0;i<points.length;i++){const point2=points[i];array[2*i+0]=point2.x,array[2*i+1]=point2.y}return array}static fromArray(array){const points=new Array;for(let i=0;i<array.length;i+=2)points.push(new Point(array[i],array[i+1]));return points}static createDeferredModifier(){const changes=[];return{push(targetPoint,value){return changes.push([targetPoint,value]),this},add(targetPoint,value){return changes.push([targetPoint,[targetPoint.x+value[0],targetPoint.y+value[1]]]),this},apply(){for(const[point2,value]of changes)point2.copy(value);return changes.length=0,this}}}static globalPoolArray=new Array;static globalPool=lazy(()=>PointUtils.createPool());static createPool(pool2=this.globalPoolArray){const usePool=[];return{get point(){const point2=pool2.pop()??new Point;return usePool.push(point2),point2},free(point2){const index2=usePool.indexOf(point2);index2<0||(usePool[index2]=usePool[usePool.length-1],usePool.pop(),pool2.push(point2))},freeAll(){for(let i=0;i<usePool.length;i++)pool2.push(usePool[i]);usePool.length=0}}}}const LINE_SYMBOL=/* @__PURE__ */Symbol("LINE_SYMBOL");class LineSegment{static get LINE_SYMBOL(){return LINE_SYMBOL}points=[new Point,new Point];userData={};currentData={};uuid=uuid();_length=null;get length(){return this._update(),null===this._length&&(this._length=this.start.distance(this.end)),this._length}get start(){return this.points[0]}get end(){return this.points[1]}_center=null;get center(){return this.getCenter()}_direction=null;constructor(p1,p2){this.set(p1??this.start,p2??this.end),this.start.currentData[LineSegment.LINE_SYMBOL]=this,this.end.currentData[LineSegment.LINE_SYMBOL]=this}_startVersion=-1;_endVersion=-1;_update(){this.start.version===this._startVersion&&this.end.version===this._endVersion||(this._center=null,this._direction=null,this._length=null,this._startVersion=this.start.version,this._endVersion=this.end.version)}getCenter(out=new Point){return this._update(),null===this._center&&(this._center=(new Point).set(.5*(this.start.x+this.end.x),.5*(this.start.y+this.end.y))),this._center.clone(out)}set(p1,p2){return this.start.copy(p1),this.end.copy(p2),this}setLength(len){const direct=this.direction(),half=.5*len,dx=direct.x*half,dy=direct.y*half,cx=.5*(this.start.x+this.end.x),cy=.5*(this.start.y+this.end.y);return this.start.set(cx-dx,cy-dy),this.end.set(cx+dx,cy+dy),this}getAnotherPoint(point2){return point2===this.start?this.end:this.start}offsetStart(width){const d2=this.end.directionFrom(this.start);return this.start.add(d2.multiplyScalar(width)),this}offsetEnd(width){const d2=this.start.directionFrom(this.end);return this.end.add(d2.multiplyScalar(width)),this}isSameEndpoint(line,eps=1e-9){return this.start.equal(line.start,eps)||this.start.equal(line.end,eps)||this.end.equal(line.start,eps)||this.end.equal(line.end,eps)}isSameEndpointAsStart(line,eps=1e-9){return this.start.equal(line.start,eps)||this.start.equal(line.end,eps)}isSameEndpointAsEnd(line,eps=1e-9){return this.end.equal(line.start,eps)||this.end.equal(line.end,eps)}getSameEndpoint(line,eps=1e-9){return this.start.equal(line.start,eps)?[this.start,line.start]:this.start.equal(line.end,eps)?[this.start,line.end]:this.end.equal(line.start,eps)?[this.end,line.start]:this.end.equal(line.end,eps)?[this.end,line.end]:null}isPointOnSegment(point2){const{start:start,end:end}=this,cross2=(point2.y-start.y)*(end.x-start.x)-(point2.x-start.x)*(end.y-start.y);if(Math.abs(cross2)>1e-10)return!1;return(point2.x-start.x)*(point2.x-end.x)+(point2.y-start.y)*(point2.y-end.y)<=1e-10}extendAlongDirection(width,direction="all"){const step=this.direction().multiplyScalar(width);return"end"!==direction&&"all"!==direction||this.end.add(step),"start"!==direction&&"all"!==direction||this.start.add(step.multiplyScalar(-1)),this}translate(dist,direction=this.direction()){const step=direction.clone().multiplyScalar(dist);return this.start.add(step),this.end.add(step),this}rotate(angle,center=this.center){return this.start.rotate(center,angle),this.end.rotate(center,angle),this}mirror(){this.end.rotate(this.start,Math.PI)}swap(){const p2=this.points[0];this.points[0]=this.points[1],this.points[1]=p2}swapValue(){const p2=this.points[0].clone();this.points[0].copy(this.points[1]),this.points[1].copy(p2)}cross(point2){const p1=this.start,p2=this.end;return(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x)}direction(out=Point.zero()){return this._update(),null===this._direction&&(this._direction=this.end.directionFrom(this.start)),this._direction.clone(out)}normal(){return this.points[1].leftNormal(this.points[0])}pointAt(t2,out=new Point){return out.set(this.start.x+(this.end.x-this.start.x)*t2,this.start.y+(this.end.y-this.start.y)*t2)}toRectangle(width=.1,cap="square",out=new Rectangle){const p1=this.start,p2=this.end,halfWidth=.5*width,normal=p2.leftNormal(p1);let extendX=0,extendY=0;if("square"===cap){const dir=p2.directionFrom(p1);extendX=dir.x*halfWidth,extendY=dir.y*halfWidth}const offsetX=normal.x*halfWidth,offsetY=normal.y*halfWidth;return out.p0.set(p1.x+offsetX-extendX,p1.y+offsetY-extendY),out.p1.set(p2.x+offsetX+extendX,p2.y+offsetY+extendY),out.p2.set(p2.x-offsetX+extendX,p2.y-offsetY+extendY),out.p3.set(p1.x-offsetX-extendX,p1.y-offsetY-extendY),out}getPointSideOfLine(point2){const cross2=this.cross(point2);return Math.abs(cross2)<1e-10?"on":cross2>0?"left":"right"}getRightDirection(){return this.normal().multiplyScalar(-1)}getLeftDirection(){return this.normal()}distanceToPoint(point2){const A=this.start,B2=this.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return point2.distance(A);const t2=((point2.x-A.x)*ABx+(point2.y-A.y)*ABy)/ABLengthSquared,clampedT=Math.max(0,Math.min(1,t2)),projX=A.x+clampedT*ABx,projY=A.y+clampedT*ABy;return PointUtils.globalPoint.set(projX,projY),point2.distance(PointUtils.globalPoint)}distanceSquaredToPoint(point2){const A=this.start,B2=this.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return point2.distanceSquared(A);const t2=((point2.x-A.x)*ABx+(point2.y-A.y)*ABy)/ABLengthSquared,clampedT=Math.max(0,Math.min(1,t2)),projX=A.x+clampedT*ABx,projY=A.y+clampedT*ABy;return PointUtils.globalPoint.set(projX,projY),point2.distanceSquared(PointUtils.globalPoint)}distanceToSegment(line){if(this.intersectLineSegment(line))return 0;const distancePointToSegment=(pt2,seg)=>{const A=seg.start,B2=seg.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return pt2.distance(A);const t2=((pt2.x-A.x)*ABx+(pt2.y-A.y)*ABy)/ABLengthSquared;if(t2<0)return pt2.distance(A);if(t2>1)return pt2.distance(B2);{const projX=A.x+t2*ABx,projY=A.y+t2*ABy;return pt2.distance(new Point(projX,projY))}};return Math.min(distancePointToSegment(this.start,line),distancePointToSegment(this.end,line),distancePointToSegment(line.start,this),distancePointToSegment(line.end,this))}isParallelTo(line,eps=1){const d1=this.direction(),d2=line.direction(),angle=d1.angle(d2,{unit:"degree",range:"180"});return Math.min(angle,180-angle)<eps}isPerpendicularTo(line,eps=1){const d1=this.direction(),d2=line.direction(),angle=d1.angle(d2,{unit:"degree",range:"180"});return Math.abs(angle-90)<eps}isCollinearOverlap(line,eps=1e-6){const p1=this.start,p2=this.end,p3=line.start,p4=line.end,d1=this.direction(),d2=line.direction();if(Math.abs(d1.cross(d2))>eps)return!1;const v2=p3.clone().subtract(p1);if(Math.abs(d1.cross(v2))>eps)return!1;const useX=Math.abs(d1.x)>Math.abs(d1.y),a1=useX?p1.x:p1.y,a2=useX?p2.x:p2.y,b1=useX?p3.x:p3.y,b22=useX?p4.x:p4.y,minA=Math.min(a1,a2),maxA=Math.max(a1,a2),minB=Math.min(b1,b22),maxB=Math.max(b1,b22),overlapStart=Math.max(minA,minB);return Math.min(maxA,maxB)-overlapStart>eps}projectLineSegment(line,out=new LineSegment){if(2!==line.points.length||2!==this.points.length)throw new Error("每条线段必须由两个点定义");const[p1,p2]=line.points,[q1,q2]=this.points,dir=new Point(q2.x-q1.x,q2.y-q1.y);if(0===dir.x&&0===dir.y)return out;const projectPoint=point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y,t3=(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared,projX=q1.x+t3*dir.x,projY=q1.y+t3*dir.y;return new Point(projX,projY)};let projP1=projectPoint(p1),projP2=projectPoint(p2);const getT=point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y;return(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared};let t1=getT(projP1),t2=getT(projP2);const clampPoint=t3=>{const clampedT=Math.max(0,Math.min(1,t3)),x=q1.x+clampedT*dir.x,y=q1.y+clampedT*dir.y;return new Point(x,y)};return(t1<0||t1>1)&&(projP1=clampPoint(t1)),(t2<0||t2>1)&&(projP2=clampPoint(t2)),projP1.x===projP2.x&&projP1.y===projP2.y?out.set(projP1,projP1):out.set(projP1,projP2)}projectPoint(p1,clip=!0){const[q1,q2]=this.points,dir=new Point(q2.x-q1.x,q2.y-q1.y);if(0===dir.x&&0===dir.y)return null;let projP1=(point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y,t2=(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared,projX=q1.x+t2*dir.x,projY=q1.y+t2*dir.y;return new Point(projX,projY)})(p1);if(!clip)return projP1;let t1=(point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y;return(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared})(projP1);return t1<0||t1>1?null:projP1}projectPointValue(point2,eps=1e-12){const q1=this.start,q2=this.end,dx=q2.x-q1.x,dy=q2.y-q1.y,len2=dx*dx+dy*dy;if(len2<eps)return 0;return((point2.x-q1.x)*dx+(point2.y-q1.y)*dy)/len2}includedAngle(line){const d1=this.direction(),d2=line.direction();return d1.angleBetween(d2)/(Math.PI/180)}angle(line,opt){const d1=this.direction(),d2=line.direction();return d1.angle(d2,opt)}sameLine(line){const a2=this.start,b4=this.end,c=line.start,d2=line.end,isCollinear=(p1,p2,p3)=>Math.abs((p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x))<1e-10;return isCollinear(a2,b4,c)&&isCollinear(a2,b4,d2)?this.containsPoint(c)||this.containsPoint(d2)||line.containsPoint(a2)||line.containsPoint(b4)?1:0:-1}crossProduct(a2,b4,c){return(b4.x-a2.x)*(c.y-a2.y)-(b4.y-a2.y)*(c.x-a2.x)}isPointInSegmentBounds(pt2,segStart,segEnd,EPSILON=1e-10){return Math.min(segStart.x,segEnd.x)-EPSILON<=pt2.x&&pt2.x<=Math.max(segStart.x,segEnd.x)+EPSILON&&Math.min(segStart.y,segEnd.y)-EPSILON<=pt2.y&&pt2.y<=Math.max(segStart.y,segEnd.y)+EPSILON}intersectLineSegment(line,endpoint=!0){const p1=this.start,p2=this.end,p3=line.start,p4=line.end;if(Math.max(p1.x,p2.x)<Math.min(p3.x,p4.x)||Math.max(p3.x,p4.x)<Math.min(p1.x,p2.x)||Math.max(p1.y,p2.y)<Math.min(p3.y,p4.y)||Math.max(p3.y,p4.y)<Math.min(p1.y,p2.y))return!1;const d1=this.crossProduct(p1,p2,p3),d2=this.crossProduct(p1,p2,p4),d3=this.crossProduct(p3,p4,p1),d4=this.crossProduct(p3,p4,p2);if(d1*d2<0&&d3*d4<0)return!0;if(endpoint){if(Math.abs(d1)<1e-10&&this.isPointInSegmentBounds(p3,p1,p2,1e-10))return!0;if(Math.abs(d2)<1e-10&&this.isPointInSegmentBounds(p4,p1,p2,1e-10))return!0;if(Math.abs(d3)<1e-10&&this.isPointInSegmentBounds(p1,p3,p4,1e-10))return!0;if(Math.abs(d4)<1e-10&&this.isPointInSegmentBounds(p2,p3,p4,1e-10))return!0}return!1}containsPoint(pt2){const d1=pt2.distance(this.start),d2=pt2.distance(this.end),len=this.length;return Math.abs(d1+d2-len)<1e-10}getIntersection(line){const p1=this.start,p2=this.end,p3=line.start,p4=line.end,denom=(p1.x-p2.x)*(p3.y-p4.y)-(p1.y-p2.y)*(p3.x-p4.x);if(Math.abs(denom)<1e-10)return null;const t2=((p1.x-p3.x)*(p3.y-p4.y)-(p1.y-p3.y)*(p3.x-p4.x))/denom,x=p1.x+t2*(p2.x-p1.x),y=p1.y+t2*(p2.y-p1.y);return new Point(x,y)}directionEqual(line,errAngle=.1){return this.includedAngle(line)<errAngle}clone(userData=!0,cloneUUid=!1,out=new LineSegment){return out.set(this.points[0],this.points[1]),cloneUUid&&(out.uuid=this.uuid),userData&&(out.userData=cloneUserData(this.userData)),out}copy(line){return this.start.copy(line.start),this.end.copy(line.end),this}static getSegmentFromPoint(point2){return point2.currentData[LINE_SYMBOL]??null}static axisY(width,out=new LineSegment){const helf=.5*width;return out.set([0,-helf],[0,helf])}static axisX(width,out=new LineSegment){const helf=.5*width;return out.set([-helf,0],[helf,0])}static angleToYAxis(line){const dx=line.end.x-line.start.x,dy=line.end.y-line.start.y;return Math.atan2(dx,dy)}static from(line){return new LineSegment(Point.from(line.start),Point.from(line.end))}}const POW10=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Point{_x;_y;_version=0;get version(){return this._version}get X(){return this._x}get Y(){return this._y}get x(){return this._x}get y(){return this._y}set x(x){this.setX(x)}set y(y){this.setY(y)}userData={};currentData={};constructor(x=0,y=0){this._x=x,this._y=y}_set(x,y){return this._x=x,this._y=y,this._version++,this}set(x,y){return x===this._x&&this._y===y||this._set(x,y),this}setByDirect(direct,origin,width){this.copy(origin.clone().add(direct.clone().multiplyScalar(width)))}setX(x){return x===this._x||(this._x=x,this._version++),this}setY(y){return this._y===y||(this._y=y,this._version++),this}equal(point2,eps=1e-9){return Math.abs(point2._x-this._x)<eps&&Math.abs(point2._y-this._y)<eps}setByArray(arr){return this._set(arr[0],arr[1]),this}multiply(point2){return this._set(this._x*point2._x,this._y*point2._y),this}multiplyScalar(scalar){return this._set(this._x*scalar,this._y*scalar),this}division(point2){return this._set(this._x/point2._x,this._y/point2._y),this}divisionScalar(scalar){return this._set(this._x/scalar,this._y/scalar),this}subtract(point2){return this._set(this._x-point2._x,this._y-point2._y),this}subtractScalar(value){return this._set(this._x-value,this._y-value),this}add(point2){return this._set(this._x+point2._x,this._y+point2._y),this}addScalar(value){return this._set(this._x+value,this._y+value),this}added(point2,out=new Point){return out._set(this._x+point2._x,this._y+point2._y)}subtracted(point2,out=new Point){return out._set(this._x-point2._x,this._y-point2._y)}parseInt(){return this._set(~~this._x,~~this._y),this}rotate(point2,angle){const dx=this._x-point2.x,dy=this._y-point2.y,cosAngle=Math.cos(angle),sinAngle=Math.sin(angle),rotatedX=dx*cosAngle-dy*sinAngle,rotatedY=dx*sinAngle+dy*cosAngle;return this._set(rotatedX+point2.x,rotatedY+point2.y),this}rotated(center,angle,out=new Point){const dx=this._x-center.x,dy=this._y-center.y,cos=Math.cos(angle),sin=Math.sin(angle);return out._set(dx*cos-dy*sin+center.x,dx*sin+dy*cos+center.y)}precision(count){const factor=POW10[count]??10**count;return this._set(Math.round(this._x*factor)/factor,Math.round(this._y*factor)/factor),this}precision4(){return this._set(Math.round(1e4*this._x)/1e4,Math.round(1e4*this._y)/1e4),this}normalize(){const length=Math.sqrt(this._x*this._x+this._y*this._y);return 0===length||this._set(this._x/length,this._y/length),this}normalized(out=new Point){const length=Math.hypot(this._x,this._y);return 0===length?out._set(0,0):out._set(this._x/length,this._y/length)}leftNormal(point2,out=new Point){const dx=this._x-point2._x,dy=this._y-point2._y,length=Math.sqrt(dx*dx+dy*dy);if(0===length)return Point.zero();const nx=-dy/length,ny=dx/length;return out._set(nx,ny)}directionFrom(point2,out=new Point){const dx=this._x-point2._x,dy=this._y-point2._y,length=Math.sqrt(dx*dx+dy*dy);return 0!==length&&out._set(dx/length,dy/length),out}expandAsLine(direction,length,userData,out=new LineSegment){return out.set(this.clone(),this.clone().add(direction.clone().multiplyScalar(length))),out.userData=userData??{},out}magnitude(){return Math.hypot(this._x,this._y)}dot(point2){return this._x*point2._x+this._y*point2._y}cross(point2){return this._x*point2._y-this._y*point2._x}angleBetween(point2,type="radian",angle="180"){const dotProduct=this.dot(point2),magnitude1=this.magnitude(),magnitude2=point2.magnitude();if(0===magnitude1||0===magnitude2)return 0;const cosTheta=dotProduct/(magnitude1*magnitude2),clampedCosTheta=Math.max(-1,Math.min(1,cosTheta));return"radian"===type?Math.acos(clampedCosTheta):"cos"===type?clampedCosTheta:"180"===angle||this.cross(point2)<0?Math.acos(clampedCosTheta)/(Math.PI/180):360-Math.acos(clampedCosTheta)/(Math.PI/180)}angleBetween2(point2){const magnitude1=this.magnitude(),magnitude2=point2.magnitude();if(0===magnitude1||0===magnitude2)return 0;const dot=this.dot(point2),cross2=this.cross(point2);return Math.atan2(cross2,dot)}angle(point2,opt={}){const{unit:unit="radian",range:range="180"}=opt,dot=this.dot(point2),cross2=this.cross(point2);if("cos"===unit){const mag=this.magnitude()*point2.magnitude();return 0===mag?0:Math.max(-1,Math.min(1,dot/mag))}let theta=Math.atan2(cross2,dot);return"180"===range?theta=Math.abs(theta):theta<0&&(theta+=2*Math.PI),"degree"===unit?180*theta/Math.PI:theta}length(){const magnitude=Math.sqrt(this._x*this._x+this._y*this._y);return Math.abs(magnitude-Math.round(magnitude))<1e-9?Math.round(magnitude):magnitude}distance(point2){return Math.sqrt((this._x-point2.x)*(this._x-point2.x)+(this._y-point2.y)*(this._y-point2.y))}distanceSquared(point2){const dx=this._x-point2.x,dy=this._y-point2.y;return dx*dx+dy*dy}hashCode(fixed=6){return`${this._x.toFixed(fixed)},${this._y.toFixed(fixed)}`}encode(){return BigInt(Math.round(this._x/1e-4))<<32n|0xffffffffn&BigInt(Math.round(this._y/1e-4))}clone(out=new Point){return out._set(this._x,this._y),out}copy(p2){return p2&&"x"in p2&&"y"in p2?this._set(Number(p2.x),Number(p2.y)):Array.isArray(p2)&&this._set(Number(p2[0]),Number(p2[1])),this}toArray(){return[this._x,this._y]}toJson(z=0){return{x:this._x,y:this._y,z:z}}toJson2D(){return{x:this._x,y:this._y}}toVector3(z=0){return new Vector3(this._x,this._y,z)}static from(arr,out=new Point){return arr?Array.isArray(arr)?out.set(arr[0],arr[1]):"x"in arr&&"y"in arr?out.set(arr.x,arr.y):"X"in arr&&"Y"in arr?out.set(arr.X,arr.Y):out:out}static fromByList(arr){return arr.map(item=>Point.from(item))}static zero(){return new Point(0,0)}}class Box2{minX=0;maxX=0;minY=0;maxY=0;get points(){return[new Point(this.minX,this.minY),new Point(this.maxX,this.minY),new Point(this.maxX,this.maxY),new Point(this.minX,this.maxY)]}get width(){return this.maxX-this.minX}get height(){return this.maxY-this.minY}get center(){return new Point(.5*(this.maxX+this.minX),.5*(this.maxY+this.minY))}constructor(minX=0,maxX=0,minY=0,maxY=0){this.minX=minX,this.maxX=maxX,this.minY=minY,this.maxY=maxY}getPaths3D(z=0){const points=this.points,list=[];return points.forEach((p2,i)=>{const nextP=points[(i+1)%points.length];list.push(p2.x,p2.y,z),list.push(nextP.x,nextP.y,z)}),list}intersectLineSegment(line){const p1=line.points[0],p2=line.points[1],dx=p2.x-p1.x,dy=p2.y-p1.y;if(0===dx&&0===dy)return this.minX<=p1.x&&p1.x<=this.maxX&&this.minY<=p1.y&&p1.y<=this.maxY;let tNear=Number.NEGATIVE_INFINITY,tFar=Number.POSITIVE_INFINITY;if(0!==dx){const tx1=(this.minX-p1.x)/dx,tx2=(this.maxX-p1.x)/dx;tNear=Math.max(tNear,Math.min(tx1,tx2)),tFar=Math.min(tFar,Math.max(tx1,tx2))}else if(p1.x<this.minX||p1.x>this.maxX)return!1;if(0!==dy){const ty1=(this.minY-p1.y)/dy,ty2=(this.maxY-p1.y)/dy;tNear=Math.max(tNear,Math.min(ty1,ty2)),tFar=Math.min(tFar,Math.max(ty1,ty2))}else if(p1.y<this.minY||p1.y>this.maxY)return!1;return tNear<=tFar&&tNear<=1&&tFar>=0}containsLineSegment(line){const[p1,p2]=line.points;return this.minX<=p1.x&&p1.x<=this.maxX&&this.minY<=p1.y&&p1.y<=this.maxY&&this.minX<=p2.x&&p2.x<=this.maxX&&this.minY<=p2.y&&p2.y<=this.maxY}intersectRectangle(rectangle){const rPoints=rectangle.points;let rMinX=rPoints[0].x,rMinY=rPoints[0].y,rMaxX=rPoints[0].x,rMaxY=rPoints[0].y;for(let i=1;i<4;i++){const p2=rPoints[i];p2.x<rMinX&&(rMinX=p2.x),p2.y<rMinY&&(rMinY=p2.y),p2.x>rMaxX&&(rMaxX=p2.x),p2.y>rMaxY&&(rMaxY=p2.y)}if(this.maxX<rMinX||this.minX>rMaxX||this.maxY<rMinY||this.minY>rMaxY)return!1;const bPoints=this.points;for(let i=0;i<4;i++){const bp1=bPoints[i],bp2=bPoints[(i+1)%4];for(let j=0;j<4;j++){const rp1=rPoints[j],rp2=rPoints[(j+1)%4],o1=(bp2.x-bp1.x)*(rp1.y-bp1.y)-(bp2.y-bp1.y)*(rp1.x-bp1.x),o2=(bp2.x-bp1.x)*(rp2.y-bp1.y)-(bp2.y-bp1.y)*(rp2.x-bp1.x),o3=(rp2.x-rp1.x)*(bp1.y-rp1.y)-(rp2.y-rp1.y)*(bp1.x-rp1.x),o4=(rp2.x-rp1.x)*(bp2.y-rp1.y)-(rp2.y-rp1.y)*(bp2.x-rp1.x);if(o1*o2<0&&o3*o4<0)return!0;if(0===o1&&Math.min(bp1.x,bp2.x)<=rp1.x&&rp1.x<=Math.max(bp1.x,bp2.x)&&Math.min(bp1.y,bp2.y)<=rp1.y&&rp1.y<=Math.max(bp1.y,bp2.y))return!0;if(0===o2&&Math.min(bp1.x,bp2.x)<=rp2.x&&rp2.x<=Math.max(bp1.x,bp2.x)&&Math.min(bp1.y,bp2.y)<=rp2.y&&rp2.y<=Math.max(bp1.y,bp2.y))return!0;if(0===o3&&Math.min(rp1.x,rp2.x)<=bp1.x&&bp1.x<=Math.max(rp1.x,rp2.x)&&Math.min(rp1.y,rp2.y)<=bp1.y&&bp1.y<=Math.max(rp1.y,rp2.y))return!0;if(0===o4&&Math.min(rp1.x,rp2.x)<=bp2.x&&bp2.x<=Math.max(rp1.x,rp2.x)&&Math.min(rp1.y,rp2.y)<=bp2.y&&bp2.y<=Math.max(rp1.y,rp2.y))return!0}}for(let i=0;i<4;i++){const p2=rPoints[i];if(p2.x>=this.minX&&p2.x<=this.maxX&&p2.y>=this.minY&&p2.y<=this.maxY)return!0}const isPointInRect=point2=>{let sign=0;for(let i=0;i<4;i++){const p1=rPoints[i],p2=rPoints[(i+1)%4],cross2=(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x);if(0===cross2){const denom=Math.abs(p2.x-p1.x)>1e-10?p2.x-p1.x:p2.y-p1.y,t2=denom?(point2.x-p1.x)/denom:0;if(t2>=0&&t2<=1)return!0}else{const currentSign=cross2>0?1:-1;if(0===sign)sign=currentSign;else if(sign!==currentSign)return!1}}return!0};for(let i=0;i<4;i++)if(isPointInRect(bPoints[i]))return!0;return!1}containsRectangle(rectangle){return rectangle.points.every(p2=>this.minX<=p2.x&&p2.x<=this.maxX&&this.minY<=p2.y&&p2.y<=this.maxY)}intersectBox(box){return!(this.maxX<box.minX||this.minX>box.maxX||this.maxY<box.minY||this.minY>box.maxY)}containsBox(box){return this.minX<=box.minX&&box.maxX<=this.maxX&&this.minY<=box.minY&&box.maxY<=this.maxY}containsPoint(point2){return point2.x>=this.minX&&point2.x<=this.maxX&&point2.y>=this.minY&&point2.y<=this.maxY}set(minX,minY,maxX,maxY){return this.minX=minX,this.minY=minY,this.maxX=maxX,this.maxY=maxY,this}scaleSize(maxWidth,maxHeight,mode="min"){const scaleX=maxWidth/this.width,scaleY=maxHeight/this.height;return Math[mode](scaleX,scaleY)}multiplyScalar(scalar){return this.minX*=scalar,this.minY*=scalar,this.maxX*=scalar,this.maxY*=scalar,this}expansion(w){return this.minX-=w,this.minY-=w,this.maxX+=w,this.maxY+=w,this}clone(){return new Box2(this.minX,this.maxX,this.minY,this.maxY)}static fromByPoints(...points){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return points.forEach(p2=>{minX=Math.min(minX,p2.x),maxX=Math.max(maxX,p2.x),minY=Math.min(minY,p2.y),maxY=Math.max(maxY,p2.x)}),new Box2(minX,maxX,minY,maxY)}static fromByLineSegment(...lines){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return lines.forEach(line=>{line?.points?.forEach(p2=>{Number.isFinite(p2.x)&&(minX=Math.min(minX,p2.x),maxX=Math.max(maxX,p2.x)),Number.isFinite(p2.y)&&(minY=Math.min(minY,p2.y),maxY=Math.max(maxY,p2.y))})}),new Box2(minX,maxX,minY,maxY)}}class Quadtree{bounds;capacity;maxDepth;depth;isLeaf=!0;children=null;nodes=[];color=[Math.random(),Math.random(),Math.random()];id;constructor(bounds,capacity=8,maxDepth=10,depth=1,id=/* @__PURE__ */Symbol("id")){this.bounds=bounds,this.capacity=capacity,this.depth=depth,this.maxDepth=maxDepth,this.id=id,GCHandler.add(this,{value:{quadtrees:this.children,nodes:this.nodes,id:this.id},onGc:({quadtrees:quadtrees,nodes:nodes,id:id2})=>{const clear=nodes2=>nodes2.forEach(node=>delete node.line.currentData[id2]),clearEach=quadtrees2=>{quadtrees2?.forEach(quadtree=>{clear(quadtree.nodes),clearEach(quadtree.children)})};clear(nodes),quadtrees&&clearEach(quadtrees)}})}insert(node,userData){if(node instanceof LineSegment)this.insert({line:node,userData:userData??{}});else{if(!this.isLeaf){const quadrant=this.getQuadrant(node.line);if(-1!==quadrant)return void this.children[quadrant].insert(node)}if(this.nodes.push(node),node.line.currentData[this.id]=node,node.parent=this,this.isLeaf&&this.nodes.length>this.capacity&&this.depth<this.maxDepth){this.subdivide();const nodes=this.nodes;this.nodes=[];for(const n of nodes){const quadrant=this.getQuadrant(n.line);-1!==quadrant?this.children[quadrant].insert(n):(n.parent=this,this.nodes.push(n),node.line.currentData[this.id]=node)}}}}remove(node){if(node instanceof LineSegment)return void((node=node.currentData[this.id])&&this.remove(node));const index2=node.parent?.nodes.indexOf(node);index2>-1&&(node.parent?.nodes.splice(index2,1),delete node.line.currentData[this.id])}update(node){this.remove(node),this.insert(node)}clear(){this.isLeaf||(this.children?.forEach(child=>child.clear()),this.children=null,this.isLeaf=!0),this.nodes.forEach(node=>{delete node.line.currentData[this.id]}),this.nodes=[]}getQuadrant(line){let count=0,quadrant=-1;return this.children[0].bounds.intersectLineSegment(line)&&(count++,quadrant=0),this.children[1].bounds.intersectLineSegment(line)&&(count++,quadrant=1),this.children[2].bounds.intersectLineSegment(line)&&(count++,quadrant=2),this.children[3].bounds.intersectLineSegment(line)&&(count++,quadrant=3),1===count?quadrant:-1}subdivide(){if(!this.isLeaf)return;this.isLeaf=!1,this.children=[];const midX=(this.bounds.minX+this.bounds.maxX)/2,midY=(this.bounds.minY+this.bounds.maxY)/2;this.children[0]=new Quadtree(new Box2(this.bounds.minX,midX,this.bounds.minY,midY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[1]=new Quadtree(new Box2(midX,this.bounds.maxX,this.bounds.minY,midY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[2]=new Quadtree(new Box2(this.bounds.minX,midX,midY,this.bounds.maxY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[3]=new Quadtree(new Box2(midX,this.bounds.maxX,midY,this.bounds.maxY),this.capacity,this.maxDepth,this.depth+1,this.id)}queryBox(box2){const result=[];if(!this.bounds.intersectBox(box2))return result;for(const node of this.nodes)box2.intersectLineSegment(node.line)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryBox(box2));return result}queryCircle(pos,radius){const result=[],circleBox=new Box2(pos.x-radius,pos.x+radius,pos.y-radius,pos.y+radius);if(!this.bounds.intersectBox(circleBox))return result;for(const node of this.nodes){const[p1,p2]=node.line.points,dx=p2.x-p1.x,dy=p2.y-p1.y,l2=dx*dx+dy*dy;let t2=((pos.x-p1.x)*dx+(pos.y-p1.y)*dy)/l2;t2=Math.max(0,Math.min(1,t2));const closestX=p1.x+t2*dx,closestY=p1.y+t2*dy;pos.distance(new Point(closestX,closestY))<=radius&&result.push(node)}if(!this.isLeaf)for(const child of this.children)result.push(...child.queryCircle(pos,radius));return result.sort(l=>l.line.length),result}queryPoint(point2){const result=[];if(point2.x<this.bounds.minX||point2.x>this.bounds.maxX||point2.y<this.bounds.minY||point2.y>this.bounds.maxY)return result;for(const node of this.nodes)node.line.isPointOnSegment(point2)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryPoint(point2));return result}queryRect(rectangle){const result=[];if(!this.bounds.intersectRectangle(rectangle))return result;for(const node of this.nodes)rectangle.intersectLineSegment(node.line)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryRect(rectangle));return result}queryLineSegment(lineSegment,endpoint=!0){const result=[];if(!this.bounds.intersectLineSegment(lineSegment))return result;for(const node of this.nodes)lineSegment.intersectLineSegment(node.line,endpoint)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryLineSegment(lineSegment));return result}raycast(origin,direct,near=0,far=10){const result=[],rayBox=new Box2(Math.min(origin.x,origin.x+direct.x*far),Math.max(origin.x,origin.x+direct.x*far),Math.min(origin.y,origin.y+direct.y*far),Math.max(origin.y,origin.y+direct.y*far));if(!this.bounds.intersectBox(rayBox))return result;const len=Math.hypot(direct.x,direct.y),dir_x=direct.x/len,dir_y=direct.y/len;for(const node of this.nodes){const[p1,p2]=node.line.points,dx=p2.x-p1.x,dy=p2.y-p1.y,det=dir_x*dy-dir_y*dx;if(Math.abs(det)<1e-10)continue;const ox=origin.x,oy=origin.y,t2=((p1.x-ox)*dy-(p1.y-oy)*dx)/det,u2=((p1.x-ox)*dir_y-(p1.y-oy)*dir_x)/det;if(t2>=near&&t2<=far&&u2>=0&&u2<=1){const point2=new Point(ox+dir_x*t2,oy+dir_y*t2);result.push({targetLine:node.line,intersectPoint:point2,distance:t2})}}if(!this.isLeaf)for(const child of this.children)result.push(...child.raycast(origin,direct,near,far));return 1==this.depth&&result.sort((a2,b4)=>a2.distance-b4.distance),result}boundsToArray(array=[],colors2,recursion=!0){return!this.isLeaf&&recursion&&this.children?.forEach(child=>child.boundsToArray(array,colors2)),array.push(...this.bounds.points.flatMap((p2,i,array2)=>{const np=array2[(i+1)%array2.length];return colors2?.push(...this.color),colors2?.push(...this.color),[p2.x,p2.y,0,np.x,np.y,0]})),array}static from(lines,userDataFun){const quadtree=new Quadtree(Box2.fromByLineSegment(...lines));return lines.forEach((line,index2)=>quadtree.insert({line:line,userData:userDataFun?userDataFun(line,index2):void 0})),quadtree}}class MapEnhance extends Map{get valueArray(){return[...this.values()]}map(callbackfn){const result=[];for(const[k,v2]of this)result.push(callbackfn(v2,k));return result}filter(callbackfn){const result=[];for(const[k,v2]of this)callbackfn(v2,k)&&result.push(v2);return result}filterKey(callbackfn){const result=[];for(const[k,v2]of this)callbackfn(v2,k)&&result.push(k);return result}reduce(callbackfn,result){for(const[k,v2]of this)result=callbackfn(result,v2,k);return result}some(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return!0;return!1}every(callbackfn){for(const[k,v2]of this)if(!callbackfn(v2,k))return!1;return!0}find(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return v2}findKey(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return k}someKeys(keys){return keys.some(key=>this.has(key))}everyKeys(keys){return keys.every(key=>this.has(key))}group(callbackfn){const map=new ArrayMap;for(const[k,v2]of this){const groupKey=callbackfn(v2,k);map.append(groupKey,v2)}return map}toObject(){return this.reduce((obj,v2,k)=>(obj[`${k}`]=v2,obj),{})}first(){return this.values().next().value}firstKey(){return this.keys().next().value}last(){let last;for(const v2 of this.values())last=v2;return last}sortBy(callback){return[...this.entries()].sort((a2,b4)=>{const va2=callback(a2[1],a2[0]),vb=callback(b4[1],b4[0]);return va2<vb?-1:va2>vb?1:0})}pluck(keyPath){return this.map(v2=>v2[keyPath])}}class ArrayMap extends MapEnhance{maxLength=1/0;append(k,...arr){return arr.forEach(v2=>{this.has(k)||this.set(k,[]);const list=this.get(k);list.push(v2),list.length>this.maxLength&&list.splice(0,list.length-this.maxLength)}),this}setLength(key,len){const list=this.get(key);list&&(list.length=Math.max(0,len))}remove(k,...arr){const set2=this.get(k);return set2&&arr.forEach(v2=>set2.splice(set2.indexOf(v2),1)),this}getOrCreate(key){return this.has(key)||this.set(key,[]),this.get(key)}}class SetMap extends MapEnhance{append(k,...arr){return arr.forEach(v2=>{this.has(k)||this.set(k,/* @__PURE__ */new Set),this.get(k)?.add(v2)}),this}hasValue(key,value){return this.get(key)?.has(value)??!1}}class CounterMap extends MapEnhance{set(key,step=1){return console.warn("Use increment() instead of set() in CounterMap"),this.increment(key,step),this}increment(key,step=1){const count=super.get(key)??0;return super.set(key,count+step),this}getByCount(count){return this.filterKey(v2=>v2===count)}getAllCount(){return this.reduce((count,v2)=>count+v2,0)}getMaxKey(){let maxKey,maxValue=-1/0;for(const[k,v2]of this)v2>maxValue&&(maxValue=v2,maxKey=k);return maxKey}getminKey(){let maxKey,maxValue=-1/0;for(const[k,v2]of this)v2<maxValue&&(maxValue=v2,maxKey=k);return maxKey}}class UnionFindSet{parent;rank;constructor(size2){this.parent=new Uint32Array(size2),this.rank=new Uint8Array(size2).fill(1);for(let i=0;i<size2;i++)this.parent[i]=i}find(x){return this.parent[x]!==x&&(this.parent[x]=this.find(this.parent[x])),this.parent[x]}union(x,y){let rootX=this.find(x),rootY=this.find(y);rootX!==rootY&&(this.rank[rootX]>this.rank[rootY]?this.parent[rootY]=rootX:this.rank[rootX]<this.rank[rootY]?this.parent[rootX]=rootY:(this.parent[rootY]=rootX,this.rank[rootX]+=1))}getAllSets(){const sets=new ArrayMap;for(const el of this.parent.keys()){const root=this.find(el);sets.append(root,el)}return sets}}class LineSegmentSpatialHash{constructor(cellSize=.2){this.cellSize=cellSize}buckets=/* @__PURE__ */new Map;lineCells=/* @__PURE__ */new Map;insert(line){const keys=this.getLineCellKeys(line);this.lineCells.set(line,keys);for(const key of keys){let bucket=this.buckets.get(key);bucket||(bucket=/* @__PURE__ */new Set,this.buckets.set(key,bucket)),bucket.add(line)}return this}insertLines(lines){for(const line of lines)this.insert(line);return this}remove(line){const keys=this.lineCells.get(line);if(!keys)return this;for(const key of keys){const bucket=this.buckets.get(key);bucket&&(bucket.delete(line),0===bucket.size&&this.buckets.delete(key))}return this.lineCells.delete(line),this}update(line){return this.remove(line),this.insert(line),this}clear(){return this.buckets.clear(),this.lineCells.clear(),this}visited=/* @__PURE__ */new Set;queryPoint(point2,radius=0,out=[]){const radiusSq=radius*radius;this.visited.clear(),out.length=0;const minX=point2.x-radius,minY=point2.y-radius,maxX=point2.x+radius,maxY=point2.y+radius,minCellX=this.toCell(minX),minCellY=this.toCell(minY),maxCellX=this.toCell(maxX),maxCellY=this.toCell(maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket){if(this.visited.has(line))continue;this.visited.add(line);line.distanceSquaredToPoint(point2)<=radiusSq&&out.push(line)}}return out}queryBounds(bounds,out=[]){this.visited.clear(),out.length=0;const minCellX=this.toCell(bounds.minX),minCellY=this.toCell(bounds.minY),maxCellX=this.toCell(bounds.maxX),maxCellY=this.toCell(bounds.maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket)this.visited.has(line)||(this.visited.add(line),out.push(line))}return out}queryPotentialLine(line,out=[]){this.visited.clear(),out.length=0;const keys=this.getLineCellKeys(line);for(const key of keys){const bucket=this.buckets.get(key);if(bucket)for(const other of bucket)this.visited.has(other)||(this.visited.add(other),other!==line&&out.push(other))}return out}queryLine(line,out=[]){this.queryPotentialLine(line,out);let write=0;for(let i=0;i<out.length;i++){const other=out[i];line.intersectLineSegment(other)&&(out[write++]=other)}return out.length=write,out}rectangleBounds=new Box2;queryRectangle(rectangle,out=[]){const bounds=rectangle.toBox(this.rectangleBounds);this.visited.clear(),out.length=0;const minCellX=this.toCell(bounds.minX),minCellY=this.toCell(bounds.minY),maxCellX=this.toCell(bounds.maxX),maxCellY=this.toCell(bounds.maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket)this.visited.has(line)||(this.visited.add(line),(rectangle.containsPoint(line.start)||rectangle.containsPoint(line.end)||rectangle.intersectLineSegment(line))&&out.push(line))}return out}rayIntersectSegment(origin,dir,seg){const x1=origin.x,y1=origin.y,x2=origin.x+dir.x,y2=origin.y+dir.y,x3=seg.start.x,y3=seg.start.y,x4=seg.end.x,y4=seg.end.y,denom=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);if(Math.abs(denom)<1e-9)return null;const t2=((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/denom,u2=-((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))/denom;return t2<0||u2<0||u2>1?null:{t:t2,point:new Point(x1+dir.x*t2,y1+dir.y*t2)}}raycast(origin,direction,maxDistance=1/0,out){this.visited.clear();const cellSize=this.cellSize,ox=origin.x/cellSize,oy=origin.y/cellSize;let cellX=Math.floor(ox),cellY=Math.floor(oy);const dx=direction.x,dy=direction.y,stepX=dx>0?1:dx<0?-1:0,stepY=dy>0?1:dy<0?-1:0,tDeltaX=0===stepX?1/0:Math.abs(1/dx),tDeltaY=0===stepY?1/0:Math.abs(1/dy);let tMaxX=stepX>0?(Math.floor(ox)+1-ox)*tDeltaX:(ox-Math.floor(ox))*tDeltaX,tMaxY=stepY>0?(Math.floor(oy)+1-oy)*tDeltaY:(oy-Math.floor(oy))*tDeltaY,bestT=1/0,bestLine=null,bestPoint=null;for(;;){const bucket=this.buckets.get(this.getKey(cellX,cellY));if(bucket)for(const line of bucket){if(this.visited.has(line))continue;this.visited.add(line);const hit=this.rayIntersectSegment(origin,direction,line);hit&&(hit.t<0||hit.t>maxDistance||hit.t<bestT&&(bestT=hit.t,bestLine=line,bestPoint=hit.point))}const nextT=Math.min(tMaxX,tMaxY);if(nextT*cellSize>bestT)break;if(nextT>maxDistance)break;tMaxX<tMaxY?(tMaxX+=tDeltaX,cellX+=stepX):(tMaxY+=tDeltaY,cellY+=stepY)}return bestLine&&bestPoint?out?(out.line=bestLine,out.point=bestPoint,out.distance=bestT,out.t=bestT,out):{line:bestLine,point:bestPoint,distance:bestT,t:bestT}:null}tempKeys=[];getLineCellKeys(line,out=this.tempKeys){out.length=0;const x0=line.start.x/this.cellSize,y0=line.start.y/this.cellSize,x1=line.end.x/this.cellSize,y1=line.end.y/this.cellSize;let cellX=Math.floor(x0),cellY=Math.floor(y0);const endX=Math.floor(x1),endY=Math.floor(y1),dx=x1-x0,dy=y1-y0,stepX=dx>0?1:dx<0?-1:0,stepY=dy>0?1:dy<0?-1:0,tDeltaX=0===stepX?1/0:Math.abs(1/dx),tDeltaY=0===stepY?1/0:Math.abs(1/dy);let tMaxX=stepX>0?(Math.floor(x0)+1-x0)*tDeltaX:(x0-Math.floor(x0))*tDeltaX,tMaxY=stepY>0?(Math.floor(y0)+1-y0)*tDeltaY:(y0-Math.floor(y0))*tDeltaY;try{for(;;){if(out.length>1e4){out.length=0;break}if(out.push(this.getKey(cellX,cellY)),cellX===endX&&cellY===endY)break;tMaxX<tMaxY?(tMaxX+=tDeltaX,cellX+=stepX):(tMaxY+=tDeltaY,cellY+=stepY)}}catch(error){console.log(out.length)}return out}toCell(value){return Math.floor(value/this.cellSize)}getKey(x,y){return 73856093n*BigInt(x)^19349663n*BigInt(y)}static from(lines,cellSize){const lsh=new LineSegmentSpatialHash(cellSize);return lsh.insertLines(lines),lsh}}class LineIndexGenerator{index=0;get size(){return this.index}constructor(lines=[]){lines.forEach(key=>{const id=this.next();this.map.set(key,id),this.lineMap.set(id,key)})}next(){return this.index++}reset(){this.index=0}map=/* @__PURE__ */new Map;lineMap=/* @__PURE__ */new Map;getIndex(key){if(!this.map.has(key)){const id=this.next();this.map.set(key,id),this.lineMap.set(id,key)}return this.map.get(key)}getLine(index2){return this.lineMap.get(index2)}}class UndirectedGraph{adjacencyList;get size(){return this.adjacencyList.size}constructor(){this.adjacencyList=/* @__PURE__ */new Map}addNode(node){this.adjacencyList.has(node)||this.adjacencyList.set(node,/* @__PURE__ */new Set)}addEdge(u2,v2){this.adjacencyList.get(u2)?.add(v2)??this.adjacencyList.set(u2,/* @__PURE__ */new Set([v2])),this.adjacencyList.get(v2)?.add(u2)??this.adjacencyList.set(v2,/* @__PURE__ */new Set([u2]))}removeEdge(u2,v2){this.adjacencyList.get(u2)?.delete(v2),this.adjacencyList.get(v2)?.delete(u2)}removeNode(node){const neighbors=this.adjacencyList.get(node);if(neighbors){for(const neighbor of neighbors)this.adjacencyList.get(neighbor)?.delete(node);this.adjacencyList.delete(node)}}getNeighbors(node){return this.adjacencyList.get(node)}printGraph(){for(let[node,neighbors]of this.adjacencyList.entries())console.log(`${node} -> ${[...neighbors].join(", ")}`)}getPaths(){let paths=[];const visited=/* @__PURE__ */new Set,dfs=(node,path)=>{path.push(node),visited.add(node);let hasUnvisitedNeighbor=!1;const neighbors=this.getNeighbors(node);if(neighbors)for(const neighbor of neighbors)visited.has(neighbor)||(hasUnvisitedNeighbor=!0,dfs(neighbor,path));!hasUnvisitedNeighbor&&path.length>1&&paths.push([...path]),path.pop()};for(const node of this.adjacencyList.keys())visited.has(node)||dfs(node,[]);return paths}forEach(callbackFun){for(let[node,neighbors]of this.adjacencyList.entries())callbackFun(node,neighbors)}forEachEdge(callbackFun){for(const[node,neighbors]of this.adjacencyList.entries())for(const neighbor of neighbors)neighbor>node&&callbackFun(node,neighbor)}}class LineSegmentUndirectedGraph extends UndirectedGraph{lineMap=/* @__PURE__ */new Map;pointToIndex=/* @__PURE__ */new Map;indexToPoint=/* @__PURE__ */new Map;nextIndex=0;constructor(lines=[]){super(),lines.length>0&&this.buildFromLines(lines)}buildFromLines(lines){lines.length>1e3&&(this.pointToIndex.clear(),this.indexToPoint.clear(),this.nextIndex=0);for(const line of lines){const i1=this.getOrCreateIndex(line.start),i2=this.getOrCreateIndex(line.end);super.addEdge(i1,i2);const key=i1<i2?`${i1}-${i2}`:`${i2}-${i1}`;this.lineMap.set(key,line)}}getLine(a2,b4){const key=a2<b4?`${a2}-${b4}`:`${b4}-${a2}`;return this.lineMap.get(key)}getLineAll(){return Array.from(this.lineMap.values())}getOrCreateIndex(point2){const code=point2.hashCode();let index2=this.pointToIndex.get(code);return void 0===index2&&(index2=this.nextIndex++,this.pointToIndex.set(code,index2),this.indexToPoint.set(index2,point2)),index2}getIndex(point2){return this.pointToIndex.get(point2.hashCode())}getPoint(index2){return this.indexToPoint.get(index2)}get points(){return Array.from(this.indexToPoint.values())}get lines(){return Array.from(this.lineMap.values())}addLines(lines){return this.buildFromLines(lines),this}removeLines(lines){for(const line of lines){const i1=this.getIndex(line.start),i2=this.getIndex(line.end);if(void 0!==i1&&void 0!==i2){super.removeEdge(i1,i2);const key=i1<i2?`${i1}-${i2}`:`${i2}-${i1}`;this.lineMap.delete(key)}}}pathToLines(path){const lines=[];for(let i=0;i<path.length;i++){const line=this.getLine(path[i],path[(i+1)%path.length]);line&&lines.push(line)}return lines}clear(){this.adjacencyList.clear(),this.lineMap.clear(),this.pointToIndex.clear(),this.indexToPoint.clear(),this.nextIndex=0}breakpointMerging(callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){const unionFindSet=new UnionFindSet(this.lineMap.size),lineIndexGenerator=new LineIndexGenerator;this.adjacencyList.forEach((set2,k)=>{if(2!==set2.size)return;const values=set2.values(),v12=values.next().value,v2=values.next().value,line1=this.getLine(k,v12),line2=this.getLine(k,v2);line1.isParallelTo(line2)&&unionFindSet.union(lineIndexGenerator.getIndex(line1),lineIndexGenerator.getIndex(line2))}),unionFindSet.getAllSets().forEach(list=>{if(list.length<=1)return;const lines=list.map(i=>lineIndexGenerator.getLine(i)),newLine=LineSegmentUtils.mergeCollinearSegments(lines);callBack&&callBack(newLine,lines),lines.forEach(line=>removeLines.add(line)),newLines.push(newLine),this.removeLines(lines),this.addLines([newLine])})}forEachPathLine(fun){const leafVertices=[];this.adjacencyList.forEach((v2,k)=>1===v2.size&&leafVertices.push(k));const getEdgeKey=(a2,b4)=>a2<b4?`${a2}_${b4}`:`${b4}_${a2}`,visitedEdge=/* @__PURE__ */new Set,vertexIndexMap=new ArrayMap;let index2=0;const traverseEdges=v2=>{const set2=this.getNeighbors(v2);if(!set2)return;const start=this.getPoint(v2);for(const v12 of set2){const key=getEdgeKey(v2,v12);if(visitedEdge.has(key))continue;const end=this.getPoint(v12),line=this.getLine(v2,v12);let endType="none";1===this.getNeighbors(v12).size?endType="isolated":vertexIndexMap.has(v12)&&(endType="intersect");const indexList=[...vertexIndexMap.get(v2)??[]];vertexIndexMap.append(v2,index2),vertexIndexMap.append(v12,index2),fun(start,end,line,index2++,endType,indexList),visitedEdge.add(key),traverseEdges(v12)}};for(let i=0;i<leafVertices.length;i++){const v2=leafVertices[i];index2=0,traverseEdges(v2)}for(const v2 of this.adjacencyList.keys())vertexIndexMap.has(v2)||(index2=0,traverseEdges(v2))}static breakpointMerging(lines,callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){PointUtils.adsorb(LineSegmentUtils.flatPoints(lines),1e-4);const lud=new LineSegmentUndirectedGraph(lines);return lud.breakpointMerging(callBack,removeLines,newLines),lines=lud.getLineAll()}static rotate(lines,angle,callbackFun){const center=Box2.fromByLineSegment(...lines).center;return lines.map(line=>(line.start.rotate(center,angle),line.end.rotate(center,angle),callbackFun&&callbackFun(line,center,angle),line))}toJson(){const edges=[],ids=/* @__PURE__ */new Set;return this.adjacencyList.forEach((list,v2)=>list.forEach(v22=>{const id=v2>v22?`${v2}_${v22}`:`${v22}_${v2}`;ids.has(id)||(edges.push([v2,v22]),ids.add(id))})),{points:this.points,edges:edges}}}class LineSegmentUtils{static clone(lines){return lines.map(line=>line.clone())}static precision(lines,count){for(const l of lines)l.start.precision(count),l.end.precision(count);return lines}static legitimacy(line){return[line.start.x,line.start.y,line.end.x,line.end.y].every(v2=>"number"==typeof v2&&!Number.isNaN(v2))}static precision4(lines){for(const l of lines)l.start.precision4(),l.end.precision4();return lines}static maxLengthLineIndex(lines,excludeCallBack){let maxLength=-1/0,maxIndex=-1;for(let i=0;i<lines.length;i++){if(excludeCallBack&&excludeCallBack(lines[i]))continue;const length=lines[i].length;length>maxLength&&(maxLength=length,maxIndex=i)}return maxIndex}static getLinesCenter(lines){let totalWeight=0,x=0,y=0;for(const line of lines){const len=line.length,center=line.center;x+=center.x*len,y+=center.y*len,totalWeight+=len}return new Point(x/totalWeight,y/totalWeight)}static GroupBuilder(groups){const builder={handle(k,fn2){return Array.isArray(k)?(k.forEach(k2=>this.handle(k2,fn2)),builder):(groups[k]&&(groups[k]=fn2(groups[k],groups)),builder)},handleAll:fn2=>(Object.keys(groups).forEach(k=>{groups[k]=fn2(groups[k],k,groups)}),builder),merge:()=>Object.values(groups).flat()};return builder}static group(lines,fn2){const arrayMap=new ArrayMap;for(let i=0;i<lines.length;i++){const line=lines[i],key=fn2(line);arrayMap.append(key,line)}return arrayMap.reduce((list,lines2,key)=>(list[key]=lines2,list),{})}static groupByPathAndParallel(lines){const pointVirtualGrid=new PointSpatialHash,quadtree=new Quadtree(Box2.fromByLineSegment(...lines));lines.forEach(line=>{line.points.forEach(p2=>pointVirtualGrid.insert(p2,line)),quadtree.insert(line)});const visited=/* @__PURE__ */new Set;function dfs(line,visited2,group2){if(visited2.has(line))return;const waitLines=[];return waitLines.push(...pointVirtualGrid.queryPoint(line.start).filter(result=>result.userData!==line&&line.isParallelTo(result.userData,.1)).map(item=>item.userData),...pointVirtualGrid.queryPoint(line.end).filter(result=>result.userData!==line&&line.isParallelTo(result.userData,.1)).map(item=>item.userData),...quadtree.queryPoint(line.start).filter(result=>result.line!==line&&line.isParallelTo(result.line,.1)).map(item=>item.line),...quadtree.queryPoint(line.end).filter(result=>result.line!==line&&line.isParallelTo(result.line,.1)).map(item=>item.line)),waitLines.forEach(line1=>{line1&&!group2.has(line1)&&(group2.add(line1),dfs(line1,visited2,group2))}),visited2.add(line),group2}const groups=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(visited.has(line))continue;const group2=dfs(line,visited,/* @__PURE__ */new Set([line]));group2&&groups.push([...group2])}return groups}static groupByCenterPointSide(lines,line){const map=/* @__PURE__ */new Map;return lines.forEach(l=>{const m=line.getPointSideOfLine(l.center);map.has(m)||map.set(m,[]),map.get(m)?.push(l)}),[...map.values()]}static groupByPath(lines){const pointVirtualGrid=new PointSpatialHash;function dfs(point2,group2,visted2){pointVirtualGrid.queryPoint(point2,!0).forEach(item=>{const line=item.userData;if(visted2.has(line))return;visted2.add(line),group2.push(line);dfs(line.getAnotherPoint(item.point),group2,visted2)})}lines.forEach(line=>line.points.forEach(p2=>pointVirtualGrid.insert(p2,line)));const visted=/* @__PURE__ */new Set,groups=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(visted.has(line))continue;const group2=[line];visted.add(line),dfs(line.start,group2,visted),dfs(line.end,group2,visted),groups.push(group2)}return groups}static groupBySharedPoints(lines){const unionFindSet=new UnionFindSet(lines.length),map=/* @__PURE__ */new Map;for(let i=0;i<lines.length;i++)lines[i].points.forEach(point2=>{const id=point2.hashCode();map.has(id)&&unionFindSet.union(map.get(id),i),map.set(id,i)});return unionFindSet.getAllSets().valueArray.map(list=>list.map(i=>lines[i]))}static groupByLeafPath(lines){PointUtils.adsorb(lines.flatMap(line=>line.points));const paths=[],lud=new LineSegmentUndirectedGraph(lines);let path=[];return lud.forEachPathLine((_start,_end,line,_,endType)=>{path.push(line),"none"!==endType&&(paths.push(path),path=[])}),paths}static groupByParallelToAxis(lines,axisLine,errAngle=1e-9){const parallelLines=[],otherLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];axisLine.isParallelTo(line,errAngle)?parallelLines.push(line):otherLines.push(line)}return[parallelLines,otherLines]}static groupByProjectedOverlap(lines,parallelAxis,verticalAxis,esp=.05,gap=.01,onGroup){esp/=verticalAxis.length,gap/=parallelAxis.length;const vls=lines.map(line=>[verticalAxis.projectPointValue(line.start),line,[parallelAxis.projectPointValue(line.start),parallelAxis.projectPointValue(line.end)].sort((a2,b4)=>a2-b4)]).sort((a2,b4)=>a2[0]-b4[0]),unionFindSet=new UnionFindSet(vls.length);for(let i2=0;i2<vls.length;i2++){const[ipv,_iline,[istart,iend]]=vls[i2];for(let j=i2+1;j<vls.length;j++){const[jpv,_jline,[jstart,jend]]=vls[j];if(jpv-ipv>esp)break;Math.min(iend,jend)-Math.max(istart,jstart)>-gap&&unionFindSet.union(i2,j)}}const map=unionFindSet.getAllSets(),groups=new Array(map.size);let i=0;return map.forEach(list=>{const group2=new Array(list.length),verticalPvList=new Array(list.length),parallelPvList=new Array(list.length);groups[i++]=group2;for(let i2=0;i2<list.length;i2++){const[pv,line,pv2]=vls[list[i2]];group2[i2]=line,verticalPvList[i2]=pv,parallelPvList[i2]=pv2}onGroup?.(group2,verticalPvList,verticalAxis,parallelPvList,parallelAxis)}),groups}static merge(lines,out=new LineSegment){if(1===lines.length)return lines[0];let mainLine=lines[0];for(const l of lines)l.length>mainLine.length&&(mainLine=l);let maxPValue=-1/0,minPValue=1/0,maxPoint=null,minPoint=null;for(let i=0;i<lines.length;i++){const line=lines[i];for(let j=0;j<line.points.length;j++){const p2=line.points[j],pValue=mainLine.projectPointValue(p2);pValue>maxPValue&&(maxPValue=pValue,maxPoint=p2),pValue<minPValue&&(minPValue=pValue,minPoint=p2)}}if(!minPoint||!maxPoint)throw new Error("mergeCollinearSegments: 无效输入");const newStart=minPoint.clone(),newEnd=maxPoint.clone(),fittedLine=out.set(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeLinesByMaxlength(...lines){if(1===lines.length)return lines[0];const baseLine=lines.slice(0).sort((a2,b4)=>b4.length-a2.length)[0],principal=baseLine.direction().normalize();let newStart=baseLine.start.clone(),newEnd=baseLine.end.clone();const getScalar=pt2=>pt2.x*principal.x+pt2.y*principal.y;let minScalar=getScalar(newStart),maxScalar=getScalar(newEnd);for(const line of lines)for(const pt2 of line.points){const scalar=getScalar(pt2);scalar<minScalar&&(minScalar=scalar,newStart=baseLine.projectPoint(pt2,!1)),scalar>maxScalar&&(maxScalar=scalar,newEnd=baseLine.projectPoint(pt2,!1))}const fittedLine=new LineSegment(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeCollinearSegments(lines,out=new LineSegment){if(1===lines.length)return lines[0];let mainLine=lines[0];for(const l of lines)l.length>mainLine.length&&(mainLine=l);let maxPValue=-1/0,minPValue=1/0,maxPoint=null,minPoint=null;for(let i=0;i<lines.length;i++){const line=lines[i];for(let j=0;j<line.points.length;j++){const p2=line.points[j],pValue=mainLine.projectPointValue(p2);pValue>maxPValue&&(maxPValue=pValue,maxPoint=p2),pValue<minPValue&&(minPValue=pValue,minPoint=p2)}}if(!minPoint||!maxPoint)throw new Error("mergeCollinearSegments: 无效输入");const newStart=minPoint.clone(),newEnd=maxPoint.clone(),fittedLine=out.set(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeParallelSegments(lines,callBack){const groups=this.groupByPathAndParallel(lines),newLines=[],deleteLines=[];return groups.forEach(group2=>{if(group2.length<=1)return;const newLine=this.mergeCollinearSegments(group2);newLine&&(newLines.push(newLine),deleteLines.push(...group2),callBack&&callBack(newLine,group2))}),lines.push(...newLines),{lines:lines.filter(line=>!deleteLines.includes(line)),newLines:newLines,deleteLines:deleteLines}}static mergeCollinearSegmentsAll(lines,callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){const map=/* @__PURE__ */new Map;lines.forEach(line=>line.points.forEach(p2=>{const id=`${p2.X.toFixed(6)}_${p2.Y.toFixed(6)}`;map.has(id)||map.set(id,[]),map.get(id)?.push(line)}));const statistics=/* @__PURE__ */new Map,ids=/* @__PURE__ */new Map;function push(lines2){const id1=ids.get(lines2[0]),id2=ids.get(lines2[1]);let id;if(id1&&id2){id=id1;const list1=statistics.get(id1);[...statistics.get(id2)].forEach(line=>{list1.add(line),ids.set(line,id)})}else id=id1??id2??(16777215*Math.random()).toString(16);statistics.has(id)||statistics.set(id,/* @__PURE__ */new Set);const list=statistics.get(id);lines2.forEach(line=>{ids.set(line,id),list?.add(line)})}for(const list of map.values()){if(2!==list.length)continue;const startLine=list[0],endLine=list[1];startLine.isParallelTo(endLine)&&push(list)}for(const set2 of statistics.values()){const list=[...set2],newLine=this.mergeCollinearSegments(list);callBack&&callBack(newLine,list),list.forEach(line=>removeLines.add(line)),newLines.push(newLine)}return(lines=lines.filter(line=>!removeLines.has(line))).push(...newLines),lines}static deduplicate(lines,opt){const{precision:precision=4,necessaryLines:necessaryLines=[]}=opt??{},scale2=10**precision,seen=/* @__PURE__ */new Set;return necessaryLines.filter(line=>{const a2=`${Math.round(line.start.x*scale2)}_${Math.round(line.start.y*scale2)}`,b4=`${Math.round(line.end.x*scale2)}_${Math.round(line.end.y*scale2)}`,key=a2<b4?`${a2}_${b4}`:`${b4}_${a2}`;seen.add(key)}),lines.filter(line=>{const a2=`${Math.round(line.start.x*scale2)}_${Math.round(line.start.y*scale2)}`,b4=`${Math.round(line.end.x*scale2)}_${Math.round(line.end.y*scale2)}`,key=a2<b4?`${a2}_${b4}`:`${b4}_${a2}`;return!seen.has(key)&&(seen.add(key),!0)})}static clippingByPoints(line,points,callBack){if(!(line instanceof LineSegment))throw new Error("参数1并非线段");let ts2=points.map(p2=>Math.min(1,Math.max(0,line.projectPointValue(p2)))).filter(t2=>!Number.isNaN(t2)).concat([0,1]);ts2=ts2.filter(t2=>t2>=-1e-8&&t2<=1+1e-8),ts2.sort((a2,b4)=>a2-b4);const uniqueTs=[];for(let i=0;i<ts2.length;i++)(0===i||Math.abs(ts2[i]-ts2[i-1])>1e-8)&&uniqueTs.push(ts2[i]);const result=[],newPoints=uniqueTs.map(t2=>line.pointAt(t2));for(let i=0;i<uniqueTs.length-1;i++){const p1=newPoints[i],p2=newPoints[i+1],newLine=line.clone();newLine.set(p1,p2),callBack&&callBack(newLine,line),result.push(newLine)}return result}static clippingByLines(target,clippingLines,callBack){if(0===clippingLines.length)return[target];const eps=1e-6,intervals=clippingLines.map(line=>{const ts2=line.points.map(p2=>target.projectPointValue(p2)).sort((a2,b4)=>a2-b4);return[Math.max(0,ts2[0]),Math.min(1,ts2[1])]}).filter(([s,e])=>e-s>eps).sort((a2,b4)=>a2[0]-b4[0]);if(0===intervals.length)return callBack?.(target.clone(),target),[target];const merged=[];let cur=intervals[0];for(let i=1;i<intervals.length;i++){const next=intervals[i];next[0]<=cur[1]+eps?cur[1]=Math.max(cur[1],next[1]):(merged.push(cur),cur=next)}merged.push(cur);const newLines=[];let prev=0;for(const[s,e]of merged){if(s>prev+eps){const newLine=new LineSegment(target.pointAt(prev),target.pointAt(s));newLine.length>1e-4&&(newLines.push(newLine),callBack?.(newLine,target))}prev=Math.max(prev,e)}if(prev<1-eps){const newLine=new LineSegment(target.pointAt(prev),target.pointAt(1));newLine.length>1e-4&&(newLines.push(newLine),callBack?.(newLine,target))}return newLines}static clippingByLine(target,clippingLine,callBack){return LineSegmentUtils.clippingByLines(target,[clippingLine],callBack)}static constrainLine(line,base){const center=line.center,width=line.length;if(base.length<width)return line.start.copy(base.start),line.end.copy(base.end),line;const hw=.5*width,start=base.start.clone().add(base.end.directionFrom(base.start).multiplyScalar(.5*width)),end=base.end.clone().add(base.start.directionFrom(base.end).multiplyScalar(.5*width)),dir=base.direction(),pl=new LineSegment(start,end);return center.copy(pl.projectPoint(center,!1)),pl.projectPoint(center,!0)||(center.distance(start)<center.distance(end)?center.copy(start):center.copy(end),line.start.copy(center).add(dir.clone().multiplyScalar(-hw)),line.end.copy(center).add(dir.clone().multiplyScalar(hw))),line}static flatPoints(lines){if(lines instanceof LineSegment)return[...lines.points];const points=new Array(2*lines.length);for(let i=0;i<lines.length;i++){const line=lines[i];points[2*i]=line.start,points[2*i+1]=line.end}return points}static splitIntersections(lines,opt){console.log();const{onSplit:onSplit,obstacle:obstacle=[]}=opt??{},queryLines=[...lines,...obstacle],lsh=LineSegmentSpatialHash.from(queryLines),queryLine2=new LineSegment,arrayMap=new ArrayMap,obstacleSet=new Set(obstacle);for(let i=0;i<queryLines.length;i++){const line=queryLines[i];queryLine2.copy(line).setLength(line.length+.04),lsh.queryLine(queryLine2).forEach(resLine=>{if(obstacleSet.has(resLine))return;if(line.isSameEndpoint(resLine,1e-4))return;const point2=resLine.getIntersection(line);point2&&arrayMap.append(resLine,point2)})}const newLines=[],removeSet=/* @__PURE__ */new Set;return arrayMap.forEach((points,line)=>{if(points.length){let lines2=LineSegmentUtils.clippingByPoints(line,points);onSplit?.(line,lines2),newLines.push(...lines2),removeSet.add(line)}else newLines.push(line)}),(lines=lines.filter(line=>!removeSet.has(line))).push(...newLines),lines}static findDominantDirectionLine(lineSegments,bin=5){const yAxisLine=new LineSegment(new Point(0,0),new Point(0,1)),lines=[...lineSegments].sort((a2,b4)=>b4.length-a2.length).slice(0,20),angles=lines.map(line2=>{let angle=yAxisLine.angle(line2,{unit:"degree",range:"180"});return angle>90&&(angle=180-angle),Math.round(angle/bin)*bin}),lineMap=/* @__PURE__ */new Map;angles.forEach((angle,index2)=>{lineMap.has(angle)||lineMap.set(angle,[]),lineMap.get(angle)?.push(lines[index2])});const line=[...lineMap.values()].sort((a2,b4)=>b4.length-a2.length)[0]?.sort((a2,b4)=>b4.length-a2.length)[0];return line??new LineSegment}static createModifyManager(){const modifyMap=new MapEnhance;function setPoint(line,point2,value){modifyMap.has(line)||modifyMap.set(line,new ArrayMap);modifyMap.get(line).append(point2,value)}function modify(){modifyMap.forEach((arrayMap,line)=>{arrayMap.forEach((list,point2)=>{const otherPoint=line.getAnotherPoint(point2);list.push(point2),list.sort((p1,p2)=>p2.distance(otherPoint)-p1.distance(otherPoint)),list[0]===point2?point2.copy(list[1]):point2.copy(list[0])})}),modifyMap.clear()}return{get setPoint(){return setPoint},get modify(){return modify},clear(){modifyMap.clear()}}}static dash(line,pattern){const result=[],length=line.length;if(length<=0||0===pattern.length)return result;const dirX=(line.end.x-line.start.x)/length,dirY=(line.end.y-line.start.y)/length;let offset=0,patternIndex=0;for(;offset<length;){const value=pattern[patternIndex%pattern.length],abs=Math.abs(value);if(abs<=0){patternIndex++;continue}const startOffset=offset,endOffset=Math.min(offset+abs,length);if(patternIndex%2==0){const x1=line.start.x+dirX*startOffset,y1=line.start.y+dirY*startOffset,x2=line.start.x+dirX*endOffset,y2=line.start.y+dirY*endOffset;result.push(new LineSegment(new Point(x1,y1),new Point(x2,y2)))}offset=endOffset,patternIndex++}return result}static findBestReferenceSegment(opt){const{lines:lines}=opt,lsh=LineSegmentSpatialHash.from(opt.referenceLines),results=new Array(lines.length);function parallelWeight(angle){return Math.abs(angle-90)/90}for(let i=0;i<lines.length;i++){const line=lines[i],rectangle=line.toRectangle(.5,"butt"),findResult=lsh.queryRectangle(rectangle).filter(quLine=>quLine.isParallelTo(line,20)).sort((l1,l2)=>{const angle1=line.angle(l1,{unit:"degree",range:"180"}),angle2=line.angle(l2,{unit:"degree",range:"180"}),aW1=5*parallelWeight(angle1),aW2=5*parallelWeight(angle2),dist1=line.distanceToSegment(l1),dist2=line.distanceToSegment(l2),maxDist=Math.max(dist1,dist2);return aW2+3*(1-dist2/maxDist)-(aW1+3*(1-dist1/maxDist))});results[i]=findResult.length?findResult[0]:null}return results}static sampleSegment(line,count){let step=1/count;const result=[];for(let i=0;i<=count;i++){const t2=i*step;result.push(line.pointAt(t2))}return result}static sampleSegmentBydistance(line,dist=.001){let count=1/dist;const result=[];for(let i=0;i<=count;i++){const t2=i*dist;result.push(line.pointAt(t2))}return result}static globalPoolArray=new Array;static globalPool=lazy(()=>LineSegmentUtils.createPool());static createPool(pool2=this.globalPoolArray){const usePool=[];return{get line(){const line=pool2.pop()??new LineSegment;return usePool.push(line),line},free(line){const index2=usePool.indexOf(line);index2<0||(usePool[index2]=usePool[usePool.length-1],usePool.pop(),pool2.push(line))},freeAll(){for(let i=0;i<usePool.length;i++)pool2.push(usePool[i]);usePool.length=0}}}}class Lines extends THREE.LineSegments{geometry=new THREE.BufferGeometry;points=[];pointsObject3D;continuous=!0;constructor(points=[],color=16777215){super(),this.geometry=this.geometry,this.addPoint(...points),this.frustumCulled=!1,this.pointsObject3D=new THREE.Points(this.geometry,new THREE.PointsMaterial({sizeAttenuation:!1,size:10})),this.material=new THREE.LineBasicMaterial({color:color})}addPoint(...points){this.points.push(...points),this.updateGeometry()}setPoint(...points){this.points.length=0,this.addPoint(...points)}setColor(color){return this.material.color instanceof THREE.Color?this.material.color.setHex(color):this.material.color=new THREE.Color(color),this}setOpacity(opacity){return this.material.transparent=!0,this.material.opacity=opacity,this}getCenter(startIndex,endIndex){if(endIndex=endIndex??startIndex,startIndex<=this.points.length-1&&endIndex<=this.points.length-1){const start=this.points[startIndex],end=this.points[endIndex];return start.clone().add(end).multiplyScalar(.5)}throw new Error("索引不在可取范围")}getDistance(startIndex,endIndex){if(endIndex=endIndex??startIndex,startIndex<=this.points.length-1&&endIndex<=this.points.length-1){const start=this.points[startIndex],end=this.points[endIndex];return start.distanceTo(end)}throw new Error("索引不在可取范围")}_timer=null;updateGeometry(){this._timer&&clearTimeout(this._timer),this._timer=setTimeout(()=>{const array=[];if(this.continuous)this.points.forEach((p2,i)=>{if(0===i)return;const p0=this.points[i-1];array.push(p0.x,p0.y,p0.z,p2.x,p2.y,p2.z)});else for(let i=0;i<this.points.length;i+=2){const p0=this.points[i],p2=this.points[i+1];p0&&p2&&array.push(p0.x,p0.y,p0.z,p2.x,p2.y,p2.z)}const position=new THREE.BufferAttribute(new Float32Array(array),3);this.geometry.setAttribute("position",position),this._timer=null,this.dispatchEvent({type:"updateGeometry"})})}}class LineDashed extends Lines{constructor(points,color,dashSize=.02,gapSize=.02){super(points,color),this.material=new THREE.LineDashedMaterial({color:color,dashSize:dashSize,gapSize:gapSize}),this.addEventListener("updateGeometry",()=>{this.computeLineDistances()})}setDashSize(dashSize){this.material.dashSize=dashSize,this.computeLineDistances()}setGapSize(gapSize){this.material.gapSize=gapSize,this.computeLineDistances()}}var factors={centimeters:637100880,centimetres:637100880,degrees:360/(2*Math.PI),feet:20902260.511392,inches:6371008.8*39.37,kilometers:6371.0088,kilometres:6371.0088,meters:6371008.8,metres:6371008.8,miles:3958.761333810546,millimeters:6371008800,millimetres:6371008800,nauticalmiles:6371008.8/1852,radians:1,yards:6371008.8*1.0936};function feature(geom,properties,options={}){const feat={type:"Feature"};return(0===options.id||options.id)&&(feat.id=options.id),options.bbox&&(feat.bbox=options.bbox),feat.properties=properties||{},feat.geometry=geom,feat}function point$1(coordinates,properties,options={}){if(!coordinates)throw new Error("coordinates is required");if(!Array.isArray(coordinates))throw new Error("coordinates must be an Array");if(coordinates.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!isNumber$1(coordinates[0])||!isNumber$1(coordinates[1]))throw new Error("coordinates must contain numbers");return feature({type:"Point",coordinates:coordinates},properties,options)}function polygon$2(coordinates,properties,options={}){for(const ring of coordinates){if(ring.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(ring[ring.length-1].length!==ring[0].length)throw new Error("First and last Position are not equivalent.");for(let j=0;j<ring[ring.length-1].length;j++)if(ring[ring.length-1][j]!==ring[0][j])throw new Error("First and last Position are not equivalent.")}return feature({type:"Polygon",coordinates:coordinates},properties,options)}function radiansToDegrees(radians){return 180*(radians%(2*Math.PI))/Math.PI}function degreesToRadians(degrees){return degrees%360*Math.PI/180}function convertLength(length,originalUnit="kilometers",finalUnit="kilometers"){if(!(length>=0))throw new Error("length must be a positive number");return function(radians,units2="kilometers"){const factor=factors[units2];if(!factor)throw new Error(units2+" units is invalid");return radians*factor}(function(distance2,units2="kilometers"){const factor=factors[units2];if(!factor)throw new Error(units2+" units is invalid");return distance2/factor}(length,originalUnit),finalUnit)}function isNumber$1(num){return!isNaN(num)&&null!==num&&!Array.isArray(num)}function coordEach(geojson,callback,excludeWrapCoord){if(null!==geojson)for(var j,k,l,geometry,stopG,coords,geometryMaybeCollection,isGeometryCollection,wrapShrink=0,coordIndex=0,type=geojson.type,isFeatureCollection="FeatureCollection"===type,isFeature="Feature"===type,stop=isFeatureCollection?geojson.features.length:1,featureIndex=0;featureIndex<stop;featureIndex++){stopG=(isGeometryCollection=!!(geometryMaybeCollection=isFeatureCollection?geojson.features[featureIndex].geometry:isFeature?geojson.geometry:geojson)&&"GeometryCollection"===geometryMaybeCollection.type)?geometryMaybeCollection.geometries.length:1;for(var geomIndex=0;geomIndex<stopG;geomIndex++){var multiFeatureIndex=0,geometryIndex=0;if(null!==(geometry=isGeometryCollection?geometryMaybeCollection.geometries[geomIndex]:geometryMaybeCollection)){coords=geometry.coordinates;var geomType=geometry.type;switch(wrapShrink=!excludeWrapCoord||"Polygon"!==geomType&&"MultiPolygon"!==geomType?0:1,geomType){case null:break;case"Point":if(!1===callback(coords,coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++,multiFeatureIndex++;break;case"LineString":case"MultiPoint":for(j=0;j<coords.length;j++){if(!1===callback(coords[j],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++,"MultiPoint"===geomType&&multiFeatureIndex++}"LineString"===geomType&&multiFeatureIndex++;break;case"Polygon":case"MultiLineString":for(j=0;j<coords.length;j++){for(k=0;k<coords[j].length-wrapShrink;k++){if(!1===callback(coords[j][k],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++}"MultiLineString"===geomType&&multiFeatureIndex++,"Polygon"===geomType&&geometryIndex++}"Polygon"===geomType&&multiFeatureIndex++;break;case"MultiPolygon":for(j=0;j<coords.length;j++){for(geometryIndex=0,k=0;k<coords[j].length;k++){for(l=0;l<coords[j][k].length-wrapShrink;l++){if(!1===callback(coords[j][k][l],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++}geometryIndex++}multiFeatureIndex++}break;case"GeometryCollection":for(j=0;j<geometry.geometries.length;j++)if(!1===coordEach(geometry.geometries[j],callback,excludeWrapCoord))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function geomReduce(geojson,callback,initialValue){var previousValue=initialValue;return function(geojson,callback){var i,j,g,geometry,stopG,geometryMaybeCollection,isGeometryCollection,featureProperties,featureBBox,featureId,featureIndex=0,isFeatureCollection="FeatureCollection"===geojson.type,isFeature="Feature"===geojson.type,stop=isFeatureCollection?geojson.features.length:1;for(i=0;i<stop;i++){for(geometryMaybeCollection=isFeatureCollection?geojson.features[i].geometry:isFeature?geojson.geometry:geojson,featureProperties=isFeatureCollection?geojson.features[i].properties:isFeature?geojson.properties:{},featureBBox=isFeatureCollection?geojson.features[i].bbox:isFeature?geojson.bbox:void 0,featureId=isFeatureCollection?geojson.features[i].id:isFeature?geojson.id:void 0,stopG=(isGeometryCollection=!!geometryMaybeCollection&&"GeometryCollection"===geometryMaybeCollection.type)?geometryMaybeCollection.geometries.length:1,g=0;g<stopG;g++)if(null!==(geometry=isGeometryCollection?geometryMaybeCollection.geometries[g]:geometryMaybeCollection))switch(geometry.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===callback(geometry,featureIndex,featureProperties,featureBBox,featureId))return!1;break;case"GeometryCollection":for(j=0;j<geometry.geometries.length;j++)if(!1===callback(geometry.geometries[j],featureIndex,featureProperties,featureBBox,featureId))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===callback(null,featureIndex,featureProperties,featureBBox,featureId))return!1;featureIndex++}}(geojson,function(currentGeometry,featureIndex,featureProperties,featureBBox,featureId){previousValue=0===featureIndex&&void 0===initialValue?currentGeometry:callback(previousValue,currentGeometry,featureIndex,featureProperties,featureBBox,featureId)}),previousValue}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if("function"==typeof f){var a2=function a3(){var isInstance=!1;try{isInstance=this instanceof a3}catch{}return isInstance?Reflect.construct(f,arguments,this.constructor):f.apply(this,arguments)};a2.prototype=f.prototype}else a2={};return Object.defineProperty(a2,"__esModule",{value:!0}),Object.keys(n).forEach(function(k){var d2=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a2,k,d2.get?d2:{enumerable:!0,get:function(){return n[k]}})}),a2}var hasRequiredRbush_min,concaveman$2={exports:{}},rbush_min$1={exports:{}};function requireRbush_min(){return hasRequiredRbush_min?rbush_min$1.exports:(hasRequiredRbush_min=1,rbush_min$1.exports=function(){function t2(t3,r3,e2,a3,h3){!function t4(n2,r4,e3,a4,h4){for(;a4>e3;){if(a4-e3>600){var o2=a4-e3+1,s2=r4-e3+1,l2=Math.log(o2),f2=.5*Math.exp(2*l2/3),u3=.5*Math.sqrt(l2*f2*(o2-f2)/o2)*(s2-o2/2<0?-1:1);t4(n2,r4,Math.max(e3,Math.floor(r4-s2*f2/o2+u3)),Math.min(a4,Math.floor(r4+(o2-s2)*f2/o2+u3)),h4)}var p3=n2[r4],d3=e3,x=a4;for(i(n2,e3,r4),h4(n2[a4],p3)>0&&i(n2,e3,a4);d3<x;){for(i(n2,d3,x),d3++,x--;h4(n2[d3],p3)<0;)d3++;for(;h4(n2[x],p3)>0;)x--}0===h4(n2[e3],p3)?i(n2,e3,x):i(n2,++x,a4),x<=r4&&(e3=x+1),r4<=x&&(a4=x-1)}}(t3,r3,e2||0,a3||t3.length-1,h3||n)}function i(t3,i2,n2){var r3=t3[i2];t3[i2]=t3[n2],t3[n2]=r3}function n(t3,i2){return t3<i2?-1:t3>i2?1:0}var r2=function(t3){void 0===t3&&(t3=9),this._maxEntries=Math.max(4,t3),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function e(t3,i2,n2){if(!n2)return i2.indexOf(t3);for(var r3=0;r3<i2.length;r3++)if(n2(t3,i2[r3]))return r3;return-1}function a2(t3,i2){h2(t3,0,t3.children.length,i2,t3)}function h2(t3,i2,n2,r3,e2){e2||(e2=p2(null)),e2.minX=1/0,e2.minY=1/0,e2.maxX=-1/0,e2.maxY=-1/0;for(var a3=i2;a3<n2;a3++){var h3=t3.children[a3];o(e2,t3.leaf?r3(h3):h3)}return e2}function o(t3,i2){return t3.minX=Math.min(t3.minX,i2.minX),t3.minY=Math.min(t3.minY,i2.minY),t3.maxX=Math.max(t3.maxX,i2.maxX),t3.maxY=Math.max(t3.maxY,i2.maxY),t3}function s(t3,i2){return t3.minX-i2.minX}function l(t3,i2){return t3.minY-i2.minY}function f(t3){return(t3.maxX-t3.minX)*(t3.maxY-t3.minY)}function u2(t3){return t3.maxX-t3.minX+(t3.maxY-t3.minY)}function m(t3,i2){return t3.minX<=i2.minX&&t3.minY<=i2.minY&&i2.maxX<=t3.maxX&&i2.maxY<=t3.maxY}function c(t3,i2){return i2.minX<=t3.maxX&&i2.minY<=t3.maxY&&i2.maxX>=t3.minX&&i2.maxY>=t3.minY}function p2(t3){return{children:t3,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function d2(i2,n2,r3,e2,a3){for(var h3=[n2,r3];h3.length;)if(!((r3=h3.pop())-(n2=h3.pop())<=e2)){var o2=n2+Math.ceil((r3-n2)/e2/2)*e2;t2(i2,o2,n2,r3,a3),h3.push(n2,o2,o2,r3)}}return r2.prototype.all=function(){return this._all(this.data,[])},r2.prototype.search=function(t3){var i2=this.data,n2=[];if(!c(t3,i2))return n2;for(var r3=this.toBBox,e2=[];i2;){for(var a3=0;a3<i2.children.length;a3++){var h3=i2.children[a3],o2=i2.leaf?r3(h3):h3;c(t3,o2)&&(i2.leaf?n2.push(h3):m(t3,o2)?this._all(h3,n2):e2.push(h3))}i2=e2.pop()}return n2},r2.prototype.collides=function(t3){var i2=this.data;if(!c(t3,i2))return!1;for(var n2=[];i2;){for(var r3=0;r3<i2.children.length;r3++){var e2=i2.children[r3],a3=i2.leaf?this.toBBox(e2):e2;if(c(t3,a3)){if(i2.leaf||m(t3,a3))return!0;n2.push(e2)}}i2=n2.pop()}return!1},r2.prototype.load=function(t3){if(!t3||!t3.length)return this;if(t3.length<this._minEntries){for(var i2=0;i2<t3.length;i2++)this.insert(t3[i2]);return this}var n2=this._build(t3.slice(),0,t3.length-1,0);if(this.data.children.length)if(this.data.height===n2.height)this._splitRoot(this.data,n2);else{if(this.data.height<n2.height){var r3=this.data;this.data=n2,n2=r3}this._insert(n2,this.data.height-n2.height-1,!0)}else this.data=n2;return this},r2.prototype.insert=function(t3){return t3&&this._insert(t3,this.data.height-1),this},r2.prototype.clear=function(){return this.data=p2([]),this},r2.prototype.remove=function(t3,i2){if(!t3)return this;for(var n2,r3,a3,h3=this.data,o2=this.toBBox(t3),s2=[],l2=[];h3||s2.length;){if(h3||(h3=s2.pop(),r3=s2[s2.length-1],n2=l2.pop(),a3=!0),h3.leaf){var f2=e(t3,h3.children,i2);if(-1!==f2)return h3.children.splice(f2,1),s2.push(h3),this._condense(s2),this}a3||h3.leaf||!m(h3,o2)?r3?(n2++,h3=r3.children[n2],a3=!1):h3=null:(s2.push(h3),l2.push(n2),n2=0,r3=h3,h3=h3.children[0])}return this},r2.prototype.toBBox=function(t3){return t3},r2.prototype.compareMinX=function(t3,i2){return t3.minX-i2.minX},r2.prototype.compareMinY=function(t3,i2){return t3.minY-i2.minY},r2.prototype.toJSON=function(){return this.data},r2.prototype.fromJSON=function(t3){return this.data=t3,this},r2.prototype._all=function(t3,i2){for(var n2=[];t3;)t3.leaf?i2.push.apply(i2,t3.children):n2.push.apply(n2,t3.children),t3=n2.pop();return i2},r2.prototype._build=function(t3,i2,n2,r3){var e2,h3=n2-i2+1,o2=this._maxEntries;if(h3<=o2)return a2(e2=p2(t3.slice(i2,n2+1)),this.toBBox),e2;r3||(r3=Math.ceil(Math.log(h3)/Math.log(o2)),o2=Math.ceil(h3/Math.pow(o2,r3-1))),(e2=p2([])).leaf=!1,e2.height=r3;var s2=Math.ceil(h3/o2),l2=s2*Math.ceil(Math.sqrt(o2));d2(t3,i2,n2,l2,this.compareMinX);for(var f2=i2;f2<=n2;f2+=l2){var u3=Math.min(f2+l2-1,n2);d2(t3,f2,u3,s2,this.compareMinY);for(var m2=f2;m2<=u3;m2+=s2){var c3=Math.min(m2+s2-1,u3);e2.children.push(this._build(t3,m2,c3,r3-1))}}return a2(e2,this.toBBox),e2},r2.prototype._chooseSubtree=function(t3,i2,n2,r3){for(;r3.push(i2),!i2.leaf&&r3.length-1!==n2;){for(var e2=1/0,a3=1/0,h3=void 0,o2=0;o2<i2.children.length;o2++){var s2=i2.children[o2],l2=f(s2),u3=(m2=t3,c3=s2,(Math.max(c3.maxX,m2.maxX)-Math.min(c3.minX,m2.minX))*(Math.max(c3.maxY,m2.maxY)-Math.min(c3.minY,m2.minY))-l2);u3<a3?(a3=u3,e2=l2<e2?l2:e2,h3=s2):u3===a3&&l2<e2&&(e2=l2,h3=s2)}i2=h3||i2.children[0]}var m2,c3;return i2},r2.prototype._insert=function(t3,i2,n2){var r3=n2?t3:this.toBBox(t3),e2=[],a3=this._chooseSubtree(r3,this.data,i2,e2);for(a3.children.push(t3),o(a3,r3);i2>=0&&e2[i2].children.length>this._maxEntries;)this._split(e2,i2),i2--;this._adjustParentBBoxes(r3,e2,i2)},r2.prototype._split=function(t3,i2){var n2=t3[i2],r3=n2.children.length,e2=this._minEntries;this._chooseSplitAxis(n2,e2,r3);var h3=this._chooseSplitIndex(n2,e2,r3),o2=p2(n2.children.splice(h3,n2.children.length-h3));o2.height=n2.height,o2.leaf=n2.leaf,a2(n2,this.toBBox),a2(o2,this.toBBox),i2?t3[i2-1].children.push(o2):this._splitRoot(n2,o2)},r2.prototype._splitRoot=function(t3,i2){this.data=p2([t3,i2]),this.data.height=t3.height+1,this.data.leaf=!1,a2(this.data,this.toBBox)},r2.prototype._chooseSplitIndex=function(t3,i2,n2){for(var r3,e2,a3,o2,s2,l2,u3,m2=1/0,c3=1/0,p3=i2;p3<=n2-i2;p3++){var d3=h2(t3,0,p3,this.toBBox),x=h2(t3,p3,n2,this.toBBox),v2=(e2=d3,a3=x,o2=void 0,s2=void 0,l2=void 0,u3=void 0,o2=Math.max(e2.minX,a3.minX),s2=Math.max(e2.minY,a3.minY),l2=Math.min(e2.maxX,a3.maxX),u3=Math.min(e2.maxY,a3.maxY),Math.max(0,l2-o2)*Math.max(0,u3-s2)),M=f(d3)+f(x);v2<m2?(m2=v2,r3=p3,c3=M<c3?M:c3):v2===m2&&M<c3&&(c3=M,r3=p3)}return r3||n2-i2},r2.prototype._chooseSplitAxis=function(t3,i2,n2){var r3=t3.leaf?this.compareMinX:s,e2=t3.leaf?this.compareMinY:l;this._allDistMargin(t3,i2,n2,r3)<this._allDistMargin(t3,i2,n2,e2)&&t3.children.sort(r3)},r2.prototype._allDistMargin=function(t3,i2,n2,r3){t3.children.sort(r3);for(var e2=this.toBBox,a3=h2(t3,0,i2,e2),s2=h2(t3,n2-i2,n2,e2),l2=u2(a3)+u2(s2),f2=i2;f2<n2-i2;f2++){var m2=t3.children[f2];o(a3,t3.leaf?e2(m2):m2),l2+=u2(a3)}for(var c3=n2-i2-1;c3>=i2;c3--){var p3=t3.children[c3];o(s2,t3.leaf?e2(p3):p3),l2+=u2(s2)}return l2},r2.prototype._adjustParentBBoxes=function(t3,i2,n2){for(var r3=n2;r3>=0;r3--)o(i2[r3],t3)},r2.prototype._condense=function(t3){for(var i2=t3.length-1,n2=void 0;i2>=0;i2--)0===t3[i2].children.length?i2>0?(n2=t3[i2-1].children).splice(n2.indexOf(t3[i2]),1):this.clear():a2(t3[i2],this.toBBox)},r2}())}function defaultCompare$1(a2,b4){return a2<b4?-1:a2>b4?1:0}const require$$1=/* @__PURE__ */getAugmentedNamespace(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(data=[],compare=defaultCompare$1){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return this.length--,this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos<halfLength;){let left=1+(pos<<1),best=data[left];const right=left+1;if(right<this.length&&compare(data[right],best)<0&&(left=right,best=data[right]),compare(best,item)>=0)break;data[pos]=best,pos=left}data[pos]=item}}},Symbol.toStringTag,{value:"Module"})));var flat,hasRequiredFlat,nested,hasRequiredNested,hasRequiredPointInPolygon,pointInPolygon$1={exports:{}};function requirePointInPolygon(){if(hasRequiredPointInPolygon)return pointInPolygon$1.exports;hasRequiredPointInPolygon=1;var pointInPolygonFlat=hasRequiredFlat?flat:(hasRequiredFlat=1,flat=function(point2,vs2,start,end){var x=point2[0],y=point2[1],inside2=!1;void 0===start&&(start=0),void 0===end&&(end=vs2.length);for(var len=(end-start)/2,i=0,j=len-1;i<len;j=i++){var xi2=vs2[start+2*i+0],yi2=vs2[start+2*i+1],xj=vs2[start+2*j+0],yj=vs2[start+2*j+1];yi2>y!=yj>y&&x<(xj-xi2)*(y-yi2)/(yj-yi2)+xi2&&(inside2=!inside2)}return inside2}),pointInPolygonNested=hasRequiredNested?nested:(hasRequiredNested=1,nested=function(point2,vs2,start,end){var x=point2[0],y=point2[1],inside2=!1;void 0===start&&(start=0),void 0===end&&(end=vs2.length);for(var len=end-start,i=0,j=len-1;i<len;j=i++){var xi2=vs2[i+start][0],yi2=vs2[i+start][1],xj=vs2[j+start][0],yj=vs2[j+start][1];yi2>y!=yj>y&&x<(xj-xi2)*(y-yi2)/(yj-yi2)+xi2&&(inside2=!inside2)}return inside2});return pointInPolygon$1.exports=function(point2,vs2,start,end){return vs2.length>0&&Array.isArray(vs2[0])?pointInPolygonNested(point2,vs2,start,end):pointInPolygonFlat(point2,vs2,start,end)},pointInPolygon$1.exports.nested=pointInPolygonNested,pointInPolygon$1.exports.flat=pointInPolygonFlat,pointInPolygon$1.exports}var hasRequiredOrient2d_min,hasRequiredConcaveman,orient2d_min$1={exports:{}};function requireOrient2d_min(){return hasRequiredOrient2d_min||(hasRequiredOrient2d_min=1,function(t2){const e=134217729,n=33306690738754706e-32;function r2(t3,e2,n2,r3,o2){let f2,i2,u3,c3,s2=e2[0],a3=r3[0],d3=0,l2=0;a3>s2==a3>-s2?(f2=s2,s2=e2[++d3]):(f2=a3,a3=r3[++l2]);let p2=0;if(d3<t3&&l2<n2)for(a3>s2==a3>-s2?(u3=f2-((i2=s2+f2)-s2),s2=e2[++d3]):(u3=f2-((i2=a3+f2)-a3),a3=r3[++l2]),f2=i2,0!==u3&&(o2[p2++]=u3);d3<t3&&l2<n2;)a3>s2==a3>-s2?(u3=f2-((i2=f2+s2)-(c3=i2-f2))+(s2-c3),s2=e2[++d3]):(u3=f2-((i2=f2+a3)-(c3=i2-f2))+(a3-c3),a3=r3[++l2]),f2=i2,0!==u3&&(o2[p2++]=u3);for(;d3<t3;)u3=f2-((i2=f2+s2)-(c3=i2-f2))+(s2-c3),s2=e2[++d3],f2=i2,0!==u3&&(o2[p2++]=u3);for(;l2<n2;)u3=f2-((i2=f2+a3)-(c3=i2-f2))+(a3-c3),a3=r3[++l2],f2=i2,0!==u3&&(o2[p2++]=u3);return 0===f2&&0!==p2||(o2[p2++]=f2),p2}function o(t3){return new Float64Array(t3)}const f=33306690738754716e-32,i=22204460492503146e-32,u2=11093356479670487e-47,c=o(4),s=o(8),a2=o(12),d2=o(16),l=o(4);t2.orient2d=function(t3,o2,p2,b4,y,h2){const M=(o2-h2)*(p2-y),x=(t3-y)*(b4-h2),j=M-x;if(0===M||0===x||M>0!=x>0)return j;const m=Math.abs(M+x);return Math.abs(j)>=f*m?j:-function(t4,o3,f2,p3,b5,y2,h3){let M2,x2,j2,m2,_,v2,w,A,F,O2,P,g,k,q,z,B2,C,D2;const E=t4-b5,G=f2-b5,H2=o3-y2,I=p3-y2;_=(z=(A=E-(w=(v2=e*E)-(v2-E)))*(O2=I-(F=(v2=e*I)-(v2-I)))-((q=E*I)-w*F-A*F-w*O2))-(P=z-(C=(A=H2-(w=(v2=e*H2)-(v2-H2)))*(O2=G-(F=(v2=e*G)-(v2-G)))-((B2=H2*G)-w*F-A*F-w*O2))),c[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),c[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,c[2]=g-(D2-_)+(P-_),c[3]=D2;let J=function(t5,e2){let n2=e2[0];for(let r3=1;r3<t5;r3++)n2+=e2[r3];return n2}(4,c),K2=i*h3;if(J>=K2||-J>=K2)return J;if(M2=t4-(E+(_=t4-E))+(_-b5),j2=f2-(G+(_=f2-G))+(_-b5),x2=o3-(H2+(_=o3-H2))+(_-y2),m2=p3-(I+(_=p3-I))+(_-y2),0===M2&&0===x2&&0===j2&&0===m2)return J;if(K2=u2*h3+n*Math.abs(J),(J+=E*m2+I*M2-(H2*j2+G*x2))>=K2||-J>=K2)return J;_=(z=(A=M2-(w=(v2=e*M2)-(v2-M2)))*(O2=I-(F=(v2=e*I)-(v2-I)))-((q=M2*I)-w*F-A*F-w*O2))-(P=z-(C=(A=x2-(w=(v2=e*x2)-(v2-x2)))*(O2=G-(F=(v2=e*G)-(v2-G)))-((B2=x2*G)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const L=r2(4,c,4,l,s);_=(z=(A=E-(w=(v2=e*E)-(v2-E)))*(O2=m2-(F=(v2=e*m2)-(v2-m2)))-((q=E*m2)-w*F-A*F-w*O2))-(P=z-(C=(A=H2-(w=(v2=e*H2)-(v2-H2)))*(O2=j2-(F=(v2=e*j2)-(v2-j2)))-((B2=H2*j2)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const N=r2(L,s,4,l,a2);_=(z=(A=M2-(w=(v2=e*M2)-(v2-M2)))*(O2=m2-(F=(v2=e*m2)-(v2-m2)))-((q=M2*m2)-w*F-A*F-w*O2))-(P=z-(C=(A=x2-(w=(v2=e*x2)-(v2-x2)))*(O2=j2-(F=(v2=e*j2)-(v2-j2)))-((B2=x2*j2)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const Q2=r2(N,a2,4,l,d2);return d2[Q2-1]}(t3,o2,p2,b4,y,h2,m)},t2.orient2dfast=function(t3,e2,n2,r3,o2,f2){return(e2-f2)*(n2-o2)-(t3-o2)*(r3-f2)},Object.defineProperty(t2,"__esModule",{value:!0})}(orient2d_min$1.exports)),orient2d_min$1.exports}const concaveman$1=/* @__PURE__ */getDefaultExportFromCjs(function(){if(hasRequiredConcaveman)return concaveman$2.exports;hasRequiredConcaveman=1;var RBush2=requireRbush_min(),Queue=require$$1,pointInPolygon2=requirePointInPolygon(),orient=requireOrient2d_min().orient2d;function concaveman2(points,concavity,lengthThreshold){concavity=Math.max(0,void 0===concavity?2:concavity),lengthThreshold=lengthThreshold||0;var hull=function(points){for(var left=points[0],top=points[0],right=points[0],bottom=points[0],i=0;i<points.length;i++){var p2=points[i];p2[0]<left[0]&&(left=p2),p2[0]>right[0]&&(right=p2),p2[1]<top[1]&&(top=p2),p2[1]>bottom[1]&&(bottom=p2)}var cull2=[left,top,right,bottom],filtered=cull2.slice();for(i=0;i<points.length;i++)pointInPolygon2(points[i],cull2)||filtered.push(points[i]);return function(points){points.sort(compareByX2);for(var lower=[],i=0;i<points.length;i++){for(;lower.length>=2&&cross2(lower[lower.length-2],lower[lower.length-1],points[i])<=0;)lower.pop();lower.push(points[i])}for(var upper=[],ii2=points.length-1;ii2>=0;ii2--){for(;upper.length>=2&&cross2(upper[upper.length-2],upper[upper.length-1],points[ii2])<=0;)upper.pop();upper.push(points[ii2])}return upper.pop(),lower.pop(),lower.concat(upper)}(filtered)}(points),tree=new RBush2(16);tree.toBBox=function(a3){return{minX:a3[0],minY:a3[1],maxX:a3[0],maxY:a3[1]}},tree.compareMinX=function(a3,b5){return a3[0]-b5[0]},tree.compareMinY=function(a3,b5){return a3[1]-b5[1]},tree.load(points);for(var last,queue=[],i=0;i<hull.length;i++){var p2=hull[i];tree.remove(p2),last=insertNode2(p2,last),queue.push(last)}var segTree=new RBush2(16);for(i=0;i<queue.length;i++)segTree.insert(updateBBox2(queue[i]));for(var sqConcavity=concavity*concavity,sqLenThreshold=lengthThreshold*lengthThreshold;queue.length;){var node=queue.shift(),a2=node.p,b4=node.next.p,sqLen=getSqDist2(a2,b4);if(!(sqLen<sqLenThreshold)){var maxSqLen=sqLen/sqConcavity;(p2=findCandidate2(tree,node.prev.p,a2,b4,node.next.next.p,maxSqLen,segTree))&&Math.min(getSqDist2(p2,a2),getSqDist2(p2,b4))<=maxSqLen&&(queue.push(node),queue.push(insertNode2(p2,node)),tree.remove(p2),segTree.remove(node),segTree.insert(updateBBox2(node)),segTree.insert(updateBBox2(node.next)))}}node=last;var concave=[];do{concave.push(node.p),node=node.next}while(node!==last);return concave.push(node.p),concave}function findCandidate2(tree,a2,b4,c,d2,maxDist,segTree){for(var queue=new Queue([],compareDist2),node=tree.data;node;){for(var i=0;i<node.children.length;i++){var child=node.children[i],dist=node.leaf?sqSegDist2(child,b4,c):sqSegBoxDist2(b4,c,child);dist>maxDist||queue.push({node:child,dist:dist})}for(;queue.length&&!queue.peek().node.children;){var item=queue.pop(),p2=item.node,d0=sqSegDist2(p2,a2,b4),d1=sqSegDist2(p2,c,d2);if(item.dist<d0&&item.dist<d1&&noIntersections2(b4,p2,segTree)&&noIntersections2(c,p2,segTree))return p2}(node=queue.pop())&&(node=node.node)}return null}function compareDist2(a2,b4){return a2.dist-b4.dist}function sqSegBoxDist2(a2,b4,bbox2){if(inside2(a2,bbox2)||inside2(b4,bbox2))return 0;var d1=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.maxX,bbox2.minY);if(0===d1)return 0;var d2=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.minX,bbox2.maxY);if(0===d2)return 0;var d3=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.maxX,bbox2.minY,bbox2.maxX,bbox2.maxY);if(0===d3)return 0;var d4=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.maxY,bbox2.maxX,bbox2.maxY);return 0===d4?0:Math.min(d1,d2,d3,d4)}function inside2(a2,bbox2){return a2[0]>=bbox2.minX&&a2[0]<=bbox2.maxX&&a2[1]>=bbox2.minY&&a2[1]<=bbox2.maxY}function noIntersections2(a2,b4,segTree){for(var minX=Math.min(a2[0],b4[0]),minY=Math.min(a2[1],b4[1]),maxX=Math.max(a2[0],b4[0]),maxY=Math.max(a2[1],b4[1]),edges=segTree.search({minX:minX,minY:minY,maxX:maxX,maxY:maxY}),i=0;i<edges.length;i++)if(intersects2(edges[i].p,edges[i].next.p,a2,b4))return!1;return!0}function cross2(p1,p2,p3){return orient(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1])}function intersects2(p1,q1,p2,q2){return p1!==q2&&q1!==p2&&cross2(p1,q1,p2)>0!=cross2(p1,q1,q2)>0&&cross2(p2,q2,p1)>0!=cross2(p2,q2,q1)>0}function updateBBox2(node){var p1=node.p,p2=node.next.p;return node.minX=Math.min(p1[0],p2[0]),node.minY=Math.min(p1[1],p2[1]),node.maxX=Math.max(p1[0],p2[0]),node.maxY=Math.max(p1[1],p2[1]),node}function insertNode2(p2,prev){var node={p:p2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return prev?(node.next=prev.next,node.prev=prev,prev.next.prev=node,prev.next=node):(node.prev=node,node.next=node),node}function getSqDist2(p1,p2){var dx=p1[0]-p2[0],dy=p1[1]-p2[1];return dx*dx+dy*dy}function sqSegDist2(p2,p1,p22){var x=p1[0],y=p1[1],dx=p22[0]-x,dy=p22[1]-y;if(0!==dx||0!==dy){var t2=((p2[0]-x)*dx+(p2[1]-y)*dy)/(dx*dx+dy*dy);t2>1?(x=p22[0],y=p22[1]):t2>0&&(x+=dx*t2,y+=dy*t2)}return(dx=p2[0]-x)*dx+(dy=p2[1]-y)*dy}function sqSegSegDist2(x0,y0,x1,y1,x2,y2,x3,y3){var sc,sN,tc,tN,ux=x1-x0,uy=y1-y0,vx=x3-x2,vy=y3-y2,wx=x0-x2,wy=y0-y2,a2=ux*ux+uy*uy,b4=ux*vx+uy*vy,c=vx*vx+vy*vy,d2=ux*wx+uy*wy,e=vx*wx+vy*wy,D2=a2*c-b4*b4,sD=D2,tD=D2;0===D2?(sN=0,sD=1,tN=e,tD=c):(tN=a2*e-b4*d2,(sN=b4*e-c*d2)<0?(sN=0,tN=e,tD=c):sN>sD&&(sN=sD,tN=e+b4,tD=c)),tN<0?(tN=0,-d2<0?sN=0:-d2>a2?sN=sD:(sN=-d2,sD=a2)):tN>tD&&(tN=tD,-d2+b4<0?sN=0:-d2+b4>a2?sN=sD:(sN=-d2+b4,sD=a2));var dx=(1-(tc=0===tN?0:tN/tD))*x2+tc*x3-((1-(sc=0===sN?0:sN/sD))*x0+sc*x1),dy=(1-tc)*y2+tc*y3-((1-sc)*y0+sc*y1);return dx*dx+dy*dy}function compareByX2(a2,b4){return a2[0]===b4[0]?a2[1]-b4[1]:a2[0]-b4[0]}return Queue.default&&(Queue=Queue.default),concaveman$2.exports=concaveman2,concaveman$2.exports.default=concaveman2,concaveman$2.exports}());function centroid(geojson,options={}){let xSum=0,ySum=0,len=0;return coordEach(geojson,function(coord){xSum+=coord[0],ySum+=coord[1],len++},!0),point$1([xSum/len,ySum/len],options.properties)}function getCoord(coord){if(!coord)throw new Error("coord is required");if(!Array.isArray(coord)){if("Feature"===coord.type&&null!==coord.geometry&&"Point"===coord.geometry.type)return[...coord.geometry.coordinates];if("Point"===coord.type)return[...coord.coordinates]}if(Array.isArray(coord)&&coord.length>=2&&!Array.isArray(coord[0])&&!Array.isArray(coord[1]))return[...coord];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function calculateRhumbBearing(from,to2){const phi1=degreesToRadians(from[1]),phi2=degreesToRadians(to2[1]);let deltaLambda=degreesToRadians(to2[0]-from[0]);deltaLambda>Math.PI&&(deltaLambda-=2*Math.PI),deltaLambda<-Math.PI&&(deltaLambda+=2*Math.PI);const deltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4));return(radiansToDegrees(Math.atan2(deltaLambda,deltaPsi))+360)%360}function rhumbDistance(from,to2,options={}){const origin=getCoord(from),destination=getCoord(to2);destination[0]+=destination[0]-origin[0]>180?-360:origin[0]-destination[0]>180?360:0;const distanceInMeters=function(origin,destination,radius){const R2=radius=void 0===radius?6371008.8:Number(radius),phi1=origin[1]*Math.PI/180,phi2=destination[1]*Math.PI/180,DeltaPhi=phi2-phi1;let DeltaLambda=Math.abs(destination[0]-origin[0])*Math.PI/180;DeltaLambda>Math.PI&&(DeltaLambda-=2*Math.PI);const DeltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4)),q=Math.abs(DeltaPsi)>1e-11?DeltaPhi/DeltaPsi:Math.cos(phi1),delta2=Math.sqrt(DeltaPhi*DeltaPhi+q*q*DeltaLambda*DeltaLambda);return delta2*R2}(origin,destination);return convertLength(distanceInMeters,"meters",options.units)}function rhumbDestination(origin,distance2,bearing2,options={}){const wasNegativeDistance=distance2<0;let distanceInMeters=convertLength(Math.abs(distance2),options.units,"meters");wasNegativeDistance&&(distanceInMeters=-Math.abs(distanceInMeters));const coords=getCoord(origin),destination=function(origin,distance2,bearing2,radius){radius=void 0===radius?6371008.8:Number(radius);const delta2=distance2/radius,lambda1=origin[0]*Math.PI/180,phi1=degreesToRadians(origin[1]),theta=degreesToRadians(bearing2),DeltaPhi=delta2*Math.cos(theta);let phi2=phi1+DeltaPhi;Math.abs(phi2)>Math.PI/2&&(phi2=phi2>0?Math.PI-phi2:-Math.PI-phi2);const DeltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4)),q=Math.abs(DeltaPsi)>1e-11?DeltaPhi/DeltaPsi:Math.cos(phi1),DeltaLambda=delta2*Math.sin(theta)/q;return[(180*(lambda1+DeltaLambda)/Math.PI+540)%360-180,180*phi2/Math.PI]}(coords,distanceInMeters,bearing2);return destination[0]+=destination[0]-coords[0]>180?-360:coords[0]-destination[0]>180?360:0,point$1(destination,options.properties)}function clone(geojson){if(!geojson)throw new Error("geojson is required");switch(geojson.type){case"Feature":return cloneFeature(geojson);case"FeatureCollection":return function(geojson){const cloned={type:"FeatureCollection"};return Object.keys(geojson).forEach(key=>{switch(key){case"type":case"features":return;default:cloned[key]=geojson[key]}}),cloned.features=geojson.features.map(feature2=>cloneFeature(feature2)),cloned}(geojson);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return cloneGeometry(geojson);default:throw new Error("unknown GeoJSON type")}}function cloneFeature(geojson){const cloned={type:"Feature"};return Object.keys(geojson).forEach(key=>{switch(key){case"type":case"properties":case"geometry":return;default:cloned[key]=geojson[key]}}),cloned.properties=cloneProperties(geojson.properties),null==geojson.geometry?cloned.geometry=null:cloned.geometry=cloneGeometry(geojson.geometry),cloned}function cloneProperties(properties){const cloned={};return properties?(Object.keys(properties).forEach(key=>{const value=properties[key];"object"==typeof value?null===value?cloned[key]=null:Array.isArray(value)?cloned[key]=value.map(item=>item):cloned[key]=cloneProperties(value):cloned[key]=value}),cloned):cloned}function cloneGeometry(geometry){const geom={type:geometry.type};return geometry.bbox&&(geom.bbox=geometry.bbox),"GeometryCollection"===geometry.type?(geom.geometries=geometry.geometries.map(g=>cloneGeometry(g)),geom):(geom.coordinates=deepSlice(geometry.coordinates),geom)}function deepSlice(coords){const cloned=coords;return"object"!=typeof cloned[0]?cloned.slice():cloned.map(coord=>deepSlice(coord))}function transformRotate(geojson,angle,options){if(null===(input=options=options||{})||"object"!=typeof input||Array.isArray(input))throw new Error("options is invalid");var input;const pivot=options.pivot,mutate=options.mutate;if(!geojson)throw new Error("geojson is required");if(null==angle||isNaN(angle))throw new Error("angle is required");if(0===angle)return geojson;const pivotCoord=null!=pivot?pivot:centroid(geojson);return!1!==mutate&&void 0!==mutate||(geojson=clone(geojson)),coordEach(geojson,function(pointCoords){const initialAngle=function(start,end,options={}){let bear360;return bear360=options.final?calculateRhumbBearing(getCoord(end),getCoord(start)):calculateRhumbBearing(getCoord(start),getCoord(end)),bear360>180?-(360-bear360):bear360}(pivotCoord,pointCoords),finalAngle=initialAngle+angle,distance2=rhumbDistance(pivotCoord,pointCoords),newCoords=function(coords){if(Array.isArray(coords))return coords;if("Feature"===coords.type){if(null!==coords.geometry)return coords.geometry.coordinates}else if(coords.coordinates)return coords.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}(rhumbDestination(pivotCoord,distance2,finalAngle));pointCoords[0]=newCoords[0],pointCoords[1]=newCoords[1]}),geojson}function bearing(start,end,options={}){if(!0===options.final)return function(start,end){let bear=bearing(end,start);return bear=(bear+180)%360,bear}(start,end);const coordinates1=getCoord(start),coordinates2=getCoord(end),lon1=degreesToRadians(coordinates1[0]),lon2=degreesToRadians(coordinates2[0]),lat1=degreesToRadians(coordinates1[1]),lat2=degreesToRadians(coordinates2[1]),a2=Math.sin(lon2-lon1)*Math.cos(lat2),b4=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1);return radiansToDegrees(Math.atan2(a2,b4))}function envelope(geojson){return function(bbox2,options={}){const west=Number(bbox2[0]),south=Number(bbox2[1]),east=Number(bbox2[2]),north=Number(bbox2[3]);if(6===bbox2.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");const lowLeft=[west,south];return polygon$2([[lowLeft,[east,south],[east,north],[west,north],lowLeft]],options.properties,{bbox:bbox2,id:options.id})}(function(geojson,options={}){if(null!=geojson.bbox&&!0!==options.recompute)return geojson.bbox;const result=[1/0,1/0,-1/0,-1/0];return coordEach(geojson,coord=>{result[0]>coord[0]&&(result[0]=coord[0]),result[1]>coord[1]&&(result[1]=coord[1]),result[2]<coord[0]&&(result[2]=coord[0]),result[3]<coord[1]&&(result[3]=coord[1])}),result}(geojson))}function area$1(geojson){return geomReduce(geojson,(value,geom)=>value+function(geom){let i,total=0;switch(geom.type){case"Polygon":return polygonArea(geom.coordinates);case"MultiPolygon":for(i=0;i<geom.coordinates.length;i++)total+=polygonArea(geom.coordinates[i]);return total;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}(geom),0)}function polygonArea(coords){let total=0;if(coords&&coords.length>0){total+=Math.abs(ringArea(coords[0]));for(let i=1;i<coords.length;i++)total-=Math.abs(ringArea(coords[i]))}return total}var FACTOR=20294876564838.72,PI_OVER_180=Math.PI/180;function ringArea(coords){const coordsLength=coords.length-1;if(coordsLength<=2)return 0;let total=0,i=0;for(;i<coordsLength;){const lower=coords[i],middle=coords[i+1===coordsLength?0:i+1],upper=coords[i+2>=coordsLength?(i+2)%coordsLength:i+2],lowerX=lower[0]*PI_OVER_180,middleY=middle[1]*PI_OVER_180;total+=(upper[0]*PI_OVER_180-lowerX)*Math.sin(middleY),i++}return total*FACTOR}function smallestSurroundingRectangleByArea(geoJsonInput){const convexHull2=function(geojson,options={}){options.concavity=options.concavity||1/0;const points=[];if(coordEach(geojson,coord=>{points.push([coord[0],coord[1]])}),!points.length)return null;const convexHull2=concaveman$1(points,options.concavity);return convexHull2.length>3?polygon$2([convexHull2]):null}(geoJsonInput);if(!convexHull2)throw new Error("Can't calculate smallestSurroundingRectangleByArea for given geometry");const centroidCoords=centroid(convexHull2),allHullCoords=(coords=[],coordEach(convexHull2,function(coord){coords.push(coord)}),coords);var coords;let minArea=Number.MAX_SAFE_INTEGER,resultPolygon=null;for(let index2=0;index2<allHullCoords.length-1;index2++){let angle=bearing(allHullCoords[index2],allHullCoords[index2+1]),envelopeOfHull=envelope(transformRotate(convexHull2,-1*angle,{pivot:centroidCoords})),envelopeArea=area$1(envelopeOfHull);envelopeArea<minArea&&(minArea=envelopeArea,resultPolygon=transformRotate(envelopeOfHull,angle,{pivot:centroidCoords}))}return resultPolygon}class Polygon extends Array{[Symbol.iterator](){return super[Symbol.iterator]()}constructor(points=[]){Array.isArray(points)?(super(),this.set(points)):super(points)}set(points=[]){this.length=0,points.forEach(p2=>this.push(p2))}getCenter(out=new Point){const len=this.length;if(0===len)return out.set(0,0);let area2=0,centerX=0,centerY=0;for(let i=0;i<len;i++){const p1=this[i],p2=this[(i+1)%len],cross2=p1.x*p2.y-p2.x*p1.y;area2+=cross2,centerX+=(p1.x+p2.x)*cross2,centerY+=(p1.y+p2.y)*cross2}if(area2*=.5,Math.abs(area2)<1e-9){let sumX=0,sumY=0;for(let i=0;i<len;i++)sumX+=this[i].x,sumY+=this[i].y;const inv=1/len;return out.set(sumX*inv,sumY*inv)}const factor=1/(6*area2);return out.set(centerX*factor,centerY*factor)}getBox2(){if(0===this.length)return new Box2;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(const p2 of this)p2.x<minX&&(minX=p2.x),p2.y<minY&&(minY=p2.y),p2.x>maxX&&(maxX=p2.x),p2.y>maxY&&(maxY=p2.y);return new Box2(minX,maxX,minY,maxY)}getMinimumBoundingRectangle(polygon2=new Polygon){if(this.length<3)return null;const result=smallestSurroundingRectangleByArea({type:"Polygon",coordinates:[this.toArrays()]});if(!result)return null;const rectangle=result.geometry.coordinates[0];return polygon2.set(rectangle.map(arr=>Point.from(arr))),polygon2}area(signed=!1){if(this.length<3)return 0;let area2=0;const n=this.length;for(let i=0;i<n;i++){const j=(i+1)%n;area2+=this[i].x*this[j].y,area2-=this[j].x*this[i].y}return signed?area2/2:Math.abs(area2)/2}signedArea(){return this.area(!0)}closedLoop(){if(this.length<2)return!1;const first=this[0],last=this[this.length-1];return first.equal(last)}closedExpansion(width,scale2=100){if(this.length<3)return null;const inv=1/scale2,path=this.clone().scale(scale2).round(),co2=new ClipperLib.ClipperOffset(2,.25*scale2);co2.AddPath(path,ClipperLib.JoinType.jtMiter,ClipperLib.EndType.etClosedPolygon);const solution=[];if(co2.Execute(solution,width*scale2),!solution.length)return null;const result=solution[0].map(p2=>new Point(p2.X*inv,p2.Y*inv));return this.set(result),this}clipByLine(line){if(this.length<3)return[];const intersections=[],lines=this.toLines(!0);for(let i=0;i<lines.length;i++){const p2=lines[i].getIntersection(line);p2&&intersections.push({index:i,point:p2})}if(intersections.length<2)return[this.clone()];intersections.sort((a22,b22)=>a22.index-b22.index);const newPoints=[];for(let i=0;i<this.length;i++){const p2=this[i].clone();newPoints.push(p2),intersections.forEach(inter=>{inter.index===i&&newPoints.push(inter.point.clone())})}const polygon2=new Polygon(newPoints),left=[],right=[],a2=line.start,b4=line.end,side=p2=>(b4.x-a2.x)*(p2.y-a2.y)-(b4.y-a2.y)*(p2.x-a2.x);polygon2.forEach(p2=>{side(p2)>=0&&left.push(p2.clone()),side(p2)<=0&&right.push(p2.clone())});const results=[];return left.length>=3&&results.push(new Polygon(left)),right.length>=3&&results.push(new Polygon(right)),results}getPointSideOfLine(point2){if(this.length<3)return"outside";for(let i=0,j=this.length-1;i<this.length;j=i++){const a2=this[j],b4=this[i],cross2=(b4.x-a2.x)*(point2.y-a2.y)-(b4.y-a2.y)*(point2.x-a2.x);if(Math.abs(cross2)<1e-10){const minX=Math.min(a2.x,b4.x),maxX=Math.max(a2.x,b4.x),minY=Math.min(a2.y,b4.y),maxY=Math.max(a2.y,b4.y);if(point2.x>=minX-1e-10&&point2.x<=maxX+1e-10&&point2.y>=minY-1e-10&&point2.y<=maxY+1e-10)return"on"}}let inside2=!1;for(let i=0,j=this.length-1;i<this.length;j=i++){const xi2=this[i].x,yi2=this[i].y,xj=this[j].x,yj=this[j].y;if(yi2>point2.y!=yj>point2.y){const intersectionX=(xj-xi2)*(point2.y-yi2)/(yj-yi2)+xi2;point2.x<intersectionX&&(inside2=!inside2)}}return inside2?"inside":"outside"}getMaxLengthInfo(){let len=-1/0,start=Point.zero(),end=start;for(let i=0;i<this.length-1;i++){const p1=this[i],p2=this[i+1],l=p1.distance(p2);p1.distance(p2)>len&&(len=l,start=p1,end=p2)}return{start:start,end:end,length:len}}getMinLengthInfo(){let len=1/0,start=Point.zero(),end=start;for(let i=0;i<this.length-1;i++){const p1=this[i],p2=this[i+1],l=p1.distance(p2);p1.distance(p2)<len&&(len=l,start=p1,end=p2)}return{start:start,end:end,length:len}}pointIn(point2){return"outside"!==this.getPointSideOfLine(point2)}pointWithin(point2){let inside2=!1;for(let i=0,j=this.length-1;i<this.length;j=i++){const xi2=this[i].x,yi2=this[i].y,xj=this[j].x,yj=this[j].y;if(yi2>point2.y!=yj>point2.y){const intersectionX=(xj-xi2)*(point2.y-yi2)/(yj-yi2)+xi2;point2.x<intersectionX&&(inside2=!inside2)}}return inside2}scale(scale2=1){return this.forEach(p2=>p2.multiplyScalar(scale2)),this}round(){return this.forEach(p2=>{p2.x=Math.round(p2.x),p2.y=Math.round(p2.y)}),this}union(polygons,scale2=1){return 1===(polygons=Polygon.booleanOp(this,polygons,{scale:scale2,type:"Union"})).length&&(this.set(polygons[0]),!0)}difference(polygons,scale2=1){return 1===(polygons=Polygon.booleanOp(this,polygons,{scale:scale2,type:"Difference"})).length&&(this.set(polygons[0]),!0)}intersectsBox(box){const thisBox=this.getBox2();return!(thisBox.maxX<box.minX||thisBox.minX>box.maxX||thisBox.maxY<box.minY||thisBox.minY>box.maxY)}toLines(closed=!0){const lines=[];for(let i=0;i<this.length&&(closed||i!==this.length-1);i++){const p2=this[i].clone(),nextP=this[(i+1)%this.length].clone();lines.push(new LineSegment(p2,nextP))}return lines.filter(line=>line.length>1e-9)}toRectangle(out=new Rectangle){const polygon2=this.getMinimumBoundingRectangle();if(polygon2)return out.points=[polygon2[0],polygon2[1],polygon2[2],polygon2[3]],out}toArrays(){return this.map(p2=>p2.toArray())}close(){if(this.length<2)return this;const first=this[0],last=this[this.length-1];return first.equal(last)||this.push(first.clone()),this}clone(){return new Polygon([...this].map(p2=>p2.clone()))}static fromByLines(lines){const grid=new PointSpatialHash,points=/* @__PURE__ */new Set;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));const start=lines[0].start;let current=start;for(points.add(lines[0].end),points.add(current);;){const list=grid.queryPoint(current,!0);if(1!==list.length)break;const{point:point2,userData:userData}=list[0];if(current=userData?.getAnotherPoint(point2),points.has(current))break;points.add(current)}return points.add(start.clone()),new Polygon([...points].map(p2=>p2.clone()))}static fromByLines2(lines,skipGroup=!1){if(!lines.length)return new Polygon;if(skipGroup||(lines=LineSegmentUtils.groupByLeafPath(lines).sort((a2,b4)=>b4.length-a2.length)[0]),1===lines.length)return new Polygon(lines[0].points.map(p2=>p2.clone()));const grid=new PointSpatialHash,points=/* @__PURE__ */new Set;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));let start=lines[0].isSameEndpointAsEnd(lines[1])?lines[0].end:lines[0].start,current=start;points.add(lines[0].getAnotherPoint(start)),points.add(current);for(let i=1;i<lines.length;i++){const line=lines[i];line.start.equal(current)?(points.add(line.end),current=line.end):(points.add(line.start),current=line.start)}return new Polygon([...points].map(p2=>p2.clone()))}static multipleFromByLines(lines){return LineSegmentUtils.groupByLeafPath(lines).map(path=>this.fromByLines2(path,!0))}static fromByLinePath(lines,polygon2=new Polygon){if(lines.length<2)polygon2.set(lines[0].points);else{const points=lines.flatMap((line,index2)=>{if(0===index2){const lines2=lines[index2+1];return line.isSameEndpointAsStart(lines2)?[line.end,line.start]:[line.start,line.end]}{const lines2=lines[index2-1];return line.isSameEndpointAsStart(lines2)?[line.end]:[line.start]}});polygon2.set(points)}return polygon2}static ensureCCW(poly){ClipperLib.Clipper.Orientation(poly)||poly.reverse()}static booleanOp(subject,clips,opt){const{type:type="Union",subjectFillType:subjectFillType="NonZero",clipFillType:clipFillType="NonZero",scale:scale2=100}=opt;subject instanceof Polygon&&(subject=[subject]),clips instanceof Polygon&&(clips=[clips]),subject=subject.map(subject2=>subject2.clone().scale(scale2).round()),clips=clips.map(clips2=>clips2.clone().scale(scale2).round());const clipper=new ClipperLib.Clipper;clipper.StrictlySimple=!0,clipper.PreserveCollinear=!0,subject=subject.map(p2=>(p2=ClipperLib.Clipper.CleanPolygon(p2,.5*scale2/100),Polygon.ensureCCW(p2),p2)),clips=clips.map(p2=>(p2=ClipperLib.Clipper.CleanPolygon(p2,.5*scale2/100),Polygon.ensureCCW(p2),p2)),clipper.AddPaths(subject,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clips,ClipperLib.PolyType.ptClip,!0);let solutions=[];clipper.Execute(ClipperLib.ClipType["ct"+type],solutions,ClipperLib.PolyFillType["pft"+subjectFillType],ClipperLib.PolyFillType["pft"+clipFillType]);const inv=1/scale2;return solutions.map(solution=>(solution=solution.map(p2=>new Point(p2.X*inv,p2.Y*inv)),new Polygon(solution))).filter(poly=>Math.abs(poly.area())>.01)}static offset(poly,option){const{offsetHalfWidth:offsetHalfWidth,joinType:joinType="jtMiter",endType:endType="etOpenButt",scale:scale2=1e5}=option??{},offset=new ClipperLib.ClipperOffset(2,.25);let solutions=new ClipperLib.Paths;offset.AddPath(poly.map(p2=>p2.multiplyScalar(scale2)),ClipperLib.JoinType[joinType],ClipperLib.EndType[endType]),offset.Execute(solutions,offsetHalfWidth*scale2);const inv=1/scale2;return poly.map(p2=>p2.multiplyScalar(inv)),solutions.map(solution=>solution.map(p2=>Point.from(p2).multiplyScalar(1/scale2))).map(ps2=>new Polygon(ps2))[0]}}function selectLocalFileFun(){return new Promise(resolve=>{const input=document.createElement("input");input.type="file",input.accept="application/json",input.click(),input.onchange=()=>{input.files?.length?resolve(input.files[0]):resolve(null)}})}const SelectLocalFile=Object.assign(selectLocalFileFun,{arrayBuffer:()=>new Promise(async resolve=>{const file=await selectLocalFileFun();if(file instanceof File){const fileReader=new FileReader;fileReader.onload=()=>{resolve(fileReader.result)},fileReader.readAsArrayBuffer(file)}else resolve(null)}),text:()=>new Promise(async resolve=>{const file=await selectLocalFileFun();if(file instanceof File){const fileReader=new FileReader;fileReader.onload=()=>{resolve(fileReader.result)},fileReader.readAsText(file,"utf-8")}else resolve(null)}),async json(){const text=await this.text();if(text)return JSON.parse(text)}});class CommandFlow extends EventDispatcher{list=[];dataList=[];rollbacklist=[];revokeRollbacklist=[];writeOperationRecord=!0;loop=!1;currentIndex=0;userData={};setLoop(loop){return this.loop=loop,this}add(operation,data){return this.list.push(operation),this.dataList.push(data??{}),this}addRollback(callBack){return this.rollbacklist.push(callBack),this}addRevokeRollback(callBack){return this.revokeRollbacklist.push(callBack),this}getData(index2){return this.dataList[index2]}}class CommandManager extends EventDispatcher{commandFlowMap=/* @__PURE__ */new Map;lock=!1;abortController=null;resolve=null;currentName=null;_disabled=!1;set disabled(disabled){this._disabled=disabled,this._disabled&&this.cancel()}get disabled(){return this._disabled}operationList=[];rollbackList=[];constructor(){super()}addOperation(name,data){const commandFlow=this.getCommandFlow(name);if(!commandFlow)throw new Error(`${name} 命令不存在`);commandFlow.writeOperationRecord&&(this.operationList.push({name:name,data:data}),this.rollbackList.length=0)}addCommandFlow(name,custom){if(this.commandFlowMap.has(name))throw new Error(`${name} 命令已经存在`);const commandFlow=custom?custom():new CommandFlow;return this.commandFlowMap.set(name,commandFlow),commandFlow}getCommandFlow(name){return this.commandFlowMap.get(name)}executionPromise=null;executionResolve=null;async start(name,data=null,step=0){if(this.disabled)throw new Error("命令管理器已禁用,无法启动新的命令流");if(this.dispatchEvent({type:"startedBefore",name:name,currentName:this.currentName}),this.executionPromise&&await this.executionPromise,this.executionPromise=null,this.lock)throw new Error("命令管理器已被 "+this.currentName+" 命令锁定,无法启动新的命令流,请退出或等待命令执行结束");const commandFlow=this.commandFlowMap.get(name);if(!commandFlow)throw new Error(`命令流 ${name} 不存在`);this.lock=!0,this.abortController=new AbortController,this.currentName=name,commandFlow.dispatchEvent({type:"started"}),this.dispatchEvent({type:"started",name:name});try{for(let i=step;i<commandFlow.list.length;i++){const operation=commandFlow.list[i];if(commandFlow.currentIndex=i,commandFlow.dispatchEvent({type:"executing",index:i}),this.dispatchEvent({type:"executing",name:name,index:i}),data=await new Promise(resolve=>{this.resolve=resolve,operation(resolve,data)}),this.abortController.signal.aborted){commandFlow.dispatchEvent({type:"executionInterrupt",index:i}),this.dispatchEvent({type:"executionInterrupt",name:name,index:i}),this.dispatchEvent({type:"cancel",name:name});break}commandFlow.dispatchEvent({type:"executionCompleted",index:i,data:data}),this.dispatchEvent({type:"executionCompleted",name:name,index:i,data:data})}}catch(error){console.error(error)}finally{this.lock=!1,this.currentName=null,commandFlow.currentIndex=0,this.abortController&&!this.abortController.signal.aborted&&(commandFlow.dispatchEvent({type:"completed",data:data}),this.dispatchEvent({type:"completed",name:name,data:data}),commandFlow.writeOperationRecord&&(this.operationList.push({name:name,data:data}),this.rollbackList.length=0),commandFlow.loop&&queueMicrotask(()=>this.start(name))),this.abortController=null,commandFlow.dispatchEvent({type:"finally"}),this.dispatchEvent({type:"finally",name:name}),this.executionResolve&&(this.executionResolve(null),this.executionResolve=null)}return data}cancel(){this.abortController&&(this.abortController.abort(),this.resolve&&this.resolve(),this.executionPromise=new Promise(resolve=>this.executionResolve=resolve))}rollback(){try{const operation=this.operationList.pop();if(!operation)return!1;const commandFlow=this.commandFlowMap.get(operation.name);if(!commandFlow)return!1;const data=commandFlow.rollbacklist.reduce((data2,callBack)=>callBack(data2),operation.data);return this.dispatchEvent({type:"rollback",name:operation.name}),this.rollbackList.push({data:data,name:operation.name}),!0}catch(error){throw new Error(`回滚失败:${error}`)}}revokeRollback(){try{const operation=this.rollbackList.pop();if(!operation)return!1;const commandFlow=this.commandFlowMap.get(operation.name);if(!commandFlow)return!1;const data=commandFlow.revokeRollbacklist.reduce((data2,callBack)=>callBack(data2),operation.data);return this.dispatchEvent({type:"revokeRollback",name:operation.name}),this.operationList.push({name:operation.name,data:data}),!0}catch(error){throw new Error(`撤回回滚失败:${error}`)}}destroy(){this.cancel(),this.addEventListener("cancel",()=>{this.commandFlowMap.clear(),this.lock=!1,this.abortController=null,this.resolve=null,this.executionResolve=null,this.executionPromise=null,this.currentName=null,this.operationList.length=0,this.rollbackList.length=0},{once:!0})}}async function include(path,exportDefault=!0){if("undefined"!=typeof global&&"undefined"!=typeof require)return require(path);{let pack=await import(path);return exportDefault&&(pack=pack.default),pack}}"undefined"!=typeof globalThis&&"undefined"==typeof ProgressEvent&&(globalThis.ProgressEvent=class extends EventTarget{type;lengthComputable;loaded;total;bubbles;cancelable;defaultPrevented;eventPhase;timeStamp;isTrusted;constructor(type,options={}){super(),this.type=type,this.lengthComputable=options.lengthComputable||!1,this.loaded=options.loaded||0,this.total=options.total||0,this.bubbles=!1,this.cancelable=!1,this.defaultPrevented=!1,this.eventPhase=0,this.timeStamp=Date.now(),this.isTrusted=!0}preventDefault(){}stopPropagation(){}stopImmediatePropagation(){}});let promise,gltfLoader=GLTFExporter,gltfExporter=GLTFLoader;function GltfInit(){return promise||(promise=new Promise(async resolve=>{try{const{GLTFLoader:GLTFLoader2}=await("undefined"!=typeof window?import("three/addons/loaders/GLTFLoader.js"):include("node-three-gltf",!1));gltfLoader=GLTFLoader2;const{GLTFExporter:GLTFExporter2}=await("undefined"!=typeof window?import("three/addons/exporters/GLTFExporter.js"):include("node-three-gltf",!1));gltfExporter=GLTFExporter2}catch(error){console.error(error)}resolve(!0)}),promise)}const gltf={get GLTFLoader(){return gltfLoader},get GLTFExporter(){return gltfExporter}};const polygon$1=new Polygon;var Side=/* @__PURE__ */(Side2=>(Side2[Side2.ALL=0]="ALL",Side2[Side2.OUT=1]="OUT",Side2[Side2.IN=2]="IN",Side2))(Side||{});class MiniCircles{debug={angle:!1,edges:!1};scope=1e-4;findCycleEntryEdges(lineUG_){if(!(lineUG_ instanceof LineSegmentUndirectedGraph)){if(!Array.isArray(lineUG_))throw new Error("参数错误");lineUG_=new LineSegmentUndirectedGraph(lineUG_)}const lineUG=lineUG_,unionFind=new UnionFindSet(lineUG.size),ringEdges=[];return lineUG.forEachEdge((n1,n2)=>{const line=lineUG.getLine(n1,n2);unionFind.find(n1)===unionFind.find(n2)?ringEdges.push(line):unionFind.union(n1,n2)}),ringEdges}deduplicate(rings){const map=new ArrayMap,newRings=[];rings.forEach(ring=>map.append(ring.length,ring));for(const rings2 of map.values()){const lineIndexGenerator=new LineIndexGenerator(rings2.flat()),ringMap=new ArrayMap;rings2.map(ring=>{const key=ring.map(line=>lineIndexGenerator.getIndex(line)).sort((a2,b4)=>a2-b4).join(",");ringMap.append(key,ring)}),ringMap.forEach(list=>newRings.push(list[0]))}return newRings}sideTest(circles,side=0){if(circles.length<2||0===side)return circles;const result=[];for(const circle of circles){Polygon.fromByLinePath(circle,polygon$1);const isCCW=polygon$1.signedArea()<0;(2===side&&isCCW||1===side&&!isCCW)&&result.push(circle)}return result}findSameSidePath(opt){let count=0,{A:A,B:B2,exitPoint:exitPoint=A,grid:grid,path:path=/* @__PURE__ */new Set}=opt;if(Array.isArray(grid)){const lines=grid;grid=new PointSpatialHash;for(let i=0;i<lines.length;i++)grid.insert(lines[i].start,lines[i]).insert(lines[i].end,lines[i])}for(;;){if(++count>1e5)return void console.warn("超过最大循环次数");if(exitPoint.equal(B2))return[...path];const candidates=grid.queryCircle(B2,this.scope).filter(item=>item.point!==B2).filter(item=>!path.has(item.userData));if(0===candidates.length)return;const BA=A.directionFrom(B2);let minAngle=1/0,minC=null,mineLie=null;for(let i=0;i<candidates.length;i++){const candidateLine=candidates[i].userData,C=candidateLine.getAnotherPoint(candidates[i].point),BC=C.directionFrom(B2),angle=BA.angle(BC,{unit:"degree",range:"360"});angle<minAngle&&(minAngle=angle,minC=C,mineLie=candidateLine)}if(null==minC)return;A=B2,B2=minC,path.add(mineLie),this.debug.angle&&drawText(minAngle.toFixed(),mineLie?.center)}}miniCircle(lines,option){const{side:side=2,circleEdges:circleEdges=this.findCycleEntryEdges(lines)}=option??{},grid=PointSpatialHash.fromByLines(lines),findSetMap=new ArrayMap,getBaseCircle=line=>{const circles=[];return line.points.forEach(point2=>{const otherPoint=line.getAnotherPoint(point2),set2=/* @__PURE__ */new Set([line]),circle=this.findSameSidePath({grid:grid,B:point2,A:otherPoint,exitPoint:otherPoint,path:set2});findSetMap.append(line,set2),circle&&circles.push(circle)}),this.sideTest(circles,side)},circleList=[];for(let i=0;i<circleEdges.length;i++){const line=circleEdges[i];if(!(line instanceof LineSegment))continue;const circles=getBaseCircle(line);circleList.push(...circles)}return{circles:this.deduplicate(circleList),setMap:findSetMap,circleEdges:circleEdges}}}class MaxiCircles extends MiniCircles{static#instance=null;static get instance(){return this.#instance||(this.#instance=new MaxiCircles),this.#instance}mergeCircles(circles,internalEdges=[]){const visited=/* @__PURE__ */new Map,unionFindSet=new UnionFindSet(circles.length);circles.forEach((circle,index2)=>{for(let i=0;i<circle.length;i++){const line=circle[i];visited.has(line)?unionFindSet.union(index2,visited.get(line)):visited.set(line,index2)}});const countMap=new CounterMap,groups=unionFindSet.getAllSets().valueArray.map(list=>{let group2=list.map(i=>circles[i]);if(1===group2.length)return group2[0];countMap.clear(),group2=this.deduplicate(group2),group2.forEach(lines=>lines.forEach(line=>countMap.increment(line)));return countMap.reduce((lines,count,line)=>(1===count?lines.push(line):internalEdges.push(line),lines),[])});return{internalEdges:internalEdges,circles:groups}}maxiCircles(lines,findMinCirclesFilter=circles=>circles){let removeSet=findDiscretePointLine2(lines,/* @__PURE__ */new Set,!0);lines=lines.filter(line=>!removeSet.has(line));const linesGroup=LineSegmentUtils.groupByPath(lines),circles=[],internalEdges=[];linesGroup.forEach((lines2,_)=>{try{const miniCircles2=this.miniCircle(lines2).circles,findCircles=findMinCirclesFilter(miniCircles2),result=this.mergeCircles(findCircles);circles.push(...result.circles),internalEdges.push(...result.internalEdges)}catch(error){console.warn("环查找出现异常:",error)}});const internalEdgesSet=/* @__PURE__ */new Set([...internalEdges]),groupsSet=/* @__PURE__ */new Set([...circles.flat()]);return(lines=lines.filter(line=>!internalEdgesSet.has(line))).forEach(line=>!groupsSet.has(line)),lines.push(...removeSet),{newLines:lines=[...new Set(lines)],circles:circles,internalEdges:internalEdges}}}const a={c:null,u:[new Vector3,new Vector3,new Vector3],e:[]},b$1={c:null,u:[new Vector3,new Vector3,new Vector3],e:[]},R=[[],[],[]],AbsR=[[],[],[]],t$1=[],xAxis=new Vector3,yAxis=new Vector3,zAxis=new Vector3,v1=new Vector3,size=new Vector3,closestPoint=new Vector3,rotationMatrix=new Matrix3,aabb=new Box3,matrix=new Matrix4,inverse=new Matrix4,localRay=new Ray;let OBB$1=class{constructor(center=new Vector3,halfSize=new Vector3,rotation=new Matrix3){this.center=center,this.halfSize=halfSize,this.rotation=rotation}set(center,halfSize,rotation){return this.center=center,this.halfSize=halfSize,this.rotation=rotation,this}copy(obb2){return this.center.copy(obb2.center),this.halfSize.copy(obb2.halfSize),this.rotation.copy(obb2.rotation),this}clone(){return(new this.constructor).copy(this)}getSize(target){return target.copy(this.halfSize).multiplyScalar(2)}clampPoint(point2,target){const halfSize=this.halfSize;v1.subVectors(point2,this.center),this.rotation.extractBasis(xAxis,yAxis,zAxis),target.copy(this.center);const x=MathUtils.clamp(v1.dot(xAxis),-halfSize.x,halfSize.x);target.add(xAxis.multiplyScalar(x));const y=MathUtils.clamp(v1.dot(yAxis),-halfSize.y,halfSize.y);target.add(yAxis.multiplyScalar(y));const z=MathUtils.clamp(v1.dot(zAxis),-halfSize.z,halfSize.z);return target.add(zAxis.multiplyScalar(z)),target}containsPoint(point2){return v1.subVectors(point2,this.center),this.rotation.extractBasis(xAxis,yAxis,zAxis),Math.abs(v1.dot(xAxis))<=this.halfSize.x&&Math.abs(v1.dot(yAxis))<=this.halfSize.y&&Math.abs(v1.dot(zAxis))<=this.halfSize.z}intersectsBox3(box32){return this.intersectsOBB(obb.fromBox3(box32))}intersectsSphere(sphere){return this.clampPoint(sphere.center,closestPoint),closestPoint.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius}intersectsOBB(obb2,epsilon2=Number.EPSILON){a.c=this.center,a.e[0]=this.halfSize.x,a.e[1]=this.halfSize.y,a.e[2]=this.halfSize.z,this.rotation.extractBasis(a.u[0],a.u[1],a.u[2]),b$1.c=obb2.center,b$1.e[0]=obb2.halfSize.x,b$1.e[1]=obb2.halfSize.y,b$1.e[2]=obb2.halfSize.z,obb2.rotation.extractBasis(b$1.u[0],b$1.u[1],b$1.u[2]);for(let i=0;i<3;i++)for(let j=0;j<3;j++)R[i][j]=a.u[i].dot(b$1.u[j]);v1.subVectors(b$1.c,a.c),t$1[0]=v1.dot(a.u[0]),t$1[1]=v1.dot(a.u[1]),t$1[2]=v1.dot(a.u[2]);for(let i=0;i<3;i++)for(let j=0;j<3;j++)AbsR[i][j]=Math.abs(R[i][j])+epsilon2;let ra2,rb;for(let i=0;i<3;i++)if(ra2=a.e[i],rb=b$1.e[0]*AbsR[i][0]+b$1.e[1]*AbsR[i][1]+b$1.e[2]*AbsR[i][2],Math.abs(t$1[i])>ra2+rb)return!1;for(let i=0;i<3;i++)if(ra2=a.e[0]*AbsR[0][i]+a.e[1]*AbsR[1][i]+a.e[2]*AbsR[2][i],rb=b$1.e[i],Math.abs(t$1[0]*R[0][i]+t$1[1]*R[1][i]+t$1[2]*R[2][i])>ra2+rb)return!1;return ra2=a.e[1]*AbsR[2][0]+a.e[2]*AbsR[1][0],rb=b$1.e[1]*AbsR[0][2]+b$1.e[2]*AbsR[0][1],!(Math.abs(t$1[2]*R[1][0]-t$1[1]*R[2][0])>ra2+rb)&&(ra2=a.e[1]*AbsR[2][1]+a.e[2]*AbsR[1][1],rb=b$1.e[0]*AbsR[0][2]+b$1.e[2]*AbsR[0][0],!(Math.abs(t$1[2]*R[1][1]-t$1[1]*R[2][1])>ra2+rb)&&(ra2=a.e[1]*AbsR[2][2]+a.e[2]*AbsR[1][2],rb=b$1.e[0]*AbsR[0][1]+b$1.e[1]*AbsR[0][0],!(Math.abs(t$1[2]*R[1][2]-t$1[1]*R[2][2])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][0]+a.e[2]*AbsR[0][0],rb=b$1.e[1]*AbsR[1][2]+b$1.e[2]*AbsR[1][1],!(Math.abs(t$1[0]*R[2][0]-t$1[2]*R[0][0])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][1]+a.e[2]*AbsR[0][1],rb=b$1.e[0]*AbsR[1][2]+b$1.e[2]*AbsR[1][0],!(Math.abs(t$1[0]*R[2][1]-t$1[2]*R[0][1])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][2]+a.e[2]*AbsR[0][2],rb=b$1.e[0]*AbsR[1][1]+b$1.e[1]*AbsR[1][0],!(Math.abs(t$1[0]*R[2][2]-t$1[2]*R[0][2])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][0]+a.e[1]*AbsR[0][0],rb=b$1.e[1]*AbsR[2][2]+b$1.e[2]*AbsR[2][1],!(Math.abs(t$1[1]*R[0][0]-t$1[0]*R[1][0])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][1]+a.e[1]*AbsR[0][1],rb=b$1.e[0]*AbsR[2][2]+b$1.e[2]*AbsR[2][0],!(Math.abs(t$1[1]*R[0][1]-t$1[0]*R[1][1])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][2]+a.e[1]*AbsR[0][2],rb=b$1.e[0]*AbsR[2][1]+b$1.e[1]*AbsR[2][0],!(Math.abs(t$1[1]*R[0][2]-t$1[0]*R[1][2])>ra2+rb)))))))))}intersectsPlane(plane){this.rotation.extractBasis(xAxis,yAxis,zAxis);const r2=this.halfSize.x*Math.abs(plane.normal.dot(xAxis))+this.halfSize.y*Math.abs(plane.normal.dot(yAxis))+this.halfSize.z*Math.abs(plane.normal.dot(zAxis)),d2=plane.normal.dot(this.center)-plane.constant;return Math.abs(d2)<=r2}intersectRay(ray,target){return this.getSize(size),aabb.setFromCenterAndSize(v1.set(0,0,0),size),matrix.setFromMatrix3(this.rotation),matrix.setPosition(this.center),inverse.copy(matrix).invert(),localRay.copy(ray).applyMatrix4(inverse),localRay.intersectBox(aabb,target)?target.applyMatrix4(matrix):null}intersectsRay(ray){return null!==this.intersectRay(ray,v1)}fromBox3(box32){return box32.getCenter(this.center),box32.getSize(this.halfSize).multiplyScalar(.5),this.rotation.identity(),this}equals(obb2){return obb2.center.equals(this.center)&&obb2.halfSize.equals(this.halfSize)&&obb2.rotation.equals(this.rotation)}applyMatrix4(matrix2){const e=matrix2.elements;let sx=v1.set(e[0],e[1],e[2]).length();const sy=v1.set(e[4],e[5],e[6]).length(),sz=v1.set(e[8],e[9],e[10]).length();matrix2.determinant()<0&&(sx=-sx),rotationMatrix.setFromMatrix4(matrix2);const invSX=1/sx,invSY=1/sy,invSZ=1/sz;return rotationMatrix.elements[0]*=invSX,rotationMatrix.elements[1]*=invSX,rotationMatrix.elements[2]*=invSX,rotationMatrix.elements[3]*=invSY,rotationMatrix.elements[4]*=invSY,rotationMatrix.elements[5]*=invSY,rotationMatrix.elements[6]*=invSZ,rotationMatrix.elements[7]*=invSZ,rotationMatrix.elements[8]*=invSZ,this.rotation.multiply(rotationMatrix),this.halfSize.x*=sx,this.halfSize.y*=sy,this.halfSize.z*=sz,v1.setFromMatrixPosition(matrix2),this.center.add(v1),this}};const obb=new OBB$1;function distance(p1,p2){const dx=p2[0]-p1[0],dy=p2[1]-p1[1];return Math.sqrt(dx*dx+dy*dy)}class OBB2 extends OBB$1{getBoxMesh(){matrix4.identity(),matrix4.setFromMatrix3(this.rotation),matrix4.decompose(vec3$3,quat,new THREE.Vector3);const size2=this.halfSize.clone().multiplyScalar(2),box=new THREE.Mesh(new THREE.BoxGeometry(size2.x,size2.y,size2.z));return box.position.copy(this.center),box.rotation.setFromQuaternion(quat),box}getBoxEdge(color=16776960){const box=this.getBoxMesh();box3$2.setFromObject(box);const geometry_=new THREE.EdgesGeometry(box.geometry.clone().applyMatrix4(box.matrixWorld));return new THREE.LineSegments(geometry_,new THREE.LineBasicMaterial({color:color,toneMapped:!1}))}toJson(){return matrix4.identity(),matrix4.setFromMatrix3(this.rotation),matrix4.decompose(vec3$3,quat,new THREE.Vector3),{size:this.halfSize.toArray(),center:this.center.toArray(),quaternion:quat.toArray()}}static from(box,position,rotation,out=new OBB2){if(rotation instanceof THREE.Euler)quat.setFromEuler(rotation);else{if(!(rotation instanceof THREE.Quaternion))throw new Error("传入的旋转不是欧拉角或者四元数");quat.copy(rotation)}return matrix4.compose(position,quat,scale),out.center.copy(position),out.halfSize.copy(box.multiplyScalar(.5)),out.rotation.setFromMatrix4(matrix4),out}static fromByPath2D(path,origin,height,out=new OBB2){const result=smallestSurroundingRectangleByArea({type:"Polygon",coordinates:[path.map(p2=>[p2.x,p2.y])]});if(!result)throw new Error("2d obb 获取失败");const rectangle=result.geometry.coordinates[0],width1=distance(rectangle[0],rectangle[1]),width2=distance(rectangle[1],rectangle[2]),angle=Math.atan2(rectangle[1][1]-rectangle[0][1],rectangle[1][0]-rectangle[0][0]);vec3$3.set(width1,width2,height),euler.set(0,0,angle);const[x,y]=function(points){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(const[x,y]of points)x<minX&&(minX=x),x>maxX&&(maxX=x),y<minY&&(minY=y),y>maxY&&(maxY=y);return[.5*(maxX+minX),.5*(maxY+minY)]}(rectangle);return origin.x=x,origin.y=y,out=this.from(vec3$3,origin,euler,out)}}const matrix4=new THREE.Matrix4,quat=new THREE.Quaternion,euler=new THREE.Euler,scale=new THREE.Vector3(1,1,1),vec3$3=new THREE.Vector3,box3$2=new THREE.Box3;var layout=[new Uint8Array([0,0,0]),new Uint8Array([0,0,1]),new Uint8Array([0,1,0]),new Uint8Array([0,1,1]),new Uint8Array([1,0,0]),new Uint8Array([1,0,1]),new Uint8Array([1,1,0]),new Uint8Array([1,1,1])];new Vector3;var c2=new Vector3,Octant=class{min;max;children;data;constructor(min=new Vector3,max=new Vector3){this.min=min,this.max=max,this.children=null,this.data=null}getCenter(result){return result.addVectors(this.min,this.max).multiplyScalar(.5)}getDimensions(result){return result.subVectors(this.max,this.min)}split(){const min=this.min,max=this.max,mid=this.getCenter(c2),children=this.children=[];for(let i=0;i<8;++i){const combination=layout[i],child=new this.constructor;child.min.set(0===combination[0]?min.x:mid.x,0===combination[1]?min.y:mid.y,0===combination[2]?min.z:mid.z),child.max.set(0===combination[0]?mid.x:max.x,0===combination[1]?mid.y:max.y,0===combination[2]?mid.z:max.z),children[i]=child}}};var octantTable=[new Uint8Array([4,2,1]),new Uint8Array([5,3,8]),new Uint8Array([6,8,3]),new Uint8Array([7,8,8]),new Uint8Array([8,6,5]),new Uint8Array([8,7,8]),new Uint8Array([8,8,7]),new Uint8Array([8,8,8])];function findNextOctant(currentOctant,tx1,ty1,tz1){let min,exit;return tx1<ty1?(min=tx1,exit=0):(min=ty1,exit=1),tz1<min&&(exit=2),octantTable[currentOctant][exit]}var v=new Vector3,b=new Box3,d=new Box3,r=new Ray;var flags=new class{value;constructor(){this.value=0}};function raycastOctant(node,tx0,ty0,tz0,tx1,ty1,tz1,result){if(tx1>=0&&ty1>=0&&tz1>=0){const c3=node.children;if(null==c3)result.push(node);else{const txm=.5*(tx0+tx1),tym=.5*(ty0+ty1),tzm=.5*(tz0+tz1),f=flags.value;let currentOctant=function(tx0,ty0,tz0,txm,tym,tzm){let entry=0;return tx0>ty0&&tx0>tz0?(tym<tx0&&(entry|=2),tzm<tx0&&(entry|=1)):ty0>tz0?(txm<ty0&&(entry|=4),tzm<ty0&&(entry|=1)):(txm<tz0&&(entry|=4),tym<tz0&&(entry|=2)),entry}(tx0,ty0,tz0,txm,tym,tzm);for(;currentOctant<8;)switch(currentOctant){case 0:raycastOctant(c3[f],tx0,ty0,tz0,txm,tym,tzm,result),currentOctant=findNextOctant(currentOctant,txm,tym,tzm);break;case 1:raycastOctant(c3[1^f],tx0,ty0,tzm,txm,tym,tz1,result),currentOctant=findNextOctant(currentOctant,txm,tym,tz1);break;case 2:raycastOctant(c3[2^f],tx0,tym,tz0,txm,ty1,tzm,result),currentOctant=findNextOctant(currentOctant,txm,ty1,tzm);break;case 3:raycastOctant(c3[3^f],tx0,tym,tzm,txm,ty1,tz1,result),currentOctant=findNextOctant(currentOctant,txm,ty1,tz1);break;case 4:raycastOctant(c3[4^f],txm,ty0,tz0,tx1,tym,tzm,result),currentOctant=findNextOctant(currentOctant,tx1,tym,tzm);break;case 5:raycastOctant(c3[5^f],txm,ty0,tzm,tx1,tym,tz1,result),currentOctant=findNextOctant(currentOctant,tx1,tym,tz1);break;case 6:raycastOctant(c3[6^f],txm,tym,tz0,tx1,ty1,tzm,result),currentOctant=findNextOctant(currentOctant,tx1,ty1,tzm);break;case 7:raycastOctant(c3[7^f],txm,tym,tzm,tx1,ty1,tz1,result),currentOctant=8}}}}var OctreeRaycaster=class{static intersectOctree(node,ray){const result=[],t2=function(octree,ray,flags2){const min=b.min.set(0,0,0),max=b.max.subVectors(octree.max,octree.min),dimensions=octree.getDimensions(d.min),halfDimensions=d.max.copy(dimensions).multiplyScalar(.5),origin=r.origin.copy(ray.origin),direction=r.direction.copy(ray.direction);origin.sub(octree.getCenter(v)).add(halfDimensions),flags2.value=0,direction.x<0?(origin.x=dimensions.x-origin.x,direction.x=-direction.x,flags2.value|=4):0===direction.x&&(direction.x=Number.EPSILON),direction.y<0?(origin.y=dimensions.y-origin.y,direction.y=-direction.y,flags2.value|=2):0===direction.y&&(direction.y=Number.EPSILON),direction.z<0?(origin.z=dimensions.z-origin.z,direction.z=-direction.z,flags2.value|=1):0===direction.z&&(direction.z=Number.EPSILON);const invDirX=1/direction.x,invDirY=1/direction.y,invDirZ=1/direction.z,tx0=(min.x-origin.x)*invDirX,tx1=(max.x-origin.x)*invDirX,ty0=(min.y-origin.y)*invDirY,ty1=(max.y-origin.y)*invDirY,tz0=(min.z-origin.z)*invDirZ,tz1=(max.z-origin.z)*invDirZ;return Math.max(tx0,ty0,tz0)<Math.min(tx1,ty1,tz1)?[tx0,ty0,tz0,tx1,ty1,tz1]:null}(node,ray,flags);return null!==t2&&raycastOctant(node,t2[0],t2[1],t2[2],t2[3],t2[4],t2[5],result),result}},b2=new Box3,OctreeIterator=class{root;region;result;trace;indices;constructor(root,region=null){this.root=root,this.region=region,this.reset()}reset(){const root=this.root;return this.trace=[],this.indices=[],null!==root&&(b2.min=root.min,b2.max=root.max,(null===this.region||this.region.intersectsBox(b2))&&(this.trace.push(root),this.indices.push(0))),this.result={done:!1},this}next(){const region=this.region,indices=this.indices,trace=this.trace;let octant=null,depth=trace.length-1;for(;null===octant&&depth>=0;){const index2=indices[depth]++,children=trace[depth].children;if(index2<8)if(null!=children){const child=children[index2];if(null!==region&&(b2.min=child.min,b2.max=child.max,!region.intersectsBox(b2)))continue;trace.push(child),indices.push(0),++depth}else octant=trace.pop(),indices.pop();else trace.pop(),indices.pop(),--depth}return this.result.value=octant,this.result.done=null===octant,this.result}[Symbol.iterator](){return this}},b3=new Box3;function getDepth(node){const children=node.children;let result=0;if(null!=children)for(let i=0,l=children.length;i<l;++i){const d2=1+getDepth(children[i]);d2>result&&(result=d2)}return result}function cull(node,region,result){const children=node.children;if(b3.min=node.min,b3.max=node.max,region.intersectsBox(b3))if(null!=children)for(let i=0,l=children.length;i<l;++i)cull(children[i],region,result);else result.push(node)}function findNodesByLevel(node,level,depth,result){const children=node.children;if(depth===level)result.push(node);else if(null!=children){++depth;for(let i=0,l=children.length;i<l;++i)findNodesByLevel(children[i],level,depth,result)}}var Octree=class{root;constructor(root){this.root=root}get min(){return this.root.min}get max(){return this.root.max}get children(){return this.root.children||null}getCenter(result){return this.root.getCenter(result)}getDimensions(result){return this.root.getDimensions(result)}cull(region){const result=[];return cull(this.root,region,result),result}getDepth(){return getDepth(this.root)}findNodesByLevel(level){const result=[];return findNodesByLevel(this.root,level,0,result),result}getIntersectingNodes(raycaster){return OctreeRaycaster.intersectOctree(this.root,raycaster.ray)}leaves(region=null){return new OctreeIterator(this.root,region)}[Symbol.iterator](){return new OctreeIterator(this.root)}},PointContainer=class{data;point;distance;constructor(point2=null,data=null,distance2=0){this.point=point2,this.data=data,this.distance=distance2}},RayPointIntersection=class extends PointContainer{distanceToRay;constructor(distanceToOrigin,distanceToRay,point2,data=null){super(point2,data,distanceToOrigin),this.distanceToRay=distanceToRay}},PointData=class{points;data;constructor(){this.points=[],this.data=[]}testPoints(raycaster,result){const threshold=void 0!==raycaster.params.Points?raycaster.params.Points.threshold:0,thresholdSq=threshold*threshold,ray=raycaster.ray,points=this.points,data=this.data;for(let i=0,l=points.length;i<l;++i){const point2=points[i],distanceToRaySq=ray.distanceSqToPoint(point2);if(distanceToRaySq<thresholdSq){const closestPoint2=ray.closestPointToPoint(point2,new Vector3),distance2=ray.origin.distanceTo(closestPoint2);distance2>=raycaster.near&&distance2<=raycaster.far&&result.push(new RayPointIntersection(distance2,Math.sqrt(distanceToRaySq),closestPoint2,data[i]))}}}},p=new Vector3,PointOctant=class extends Octant{constructor(min,max){super(min,max)}distanceToSquared(point2){return p.copy(point2).clamp(this.min,this.max).sub(point2).lengthSq()}distanceToCenterSquared(point2){const center=this.getCenter(p),dx=point2.x-center.x,dy=point2.y-center.x,dz=point2.z-center.z;return dx*dx+dy*dy+dz*dz}contains(point2,bias){const min=this.min,max=this.max;return point2.x>=min.x-bias&&point2.y>=min.y-bias&&point2.z>=min.z-bias&&point2.x<=max.x+bias&&point2.y<=max.y+bias&&point2.z<=max.z+bias}redistribute(bias){const children=this.children,pointData=this.data;if(null!==children&&null!==pointData){const points=pointData.points,data=pointData.data;for(let i=0,il=points.length;i<il;++i){const point2=points[i],entry=data[i];for(let j=0,jl=children.length;j<jl;++j){const child=children[j];if(child.contains(point2,bias)){null===child.data&&(child.data=new PointData);const childData=child.data;childData.points.push(point2),childData.data.push(entry);break}}}this.data=null}}merge(){const children=this.children;if(null!==children){const pointData=new PointData;for(let i=0,l=children.length;i<l;++i){const childData=children[i].data;null!==childData&&(pointData.points=pointData.points.concat(childData.points),pointData.data=pointData.data.concat(childData.data))}this.children=null,this.data=pointData}}};function countPoints(octant){const children=octant.children;let result=0;if(null!==children)for(let i=0,l=children.length;i<l;++i)result+=countPoints(children[i]);else if(null!==octant.data){result=octant.data.points.length}return result}function set(point2,data,octree,octant,depth){let exists=!1,done=!1;if(null!==octant&&octant.contains(point2,octree.getBias())){let children=octant.children;if(null===children){let index2=0;if(null===octant.data)octant.data=new PointData;else{const points=octant.data.points;for(let i=0,l=points.length;!exists&&i<l;++i)exists=points[i].equals(point2),index2=i}const pointData=octant.data;exists?(pointData.data[index2]=data,done=!0):pointData.points.length<octree.getMaxPoints()||depth===octree.getMaxDepth()?(pointData.points.push(point2.clone()),pointData.data.push(data),done=!0):(octant.split(),octant.redistribute(octree.getBias()),children=octant.children)}if(null!==children){++depth;for(let i=0,l=children.length;!done&&i<l;++i)done=set(point2,data,octree,children[i],depth)}}return done}function remove(point2,octree,octant,parent){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(null!==children)for(let i=0,l=children.length;null===result&&i<l;++i)result=remove(point2,octree,children[i],octant);else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i)if(points[i].equals(point2)){const last=l-1;result=data[i],i<last&&(points[i]=points[last],data[i]=data[last]),points.pop(),data.pop(),null!==parent&&countPoints(parent)<=octree.getMaxPoints()&&parent.merge();break}}return result}function get(point2,octree,octant){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(null!==children)for(let i=0,l=children.length;null===result&&i<l;++i)result=get(point2,octree,children[i]);else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;null===result&&i<l;++i)point2.equals(points[i])&&(result=data[i])}return result}function move(point2,position,octree,octant,parent,depth){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(octant.contains(position,octree.getBias())){if(null!==children){++depth;for(let i=0,l=children.length;null===result&&i<l;++i){result=move(point2,position,octree,children[i],octant,depth)}}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i)if(point2.equals(points[i])){points[i].copy(position),result=data[i];break}}}else result=remove(point2,octree,octant,parent),set(position,result,octree,parent,depth-1);return result}function findNearestPoint(point2,maxDistance,skipSelf,octant){let result=null,bestDistance=maxDistance;if(null!==octant.children){const sortedChildren=octant.children.map(child=>{const octant2=child;return{distance:octant2.distanceToCenterSquared(point2),octant:octant2}}).sort((a2,b4)=>a2.distance-b4.distance);for(let i=0,l=sortedChildren.length;i<l;++i){const child=sortedChildren[i].octant;if(child.contains(point2,bestDistance)){const intermediateResult=findNearestPoint(point2,bestDistance,skipSelf,child);if(null!==intermediateResult&&(bestDistance=intermediateResult.distance,result=intermediateResult,0===bestDistance))break}}}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;let index2=-1;for(let i=0,l=points.length;i<l;++i)if(points[i].equals(point2)){if(!skipSelf){bestDistance=0,index2=i;break}}else{const distance2=point2.distanceTo(points[i]);distance2<bestDistance&&(bestDistance=distance2,index2=i)}index2>=0&&(result=new PointContainer(points[index2],data[index2],bestDistance))}return result}function findPoints(point2,radius,skipSelf,octant,result){const children=octant.children;if(null!==children)for(let i=0,l=children.length;i<l;++i){const child=children[i];child.contains(point2,radius)&&findPoints(point2,radius,skipSelf,child,result)}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i){const p2=points[i];if(p2.equals(point2))skipSelf||result.push(new PointContainer(p2.clone(),data[i],0));else{const rSq=radius*radius,dSq=p2.distanceToSquared(point2);dSq<=rSq&&result.push(new PointContainer(p2.clone(),data[i],Math.sqrt(dSq)))}}}}var PointOctree=class extends Octree{bias;maxPoints;maxDepth;constructor(min,max,bias=0,maxPoints=8,maxDepth=8){super(new PointOctant(min,max)),this.bias=Math.max(0,bias),this.maxPoints=Math.max(1,Math.round(maxPoints)),this.maxDepth=Math.max(0,Math.round(maxDepth))}getBias(){return this.bias}getMaxPoints(){return this.maxPoints}getMaxDepth(){return this.maxDepth}countPoints(octant=this.root){return countPoints(octant)}set(point2,data){return set(point2,data,this,this.root,0)}remove(point2){return remove(point2,this,this.root,null)}get(point2){return get(point2,this,this.root)}move(point2,position){return move(point2,position,this,this.root,null,0)}findNearestPoint(point2,maxDistance=Number.POSITIVE_INFINITY,skipSelf=!1){const result=findNearestPoint(point2,maxDistance,skipSelf,this.root);return null!==result&&null!==result.point&&(result.point=result.point.clone()),result}findPoints(point2,radius,skipSelf=!1){const result=[];return findPoints(point2,radius,skipSelf,this.root,result),result}raycast(raycaster){const result=[],octants=super.getIntersectingNodes(raycaster);if(octants.length>0)for(let i=0,l=octants.length;i<l;++i){const pointData=octants[i].data;null!==pointData&&pointData.testPoints(raycaster,result)}return result}};class PCSparseOctree{octree;bound;constructor(bound){this.octree=new PointOctree(bound.min,bound.max),this.bound=bound}insert(point2,data){this.octree.set(point2,data)}insertBatch(points,datas){if(points.length!==datas.length)throw new Error("Points and datas length mismatch");points.forEach((p2,i)=>{this.octree.set(p2,datas[i]??{})})}findNodeInOBB(queryOBB){const results=[],traverse=node=>{node&&(box3$1.set(node.min,node.max),queryOBB.intersectsBox3(box3$1)&&(node.data&&results.push(node),node.children?.forEach(child=>traverse(child))))};return traverse(this.octree.root),results}findPointsInOBB(queryOBB){const nodeList=this.findNodeInOBB(queryOBB),results=[];return nodeList.forEach(node=>{node.data?.points.forEach((point2,i)=>{queryOBB.containsPoint(point2)&&results.push({point:point2,data:node.data.data[i]})})}),results}findPointsByCircle(position,radius,skipSelf){return this.octree.findPoints(position,radius,skipSelf)}findNearestPoint(position,maxDistance,skipSelf){return this.octree.findNearestPoint(position,maxDistance,skipSelf)}findPointsInOBBBatch(obbList){return obbList.map(obb2=>this.findPointsInOBB(obb2))}static fromPoints(points){box3$1.setFromPoints(points);const octree=new PCSparseOctree(box3$1.clone());return octree.insertBatch(points,points.map((_,index2)=>({index:index2}))),octree}}const box3$1=new THREE.Box3,temp=new Vector3;function rectangleToLine(rectangle){const[l0,l1,l2,l3]=rectangle.toLines();return l0.length<l1.length?new LineSegment(l0.center,l2.center):new LineSegment(l1.center,l3.center)}function toCamelCase(str){return str.replace(/_([a-z])/g,(_,c)=>c.toUpperCase())}class Pipeline extends EventDispatcher{static defaultType="default";map=new ArrayMap;use(handlerOrType,func,tag){const defaultType=this.constructor.defaultType,handler="function"==typeof handlerOrType?{type:defaultType,handle:handlerOrType}:func?{type:handlerOrType,handle:func,tag:tag}:handlerOrType;return(Array.isArray(handler.type)?handler.type:[handler.type]).forEach(type=>this.map.append(type??defaultType,handler)),this}run(type,data,cache2){const ctx={type:type,data:data,cache:cache2??{}},list=this.map.get(type);if(!list)return data;this.dispatchEvent({type:"runStart",data:{type:type,context:ctx}});for(let i=0;i<list.length;i++){const handler=list[i];this.dispatchEvent({type:"handlerStart",data:{index:i,handler:handler,context:ctx}});const result=handler.handle(ctx);if(result instanceof Promise)throw new Error("当前管线存在异步任务,请使用异步执行 runAsync");if(void 0!==result&&(ctx.data=result),this.dispatchEvent({type:"handlerEnd",data:{index:i,handler:handler,context:ctx}}),ctx.stopped){this.dispatchEvent({type:"interrupt",data:{index:i,handler:handler,context:ctx}});break}}return this.dispatchEvent({type:"runEnd",data:{type:type,context:ctx}}),ctx.data}async runAsync(type,data,cache2){const ctx={type:type,data:data,cache:cache2??{}},list=this.map.get(type);if(!list)return data;this.dispatchEvent({type:"runStart",data:{type:type,context:ctx}});for(let i=0;i<list.length;i++){const handler=list[i];this.dispatchEvent({type:"handlerStart",data:{index:i,handler:handler,context:ctx}});const result=await handler.handle(ctx);if(void 0!==result&&(ctx.data=result),this.dispatchEvent({type:"handlerEnd",data:{index:i,handler:handler,context:ctx}}),ctx.stopped){this.dispatchEvent({type:"interrupt",data:{index:i,handler:handler,context:ctx}});break}}return this.dispatchEvent({type:"runEnd",data:{type:type,context:ctx}}),ctx.data}clear(){this.map.clear()}}class Feature{static getData(map){if(map)return map.get(this)?.data}static dependences=[];static run(line,opt,...arg){}static args(...args){const name=this.name,fn2=(...args2)=>this.run.apply(this,args2);return Object.defineProperty(fn2,"name",{value:name,configurable:!0}),Object.assign(fn2,{dependences:this.dependences,args:args,ontology:this})}static match(line,featureMatch,mode="every"){Array.isArray(featureMatch)||(featureMatch=[featureMatch]);let features=featureMatch;const list=features.map(key=>line.features?.get(key)).filter(v2=>!!v2);return"every"===mode&&list.length!==features.length||"some"===mode&&0===list.length?null:list}}class LineFreePoint extends Feature{constructor(mode){super(),this.mode=mode}static dependences=[];static run({start:start,end:end,line2D:line2D},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!start||!end||!line2D)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;let mode="none";1===queryTree.queryPoint(line2D.start,1e-4).length&&(mode="start"),1===queryTree.queryPoint(line2D.end,1e-4).length&&(mode="start"===mode?"all":"end"),"none"!==mode&&add(new LineFreePoint(mode))}}class FreePointRadiusNeighbor extends Feature{map=/* @__PURE__ */new Map;static intersection(m1,m2,radius){const map1=m1.map.get(radius),map2=m2.map.get(radius);if(!map1||!map2)return null;const result=/* @__PURE__ */new Map;for(const[key,value]of map1)map2.has(key)&&result.set(key,value);return result}static containLine(data,radius,line){const map=data.map.get(radius);return!!map&&map.has(line)}static dependences=[LineFreePoint];static run({line2D:line2D,features:features},{globalData:globalData,groupIndex:groupIndex,add:add},radius=.4){if(!line2D)return;const lineFreePointData=LineFreePoint.getData(features);if(!lineFreePointData)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const mode=lineFreePointData.mode,match=[["all","start"],["all","end"]],data=FreePointRadiusNeighbor.getData(features)??new FreePointRadiusNeighbor,map=/* @__PURE__ */new Map;line2D.points.forEach((point2,index2)=>{match[index2].includes(mode)&&queryTree.queryPoint(point2,radius).filter(line=>line!==line2D).forEach(line=>{map.set(line,{line:line,point:point2,isStart:0===index2})})}),map.size&&(data.map.set(radius,map),add(data))}static args(radius){return super.args(radius)}}class VoxelStatistic{voxelSize;voxelMap=new SetMap;lineVoxelSetLists;neighbors;constructor(lines,voxelSize=.083){this.voxelSize=voxelSize,this.lineVoxelSetLists=lines.map((line,i)=>{const setList=/* @__PURE__ */new Set,counterMap=new CounterMap;for(let j=0;j<line.originalPoints.length;j++){const point2=line.originalPoints[j],key=`${Math.floor(point2.x/voxelSize)},${Math.floor(point2.y/voxelSize)},${Math.floor(point2.z/voxelSize)}`;this.voxelMap.append(key,i),counterMap.increment(key,1),setList.add(key)}return[setList,counterMap]}),this.neighbors=Array.from({length:this.lineVoxelSetLists.length},()=>/* @__PURE__ */new Set),this.lineVoxelSetLists.forEach(([setList],i)=>{const result=this.neighbors[i];setList.forEach(key=>{this.voxelMap.get(key).forEach(v2=>result.add(v2))})})}getNeighbors(indices){const result=/* @__PURE__ */new Set;for(const index2 of indices)this.neighbors[index2].forEach(v2=>{result.add(v2)});return indices.forEach(v2=>result.delete(v2)),[...result]}getVoxels(indices,out=new CounterMap){out.clear();for(const index2 of indices){const[setList,counterMap]=this.lineVoxelSetLists[index2];setList.forEach(key=>{const count=counterMap.get(key)??0;out.increment(key,count)})}return out}createPipeline(index2){const indices=[index2],set2=this.getVoxels(indices),out=new CounterMap;return{getIntersectRatio:indices2=>{const list=this.getVoxels(indices2,out),size1=set2.getAllCount(),size2=list.getAllCount(),large=size1<size2?list:set2;let intersect=0;return(size1<size2?set2:list).forEach((count1,key)=>{const count2=large.get(key);count2&&(intersect+=Math.min(count1,count2))}),intersect/Math.max(1,Math.min(size1,size2))},add:indices2=>{this.getVoxels(indices2,out).forEach((count,key)=>{set2.increment(key,count)}),indices.push(...indices2)},getIndices:()=>indices}}}const delta=new Vector3,covMatrix=new Matrix3,vec3$2=new Vector3;class PointCloud3View{constructor(points){this.points=points}set(points){this.points=points}forEach(fun){if(Array.isArray(this.points))this.points.forEach(fun);else{let index2=0;for(let i=0;i<this.points.list.length;i++)for(let j=0;j<this.points.list[i].length;j++){fun(this.points.list[i][j],index2),index2++}}}*[Symbol.iterator](){const traverse=function*(value){if(Array.isArray(value))for(const item of value)yield*traverse(item);else yield value};yield*traverse(this.points)}get length(){if(Array.isArray(this.points))return this.points.length;let count=0;for(let i=0;i<this.points.list.length;i++)count+=this.points.list[i].length;return count}}function pointCloud3FitLine2(points){const pointView=new PointCloud3View(points),centroid2=new Vector3;pointView.forEach(p2=>centroid2.add(p2)),centroid2.divideScalar(pointView.length);let xx=0,xy=0,yy=0;pointView.forEach(p2=>{delta.subVectors(p2,centroid2),xx+=delta.x*delta.x,xy+=delta.x*delta.y,yy+=delta.y*delta.y}),covMatrix.set(xx,xy,0,xy,yy,0,0,0,0);let direction=new Vector3(1,0,0);for(let i=0;i<20;i++){const temp2=direction.clone().applyMatrix3(covMatrix).normalize();if(temp2.distanceToSquared(direction)<1e-10)break;direction=temp2}let minProj=1/0,maxProj=-1/0;pointView.forEach(p2=>{const projection=vec3$2.subVectors(p2,centroid2).dot(direction);projection<minProj&&(minProj=projection),projection>maxProj&&(maxProj=projection)});const start=centroid2.clone().add(direction.clone().multiplyScalar(minProj)),end=centroid2.clone().add(direction.clone().multiplyScalar(maxProj));return{direction:direction,start:start,end:end,get length(){return end.distanceTo(start)}}}class PcLineSegmentEvaluation{distances;dx=0;dy=0;lengthSquared=0;start;end;points;constructor(start,end,points){start&&end&&points&&this.set(start,end,points)}set(start,end,points){const dx=end.x-start.x,dy=end.y-start.y,lengthSquared=dx*dx+dy*dy;this.dx=dx,this.dy=dy,this.lengthSquared=lengthSquared;const distances=[];for(const point2 of points){let t2=((point2.x-start.x)*dx+(point2.y-start.y)*dy)/lengthSquared;t2=Math.max(0,Math.min(1,t2));const nearestX=start.x+t2*dx,nearestY=start.y+t2*dy,errorX=point2.x-nearestX,errorY=point2.y-nearestY;distances.push({t:t2,distance:Math.sqrt(errorX*errorX+errorY*errorY)})}this.distances=distances,this.start=start,this.end=end,this.points=points}rmse(){const dx=this.dx,dy=this.dy;if(0===this.lengthSquared){let squaredError2=0;for(const point2 of this.points){const px=point2.x-this.start.x,py=point2.y-this.start.y;squaredError2+=px*px+py*py}return Math.sqrt(squaredError2/this.points.length)}let squaredError=0,i=0;for(const point2 of this.points){let t2=this.distances[i].t;const nearestX=this.start.x+t2*dx,nearestY=this.start.y+t2*dy,errorX=point2.x-nearestX,errorY=point2.y-nearestY;squaredError+=errorX*errorX+errorY*errorY,i++}const mse=squaredError/this.points.length;return Math.sqrt(mse)}lengthWeightedRmse(binCount=100){const distances=this.distances;if(!distances.length||0===this.lengthSquared)return this.rmse();const sum2=new Float64Array(binCount),count=new Uint32Array(binCount);for(const item of distances){let index2=Math.floor(item.t*binCount);index2>=binCount&&(index2=binCount-1),sum2[index2]+=item.distance*item.distance,count[index2]++}let error=0,validBins=0;for(let i=0;i<binCount;i++)0!==count[i]&&(error+=sum2[i]/count[i],validBins++);return validBins?Math.sqrt(error/validBins):0}medianDistance(){const list=this.distances.map(item=>item.distance).sort((a2,b4)=>a2-b4),n=list.length;if(0===n)return 0;const mid=Math.floor(n/2);return n%2==1?list[mid]:(list[mid-1]+list[mid])/2}spatialOccupancyD2(gridSize){if(gridSize<=0)return 0;const dx=this.end.x-this.start.x,dy=this.end.y-this.start.y,length=Math.hypot(dx,dy);if(0===length||!this.points.length)return 0;const ux=dx/length,uy=dy/length,vx=-uy,vy=ux;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(const point2 of this.points){const x=point2.x*ux+point2.y*uy,y=point2.x*vx+point2.y*vy;x<minX&&(minX=x),x>maxX&&(maxX=x),y<minY&&(minY=y),y>maxY&&(maxY=y)}const width=maxX-minX,height=maxY-minY;if(width<=0||height<=0)return 0;const gridWidth=Math.ceil(width/gridSize),totalGridCount=gridWidth*Math.ceil(height/gridSize),grid=/* @__PURE__ */new Set;for(const point2 of this.points){const x=Math.floor((point2.x*ux+point2.y*uy-minX)/gridSize),y=Math.floor((point2.x*vx+point2.y*vy-minY)/gridSize);grid.add(y*gridWidth+x)}return grid.size/totalGridCount}}const vec3$1=new Vector3,up=new THREE.Vector3(0,0,1),line3=new THREE.Line3;function pointToLineDistanceSqFast(line,point2){line3.set(line.start,line.end);const projected=vec3$1;return line3.closestPointToPoint(point2,!1,projected),point2.distanceToSquared(projected)}const pool=LineSegmentUtils.createPool();class PointCloudLineMerger{constructor(data,opt={}){this.data=data,this.data=data,this.option=opt}averagePz=0;option;cache=/* @__PURE__ */new Map;static mergeLinePoints3d(indices,lines){let count=0;for(let i=0;i<indices.length;i++){count+=lines[indices[i]].originalPoints.length}const originalPoints=new Array(count);let offset=0;for(let i=0;i<indices.length;i++){const p2=lines[indices[i]].originalPoints;for(let j=0;j<p2.length;j++)originalPoints[offset++]=p2[j]}return{originalPoints:originalPoints}}fitLine3D2(points,key){let line=this.cache.get(key);if(!line){const info=pointCloud3FitLine2(points);info.start.z=this.averagePz,info.end.z=this.averagePz,line=Object.assign(info,{finalAvaregN:(new THREE.Vector3).crossVectors(info.direction,up).normalize()}),this.cache.set(key,line)}return line}canMerge(lineA,lineB,ratio){const dot=Math.abs(lineA.direction.dot(lineB.direction)),parallelThreshold=this.option.parallel?.threshold??.98,overlapThreshold=this.option.parallel?.overlapThreshold??1e-4,maxDistance=this.option.parallel?.maxDistance??.03;if(dot>parallelThreshold){if(ratio<overlapThreshold)return!1;const distanceSq=maxDistance*maxDistance;if(pointToLineDistanceSqFast(lineA,lineB.start)<distanceSq||pointToLineDistanceSqFast(lineA,lineB.end)<distanceSq||pointToLineDistanceSqFast(lineB,lineA.start)<distanceSq||pointToLineDistanceSqFast(lineB,lineA.end)<distanceSq)return!0;for(let t2=.3;t2<=.9;t2+=.3){if(pointToLineDistanceSqFast(lineA,(new Vector3).lerpVectors(lineB.start,lineB.end,t2))<distanceSq)return!0}return!1}const line1=pool.line.copy(lineA),line2=pool.line.copy(lineB);if(line1.intersectLineSegment(line2))return ratio>(this.option.intersectOverlap??.5);return ratio>(this.option.directMergeOverlap??.9)}merge(lines){const pcLineSegmentEvaluation=new PcLineSegmentEvaluation;lines.forEach(line=>{const originalPoints=line.originalPoints;let iLine2d=this.fitLine3D2(originalPoints,-1);pcLineSegmentEvaluation.set(iLine2d.start,iLine2d.end,originalPoints);const distances=pcLineSegmentEvaluation.distances.map(item=>item.distance).sort((a2,b4)=>a2-b4),maxDistance=distances[Math.floor(.9*distances.length)];line.originalPoints=originalPoints.filter((_,i)=>pcLineSegmentEvaluation.distances[i].distance<=maxDistance)}),lines.sort((a2,b4)=>b4.originalPoints.length-a2.originalPoints.length);const voxelStatistic=new VoxelStatistic(lines,this.option.voxelSize??.083),merged=/* @__PURE__ */new Set,results=[];for(let i=0;i<lines.length;i++){if(merged.has(i))continue;merged.add(i);const queue=voxelStatistic.getNeighbors([i]);let iLine2d=this.fitLine3D2(lines[i].originalPoints,i);const pipeline=voxelStatistic.createPipeline(i),jump=/* @__PURE__ */new Set;let index2;for(;void 0!==(index2=queue.pop());){if(merged.has(index2)||jump.has(index2))continue;const ratio=pipeline.getIntersectRatio([index2]),jLine2d=this.fitLine3D2(lines[index2].originalPoints,index2);if(this.canMerge(iLine2d,jLine2d,ratio)){merged.add(index2),pipeline.add([index2]);const indices2=pipeline.getIndices();queue.push(...voxelStatistic.getNeighbors([index2]).filter(index22=>!merged.has(index22))),iLine2d=this.fitLine3D2({list:indices2.map(i2=>lines[i2].originalPoints)},indices2.join("-"))}else jump.add(index2)}const indices=pipeline.getIndices();results.push({...PointCloudLineMerger.mergeLinePoints3d(indices,lines),...iLine2d})}return results}}function every(list=[]){return(matchLine1,matchLine2,match1,match2)=>list.every(fun=>fun(matchLine1,matchLine2,match1,match2))}function some(list=[]){return(matchLine1,matchLine2,match1,match2)=>list.some(fun=>fun(matchLine1,matchLine2,match1,match2))}function freePointIncludesNeighbor(line1,line2,_match1,_match2){const m1=FreePointRadiusNeighbor.getData(line1.features),m2=FreePointRadiusNeighbor.getData(line2.features);return!(!m1||!m2)&&(FreePointRadiusNeighbor.containLine(m1,.4,line2.line2D)&&FreePointRadiusNeighbor.containLine(m2,.4,line1.line2D))}function isParallel(l1,l2){return l1.line2D.isParallelTo(l2.line2D,1)}function isOpposition(l1,l2,_match1,_match2){const m1=FreePointRadiusNeighbor.getData(l1.features),m2=FreePointRadiusNeighbor.getData(l2.features);if(!m1||!m2)return!1;const list1=m1.map.get(.4),list2=m2.map.get(.4);if(!list1||!list2)return!1;let point1,point2;for(const[targetLine,opt]of list1)if(targetLine===l2.line2D){point1=opt.point;break}for(const[targetLine,opt]of list2)if(targetLine===l1.line2D){point2=opt.point;break}if(!point1||!point2)return!1;const point12=l1.line2D.getAnotherPoint(point1),point22=l2.line2D.getAnotherPoint(point2),dist1=point1.distanceSquared(point2),dist2=point1.distanceSquared(point22),dist3=point12.distanceSquared(point2),dist4=point12.distanceSquared(point22);let near1,near2;dist1<=dist2&&dist1<=dist3&&dist1<=dist4?(near1=point1,near2=point2):dist2<=dist3&&dist2<=dist4?(near1=point1,near2=point22):dist3<=dist4?(near1=point12,near2=point2):(near1=point12,near2=point22);const dir1=near1===point1?point1.directionFrom(point12):point12.directionFrom(point1),dir2=near2===point2?point2.directionFrom(point22):point22.directionFrom(point2);return dir1.dot(dir2)<-Math.cos(Math.PI/45)}const conditions={isParallel:isParallel,isOpposition:isOpposition,freePointIncludesNeighbor:freePointIncludesNeighbor,every:every,some:some},FeatureMerge=Object.assign(function(feature1,feature2,fun){function handle(data){const unionFindSet=new UnionFindSet(data.length);for(let j=0;j<data.length;j++){const line1=data[j],match1=Feature.match(line1,feature1),match2=Feature.match(line1,feature2);if(match1||match2)for(let k=j+1;k<data.length;k++){const line2=data[k],match3=Feature.match(line2,feature2);if(match1&&match3&&fun(line1,line2,match1,match3)){unionFindSet.union(j,k);continue}const match4=Feature.match(line2,feature1);match4&&match2&&fun(line2,line1,match4,match2)&&unionFindSet.union(j,k)}}return unionFindSet.getAllSets().map(list=>{if(1===list.length)return data[list[0]];const{originalPoints:originalPoints}=PointCloudLineMerger.mergeLinePoints3d(list,data);return{...pointCloud3FitLine2(originalPoints),originalPoints:originalPoints}})}return pipeline=>{pipeline.use({tag:"FeatureMerge",handle:ctx=>{const data=ctx.data;for(let i=0;i<data.length;i++)data[i]=handle(data[i]);return data}})}},{conditions:conditions});function FormatConversion(pipeline){pipeline.use({tag:"FormatConversion",handle:ctx=>ctx.data.map(data=>data.map(lineItems=>{const points=new Array(lineItems.length),originalPoints=new Array(lineItems.length);return lineItems.forEach((item,i)=>{points[i]={...item.p},originalPoints[i]={...item.originalP}}),{points:points,originalPoints:originalPoints}}))})}function Merge(opt){return pipeline=>{pipeline.use({tag:"Merge",handle:ctx=>[new PointCloudLineMerger([],opt).merge(ctx.data.flatMap(list=>list.map(({originalPoints:originalPoints})=>({originalPoints:originalPoints,points:[]}))))]})}}function getValue(data,key){let value=data;for(const name of key.split(".")){if(null==value)return;value=value[name]}return value}function forEachDimension(data,dimension,callback){Array.isArray(data)&&(dimension<0||(1!==dimension?data.forEach(item=>{forEachDimension(item,dimension-1,callback)}):data.forEach(callback)))}function getColor$1(color){return"number"==typeof color?color:color()}function RenderPointCloud({key:key="data",dimension:dimension=2,color:color=()=>randomColor(),pointCloud:pointCloud=!0,line:line=!0,offset:offset=new THREE.Vector3}={}){return pipeline=>{pipeline.use({tag:"RenderPointCloud",handle(ctx){if(!ctx.cache.scene)return;const scene=ctx.cache.scene,data=getValue(ctx,key),group2=new THREE.Group;group2.position.add(offset),scene.add(group2);const linePos=[];if(forEachDimension(data,dimension,pcline=>{const{originalPoints:originalPoints,start:start,end:end,line2D:line2D}=pcline;if(line){(line2D??new LineSegment(start,end)).points.forEach(p2=>linePos.push(p2.x,p2.y,0))}if(!pointCloud)return;const array=originalPoints.flatMap(p2=>[p2.x,p2.y,p2.z]),buffer=new THREE.BufferGeometry;buffer.setAttribute("position",new THREE.BufferAttribute(new Float32Array(array),3));const pointsMesh=new THREE.Points(buffer,new THREE.PointsMaterial({size:2,sizeAttenuation:!1,color:getColor$1(color)}));pointsMesh.position.z=.4,group2.add(pointsMesh)}),linePos.length){const buffer=new THREE.BufferGeometry;buffer.setAttribute("position",new THREE.BufferAttribute(new Float32Array(linePos),3));const line3d=new THREE.LineSegments(buffer,new THREE.LineBasicMaterial({color:16777215}));group2.add(line3d)}}})}}function TimeLog(pipeline){function addLog(...msg){console.log(...msg)}let time=0,runTime=0;pipeline.addEventListener(EventDispatcher.EVENT_TRIGGER,e=>{switch(e.event.type){case"runStart":runTime=performance.now();break;case"runEnd":addLog("总运行时间:",(performance.now()-runTime).toFixed(4),"ms");break;case"handlerStart":time=performance.now(),addLog(`${e.event.data?.handler?.tag??e.event.data.index}. 开始执行...`);break;case"handlerEnd":addLog(`${e.event.data?.handler?.tag??e.event.data.index}. 执行时间:${(performance.now()-time).toFixed(4)}ms`);break;case"interrupt":addLog("已中断")}})}const index$7=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ComputeBox3:function(pipeline){pipeline.use({tag:"ComputeBox3",handle(ctx){const box3s=ctx.cache.box3s??[],point2=new THREE.Vector3;ctx.data.forEach((list,i)=>{const box32=box3s[i]??new THREE.Box3;box32.makeEmpty(),list.forEach(line=>{line.originalPoints.forEach(p2=>{box32.expandByPoint(point2.set(p2.x,p2.y,p2.z))})}),box3s[i]=box32}),ctx.cache.box3s=box3s}})},FeatureExtraction:function(funs){return pipeline=>{pipeline.use({tag:"FeatureExtraction",handle:ctx=>function(lines,data){const list2=data.filterRemoveLine??[],visited=data.Features??/* @__PURE__ */new Set;data.Features=visited,data.filterRemoveLine=list2;for(let i=0;i<funs.length;i++){const fun=funs[i],dependences=fun?.dependences??[];if(0!==dependences.length){const list=dependences.filter(dependence=>!visited.has(dependence));if(0!==list.length)throw new Error(`${fun.name}特性 需要依赖前置特性:${list.map(item=>item.name).join(" | ")}`)}visited.add(fun?.ontology??fun)}lines.forEach((list,groupIndex)=>{list.map((pcLine,index2)=>{const feature2=pcLine.features??/* @__PURE__ */new Map;pcLine.features=feature2,funs.forEach(fun=>{const opt={add(feat){feat instanceof Feature?feature2.set(feat.constructor,{type:feat.constructor,data:feat}):feature2.set(feat.type,feat)},globalData:data,group:list,groupIndex:groupIndex,index:index2};"run"in fun&&"function"==typeof fun.run?fun.run(pcLine,opt):"function"==typeof fun&&fun(pcLine,opt,...fun?.args??[])})})})}(ctx.data,ctx.cache)})}},FeatureFilter:function(filters,removeSaveName="filterRemoveLine",noFeatureResult=!0){return pipeline=>{pipeline.use({tag:"FeatureFilter",handle:ctx=>function(data,cache2){const list2=cache2[removeSaveName]??[];return cache2[removeSaveName]=list2,data.map(list=>list.filter(pcLine=>{if(!pcLine.features)return noFeatureResult;for(let{feature:condition,fun:fun}of filters){const list3=Feature.match(pcLine,condition);if(list3&&!fun(list3,pcLine))return list2.push(pcLine),!1}return!0}))}(ctx.data,ctx.cache)})}},FeatureMerge:FeatureMerge,FeaturePrint:function(pipeline){pipeline.use({tag:"FeaturePrint",handle(ctx){ctx.data.forEach((list,groupIndex)=>list.forEach(({features:features},index2)=>{features&&(console.log(groupIndex,index2),[...features.values()].map(item=>{console.log("string"==typeof item.type?item.type:item.type?.name)}))}))}})},FormatConversion:FormatConversion,Merge:Merge,QueryTree:function(pipeline){pipeline.use({tag:"QueryTree",handle(ctx){ctx.cache.lineQueryTrees=[],ctx.cache.pointQueryTrees=[],ctx.data.forEach(pcLines=>{const tree=new LineSegmentSpatialHash,pointTree=new PointSpatialHash;pcLines.forEach(pcLine=>{const line=new LineSegment(pcLine.start,pcLine.end);tree.insert(line),pointTree.insert(line.start,line).insert(line.end,line),pcLine.line2D=line}),ctx.cache.lineQueryTrees?.push(tree),ctx.cache.pointQueryTrees?.push(pointTree)})}})},RenderPointCloud:RenderPointCloud,Slice:function(start,end){return pipeline=>{pipeline.use({tag:"Slice",handle:ctx=>ctx.data.map(data=>data.splice(start,end))})}},TimeLog:TimeLog,VoxelStatistics:function(voxelSize){return pipeline=>{pipeline.use({tag:"VoxelStatistics",handle(ctx){ctx.cache.voxelStatistics=[],ctx.data.forEach(pcLines=>{ctx.cache.voxelStatistics?.push(new VoxelStatistic(pcLines,voxelSize))})}})}},every:every,forEachDimension:forEachDimension,freePointIncludesNeighbor:freePointIncludesNeighbor,getValue:getValue,isOpposition:isOpposition,isParallel:isParallel,some:some},Symbol.toStringTag,{value:"Module"}));class PointCloudPipeline extends Pipeline{static defaultType="handle";async start(data,cache2){return await this.runAsync(PointCloudPipeline.defaultType,data,cache2)}usePlugin(plugin){return plugin(this),this}static template(){return(new PointCloudPipeline).usePlugin(FormatConversion).usePlugin(TimeLog).usePlugin(Merge({voxelSize:.083,parallel:{threshold:.98,overlapThreshold:1e-4,maxDistance:.02},directMergeOverlap:.8,intersectOverlap:.6})).usePlugin(RenderPointCloud({pointCloud:!0}))}}const queryLine=new LineSegment;class FreePointDirectionNeighbor extends Feature{constructor(list){super(),this.list=list}static run({line2D:line2D,features:features},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!line2D)return;const feature2=LineFreePoint.getData(features);if(!feature2)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const mode=feature2.mode,match=[["all","start"],["all","end"]],list=[];line2D.points.forEach((point2,index2)=>{if(!match[index2].includes(mode))return;const other=line2D.getAnotherPoint(point2),direct=point2.directionFrom(other);point2.expandAsLine(direct,.2,void 0,queryLine),queryTree.queryLine(queryLine).filter(line=>line!==line2D).forEach(line=>{const intersectPoint=line2D.getIntersection(line);intersectPoint&&list.push({intersectPoint:intersectPoint,line:line,angle:line.angle(line2D,{unit:"degree",range:"180"}),distanceSq:intersectPoint.distanceSquared(point2),point:point2,isStart:0===index2})})}),list.length&&(list.sort((a2,b4)=>a2.distanceSq-b4.distanceSq),add(new FreePointDirectionNeighbor(list)))}}class IntersectionPoint extends Feature{constructor(list){super(),this.list=list}static run({start:start,end:end,line2D:line2D},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!start||!end||!line2D)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const list=queryTree.queryLine(line2D).filter(line=>line!==line2D).map(line=>{const intersectPoint=line.getIntersection(line2D);if(intersectPoint)return{line:line,intersectPoint:intersectPoint}}).filter(r2=>!!r2);list.length&&add(new IntersectionPoint(list))}}class IsolateLine extends Feature{static dependences=[LineFreePoint,IntersectionPoint];static run({features:features},{add:add}){const freePointData=LineFreePoint.getData(features);if(!freePointData)return;if("all"!==freePointData.mode)return;IntersectionPoint.getData(features)||add(new IsolateLine)}}class NearestEndpointIntersection extends Feature{constructor(start,end){super(),this.start=start,this.end=end}static run({features:features,line2D:line2D},{add:add}){if(!line2D)return;const feature2=IntersectionPoint.getData(features);if(!feature2)return;const ppv=feature2.list.map(({intersectPoint:intersectPoint})=>line2D.projectPointValue(intersectPoint)).sort((a2,b4)=>a2-b4);add(new NearestEndpointIntersection(ppv[0],ppv[ppv.length-1]))}}class PhagocyticRate extends Feature{constructor(value){super(),this.value=value}static dependences=[];static run({},{globalData:globalData,groupIndex:groupIndex,index:index2,add:add}){const voxelStatistic=globalData.voxelStatistics?.[groupIndex];if(!voxelStatistic)return;const neighbors=voxelStatistic.getNeighbors([index2]),ratio=voxelStatistic.createPipeline(index2).getIntersectRatio(neighbors);add(new PhagocyticRate(ratio))}}const vec3=new Vector3;class PointCloudLineBox3 extends Feature{constructor(box32,size2){super(),this.box3=box32,this.size=size2}static run({originalPoints:originalPoints},{add:add}){if(!originalPoints.length)return;const box32=new Box3;for(const point2 of originalPoints)box32.expandByPoint(vec3.set(point2.x,point2.y,point2.z));add(new PointCloudLineBox3(box32,box32.getSize(new Vector3)))}}class PointCloudsCount extends Feature{constructor(count){super(),this.count=count}static run(line,{add:add}){add(new PointCloudsCount(line.originalPoints.length))}}class PointCloudsLineLength extends Feature{constructor(length){super(),this.length=length}static run(line,{add:add}){add(new PointCloudsLineLength(line.start.distanceTo(line.end)))}}class PointCloudsMSE extends Feature{constructor(value){super(),this.value=value}static run({start:start,end:end,originalPoints:originalPoints},{add:add}){if(!start||!end)return;const mse=new PcLineSegmentEvaluation(start,end,originalPoints).rmse();add(new PointCloudsMSE(mse))}}const index$5={PointCloudLineBox3:PointCloudLineBox3,PointCloudsCount:PointCloudsCount,PointCloudsLineLength:PointCloudsLineLength,PointCloudsMSE:PointCloudsMSE,IntersectionPoint:IntersectionPoint,LineFreePoint:LineFreePoint,FreePointDirectionNeighbor:FreePointDirectionNeighbor,FreePointRadiusNeighbor:FreePointRadiusNeighbor,NearestEndpointIntersection:NearestEndpointIntersection,IsolateLine:IsolateLine,PhagocyticRate:PhagocyticRate},index$6=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:index$5},Symbol.toStringTag,{value:"Module"})),index$4=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,PointCloudPipeline:PointCloudPipeline,features:index$6,plugins:index$7},Symbol.toStringTag,{value:"Module"})),load=lazy(()=>init$1());async function dxfToDwgByBlob(blob){await load.value;const data=await dxf_to_dwg(new Uint8Array(await blob.arrayBuffer()));return new Blob([new Uint8Array(data)])}const index$3=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ArrayMap:ArrayMap,Box2:Box2,CheckPointCloudContinuity:class{static continuity(ts2,len,gridSize=.02,ratio=.6){if(ts2.length<2)return!1;const voxels=/* @__PURE__ */new Set;let min=1/0,max=-1/0;for(let i2=0;i2<ts2.length;i2++){const dist=ts2[i2]*len,voxel=Math.floor(dist/gridSize);voxels.add(voxel),min=Math.min(min,voxel),max=Math.max(max,voxel)}const values=[...voxels].sort((a2,b4)=>a2-b4);let start=values[0],i=0;const ranges=[];for(i=1;i<values.length;i++){const pre=values[i-1],v2=values[i];v2-pre>2&&(ranges.push([start,pre]),start=v2)}ranges.push([start,values[values.length-1]]);return!(ranges.reduce((sum2,[start2,end])=>sum2+(end-start2+1),0)/(max-min+1)<ratio)}static checkByProjectionContinuity(points,opt){let{ratio:ratio=.6,gridSize:gridSize=.02,axisLine:axisLine}=opt??{};if(axisLine)axisLine instanceof LineSegment||(axisLine=new LineSegment(Point.from(axisLine.start),Point.from(axisLine.end)));else{axisLine=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}const xline=axisLine,start=new Vector3,end=new Vector3;start.set(xline.start.x,xline.start.y,0),end.set(xline.end.x,xline.end.y,0);const xts=this.projectPoint(points,start,end);if(!this.continuity(xts,xline.length,gridSize,ratio))return!1;const yline2=xline.clone().rotate(.5*Math.PI);start.set(yline2.start.x,yline2.start.y,0),end.set(yline2.end.x,yline2.end.y,0);const yts=this.projectPoint(points,start,end);if(!this.continuity(yts,yline2.length,gridSize,ratio))return!1;const center=xline.center.clone();start.set(center.x,center.y,10),end.set(center.x,center.y,-10);const zts=this.projectPoint(points,start,end);return!!this.continuity(zts,20,gridSize,ratio)}static checkByVoxelDensity(points,opt){let{gridSize:gridSize=.08,xRatio:xRatio=.5,yRatio:yRatio=.4,overallRatio:overallRatio=.5,axisLine:axisLine}=opt??{};if(axisLine)axisLine instanceof LineSegment||(axisLine=new LineSegment(Point.from(axisLine.start),Point.from(axisLine.end)));else{axisLine=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}let xline=axisLine;if(!xline){xline=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}const dir=xline.direction(),angle=Math.atan2(dir.y,dir.x),center=xline.center,cos=Math.cos(-angle),sin=Math.sin(-angle),voxelizationPoints=[],xMap=new CounterMap,yMap=new CounterMap,occupied=/* @__PURE__ */new Set;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;points.forEach(p2=>{const dx=p2.x-center.x,dy=p2.y-center.y,x=Math.floor((dx*cos-dy*sin)/gridSize),y=Math.floor(p2.z/gridSize),key=BigInt(x)<<32n|0xffffffffn&BigInt(y);occupied.has(key)||(occupied.add(key),xMap.increment(x,1),yMap.increment(y,1),voxelizationPoints.push(x,y),minX=Math.min(minX,x),minY=Math.min(minY,y),maxX=Math.max(maxX,x),maxY=Math.max(maxY,y))});const xRange=maxX-minX+1,yRange=maxY-minY+1;let satisfyQuantity=0;for(let i=0;i<voxelizationPoints.length;i+=2){const x=voxelizationPoints[i],y=voxelizationPoints[i+1],xCount=xMap.get(x),yCount=yMap.get(y);xCount/yRange>xRatio&&yCount/xRange>yRatio&&satisfyQuantity++}return satisfyQuantity/(voxelizationPoints.length/2)>overallRatio}static projectPoint(points,start,end){const point2=new Vector3,dir=end.clone().sub(start);return points.map(p2=>(point2.copy(p2),function(point2,start,_end,dir){const len2=dir.lengthSq();if(len2<1e-12)return 0;temp.copy(point2);let t2=temp.sub(start).dot(dir)/len2;return t2=Math.max(0,Math.min(1,t2)),t2}(point2,start,0,dir)))}},CommandFlow:CommandFlow,CommandManager:CommandManager,Component:Component,ComponentContainer:ComponentContainer,CounterMap:CounterMap,EventDispatcher:EventDispatcher,GltfInit:GltfInit,LineDashed:LineDashed,LineIndexGenerator:LineIndexGenerator,LineSegment:LineSegment,LineSegmentUndirectedGraph:LineSegmentUndirectedGraph,LineSegmentUtils:LineSegmentUtils,Lines:Lines,MapEnhance:MapEnhance,MaxiCircles:MaxiCircles,MiniCircles:MiniCircles,OBB:OBB2,PCSparseOctree:PCSparseOctree,PcLineSegmentEvaluation:PcLineSegmentEvaluation,Point:Point,PointSpatialHash:PointSpatialHash,PointUtils:PointUtils,Polygon:Polygon,Quadtree:Quadtree,Rectangle:Rectangle,SelectLocalFile:SelectLocalFile,SetMap:SetMap,Side:Side,SnapLine:class{nearestPointCluster(lineDatas,referenceLineData){const referenceLines=[],referenceLinesScope=[];for(let i=0;i<referenceLineData.length;i++){const item=referenceLineData[i],points=item.originalPoints.map(p2=>Point.from(p2)),rectangle=new Polygon(points).toRectangle(),line=new LineSegment(Point.from(item.start),Point.from(item.end));referenceLines.push(line),referenceLinesScope.push(rectangle)}const lines=[],linesScope=[];for(let i=0;i<lineDatas.length;i++){const element=lineDatas[i],points=element.originalPoints.map(item=>Point.from(item)),rectangle=new Polygon(points).toRectangle(),line=new LineSegment(Point.from(element.start),Point.from(element.end));lines.push(line),linesScope.push(rectangle)}const results=LineSegmentUtils.findBestReferenceSegment({lines:lines,linesScope:linesScope,referenceLines:referenceLines,referenceLinesScope:referenceLinesScope});for(let i=0;i<results.length;i++){const result=results[i];result&&(lineDatas[i].start=result.start.toJson2D(),lineDatas[i].end=result.end.toJson2D())}return lineDatas}},UndirectedGraph:UndirectedGraph,UnionFindSet:UnionFindSet,cloneUserData:cloneUserData,dxfToDwgByBlob:dxfToDwgByBlob,gltf:gltf,pointCloundPipeline:index$4,toCamelCase:toCamelCase,uuid:uuid},Symbol.toStringTag,{value:"Module"}));class LineGroupType{static get(line){const group2=[];return void 0!==line.userData.groupId&&group2.push({id:line.userData.groupId,type:line.userData.groupType}),line.userData?.groups?.forEach(item=>group2.push({id:item.id,type:item.type})),group2}static set(line,id,type,repeat=!1){if(!(this.hasId(line,id)||!repeat&&this.hasType(line,type))){if(void 0===line.userData.groupId)return line.userData.groupId=id,void(line.userData.groupType=type);void 0===line.userData.groups&&(line.userData.groups=[]),line.userData?.groups?.push({id:id,type:type})}}static getIdByType(line,type){return line.userData.groupType==type?line.userData.groupId:line.userData?.groups?.find(item=>item.type===type)?.id}static getIdsByType(line,type){const ids=[];return line.userData.groupType==type&&ids.push(line.userData.groupId),line.userData?.groups?.forEach(group2=>{group2.type===type&&ids.push(group2.id)}),ids}static getGroupsByType(lines,type,remainingLines=[]){const list=lines.reduce((map,line)=>{const ids=LineGroupType.getIdsByType(line,type);return ids&&ids.length?ids.forEach(id=>map.append(id,line)):remainingLines.push(line),map},new ArrayMap).valueArray;return Object.defineProperty(list,"remainingLines",{value:remainingLines}),list}static getGroupById(lines,id){return lines.filter(line=>this.hasId(line,id))}static replace(line,id,type){if(line.userData.groupId===id)return line.userData.groupType=type,!0;if(line.userData.groupType===type)return line.userData.groupId=id,!0;if(line.userData.groups)for(let i=0;i<line.userData.groups.length;i++){const group2=line.userData.groups[i];if(group2.id===id)return group2.type=type,!0;if(group2.type===type)return group2.id=id,!0}return!1}static hasGroup(line){return!(void 0===line.userData.groupId&&!line.userData.groups?.length)}static hasId(line,id){return void 0!==line.userData.groupId&&line.userData.groupId===id||line.userData?.groups?.some(item=>item.id===id)}static hasType(line,type){return void 0!==line.userData.groupType&&line.userData.groupType===type||!!line.userData?.groups?.some(item=>item.type===type)}static hasTypes(line,types){return types.every(type=>this.hasType(line,type))}static everyType(lines,type){return!(!lines||0===lines.length)&&lines.every(line=>this.hasType(line,type))}static getIntersectionTypes(lines){const countMap=new CounterMap;lines.forEach(line=>{line.userData.groups&&line.userData.groups.forEach(group2=>countMap.set(group2.type)),line.userData.groupType&&countMap.increment(line.userData.groupType)});const types=[];return countMap.forEach((v2,k)=>{v2===lines.length&&types.push(k)}),types}static getUnionTypes(lines){const typeSet=/* @__PURE__ */new Set;return lines.forEach(line=>{line.userData.groups&&line.userData.groups.forEach(group2=>typeSet.add(group2.type)),line.userData.groupType&&typeSet.add(line.userData.groupType)}),Array.from(typeSet)}static isGroup(lines){return 0!==this.getIntersectionTypes(lines).length}static remove(line,id){if(void 0!==line.userData.groupType&&line.userData.groupId===id)return delete line.userData.groupId,delete line.userData.groupType,!0;if(line.userData?.groups)for(let i=0;i<line.userData.groups.length;i++){if(line.userData.groups[i].id===id)return line.userData.groups.splice(i,1),!0}return!1}static removeByType(line,type){let is2=!1;line.userData?.groupType===type&&(delete line.userData.groupId,delete line.userData.groupType,is2=!0);const groups=line.userData?.groups;if(groups)for(let i=groups.length-1;i>=0;i--){groups[i].type===type&&(groups.splice(i,1),is2=!0)}return is2}static removeByTypes(line,types){if(!line.userData)return;const typeSet=new Set(types);line.userData.groupType&&typeSet.has(line.userData.groupType)&&(delete line.userData.groupType,delete line.userData.groupId);const groups=line.userData.groups;Array.isArray(groups)&&groups.length>0&&(line.userData.groups=groups.filter(element=>!element?.type||!typeSet.has(element.type)))}static clear(line){delete line.userData.groupId,delete line.userData.groupType,delete line.userData.groups}}class WallHole{static mountedObjectType=[];lines;constructor(lines){this.lines=lines}static isHoleData(hole){return hole&&"p"in hole&&"x"in hole.p&&"y"in hole.p&&"width"in hole}static isHole(line){return line.userData.isWindow||line.userData.isPassageEntrance}isHole(line){return WallHole.isHole(line)}static isDoor(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>"door"===hole.type)}static isDoubleDoor(line){if(line.userData.isPassageEntrance&&line.userData.passageEntrance?.length){return line.userData.passageEntrance.some(item=>"door"===item.type&&"number"==typeof this.getNearId(item))}return!1}static isBeam(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>"beam"===hole.type)}static isPass(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>void 0===hole.type)}static isDouble(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance.some(item=>{const nearId=this.getNearId(item),id=this.getId(item);return"number"==typeof nearId&&"number"==typeof id&&id!==nearId})}static isPairing(lines){const set2=/* @__PURE__ */new Set;for(let i=0;i<lines.length;i++){const passageEntrance=lines[i].userData.passageEntrance??[];for(let i2=0;i2<passageEntrance.length;i2++){const item=passageEntrance[i2],id=this.getId(item),nearId=this.getNearId(item);if("number"==typeof item.nearId&&"number"==typeof id){if(set2.has(nearId))return!0;set2.add(id)}}}}static cancelPairing(line,line2){const map=/* @__PURE__ */new Map,lines=[line,line2];for(let i=0;i<lines.length;i++){const line32=lines[i];for(const data of this.getIterator(line32)){const id=this.getId(data),nearId=this.getNearId(data);if("number"!=typeof nearId||"number"!=typeof id)continue;const nearData=map.get(nearId);nearData?data.nearDoorId=data.nearId=nearData.nearDoorId=nearData.doorId=-1:map.set(id,data)}}}static getId(item){return item.id??item.doorId}static getNearId(item){let nearId=item.nearId??item.nearDoorId;return-1===nearId&&(nearId=void 0),nearId}static buildPairing(lineSegments){const map=new ArrayMap,originMap=/* @__PURE__ */new Map;WallHole.merge(lineSegments),lineSegments.forEach(line=>{for(const holeData of WallHole.getIterator(line)){const holeLine=WallHole.holeDataToLine(line,holeData);holeData.type=holeData.type??"passageEntrance",map.append(holeData.type,holeLine),originMap.set(holeLine,line)}});let idIndex=0;return{matchQueues:map.map(holeLines=>{const lsh=LineSegmentSpatialHash.from(holeLines),unionFindSet=new UnionFindSet(holeLines.length),lineIndexGenerator=new LineIndexGenerator(holeLines);for(const holeLine of holeLines){const rectangle=holeLine.toRectangle(.8,"butt");let list=lsh.queryRectangle(rectangle).filter(rline=>rline!==holeLine&&rline.isParallelTo(holeLine,10)&&!rline.isSameEndpoint(holeLine,1e-4)).filter(rline=>{const line=holeLine.projectLineSegment(rline);return!(line.length<1e-5)&&(line.length/holeLine.length>.1||line.length/rline.length>.1)});if(list.length){if(list.length>1){const dist=list.map(line=>({line:line,dist:line.distanceToSegment(holeLine)}));dist.sort((a2,b4)=>a2.dist-b4.dist),list=dist.map(d2=>d2.line)}unionFindSet.union(lineIndexGenerator.getIndex(holeLine),lineIndexGenerator.getIndex(list[0]))}}const matchQueue=[];return unionFindSet.getAllSets().forEach(list=>{2===list.length&&matchQueue.push(list.map(i=>lineIndexGenerator.getLine(i)))}),matchQueue.forEach(([holeLine1,holeLine2])=>{const id1=idIndex++,id2=idIndex++;holeLine1.userData.id=id1,holeLine1.userData.nearId=id2,holeLine2.userData.id=id2,holeLine2.userData.nearId=id1}),matchQueue}),originMap:originMap}}static holeDataToLine(line,hole,projClip=!0,snap=!0){const holeLine=(()=>{if(hole.full)return(new LineSegment).set(line.start,line.end);const center=PointUtils.globalPoint.copy(hole.p),direct=line.direction(),width=hole.width??0;return center.expandAsLine(direct,width).translate(.5*-width,direct)})();if(projClip&&line.projectLineSegment(holeLine,holeLine),("beam"===hole.type||"passageEntrance"===hole.type)&&snap){let eps="passageEntrance"===hole.type?.02:.2;line.start.distance(holeLine.start)<eps&&holeLine.start.copy(line.start),line.end.distance(holeLine.end)<eps&&holeLine.end.copy(line.end)}return holeLine.userData=hole,holeLine.currentData.wallLine=line,holeLine.currentData.wallWidth=line.userData.wallWidth,holeLine}static getDoubleGroup(lines){const otherLines=[],doorMap=/* @__PURE__ */new Map,lineMap=/* @__PURE__ */new Map;lines.flatMap(line=>{if(!WallHole.isDouble(line))return otherLines.push(line),[];WallHole.forEachStorageType(line,(data,k)=>{"passageEntrance"===k&&data.forEach(v2=>{const id=WallHole.getId(v2),peLine=WallHole.holeDataToLine(line,v2);peLine.currentData.line=line,peLine.currentData.type=v2.type,peLine.currentData.ket=k,doorMap.set(id,{line:peLine,nearId:WallHole.getNearId(v2)}),lineMap.set(id,line)})})});const visited=/* @__PURE__ */new Set,results=[];for(const[id,{line:line,nearId:nearId}]of doorMap){if(visited.has(id))continue;const near=doorMap.get(nearId);if(!near)continue;const d1=line.direction(),d2=near.line.direction();d1.dot(d2)<0&&near.line.swap(),results.push([line,near.line]),visited.add(id),visited.add(nearId)}return{results:results,otherLines:otherLines}}static*getIterator(line){line.userData?.drawWindow?.forEach(item=>item.type="window"),yield*line.userData?.drawWindow??[],yield*line.userData?.passageEntrance??[]}static*getStorageDataIterator(line){yield line.userData?.drawWindow??[],yield line.userData?.passageEntrance??[]}static forEachStorageType(line,callBack){line.userData.isWindow&&(line.userData.drawWindow?.forEach(item=>item.type="window"),callBack(line.userData.drawWindow??[],"drawWindow")),line.userData.isPassageEntrance&&callBack(line.userData.passageEntrance??[],"passageEntrance")}static getMinWidth(key,type){if("drawWindow"===key)return.3;if("passageEntrance"===key){if("door"===type)return.35;if("passageEntrance"===type)return.2;if("beam"===type)return.2}return.05}static clear(target,key){if(void 0===key)return this.clear(target,"drawWindow"),void this.clear(target,"passageEntrance");const eabledKey="drawWindow"===key?"isWindow":"isPassageEntrance",key_="drawWindow"===key?"drawWindow":"passageEntrance";target.userData[eabledKey]=!1,delete target.userData[key_]}static miniWidthFilter(line){return Array.isArray(line)?(line.forEach(line2=>this.miniWidthFilter(line2)),this):(this.forEachStorageType(line,(data,key)=>{line.userData[key]=data.filter(w=>w.width>WallHole.getMinWidth(key,w.type)),0===line.userData[key].length&&WallHole.clear(line,key)}),this)}static filterIllegal(line){return Array.isArray(line)?(line.forEach(line2=>this.filterIllegal(line2)),this):(this.forEachStorageType(line,(data,key)=>{data.forEach(w=>{w.type||"drawWindow"!==key||(w.type="window"),w.uuid||(w.uuid=uuid());try{const center=Point.from(w.p),windowLine=line.projectLineSegment(this.holeDataToLine(line,w));if("beam"===w.type)return w.p=windowLine.center.toJson(w.p.z),void(w.width=windowLine.length);if(windowLine.length/w.width<.4&&!windowLine.containsPoint(center))return void(w.width=0)}catch(error){}}),line.userData[key]=data.filter(w=>w.width>1e-9),0===line.userData[key].length&&WallHole.clear(line,key)}),this)}static recomputedCenter(lines){return lines.forEach(line=>{for(const hole of this.getIterator(line))try{const center=line.projectPoint(hole.p);hole.p={x:center?.x??0,y:center?.y??0,z:hole.p.z}}catch(error){}}),this}static merge(line){if(Array.isArray(line))return line.forEach(line2=>this.merge(line2)),this;for(const data of this.getStorageDataIterator(line)){if(0===data.length)continue;const results=data.map(hole=>{const holeLine=this.holeDataToLine(line,hole),groundClearance=hole.groundClearance??0,height=hole.height??0;return{holeLine:holeLine,startV:line.projectPointValue(holeLine.start),endV:line.projectPointValue(holeLine.end),bottom:groundClearance,top:groundClearance+height}});results.sort((a2,b4)=>a2.startV-b4.startV);const unionFindSet=new UnionFindSet(results.length);for(let i=0;i<results.length;i++){const a2=results[i];for(let j=i+1;j<results.length;j++){const b4=results[j];if(b4.startV>a2.endV)break;a2.top<b4.bottom||b4.top<a2.bottom||unionFindSet.union(i,j)}}const newData=unionFindSet.getAllSets().map(values=>{const opt={};let min=1/0,max=-1/0;for(let i=0;i<values.length;i++){const{startV:startV,endV:endV,holeLine:holeLine}=results[values[i]];Object.assign(opt,holeLine.userData),min=Math.min(min,startV,endV),max=Math.max(max,startV,endV)}const newHoleLine=new LineSegment(line.pointAt(min),line.pointAt(max));return newHoleLine.userData=opt,newHoleLine}).map(line2=>({...line2.userData,width:line2.length,p:line2.center.toJson(line2.userData.p.z)}));data.splice(0,data.length,...newData)}return this}static addHole(target,hole,type){type||(type="window"===hole.type?"drawWindow":"passageEntrance");const eabledKey="drawWindow"===type?"isWindow":"isPassageEntrance",key="drawWindow"===type?"drawWindow":"passageEntrance";hole.uuid=hole.uuid??uuid(),target.userData[eabledKey]=!0,target.userData[key]||(target.userData[key]=[]),target.userData[key]?.push(hole)}static removeHole(target,hole){this.forEachStorageType(target,(data,key)=>{let index2=data.indexOf(hole);index2>-1&&data.splice(index2,1),0===target.userData[key]?.length&&WallHole.clear(target,key)})}static copyHole(target,source){WallHole.forEachStorageType(source,(data,key)=>{data.forEach(item=>{WallHole.addHole(target,cloneUserData(item),key)})})}static splitHole(target,source){if(Array.isArray(source)||(source=[source]),target instanceof LineSegment){this.filterIllegal(target);const iterator=this.getIterator(target);return this.splitHole([...iterator],source),void this.clear(target)}if(!Array.isArray(target))throw new Error("传入参数非孔洞数组或线段");source=source.filter(line=>line.length>1e-9);for(const hole of target){let find=!1,min=1/0,maxLine=null;for(let i=0;i<source.length;i++){const line=source[i],v2=line.projectPointValue(hole.p);if(v2>=0&&v2<=1){this.addHole(line,hole),find=!0;break}const dist=Math.abs(v2-.5);dist<min&&(min=dist,maxLine=line)}if(!find&&maxLine){let v2=maxLine.projectPointValue(hole.p);v2=Math.min(1,Math.max(0,v2));const point2=maxLine.pointAt(v2,PointUtils.globalPoint);hole.p.x=point2.x,hole.p.y=point2.y,this.addHole(maxLine,hole)}}}static splitHoleByProjectPoint(target,source){Array.isArray(source)||(source=[source]),this.filterIllegal(target),source=source.filter(line=>line.length>1e-9),this.forEachStorageType(target,(holes,key)=>{for(const hole of holes){const holeLine=this.holeDataToLine(target,hole);for(let i=0;i<source.length;i++){const line=source[i],newHoleLine=line.projectLineSegment(holeLine),minW=this.getMinWidth(key,hole.type);newHoleLine.length>minW&&this.addHole(line,{...cloneUserData(hole),p:newHoleLine.center.toJson(hole.p.z),width:newHoleLine.length})}}}),this.clear(target)}static byWindowStructure(line,holeData){const holeLine=this.holeDataToLine(line,holeData),dottedLine=holeLine.clone(!1);dottedLine.userData.isBayWindow=!0,dottedLine.userData.topClearance=(line.userData.height??0)-holeLine.userData.height-(holeData.groundClearance??0);const lines=[];if(holeData.shape){const shape=holeData.shape;for(let i=1;i<shape.path.length;i++)lines.push(new LineSegment(shape.path[i-1],shape.path[i]));(shape.fragmentAttr??[{type:"window",index:1}]).forEach(({type:type,index:index2})=>{index2>=lines.length||WallHole.addHole(lines[index2],{p:holeLine.center.toJson(),width:0,full:!0,type:type,groundClearance:holeData.groundClearance,height:holeLine.userData.height})})}else{const{direction:direction,distance:distance2}=holeLine.userData.extrusion,line2=holeLine.clone(!1);line2.translate(distance2,Point.from(direction)),lines.push(new LineSegment(holeLine.start,line2.start),new LineSegment(line2.start,line2.end),new LineSegment(line2.end,holeLine.end)),WallHole.addHole(lines[1],{p:holeLine.center.toJson(),width:0,full:!0,type:"window",groundClearance:holeData.groundClearance,height:holeLine.userData.height})}const id=uuid();return{holeLine:holeLine,structure:[dottedLine,...lines].map(line2=>(LineGroupType.set(line2,id,"bayWindow"),line2.userData.height=line2.userData.height,line2))}}}const WH=WallHole;function findDiscretePointLine(lines,grid0,lineSet,deep=!0){lineSet=lineSet??/* @__PURE__ */new Set;const is2=!!grid0,grid=grid0||PointSpatialHash.fromByLines(lines);function handle(line){if(!(line instanceof LineSegment))return;if(lineSet?.has(line))return;const startInfo=grid?.queryCircle(line.start,1e-4,!0).filter(item=>item.userData!==line),endInfo=grid?.queryCircle(line.end,1e-4,!0).filter(item=>item.userData!==line);startInfo&&endInfo&&(0===startInfo?.length||0===endInfo?.length)&&(lineSet?.add(line),grid.remove(line.start),grid.remove(line.end),deep&&(startInfo.forEach(({userData:userData})=>handle(userData)),endInfo.forEach(({userData:userData})=>handle(userData))))}for(let i=0;i<lines.length;i++){handle(lines[i])}return is2||grid.clear(),lineSet}function findDiscretePointLine2(lines,lineSet,deep=!1){lineSet=lineSet||/* @__PURE__ */new Set;const map=new MapEnhance;for(lines.forEach(line=>{lineSet.size&&lineSet.has(line)||line.points.forEach(p2=>{const id=p2.hashCode(4);map.has(id)||map.set(id,/* @__PURE__ */new Set),map.get(id)?.add(line)})});;){const linesSet=/* @__PURE__ */new Set;for(const[id,set2]of map.entries()){if(1!==set2.size)continue;const line=set2.values().next().value;lineSet.add(line),map.delete(id),linesSet.add(line)}if(linesSet.forEach(line=>{map.get(line.start.hashCode())?.delete(line),map.get(line.end.hashCode())?.delete(line)}),0===linesSet.size||!deep)break}return lineSet}function findDiscretePoint(lines){const pointMap=new MapEnhance,map=new MapEnhance;lines.forEach(line=>{line.points.forEach((p2,i)=>{const id=p2.hashCode(4);map.has(id)||map.set(id,/* @__PURE__ */new Set),map.get(id)?.add(line),line.currentData[i]=id})});for(const[id,set2]of map.entries()){if(1!==set2.size)continue;const line=set2.values().next().value;line.currentData[0]===id?pointMap.set(line.start,line):pointMap.set(line.end,line)}return pointMap}function findDiscretePoint2(lines){const pointMap=new MapEnhance,pvg=PointSpatialHash.fromByLines(lines);return lines.forEach(line=>{const qr2=Math.min(.001,.009*line.length);line.points.forEach(p2=>{0===pvg.queryCircle(p2,qr2,!0).filter(item=>item.userData!==line).length&&pointMap.set(p2,line)})}),pointMap}function buildBayWindowGroup(lines,clear=!0){const bayWindowLines=lines.filter(line=>line.userData.isBayWindow),groupedLineSet=/* @__PURE__ */new Set,removeSet=findDiscretePointLine2(lines,null,!0),lines_=lines.filter(line=>!removeSet.has(line));lines.forEach(line=>{LineGroupType.hasType(line,"bayWindow")&&(line.userData.isWindow&&(line.currentData.isBayWindowLine=!0),LineGroupType.removeByType(line,"bayWindow"))});const grid=PointSpatialHash.fromByLines(lines);return removeSet.clear(),bayWindowLines.forEach(bayWindowLine=>{let{circles:circles}=MaxiCircles.instance.miniCircle(lines_,{circleEdges:[bayWindowLine]});circles=circles.filter(group2=>group2.some(line=>{if(!line.userData.isWindow)return!1;for(const data of WallHole.getIterator(line))if(data.pair===bayWindowLine.userData.pair)return!0;return!1})),circles.length&&grid.queryPolygon(Polygon.fromByLines(circles[0]),"inside").forEach(res=>removeSet.add(res.userData));const id=uuid();if(circles.length){circles[0].forEach(line=>{clear&&LineGroupType.clear(line),LineGroupType.set(line,id,"bayWindow",!0),groupedLineSet.add(line)})}else clear&&LineGroupType.clear(bayWindowLine)}),lines=lines.filter(line=>!removeSet.has(line)),clear&&lines.forEach(line=>groupedLineSet.has(line)||LineGroupType.clear(line)),lines}let trajectory;function isDoublePeCircle(circle){return WallHole.getDoubleGroup(circle).results.length>0}function isPolyHasTrajectoryPoint(lines){if(!trajectory)return!0;const ploy=Polygon.fromByLines2(lines),box=ploy.getBox2();for(let i=0;i<trajectory.length;i++){const p2=trajectory[i];if(!(p2.x<box.minX||p2.x>box.maxX||p2.y<box.minY||p2.y>box.maxY)&&ploy.pointWithin(p2))return!1}return!0}function group(lines_,clearInternalLine=!1){PointUtils.adsorb(lines_.flatMap(line=>line.points),5e-4),lines_=lines_.filter(line=>line.length>1e-7);const{doorLines:doorLines,otherLines:otherLines,peDoubleDoors:peDoubleDoors,balconyRailingLines:balconyRailingLines}=function(lines){const doorLines=[],otherLines=[],balconyRailingLines=[],bayWindowLines=[],peDoors=[],peDoubleDoors=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(line.userData.isDoor)doorLines.push(line);else if(line.userData.isBalconyRailing)balconyRailingLines.push(line);else if(line.userData.isBayWindow||line.userData.isWindow&&LineGroupType.hasType(line,"bayWindow"))bayWindowLines.push(line);else{if(line.userData.isPassageEntrance&&line.userData.passageEntrance?.length){WallHole.isDouble(line)?peDoubleDoors.push(line):peDoors.push(line);continue}otherLines.push(line)}}return{doorLines:doorLines,balconyRailingLines:balconyRailingLines,otherLines:otherLines,bayWindowLines:bayWindowLines,peDoors:peDoors,peDoubleDoors:peDoubleDoors}}(lines_),{circlesList:circlesList}=function(lines,peDoubleDoorLines){let allLines=[...lines,...peDoubleDoorLines],notFoundLines=[],circlesList=[];for(let i=0;i<peDoubleDoorLines.length;i++){const line=peDoubleDoorLines[i];let{circles:circles}=MaxiCircles.instance.miniCircle(allLines,{circleEdges:[line]});const finalCircles=circles.filter(isDoublePeCircle);finalCircles.length?circlesList.push(...finalCircles):notFoundLines.push(line)}return{circlesList:circlesList,notFoundLines:notFoundLines}}(otherLines,peDoubleDoors),set2=findDiscretePointLine(otherLines),queryLines=otherLines.filter(line=>!set2.has(line));let{internalEdges:internalEdges,circles:circles}=MaxiCircles.instance.maxiCircles(queryLines,circles2=>circles2.filter(isPolyHasTrajectoryPoint));const{circles:finalCircles}=MaxiCircles.instance.mergeCircles([...circlesList,...circles],internalEdges);lines_.forEach(line=>LineGroupType.removeByTypes(line,["doubleWall","wall"]));const grid=new PointSpatialHash,finalCirclesSet=new Set(finalCircles.flat(2));otherLines.forEach(line=>!finalCirclesSet.has(line)&&grid.insert(line.center,line)),finalCircles.forEach(group2=>{const id2=uuid();group2.forEach(line=>LineGroupType.set(line,id2,"doubleWall"))}),clearInternalLine&&finalCircles.forEach(group2=>{grid.queryPolygon(Polygon.fromByLines(group2)).forEach(res=>internalEdges.push(res.userData))}),otherLines.forEach(line=>{finalCirclesSet.has(line)||LineGroupType.hasType(line,"bayWindow")||LineGroupType.set(line,"default","wall")});const id=uuid();doorLines.forEach(doorLine=>{LineGroupType.replace(doorLine,id,"door")||LineGroupType.set(doorLine,id,"door")});const brid=uuid();balconyRailingLines.forEach(line=>{LineGroupType.replace(line,brid,"balconyRailing")||LineGroupType.set(line,brid,"balconyRailing")});const internalEdgesSet=new Set(internalEdges);return lines_=lines_.filter(line=>!internalEdgesSet.has(line))}const buildDoubleWallGroup=Object.assign((lines_,clearInternalLine)=>LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines_,line=>LineGroupType.hasType(line,"pillar")?"pillar":WallHole.isBeam(line)?"beam":"lines")).handle("lines",lines=>(WallHole.buildPairing(lines),group(lines,clearInternalLine))).merge(),{setTrajectory(trajectory_){trajectory=trajectory_?Object.values(trajectory_).filter(p2=>!(Math.abs(p2.x)<.01&&Math.abs(p2.y)<.01)):void 0}});class BuildGroup{static get bayWindow(){return buildBayWindowGroup}static get doubleWall(){return buildDoubleWallGroup}}class DoubleWallFinder{static group(lines,parallelAxis,verticalAxis,esp=.05,gap=0){esp/=verticalAxis.length;const vls=lines.map(line=>[verticalAxis.projectPointValue(line.start),line,[parallelAxis.projectPointValue(line.start),parallelAxis.projectPointValue(line.end)].sort((a2,b4)=>a2-b4)]).sort((a2,b4)=>a2[0]-b4[0]),newLines=[];for(let i=0;i<vls.length;i++){const[ipv,iline,[istart,iend]]=vls[i];for(let j=i+1;j<vls.length;j++){const[jpv,jline,[jstart,jend]]=vls[j];if(jpv-ipv>esp)break;Math.min(iend,jend)-Math.max(istart,jstart)>-gap&&new Array([iline,jline],[jline,iline]).forEach(([line,target])=>{if(WallHole.isBeam(line))return;const holeLines=[];for(const h2 of WallHole.getIterator(target)){const holeLine=WallHole.holeDataToLine(target,h2,!0,!1);holeLine.setLength(holeLine.length-.004),holeLines.push(holeLine)}line.points.forEach(point2=>{let pv=target.projectPointValue(point2);if(pv<0||pv>1)return;const pvPoint=target.pointAt(pv);if(holeLines.some(hl=>hl.isPointOnSegment(pvPoint)))return;const newLine=deriveLine(target);newLine.start.copy(point2),newLine.end.copy(pvPoint),newLines.push(newLine)})})}}return newLines}static find(lines,obstacle=[],esp=.4){return lines=splitIntersectedLine(lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,_line=>"lines")).handle("lines",lines2=>{const parallelAxis=lines2[0],verticalAxis=parallelAxis.clone().rotate(.5*Math.PI),[group1,group2]=LineSegmentUtils.groupByParallelToAxis(lines2,lines2[0],5),newLines1=this.group(group1,parallelAxis,verticalAxis,esp),newLines2=this.group(group2,verticalAxis,parallelAxis,esp),appendLines=newLines1.concat(newLines2);return lines2=lines2.concat(appendLines)}).merge(),1e-9,{obstacle:obstacle})}static buildGroup(lineSegments){let otherLines=[];return lineSegments=lineSegments.filter(line=>!(line.userData.isDoor||WallHole.isBeam(line)||line.userData.isBalconyRailing||line.userData.isBayWindowWin||line.userData.isBayWindow)||(otherLines.push(line),!1)),lineSegments=BuildGroup.doubleWall(lineSegments,!0),lineSegments=this.find(lineSegments,[...otherLines]),lineSegments=LineSegmentUtils.deduplicate(lineSegments,{necessaryLines:otherLines}),WallHole.filterIllegal(lineSegments),lineSegments=BuildGroup.doubleWall(lineSegments,!0),[...lineSegments,...otherLines]}}const VITE_OSS_BASEURL="https://img.unrealspace3d.com/common-assets/".endsWith("/")?"https://img.unrealspace3d.com/common-assets/":"https://img.unrealspace3d.com/common-assets//",DEFAULT_WALL_WIDTH=.12,MAX_WALL_WIDTH=.3;class RangeCore{static union(list){if(0===list.length)return[];const ranges=list.map(([start,end])=>start<=end?[start,end]:[end,start]).sort((a2,b4)=>a2[0]-b4[0]),result=[ranges[0]];for(let i=1;i<ranges.length;i++){const current=ranges[i],last=result[result.length-1];current[0]<=last[1]?last[1]=Math.max(last[1],current[1]):result.push(current)}return result}static intersection(list){if(0===list.length)return[];let start=-1/0,end=1/0;for(const[a2,b4]of list)if(start=Math.max(start,Math.min(a2,b4)),end=Math.min(end,Math.max(a2,b4)),start>end)return[];return[[start,end]]}static difference(range,occupied){const[start,end]=range;if(start>=end)return[];const ranges=this.union(occupied.map(([a2,b4])=>[Math.max(start,Math.min(a2,b4)),Math.min(end,Math.max(a2,b4))]).filter(([a2,b4])=>a2<b4)),result=[];let cursor=start;for(const[a2,b4]of ranges)cursor<a2&&result.push([cursor,a2]),cursor=Math.max(cursor,b4);return cursor<end&&result.push([cursor,end]),result}}class BoundExt{static createQuery(lines,trajectoryPoints,minWidth=.4){lines=lines.flatMap(line=>{let ranges=[];for(const holeData of WallHole.getIterator(line)){if("beam"!==(holeData.type??"passageEntrance"))continue;const holeLine=WallHole.holeDataToLine(line,holeData),startV=line.projectPointValue(holeLine.start),endV=line.projectPointValue(holeLine.end);ranges.push(startV<endV?[startV,endV]:[endV,startV])}if(ranges=RangeCore.union(ranges),0===ranges.length)return[line];const clipLines=ranges.map(range=>new LineSegment(line.pointAt(range[0]),line.pointAt(range[1])));return LineSegmentUtils.clippingByLines(line,clipLines)});const lsh=LineSegmentSpatialHash.from(lines);return{query(line){const center=line.center,set2=/* @__PURE__ */new Set;for(const point2 of trajectoryPoints){if(2===set2.size)break;const lineA=new LineSegment(center,point2);if(!lsh.queryLine(lineA).filter(targetLine=>{if(targetLine===line)return!1;if(LineGroupType.hasGroup(line))return!0;if(targetLine.isParallelTo(line)&&line.distanceToSegment(targetLine)<minWidth){if(targetLine.projectLineSegment(line).length/line.length>.6)return!1}return!0}).length){const position=line.getPointSideOfLine(point2);"on"!==position&&set2.add(position)}}return set2}}}static findExtWallByTraj(lines,trajectoryPoints,minWidth=.4){lines=lines.filter(line=>!line.userData.isBayWindow);const{query:query}=this.createQuery(lines,trajectoryPoints,minWidth);return lines=lines.filter(line=>{if(LineGroupType.hasType(line,"doubleWall")||LineGroupType.hasType(line,"pillar"))return;const set2=query(line);return line.userData.expandDirect=[...set2][0],set2.size<2||void 0})}static boundExtbyTrajAndOriginalData(opt){const zList=[];let lines=opt.data.map(({start:start,end:end,...opt2})=>{const line=new LineSegment(Point.from(start),Point.from(end));return line.userData=opt2,zList.push(start.z??0,end.z??0),line});const originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length;return this.boundExtbyTraj({...opt,lines:lines}).toOriginalData(originalZAverage)}static boundExtbyTraj(opt){let{lines:lines,trajectory:trajectory2,wallWidth:wallWidth=DEFAULT_WALL_WIDTH,updateDoubleWallGroup:updateDoubleWallGroup=!1,findCallBack:findCallBack}=opt;updateDoubleWallGroup&&(lines=DoubleWallFinder.buildGroup(lines));const trajectoryPoints=Object.keys(trajectory2).map(key=>Point.from(trajectory2[key]));return lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,line=>WallHole.isBeam(line)?"exclude":"lines")).handle("lines",lines2=>{const findLines=BoundExt.findExtWallByTraj(lines2,trajectoryPoints);findLines.forEach(line=>{line.userData.expandDirect||(line.userData.miscellaneous=!0)});let exteriorLines=findLines.filter(line=>line.userData.expandDirect).filter(line=>!line.userData.isBalconyRailing).filter(line=>!LineGroupType.hasType(line,"bayWindow"));(lines2=lines2.filter(line=>!exteriorLines.includes(line))).push(...exteriorLines);const grid=PointSpatialHash.fromByLines(lines2),quadtree=Quadtree.from(lines2),arrayMap=new ArrayMap,pointMap=/* @__PURE__ */new Map;let appendLines=[];exteriorLines.forEach(line=>{const direction="left"===line.userData.expandDirect?line.getRightDirection():line.getLeftDirection();quadtree.raycast(line.center,direction,.001,wallWidth).length>0||(line.points.forEach(point2=>{const id=point2.hashCode();arrayMap.append(id,{point:point2,line:line}),pointMap.has(id)||pointMap.set(id,point2.clone()),grid.update(point2)}),line.translate(.5*wallWidth,direction),grid.updates(line.points),delete line.userData.wallWidth)}),arrayMap.forEach((list,id)=>{if(list.length>=2){if(list[0].line.isParallelTo(list[1].line,20))return;const p1=list[0].line.getIntersection(list[1].line);p1&&(list[0].point.copy(p1),list[1].point.copy(p1))}else{if(grid.queryCircle(pointMap.get(id),1e-4).length){const newLine=new LineSegment(pointMap.get(id),list[0].point.clone()),list_=list.filter(i=>!i.line.userData.isDoor&&!i.line.userData.isWindow);if(list_.length&&(newLine.userData=cloneUserData(list_[0].line.userData)),quadtree.queryCircle(newLine.center,1e-4).length)return;newLine.userData.boundExtAppendLine=!0,newLine.userData.boundExtAppendLineLen=newLine.length,appendLines.push(newLine)}}}),appendLines=LineSegmentUtils.mergeParallelSegments(appendLines).lines,lines2.push(...appendLines.filter(line=>line.length>1e-9));const doors=(lines2=splitIntersectedLine(lines2,1e-9)).filter(line=>line.userData.isDoor),walls=lines2.filter(line=>!line.userData.isDoor);return lines2=[...LineSegmentUtils.mergeCollinearSegmentsAll(walls,mergeLineUserData),...doors],WallHole.filterIllegal(lines2),lines2=lines2.filter(line=>line.length>1e-4).filter(line=>!line.userData.isDoor||line.length>.25),findCallBack&&findCallBack([...exteriorLines,...appendLines],trajectoryPoints),lines2}).merge(),{lines:lines,toOriginalData:originalZAverage=>lineDataToOriginalData(lines,originalZAverage)}}}function getDividingLine(lines){const maxLine=lines.reduce((maxLine2,line)=>maxLine2?line.length>maxLine2.length?line:maxLine2:line),normal=maxLine.normal(),axisLine=maxLine.center.expandAsLine(normal,.1).translate(.05,normal.multiplyScalar(-1)),axisValue=axisLine.projectPointValue(maxLine.start);let min=1/0,minAxisLine=null,max=-1/0,maxAxisLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.isParallelTo(maxLine)||line===maxLine)continue;const v2=axisLine.projectPointValue(line.start);Math.abs(v2-axisValue)<1e-6||(v2<min&&(min=v2,minAxisLine=line),v2>max&&(max=v2,maxAxisLine=line))}if(minAxisLine===maxAxisLine)return;const[_,clipLine]=[[axisValue,maxLine],[min,minAxisLine],[max,maxAxisLine]].sort((a2,b4)=>a2[0]-b4[0])[1];return clipLine}function segmentationPath(lines,clipLine){const quadtree=LineSegmentSpatialHash.from(lines),queryLine2=clipLine.clone().extendAlongDirection(100),removeLines=/* @__PURE__ */new Set,fractureLines=/* @__PURE__ */new Set;lines.forEach(line=>quadtree.insert(line));const list=quadtree.queryRectangle(queryLine2.toRectangle(.001,"butt"));for(let i=0;i<list.length;i++){const line=list[i];if(line.isParallelTo(queryLine2,8)){removeLines.add(line);continue}const point2=line.getIntersection(queryLine2);if(point2){if(line.start.equal(point2)||line.end.equal(point2))continue;const newLines=LineSegmentUtils.clippingByPoints(line,[point2],clippingLineUserData);removeLines.add(line),newLines.forEach(line2=>fractureLines.add(line2))}}(lines=lines.filter(line=>!removeLines.has(line))).push(...fractureLines);const groups=LineSegmentUtils.groupByCenterPointSide(lines,queryLine2),newGroups=[];return groups.forEach(group2=>{PointUtils.adsorb(group2.flatMap(line=>line.points),.001);const points=[...findDiscretePoint2(group2=mergeChainsLine(group2)).keys()],projValues=/* @__PURE__ */new Map;points.forEach(p2=>projValues.set(p2,queryLine2.projectPointValue(p2))),points.sort((a2,b4)=>projValues.get(a2)-projValues.get(b4));for(let i=0;i<points.length;i+=2){const p1=points[i],p2=points[i+1];p1&&p2&&group2.push(new LineSegment(p1.clone(),p2.clone()))}group2=mergeChainsLine(group2),newGroups.push(group2)}),quadtree.clear(),newGroups}function clippingDoubleWall(lines){if(4===(lines=mergeChainsLine(lines=lines.map(line=>line.clone()))).length)return[lines];const queue=[lines],groups=[];let pendingLines,count=0;for(;void 0!==(pendingLines=queue.pop());){if(count++,count>2e4)throw new Error("超过最大循环次数");if(pendingLines.length<=4){groups.push(pendingLines);continue}const clipLine=getDividingLine(pendingLines);if(!clipLine){groups.push(pendingLines);continue}const result=segmentationPath(pendingLines,clipLine).flatMap(group2=>LineSegmentUtils.groupByPath(group2));1!==result.length?result.forEach(group2=>{4===(group2=mergeChainsLine(group2)).length?groups.push(group2):queue.push(group2)}):groups.push(pendingLines)}return groups}const miniCircles=new MiniCircles;function clippingInsertObjectDoubleWall(lines){if(!lines.some(line=>WallHole.isHole(line)))return clippingDoubleWall(lines);const quadtree=Quadtree.from(lines),poly=Polygon.fromByLines2(lines);let polygons=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(WallHole.isHole(line)){const normal=line.normal(),center=line.center;poly.pointWithin(center.add(normal.clone().multiplyScalar(1e-6)))||normal.multiplyScalar(-1),WallHole.forEachStorageType(line,data=>data.forEach(d2=>{const wioLine=WallHole.holeDataToLine(line,d2);wioLine.setLength(wioLine.length-.004);const len=wioLine.length;let startResults=quadtree.raycast(wioLine.start,normal,1e-4,10).filter(item=>item.targetLine.isParallelTo(wioLine)),endResults=quadtree.raycast(wioLine.end,normal,1e-4,10).filter(item=>item.targetLine.isParallelTo(wioLine));if(startResults.length>1&&(startResults=startResults.filter(item=>item.targetLine.projectLineSegment(wioLine).length/len>.01)),endResults.length>1&&(endResults=endResults.filter(item=>item.targetLine.projectLineSegment(wioLine).length/len>.01)),0===startResults.length||0===endResults.length)return;const startResult=startResults[0],endResult=endResults[0];if(startResult.targetLine!==endResult.targetLine){const pl1=startResult.targetLine.projectLineSegment(wioLine),pl2=endResult.targetLine.projectLineSegment(wioLine),finalPl=pl1.length>pl2.length?pl1:pl2;return void polygons.push(new Polygon([wioLine.projectPoint(finalPl.start,!1),finalPl.start,finalPl.end,wioLine.projectPoint(finalPl.end,!1)]))}polygons.push(new Polygon([wioLine.start,startResult.intersectPoint,endResult.intersectPoint,wioLine.end]))}))}}if(!polygons.length)return[lines];polygons=Polygon.booleanOp(polygons[0],polygons.slice(1),{type:"Union",scale:1e4});const newLines=polygons.map(poly2=>poly2.toLines()).flat().flatMap(line=>{let list=quadtree.queryRect(line.toRectangle(2e-4,"butt")).map(res=>res.line).filter(l=>l.isParallelTo(line,10));if(list.length){return LineSegmentUtils.clippingByLines(line,list)??[]}return[line]});lines.push(...newLines),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),lines=mergeChainsLine(lines=splitIntersectedLine(lines=lines.map(line=>line.clone()),1e-9)).filter(line=>line.length>0),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),WallHole.filterIllegal(lines).merge(lines);const{circles:circles}=miniCircles.miniCircle(lines);return circles.flatMap(circle=>clippingDoubleWall(circle))}class WallGroupManager{[Symbol.iterator](){return this.groups[Symbol.iterator]()}groups=[];add(group2){this.groups.push(group2)}forEach(fun){for(let i=0;i<this.groups.length;i++)fun(this.groups[i],i,i==this.groups.length-1)}map(fun){const list=[];for(let i=0;i<this.groups.length;i++)list.push(fun(this.groups[i],i));return list}findGroup(fun){for(let i=0;i<this.groups.length;i++){const group2=this.groups[i];if(fun(group2))return group2}}findGroupByType(type){return this.findGroup(group2=>group2.type===type)}findGroups(fun){const list=[];for(let i=0;i<this.groups.length;i++){const group2=this.groups[i];fun(group2)&&list.push(group2)}return list}findGroupsByType(type){"string"==typeof type&&(type=[type]);const set2=new Set(type);return this.findGroups(group2=>set2.has(group2.type))}static createGroup(lines){return LineSegmentUtils.group(lines,line=>"pillar"===line.userData.type||LineGroupType.hasType(line,"pillar")?"pillar":WallHole.isBeam(line)?"beam":line.userData.isBalconyRailing?"railing":"wall")}static fromByLines(lineSegments){const wallGroupManager=new WallGroupManager,removeLines=[];LineGroupType.getGroupsByType(lineSegments,"doubleWall").forEach(doubleWall=>{wallGroupManager.add({type:"doubleWall",lines:doubleWall}),removeLines.push(...doubleWall)});LineGroupType.getGroupsByType(lineSegments,"pillar").forEach(pillar=>{wallGroupManager.add({type:"pillar",lines:pillar}),removeLines.push(...pillar)});const bayWindowGroups=LineGroupType.getGroupsByType(lineSegments,"bayWindow");bayWindowGroups.forEach(bayWindowGroup=>{wallGroupManager.add({type:"bayWindow",lines:bayWindowGroup,data:[]})});const doors=(lineSegments=bayWindowGroups.remainingLines).filter(line=>line.userData.isDoor);wallGroupManager.add({type:"door",lines:doors}),removeLines.push(...doors);const set2=new Set(removeLines),walls=[],windowLines=[],balconyRailingLines=[];return lineSegments.filter(line=>!set2.has(line)).forEach(line=>{line.userData.isBayWindow||(line.userData.isWindow?windowLines.push(line):line.userData.isBalconyRailing?balconyRailingLines.push(line):walls.push(line))}),walls.length&&wallGroupManager.add({type:"wall",lines:walls}),windowLines.length&&wallGroupManager.add({type:"window",lines:windowLines}),balconyRailingLines.length&&wallGroupManager.add({type:"balconyRailing",lines:balconyRailingLines}),wallGroupManager}static fromByLines1_5(lineSegments){const wallGroupManager=new WallGroupManager,removeLinesSet=/* @__PURE__ */new Set,structure={wall:[],pillar:[],bayWindow:[],railing:[]};LineGroupType.getGroupsByType(lineSegments,"pillar").forEach(pillar=>{pillar.forEach(line=>removeLinesSet.add(line)),structure.pillar.push(pillar)}),lineSegments=lineSegments.filter(line=>!removeLinesSet.has(line));LineGroupType.getGroupsByType(lineSegments,"doubleWall").forEach(doubleWall=>{doubleWall.forEach(line=>removeLinesSet.add(line));clippingInsertObjectDoubleWall(doubleWall).forEach(group2=>{const walls=function(lines){if(lines.length<4)return lines;if(lines.length>4){const polygon2=Polygon.fromByLinePath(lines).getMinimumBoundingRectangle();polygon2&&(lines=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines=[...lines].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,newLine.currentData.doubleWall=!0,WallHole.merge(newLine).filterIllegal(newLine),[newLine]}(group2);structure.wall.push(...walls)})});return LineGroupType.getGroupsByType(lineSegments,"bayWindow").forEach(bayWindowGroup=>{bayWindowGroup.forEach(line=>removeLinesSet.add(line)),structure.bayWindow.push(bayWindowGroup)}),lineSegments.filter(line=>!removeLinesSet.has(line)).forEach(line=>{line.userData.isBalconyRailing?structure.railing.push(line):structure.wall.push(line)}),wallGroupManager.add({type:"wall",lines:structure.wall}),wallGroupManager.add({type:"railing",lines:structure.railing}),structure.bayWindow.forEach(lines=>wallGroupManager.add({type:"bayWindow",lines:lines})),structure.pillar.forEach(lines=>wallGroupManager.add({type:"pillar",lines:lines})),wallGroupManager}}function createPromise(){let resolve,reject;const promise2=new Promise((re2,rt)=>{resolve=re2,reject=rt});return{get resolve(){return resolve},get reject(){return reject},get promise(){return promise2}}}function precision4(value){return 1e-4*Math.round(1e4*value)}function precision4Nullable(value){return null==value?void 0:precision4(value)}const defaultWallWidth$1=DEFAULT_WALL_WIDTH;class WallHoleDrawData{static singleHoleLine(line,grid){if(WallHole.isHole(line)){const newLines=[];WallHole.merge([line]);let openDirect=null;return"expandDirect"in line.userData&&(openDirect="left"===line.userData.expandDirect?line.getRightDirection():line.getLeftDirection()),WallHole.forEachStorageType(line,(data,k)=>{const list=grid&&function(grid,line){const startList=grid.queryPoint(line.start,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),endList=grid.queryPoint(line.end,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),results=[];return 0===startList.length?results.push(0):startList.some(item=>"wall"===item)?results.push(1):results.push(2),0===endList.length?results.push(0):endList.some(item=>"wall"===item)?results.push(1):results.push(2),results}(grid,line),dwh=.5*defaultWallWidth$1;data.map(hole=>{let{height:height,groundClearance:groundClearance,uuid:uuid2,type:type}=hole;const insertObjectLine=WallHole.holeDataToLine(line,hole),hole_type=insertObjectLine.userData.type;if(insertObjectLine.userData={openDirect:openDirect,wallWidth:line.userData.wallWidth??defaultWallWidth$1,wallHeight:line.userData.height,height:height,groundClearance:groundClearance,type:"drawWindow"===k?"window":type??"passageEntrance",maxHeight:line.userData.height,extrusion:hole.extrusion,p:{...hole.p},width:hole.width,full:hole.full,shape:hole.shape},!list||"beam"===hole_type||"passageEntrance"===hole_type)return newLines.push(insertObjectLine);const startDistance=insertObjectLine.start.distance(line.start);if(startDistance<dwh&&1===list[0]){const diff=dwh-startDistance;insertObjectLine.offsetStart(diff)}const endDistance=insertObjectLine.end.distance(line.end);if(endDistance<dwh&&1===list[1]){const diff=dwh-endDistance;insertObjectLine.offsetEnd(diff)}insertObjectLine.userData.winUuid=uuid2,insertObjectLine.userData.lineUuid=line.userData.uuid,insertObjectLine.userData.type="drawWindow"===k?"window":type??"passageEntrance",newLines.push(insertObjectLine)})}),newLines.filter(line2=>line2.length>defaultWallWidth$1),newLines}return null}static doubleHoleLine(lines){if(lines.length<3)return[];const heights=(lines=[...lines].sort((a2,b4)=>b4.length-a2.length)).map(line=>line.userData.height??0),direct=lines[0].direction(),center=Polygon.fromByLines2(lines).getCenter(),newLine=new LineSegment(center.clone(),center.clone().add(direct)),pvs=lines.flatMap(line=>line.points.map(p2=>newLine.projectPointValue(p2))).sort((a2,b4)=>a2-b4),minPoint=newLine.pointAt(pvs[0]),maxPoint=newLine.pointAt(pvs[pvs.length-1]),normalLine=newLine.clone().rotate(.5*Math.PI),npvs=lines.flatMap(line=>line.points.map(p2=>normalLine.projectPointValue(p2))).sort((a2,b4)=>a2-b4),wallWidth=(npvs[npvs.length-1]-npvs[0])*normalLine.length;newLine.start.copy(minPoint),newLine.end.copy(maxPoint);let wallHeight=0;lines.forEach(line=>wallHeight=Math.max(wallHeight,line.userData.height??0)),mergeLineUserData(newLine,lines),WallHole.merge(newLine);const newLines=[];return WallHole.forEachStorageType(newLine,(data,key)=>{data.forEach(({full:full,width:width,p:p2,height:height,groundClearance:groundClearance,type:type})=>{const point2=Point.from(p2),direct2=newLine.direction();full&&(width=newLine.length);const insertObjectLine=point2.expandAsLine(direct2,width).translate(.5*-width,direct2);try{insertObjectLine.start.copy(newLine.projectPoint(insertObjectLine.start,!1)),insertObjectLine.end.copy(newLine.projectPoint(insertObjectLine.end,!1))}catch(error){}insertObjectLine.userData={wallHeight:wallHeight||void 0,wallWidth:wallWidth,height:height,groundClearance:groundClearance,type:"drawWindow"===key?"window":type??"passageEntrance",maxHeight:Math.max(...heights)},newLines.push(insertObjectLine)})}),newLines.filter(line=>line.length>defaultWallWidth$1)}static handleHoleDrawData(doubleWallGroup,wall,lines=[]){const grid=new PointSpatialHash;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));const holes=new ArrayMap,newLines=[];return(wall=wall.filter(line=>{const holeLines=this.singleHoleLine(line,grid);if(!holeLines?.length)return!0;{holeLines.forEach(line2=>holes.append(line2.userData.type,line2));const lines2=LineSegmentUtils.clippingByPoints(line,PointUtils.adsorb(holeLines.flatMap(line2=>line2.points))).filter(line2=>{const center=line2.center;return!holeLines.some(line22=>line22.isPointOnSegment(center))});newLines.push(...lines2)}})).push(...newLines),grid.clear(),doubleWallGroup=doubleWallGroup.filter(lines2=>{if(lines2.length<3)return!1;const holeLines=this.doubleHoleLine(lines2);return holeLines.forEach(line=>holes.append(line.userData.type,line)),0===holeLines.length}),Object.assign(holes,{get untreatedDoubleWallGroup(){return doubleWallGroup},get untreatedWall(){return wall},get passageEntrance(){return holes.get("passageEntrance")??[]},get window(){return holes.get("window")??[]},get door(){return holes.get("door")??[]},get beam(){return holes.get("beam")??[]}})}}function createGeometry(points,options){points=points.map(p2=>p2 instanceof Point?new THREE.Vector2(p2.x,p2.y):p2);const shape=new THREE.Shape(points);return new THREE.ExtrudeGeometry(shape,{bevelEnabled:!1,...options})}class ExtrudeMesh extends THREE.Mesh{geometry;options;constructor(points,options,material){const geometry=createGeometry(points,options);super(geometry,material),this.geometry=geometry,this.options=options}setPoints(points,options=this.options){const geometry=createGeometry(points,options);this.geometry=geometry}}class BayWindowHelper{static computedInfo(lines){let dottedLine=lines.find(line=>line.userData.isBayWindow),windowLine=lines.find(line=>line.userData.isWindow),counter=new CounterMap,side="LEFT",depth=0;if(dottedLine){for(let i=0;i<lines.length;i++){const line=lines[i];if(line===dottedLine)continue;const center=line.center,side2=dottedLine.getPointSideOfLine(center);"on"!==side2&&counter.increment(side2),depth=Math.max(depth,line.start.distance(dottedLine.projectPoint(line.start,!1)),line.end.distance(dottedLine.projectPoint(line.end,!1)))}return side="left"===counter.getMaxKey()?"LEFT":"RIGHT",{side:side,depth:depth,dottedLine:dottedLine,windowLine:windowLine}}}static getDrawData(lines){if(4===(lines=mergeChainsLine(lines.map(line=>line.clone()))).length){let bayWindowLine=null,windowLine=null,deptLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isBayWindow?bayWindowLine=line:line.userData.isWindow&&line.userData.drawWindow&&line.userData.drawWindow.length?windowLine=line:deptLine=line}if(bayWindowLine&&windowLine&&deptLine){const{width:width,height:height,groundClearance:groundClearance}=windowLine.userData.drawWindow[0],direction=Point.zero();return deptLine.isSameEndpointAsEnd(bayWindowLine)?deptLine.start.directionFrom(deptLine.end,direction):deptLine.end.directionFrom(deptLine.start,direction),{height1:bayWindowLine.userData.topClearance??0,height2:height,height3:groundClearance,depth:deptLine.length,windowWidth:width,windowHeight:height,bayWindowLine:bayWindowLine,windowLine:windowLine,deptLine:deptLine,direction:direction}}}return null}static getDrawData2(lines){lines=mergeChainsLine(lines.map(line=>line.clone()));let bayWindowLine=null,windowLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isBayWindow?bayWindowLine=line:line.userData.isWindow&&line.userData.drawWindow&&line.userData.drawWindow.length&&(windowLine=line)}if(bayWindowLine&&windowLine){const{width:width,height:height,groundClearance:groundClearance}=windowLine.userData.drawWindow[0],direction=Point.zero();return{height1:bayWindowLine.userData.topClearance??0,height2:height,height3:groundClearance,windowWidth:width,windowHeight:height,direction:direction}}return null}static getDrawDataAll(lineSegments){const groups=LineGroupType.getGroupsByType(lineSegments,"bayWindow"),drawDataList=groups.map(this.getDrawData);return groups.map((group2,indxe)=>({group:group2,drawData:drawDataList[indxe]})).filter(item=>item.drawData)}static drawDataToModel(drawData){const pos=drawData.bayWindowLine.center,dirct=drawData.bayWindowLine.direction(),length=drawData.bayWindowLine.length,bayWindowLine=Point.zero().expandAsLine(dirct,length).translate(.5*length,dirct.multiplyScalar(-1)),winGroup=new THREE.Group,material=new THREE.MeshBasicMaterial({color:16777215});winGroup.position.set(pos.x,pos.y,0);const rectangle=bayWindowLine.toRectangle(DEFAULT_WALL_WIDTH),extrudeMesh=new ExtrudeMesh(rectangle.points,{depth:drawData.height3},material);winGroup.add(extrudeMesh);const rectangle2=bayWindowLine.clone().translate(drawData.depth,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH),extrudeMesh2=new ExtrudeMesh(rectangle2.points,{depth:drawData.height2},new THREE.MeshPhongMaterial({color:16777215,transparent:!0,opacity:.2}));extrudeMesh2.position.z=drawData.height3,winGroup.add(extrudeMesh2);const rectangle3=bayWindowLine.start.expandAsLine(drawData.direction,drawData.depth).translate(-.06,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH,"butt"),extrudeMesh3=new ExtrudeMesh(rectangle3.points,{depth:drawData.height2},material);extrudeMesh3.position.z=drawData.height3,winGroup.add(extrudeMesh3);const rectangle4=bayWindowLine.end.expandAsLine(drawData.direction,drawData.depth).translate(-.06,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH,"butt"),extrudeMesh4=new ExtrudeMesh(rectangle4.points,{depth:drawData.height2},material);extrudeMesh4.position.z=drawData.height3,winGroup.add(extrudeMesh4);const extrudeMesh5=new ExtrudeMesh(rectangle.points,{depth:drawData.height1},material);extrudeMesh5.position.z=drawData.height3+drawData.height2,winGroup.add(extrudeMesh5);const rectangle6=bayWindowLine.clone().translate(.5*drawData.depth,drawData.direction).toRectangle(drawData.depth-DEFAULT_WALL_WIDTH,"butt"),extrudeMesh6=new ExtrudeMesh(rectangle6.points,{depth:.001},material);extrudeMesh6.position.z=drawData.height3,winGroup.add(extrudeMesh6);const extrudeMesh7=new ExtrudeMesh(rectangle6.points,{depth:.001},material);return extrudeMesh7.position.z=drawData.height3+drawData.height2,winGroup.add(extrudeMesh7),winGroup}}const holeTypeMap={door:"DOOR",RAILING:"RAILING",window:"WINDOW",passageEntrance:"WALL_HOLE",bay_window:"BAY_WINDOW"},placeHoldersMap={switch:"开关",socket:"插座"},WALL_HEIGHT_KEY$1=/* @__PURE__ */Symbol("height");class ThreeVJiaPipeline extends Pipeline{manager;index=0;maxHeight;lines;constructor(lines,maxHeight){super(),this.maxHeight=maxHeight,this.lines=lines,this.manager=WallGroupManager.fromByLines(lines),this.use({type:"bayWindow",handle:this.bayWindowHandle.bind(this)}),this.use({type:"doubleWall",handle:this.doubleWallHandle.bind(this)}),this.use({type:"wall",handle:this.wallHandle.bind(this)}),this.use({type:"door",handle:this.doorHandle.bind(this)}),this.use({type:"window",handle:this.wallHandle.bind(this)}),this.use({type:"balconyRailing",handle:this.balconyRailing.bind(this)}),this.use({type:"wallHole",handle:this.wallHoleHandle.bind(this)})}doubleWallHandle({data:{lines:lines},cache:cache2}){const groups=clippingInsertObjectDoubleWall(lines),{door:door,window:windowLines,passageEntrance:passageEntrance,untreatedDoubleWallGroup:untreatedDoubleWallGroup}=WallHoleDrawData.handleHoleDrawData(groups,[]),walls=untreatedDoubleWallGroup.flatMap(lines2=>{if(lines2.length<4)return lines2;if(lines2.length>4){const polygon2=Polygon.fromByLinePath(lines2).getMinimumBoundingRectangle();polygon2&&(lines2=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines2=[...lines2].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines2[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines2),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,[newLine]});this.manager.add({type:"wallHole",lines:windowLines}),this.manager.add({type:"wallHole",lines:door}),this.manager.add({type:"wallHole",lines:passageEntrance}),cache2.wallLines=[...cache2.wallLines,...walls,...windowLines,...door,...passageEntrance]}wallHandle({data:{lines:lines},cache:cache2}){const holeLines=lines.flatMap(line=>WallHoleDrawData.singleHoleLine(line)??[]);this.manager.add({type:"wallHole",lines:holeLines}),cache2.wallLines.push(...lines)}doorHandle({data:{lines:lines},cache:cache2}){const doors=lines.map(line=>{const doorLine=new LineSegment(line.start.clone(),line.end.clone());return doorLine.userData={groundClearance:line.userData.drawDoorData?.sillHeight,height:line.userData.drawDoorData?.height,type:"door",wallHeight:line.userData.drawDoorData?.height,wallWidth:void 0},doorLine});this.manager.add({type:"wallHole",lines:doors}),cache2.wallLines.push(...doors)}bayWindowHandle({data:{lines:lines},cache:cache2}){const info=BayWindowHelper.computedInfo(lines);if(info){const{dottedLine:dottedLine,windowLine:windowLine,depth:depth,side:side}=info,line=new LineSegment(dottedLine.start.clone(),dottedLine.end.clone()),win=windowLine?.userData.drawWindow&&windowLine.userData.drawWindow[0];"LEFT"===side&&line.swapValue(),line.translate(.5*-DEFAULT_WALL_WIDTH,line.normal()),line.userData={groundClearance:win?.groundClearance??0,height:win?.height,type:"bay_window",wallHeight:win?.height,wallWidth:void 0,depth:depth??.5,openSide:side},this.manager.add({type:"wallHole",lines:[line]}),line.setLength(line.length+.001),cache2.wallLines.push(line)}}balconyRailing({data:{lines:lines},cache:cache2}){const brls=lines.map(line=>{line.currentData[WALL_HEIGHT_KEY$1]=line.userData.height;const brl=new LineSegment(line.start.clone(),line.end.clone());return brl.userData={groundClearance:0,height:line.userData.height,type:"RAILING",wallWidth:void 0},brl});this.manager.add({type:"wallHole",lines:brls}),cache2.wallLines.push(...lines)}wallHoleHandle({data:{lines:lines,json:json}}){lines.forEach(line=>{if(line.length<1e-4)return;let type=holeTypeMap[line.userData.type]??"WALL_HOLE";const hole={id:this.index++,type:type,start:line.start.precision4().toJson2D(),end:line.end.precision4().toJson2D(),depth:precision4Nullable(line.userData.depth),height:precision4Nullable(line.userData?.height??2.1),sillHeight:precision4Nullable(line.userData?.groundClearance??0),groundClearance:precision4Nullable(line.userData?.groundClearance??0)};"DOOR"===type?Object.assign(hole,{openSide:"RIGHT"}):"BAY_WINDOW"===type&&Object.assign(hole,{openSide:line.userData.openSide}),json.holes.push(hole)})}transform(){const option={version:"2",name:"",communityName:"",city:"",province:"",height:this.maxHeight,walls:[],pillars:[],beams:[],holes:[],rooms:[],placeHolders:[],center:{x:0,y:0},angle:0},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),cache2.wallLines.forEach(line=>{option.walls.push({ID:this.index++,start:line.start.precision4().toJson2D(),end:line.end.precision4().toJson2D(),thickness:precision4(Math.max(line.userData.wallWidth?line.userData.wallWidth:DEFAULT_WALL_WIDTH,DEFAULT_WALL_WIDTH)),type:"LINE",isDoor:!1,loadBearingWall:!1,height:precision4(line.currentData[WALL_HEIGHT_KEY$1]??this.maxHeight)})}),option}static appendRooms(json,rooms){return Array.isArray(json.rooms)||(json.rooms=[]),rooms.map((room,i)=>{json.rooms.push({name:`房间(${i+1})`,position:room.center.clone().rotate(json.center,json.angle).toJson(),roomTypeId:17,polygon:room.ploy.map(p2=>p2.clone().rotate(json.center,json.angle).toJson2D()),id:i})}),json}static appendPlaceHolders(json,publicInfo,z){Array.isArray(json.placeHolders)||(json.placeHolders=[]);const rooms=json.rooms,roomPloys=rooms.map(room=>new Polygon(room.polygon.map(p2=>Point.from(p2))));return 0===roomPloys.length||publicInfo?.itemInfo?.forEach((item,i)=>{if(!placeHoldersMap[item.category])return;const contour=item.quadContour??item.contour;if(0===contour.length)return void console.warn(`第${i}个物品轮廓为空`);let itemPoly=new Polygon(contour.map(p2=>Point.from(p2).rotate(json.center,json.angle)));const center=itemPoly.getCenter(),index2=roomPloys.findIndex(poly=>poly.pointWithin(center));if(index2<0)return;try{let newR=itemPoly.getMinimumBoundingRectangle();newR&&(itemPoly=newR)}catch(error){console.warn(`第${i}个物品 转四边形错误`)}const direction=Point.from(item.direction).normalize().rotate(Point.zero(),json.angle);itemPoly[1].distanceSquared(itemPoly[0])<itemPoly[2].distanceSquared(itemPoly[1])&&itemPoly.reverse();const rect=itemPoly.map(p2=>p2.toJson2D());json.placeHolders.push({name:placeHoldersMap[item.category],polygon:rect,direction:direction.toJson2D(),height:item.box.max.z-item.box.min.z,sillHeight:item.box.min.z-z,roomId:rooms[index2].roomTypeId,id:i})}),json}static toThreeVJiaJson(lineSegments,angle=0,updateGroup=!0){let centerVec2=null;lineSegments=LineSegmentUndirectedGraph.rotate(lineSegments.map(line=>line.clone()),angle,(line,center,angle2)=>{centerVec2||(centerVec2={x:center.x,y:center.y}),WallHole.forEachStorageType(line,data=>{data.forEach(item=>{const point2=Point.from(item.p);point2.rotate(center,angle2),item.p=point2.toJson(item.p.z)})})});const heights=[];lineSegments.forEach(line=>{line.userData.isDoor&&heights.push(line.userData.height??0),WallHole.forEachStorageType(line,data=>{heights.push(line.userData.height??0),data.forEach(item=>{const h2=(item.height??0)+(item.groundClearance??0);heights.push(h2)})})}),0===heights.length&&heights.push(2.8);const maxHeight=precision4(Math.max(...heights));updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));const json=new ThreeVJiaPipeline(lineSegments,maxHeight).transform();return json.angle=angle,json.center=centerVec2,json}static mergeParallelLine(json){let map=new ArrayMap;return json.walls.forEach(line=>{map.append(line.thickness.toFixed(4),line)}),json.walls=map.map(list=>{if(1===list.length)return list;const lines=list.map((line,i)=>((line=LineSegment.from(line)).userData=list[i],line));return LineSegmentUtils.mergeCollinearSegmentsAll(lines,(newLine,group2)=>{group2.forEach(line=>Object.assign(newLine.userData,line.userData))}).map(line=>({...line.userData,start:line.start.toJson2D(),end:line.end.toJson2D()}))}).flat(),json}static externalDataToThreeVJia(json,height){let id=0;const cacheJson={version:"2",name:"",center:json.angleCorre.center,angle:json.angleCorre.angle,communityName:"",city:"",province:"",height:height,walls:[],pillars:[],beams:[],holes:[],rooms:[],placeHolders:[]};this.mergeParallelLine(json),json.walls.forEach(wall=>{cacheJson.walls.push({ID:id++,start:wall.start,end:wall.end,thickness:wall.thickness,type:"LINE",isDoor:!1,loadBearingWall:!1,height:height??wall.height})});const point2=Point.zero();json.holes.forEach(hole=>{const data={id:id++,type:"DOOR",start:hole.start,end:hole.end,height:hole.height??2.1,sillHeight:hole.groundClearance??0,groundClearance:hole.groundClearance??0};switch(hole.type){case"door":data.type="DOOR",data.openSide="RIGHT";break;case"window":data.type="WINDOW";break;case"passageEntrance":data.type="WALL_HOLE";break;case"byWindow":if(data.type="BAY_WINDOW",hole.shape){const line2=LineSegment.from(hole);hole.shape.path.forEach(p2=>{point2.copy(p2),data.depth=Math.max(data.depth??0,line2.distanceToPoint(point2))});const center=PointUtils.getCenter(hole.shape.path);data.openSide="left"===line2.getPointSideOfLine(center)?"LEFT":"RIGHT"}break;default:return}cacheJson.holes.push(data)}),json.railings.forEach(railing=>{cacheJson.holes.push({id:id++,type:"RAILING",start:railing.start,end:railing.end,height:railing.height,sillHeight:0,groundClearance:0}),cacheJson.walls.push({ID:id++,start:railing.start,end:railing.end,thickness:railing.thickness,type:"LINE",isDoor:!1,loadBearingWall:!1,height:height??railing.height})}),cacheJson.holes.sort((a2,_)=>"WALL_HOLE"===a2.type?1:-1),json.beams.forEach(beam=>{cacheJson.beams.push({id:id++,start:beam.start,end:beam.end,height:beam.height,thickness:beam.thickness})});const pool2=PointUtils.createPool();json.pillars.forEach(pillar=>{const ploy=new Polygon(pillar.shape.map(p2=>pool2.point.copy(p2)));try{const rect=ploy.getMinimumBoundingRectangle();if(!rect)return;const shape=rect.map(p2=>p2.toJson2D());shape.length=4,cacheJson.pillars.push({polygon:shape})}finally{pool2.freeAll()}});const line=new LineSegment;return cacheJson.walls.forEach(wall=>{line.start.copy(wall.start),line.end.copy(wall.end),line.setLength(line.length+.002),wall.start=line.start.toJson2D(),wall.end=line.end.toJson2D(),wall.thickness!==DEFAULT_WALL_WIDTH&&(wall.thickness+=.002)}),deepPrecision4(cacheJson)}}function mToMm(value){return Number((1e3*value).toFixed(0))}function mmTom(value){return Number((value/1e3).toFixed(4))}function getLineIndexByCenter(targetLines,lines){const grid=Quadtree.from(lines,(_,i)=>({index:i}));return targetLines.map(line=>{const res=grid.queryPoint(line.center);return res.length?res[0].userData.index:-1})}function originalDataToLineData(data){let lineSegments=[],verticalReferenceIndex=-1;const zList=[];data.forEach(({start:start,end:end,...opt},index2)=>{zList.push(start.z??0,end.z??0);const lineSegment=new LineSegment(Point.from(start),Point.from(end));lineSegment.userData=opt,lineSegments.push(lineSegment),opt.uuid&&(lineSegment.uuid=opt.uuid),lineSegment.userData.isWindow&&lineSegment.userData.drawWindow?.forEach(item=>{item.uuid=item.uuid??uuid()}),opt.isVerticalReferenceLine&&(verticalReferenceIndex=index2)});return{originalZAverage:zList.reduce((count,num)=>count+num,0)/zList.length,lineSegments:lineSegments,verticalReferenceIndex:verticalReferenceIndex}}function toOriginalDataItem(line,originalZAverage=0,quadtree,lines){const userData=line.userData,drawWindow=userData.drawWindow,insetionArr=quadtree?quadtree.queryLineSegment(line).filter(r2=>r2.line!==line&&!r2.userData?.isDoor).map(r2=>({index:lines?.indexOf(r2.line)})):[];return{...cloneUserData(userData),start:line.start.toJson(originalZAverage),end:line.end.toJson(originalZAverage),insetionArr:insetionArr,length:line.length,uuid:line.uuid,drawWindow:drawWindow&&drawWindow.map(w=>({...cloneUserData(w),p:{x:w.p.x,y:w.p.y,z:w.p.z}}))}}function lineDataToOriginalData(lines,originalZAverage=0,quadtree){return quadtree||(quadtree=new Quadtree(Box2.fromByLineSegment(...lines)),lines.forEach(line=>quadtree?.insert({line:line,userData:void 0})),Promise.resolve().then(()=>quadtree?.clear())),lines.map(line=>toOriginalDataItem(line,originalZAverage,quadtree,lines))}function deriveLine(line){const newLine=line.clone(!0,!1);return delete newLine.userData.isBalconyRailing,delete newLine.userData.isBayWindow,delete newLine.userData.isBayWindowWin,delete newLine.userData.isDoor,delete newLine.userData.isWindow,delete newLine.userData.isVerticalReferenceLine,WallHole.clear(newLine),newLine}function splitIntersectedLine(lines,minLen=1e-9,opt){const{dedup:dedup=!0,balconyRailing:balconyRailing={filteringRatio:.2},obstacle:obstacle=[]}=opt??{},removeSet=/* @__PURE__ */new Set;return lines=(lines=LineSegmentUtils.splitIntersections(lines,{obstacle:obstacle,onSplit:(line,newLines)=>{try{if(WallHole.splitHole(line,newLines),line.userData.isBayWindow){newLines.sort((a2,b4)=>b4.length-a2.length);for(let i=1;i<newLines.length;i++)newLines[i].userData.isBayWindow=!1}if(balconyRailing&&line.userData.isBalconyRailing){const len=line.length;newLines.forEach(line2=>{line2.length/len<balconyRailing.filteringRatio&&("discard"===opt?.balconyRailing?.behavior?removeSet.add(line2):delete line2.userData.isBalconyRailing)})}}catch(error){console.error(error.message)}}})).filter(line=>line.length>=minLen&&!removeSet.has(line)&&LineSegmentUtils.legitimacy(line)),dedup?LineSegmentUtils.deduplicate(lines,{precision:3}):lines}function mergeChainsLine(lines,callBack,removeLines,newLines){callBack=callBack??mergeLineUserData;let otherLines=[],lines_=[];return lines.forEach(line=>{line.userData.isBalconyRailing||line.userData.isDoor?otherLines.push(line):lines_.push(line)}),(lines=LineSegmentUndirectedGraph.breakpointMerging(lines_,callBack,removeLines,newLines)).push(...otherLines),lines}function clippingLineUserData(newLine,line2){const{drawWindow:drawWindow,passageEntrance:passageEntrance,...opt}=line2.userData;WallHole.forEachStorageType(line2,(data,key)=>{if("drawWindow"===key)return;const removeSet=/* @__PURE__ */new Set;data.forEach((item,i)=>{if("door"!==item.type)return;const point2=Point.from(item.p);newLine.projectPoint(point2)?data[i]=item:removeSet.add(i)}),newLine.userData[key]=data.filter((_,i)=>!removeSet.has(i))}),WallHole.filterIllegal([newLine]),Object.assign(newLine.userData,opt)}function mergeLineUserData(newLine,line2){if(Array.isArray(line2))return(line2=[...line2].sort((a2,b4)=>a2.length-b4.length)).forEach(l=>mergeLineUserData(newLine,l));WallHole.cancelPairing(newLine,line2),!1===line2.userData.isDoor&&delete line2.userData.isDoor,!1===line2.userData.isWindow&&delete line2.userData.isWindow,!1===line2.userData.isBayWindow&&delete line2.userData.isBayWindow,!1===line2.userData.isPassageEntrance&&delete line2.userData.isPassageEntrance,!1===newLine.userData.isPassageEntrance&&delete newLine.userData.isPassageEntrance;const{drawWindow:drawWindow,passageEntrance:passageEntrance,...opt}=line2.userData;Object.keys(opt).forEach(key=>{void 0===opt[key]&&delete opt[key]}),drawWindow&&(newLine.userData.drawWindow||(newLine.userData.drawWindow=[]),newLine.userData.drawWindow.push(...drawWindow)),passageEntrance&&(newLine.userData.passageEntrance||(newLine.userData.passageEntrance=[]),newLine.userData.passageEntrance.push(...passageEntrance)),Object.assign(newLine.userData,opt)}function getDrawingMaxHeight(lineSegments){const heights=[];lineSegments.forEach(line=>{line.userData.isDoor&&heights.push(line.userData.height??0),WallHole.forEachStorageType(line,data=>{heights.push(line.userData.height??0),data.forEach(item=>{const h2=(item.height??0)+(item.groundClearance??0);heights.push(h2)})})}),0===heights.length&&heights.push(2.8);return precision4(Math.max(...heights))}function deepPrecision4(value){return"number"==typeof value?Number(value.toFixed(4)):Array.isArray(value)?(value.forEach((item,index2)=>{value[index2]=deepPrecision4(item)}),value):(value&&"object"==typeof value&&Object.keys(value).forEach(key=>{value[key]=deepPrecision4(value[key])}),value)}const tools=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ThreeVJiaPipeline:ThreeVJiaPipeline,WallGroupManager:WallGroupManager,clippingLineUserData:clippingLineUserData,deepPrecision4:deepPrecision4,deriveLine:deriveLine,findBoundExt:async function(lines,trajectorys,originalZAverage=0){const{promise:promise2,resolve:resolve,reject:reject}=createPromise(),url=new URL("data:video/mp2t;base64,DQppbXBvcnQgeyBERUZBVUxUX1dBTExfV0lEVEggfSBmcm9tICJAL2NvbnN0YW50cyINCmltcG9ydCB7IEJvdW5kRXh0IH0gZnJvbSAiLi9Cb3VuZEV4dCINCmltcG9ydCB7IG9yaWdpbmFsRGF0YVRvTGluZURhdGEgfSBmcm9tICIuL3Rvb2xzIg0KDQpzZWxmLm9ubWVzc2FnZSA9IChlKSA9PiB7DQogICAgY29uc3QgeyBsaW5lcywgdHJhamVjdG9yeXMsIG9yaWdpbmFsWkF2ZXJhZ2UgfSA9IEpTT04ucGFyc2UoZS5kYXRhKQ0KICAgIGNvbnN0IGxpbmVTZWdtZW50cyA9IG9yaWdpbmFsRGF0YVRvTGluZURhdGEobGluZXMpLmxpbmVTZWdtZW50cw0KDQogICAgY29uc3QgZGF0YSA9IEJvdW5kRXh0LmJvdW5kRXh0YnlUcmFqKHsNCiAgICAgICAgbGluZXM6IGxpbmVTZWdtZW50cywgDQogICAgICAgIHRyYWplY3Rvcnk6IHRyYWplY3RvcnlzLA0KICAgICAgICB3YWxsV2lkdGg6IERFRkFVTFRfV0FMTF9XSURUSA0KICAgIH0pLnRvT3JpZ2luYWxEYXRhKG9yaWdpbmFsWkF2ZXJhZ2UpDQoNCiAgICBzZWxmLnBvc3RNZXNzYWdlKEpTT04uc3RyaW5naWZ5KGRhdGEpKQ0KfQ==",import.meta.url),data=lineDataToOriginalData(lines),worker=new Worker(url,{type:"module"});return worker.onerror=err=>{reject({err:err,url:url})},worker.onmessage=e=>{const data2=JSON.parse(e.data);resolve(originalDataToLineData(data2).lineSegments)},worker.postMessage(JSON.stringify({lines:data,trajectorys:trajectorys,originalZAverage:originalZAverage})),promise2},getDrawingMaxHeight:getDrawingMaxHeight,getLineIndexByCenter:getLineIndexByCenter,innerWallLine:function(lines,trajectory2){lines=lines.filter(line=>!line.userData.isBayWindow),lines=LineSegmentUtils.clone(lines),lines=BuildGroup.doubleWall(lines);let outerLines=[];if(trajectory2){const trajectoryPoints=Object.values(trajectory2).map(v2=>Point.from(v2));outerLines=BoundExt.findExtWallByTraj(lines,trajectoryPoints);const outerLinesSet=new Set(outerLines);lines=lines.filter(line=>!outerLinesSet.has(line)),outerLines=outerLines.filter(line=>line.userData.expandDirect)}else{outerLines=lines.filter(line=>line.userData.expandDirect);const outerLinesSet=new Set(outerLines);lines=lines.filter(line=>!outerLinesSet.has(line))}const manager=WallGroupManager.fromByLines(lines),pipeline=new Pipeline;pipeline.use("doubleWall",ctx=>{ctx.cache.doubleWall.push(ctx.data)}),pipeline.use(["wall","bayWindow","door","window"],ctx=>{const lines2=ctx.data.filter(line=>!LineGroupType.hasType(line,"doubleWall"));ctx.cache.lines.push(...lines2)});const option={doubleWall:[],lines:[]};manager.forEach(group2=>pipeline.run(group2.type,group2.lines,option));const lud=new LineSegmentUndirectedGraph(option.lines),temLine=new LineSegment;let singleLine=[];const wallWidths=[];lud.forEachPathLine((start,end,_line,index2,endType,indxeList)=>{temLine.start.copy(start),temLine.end.copy(end);const wallWidth=DEFAULT_WALL_WIDTH;wallWidths[index2]=wallWidth;const hw=indxeList.length?.5*Math.max(...indxeList.map(i=>wallWidths[i])):.5*wallWidth;0!==index2&&temLine.offsetStart(hw),"none"===endType&&temLine.offsetEnd(-hw),singleLine.push(...temLine.setLength(temLine.length+1e-4).toRectangle(wallWidth,"butt").toLines())});const paths=Polygon.multipleFromByLines(singleLine);if(paths.length>1){const[p1,...pn2]=paths;singleLine=Polygon.booleanOp(p1,pn2,{type:"Union",scale:1e4}).flatMap(p2=>p2.toLines())}singleLine=singleLine.filter(line=>line.length>.2),singleLine=LineSegmentUtils.deduplicate(LineSegmentUtils.splitIntersections(singleLine,{obstacle:option.doubleWall.flat()}));const polys=option.doubleWall.map(lines2=>Polygon.fromByLines2(lines2));return singleLine=singleLine.filter(line=>{const center=line.center;return!polys.find(poly=>poly.pointIn(center))}),[...singleLine,...option.doubleWall.flat(),...outerLines]},lineDataToOriginalData:lineDataToOriginalData,mToMm:mToMm,mergeChainsLine:mergeChainsLine,mergeGltf:async function(paths,binary=!0){await GltfInit();const load2=new gltf.GLTFLoader,onject3dList=await Promise.all(paths.map(path=>load2.loadAsync(path))),group2=new Group$1;return onject3dList.map(g=>group2.add(g.scene)),(new gltf.GLTFExporter).parseAsync([group2],{binary:binary})},mergeLineUserData:mergeLineUserData,mmTom:mmTom,originalDataToLineData:originalDataToLineData,splitIntersectedLine:splitIntersectedLine,toOriginalDataItem:toOriginalDataItem},Symbol.toStringTag,{value:"Module"})),units={Unitless:1,Inches:39.37007874015748,Feet:3.280839895013123,Miles:.0006213711922373339,Millimeters:1e3,Centimeters:100,Meters:1,Kilometers:.001,Microinches:39370078.74015748,Mils:39370.07874015748,Yards:1.0936132983377078,Angstroms:1e10,Nanometers:1e9,Microns:1e6,Decimeters:10,Decameters:.1,Hectometers:.01,Gigameters:1e-9,"Astronomical units":6684587122268445e-27,"Light years":10570008340246154e-32,Parsecs:3240779289666404e-32};function toDrawData(unit="Centimeters"){if(!this.needUpdate&&this._cachedDrawDataMap.has(unit))return this._cachedDrawDataMap.get(unit);this._cachedDrawDataMap.clear(),this.needUpdate=!1;const lines=this.groups.flatMap(group2=>group2.lines),s=units[unit],box=Box2.fromByLineSegment(...lines).expansion(1),data={unit:unit,entitys:[],center:box.center.clone().multiplyScalar(s).toJson(),width:box.width*s,height:box.height*s,scale:s};let color="white";function drawText2(str,p2,opt){data.entitys.push({type:"text",text:str,center:{x:p2.x*s,y:p2.y*s},color:opt?.color??color,rotation:opt?.rotation??0,fontSize:.1*s})}function drawLine(p1,p2,opt){data.entitys.push({type:"line",start:{x:p1.x*s,y:p1.y*s},end:{x:p2.x*s,y:p2.y*s},color:opt?.color??color})}function drawDottedLine(p1,p2,opt){const{dash:dash=.04,gap:gap=.05}=opt??{},distance2=dash+gap;let current=0;const direction=p2.directionFrom(p1),length=p1.distance(p2);for(;current<length;){const dashEnd=Math.min(current+dash,length);drawLine(p1.clone().add(direction.clone().multiplyScalar(current)),p1.clone().add(direction.clone().multiplyScalar(dashEnd))),current+=distance2}}function drawArc(pos,radius,startAngle,endAngle,opt){data.entitys.push({type:"arc",center:{x:pos.x*s,y:pos.y*s},color:opt?.color??color,radius:radius*s,startAngle:startAngle,endAngle:endAngle})}function drawPolygonFill(path,opt){data.entitys.push({type:"polygon-fill",path:path.map(p2=>({x:p2.x*s,y:p2.y*s})),color:opt?.color??color})}return this.groups.forEach(group2=>{const set2=this._drawHandlerMap.get(group2.type);if(!set2)return;const option={group:group2,drawArc:drawArc,drawLine:drawLine,drawDottedLine:drawDottedLine,drawText:drawText2,drawPolygonFill:drawPolygonFill,setColor(c){color=c}};set2.forEach(fun=>fun.handler(option))}),this._cachedDrawDataMap.set(unit,data),data}const steiners=/* @__PURE__ */new Set;let filteredOut=!1;function earcut(data,holeIndices,dim=2){const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;steiners.size&&steiners.clear();let outerNode=linkedList(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX=0,minY=0,invSize=0;if(hasHoles&&(outerNode=function(data,holeIndices,outerNode,dim){const queue=[];for(let i=0,len=holeIndices.length;i<len;i++){const list=linkedList(data,holeIndices[i]*dim,i<len-1?holeIndices[i+1]*dim:data.length,dim,!1);list===list.next&&steiners.add(list),queue.push(getLeftmost(list))}queue.sort(compareXYSlope),function(maxNodes,numHoles){const maxBlocks=Math.ceil((maxNodes+2*numHoles)/K$1)+numHoles+2;blockBBox.length<4*maxBlocks&&(blockBBox=new Float64Array(4*maxBlocks));numBlocks=0}(data.length/dim,holeIndices.length),indexSegment(outerNode,outerNode),indexActive=!0;for(let i=0;i<queue.length;i++)outerNode=eliminateHole(queue[i],outerNode);return indexActive=!1,filterPoints(outerNode)}(data,holeIndices,outerNode,dim)),data.length>80*dim){minX=data[0],minY=data[1];let maxX=minX,maxY=minY;for(let i=dim;i<outerLen;i+=dim){const x=data[i],y=data[i+1];x<minX&&(minX=x),y<minY&&(minY=y),x>maxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?32767/invSize:0}return earcutLinked(outerNode,triangles,minX,minY,invSize),triangles}function linkedList(data,start,end,dim,clockwise){let last=null;if(clockwise===function(data,start,end,dim){let sum2=0;for(let i=start,j=end-dim;i<end;i+=dim)sum2+=(data[j]-data[i])*(data[i+1]+data[j+1]),j=i;return sum2}(data,start,end,dim)>0)for(let i=start;i<end;i+=dim)last=insertNode$1(i/dim|0,data[i],data[i+1],last);else for(let i=end-dim;i>=start;i-=dim)last=insertNode$1(i/dim|0,data[i],data[i+1],last);return last&&equals(last,last.next)&&(removeNode(last),last=last.next),last}function filterPoints(start,end=start){const full=end===start;let again,p2=start;do{again=!1,p2===p2.next||0!==steiners.size&&steiners.has(p2)||!equals(p2,p2.next)&&0!==area(p2.prev,p2,p2.next)?(full||p2!==end)&&(p2=p2.next,again=!full):((full||p2===end)&&(end=p2.prev),filteredOut=!0,removeNode(p2),p2=p2.prev,again=!0)}while(again||p2!==end);return end}function earcutLinked(ear,triangles,minX,minY,invSize){invSize&&function(start,minX,minY,invSize){let p2=start,n=0;do{p2.z=zOrder(p2.x,p2.y,minX,minY,invSize),sortArr[n++]=p2,p2=p2.next}while(p2!==start);!function(n){if(n<=32){for(let i=1;i<n;i++){const node=sortArr[i],z=node.z;let j=i-1;for(;j>=0&&sortArr[j].z>z;)sortArr[j+1]=sortArr[j],j--;sortArr[j+1]=node}return}zArr.length<n&&(zArr=new Uint32Array(n),zBuf=new Uint32Array(n),sortBuf=new Array(n));for(let i=0;i<n;i++)zArr[i]=sortArr[i].z;radixPass(n,sortArr,zArr,sortBuf,zBuf,0),radixPass(n,sortBuf,zBuf,sortArr,zArr,8),radixPass(n,sortArr,zArr,sortBuf,zBuf,16),radixPass(n,sortBuf,zBuf,sortArr,zArr,24)}(n);let prev=null;for(let i=0;i<n;i++){const node=sortArr[i];node.prevZ=prev,prev&&(prev.nextZ=node),prev=node}prev.nextZ=null}(ear,minX,minY,invSize);let stop=ear,cured=!1;for(;ear.prev!==ear.next;){const prev=ear.prev,next=ear.next;if(area(prev,ear,next)<0&&(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)))triangles.push(prev.i,ear.i,next.i),removeNode(ear),ear=next,stop=next;else if((ear=next)===stop){if(filteredOut=!1,ear=filterPoints(ear),filteredOut){stop=ear;continue}if(!cured){stop=ear=cureLocalIntersections(ear,triangles),cured=!0;continue}splitEarcut(ear,triangles,minX,minY,invSize);break}}}function isEar(ear){const a2=ear.prev,b4=ear,c=ear.next,ax=a2.x,bx=b4.x,cx=c.x,ay=a2.y,by=b4.y,cy=c.y,x0=Math.min(ax,bx,cx),y0=Math.min(ay,by,cy),x1=Math.max(ax,bx,cx),y1=Math.max(ay,by,cy);let p2=c.next;for(;p2!==a2;){if(p2.x>=x0&&p2.x<=x1&&p2.y>=y0&&p2.y<=y1&&(ax!==p2.x||ay!==p2.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,p2.x,p2.y)&&area(p2.prev,p2,p2.next)>=0)return!1;p2=p2.next}return!0}function isEarHashed(ear,minX,minY,invSize){const a2=ear.prev,b4=ear,c=ear.next,ax=a2.x,bx=b4.x,cx=c.x,ay=a2.y,by=b4.y,cy=c.y,x0=Math.min(ax,bx,cx),y0=Math.min(ay,by,cy),x1=Math.max(ax,bx,cx),y1=Math.max(ay,by,cy),minZ=zOrder(x0,y0,minX,minY,invSize),maxZ=zOrder(x1,y1,minX,minY,invSize);let p2=ear.prevZ;for(;p2&&p2.z>=minZ;){if(p2.x>=x0&&p2.x<=x1&&p2.y>=y0&&p2.y<=y1&&p2!==c&&(ax!==p2.x||ay!==p2.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,p2.x,p2.y)&&area(p2.prev,p2,p2.next)>=0)return!1;p2=p2.prevZ}let n=ear.nextZ;for(;n&&n.z<=maxZ;){if(n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==c&&(ax!==n.x||ay!==n.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0}function cureLocalIntersections(start,triangles){let p2=start,cured=!1;do{const a2=p2.prev,b4=p2.next.next;intersects$2(a2,p2,p2.next,b4,!1)&&locallyInside(a2,b4)&&locallyInside(b4,a2)&&(triangles.push(a2.i,p2.i,b4.i),removeNode(p2),removeNode(p2.next),p2=start=b4,cured=!0),p2=p2.next}while(p2!==start);return cured?filterPoints(p2):p2}function splitEarcut(start,triangles,minX,minY,invSize){let a2=start;do{let b4=a2.next.next;for(;b4!==a2.prev;){if(a2.i!==b4.i&&isValidDiagonal(a2,b4)){let c=splitPolygon(a2,b4);return a2=filterPoints(a2,a2.next),c=filterPoints(c,c.next),earcutLinked(a2,triangles,minX,minY,invSize),void earcutLinked(c,triangles,minX,minY,invSize)}b4=b4.next}a2=a2.next}while(a2!==start)}let indexActive=!1;function compareXYSlope(a2,b4){return a2.x-b4.x||a2.y-b4.y||(a2.next.y-a2.y)/(a2.next.x-a2.x)-(b4.next.y-b4.y)/(b4.next.x-b4.x)}function eliminateHole(hole,outerNode){const bridge=function(hole,outerNode){let p2=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;if(equals(hole,p2))return p2;for(let b4=0,g=0;b4<numBlocks;b4++,g+=4){if(hy<blockBBox[g+1]||hy>blockBBox[g+3]||blockBBox[g]>hx||blockBBox[g+2]<=qx)continue;const stop=liveBlockStop(b4);p2=liveBlockHead(b4);do{if(p2.prev.next===p2){if(equals(hole,p2.next))return p2.next;if(hy<=p2.y&&hy>=p2.next.y&&p2.next.y!==p2.y){const x=p2.x+(hy-p2.y)*(p2.next.x-p2.x)/(p2.next.y-p2.y);if(x<=hx&&x>qx&&(qx=x,m=p2.x<p2.next.x?p2:p2.next,x===hx))return m}}p2=p2.next}while(p2!==stop)}if(!m)return null;const mx=m.x,my=m.y,tminY=Math.min(hy,my),tmaxY=Math.max(hy,my);let tanMin=1/0;for(let b4=0,g=0;b4<numBlocks;b4++,g+=4){if(blockBBox[g+2]<mx||blockBBox[g]>hx||blockBBox[g+3]<tminY||blockBBox[g+1]>tmaxY)continue;const stop=liveBlockStop(b4);p2=liveBlockHead(b4);do{if(p2.prev.next===p2&&hx>=p2.x&&p2.x>=mx&&hx!==p2.x&&pointInTriangle(hy<my?hx:qx,hy,mx,my,hy<my?qx:hx,hy,p2.x,p2.y)){const tan=Math.abs(hy-p2.y)/(hx-p2.x);(locallyInside(p2,hole)||p2.y===hy&&p2.next.y===hy&&p2.next.x>hx)&&(tan<tanMin||tan===tanMin&&(p2.x>m.x||p2.x===m.x&§orContainsSector(m,p2)))&&(m=p2,tanMin=tan)}p2=p2.next}while(p2!==stop)}return m}(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole);return indexSegment(bridge,bridgeReverse.next.next),filterPoints(bridgeReverse,bridgeReverse.next),filterPoints(bridge,bridge.next)}const K$1=16;let blockBBox=new Float64Array(0),numBlocks=0;const blockHead=[],blockStop=[];function indexSegment(head,stop){let p2=head;do{const b4=numBlocks++;blockHead[b4]=p2;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,k=0;do{const c=p2.next;p2.z=b4,p2.x<minX&&(minX=p2.x),p2.x>maxX&&(maxX=p2.x),p2.y<minY&&(minY=p2.y),p2.y>maxY&&(maxY=p2.y),c.x<minX&&(minX=c.x),c.x>maxX&&(maxX=c.x),c.y<minY&&(minY=c.y),c.y>maxY&&(maxY=c.y),p2=c}while(++k<K$1&&p2!==stop);blockStop[b4]=p2;const g=4*b4;blockBBox[g]=minX,blockBBox[g+1]=minY,blockBBox[g+2]=maxX,blockBBox[g+3]=maxY}while(p2!==stop)}function liveBlockStop(b4){let stop=blockStop[b4];for(;stop.prev.next!==stop;)stop=stop.next;return blockStop[b4]=stop,stop}function liveBlockHead(b4){let head=blockHead[b4];for(;head.prev.next!==head;)head=head.next;return blockHead[b4]=head,head}function sectorContainsSector(m,p2){return area(m.prev,m,p2.prev)<0&&area(p2.next,m,m.next)<0}const sortArr=[];let sortBuf=[],zArr=new Uint32Array(0),zBuf=new Uint32Array(0);const counts=new Uint32Array(256);function radixPass(n,src,srcZ,dst,dstZ,shift){counts.fill(0);for(let i=0;i<n;i++)counts[srcZ[i]>>>shift&255]++;let sum2=0;for(let b4=0;b4<256;b4++){const c=counts[b4];counts[b4]=sum2,sum2+=c}for(let i=0;i<n;i++){const z=srcZ[i],pos=counts[z>>>shift&255]++;dst[pos]=src[i],dstZ[pos]=z}}function zOrder(x,y,minX,minY,invSize){return(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=(x-minX)*invSize|0)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=(y-minY)*invSize|0)|y<<8))|y<<4))|y<<2))|y<<1))<<1}function getLeftmost(start){let p2=start,leftmost=start;do{(p2.x<leftmost.x||p2.x===leftmost.x&&p2.y<leftmost.y)&&(leftmost=p2),p2=p2.next}while(p2!==start);return leftmost}function pointInTriangle(ax,ay,bx,by,cx,cy,px,py){return(cx-px)*(ay-py)>=(ax-px)*(cy-py)&&(ax-px)*(by-py)>=(bx-px)*(ay-py)&&(bx-px)*(cy-py)>=(cx-px)*(by-py)}function isValidDiagonal(a2,b4){const zeroLength=equals(a2,b4)&&area(a2.prev,a2,a2.next)>0&&area(b4.prev,b4,b4.next)>0;return a2.next.i!==b4.i&&(zeroLength||locallyInside(a2,b4)&&locallyInside(b4,a2)&&(0!==area(a2.prev,a2,b4.prev)||0!==area(a2,b4.prev,b4)))&&!function(a2,b4){const minX=Math.min(a2.x,b4.x),maxX=Math.max(a2.x,b4.x),minY=Math.min(a2.y,b4.y),maxY=Math.max(a2.y,b4.y);let p2=a2;do{const n=p2.next;if(p2.x>maxX&&n.x>maxX||p2.x<minX&&n.x<minX||p2.y>maxY&&n.y>maxY||p2.y<minY&&n.y<minY)p2=n;else{if(p2.i!==a2.i&&n.i!==a2.i&&p2.i!==b4.i&&n.i!==b4.i&&intersects$2(p2,n,a2,b4))return!0;p2=n}}while(p2!==a2);return!1}(a2,b4)&&(zeroLength||function(a2,b4){let p2=a2,inside2=!1;const px=(a2.x+b4.x)/2,py=(a2.y+b4.y)/2;do{const n=p2.next;p2.y>py!=n.y>py&&px<(n.x-p2.x)*(py-p2.y)/(n.y-p2.y)+p2.x&&(inside2=!inside2),p2=n}while(p2!==a2);return inside2}(a2,b4))}function area(p2,q,r2){return(q.y-p2.y)*(r2.x-q.x)-(q.x-p2.x)*(r2.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}function intersects$2(p1,q1,p2,q2,includeBoundary=!0){const o1=area(p1,q1,p2),o2=area(p1,q1,q2),o3=area(p2,q2,p1),o4=area(p2,q2,q1);return(o1>0&&o2<0||o1<0&&o2>0)&&(o3>0&&o4<0||o3<0&&o4>0)||!!includeBoundary&&(!(0!==o1||!onSegment(p1,p2,q1))||(!(0!==o2||!onSegment(p1,q2,q1))||(!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2)))))}function onSegment(p2,q,r2){return q.x<=Math.max(p2.x,r2.x)&&q.x>=Math.min(p2.x,r2.x)&&q.y<=Math.max(p2.y,r2.y)&&q.y>=Math.min(p2.y,r2.y)}function locallyInside(a2,b4){return area(a2.prev,a2,a2.next)<0?area(a2,b4,a2.next)>=0&&area(a2,a2.prev,b4)>=0:area(a2,b4,a2.prev)<0||area(a2,a2.next,b4)<0}function splitPolygon(a2,b4){const a22=createNode$1(a2.i,a2.x,a2.y),b22=createNode$1(b4.i,b4.x,b4.y),an2=a2.next,bp=b4.prev;return a2.next=b4,b4.prev=a2,a22.next=an2,an2.prev=a22,b22.next=a22,a22.prev=b22,bp.next=b22,b22.prev=bp,b22}function insertNode$1(i,x,y,last){const p2=createNode$1(i,x,y);return last?(p2.next=last.next,p2.prev=last,last.next.prev=p2,last.next=p2):(p2.prev=p2,p2.next=p2),p2}function removeNode(p2){p2.next.prev=p2.prev,p2.prev.next=p2.next,p2.prevZ&&(p2.prevZ.nextZ=p2.nextZ),p2.nextZ&&(p2.nextZ.prevZ=p2.prevZ),indexActive&&function(head,tail){const g=4*head.z;tail.x<blockBBox[g]&&(blockBBox[g]=tail.x),tail.y<blockBBox[g+1]&&(blockBBox[g+1]=tail.y),tail.x>blockBBox[g+2]&&(blockBBox[g+2]=tail.x),tail.y>blockBBox[g+3]&&(blockBBox[g+3]=tail.y)}(p2.prev,p2.next)}function createNode$1(i,x,y){return{i:i,x:x,y:y,prev:null,next:null,z:0,prevZ:null,nextZ:null}}const colors={cyan:"cyan",yellow:"yellow",white:"white",gray:"#c9c9c9",green:"green",deepgreen:"#006400",red:"red",blue:"#2c2cff",deepblue:"#0001bb",text:"#ffffff",ruler:"green",ruler_deep:"#006400"},getColor=color=>colors[color??""]??color??"#fff";class Group{type="";userData={color:"#fff"};constructor(lines=[],type="",userData={}){this.type=type,this.addLine(...lines),Object.assign(this.userData,userData)}lines=[];addLine(...arg){this.lines.push(...arg)}removeLine(...lines){if(0===lines.length)return;if(1===lines.length){const index2=this.lines.indexOf(lines[0]);return void this.lines.splice(index2,1)}const set2=new Set(lines);this.lines=this.lines.filter(line=>!set2.has(line))}clone(){const group2=new this.constructor;return group2.type=this.type,group2.lines=this.lines.map(line=>line.clone()),Object.assign(group2.userData,this.userData),group2}}class CAD{groups=[];_drawHandlerMap=new SetMap;needUpdate=!0;getAllLines(){return this.groups.flatMap(group2=>group2.lines)}addGroup(lines,type="",userData={}){const group2=new Group(lines,type,userData);return this.groups.push(group2),this.needUpdate=!0,group2}addGroups(groups,type=""){return this.needUpdate=!0,groups.map(lines=>this.addGroup(lines,type))}addGroupAndOffset(lines,option){const{offsetHalfWidth:offsetHalfWidth=.5*DEFAULT_WALL_WIDTH,joinType:joinType="jtMiter",endType:endType="etOpenButt",type:type="groupOffset",scale:scale2=1e5}=option??{};let offsetPolygons=LineSegmentUtils.groupBySharedPoints(lines).flatMap(group2=>Polygon.multipleFromByLines(group2)).map(polygon2=>Polygon.offset(polygon2,{offsetHalfWidth:offsetHalfWidth,scale:scale2,joinType:joinType,endType:endType})).filter(Boolean);if(offsetPolygons.length>1){const[first,...other]=offsetPolygons;offsetPolygons=Polygon.booleanOp(first,other,{type:"Union",scale:scale2})}return offsetPolygons.forEach(polygon2=>{let lines2=mergeChainsLine(polygon2.toLines(!0));lines2.forEach(line=>line.extendAlongDirection(.001)),lines2=splitIntersectedLine(lines2,1e-9);const set2=findDiscretePointLine2(lines2);lines2=lines2.filter(line=>!set2.has(line)),this.addGroup(lines2,type,{polygon:polygon2})}),this.needUpdate=!0,this}removeGroup(group2){const index2=this.groups.indexOf(group2);return index2>-1&&this.groups.splice(index2,1),this.needUpdate=!0,group2}filterGroups(fun){const groups=[];return this.groups=this.groups.filter(group2=>{const b4=fun(group2);return b4||groups.push(group2),b4}),groups}findGroups(fun){const groups=[];return this.groups.forEach(group2=>{fun(group2)&&groups.push(group2)}),groups}unionGroup(fun,opt){const{type:type="unionGroupAll",connectingBridge:connectingBridge=!0,threshold:threshold=.1}=opt??{},groups=[];this.groups=this.groups.filter(group2=>{const b4=fun(group2);return b4&&groups.push(group2),!b4});const polys=[],lines=groups.flatMap(group2=>(group2.userData.polygon?polys.push(group2.userData.polygon):polys.push(...Polygon.multipleFromByLines(group2.lines)),group2.lines)),quadtree=Quadtree.from(lines),temLine=new LineSegment,visited=/* @__PURE__ */new Set;if(connectingBridge)for(let i=0;i<lines.length;i++){const line=lines[i],len=line.length;temLine.copy(line);const rectangle=temLine.extendAlongDirection(.01*len).toRectangle(2*threshold,"butt"),results=quadtree.queryRect(rectangle).filter(result=>result.line!==line&&!visited.has(result.line)&&result.line.isParallelTo(line)).sort((a2,b4)=>b4.line.length-a2.line.length);if(results.length){const resultLine=results[0].line,pl1=resultLine.projectLineSegment(line),pl2=line.projectLineSegment(resultLine),pLine=pl1.length>pl2.length?pl1:pl2;polys.push(new Polygon(pLine.toRectangle(2*threshold,"butt").points).close())}visited.add(line),quadtree.remove(line)}if(0===polys.length)return;const[first,...rest]=polys;Polygon.booleanOp(first,rest??[],{type:"Union",scale:1e3}).forEach(polygon2=>{this.addGroup(polygon2.toLines(!0),type,{polygon:polygon2})}),this.needUpdate=!0}unionGroupAll(type="unionGroupAll",threshold=.01){this.unionGroup(_=>!0,{type:type,threshold:threshold})}rotate(angle){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(...lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.rotate(angle,center)})),this.needUpdate=!0}resetOrigin(){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(...lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.start.subtract(center),line.end.subtract(center)})),this.needUpdate=!0}rotateAndResetOrigin(angle){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(...lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.rotate(angle,center),line.start.subtract(center),line.end.subtract(center)})),this.needUpdate=!0}addDrawHandler(handler){handler.type.forEach(type=>{this._drawHandlerMap.append(type,handler)}),this.needUpdate=!0}_cachedDrawDataMap=/* @__PURE__ */new Map;toDrawData(unit="Centimeters"){return toDrawData.call(this,unit)}async toDxfImageBlob(unit="Centimeters",type="image/jpeg",background="#000"){return async function(data,type="image/jpeg",background="#000"){const margin=0*data.scale;let canvas;if("undefined"!=typeof window)canvas=document.createElement("canvas");else{if("undefined"==typeof global)throw new Error("创建画布失败");{const{createCanvas:createCanvas}=await include("canvas");canvas=createCanvas(data.width+2*margin,data.height+2*margin)}}const colors2={cyan:"cyan",yellow:"yellow",white:"white",gray:"#c9c9c9",green:"green",deepgreen:"#006400",red:"red",blue:"#2c2cff",deepblue:"#0001bb",text:"#ffffff",ruler:"green",ruler_deep:"#006400"};canvas.width=data.width+2*margin,canvas.height=data.height+2*margin;const ctx=canvas.getContext("2d");return background&&(ctx.fillStyle=background,ctx.fillRect(0,0,canvas.width,canvas.height)),ctx.translate(-data.center.x+.5*data.width+margin,data.center.y+.5*data.height+margin),ctx.scale(1,-1),data.entitys.forEach(entity=>{switch(entity.type){case"line":ctx.strokeStyle=colors2[entity.color]??entity.color,ctx.beginPath(),ctx.moveTo(entity.start.x,entity.start.y),ctx.lineTo(entity.end.x,entity.end.y),ctx.closePath(),ctx.stroke();break;case"arc":ctx.strokeStyle=colors2[entity.color],ctx.beginPath(),ctx.arc(entity.center.x,entity.center.y,entity.radius,entity.startAngle*(Math.PI/180),entity.endAngle*(Math.PI/180)),ctx.stroke();break;case"dotted-line":ctx.beginPath(),ctx.moveTo(entity.start.x,entity.start.y),ctx.lineTo(entity.end.x,entity.end.y),ctx.setLineDash([entity.dash,entity.gap]),ctx.strokeStyle=colors2[entity.color],ctx.lineWidth=1,ctx.stroke(),ctx.setLineDash([]);break;case"text":ctx.fillStyle=colors2[entity.color]??entity.color??"#fff",ctx.font=`${entity.fontSize}px Arial`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.save(),ctx.translate(entity.center.x,entity.center.y),ctx.rotate(Math.PI/180*entity.rotation),ctx.scale(1,-1),ctx.letterSpacing=.1*entity.fontSize+"px",ctx.fillText(entity.text,0,0),ctx.restore();break;case"polygon-fill":ctx.fillStyle=colors2[entity.color]??entity.color??"#fff",ctx.save(),ctx.beginPath(),entity.path.forEach((p2,i)=>{0===i?ctx.moveTo(p2.x,p2.y):ctx.lineTo(p2.x,p2.y)}),ctx.closePath(),ctx.fill(),ctx.restore()}}),"toBlob"in canvas?new Promise(resolve=>{canvas.toBlob(b4=>{resolve(b4)},type,1)}):canvas.toBuffer(type,{quality:1})}(this.toDrawData(unit),type,background)}async downloadDxfImage(filename,unit="Centimeters",type="image/jpeg"){const blob=await this.toDxfImageBlob(unit,type);if(!blob)return!1;if("undefined"!=typeof window){const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,blob)}else console.error("图片下载失败");return!0}toDxfString(unit="Millimeters"){return function(data,unit="Millimeters"){const drawing=new Drawing;drawing.setUnits(unit);const ACI={cyan:Drawing.ACI.CYAN,yellow:Drawing.ACI.YELLOW,white:Drawing.ACI.WHITE,green:Drawing.ACI.GREEN,deepgreen:83,red:Drawing.ACI.RED,gray:9,blue:Drawing.ACI.BLUE,deepblue:175,text:Drawing.ACI.WHITE,ruler:Drawing.ACI.GREEN,ruler_deep:83};Object.keys({cyan:65535,yellow:16776960,white:16777215,green:65280,deepgreen:25600,red:16711680,gray:13224393,blue:2895103,deepblue:443,text:16777215,ruler:65280,ruler_deep:25600}).forEach(key=>{drawing.addLayer(`${key}_CONTINUOUS`,ACI[key],"CONTINUOUS"),drawing.addLayer(`${key}_DASHED`,ACI[key],"DASHED"),drawing.setActiveLayer(key)});const setColor=(c,lineType="CONTINUOUS")=>{drawing.setActiveLayer(`${c}_${lineType}`)};return data.entitys.forEach(entity=>{switch(entity.type){case"line":setColor(entity.color),drawing.drawLine(entity.start.x,entity.start.y,entity.end.x,entity.end.y);break;case"arc":setColor(entity.color),drawing.drawArc(entity.center.x,entity.center.y,entity.radius,entity.startAngle,entity.endAngle);break;case"dotted-line":break;case"polygon-fill":setColor(entity.color);const faceIndex=earcut(entity.path.flatMap(p2=>[p2.x,p2.y]),null,2);for(let i=0;i<faceIndex.length;i+=3){const p1=entity.path[faceIndex[i]],p2=entity.path[faceIndex[i+1]],p3=entity.path[faceIndex[i+2]];drawing.drawFace(p1.x,p1.y,0,p2.x,p2.y,0,p3.x,p3.y,0,p1.x,p1.y,0)}break;case"text":setColor(entity.color),drawing.drawText(entity.center.x,entity.center.y,entity.fontSize,entity.rotation,entity.text,"center","middle")}}),drawing.toDxfString()}(this.toDrawData(unit),unit)}toDxfBlob(unit="Millimeters"){return new Blob([this.toDxfString(unit)])}async downloadDxf(filename,unit="Millimeters"){if("undefined"!=typeof window){const blob=this.toDxfBlob(unit),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename+".dxf",a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,this.toDxfString(unit))}}toDxfObject3D(unit="Millimeters"){return function(data){const root=new THREE.Group;return data.entitys.forEach(entity=>{switch(entity.type){case"line":{const geometry=(new THREE.BufferGeometry).setFromPoints([new THREE.Vector3(entity.start.x,entity.start.y,0),new THREE.Vector3(entity.end.x,entity.end.y,0)]);root.add(new THREE.Line(geometry,new THREE.LineBasicMaterial({color:getColor(entity.color)})));break}case"arc":{const curve=new THREE.ArcCurve(entity.center.x,entity.center.y,entity.radius,THREE.MathUtils.degToRad(entity.startAngle),THREE.MathUtils.degToRad(entity.endAngle)),geometry=(new THREE.BufferGeometry).setFromPoints(curve.getPoints(Math.max(16,Math.ceil(Math.abs(entity.endAngle-entity.startAngle)/5))).map(p2=>new THREE.Vector3(p2.x,p2.y,0)));root.add(new THREE.Line(geometry,new THREE.LineBasicMaterial({color:getColor(entity.color)})));break}case"dotted-line":{const geometry=(new THREE.BufferGeometry).setFromPoints([new THREE.Vector3(entity.start.x,entity.start.y,0),new THREE.Vector3(entity.end.x,entity.end.y,0)]),line=new THREE.Line(geometry,new THREE.LineDashedMaterial({color:getColor(entity.color),dashSize:entity.dash,gapSize:entity.gap}));line.computeLineDistances(),root.add(line);break}case"text":break;case"polygon-fill":{const shape=new THREE.Shape;entity.path.forEach((p2,i)=>0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y)),shape.closePath(),root.add(new THREE.Mesh(new THREE.ShapeGeometry(shape),new THREE.MeshBasicMaterial({color:getColor(entity.color),side:THREE.DoubleSide})));break}}}),root}(this.toDrawData(unit))}usePlugin(plugin){return plugin.install(this),this}clone(drawHandle=!0){const cad2=new this.constructor;return cad2.groups=this.groups.map(g=>g.clone()),drawHandle&&this._drawHandlerMap.forEach((v2,k)=>cad2._drawHandlerMap.set(k,v2)),cad2}clear(){this.groups.length=0,this._drawHandlerMap.clear(),this.needUpdate=!0}static obliquity(cad2){const lineSegments=cad2.groups.flatMap(g=>g.lines),vrLine=LineSegmentUtils.findDominantDirectionLine(lineSegments);return{angle:-vrLine.direction().angleBetween(new Point(0,1),"angle","360")*(Math.PI/180),referenceLine:vrLine}}}class AxisAlignCorr{static start(lines,targettLine,excludeLines){return new AxisAlignCorr(lines,targettLine,excludeLines).start()}lines;baseline;excludeLines;grid;constructor(lines,baseline,excludeLines){this.lines=lines,this.baseline=baseline,this.excludeLines=excludeLines??[],this.grid=PointSpatialHash.fromByLines(lines)}visited=/* @__PURE__ */new Set;newLines=[];start(){const excludeSet=new Set(this.excludeLines);for(let i=0;i<this.lines.length;i++){const line=this.lines[i];excludeSet.size&&excludeSet.has(line)||(this.visited.has(line)||this.correction(line))}const quadtree=Quadtree.from(this.lines);return this.newLines=this.newLines.filter(line=>0===quadtree.queryCircle(line.center,1e-4).length),[...this.lines,...this.newLines]}addVisited(lines){return lines instanceof LineSegment&&(lines=[lines]),lines.forEach(line=>this.visited.add(line)),this}queryPoint(point2){return this.grid.queryPoint(point2,!0).filter(item=>!this.visited.has(item.userData))}correction(line){const startConnectList=this.queryPoint(line.start),endConnectLines=this.queryPoint(line.end);this.rotate(line),startConnectList.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,line.start)}),endConnectLines.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,line.end)})}recursion(line,enterPoint,nextLine,nextPoint){const otherPoint=line.getAnotherPoint(enterPoint),connectList=this.queryPoint(otherPoint);this.rotate(line),this.establishConnection(enterPoint,line,nextLine,nextPoint),connectList.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,otherPoint)})}establishConnection(point2,line,nextLine,nextPoint){if(line.isParallelTo(nextLine)){const interPoint2=nextLine.projectPoint(point2,!1),newLine=new LineSegment(point2.clone(),interPoint2?.clone()??nextPoint.clone());return void(newLine.length>1e-9&&this.newLines.push(newLine))}const interPoint=nextLine.projectPoint(point2,!1);interPoint&&(point2.copy(interPoint),nextLine.isPointOnSegment(interPoint)||nextPoint.copy(interPoint))}point=new Point;rotate(line,errAngle=45){const baseline=this.baseline;this.point.copy(line.start),line.isParallelTo(baseline,errAngle)?function(line,baseline){const currentAngle=Math.atan2(line.end.y-line.start.y,line.end.x-line.start.x);let diff=Math.atan2(baseline.end.y-baseline.start.y,baseline.end.x-baseline.start.x)-currentAngle;for(;diff>Math.PI;)diff-=2*Math.PI;for(;diff<-Math.PI;)diff+=2*Math.PI;const center=line.center;line.start.rotate(center,diff),line.end.rotate(center,diff),Math.abs(diff)>Math.PI/2&&line.swapValue()}(line,baseline):function(line,baseline){const currentAngle=Math.atan2(line.end.y-line.start.y,line.end.x-line.start.x),targetAngle=Math.atan2(baseline.end.y-baseline.start.y,baseline.end.x-baseline.start.x);let diff1=targetAngle+Math.PI/2-currentAngle,diff2=targetAngle-Math.PI/2-currentAngle;for(;diff1>Math.PI;)diff1-=2*Math.PI;for(;diff1<-Math.PI;)diff1+=2*Math.PI;for(;diff2>Math.PI;)diff2-=2*Math.PI;for(;diff2<-Math.PI;)diff2+=2*Math.PI;const diff=Math.abs(diff1)<Math.abs(diff2)?diff1:diff2,center=line.center;line.start.rotate(center,diff),line.end.rotate(center,diff),Math.abs(diff)>Math.PI/2&&line.swapValue()}(line,baseline),this.addVisited(line)}}class LineQueryer{pointVirtualGrid;lsh;constructor(lines){this.pointVirtualGrid=PointSpatialHash.fromByLines(lines),this.lsh=LineSegmentSpatialHash.from(lines)}update(lines){this.clear(),this.pointVirtualGrid=PointSpatialHash.fromByLines(lines),this.lsh=LineSegmentSpatialHash.from(lines)}clear(){this.pointVirtualGrid.clear(),this.lsh.clear()}queryNearestPoint(point2,opt){if(!point2)throw new Error("请传入查询点");const{resultIndex:resultIndex=0,radius:radius=.4,condition:condition}=opt??{},results=this.pointVirtualGrid.queryCircle(point2,radius).filter(item=>item.point!==point2).filter(item=>!condition||condition(item));return results.sort((a2,b4)=>a2.point.distance(point2)-b4.point.distance(point2)),results.length>resultIndex?{point:results[resultIndex].point,line:results[resultIndex].userData}:null}queryNearestLine(point2,opt){if(!point2)throw new Error("请传入查询点");const{resultIndex:resultIndex=0,radius:radius=.4,condition:condition}=opt??{},results=this.lsh.queryPoint(point2,radius).map(item=>{const projPoint=item.projectPoint(point2,!1);return projPoint&&(!condition||condition(item,projPoint))&&projPoint?{line:item,distance:projPoint.distance(point2)??1/0,projPoint:projPoint}:null}).filter(i=>!!i);return results.sort((a2,b4)=>a2.distance-b4.distance),results.length>resultIndex?{point:results[resultIndex].projPoint,line:results[resultIndex].line}:null}}function removeDangline(lines,maxLen=.01,consecutive=!1){const grid=PointSpatialHash.fromByLines(lines);let defaultLines=[];const doorLines=[],removeLineSet=/* @__PURE__ */new Set;function find(lines2){removeLineSet.clear();const shortLine=lines2.filter(line=>line.length<=maxLen);for(let i=0;i<shortLine.length;i++){const line=shortLine[i];line.points.some(p2=>0===grid.queryCircle(p2,1e-4).filter(item=>item.userData!==line).length)&&removeLineSet.add(line)}return removeLineSet}for(lines.forEach(line=>{line.userData.isDoor?doorLines.push(line):defaultLines.push(line)});0!=find(defaultLines).size&&(defaultLines=defaultLines.filter(line=>!removeLineSet.has(line)),removeLineSet.forEach(line=>{grid.removes(line.points)}),consecutive););return defaultLines=mergeChainsLine(defaultLines,(newLine,lines2)=>{mergeLineUserData(newLine,lines2=lines2.filter(line=>line.length>0)),newLine.userData.isBayWindow=lines2.some(line=>line.userData.isBayWindow)}),WallHole.filterIllegal(defaultLines),[...defaultLines,...doorLines]}const DELETE_SYMBOL=/* @__PURE__ */Symbol("DELETE_SYMBOL");function fitting(lines){const index2=LineSegmentUtils.maxLengthLineIndex(lines);if(-1===index2)throw Error("未找到最长线段");const maxLine=lines[index2],center=LineSegmentUtils.getLinesCenter(lines),direct=maxLine.direction(),start=center.clone().add(direct.clone().multiplyScalar(-1)),end=center.clone().add(direct.clone().multiplyScalar(1));return new LineSegment(start,end)}function layoutDesign(lines,axis,intersectPoints,opt){let blocks=lines.map((line,index2)=>{const sv=axis.projectPointValue(line.start),ev=axis.projectPointValue(line.end),range=sv<ev?[sv,ev]:[ev,sv];return{range:range,index:index2,rangeSize:range[1]-range[0]}});blocks.sort((a2,b4)=>Math.abs(a2.range[0]-b4.range[0])<1e-4?b4.rangeSize-a2.rangeSize:a2.range[0]-b4.range[0]);const newLines=[];for(let i=0;i<blocks.length;i++){const block=blocks[i],line=lines[block.index],occupationIndexList=[];let ranges=[],start=block.range[0];for(let j=i+1;j<blocks.length;j++){const nextBlock=blocks[j];if(Math.min(block.range[1],nextBlock.range[1])-Math.max(block.range[0],nextBlock.range[0])<0)break;nextBlock.range[0]>start&&ranges.push([start,nextBlock.range[0]]),start=Math.max(start,nextBlock.range[1]),occupationIndexList.push(nextBlock.index)}start<block.range[1]&&ranges.push([start,block.range[1]]),ranges=ranges.filter(range=>range[1]-range[0]>1e-4);for(let j=0;j<ranges.length;j++){const range=ranges[j],start2=axis.pointAt(range[0]),end=axis.pointAt(range[1]);if(0===j)line.set(start2,end),newLines.push(line);else{let newLine=line.clone();newLine.set(start2,end),newLines.push(newLine)}}0===ranges.length&&(line.currentData[DELETE_SYMBOL]=!0,opt.onSegmentClippedAway?.(line,occupationIndexList.map(i2=>lines[i2]).filter(line2=>!line2.currentData[DELETE_SYMBOL])))}!function(lines,axis){lines.sort((a2,b4)=>{const sa2=axis.projectPointValue(a2.start),sb=axis.projectPointValue(b4.start);if(Math.abs(sa2-sb)<1e-6){const aLen=axis.projectPointValue(a2.end)-sa2;return axis.projectPointValue(b4.end)-sb-aLen}return sa2-sb})}(newLines,axis);const psh=PointSpatialHash.from(intersectPoints);for(let i=0;i<newLines.length-1;i++){const line=newLines[i];if(0!==psh.queryPoint(line.end).length)continue;const nextLine=newLines[i+1];nextLine.start.copy(line.start),line.currentData[DELETE_SYMBOL]=!0,opt.onMergeLine?.(nextLine,line)}return lines.length=0,lines.push(...newLines),lines}class AlignToParallelSegments{static fittingAlignment(groups,verticalLines,opt={}){const grid=PointSpatialHash.fromByLines(verticalLines);for(let i=0;i<groups.length;i++){const group2=groups[i];if(group2.length<=1)continue;const axisLine=fitting(group2),intersectList=[];for(let j=0;j<group2.length;j++){group2[j].points.forEach(p2=>{const intersects2=grid.queryCircle(p2,1e-4),pv=axisLine.projectPointValue(p2);axisLine.pointAt(pv,p2),intersects2.forEach(({point:point2})=>point2.copy(p2)),intersectList.push(...intersects2)})}const intersectPoints=intersectList.filter(item=>item.userData.length>1e-5).map(item=>item.point);let oldGroup=[...group2];layoutDesign(group2,axisLine,intersectPoints,opt),opt.onLayoutDesign?.(oldGroup,DELETE_SYMBOL)}return groups.flat().filter(line=>!(line.length<1e-9)&&(!line.currentData[DELETE_SYMBOL]||(delete line.currentData[DELETE_SYMBOL],!1)))}static align(lines,opt={}){const{esp:esp=.08,gap:gap=.05}=opt,axisLine=lines[LineSegmentUtils.maxLengthLineIndex(lines)].clone().setLength(100),axisLineV=axisLine.clone().rotate(.5*Math.PI,axisLine.center);let[pllLines,verticalLines]=LineSegmentUtils.groupByParallelToAxis(lines,axisLine);const groups=LineSegmentUtils.groupByProjectedOverlap(pllLines,axisLine,axisLineV,esp,gap,opt.onGroup);pllLines=this.fittingAlignment(groups,verticalLines,opt),verticalLines=verticalLines.filter(line=>line.length>1e-6);const groups2=LineSegmentUtils.groupByProjectedOverlap(verticalLines,axisLineV,axisLine,esp,gap,opt.onGroup);return verticalLines=this.fittingAlignment(groups2,pllLines,opt),pllLines=pllLines.filter(line=>line.length>1e-6),[...pllLines,...verticalLines]}}function preprocessing(lines){return lines=function(lines,radius=.1){const pvg=PointSpatialHash.fromByLines(lines);return lines.forEach(line=>{line.points.forEach(p2=>{if(0!==pvg.queryCircle(p2,.001,!0).length)return;const list=pvg.queryCircle(p2,radius,!0).filter(item=>item.userData?.userData.isBayWindow);if(0===list.length)return;let direct1=line.getAnotherPoint(p2).directionFrom(p2);for(let i=0;i<list.length;i++){const{point:point2}=list[i],direct2=point2.directionFrom(p2);direct1.angle(direct2,{unit:"degree",range:"180"})<85||p2.copy(point2)}})}),lines}(lines=function(lines,radius=.1){const dpSet=findDiscretePoint(lines.filter(line=>!line.userData.isDoor)),pointVirtualGrid=PointSpatialHash.fromByLines(dpSet.map(v2=>v2)),lsh=LineSegmentSpatialHash.from(lines),appendLines=[],visited=/* @__PURE__ */new Set,getWeight2=(target,point2,line)=>{if(target.weight)return target.weight;const targetLine=target.userData,targetPoint=target.point,direct1=line.getAnotherPoint(point2).directionFrom(point2),direct2=targetLine.getAnotherPoint(targetPoint).directionFrom(targetPoint),direct3=targetPoint.directionFrom(point2),angle=direct1.angleBetween(direct2),angle2=direct1.angleBetween(direct3),weight=1-point2.distance(target.point)/radius+angle/Math.PI*1.2+1.2*(1-angle2/Math.PI);return target.weight=weight,weight},queryLine2=new LineSegment;for(const[point2,line]of dpSet){if(line.userData.isDoor)continue;if(visited.has(point2))continue;const list=pointVirtualGrid.queryCircle(point2,radius,!0).map(item=>Object.assign({},item)).filter(item=>{const targetLine2=item.userData;return targetLine2!==line&&(!targetLine2.isSameEndpoint(line)&&(queryLine2.set(point2,item.point),0===lsh.queryLine(queryLine2).filter(l=>l!==line&&l!==targetLine2).length))}).filter(item=>{const targetLine2=item.userData,targetPoint2=item.point,direct1=line.getAnotherPoint(point2).directionFrom(point2),direct2=targetLine2.getAnotherPoint(targetPoint2).directionFrom(targetPoint2);return direct1.angleBetween(direct2,"angle")>90}).sort((a2,b4)=>getWeight2(b4,point2,line)-getWeight2(a2,point2,line));if(0===list.length)continue;const{point:targetPoint}=list[0],targetLine=list[0].userData;visited.add(point2),visited.add(targetPoint);const projectLine1=line.projectLineSegment(targetLine),projectLine2=targetLine.projectLineSegment(line),len1=projectLine1.length,len2=projectLine2.length;let newLine=0===len1&&0===len2?new LineSegment(point2.clone(),list[0].point.clone()):new LineSegment(projectLine1.center,projectLine2.center);if(newLine.isParallelTo(line)){point2.copy(newLine.end);const otherPoint=line.getAnotherPoint(point2),step=point2.directionFrom(otherPoint).multiplyScalar(.5*newLine.length);WallHole.isBeam(line)&&new Array(...WallHole.getIterator(line)).forEach(hole=>{const p2=Point.from(hole.p);p2.add(step),hole.width+=newLine.length,hole.p=p2.toJson(hole.p.z)})}else appendLines.push(newLine);pointVirtualGrid.update(point2),lsh.update(line)}return[...lines,...appendLines]}(lines,.4),.05)}function adsorption(lines,option,otherLines=[]){const{snapThreshold:threshold=.2}=option??{},lineQueryer=new LineQueryer([...lines,...otherLines]),modifyManager=LineSegmentUtils.createModifyManager();function adsorptLine(point2,line){const direct=line.getAnotherPoint(point2).directionFrom(point2),len=line.length,result=lineQueryer.queryNearestLine(point2,{radius:threshold,condition:(target_line,projPoint)=>{if(line!==target_line&&target_line.isPerpendicularTo(line,35)){if(projPoint.distance(point2)<len)return!0;return projPoint.directionFrom(point2).angleBetween(direct)>.5*Math.PI}return!1}});if(result)return modifyManager.setPoint(line,point2,result.point.clone())}for(let i=0;i<lines.length;i++){const line=lines[i];line.points.map(point2=>{0===lineQueryer.pointVirtualGrid.queryPoint(point2,!0).length&&lineQueryer.lsh.queryPoint(point2,1e-4).length<2&&adsorptLine(point2,line)})}return modifyManager.modify(),lineQueryer.clear(),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),lines}function breakpointMerging$1(lines){let defaultLines=[],doorLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isDoor?doorLines.push(line):defaultLines.push(line)}return defaultLines=mergeChainsLine(defaultLines),doorLines=mergeChainsLine(doorLines),[...defaultLines,...doorLines]}function alignConfig(opt){const{min_wall_width:min_wall_width=DEFAULT_WALL_WIDTH,max_wall_width:max_wall_width=MAX_WALL_WIDTH}=opt??{};return{onMergeLine:mergeLineUserData,onGroup(group2,projValues,axis){if(group2.length<=1)return;const dist=precision4((Math.max(...projValues)-Math.min(...projValues))*axis.length);dist<min_wall_width||group2.forEach(line=>{line.userData.wallWidth=Math.min(dist,max_wall_width),line.userData.type="beams"})},onLayoutDesign(lines,delKey){const holes=[];lines=lines.filter(line=>(holes.push(...WallHole.getIterator(line)),WallHole.clear(line),!line.currentData[delKey])),WallHole.splitHole(holes,lines)}}}function sparse(trajectory2,size2=.4){const idSet=/* @__PURE__ */new Set;Object.keys(trajectory2??{}).forEach(key=>{const p2=trajectory2[key],i=Math.round(p2.x/size2),j=Math.round(p2.y/size2),id=BigInt(i)<<32n|0xffffffffn&BigInt(j);idSet.has(id)?delete trajectory2[key]:idSet.add(id)})}const sortByDistance=(a2,b4,dockPoint)=>a2.point.distance(dockPoint,!0)-b4.point.distance(dockPoint,!0);function getWeight(target,dock,doorLength){if(target.weight)return target.weight;const distance2=dock.dockPoint.distance(target.point);let weight=1-Math.abs(1-distance2/doorLength);const direct1=target.point.directionFrom(dock.dockPoint),direct2=dock.dockLine.getAnotherPoint(dock.dockPoint).directionFrom(dock.dockPoint);return weight+=direct1.angleBetween(direct2)/Math.PI*1.5,target.weight=weight,weight}class DoorFind{lines;grid;quadtree;constructor(lines){lines=this.findBrotherDoor(lines),this.lines=lines;const doors=lines.filter(line=>line.userData.isDoor),noDoorLines=lines.filter(line=>!line.userData.isDoor),openDoors=doors.filter(line=>!line.userData.doorDirectConnection),closeDoors=doors.filter(line=>line.userData.doorDirectConnection);this.grid=PointSpatialHash.fromByLines(noDoorLines),this.quadtree=Quadtree.from([...noDoorLines,...closeDoors]),openDoors.forEach(l=>l.userData.doorDirectConnection=!0),closeDoors.forEach(line=>this.findCloseDoors(line)),openDoors.forEach(line=>this.findOpenDoors(line))}findBrotherDoor(lines){const grid=PointSpatialHash.fromByLines(lines),doorLines=[];findDiscretePointLine2(lines).forEach(line=>line.userData.isDoor&&doorLines.push(line));const searchedList=[];doorLines.forEach(line=>{const pointStartIsFree=grid.isFreePoint(line.start),pointEndIsFree=grid.isFreePoint(line.end);pointStartIsFree&&pointEndIsFree||(pointStartIsFree?searchedList.push({door:line,point:line.end}):searchedList.push({door:line,point:line.start}))}),searchedList.forEach(item=>{let list=grid.queryPoint(item.point,!0);list.length>1&&(list=list.filter(target=>{const otherPoint=target.userData.getAnotherPoint(target.point);return!grid.isFreePoint(otherPoint)})),item.line=list[0]?.userData,item.linePoint=list[0]?.point});const doorGrid=new PointSpatialHash,minAngle=Math.PI/180*170;searchedList.forEach((item,index2)=>item.line&&doorGrid.insert(item.point,index2));const removeLines=[];searchedList.forEach(item=>{if(!item.line||item.found)return;const dir=item.line?.getAnotherPoint(item.linePoint).directionFrom(item.linePoint),list=doorGrid.queryCircle(item.point,2.5*item.door.length).filter(result=>{const{line:line}=searchedList[result.userData];return line.isParallelTo(item.line,10)}).filter(result=>{const{line:line,linePoint:linePoint}=searchedList[result.userData],dir2=line?.getAnotherPoint(linePoint).directionFrom(linePoint);return dir.angleBetween(dir2)>minAngle}).filter(result=>{const{point:point2}=searchedList[result.userData],dir2=item.point.directionFrom(point2),dir3=item.linePoint.directionFrom(item.line.getAnotherPoint(item.linePoint));return dir2.angleBetween(dir3)>Math.PI/180*135});if(list.length){const item2=searchedList[list[0].userData];item2.found=!0,item.door.getAnotherPoint(item.point).copy(item2.point),item.door.userData.doorDirectConnection=!0,removeLines.push(item2.door)}});const set2=new Set(removeLines);return lines.filter(line=>!set2.has(line))}findCloseDoors(line){const startList=this.grid.queryCircle(line.start,.01,!0).sort((a2,b4)=>sortByDistance(a2,b4,line.start)),endList=this.grid.queryCircle(line.end,.01,!0).sort((a2,b4)=>sortByDistance(a2,b4,line.end));if(startList.length+endList.length===0)return this.findOpenDoors(line);if(startList.length&&endList.length)return line.start.copy(startList[0].point),void line.end.copy(endList[0].point);let dock=null;if(startList.length?dock={dockLine:startList[0].userData,dockPoint:startList[0].point,point:line.start,pointType:"start"}:endList.length&&(dock={dockLine:endList[0].userData,dockPoint:endList[0].point,point:line.end,pointType:"end"}),!dock)return;const point2=this.adsorpt(dock,line,20);point2&&(line.userData.doorAutomaticFind=!0,line.getAnotherPoint(dock.point).copy(point2))}findOpenDoors(line){let dock;const queryList=point22=>{let list=this.grid.queryPoint(point22,!0);if(1===list.length)return list;list=this.grid.queryCircle(point22,.6,!0),list=list.filter(item=>!item.userData?.userData.isDoor&&!item.userData?.userData.isBayWindow).filter(item=>!this.grid.queryPoint(item.point,!0).some(i=>i.userData?.isParallelTo(item.userData))).filter(item=>{const line2=item.userData,direct1=line.getAnotherPoint(point22).directionFrom(item.point),direct2=line2.getAnotherPoint(item.point).directionFrom(item.point);return direct1.angleBetween(direct2,"angle")>70});const list2=list.filter(item=>{const otherPoint=item.userData?.getAnotherPoint(item.point);return 0!==this.grid.queryPoint(otherPoint,!0).length});return list2.length&&(list=list2),list.sort((a2,b4)=>sortByDistance(a2,b4,point22)),list},startList=queryList(line.start),endList=queryList(line.end);if(startList.length+endList.length===0)return;dock=0===endList.length||0!==startList.length&&startList[0].point.distance(line.start)<endList[0].point.distance(line.end)?{dockLine:startList[0].userData,dockPoint:startList[0].point,point:line.start,pointType:"start"}:{dockLine:endList[0].userData,dockPoint:endList[0].point,point:line.end,pointType:"end"};const point2=this.adsorpt(dock,line);point2&&(line.userData.doorDirectConnection=!0,line.userData.doorAutomaticFind=!0,line.getAnotherPoint(dock.point).copy(point2))}adsorpt(dock,line,maxAngle=70){const length=line.length,targetDirect=dock.dockLine.getAnotherPoint(dock.dockPoint).directionFrom(dock.dockPoint);dock.point.copy(dock.dockPoint);const list=this.grid.queryCircle(dock.point,2*length,!0).map(item=>({...item})).filter(item=>item.userData!==dock.dockLine).filter(item=>0===this.grid.queryPoint(item.point,!0).length).filter(item=>item.point.directionFrom(dock.point).angleBetween(targetDirect,"angle")>70).filter(item=>{const line2=item.userData,d1=item.point.directionFrom(dock.point),d2=line2.getAnotherPoint(item.point).directionFrom(item.point),d3=dock.dockPoint.directionFrom(dock.dockLine.getAnotherPoint(dock.dockPoint));return d1.angleBetween(d2,"angle")<maxAngle&&d3.angleBetween(d2,"angle")<maxAngle}).filter(item=>{const queryLine2=new LineSegment(item.point.clone(),dock.point.clone());return queryLine2.offsetStart(.01).offsetEnd(.001),0===this.quadtree.queryLineSegment(queryLine2).length}).filter(item=>item.point.distance(dock.point)/length>.5).filter(item=>{const normal=item.point.leftNormal(dock.point),center=new Point((item.point.x+dock.point.x)/2,(item.point.y+dock.point.y)/2),length2=item.point.distance(dock.point),normalLine=new LineSegment(center,center.clone().add(normal.clone().multiplyScalar(length2)));normalLine.translate(.5*-length2,normal);return 0===this.quadtree.queryLineSegment(normalLine).filter(result=>result.line!==line&&result.line!==dock.dockLine).length}).sort((a2,b4)=>getWeight(b4,dock,length)-getWeight(a2,dock,length));if(list.length){const line2=list[0].userData;let point2=list[0].point;if(dock.dockLine.isPerpendicularTo(line2,25)){const p2=line2.projectPoint(dock.point,!0);p2&&(point2=p2)}return point2}return this.extendLink(dock,line)}extendLink(dock,line){const length=line.length,direct=dock.dockPoint.directionFrom(dock.dockLine.getAnotherPoint(dock.dockPoint)),queryLine2=new LineSegment(dock.dockPoint,dock.dockPoint.clone().add(direct.multiplyScalar(2*length)));let result=this.quadtree.queryLineSegment(queryLine2,!1).filter(item=>item.line!==dock.dockLine&&item.line!==line).map(item=>item.line.getIntersection(queryLine2)).filter(p2=>!!p2).filter(p2=>p2.distance(dock.dockPoint)>.2).sort((a2,b4)=>a2.distance(dock.dockPoint)-b4.distance(dock.dockPoint));if(result.length)return result[0];const normal=dock.dockLine.normal(),nNormal=normal.multiplyScalar(-1),direct2=line.getAnotherPoint(dock.point).directionFrom(dock.point);return direct2.angleBetween(normal)<direct2.angleBetween(nNormal)?queryLine2.set(dock.dockPoint,dock.dockPoint.clone().add(normal.multiplyScalar(2*length))):queryLine2.set(dock.dockPoint,dock.dockPoint.clone().add(nNormal.multiplyScalar(2*length))),result=this.quadtree.queryLineSegment(queryLine2,!1).filter(item=>{item.line!==dock.dockLine&&item.line}).map(item=>{const point2=item.line.getIntersection(queryLine2);if(point2)return point2}).filter(p2=>!!p2).filter(p2=>p2.distance(dock.dockPoint)>.2).sort((a2,b4)=>a2.distance(dock.dockPoint)-b4.distance(dock.dockPoint)),result.length?result[0]:null}getLines(){return this.lines.filter(line=>!(line.userData.isDoor&&line.length<.4))}}let loader;class LoadModel{static _cache=/* @__PURE__ */new Map;static _nameMap=/* @__PURE__ */new Map;static addNameMap(mapName,name){this._nameMap.set(mapName,name)}static loadGlb(name){if(this._nameMap.has(name)&&(name=this._nameMap.get(name)),this._cache.has(name))return this._cache.get(name);loader||(loader=new gltf.GLTFLoader);const promise2=new Promise(async resolve=>{const response=await fetch(`${VITE_OSS_BASEURL}models/${name}.glb`);if(!response.ok)return void resolve(null);const arrayBuffer=await response.arrayBuffer();resolve((await new Promise((resolve2,reject)=>{loader.parse(arrayBuffer,"",resolve2,reject)})).scene)});return this._cache.set(name,promise2),promise2}}LoadModel.addNameMap("water cooler","饮水机1"),LoadModel.addNameMap("table","桌子"),LoadModel.addNameMap("chair","椅子"),LoadModel.addNameMap("switch","开关"),LoadModel.addNameMap("cabinet","柜子"),LoadModel.addNameMap("tv","电视"),LoadModel.addNameMap("socket","插座"),LoadModel.addNameMap("refrigerator","冰箱"),LoadModel.addNameMap("kitchen hood","抽油烟机"),LoadModel.addNameMap("toilet","马桶"),LoadModel.addNameMap("sofa","沙发"),LoadModel.addNameMap("the bed","床"),LoadModel.addNameMap("door","门"),LoadModel.addNameMap("doubleDoor","双开门2"),LoadModel.addNameMap("window","窗户"),LoadModel.addNameMap("wall","单线墙"),LoadModel.addNameMap("doubleWall","双线墙"),LoadModel.addNameMap("balcony","阳台"),LoadModel.addNameMap("balconyFilm","阳台片"),LoadModel.addNameMap("balconyFilmFilm","阳台片片"),LoadModel.addNameMap("balconyFilmFilmFilm","阳台片片片");const defaultWallWidth=DEFAULT_WALL_WIDTH;function winDrawLine(line,grid){if(line.userData.isWindow&&Array.isArray(line.userData.drawWindow)){WallHole.merge([line]);const list=grid&&function(grid,line){const startList=grid.queryPoint(line.start,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),endList=grid.queryPoint(line.end,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),results=[];return 0===startList.length?results.push(0):startList.some(item=>"wall"===item)?results.push(1):results.push(2),0===endList.length?results.push(0):endList.some(item=>"wall"===item)?results.push(1):results.push(2),results}(grid,line),dwh=.5*defaultWallWidth;return line.userData.drawWindow.map(({full:full,width:width,p:p2,height:height,groundClearance:groundClearance,uuid:uuid2})=>{full&&(width=line.length);const point2=Point.from(p2),direct=line.direction(),winLine=point2.expandAsLine(direct,width).translate(.5*-width,direct);if(winLine.userData={wallWidth:defaultWallWidth,height:height,groundClearance:groundClearance},winLine.start.copy(line.projectPoint(winLine.start,!1)),winLine.end.copy(line.projectPoint(winLine.end,!1)),!list)return winLine;const startDistance=winLine.start.distance(line.start);if(startDistance<dwh&&1===list[0]){const diff=dwh-startDistance;winLine.offsetStart(diff)}const endDistance=winLine.end.distance(line.end);if(endDistance<dwh&&1===list[1]){const diff=dwh-endDistance;winLine.offsetEnd(diff)}return winLine.userData.winUuid=uuid2,winLine.userData.lineUuid=line.userData.uuid,winLine}).filter(line2=>line2.length>defaultWallWidth)}return null}class BayWindow{bayWindowExpansion=[];dottedLinePoints=[];singleLine;bayWindowArea;bayWindowGroup;static _instance;static get Instance(){return BayWindow._instance}constructor(){BayWindow._instance=this,this.bayWindowExpansion=[],this.dottedLinePoints=[],this.singleLine=[],this.bayWindowArea=null,this.bayWindowGroup=new THREE.Group}overhangTreatment(data,singleLine){this.singleLine=singleLine;const grid=PointSpatialHash.fromByLines(Scenario.Instance.lines);for(const i in data){this.bayWindowGroup=new THREE.Group,this.dottedLinePoints.push(data[i].dottedLine);let dashedLine=Scenario.Instance.correctionSorting([data[i].dottedLine]),lines=data[i].lines.slice(),listS=Scenario.Instance.correctionSorting(lines);const centroidPoint=this.getPolygonCentroid(listS);for(const a2 in listS)if(Number(a2)%2==0&&Number(a2)!==listS.length-1){const direction=this.pointSideOfLine(listS[a2].dian,listS[Number(a2)+1].dian,centroidPoint);listS[a2].direction=direction,listS[Number(a2)+1].direction=direction}let dataList=data[i].lines.slice();dataList.push(data[i].dottedLine),this.bayWindowArea=Polygon.fromByLines2(dataList),this.dashedLineTreatment(dashedLine,centroidPoint,data[i].data);let quanti=Scenario.Instance.correctionSorting(dataList);this.createBayWindowLayout(quanti,data[i].data);for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2,winDraw=winDrawLine(lines[Number(x)/2],grid);Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:listS[x].shared}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x,direction:listS[x].direction,shared:listS[x].shared}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:listS[x].shared};const wallHeight=listS[x].wallHeight;let Mesh=this.bayWindowExecutionOffset(a2,Number(x)/2,wallHeight,data[i].data,!0);if(!Mesh){console.log("夹角异常!");continue}if(Mesh.mesh3)if(winDraw&&winDraw.length>0){for(const x2 in winDraw)if(1===winDraw.length){this.installWindows(winDraw[x2],x2,Mesh.points3);let mesh=this.windowTreatment(winDraw[x2],Mesh.mesh3,wallHeight,Mesh.points3,a2);mesh.name=`飘窗墙_${Number(x2)/2}组`,mesh.userData.category="bayWindowWall",this.bayWindowGroup.add(mesh)}}else Mesh.mesh3.name=`飘窗墙_${Number(x)/2}组`,Mesh.mesh3.userData.category="bayWindowWall",this.bayWindowGroup.add(Mesh.mesh3)}const num=Number(i)+1;this.bayWindowGroup.name=`飘窗_${num}`,this.bayWindowGroup.userData.category="bayWindow",this.bayWindowGroup.userData.width=data[i].data.windowWidth,this.bayWindowGroup.userData.height=data[i].data.height2,this.bayWindowGroup.userData.groundHeight=data[i].data.height3,this.bayWindowGroup.userData.distanceToTheTop=data[i].data.height1;for(const w in data[i].lines)data[i].lines[w].userData.isWindow&&(this.bayWindowGroup.userData.depth=data[i].dottedLine.distanceToSegment(data[i].lines[w]));Scenario.Instance.group.add(this.bayWindowGroup)}}dashedLineTreatment(data,centroidPoint,item){let listS=data;for(const a2 in listS)if(Number(a2)%2==0&&Number(a2)!==listS.length-1){let direction;const v12=new THREE.Vector2(listS[Number(a2)+1].dian.x-listS[a2].dian.x,listS[Number(a2)+1].dian.y-listS[a2].dian.y),v2=new THREE.Vector2(centroidPoint.x-listS[a2].dian.x,centroidPoint.y-listS[a2].dian.y),crossZ=v12.x*v2.y-v12.y*v2.x;direction=Math.abs(crossZ)<1e-10?0:crossZ>0?-1:1,listS[a2].direction=direction,listS[Number(a2)+1].direction=direction}for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2;Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:!1}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x,direction:listS[x].direction,shared:!1}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:!1};let Meshlist=this.bayWindowExecutionOffset(a2,Number(x)/2,item.height3,item,!1);if(!Meshlist){console.log("夹角异常1",Meshlist);continue}Scenario.Instance.group.add(Meshlist.mesh1),Scenario.Instance.group.add(Meshlist.mesh2)}}bayWindowExecutionOffset(data,index2,wallHeight,item,statuc=!1){const wallHeightc=wallHeight||Scenario.Instance.wallHeight,points=[];points.push(new THREE.Vector3(data.start.x,data.start.y,wallHeightc)),points.push(new THREE.Vector3(data.end.x,data.end.y,wallHeightc));let scale2=data.shared?.5*DEFAULT_WALL_WIDTH:DEFAULT_WALL_WIDTH;const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,scale2,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,scale2,!1);let startingPoint,finishLine;if(statuc){const dottedGrid=PointSpatialHash.fromByLines(this.singleLine),a2=new Point(data.start.x,data.start.y),b4=new Point(data.end.x,data.end.y);if(dottedGrid.queryCircle(a2,1e-4).length>0||dottedGrid.queryCircle(b4,1e-4).length>0)return startingPoint=this.xinLine(MobileX,MobileY,data.start,data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,data.direction),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint}}if(data.shared)return startingPoint=this.xinLine(MobileX,MobileY,data.start,-1*data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,-1*data.direction),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};startingPoint=this.xinLine(MobileX,MobileY,data.start,data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,data.direction);const grid=PointSpatialHash.fromByLines(Scenario.Instance.lines),isDouble=grid.queryCircle(Point.from(data.start),.001).some(item2=>LineGroupType.hasType(item2.userData,"doubleWall")||item2.userData?.userData.isDoor),isDouble1=grid.queryCircle(Point.from(data.end),.001).some(item2=>LineGroupType.hasType(item2.userData,"doubleWall")||item2.userData?.userData.isDoor);let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],0,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],1,wallHeightc);if(isDouble&&isDouble1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(isDouble&&!isDouble1){let status=!1,angle=null;for(const x in this.bayWindowExpansion)if(this.bayWindowExpansion[x].point.x===data.end.x&&this.bayWindowExpansion[x].point.y===data.end.y&&this.bayWindowExpansion[x].point.z===data.end.z){status=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z);angle=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start).dot(this.bayWindowExpansion[x].n),angle=Math.abs(angle)}if(!status){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(null!==angle&&angle<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==angle&&angle>.9){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(!isDouble&&isDouble1){let status=!1,angle=null;for(const x in this.bayWindowExpansion)if(this.bayWindowExpansion[x].point.x===data.start.x&&this.bayWindowExpansion[x].point.y===data.start.y&&this.bayWindowExpansion[x].point.z===data.start.z){status=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z);angle=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start).dot(this.bayWindowExpansion[x].n),angle=Math.abs(angle)}if(!status){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}if(null!==angle&&angle<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==angle&&angle>.9){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}if(!isDouble&&!isDouble1){let statua=!1,statub=!1,anglea=null,angleb=null;for(const x in this.bayWindowExpansion){if(this.bayWindowExpansion[x].point.x===data.start.x&&this.bayWindowExpansion[x].point.y===data.start.y&&this.bayWindowExpansion[x].point.z===data.start.z){statua=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);n.normalize();const v2=new THREE.Vector3(this.bayWindowExpansion[x].n.x,this.bayWindowExpansion[x].n.y,this.bayWindowExpansion[x].n.z);v2.normalize(),anglea=n.dot(v2),anglea=Math.abs(anglea)}if(this.bayWindowExpansion[x].point.x===data.end.x&&this.bayWindowExpansion[x].point.y===data.end.y&&this.bayWindowExpansion[x].point.z===data.end.z){statub=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);n.normalize();const v2=new THREE.Vector3(this.bayWindowExpansion[x].n.x,this.bayWindowExpansion[x].n.y,this.bayWindowExpansion[x].n.z);v2.normalize(),angleb=n.dot(v2),angleb=Math.abs(angleb)}}if(statua&&statub){if(null!==anglea&&anglea<.1&&null!==angleb&&angleb<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==anglea&&anglea>.9&&null!==angleb&&angleb<.1){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}if(null!==anglea&&anglea<.1&&null!==angleb&&angleb>.9){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(null!==anglea&&anglea>.9&&null!==angleb&&angleb>.9){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}else if(statua&&!statub){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);if(this.bayWindowExpansion.push({point:data.end,n:n}),null!==anglea&&anglea<.1){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(null!==anglea&&anglea>.9){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}{startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}else if(!statua&&statub){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);if(this.bayWindowExpansion.push({point:data.start,n:n}),null!==angleb&&angleb<.1){if(this.bayWindowArea.pointWithin(Point.from(startingPoint1[0]))){startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}if(null!==angleb&&angleb>.9){if(this.bayWindowArea.pointWithin(Point.from(startingPoint1[0]))){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}else if(!statua&&!statub){let npc1=this.bayWindowArea.pointWithin(Point.from(startingPoint1[0])),npc2=this.bayWindowArea.pointWithin(Point.from(finishLine1[0]));if(npc1&&npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(npc1&&!npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(!npc1&&npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}{const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}}createDashedLineCeilingWall(startingPoint,index2,item,num){let startingPointZ,basePoints=[];startingPointZ=num?Scenario.Instance.height+item.height3:Scenario.Instance.height+item.height3+item.height2;for(const i in startingPoint)basePoints.push(new THREE.Vector3(startingPoint[i].x,startingPoint[i].y,startingPointZ));if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const shape=new THREE.Shape;shape.moveTo(basePoints[0].x,basePoints[0].y);for(const i in basePoints)"0"!==i&&shape.lineTo(basePoints[i].x,basePoints[i].y);shape.lineTo(basePoints[0].x,basePoints[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:0===num?item.height1:item.height2,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+basePoints[0].z);const material=new THREE.MeshStandardMaterial({color:Scenario.Instance.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);return new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall",cube}}angleToXAxisDegrees(x1,y1,x2,y2,wide,cd){const dx=x2-x1,dy=y2-y1;return cd?wide*Math.sin(Math.atan2(dy,dx)):wide*Math.cos(Math.atan2(dy,dx))}windowOpeningOffset(x,y,point2,wallHeight){let point1,point22,xOverflow=x>0?.001:-.001,YOverflow=y>0?.001:-.001;return 1===wallHeight?(point1=new THREE.Vector3(point2.x+x,point2.y-y,wallHeight),point22=new THREE.Vector3(point2.x-xOverflow,point2.y+YOverflow,wallHeight)):(point1=new THREE.Vector3(point2.x+xOverflow,point2.y-YOverflow,wallHeight),point22=new THREE.Vector3(point2.x-x,point2.y+y,wallHeight)),[point1,point22]}xinLine(x,y,point2,wallHeight){let point1,point22;return 1===wallHeight?(point1=new THREE.Vector3(point2.x+x,point2.y-y,wallHeight),point22=new THREE.Vector3(point2.x,point2.y,wallHeight)):(point1=new THREE.Vector3(point2.x,point2.y,wallHeight),point22=new THREE.Vector3(point2.x-x,point2.y+y,wallHeight)),[point1,point22]}xinLine1(x,y,pointa,pointb,num,wallHeight=2.2){let point1,point2;return 0===num?(point1=new THREE.Vector3(pointa.x-x,pointa.y-y,wallHeight),point2=new THREE.Vector3(pointb.x-x,pointb.y-y,wallHeight)):(point1=new THREE.Vector3(pointa.x+x,pointa.y+y,wallHeight),point2=new THREE.Vector3(pointb.x+x,pointb.y+y,wallHeight)),[point1,point2]}getPolygonCentroid(points){const n=points.length;let cx=0,cy=0;for(let i=0;i<n;i++)cx+=points[i].dian.x,cy+=points[i].dian.y;return{x:cx/n,y:cy/n,z:points[0].dian.z}}pointSideOfLine(p1,p2,p3){const v12=new THREE.Vector2(p2.x-p1.x,p2.y-p1.y),v2=new THREE.Vector2(p3.x-p1.x,p3.y-p1.y),crossZ=v12.x*v2.y-v12.y*v2.x;return Math.abs(crossZ)<1e-10?0:crossZ>0?1:-1}windowTreatment(dblWin,mesh,wallHeight,startingPoint,data){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_WIDTH+.001,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_WIDTH+.001,!1);let startingPoints=this.windowOpeningOffset(MobileX,MobileY,data.start,data.direction),finishLine=this.windowOpeningOffset(MobileX,MobileY,data.end,data.direction);return startingPoints.push(finishLine[1]),startingPoints.push(finishLine[0]),Scenario.Instance.winHoleOpening(startingPoints,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}installWindows(data,index2,startingPoint){const point4=new THREE.Vector3(startingPoint[0].x,startingPoint[0].y,data.start.z),point3=new THREE.Vector3(startingPoint[2].x,startingPoint[2].y,data.start.z),center=new THREE.Vector3;center.addVectors(point4,point3).multiplyScalar(.5);const point1=new THREE.Vector3(data.start.x,data.start.y,startingPoint[0].z),point2=new THREE.Vector3(data.end.x,data.end.y,startingPoint[0].z),dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:Scenario.Instance.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??Scenario.Instance.WindowGroundHeight)+Scenario.Instance.height;let menModel=Scenario.Instance.windowModely.clone();if(data.center&&distance2){const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set((distance2+.12)/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(center.x,center.y,groundClearance),Scenario.Instance.windowForm=Scenario.Instance.windowForm+1,menModel.name=`窗体_${Scenario.Instance.windowForm}`,menModel.userData.category="windowForm",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.bayWindowGroup.add(menModel)}}createBayWindowLayout(listS,objData){let distance2,sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i=0;i<listS.length-1;i++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));const seen=/* @__PURE__ */new Set,uniqueCoords=objectiveList.filter(coord=>{const key=JSON.stringify(coord.dian);return!seen.has(key)&&(seen.add(key),!0)});objectiveList=uniqueCoords;const shape=new Shape;shape.moveTo(objectiveList[0].dian.x,objectiveList[0].dian.y);for(let i=1;i<objectiveList.length;i++)shape.lineTo(objectiveList[i].dian.x,objectiveList[i].dian.y);shape.lineTo(objectiveList[0].dian.x,objectiveList[0].dian.y);const geometry=new THREE.ShapeGeometry(shape),material=new THREE.MeshStandardMaterial({color:Scenario.Instance.color,side:THREE.DoubleSide}),mesh=new THREE.Mesh(geometry,material);let mesh2=mesh.clone(),height1=Scenario.Instance.height+objData.height3,height2=Scenario.Instance.height+objData.height3+objData.height2;mesh.position.z=height1,mesh2.position.z=height2,this.bayWindowGroup.add(mesh),this.bayWindowGroup.add(mesh2)}}const DEFAULT_WALL_HALF_WIDTH=.5*DEFAULT_WALL_WIDTH;class Scenario{camera;scene;renderer;controls;axesHelper;group;closedArray;lines;singleLines;doorGroup;texture;numdu;color;doorModely;doubleDoorModely;windowModely;balconyModely;doorHeight;doorGroundHeight;WindowHeight;WindowGroundHeight;CabinetModel;tableModel;chairModel;switchModel;socketModel;waterCoolerModel;height;expandedList;wallHeight;box;singleLineWallValue;liangNum;zhuNum;poortNum;doorNum;windowNum;windowForm;static _instance;static get Instance(){return Scenario._instance}constructor(scene,camera,renderer,controls){Scenario._instance=this,this.camera=camera,this.scene=scene,this.renderer=renderer,this.controls=controls,this.axesHelper=new THREE.AxesHelper(20),this.liangNum=0,this.zhuNum=0,this.poortNum=0,this.doorNum=0,this.windowNum=0,this.windowForm=0,this.scene.add(this.axesHelper),this.group=null,this.closedArray=[],this.lines=[],this.singleLines=[],this.doorGroup=new Group$1,this.doorGroup.name="",this.texture=null,this.numdu=1,this.color=16777215,this.doorModely=null,this.doubleDoorModely=null,this.windowModely=null,this.balconyModely=null,this.CabinetModel=null,this.tableModel=null,this.chairModel=null,this.switchModel=null,this.socketModel=null,this.waterCoolerModel=null,this.doorHeight=2.1,this.doorGroundHeight=0,this.WindowHeight=.8,this.WindowGroundHeight=.7,this.height=0,this.expandedList=[],this.wallHeight=2.8,this.box=null,this.singleLineWallValue=null}async drawGraphics(lines,z,trajectoryJson){lines.forEach(line=>{for(const hole of WallHole.getIterator(line))if(!hole.groundClearance&&0!==hole.groundClearance)switch(hole.type){case"door":hole.groundClearance=this.doorGroundHeight;break;case"window":hole.groundClearance=this.WindowGroundHeight;break;default:hole.groundClearance=0}});const doorLines=lines.filter(line=>line.userData.isDoor);if((lines=BuildGroup.doubleWall(lines.filter(line=>!line.userData.isDoor))).push(...doorLines),await this.modelLoader(),await this.windowModelLoader(),await this.balconyModelLoader(),this.height=z,this.lines=lines,this.group){this.scene.remove(this.group);const meshes=[];this.scene.traverse(function(object){object.isMesh&&meshes.push(object)}),meshes.forEach(mesh=>{mesh.geometry&&mesh.geometry.dispose(),mesh.material&&(Array.isArray(mesh.material)?mesh.material.forEach(material=>{material.map&&material.map.dispose(),material.dispose()}):(mesh.material.map&&mesh.material.map.dispose(),mesh.material.dispose())),mesh.parent?.remove(mesh)})}return this.group=new Group$1,this.liangNum=0,this.zhuNum=0,this.poortNum=0,this.doorNum=0,this.windowNum=0,this.windowForm=0,this.expandedList=[],BayWindow.Instance||new BayWindow,BayWindow.Instance.bayWindowExpansion=[],BayWindow.Instance.dottedLinePoints=[],this.splitProcessData(lines,this.texture),this.scene.add(this.group),this.group}loadJSONFile(callback){const input=document.createElement("input");input.type="file",input.accept=".json",input.onchange=function(event){const file=event.target.files[0];if(!file)return;const reader=new FileReader;reader.onload=function(e){const jsonData=JSON.parse(e.target.result);callback(jsonData)},reader.onerror=function(){console.error("文件读取失败"),alert("文件读取失败")},reader.readAsText(file)},input.click()}splitProcessData(lines,texture){this.closedArray=lines.filter(item=>LineGroupType.hasType(item,"doubleWall"));let pillar=LineGroupType.getGroupsByType(lines,"pillar");for(const m in pillar)this.processTheColumnData(pillar[m]);let groups=LineGroupType.getGroupsByType(this.closedArray,"doubleWall"),bayWindow=lines.filter(item=>LineGroupType.hasType(item,"bayWindow"));const set2=new Set([...this.closedArray,...pillar].flat(2));let singleLineWall=lines.filter(line=>!set2.has(line)&&!line.userData.isDoor&&!line.userData.isBayWindow&&"bayWindow"!==line.userData.groupType),menList=lines.filter(line=>line.userData.isDoor),bayWinGroups=LineGroupType.getGroupsByType(bayWindow,"bayWindow"),bayWinList=[];bayWinGroups.forEach(lines2=>{const data=BayWindowHelper.getDrawData2(lines2);if(data){let dottedLine=null;for(const i in lines2)lines2[i].userData.isBayWindow&&(dottedLine=lines2[i],lines2.splice(Number(i),1));bayWinList.push({lines:lines2,data:data,dottedLine:dottedLine})}else for(const i in lines2)singleLineWall.push(lines2[i])}),BayWindow.Instance?.overhangTreatment(bayWinList,singleLineWall),this.TheHandlingOfTheDoor(menList),this.singleLineWallValue=PointSpatialHash.fromByLines(singleLineWall),this.overallTreatmentOfSingleLineWalls(singleLineWall);for(const g in groups){const a2=clippingInsertObjectDoubleWall(groups[g]);for(const i in a2){let wallHeight=0;for(const v2 in a2[i])a2[i][v2].userData.height>wallHeight&&(wallHeight=a2[i][v2].userData.height);20===wallHeight&&(wallHeight=this.wallHeight);let distance2,bitem=a2[i].slice(),listS=this.correctionSorting(bitem),sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i2=0;i2<listS.length-1;i2++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));let c=objectiveList.map(pos=>(pos.dian.x=parseFloat(pos.dian.x.toFixed(6)),pos.dian.y=parseFloat(pos.dian.y.toFixed(6)),pos)),d2=[];for(const i2 in c)d2.push(new THREE.Vector3(c[i2].dian.x,c[i2].dian.y,c[i2].dian.z));const seen=/* @__PURE__ */new Set,E=d2.filter(coord=>{const key=JSON.stringify(coord);return!seen.has(key)&&(seen.add(key),!0)});let Mesh;if(Mesh=this.drawTheModel(E,0,Number(i),wallHeight,a2[i]),Mesh){Mesh.material.envMap=texture,Mesh.material.needsUpdate=!0;const doubleLinesWindow=WallHoleDrawData.doubleHoleLine(a2[i]);if(doubleLinesWindow&&0!=doubleLinesWindow.length){let houMesh=null;for(const x in doubleLinesWindow)if(1===doubleLinesWindow.length){const edges=new THREE.EdgesGeometry(this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]);let mesh=this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight);this.group.add(mesh)}else if(houMesh)if(Number(x)===doubleLinesWindow.length-1){const edges=new THREE.EdgesGeometry(this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]);let mesh=this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight);this.group.add(mesh)}else"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type&&this.singleLineWallMountedDoor(doubleLinesWindow[x],E),"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]),houMesh=this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight);else"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]),houMesh=this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight)}else this.group.add(Mesh)}}}}drawTheModel(data,num,index2,wallHeight,originalData){let colorValue=!1,liangOriginalData=null;if(originalData&&0===num){const doubleLinesWindow=WallHoleDrawData.doubleHoleLine(originalData);if(doubleLinesWindow&&0!=doubleLinesWindow.length)for(const x in doubleLinesWindow)"beam"===doubleLinesWindow[x].userData.type&&(colorValue=!0,liangOriginalData=doubleLinesWindow[x])}if(originalData&&1===num)for(const x in originalData)"beam"===originalData[x].userData.type&&(colorValue=!0,liangOriginalData=originalData[x]);let basePoints=[];for(const i in data)basePoints.push(new THREE.Vector3(data[i].x,data[i].y,this.height?this.height:0));if(4===basePoints.length){if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const geometry=this.createParallelepipedFromBase(basePoints,wallHeight),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);if(new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),colorValue&&liangOriginalData){const point1=new THREE.Vector3(liangOriginalData.start.x,liangOriginalData.start.y,0),point2=new THREE.Vector3(liangOriginalData.end.x,liangOriginalData.end.y,0);this.liangNum=this.liangNum+1,cube.name=`梁_${this.liangNum}`,cube.userData.category="beam";const distance2=point1.distanceTo(point2),height=liangOriginalData.userData.wallHeight-liangOriginalData.userData.height,wallWidth=liangOriginalData.userData.wallWidth?liangOriginalData.userData.wallWidth:.18,groundClearance=liangOriginalData.userData.height;cube.userData.width=distance2,cube.userData.depth=wallWidth,cube.userData.height=height,cube.userData.groundHeight=groundClearance}else 0===num?(cube.name=`双线墙_${index2}`,cube.userData.category="doubleWall"):1===num?(cube.name=`单线墙_${index2}`,cube.userData.category="wall"):(cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall");return cube}}{const geometry=this.createParallelepipedFromBase(basePoints,wallHeight),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return new THREE.EdgesGeometry(geometry),0===num?(cube.name=`双线墙_${index2}`,cube.userData.category="doubleWall"):1===num?(cube.name=`单线墙_${index2}`,cube.userData.category="wall"):(cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall"),cube}}executionOffset(data,index2,wallHeight,winDraw,line){let wallWidth;line.userData.tags?.includes("hole-independent")&&(wallWidth=.5*line.userData.wallWidth);const wallHeightc=wallHeight||this.wallHeight,points=[];points.push(new THREE.Vector3(data.start.x,data.start.y,wallHeightc)),points.push(new THREE.Vector3(data.end.x,data.end.y,wallHeightc)),(new THREE.BufferGeometry).setFromPoints(points),new THREE.LineBasicMaterial({color:65280});const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,wallWidth??DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,wallWidth??DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);const grid=PointSpatialHash.fromByLines(this.lines),isDouble=grid.queryCircle(Point.from(data.start),.001).some(item=>LineGroupType.hasType(item.userData,"doubleWall")||item.userData?.userData.isDoor),isDouble1=grid.queryCircle(Point.from(data.end),.001).some(item=>LineGroupType.hasType(item.userData,"doubleWall")||item.userData?.userData.isDoor);let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],0,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],1,wallHeightc);if(isDouble&&isDouble1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw);if(isDouble&&!isDouble1){let status=!1;for(const x in this.expandedList)this.expandedList[x].x===data.end.x&&this.expandedList[x].y===data.end.y&&this.expandedList[x].z===data.end.z&&(status=!0);if(status)return finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw);{const npcEnd=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcEnd).length?(this.expandedList.push(data.end),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.end),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw))}}if(!isDouble&&isDouble1){let status=!1;for(const x in this.expandedList)this.expandedList[x].x===data.start.x&&this.expandedList[x].y===data.start.y&&this.expandedList[x].z===data.start.z&&(status=!0);if(status)return startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw);{const npcStart=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcStart).length?(this.expandedList.push(data.start),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}}if(!isDouble&&!isDouble1){let statua=!1,statub=!1;for(const x in this.expandedList)this.expandedList[x].x===data.start.x&&this.expandedList[x].y===data.start.y&&this.expandedList[x].z===data.start.z&&(statua=!0),this.expandedList[x].x===data.end.x&&this.expandedList[x].y===data.end.y&&this.expandedList[x].z===data.end.z&&(statub=!0);if(statua&&statub)return startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw);if(statua&&!statub){const npcEnd=new Point(data.end.x,data.end.y);return 1===this.singleLineWallValue.queryPoint(npcEnd).length?(this.expandedList.push(data.end),startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.end),startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}if(!statua&&statub){const npcStart=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcStart).length?(this.expandedList.push(data.start),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}if(!statua&&!statub){const npcStart=new Point(data.start.x,data.start.y),npcEnd=new Point(data.end.x,data.end.y);let npc1=1===this.singleLineWallValue.queryPoint(npcStart).length,npc2=1===this.singleLineWallValue.queryPoint(npcEnd).length;return npc1&&npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):!npc1&&npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw)):npc1&&!npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}}}windowTreatment(dblWin,mesh,wallHeight){const doorList=dblWin;let start,end;mesh.userData.start&&mesh.userData.end?(start=mesh.userData.start,end=mesh.userData.end):(start=doorList.start,end=doorList.end);const MobileX=this.angleToXAxisDegrees(start.x,start.y,end.x,end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!0),MobileY=this.angleToXAxisDegrees(start.x,start.y,end.x,end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!1);let startingPoint=this.xinLine(MobileX,MobileY,start,wallHeight),finishLine=this.xinLine(MobileX,MobileY,end,wallHeight),x=MobileX>0?.003:-.003,y=MobileY>0?.003:-.003,startingPoint1=this.xinLine1(y,x,startingPoint[0],startingPoint[1],0,wallHeight),finishLine1=this.xinLine1(y,x,finishLine[0],finishLine[1],1,wallHeight);return startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.winHoleOpening(startingPoint1,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}windowTreatment1(dblWin,mesh,wallHeight){const doorList=dblWin,MobileX=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!0),MobileY=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!1);let startingPoint=BayWindow.Instance.xinLine(MobileX,MobileY,doorList.start,wallHeight),finishLine=BayWindow.Instance.xinLine(MobileX,MobileY,doorList.end,wallHeight);return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.winHoleOpening(startingPoint,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}TheHandlingOfTheDoor1(data){const wallHeightc=data.userData.height?data.userData.height:this.wallHeight,doorList=data,MobileX=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,DEFAULT_WALL_HALF_WIDTH+.01,!0),MobileY=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,DEFAULT_WALL_HALF_WIDTH+.01,!1);let startingPoint=this.xinLine(MobileX,MobileY,doorList.start,doorList.userData.height?doorList.userData.height:this.wallHeight),finishLine=this.xinLine(MobileX,MobileY,doorList.end,doorList.userData.height?doorList.userData.height:this.wallHeight);const quadtree=Quadtree.from(this.lines),doorPoint=doorList.start,doorPoint1=doorList.end;let statua=!1,statub=!1;if(statua=quadtree.queryPoint(doorPoint).some(item=>item.line.isPerpendicularTo(doorList,20)&&!LineGroupType.hasType(item.line,"doubleWall")),statub=quadtree.queryPoint(doorPoint1).some(item=>item.line.isPerpendicularTo(doorList,20)&&!LineGroupType.hasType(item.line,"doubleWall")),statua&&!statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc);return startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),startingPoint1}if(!statua&&statub){let finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);return startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),startingPoint}if(statua&&statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);return startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),startingPoint1}return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),startingPoint}TheHandlingOfTheDoor(data){const doorList=data;for(const i in doorList){const wallHeightc=data[i].userData.height?data[i].userData.height:this.wallHeight,point1=new THREE.Vector3(doorList[i].start.x,doorList[i].start.y,0),point2=new THREE.Vector3(doorList[i].end.x,doorList[i].end.y,0),point3=new THREE.Vector3(doorList[i].center.x,doorList[i].center.y,0),dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),MobileX=this.angleToXAxisDegrees(doorList[i].start.x,doorList[i].start.y,doorList[i].end.x,doorList[i].end.y,DEFAULT_WALL_HALF_WIDTH+.01,!0),MobileY=this.angleToXAxisDegrees(doorList[i].start.x,doorList[i].start.y,doorList[i].end.x,doorList[i].end.y,DEFAULT_WALL_HALF_WIDTH+.01,!1);let startingPoint=this.xinLine(MobileX,MobileY,doorList[i].start,doorList[i].userData.height?doorList[i].userData.height:this.wallHeight),finishLine=this.xinLine(MobileX,MobileY,doorList[i].end,doorList[i].userData.height?doorList[i].userData.height:this.wallHeight);const quadtree=Quadtree.from(this.lines),doorPoint=doorList[i].start,doorPoint1=doorList[i].end;let statua=!1,statub=!1;if(statua=quadtree.queryPoint(doorPoint).some(item=>item.line.isPerpendicularTo(doorList[i],20)&&!LineGroupType.hasType(item.line,"doubleWall")),statub=quadtree.queryPoint(doorPoint1).some(item=>item.line.isPerpendicularTo(doorList[i],20)&&!LineGroupType.hasType(item.line,"doubleWall")),statua&&!statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc);startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.doorHoleOpening(wallHeightc,startingPoint1,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData?.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_HALF_WIDTH,this.doorCenterOffset(.03,doorList[i].end,point3),angleRad,i,doorList[i])}else if(!statua&&statub){let finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.doorHoleOpening(wallHeightc,startingPoint,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_HALF_WIDTH,this.doorCenterOffset(.03,doorList[i].start,point3),angleRad,i,doorList[i])}else if(statua&&statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.doorHoleOpening(wallHeightc,startingPoint1,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_WIDTH,point3,angleRad,i,doorList[i])}else startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.doorHoleOpening(wallHeightc,startingPoint,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2,point3,angleRad,i,doorList[i])}}doorCenterOffset(distanceFromB,point2,pointc){point2=new THREE.Vector3(point2.x,point2.y,0);const direction=(new THREE.Vector3).subVectors(pointc,point2).normalize();return(new THREE.Vector3).copy(pointc).addScaledVector(direction.negate(),distanceFromB)}installWindows(data,lineCy){const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??this.WindowGroundHeight)+this.height;let menModel=this.windowModely.clone();if(data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,groundClearance),this.windowNum=this.windowNum+1,menModel.name=`窗_${this.windowNum}`,menModel.userData.category="window",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.group.add(menModel)}}dataPresentationEffect(data){}singleLineWallMountedDoor(data,lineCy){const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??this.doorGroundHeight)+this.height;let menModel;if(menModel=distance2>=1.5?this.doubleDoorModely.clone():this.doorModely.clone(),data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,groundClearance),this.doorNum=this.doorNum+1,menModel.name=`门_${this.doorNum}`,menModel.userData.category="door",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.group.add(menModel)}}installBalconys(data,index2){let balconyGroup=new Group$1;balconyGroup.name=`阳台${index2}`,balconyGroup.userData.category="balcony",balconyGroup.userData.height=data.userData.height,balconyGroup.userData.width=data.length,balconyGroup.userData.depth=0,balconyGroup.userData.groundHeight=0;const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18;data.userData.groundClearance??this.WindowGroundHeight,this.height;let menModel=this.balconyModely.clone();if(distance2<1.2){if(data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,this.height),menModel.name=`阳台_${index2}`,menModel.userData.category="balcony_",balconyGroup.add(menModel),this.group.add(balconyGroup)}}else{let splitLineInto7Points=function(startPoint,endPoint){const points2=[],startVec=new THREE.Vector3(startPoint.x,startPoint.y,startPoint.z),endVec=new THREE.Vector3(endPoint.x,endPoint.y,endPoint.z);for(let i=0;i<=npc;i++){const fraction=i/npc,point3=new THREE.Vector3;point3.lerpVectors(startVec,endVec,fraction),points2.push(point3)}return points2},npc=0;npc=distance2/.8,npc=Math.round(npc);const points=splitLineInto7Points(point1,point2);for(let o=0;o<points.length-1;o++){const spacing=points[o].distanceTo(points[o+1]),center=new THREE.Vector3;center.lerpVectors(points[o],points[o+1],.5);let balconyModel=this.balconyModely.clone();const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),balconyModel.rotation.x=Math.PI/2,balconyModel.rotation.y=angleRad,balconyModel.scale.set(spacing/size2.x,height/size2.y,wallWidth/size2.z),balconyModel.position.set(center.x,center.y,this.height),balconyModel.name=`阳台_${index2}`,balconyModel.userData.category="balcony_",balconyGroup.add(balconyModel)}this.group.add(balconyGroup)}}installCabinet(){let cabinetModel=this.CabinetModel.clone();cabinetModel.position.set(5,5,0);const box32=new THREE.Box3;box32.setFromObject(cabinetModel);let size2=new THREE.Vector3;box32.getSize(size2),cabinetModel.rotation.x=Math.PI/2,cabinetModel.scale.set(.7/size2.x,.7/size2.y,.3/size2.z),this.group.add(cabinetModel)}installTable(){let tableModel=this.tableModel.clone();tableModel.position.set(5,4,0);const box32=new THREE.Box3;box32.setFromObject(tableModel);let size2=new THREE.Vector3;box32.getSize(size2),tableModel.rotation.x=Math.PI/2,tableModel.scale.set(.7/size2.x,.75/size2.y,1.3/size2.z),this.group.add(tableModel)}installchair(){let tableModel=this.tableModel.clone();tableModel.position.set(5,4,0);const box32=new THREE.Box3;box32.setFromObject(tableModel);let size2=new THREE.Vector3;box32.getSize(size2),tableModel.rotation.x=Math.PI/2,tableModel.scale.set(.7/size2.x,.75/size2.y,1.3/size2.z),this.group.add(tableModel)}winHoleOpening(data,mesh,winGroundHeight,Height){winGroundHeight=(winGroundHeight??this.WindowGroundHeight)+this.height;const basePoints=[new THREE.Vector3(data[0].x,data[0].y,winGroundHeight),new THREE.Vector3(data[1].x,data[1].y,winGroundHeight),new THREE.Vector3(data[2].x,data[2].y,winGroundHeight),new THREE.Vector3(data[3].x,data[3].y,winGroundHeight)],geometry=this.createParallelepipedFromBase(basePoints,Height??this.WindowHeight);new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide});const brush1=new Brush(mesh.geometry);brush1.updateMatrixWorld();const brush2=new Brush(geometry);brush2.updateMatrixWorld();const result=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION);return result.material=mesh.material,"beam"!==mesh.userData.category&&"passageEntrance"!==mesh.userData.category||(result.name=mesh.name,result.userData=mesh.userData),result}doorHoleOpening(wallHeight,data,data1,groundHeight,Height,distance2,center,angleRad,index2,doorList){groundHeight=(groundHeight??this.doorGroundHeight)+this.height;const basePoints=[new THREE.Vector3(data[0].x,data[0].y,groundHeight),new THREE.Vector3(data[1].x,data[1].y,groundHeight),new THREE.Vector3(data[2].x,data[2].y,groundHeight),new THREE.Vector3(data[3].x,data[3].y,groundHeight)],basePoints1=[new THREE.Vector3(data1[0].x,data1[0].y,groundHeight),new THREE.Vector3(data1[1].x,data1[1].y,groundHeight),new THREE.Vector3(data1[2].x,data1[2].y,groundHeight),new THREE.Vector3(data1[3].x,data1[3].y,groundHeight)],basePoints2=[new THREE.Vector3(data[0].x,data1[0].y,groundHeight),new THREE.Vector3(data[1].x,data1[1].y,groundHeight),new THREE.Vector3(data[2].x,data1[2].y,groundHeight),new THREE.Vector3(data[3].x,data1[3].y,groundHeight)],geometry=this.createParallelepipedFromBase(basePoints,wallHeight),geometry1=this.createParallelepipedFromBase(basePoints1,Height||this.doorHeight),geometry2=this.createParallelepipedFromBase(basePoints2,Height||this.doorHeight),brush1=new Brush(geometry);brush1.updateMatrixWorld();const brush2=new Brush(geometry1);brush2.updateMatrixWorld();const result=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),material1=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide});result.material=material1,new THREE.Mesh(geometry2,material);const edges=new THREE.EdgesGeometry(result.geometry);let menModel;if(new THREE.EdgesGeometry(geometry2),new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),menModel=distance2>=1.5?this.doubleDoorModely.clone():this.doorModely.clone(),center&&distance2){menModel.position.set(center.x,center.y,groundHeight);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,(Height||this.doorHeight)/size2.y,DEFAULT_WALL_WIDTH/size2.z),menModel.name=`门_${index2}`,menModel.userData.category="door",menModel.userData.uuid=doorList?.uuid,menModel.userData.width=distance2,menModel.userData.height=Height||this.doorHeight,menModel.userData.groundHeight=groundHeight,this.group.add(menModel)}result.name=`额墙_${index2}`,result.userData.category="partitionWall",this.group.add(result)}angleToXAxisDegrees(x1,y1,x2,y2,wide,cd){const dx=x2-x1,dy=y2-y1;return cd?wide*Math.sin(Math.atan2(dy,dx)):wide*Math.cos(Math.atan2(dy,dx))}xinLine(x,y,point2,wallHeight){let xOverflow=x>0?.001:-.001,YOverflow=y>0?.001:-.001;return[new THREE.Vector3(point2.x+x-xOverflow,point2.y-y-YOverflow,wallHeight),new THREE.Vector3(point2.x-x-xOverflow,point2.y+y-YOverflow,wallHeight)]}expandRectangleAlongLongSide(p1,p2,p3,p4,expandAmount=.01){const edge12=(new THREE.Vector3).copy(p2).sub(p1),edge23=(new THREE.Vector3).copy(p3).sub(p2),edge34=(new THREE.Vector3).copy(p4).sub(p3),edge41=(new THREE.Vector3).copy(p1).sub(p4),len12=edge12.length(),len23=edge23.length(),len34=edge34.length(),len41=edge41.length();let longEdgeDirection,longEdgeStart1,longEdgeEnd1,longEdgeStart2,longEdgeEnd2;len12>=len23&&len12>=len34&&len12>=len41?(longEdgeDirection=edge12.clone().normalize(),edge23.clone().normalize(),longEdgeStart1=p1,longEdgeEnd1=p2,longEdgeStart2=p4,longEdgeEnd2=p3):len23>=len12&&len23>=len34&&len23>=len41?(longEdgeDirection=edge23.clone().normalize(),edge34.clone().normalize(),longEdgeStart1=p2,longEdgeEnd1=p3,longEdgeStart2=p1,longEdgeEnd2=p4):len34>=len12&&len34>=len23&&len34>=len41?(longEdgeDirection=edge34.clone().normalize(),edge41.clone().normalize(),longEdgeStart1=p3,longEdgeEnd1=p4,longEdgeStart2=p2,longEdgeEnd2=p1):(longEdgeDirection=edge41.clone().normalize(),edge12.clone().normalize(),longEdgeStart1=p4,longEdgeEnd1=p1,longEdgeStart2=p3,longEdgeEnd2=p2);return[longEdgeStart1.clone().add(longEdgeDirection.clone().multiplyScalar(-expandAmount)),longEdgeEnd1.clone().add(longEdgeDirection.clone().multiplyScalar(expandAmount)),longEdgeEnd2.clone().add(longEdgeDirection.clone().multiplyScalar(expandAmount)),longEdgeStart2.clone().add(longEdgeDirection.clone().multiplyScalar(-expandAmount))]}expandRectangleSimple(p1,p2,p3,p4,expandAmount=.01){const edge12=(new THREE.Vector3).copy(p2).sub(p1),edge14=(new THREE.Vector3).copy(p4).sub(p1),len12=edge12.length(),len14=edge14.length();let longEdgeDir,shortEdgeDir,halfLong,halfShort;len12>=len14?(longEdgeDir=edge12.clone().normalize(),shortEdgeDir=edge14.clone().normalize(),halfLong=len12/2,halfShort=len14/2):(longEdgeDir=edge14.clone().normalize(),shortEdgeDir=edge12.clone().normalize(),halfLong=len14/2,halfShort=len12/2);const center=(new THREE.Vector3).copy(p1).add(p2).add(p3).add(p4).multiplyScalar(.25),newHalfLong=halfLong+expandAmount,newHalfShort=halfShort+expandAmount;return[center.clone().addScaledVector(longEdgeDir,-newHalfLong).addScaledVector(shortEdgeDir,-newHalfShort),center.clone().addScaledVector(longEdgeDir,newHalfLong).addScaledVector(shortEdgeDir,-newHalfShort),center.clone().addScaledVector(longEdgeDir,newHalfLong).addScaledVector(shortEdgeDir,newHalfShort),center.clone().addScaledVector(longEdgeDir,-newHalfLong).addScaledVector(shortEdgeDir,newHalfShort)]}xinLine1(x,y,pointa,pointb,num,wallHeight){let point1,point2;return 0===num?(point1=new THREE.Vector3(pointa.x-x,pointa.y-y,wallHeight),point2=new THREE.Vector3(pointb.x-x,pointb.y-y,wallHeight)):(point1=new THREE.Vector3(pointa.x+x,pointa.y+y,wallHeight),point2=new THREE.Vector3(pointb.x+x,pointb.y+y,wallHeight)),[point1,point2]}createParallelepipedFromBase(points,height){const shape=new THREE.Shape;shape.moveTo(points[0].x,points[0].y);for(const i in points)"0"!==i&&shape.lineTo(points[i].x,points[i].y);shape.lineTo(points[0].x,points[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:height,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+points[0].z);return geometry}correctionSorting(bitem){let listS=[];for(const i in bitem){const abc=2===LineGroupType.getIdsByType(bitem[i],"bayWindow").length;if(0===listS.length){const b4=new THREE.Vector3(bitem[i].start.x,bitem[i].start.y,bitem[i].start.z),c=new THREE.Vector3(bitem[i].end.x,bitem[i].end.y,bitem[i].end.z);listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})}else{const b4=new THREE.Vector3(bitem[i].start.x,bitem[i].start.y,bitem[i].start.z),c=new THREE.Vector3(bitem[i].end.x,bitem[i].end.y,bitem[i].end.z),distanceAB=listS[listS.length-1].dian.distanceTo(b4),distanceAC=listS[listS.length-1].dian.distanceTo(c);distanceAB<distanceAC?(listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})):distanceAC<distanceAB?(listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})):(listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}))}}return listS}balconyTreatment(bayWinList){for(const i in bayWinList){let lines=bayWinList[i].lines;for(const o in lines)if(lines[o].userData.isBayWindow){let Mesh=this.overhangWallOffset(lines[o],i,bayWinList[i].data.height3);this.group.add(Mesh);let Mesh1=this.dashedLineCeilingTreatment(lines[o],i,bayWinList[i].data);this.group.add(Mesh1)}}}overhangWallOffset(data,index2,height){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,height)}dashedLineCeilingTreatment(data,index2,item){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let basePoints=[];const startingPointZ=this.height+item.height3+item.height2;for(const i in startingPoint)basePoints.push(new THREE.Vector3(startingPoint[i].x,startingPoint[i].y,startingPointZ));if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const shape=new THREE.Shape;shape.moveTo(basePoints[0].x,basePoints[0].y);for(const i in basePoints)"0"!==i&&shape.lineTo(basePoints[i].x,basePoints[i].y);shape.lineTo(basePoints[0].x,basePoints[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:item.height1,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+basePoints[0].z);const material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);return new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall",cube}}overallTreatmentOfSingleLineWalls(data){let balconyLins=[];for(let i=data.length-1;i>=0;i--)data[i].userData.isBalconyRailing&&(balconyLins.push(data[i]),data.splice(i,1));for(const o in balconyLins)this.installBalconys(balconyLins[o],o);const grid=PointSpatialHash.fromByLines(this.lines);let listS=this.correctionSorting(data);for(const i in listS)Number(i)%2==0&&Number(i)!==listS.length-1&&this.singleLines.push({start:listS[i].dian,end:listS[Number(i)+1].dian,index:i});for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2,winDraw=WallHoleDrawData.singleHoleLine(data[Number(x)/2],grid);this.dataPresentationEffect(winDraw),Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x};const wallHeight=listS[x].wallHeight;let Mesh,status=!1;for(const y in winDraw)"beam"===winDraw[Number(y)].userData.type&&(status=!0,Mesh=this.generateBeamModel(data[Number(x)/2]));if(status){Mesh&&this.group.add(Mesh);continue}Mesh=this.executionOffset(a2,Number(x)/2,wallHeight,winDraw,data[Number(x)/2]);for(const y in winDraw)"beam"===winDraw[Number(y)].userData.type&&(Mesh.userData.start=a2.start,Mesh.userData.end=a2.end);if(Mesh)if(winDraw&&winDraw.length>0){let houMesh=null;for(const s in winDraw)if(1===winDraw.length){const edges=new THREE.EdgesGeometry(this.windowTreatment(winDraw[s],Mesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]);let mesh=this.windowTreatment(winDraw[s],Mesh,wallHeight);this.group.add(mesh)}else if(houMesh)if(Number(s)===winDraw.length-1){const edges=new THREE.EdgesGeometry(this.windowTreatment(winDraw[s],houMesh,wallHeight).geometry);"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0}));let mesh=this.windowTreatment(winDraw[s],houMesh,wallHeight);this.group.add(mesh)}else"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"beam"===winDraw[s].userData.type?console.log("梁"):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),houMesh=this.windowTreatment(winDraw[s],houMesh,wallHeight);else"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"beam"===winDraw[s].userData.type?console.log("梁"):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),houMesh=this.windowTreatment(winDraw[s],Mesh,wallHeight)}else this.group.add(Mesh)}}generateBeamModel(line){let basePoints,expansionPoints,cube;if(line.userData.expansionWidth||line.userData.expansionDirction){const directionX=line.userData.expansionDirction.x*line.userData.expansionWidth,directionY=line.userData.expansionDirction.y*line.userData.expansionWidth;let pointStart=new THREE.Vector3(line.start.x,line.start.y,this.height?this.height:0),pointEnd=new THREE.Vector3(line.end.x,line.end.y,this.height?this.height:0),startExpansion=new THREE.Vector3(pointStart.x+directionX,pointStart.y+directionY,this.height?this.height:0);basePoints=[pointStart,pointEnd,new THREE.Vector3(pointEnd.x+directionX,pointEnd.y+directionY,this.height?this.height:0),startExpansion];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material2=new THREE.MeshStandardMaterial({color:5214420,side:THREE.DoubleSide}),beamList=WallHoleDrawData.singleHoleLine(line);cube=new THREE.Mesh(geometry,material2);for(const w in beamList)cube=this.pierceTheBeam(cube,beamList[Number(w)],line,1)}else{let wallWidth;wallWidth=line.userData.wallWidth?line.userData.wallWidth/2:.06;const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wallWidth,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wallWidth,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0);basePoints=[startingPoint[0],startingPoint[1],finishLine[1],finishLine[0]];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material2=new THREE.MeshStandardMaterial({color:5214420,side:THREE.DoubleSide}),beamList=WallHoleDrawData.singleHoleLine(line);cube=new THREE.Mesh(geometry,material2);for(const w in beamList)cube=this.pierceTheBeam(cube,beamList[Number(w)],wallWidth,0)}const material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),beamLint=WallHoleDrawData.singleHoleLine(line),point1=new THREE.Vector3(basePoints[0].x,basePoints[0].y,basePoints[0].z+beamLint[0].userData.height-.001),point2=new THREE.Vector3(basePoints[1].x,basePoints[1].y,basePoints[1].z+beamLint[0].userData.height-.001),point3=new THREE.Vector3(basePoints[2].x,basePoints[2].y,basePoints[2].z+beamLint[0].userData.height-.001),point4=new THREE.Vector3(basePoints[3].x,basePoints[3].y,basePoints[3].z+beamLint[0].userData.height-.001);expansionPoints=this.expandRectangleSimple(point1,point2,point3,point4,.001);const bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height-beamLint[0].userData.height+.002),brush1=new Brush(cube.geometry);brush1.updateMatrixWorld();const brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();const wallCube=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION);wallCube.material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),this.group.add(wallCube);const result=new THREE.Mesh(bodyGeometry,material);return this.liangNum=this.liangNum+1,result.name=`梁_${this.liangNum}`,result.userData.category="beam",result.userData.width=line.length,result.userData.depth=line.userData.expansionWidth??line.userData.wallWidth??DEFAULT_WALL_WIDTH,result.userData.height=line.userData.height-(line.userData.passageEntrance[0].groundClearance+line.userData.passageEntrance[0].height),result.userData.groundHeight=line.userData.passageEntrance[0].groundClearance+line.userData.passageEntrance[0].height,result}pierceTheBeam(model,line,wall,num){if(num){const brush1=new Brush(model.geometry),directionX=wall.userData.expansionDirction.x*wall.userData.expansionWidth,directionY=wall.userData.expansionDirction.y*wall.userData.expansionWidth;let pointStart=new THREE.Vector3(line.start.x,line.start.y,this.height?this.height:0),pointEnd=new THREE.Vector3(line.end.x,line.end.y,this.height?this.height:0),startExpansion=new THREE.Vector3(pointStart.x+directionX,pointStart.y+directionY,this.height?this.height:0),endExpansion=new THREE.Vector3(pointEnd.x+directionX,pointEnd.y+directionY,this.height?this.height:0);const expansionPoints=this.expandRectangleSimple(pointStart,pointEnd,endExpansion,startExpansion,.01),bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height),brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();return(new Evaluator).evaluate(brush1,brush2,SUBTRACTION)}{const brush1=new Brush(model.geometry);brush1.updateMatrixWorld();const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wall,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wall,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0);const expansionPoints=this.expandRectangleSimple(startingPoint[0],startingPoint[1],finishLine[1],finishLine[0],.01),bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height),brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();return(new Evaluator).evaluate(brush1,brush2,SUBTRACTION)}}generateColumnModel(data,lines,Height){let basePoints=[];for(const i in data)basePoints.push(new THREE.Vector3(data[i].x,data[i].y,this.height?this.height:0));let longerSide=0,shortSide=100;for(const w in lines)lines[w].length>longerSide&&(longerSide=lines[w].length),lines[w].length<shortSide&&(shortSide=lines[w].length);if(4===basePoints.length){if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const geometry=this.createParallelepipedFromBase(basePoints,Height),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return this.zhuNum=this.zhuNum+1,cube.name=`柱_${this.zhuNum}`,cube.userData.category="pillar",cube.userData.width=longerSide,cube.userData.depth=shortSide,cube.userData.height=Height,cube.userData.groundHeight=0,cube}}{const geometry=this.createParallelepipedFromBase(basePoints,Height),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return this.zhuNum=this.zhuNum+1,cube.name=`柱_${this.zhuNum}`,cube.userData.category="pillar",cube.userData.width=longerSide,cube.userData.depth=shortSide,cube.userData.height=Height,cube.userData.groundHeight=0,cube}}processTheColumnData(lines){let pillarHeight=0;for(const w in lines)lines[w].userData.height>pillarHeight&&(pillarHeight=lines[w].userData.height);let distance2,bitem=lines.slice(),listS=this.correctionSorting(bitem),sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i=0;i<listS.length-1;i++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));let c=objectiveList.map(pos=>(pos.dian.x=parseFloat(pos.dian.x.toFixed(6)),pos.dian.y=parseFloat(pos.dian.y.toFixed(6)),pos)),d2=[];for(const i in c)d2.push(new THREE.Vector3(c[i].dian.x,c[i].dian.y,c[i].dian.z));const seen=/* @__PURE__ */new Set,E=d2.filter(coord=>{const key=JSON.stringify(coord);return!seen.has(key)&&(seen.add(key),!0)});let mesh=this.generateColumnModel(E,lines,pillarHeight);this.group.add(mesh)}addThePassModel(line){const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,.5*line.userData.wallWidth,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,.5*line.userData.wallWidth,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0),basePoints=[startingPoint[0],startingPoint[1],finishLine[1],finishLine[0]];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material=new THREE.MeshStandardMaterial({color:5214420,transparent:!0,opacity:0,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);"passageEntrance"===line.userData.type&&(this.poortNum=this.poortNum+1,cube.name=`垭口_${this.poortNum}`,cube.userData.category="passageEntrance",cube.userData.height=line.userData.height,cube.userData.width=line.length,cube.userData.depth=line.userData.wallWidth,cube.userData.groundHeight=0),this.group.add(cube)}createAPlane(lines,menList){let precision=lines.map(pos=>(pos.start.x=parseFloat(pos.start.x.toFixed(3)),pos.start.y=parseFloat(pos.start.y.toFixed(3)),pos.end.x=parseFloat(pos.end.x.toFixed(3)),pos.end.y=parseFloat(pos.end.y.toFixed(3)),pos)),points=[],head=null,theTail=null;for(const x in precision)"0"===x?(head=precision[x].start,theTail=precision[x].end,points.push([precision[x].start.x,precision[x].start.y]),points.push([precision[x].end.x,precision[x].end.y])):precision[x].start.x===head.x&&precision[x].start.y===head.y?(points.push([precision[x].end.x,precision[x].end.y]),theTail=precision[x].end):precision[x].end.x===head.x&&precision[x].end.y===head.y?(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start):precision[x].start.x===theTail.x&&precision[x].start.y===theTail.y?(points.push([precision[x].end.x,precision[x].end.y]),head=theTail,theTail=precision[x].end):precision[x].end.x===theTail.x&&precision[x].end.y===theTail.y?(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start):(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start,points.push([precision[x].end.x,precision[x].end.y]),theTail=precision[x].end)}async modelLoader(){this.doorModely=await LoadModel.loadGlb("door"),this.doubleDoorModely=await LoadModel.loadGlb("doubleDoor")}async windowModelLoader(){this.windowModely=await LoadModel.loadGlb("window")}async balconyModelLoader(){this.balconyModely=await LoadModel.loadGlb("balconyFilmFilmFilm")}damian(){const planeGeometry=new THREE.BufferGeometry,vertices=new Float32Array([-20,-20,0,20,-20,0,20,20,0,-20,20,0]);planeGeometry.setAttribute("position",new THREE.BufferAttribute(vertices,3));const planeMaterial=new THREE.MeshBasicMaterial({color:15066597,side:THREE.DoubleSide}),indices=new Uint16Array([0,1,2,2,3,0]);planeGeometry.setIndex(new THREE.BufferAttribute(indices,1));const plane=new THREE.Mesh(planeGeometry,planeMaterial);this.group.add(plane)}drawStaircase=pcdPointsArr=>{console.log(pcdPointsArr);const pointCloudGroup=new THREE.Group,material=new THREE.MeshStandardMaterial({color:16737792,side:THREE.DoubleSide});for(let i=0;i<pcdPointsArr.length;i++){const points=[];for(let j=0;j<pcdPointsArr[i].path.length;j++)points.push(new THREE.Vector3(pcdPointsArr[i].path[j][0],pcdPointsArr[i].path[j][1],0));if(0==points.length)continue;let bottom1=new THREE.Vector3(pcdPointsArr[i].stairBottomPt1.x,pcdPointsArr[i].stairBottomPt1.y,pcdPointsArr[i].stairBottomPt1.z),bottom2=new THREE.Vector3(pcdPointsArr[i].stairBottomPt2.x,pcdPointsArr[i].stairBottomPt2.y,pcdPointsArr[i].stairBottomPt2.z);for(let x=0;x<pcdPointsArr[i].stairStepNum;x++){let rectArray=[bottom1,bottom2];rectArray.push(bottom2.clone().addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth)),rectArray.push(bottom1.clone().addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth));let boxGeometry=this.createBoxGeometryFromRectPoints(rectArray,pcdPointsArr[i].stairStepHeight);const mesh=new THREE.Mesh(boxGeometry,material);pointCloudGroup.add(mesh),bottom1=bottom1.addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth),bottom1=bottom1.addScaledVector(new THREE.Vector3(0,0,1),pcdPointsArr[i].stairStepHeight),bottom2=bottom2.addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth),bottom2=bottom2.addScaledVector(new THREE.Vector3(0,0,1),pcdPointsArr[i].stairStepHeight)}if(0!=pcdPointsArr[i].rectPt1.x&&0!=pcdPointsArr[i].rectPt1.y){let rectArray=[pcdPointsArr[i].stairBottomPt1,pcdPointsArr[i].stairBottomPt2,pcdPointsArr[i].rectPt2,pcdPointsArr[i].rectPt1],boxGeometry=this.createBoxGeometryFromRectPoints(rectArray,pcdPointsArr[i].stairStepHeight);const mesh=new THREE.Mesh(boxGeometry,material);pointCloudGroup.add(mesh)}}return pointCloudGroup};createBoxGeometryFromRectPoints=(rectPoints,height)=>{const p0=rectPoints[0],p1=rectPoints[1],p2=rectPoints[2],p3=rectPoints[3],xDir=(new THREE.Vector3).subVectors(p1,p0),yDir=(new THREE.Vector3).subVectors(p3,p0),width=xDir.length(),depth=yDir.length();xDir.normalize(),yDir.normalize();const zDir=new THREE.Vector3(0,0,1),boxCenter=(new THREE.Vector3).add(p0).add(p1).add(p2).add(p3).multiplyScalar(.25).clone().addScaledVector(zDir,height/2),geometry=new THREE.BoxGeometry(width,depth,height),matrix2=new THREE.Matrix4;return matrix2.makeBasis(xDir,yDir,zDir),matrix2.setPosition(boxCenter),geometry.applyMatrix4(matrix2),geometry.computeVertexNormals(),geometry}}function Rr(t2,e,n=0,r2=t2.length-1,i=Mu){for(;r2>n;){if(r2-n>600){const f=r2-n+1,l=e-n+1,a2=Math.log(f),c=.5*Math.exp(2*a2/3),D2=.5*Math.sqrt(a2*c*(f-c)/f)*(l-f/2<0?-1:1);Rr(t2,e,Math.max(n,Math.floor(e-l*c/f+D2)),Math.min(r2,Math.floor(e+(f-l)*c/f+D2)),i)}const u2=t2[e];let o=n,s=r2;for(Xe(t2,n,e),i(t2[r2],u2)>0&&Xe(t2,n,r2);o<s;){for(Xe(t2,o,s),o++,s--;i(t2[o],u2)<0;)o++;for(;i(t2[s],u2)>0;)s--}0===i(t2[n],u2)?Xe(t2,n,s):(s++,Xe(t2,s,r2)),s<=e&&(n=s+1),e<=s&&(r2=s-1)}}function Xe(t2,e,n){const r2=t2[e];t2[e]=t2[n],t2[n]=r2}function Mu(t2,e){return t2<e?-1:t2>e?1:0}class Kn{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const r2=[];if(!tn(e,n))return r2;const i=this.toBBox,u2=[];for(;n;){for(let o=0;o<n.children.length;o++){const s=n.children[o],f=n.leaf?i(s):s;tn(e,f)&&(n.leaf?r2.push(s):xn(e,f)?this._all(s,r2):u2.push(s))}n=u2.pop()}return r2}collides(e){let n=this.data;if(!tn(e,n))return!1;const r2=[];for(;n;){for(let i=0;i<n.children.length;i++){const u2=n.children[i],o=n.leaf?this.toBBox(u2):u2;if(tn(e,o)){if(n.leaf||xn(e,o))return!0;r2.push(u2)}}n=r2.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let r2=0;r2<e.length;r2++)this.insert(e[r2]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const r2=this.data;this.data=n,n=r2}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=xe([]),this}remove(e,n){if(!e)return this;let r2=this.data;const i=this.toBBox(e),u2=[],o=[];let s,f,l;for(;r2||u2.length;){if(r2||(r2=u2.pop(),f=u2[u2.length-1],s=o.pop(),l=!0),r2.leaf){const a2=Nu(e,r2.children,n);if(-1!==a2)return r2.children.splice(a2,1),u2.push(r2),this._condense(u2),this}l||r2.leaf||!xn(r2,i)?f?(s++,r2=f.children[s],l=!1):r2=null:(u2.push(r2),o.push(s),s=0,f=r2,r2=r2.children[0])}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const r2=[];for(;e;)e.leaf?n.push(...e.children):r2.push(...e.children),e=r2.pop();return n}_build(e,n,r2,i){const u2=r2-n+1;let s,o=this._maxEntries;if(u2<=o)return s=xe(e.slice(n,r2+1)),Ae(s,this.toBBox),s;i||(i=Math.ceil(Math.log(u2)/Math.log(o)),o=Math.ceil(u2/Math.pow(o,i-1))),s=xe([]),s.leaf=!1,s.height=i;const f=Math.ceil(u2/o),l=f*Math.ceil(Math.sqrt(o));jn(e,n,r2,l,this.compareMinX);for(let a2=n;a2<=r2;a2+=l){const c=Math.min(a2+l-1,r2);jn(e,a2,c,f,this.compareMinY);for(let D2=a2;D2<=c;D2+=f){const w=Math.min(D2+f-1,c);s.children.push(this._build(e,D2,w,i-1))}}return Ae(s,this.toBBox),s}_chooseSubtree(e,n,r2,i){for(;i.push(n),!n.leaf&&i.length-1!==r2;){let s,u2=1/0,o=1/0;for(let f=0;f<n.children.length;f++){const l=n.children[f],a2=Nn(l),c=Tu(e,l)-a2;c<o?(o=c,u2=a2<u2?a2:u2,s=l):c===o&&a2<u2&&(u2=a2,s=l)}n=s||n.children[0]}return n}_insert(e,n,r2){const i=r2?e:this.toBBox(e),u2=[],o=this._chooseSubtree(i,this.data,n,u2);for(o.children.push(e),Ze(o,i);n>=0&&u2[n].children.length>this._maxEntries;)this._split(u2,n),n--;this._adjustParentBBoxes(i,u2,n)}_split(e,n){const r2=e[n],i=r2.children.length,u2=this._minEntries;this._chooseSplitAxis(r2,u2,i);const o=this._chooseSplitIndex(r2,u2,i),s=xe(r2.children.splice(o,r2.children.length-o));s.height=r2.height,s.leaf=r2.leaf,Ae(r2,this.toBBox),Ae(s,this.toBBox),n?e[n-1].children.push(s):this._splitRoot(r2,s)}_splitRoot(e,n){this.data=xe([e,n]),this.data.height=e.height+1,this.data.leaf=!1,Ae(this.data,this.toBBox)}_chooseSplitIndex(e,n,r2){let i,u2=1/0,o=1/0;for(let s=n;s<=r2-n;s++){const f=Le(e,0,s,this.toBBox),l=Le(e,s,r2,this.toBBox),a2=bu(f,l),c=Nn(f)+Nn(l);a2<u2?(u2=a2,i=s,o=c<o?c:o):a2===u2&&c<o&&(o=c,i=s)}return i||r2-n}_chooseSplitAxis(e,n,r2){const i=e.leaf?this.compareMinX:xu,u2=e.leaf?this.compareMinY:Su;this._allDistMargin(e,n,r2,i)<this._allDistMargin(e,n,r2,u2)&&e.children.sort(i)}_allDistMargin(e,n,r2,i){e.children.sort(i);const u2=this.toBBox,o=Le(e,0,n,u2),s=Le(e,r2-n,r2,u2);let f=je(o)+je(s);for(let l=n;l<r2-n;l++){const a2=e.children[l];Ze(o,e.leaf?u2(a2):a2),f+=je(o)}for(let l=r2-n-1;l>=n;l--){const a2=e.children[l];Ze(s,e.leaf?u2(a2):a2),f+=je(s)}return f}_adjustParentBBoxes(e,n,r2){for(let i=r2;i>=0;i--)Ze(n[i],e)}_condense(e){for(let r2,n=e.length-1;n>=0;n--)0===e[n].children.length?n>0?(r2=e[n-1].children,r2.splice(r2.indexOf(e[n]),1)):this.clear():Ae(e[n],this.toBBox)}}function Nu(t2,e,n){if(!n)return e.indexOf(t2);for(let r2=0;r2<e.length;r2++)if(n(t2,e[r2]))return r2;return-1}function Ae(t2,e){Le(t2,0,t2.children.length,e,t2)}function Le(t2,e,n,r2,i){i||(i=xe(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let u2=e;u2<n;u2++){const o=t2.children[u2];Ze(i,t2.leaf?r2(o):o)}return i}function Ze(t2,e){return t2.minX=Math.min(t2.minX,e.minX),t2.minY=Math.min(t2.minY,e.minY),t2.maxX=Math.max(t2.maxX,e.maxX),t2.maxY=Math.max(t2.maxY,e.maxY),t2}function xu(t2,e){return t2.minX-e.minX}function Su(t2,e){return t2.minY-e.minY}function Nn(t2){return(t2.maxX-t2.minX)*(t2.maxY-t2.minY)}function je(t2){return t2.maxX-t2.minX+(t2.maxY-t2.minY)}function Tu(t2,e){return(Math.max(e.maxX,t2.maxX)-Math.min(e.minX,t2.minX))*(Math.max(e.maxY,t2.maxY)-Math.min(e.minY,t2.minY))}function bu(t2,e){const n=Math.max(t2.minX,e.minX),r2=Math.max(t2.minY,e.minY),i=Math.min(t2.maxX,e.maxX),u2=Math.min(t2.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,u2-r2)}function xn(t2,e){return t2.minX<=e.minX&&t2.minY<=e.minY&&e.maxX<=t2.maxX&&e.maxY<=t2.maxY}function tn(t2,e){return e.minX<=t2.maxX&&e.minY<=t2.maxY&&e.maxX>=t2.minX&&e.maxY>=t2.minY}function xe(t2){return{children:t2,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function jn(t2,e,n,r2,i){const u2=[e,n];for(;u2.length;){if((n=u2.pop())-(e=u2.pop())<=r2)continue;const o=e+Math.ceil((n-e)/r2/2)*r2;Rr(t2,o,e,n,i),u2.push(e,o,o,n)}}class Iu{constructor(e=[],n=(r2,i)=>r2<i?-1:r2>i?1:0){if(this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(let r2=(this.length>>1)-1;r2>=0;r2--)this._down(r2)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],n=this.data.pop();return--this.length>0&&(this.data[0]=n,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:n,compare:r2}=this,i=n[e];for(;e>0;){const u2=e-1>>1,o=n[u2];if(r2(i,o)>=0)break;n[e]=o,e=u2}n[e]=i}_down(e){const{data:n,compare:r2}=this,i=this.length>>1,u2=n[e];for(;e<i;){let o=1+(e<<1);const s=o+1;if(s<this.length&&r2(n[s],n[o])<0&&(o=s),r2(n[o],u2)>=0)break;n[e]=n[o],e=o}n[e]=u2}}function qr(t2){return t2&&t2.__esModule&&Object.prototype.hasOwnProperty.call(t2,"default")?t2.default:t2}var Sn,tr,Tn,er,nr,$e={exports:{}};const qu=/* @__PURE__ */qr(function(){if(nr)return $e.exports;nr=1;var t2=(tr||(tr=1,Sn=function(e,n,r2,i){var u2=e[0],o=e[1],s=!1;void 0===r2&&(r2=0),void 0===i&&(i=n.length);for(var f=(i-r2)/2,l=0,a2=f-1;l<f;a2=l++){var c=n[r2+2*l+0],D2=n[r2+2*l+1],w=n[r2+2*a2+0],M=n[r2+2*a2+1];D2>o!=M>o&&u2<(w-c)*(o-D2)/(M-D2)+c&&(s=!s)}return s}),Sn),e=(er||(er=1,Tn=function(e,n,r2,i){var u2=e[0],o=e[1],s=!1;void 0===r2&&(r2=0),void 0===i&&(i=n.length);for(var f=i-r2,l=0,a2=f-1;l<f;a2=l++){var c=n[l+r2][0],D2=n[l+r2][1],w=n[a2+r2][0],M=n[a2+r2][1];D2>o!=M>o&&u2<(w-c)*(o-D2)/(M-D2)+c&&(s=!s)}return s}),Tn);return $e.exports=function(r2,i,u2,o){return i.length>0&&Array.isArray(i[0])?e(r2,i,u2,o):t2(r2,i,u2,o)},$e.exports.nested=e,$e.exports.flat=t2,$e.exports}()),ae=11102230246251565e-32,bt=134217729,Yu=(3+8*ae)*ae;function bn(t2,e,n,r2,i){let u2,o,s,f,l=e[0],a2=r2[0],c=0,D2=0;a2>l==a2>-l?(u2=l,l=e[++c]):(u2=a2,a2=r2[++D2]);let w=0;if(c<t2&&D2<n)for(a2>l==a2>-l?(o=l+u2,s=u2-(o-l),l=e[++c]):(o=a2+u2,s=u2-(o-a2),a2=r2[++D2]),u2=o,0!==s&&(i[w++]=s);c<t2&&D2<n;)a2>l==a2>-l?(o=u2+l,f=o-u2,s=u2-(o-f)+(l-f),l=e[++c]):(o=u2+a2,f=o-u2,s=u2-(o-f)+(a2-f),a2=r2[++D2]),u2=o,0!==s&&(i[w++]=s);for(;c<t2;)o=u2+l,f=o-u2,s=u2-(o-f)+(l-f),l=e[++c],u2=o,0!==s&&(i[w++]=s);for(;D2<n;)o=u2+a2,f=o-u2,s=u2-(o-f)+(a2-f),a2=r2[++D2],u2=o,0!==s&&(i[w++]=s);return(0!==u2||0===w)&&(i[w++]=u2),w}function Ge(t2){return new Float64Array(t2)}const Xu=(3+16*ae)*ae,$u=(2+12*ae)*ae,Lu=(9+64*ae)*ae*ae,Ce=Ge(4),rr=Ge(8),ir=Ge(12),ur=Ge(16),qt=Ge(4);function Wu(t2,e,n,r2,i,u2){const o=(e-u2)*(n-i),s=(t2-i)*(r2-u2),f=o-s,l=Math.abs(o+s);return Math.abs(f)>=Xu*l?f:-function(t2,e,n,r2,i,u2,o){let s,f,l,a2,c,D2,w,M,h2,g,p2,E,F,A,d2,m,C,y;const B2=t2-i,x=n-i,T=e-u2,q=r2-u2;A=B2*q,D2=bt*B2,w=D2-(D2-B2),M=B2-w,D2=bt*q,h2=D2-(D2-q),g=q-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=T*x,D2=bt*T,w=D2-(D2-T),M=T-w,D2=bt*x,h2=D2-(D2-x),g=x-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,Ce[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,Ce[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,Ce[2]=E-(y-c)+(p2-c),Ce[3]=y;let Z=function(t2,e){let n=e[0];for(let r2=1;r2<t2;r2++)n+=e[r2];return n}(4,Ce),W=$u*o;if(Z>=W||-Z>=W||(c=t2-B2,s=t2-(B2+c)+(c-i),c=n-x,l=n-(x+c)+(c-i),c=e-T,f=e-(T+c)+(c-u2),c=r2-q,a2=r2-(q+c)+(c-u2),0===s&&0===f&&0===l&&0===a2)||(W=Lu*o+Yu*Math.abs(Z),Z+=B2*a2+q*s-(T*l+x*f),Z>=W||-Z>=W))return Z;A=s*q,D2=bt*s,w=D2-(D2-s),M=s-w,D2=bt*q,h2=D2-(D2-q),g=q-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=f*x,D2=bt*f,w=D2-(D2-f),M=f-w,D2=bt*x,h2=D2-(D2-x),g=x-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const L=bn(4,Ce,4,qt,rr);A=B2*a2,D2=bt*B2,w=D2-(D2-B2),M=B2-w,D2=bt*a2,h2=D2-(D2-a2),g=a2-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=T*l,D2=bt*T,w=D2-(D2-T),M=T-w,D2=bt*l,h2=D2-(D2-l),g=l-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const z=bn(L,rr,4,qt,ir);A=s*a2,D2=bt*s,w=D2-(D2-s),M=s-w,D2=bt*a2,h2=D2-(D2-a2),g=a2-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=f*l,D2=bt*f,w=D2-(D2-f),M=f-w,D2=bt*l,h2=D2-(D2-l),g=l-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const J=bn(z,ir,4,qt,ur);return ur[J-1]}(t2,e,n,r2,i,u2,l)}function Vu(t2,e,n){e=Math.max(0,void 0===e?2:e),n=n||0;const r2=function(t2){let e=t2[0],n=t2[0],r2=t2[0],i=t2[0];for(let s=0;s<t2.length;s++){const f=t2[s];f[0]<e[0]&&(e=f),f[0]>r2[0]&&(r2=f),f[1]<n[1]&&(n=f),f[1]>i[1]&&(i=f)}const u2=[e,n,r2,i],o=u2.slice();for(let s=0;s<t2.length;s++)qu(t2[s],u2)||o.push(t2[s]);return function(t2){t2.sort(Ku);const e=[];for(let r2=0;r2<t2.length;r2++){for(;e.length>=2&&Se(e[e.length-2],e[e.length-1],t2[r2])<=0;)e.pop();e.push(t2[r2])}const n=[];for(let r2=t2.length-1;r2>=0;r2--){for(;n.length>=2&&Se(n[n.length-2],n[n.length-1],t2[r2])<=0;)n.pop();n.push(t2[r2])}return n.pop(),e.pop(),e.concat(n)}(o)}(t2),i=new Kn(16);i.toBBox=function(D2){return{minX:D2[0],minY:D2[1],maxX:D2[0],maxY:D2[1]}},i.compareMinX=function(D2,w){return D2[0]-w[0]},i.compareMinY=function(D2,w){return D2[1]-w[1]},i.load(t2);const u2=[];let o;for(let D2=0;D2<r2.length;D2++){const w=r2[D2];i.remove(w),o=ar(w,o),u2.push(o)}const s=new Kn(16);for(let D2=0;D2<u2.length;D2++)s.insert(In(u2[D2]));const f=e*e,l=n*n;for(;u2.length;){const D2=u2.shift(),w=D2.p,M=D2.next.p,h2=On(w,M);if(h2<l)continue;const g=h2/f,p2=Hu(i,D2.prev.p,w,M,D2.next.next.p,g,s);p2&&Math.min(On(p2,w),On(p2,M))<=g&&(u2.push(D2),u2.push(ar(p2,D2)),i.remove(p2),s.remove(D2),s.insert(In(D2)),s.insert(In(D2.next)))}let a2=o;const c=[];do{c.push(a2.p),a2=a2.next}while(a2!==o);return c.push(a2.p),c}function Hu(t2,e,n,r2,i,u2,o){const s=new Iu([],Ju);let f=t2.data;for(;f;){for(let l=0;l<f.children.length;l++){const a2=f.children[l],c=f.leaf?Pn(a2,n,r2):ku(n,r2,a2);c>u2||s.push({node:a2,dist:c})}for(;s.length&&!s.peek().node.children;){const l=s.pop(),a2=l.node,c=Pn(a2,e,n),D2=Pn(a2,r2,i);if(l.dist<c&&l.dist<D2&&sr(n,a2,o)&&sr(r2,a2,o))return a2}f=s.pop(),f&&(f=f.node)}return null}function Ju(t2,e){return t2.dist-e.dist}function ku(t2,e,n){if(or(t2,n)||or(e,n))return 0;const r2=en(t2[0],t2[1],e[0],e[1],n.minX,n.minY,n.maxX,n.minY);if(0===r2)return 0;const i=en(t2[0],t2[1],e[0],e[1],n.minX,n.minY,n.minX,n.maxY);if(0===i)return 0;const u2=en(t2[0],t2[1],e[0],e[1],n.maxX,n.minY,n.maxX,n.maxY);if(0===u2)return 0;const o=en(t2[0],t2[1],e[0],e[1],n.minX,n.maxY,n.maxX,n.maxY);return 0===o?0:Math.min(r2,i,u2,o)}function or(t2,e){return t2[0]>=e.minX&&t2[0]<=e.maxX&&t2[1]>=e.minY&&t2[1]<=e.maxY}function sr(t2,e,n){const r2=Math.min(t2[0],e[0]),i=Math.min(t2[1],e[1]),u2=Math.max(t2[0],e[0]),o=Math.max(t2[1],e[1]),s=n.search({minX:r2,minY:i,maxX:u2,maxY:o});for(let f=0;f<s.length;f++)if(Gu(s[f].p,s[f].next.p,t2,e))return!1;return!0}function Se(t2,e,n){return Wu(t2[0],t2[1],e[0],e[1],n[0],n[1])}function Gu(t2,e,n,r2){return t2!==r2&&e!==n&&Se(t2,e,n)>0!=Se(t2,e,r2)>0&&Se(n,r2,t2)>0!=Se(n,r2,e)>0}function In(t2){const e=t2.p,n=t2.next.p;return t2.minX=Math.min(e[0],n[0]),t2.minY=Math.min(e[1],n[1]),t2.maxX=Math.max(e[0],n[0]),t2.maxY=Math.max(e[1],n[1]),t2}function ar(t2,e){const n={p:t2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function On(t2,e){const n=t2[0]-e[0],r2=t2[1]-e[1];return n*n+r2*r2}function Pn(t2,e,n){let r2=e[0],i=e[1],u2=n[0]-r2,o=n[1]-i;if(0!==u2||0!==o){const s=((t2[0]-r2)*u2+(t2[1]-i)*o)/(u2*u2+o*o);s>1?(r2=n[0],i=n[1]):s>0&&(r2+=u2*s,i+=o*s)}return u2=t2[0]-r2,o=t2[1]-i,u2*u2+o*o}function en(t2,e,n,r2,i,u2,o,s){const f=n-t2,l=r2-e,a2=o-i,c=s-u2,D2=t2-i,w=e-u2,M=f*f+l*l,h2=f*a2+l*c,g=a2*a2+c*c,p2=f*D2+l*w,E=a2*D2+c*w,F=M*g-h2*h2;let A,d2,m=F,C=F;0===F?(A=0,m=1,d2=E,C=g):(A=h2*E-g*p2,d2=M*E-h2*p2,A<0?(A=0,d2=E,C=g):A>m&&(A=m,d2=E+h2,C=g)),d2<0?(d2=0,-p2<0?A=0:-p2>M?A=m:(A=-p2,m=M)):d2>C&&(d2=C,-p2+h2<0?A=0:-p2+h2>M?A=m:(A=-p2+h2,m=M));const y=0===A?0:A/m,B2=0===d2?0:d2/C,W=(1-B2)*i+B2*o-((1-y)*t2+y*n),L=(1-B2)*u2+B2*s-((1-y)*e+y*r2);return W*W+L*L}function Ku(t2,e){return t2[0]===e[0]?t2[1]-e[1]:t2[0]-e[0]}function fn(){return fn=Object.assign?Object.assign.bind():function(t2){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r2 in n)({}).hasOwnProperty.call(n,r2)&&(t2[r2]=n[r2])}return t2},fn.apply(null,arguments)}var Yr={relTol:1e-12,absTol:1e-15,matrix:"Matrix",number:"number",numberFallback:"number",precision:64,predictable:!1,randomSeed:null};function to(t2,e){if(cn(t2,e))return t2[e];throw"function"==typeof t2[e]&&function(t2,e){return!(null==t2||"function"!=typeof t2[e]||kt(t2,e)&&Object.getPrototypeOf&&e in Object.getPrototypeOf(t2))&&(!!kt(uo,e)||!(e in Object.prototype||e in Function.prototype))}(t2,e)?new Error('Cannot access method "'+e+'" as a property'):new Error('No access to property "'+e+'"')}function cn(t2,e){return!(!function(t2){return"object"==typeof t2&&t2&&t2.constructor===Object}(t2)&&!Array.isArray(t2))&&(!!kt(io,e)||!(e in Object.prototype||e in Function.prototype))}var io={length:!0,name:!0},uo={toString:!0,valueOf:!0,toLocaleString:!0};class oo{constructor(e){this.wrappedObject=e,this[Symbol.iterator]=this.entries}keys(){return Object.keys(this.wrappedObject).filter(e=>this.has(e)).values()}get(e){return to(this.wrappedObject,e)}set(e,n){return function(t2,e,n){if(cn(t2,e))return t2[e]=n,n;throw new Error('No access to property "'+e+'"')}(this.wrappedObject,e,n),this}has(e){return cn(this.wrappedObject,e)&&e in this.wrappedObject}entries(){return t2=this.keys(),e=e=>[e,this.get(e)],{next:()=>{var n=t2.next();return n.done?n:{value:e(n.value),done:!1}}};var t2,e}forEach(e){for(var n of this.keys())e(this.get(n),n,this)}delete(e){cn(this.wrappedObject,e)&&delete this.wrappedObject[e]}clear(){for(var e of this.keys())this.delete(e)}get size(){return Object.keys(this.wrappedObject).length}}function lt(t2){return"number"==typeof t2}function Nt(t2){return!(!t2||"object"!=typeof t2||"function"!=typeof t2.constructor)&&(!0===t2.isBigNumber&&"object"==typeof t2.constructor.prototype&&!0===t2.constructor.prototype.isBigNumber||"function"==typeof t2.constructor.isDecimal&&!0===t2.constructor.isDecimal(t2))}function Ur(t2){return"bigint"==typeof t2}function gn(t2){return t2&&"object"==typeof t2&&!0===Object.getPrototypeOf(t2).isComplex||!1}function vn(t2){return t2&&"object"==typeof t2&&!0===Object.getPrototypeOf(t2).isFraction||!1}function Fn(t2){return t2&&!0===t2.constructor.prototype.isUnit||!1}function jt(t2){return"string"==typeof t2}var At=Array.isArray;function Mt(t2){return t2&&!0===t2.constructor.prototype.isMatrix||!1}function He(t2){return Array.isArray(t2)||Mt(t2)}function Xr(t2){return t2&&t2.isDenseMatrix&&!0===t2.constructor.prototype.isMatrix||!1}function $r(t2){return t2&&t2.isSparseMatrix&&!0===t2.constructor.prototype.isMatrix||!1}function Lr(t2){return t2&&!0===t2.constructor.prototype.isRange||!1}function wn(t2){return t2&&!0===t2.constructor.prototype.isIndex||!1}function Zr(t2){return"boolean"==typeof t2}function Wr(t2){return t2&&!0===t2.constructor.prototype.isResultSet||!1}function Vr(t2){return t2&&!0===t2.constructor.prototype.isHelp||!1}function Hr(t2){return"function"==typeof t2}function Jr(t2){return t2 instanceof Date}function kr(t2){return t2 instanceof RegExp}function qe(t2){return!(!t2||"object"!=typeof t2||t2.constructor!==Object||gn(t2)||vn(t2))}function Ie(t2){return!!t2&&(t2 instanceof Map||t2 instanceof oo||"function"==typeof t2.set&&"function"==typeof t2.get&&"function"==typeof t2.keys&&"function"==typeof t2.has)}function ao(t2){return Ie(t2)&&Ie(t2.a)&&Ie(t2.b)}function fo(t2){return Ie(t2)&&qe(t2.wrappedObject)}function Gr(t2){return null===t2}function Qr(t2){return void 0===t2}function Kr(t2){return t2&&!0===t2.isAccessorNode&&!0===t2.constructor.prototype.isNode||!1}function jr(t2){return t2&&!0===t2.isArrayNode&&!0===t2.constructor.prototype.isNode||!1}function ti(t2){return t2&&!0===t2.isAssignmentNode&&!0===t2.constructor.prototype.isNode||!1}function ei(t2){return t2&&!0===t2.isBlockNode&&!0===t2.constructor.prototype.isNode||!1}function ni(t2){return t2&&!0===t2.isConditionalNode&&!0===t2.constructor.prototype.isNode||!1}function ri(t2){return t2&&!0===t2.isConstantNode&&!0===t2.constructor.prototype.isNode||!1}function ii(t2){return t2&&!0===t2.isFunctionAssignmentNode&&!0===t2.constructor.prototype.isNode||!1}function ui(t2){return t2&&!0===t2.isFunctionNode&&!0===t2.constructor.prototype.isNode||!1}function oi(t2){return t2&&!0===t2.isIndexNode&&!0===t2.constructor.prototype.isNode||!1}function si(t2){return t2&&!0===t2.isNode&&!0===t2.constructor.prototype.isNode||!1}function ai(t2){return t2&&!0===t2.isObjectNode&&!0===t2.constructor.prototype.isNode||!1}function fi(t2){return t2&&!0===t2.isOperatorNode&&!0===t2.constructor.prototype.isNode||!1}function ci(t2){return t2&&!0===t2.isParenthesisNode&&!0===t2.constructor.prototype.isNode||!1}function li(t2){return t2&&!0===t2.isRangeNode&&!0===t2.constructor.prototype.isNode||!1}function hi(t2){return t2&&!0===t2.isRelationalNode&&!0===t2.constructor.prototype.isNode||!1}function Di(t2){return t2&&!0===t2.isSymbolNode&&!0===t2.constructor.prototype.isNode||!1}function pi(t2){return t2&&!0===t2.constructor.prototype.isChain||!1}function me(t2){var e=typeof t2;return"object"===e?null===t2?"null":Nt(t2)?"BigNumber":t2.constructor&&t2.constructor.name?t2.constructor.name:"Object":e}function Dt(t2){var e=typeof t2;if("number"===e||"bigint"===e||"string"===e||"boolean"===e||null==t2)return t2;if("function"==typeof t2.clone)return t2.clone();if(Array.isArray(t2))return t2.map(function(n){return Dt(n)});if(t2 instanceof Date)return new Date(t2.valueOf());if(Nt(t2))return t2;if(qe(t2))return function(t2,e){var n={};for(var r2 in t2)kt(t2,r2)&&(n[r2]=e(t2[r2]));return n}(t2,Dt);if("function"===e)return t2;throw new TypeError("Cannot clone: unknown type of value (value: ".concat(t2,")"))}function di(t2,e){if(Array.isArray(e))throw new TypeError("Arrays are not supported by deepExtend");for(var n in e)if(kt(e,n)&&!(n in Object.prototype)&&!(n in Function.prototype))if(e[n]&&e[n].constructor===Object)void 0===t2[n]&&(t2[n]={}),t2[n]&&t2[n].constructor===Object?di(t2[n],e[n]):t2[n]=e[n];else{if(Array.isArray(e[n]))throw new TypeError("Arrays are not supported by deepExtend");t2[n]=e[n]}return t2}function Pe(t2,e){var n,r2,i;if(Array.isArray(t2)){if(!Array.isArray(e)||t2.length!==e.length)return!1;for(r2=0,i=t2.length;r2<i;r2++)if(!Pe(t2[r2],e[r2]))return!1;return!0}if("function"==typeof t2)return t2===e;if(t2 instanceof Object){if(Array.isArray(e)||!(e instanceof Object))return!1;for(n in t2)if(!(n in e)||!Pe(t2[n],e[n]))return!1;for(n in e)if(!(n in t2))return!1;return!0}return t2===e}function lo(t2){var e={};return mi(t2,e),e}function mi(t2,e){for(var n in t2)if(kt(t2,n)){var r2=t2[n];"object"==typeof r2&&null!==r2?mi(r2,e):e[n]=r2}}function ye(t2,e,n){var i,r2=!0;Object.defineProperty(t2,e,{get:function(){return r2&&(i=n(),r2=!1),i},set:function(o){i=o,r2=!1},configurable:!0,enumerable:!0})}function kt(t2,e){return t2&&Object.hasOwnProperty.call(t2,e)}var fr=["Matrix","Array"],cr=["number","BigNumber","Fraction"];function po(t2,e){function n(r2){if(r2){if(void 0!==r2.epsilon){console.warn('Warning: The configuration option "epsilon" is deprecated. Use "relTol" and "absTol" instead.');var i=Dt(r2);return i.relTol=r2.epsilon,i.absTol=.001*r2.epsilon,delete i.epsilon,n(i)}var u2=Dt(t2);lr(r2,"matrix",fr),lr(r2,"number",cr),di(t2,r2);var o=Dt(t2),s=Dt(r2);return e("config",o,u2,s),o}return Dt(t2)}return n.MATRIX_OPTIONS=fr,n.NUMBER_OPTIONS=cr,Object.keys(Yr).forEach(r2=>{Object.defineProperty(n,r2,{get:()=>t2[r2],enumerable:!0,configurable:!0})}),n}function lr(t2,e,n){void 0!==t2[e]&&!n.includes(t2[e])&&console.warn('Warning: Unknown value "'+t2[e]+'" for configuration option "'+e+'". Available options: '+n.map(r2=>JSON.stringify(r2)).join(", ")+".")}function hr(){return!0}function Vt(){return!1}function Be(){}const Dr="Argument is not a typed-function.";const Je=function gi(){function t2(v2){return"object"==typeof v2&&null!==v2&&v2.constructor===Object}const e=[{name:"number",test:function(v2){return"number"==typeof v2}},{name:"string",test:function(v2){return"string"==typeof v2}},{name:"boolean",test:function(v2){return"boolean"==typeof v2}},{name:"Function",test:function(v2){return"function"==typeof v2}},{name:"Array",test:Array.isArray},{name:"Date",test:function(v2){return v2 instanceof Date}},{name:"RegExp",test:function(v2){return v2 instanceof RegExp}},{name:"Object",test:t2},{name:"null",test:function(v2){return null===v2}},{name:"undefined",test:function(v2){return void 0===v2}}],n={name:"any",test:hr,isAny:!0};let r2,i,u2=0,o={createCount:0};function s(v2){const _=r2.get(v2);if(_)return _;let N='Unknown type "'+v2+'"';const b4=v2.toLowerCase();let P;for(P of i)if(P.toLowerCase()===b4){N+='. Did you mean "'+P+'" ?';break}throw new TypeError(N)}function f(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"any";const N=_?s(_).index:i.length,b4=[];for(let I=0;I<v2.length;++I){if(!v2[I]||"string"!=typeof v2[I].name||"function"!=typeof v2[I].test)throw new TypeError("Object with properties {name: string, test: function} expected");const X=v2[I].name;if(r2.has(X))throw new TypeError('Duplicate type name "'+X+'"');b4.push(X),r2.set(X,{name:X,test:v2[I].test,isAny:v2[I].isAny,index:N+I,conversionsTo:[]})}const P=i.slice(N);i=i.slice(0,N).concat(b4).concat(P);for(let I=N+b4.length;I<i.length;++I)r2.get(i[I]).index=I}function l(){r2=/* @__PURE__ */new Map,i=[],u2=0,f([n],!1)}function c(v2){const _=i.filter(N=>{const b4=r2.get(N);return!b4.isAny&&b4.test(v2)});return _.length?_:["any"]}function D2(v2){return v2&&"function"==typeof v2&&"_typedFunctionData"in v2}function w(v2,_,N){if(!D2(v2))throw new TypeError(Dr);const b4=N&&N.exact,I=A(Array.isArray(_)?_.join(","):_),X=g(I);if(!b4||X in v2.signatures){const ut=v2._typedFunctionData.signatureMap.get(X);if(ut)return ut}const Y=I.length;let $,R2;if(b4){let ut;for(ut in $=[],v2.signatures)$.push(v2._typedFunctionData.signatureMap.get(ut))}else $=v2._typedFunctionData.signatures;for(let ut=0;ut<Y;++ut){const ct=I[ut],Et=[];let Yt;for(Yt of $){const Rt=y(Yt.params,ut);if(Rt&&(!ct.restParam||Rt.restParam)){if(!Rt.hasAny){const Gt=F(Rt);if(ct.types.some(Qt=>!Gt.has(Qt.name)))continue}Et.push(Yt)}}if($=Et,0===$.length)break}for(R2 of $)if(R2.params.length<=Y)return R2;throw new TypeError("Signature not found (signature: "+(v2.name||"unnamed")+"("+g(I,", ")+"))")}function g(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:",";return v2.map(N=>N.name).join(_)}function p2(v2){const _=0===v2.indexOf("..."),b4=(_?v2.length>3?v2.slice(3):"any":v2).split("|").map(Y=>s(Y.trim()));let P=!1,I=_?"...":"";return{types:b4.map(function(Y){return P=Y.isAny||P,I+=Y.name+"|",{name:Y.name,typeIndex:Y.index,test:Y.test,isAny:Y.isAny,conversion:null,conversionIndex:-1}}),name:I.slice(0,-1),hasAny:P,hasConversion:!1,restParam:_}}function E(v2){const N=function(v2){if(0===v2.length)return[];const _=v2.map(s);v2.length>1&&_.sort((P,I)=>P.index-I.index);let N=_[0].conversionsTo;if(1===v2.length)return N;N=N.concat([]);const b4=new Set(v2);for(let P=1;P<_.length;++P){let I;for(I of _[P].conversionsTo)b4.has(I.from)||(N.push(I),b4.add(I.from))}return N}(v2.types.map(X=>X.name));let b4=v2.hasAny,P=v2.name;const I=N.map(function(X){const Y=s(X.from);return b4=Y.isAny||b4,P+="|"+X.from,{name:X.from,typeIndex:Y.index,test:Y.test,isAny:Y.isAny,conversion:X,conversionIndex:X.index}});return{types:v2.types.concat(I),name:P,hasAny:b4,hasConversion:I.length>0,restParam:v2.restParam}}function F(v2){return v2.typeSet||(v2.typeSet=/* @__PURE__ */new Set,v2.types.forEach(_=>v2.typeSet.add(_.name))),v2.typeSet}function A(v2){const _=[];if("string"!=typeof v2)throw new TypeError("Signatures must be strings");const N=v2.trim();if(""===N)return _;const b4=N.split(",");for(let P=0;P<b4.length;++P){const I=p2(b4[P].trim());if(I.restParam&&P!==b4.length-1)throw new SyntaxError('Unexpected rest parameter "'+b4[P]+'": only allowed for the last parameter');if(0===I.types.length)return null;_.push(I)}return _}function d2(v2){const _=st(v2);return!!_&&_.restParam}function m(v2){if(!v2||0===v2.types.length)return hr;if(1===v2.types.length)return s(v2.types[0].name).test;if(2===v2.types.length){const _=s(v2.types[0].name).test,N=s(v2.types[1].name).test;return function(P){return _(P)||N(P)}}{const _=v2.types.map(function(N){return s(N.name).test});return function(b4){for(let P=0;P<_.length;P++)if(_[P](b4))return!0;return!1}}}function C(v2){let _,N,b4;if(d2(v2)){_=zt(v2).map(m);const P=_.length,I=m(st(v2)),X=function(Y){for(let $=P;$<Y.length;$++)if(!I(Y[$]))return!1;return!0};return function($){for(let R2=0;R2<_.length;R2++)if(!_[R2]($[R2]))return!1;return X($)&&$.length>=P+1}}return 0===v2.length?function(I){return 0===I.length}:1===v2.length?(N=m(v2[0]),function(I){return N(I[0])&&1===I.length}):2===v2.length?(N=m(v2[0]),b4=m(v2[1]),function(I){return N(I[0])&&b4(I[1])&&2===I.length}):(_=v2.map(m),function(I){for(let X=0;X<_.length;X++)if(!_[X](I[X]))return!1;return I.length===_.length})}function y(v2,_){return _<v2.length?v2[_]:d2(v2)?st(v2):null}function B2(v2,_){const N=y(v2,_);return N?F(N):/* @__PURE__ */new Set}function x(v2){return null===v2.conversion||void 0===v2.conversion}function T(v2,_){const N=/* @__PURE__ */new Set;return v2.forEach(b4=>{const P=B2(b4.params,_);let I;for(I of P)N.add(I)}),N.has("any")?["any"]:Array.from(N)}function q(v2,_,N){let b4,P;const I=v2||"unnamed";let Y,X=N;for(Y=0;Y<_.length;Y++){const ct=[];if(X.forEach(Et=>{const Rt=m(y(Et.params,Y));(Y<Et.params.length||d2(Et.params))&&Rt(_[Y])&&ct.push(Et)}),0===ct.length){if(P=T(X,Y),P.length>0){const Et=c(_[Y]);return b4=new TypeError("Unexpected type of argument in function "+I+" (expected: "+P.join(" or ")+", actual: "+Et.join(" | ")+", index: "+Y+")"),b4.data={category:"wrongType",fn:I,index:Y,actual:Et,expected:P},b4}}else X=ct}const $=X.map(function(ct){return d2(ct.params)?1/0:ct.params.length});if(_.length<Math.min.apply(null,$))return P=T(X,Y),b4=new TypeError("Too few arguments in function "+I+" (expected: "+P.join(" or ")+", index: "+_.length+")"),b4.data={category:"tooFewArgs",fn:I,index:_.length,expected:P},b4;const R2=Math.max.apply(null,$);if(_.length>R2)return b4=new TypeError("Too many arguments in function "+I+" (expected: "+R2+", actual: "+_.length+")"),b4.data={category:"tooManyArgs",fn:I,index:_.length,expectedLength:R2},b4;const ut=[];for(let ct=0;ct<_.length;++ct)ut.push(c(_[ct]).join("|"));return b4=new TypeError('Arguments of type "'+ut.join(", ")+'" do not match any of the defined signatures of function '+I+"."),b4.data={category:"mismatch",actual:ut},b4}function Z(v2){let _=i.length+1;for(let N=0;N<v2.types.length;N++)x(v2.types[N])&&(_=Math.min(_,v2.types[N].typeIndex));return _}function W(v2){let _=u2+1;for(let N=0;N<v2.types.length;N++)x(v2.types[N])||(_=Math.min(_,v2.types[N].conversionIndex));return _}function L(v2,_){if(v2.hasAny){if(!_.hasAny)return 1}else if(_.hasAny)return-1;if(v2.restParam){if(!_.restParam)return 1}else if(_.restParam)return-1;if(v2.hasConversion){if(!_.hasConversion)return 1}else if(_.hasConversion)return-1;const N=Z(v2)-Z(_);if(N<0)return-1;if(N>0)return 1;const b4=W(v2)-W(_);return b4<0?-1:b4>0?1:0}function z(v2,_){const N=v2.params,b4=_.params,P=st(N),I=st(b4),X=d2(N),Y=d2(b4);if(X&&P.hasAny){if(!Y||!I.hasAny)return 1}else if(Y&&I.hasAny)return-1;let ut,$=0,R2=0;for(ut of N)ut.hasAny&&++$,ut.hasConversion&&++R2;let ct=0,Et=0;for(ut of b4)ut.hasAny&&++ct,ut.hasConversion&&++Et;if($!==ct)return $-ct;if(X&&P.hasConversion){if(!Y||!I.hasConversion)return 1}else if(Y&&I.hasConversion)return-1;if(R2!==Et)return R2-Et;if(X){if(!Y)return 1}else if(Y)return-1;const Yt=(N.length-b4.length)*(X?-1:1);if(0!==Yt)return Yt;const Rt=[];let Qt,Gt=0;for(let Ee=0;Ee<N.length;++Ee){const Qe=L(N[Ee],b4[Ee]);Rt.push(Qe),Gt+=Qe}if(0!==Gt)return Gt;for(Qt of Rt)if(0!==Qt)return Qt;return 0}function k(v2,_){let N=_;if(v2.some(P=>P.hasConversion)){const P=d2(v2),I=v2.map(G);N=function(){const Y=[],$=P?arguments.length-1:arguments.length;for(let R2=0;R2<$;R2++)Y[R2]=I[R2](arguments[R2]);return P&&(Y[$]=arguments[$].map(I[$])),_.apply(this,Y)}}let b4=N;if(d2(v2)){const P=v2.length-1;b4=function(){return N.apply(this,it(arguments,0,P).concat([it(arguments,P)]))}}return b4}function G(v2){let _,N,b4,P;const I=[],X=[];switch(v2.types.forEach(function(Y){Y.conversion&&(I.push(s(Y.conversion.from).test),X.push(Y.conversion.convert))}),X.length){case 0:return function($){return $};case 1:return _=I[0],b4=X[0],function($){return _($)?b4($):$};case 2:return _=I[0],N=I[1],b4=X[0],P=X[1],function($){return _($)?b4($):N($)?P($):$};default:return function($){for(let R2=0;R2<X.length;R2++)if(I[R2]($))return X[R2]($);return $}}}function j(v2){return function _(N,b4,P){if(b4<N.length){const I=N[b4];let X=[];if(I.restParam){const Y=I.types.filter(x);Y.length<I.types.length&&X.push({types:Y,name:"..."+Y.map($=>$.name).join("|"),hasAny:Y.some($=>$.isAny),hasConversion:!1,restParam:!0}),X.push(I)}else X=I.types.map(function(Y){return{types:[Y],name:Y.name,hasAny:Y.isAny,hasConversion:Y.conversion,restParam:!1}});return function(v2,_){return Array.prototype.concat.apply([],v2.map(_))}(X,function(Y){return _(N,b4+1,P.concat([Y]))})}return[P]}(v2,0,[])}function rt(v2,_){const N=Math.max(v2.length,_.length);for(let Y=0;Y<N;Y++){const $=B2(v2,Y),R2=B2(_,Y);let ct,ut=!1;for(ct of R2)if($.has(ct)){ut=!0;break}if(!ut)return!1}const b4=v2.length,P=_.length,I=d2(v2),X=d2(_);return I?X?b4===P:P>=b4:X?b4>=P:b4===P}function ot(v2,_,N){const b4=[];let P;for(P of v2){let I=N[P];if("number"!=typeof I)throw new TypeError('No definition for referenced signature "'+P+'"');if(I=_[I],"function"!=typeof I)return!1;b4.push(I)}return b4}function wt(v2,_,N){const b4=function(v2){return v2.map(_=>ue(_)?Wt(_.referToSelf.callback):ie(_)?yt(_.referTo.references,_.referTo.callback):_)}(v2),P=new Array(b4.length).fill(!1);let I=!0;for(;I;){I=!1;let X=!0;for(let Y=0;Y<b4.length;++Y){if(P[Y])continue;const $=b4[Y];if(ue($))b4[Y]=$.referToSelf.callback(N),b4[Y].referToSelf=$.referToSelf,P[Y]=!0,X=!1;else if(ie($)){const R2=ot($.referTo.references,b4,_);R2?(b4[Y]=$.referTo.callback.apply(this,R2),b4[Y].referTo=$.referTo,P[Y]=!0,X=!1):I=!0}}if(X&&I)throw new SyntaxError("Circular reference detected in resolving typed.referTo")}return b4}function mt(v2,_){if(o.createCount++,0===Object.keys(_).length)throw new SyntaxError("No signatures provided");o.warnAgainstDeprecatedThis&&function(v2){const _=/\bthis(\(|\.signatures\b)/;Object.keys(v2).forEach(N=>{const b4=v2[N];if(_.test(b4.toString()))throw new SyntaxError("Using `this` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead.")})}(_);const N=[],b4=[],P={},I=[];let X;for(X in _){if(!Object.prototype.hasOwnProperty.call(_,X))continue;const nt=A(X);if(!nt)continue;N.forEach(function(Ue){if(rt(Ue,nt))throw new TypeError('Conflicting signatures "'+g(Ue)+'" and "'+g(nt)+'".')}),N.push(nt);const Ut=b4.length;b4.push(_[X]);const Bu=nt.map(E);let Ke;for(Ke of j(Bu)){const Ue=g(Ke);I.push({params:Ke,name:Ue,fn:Ut}),Ke.every(_u=>!_u.hasConversion)&&(P[Ue]=Ut)}}I.sort(z);const Y=wt(b4,P,Ye);let $;for($ in P)Object.prototype.hasOwnProperty.call(P,$)&&(P[$]=Y[P[$]]);const R2=[],ut=/* @__PURE__ */new Map;for($ of I)ut.has($.name)||($.fn=Y[$.fn],R2.push($),ut.set($.name,$));const ct=R2[0]&&R2[0].params.length<=2&&!d2(R2[0].params),Et=R2[1]&&R2[1].params.length<=2&&!d2(R2[1].params),Yt=R2[2]&&R2[2].params.length<=2&&!d2(R2[2].params),Rt=R2[3]&&R2[3].params.length<=2&&!d2(R2[3].params),Gt=R2[4]&&R2[4].params.length<=2&&!d2(R2[4].params),Qt=R2[5]&&R2[5].params.length<=2&&!d2(R2[5].params),Ee=ct&&Et&&Yt&&Rt&&Gt&&Qt;for(let nt=0;nt<R2.length;++nt)R2[nt].test=C(R2[nt].params);const Qe=ct?m(R2[0].params[0]):Vt,Qi=Et?m(R2[1].params[0]):Vt,Ki=Yt?m(R2[2].params[0]):Vt,ji=Rt?m(R2[3].params[0]):Vt,tu=Gt?m(R2[4].params[0]):Vt,eu=Qt?m(R2[5].params[0]):Vt,nu=ct?m(R2[0].params[1]):Vt,ru=Et?m(R2[1].params[1]):Vt,iu=Yt?m(R2[2].params[1]):Vt,uu=Rt?m(R2[3].params[1]):Vt,ou=Gt?m(R2[4].params[1]):Vt,su=Qt?m(R2[5].params[1]):Vt;for(let nt=0;nt<R2.length;++nt)R2[nt].implementation=k(R2[nt].params,R2[nt].fn);const au=ct?R2[0].implementation:Be,fu=Et?R2[1].implementation:Be,cu=Yt?R2[2].implementation:Be,lu=Rt?R2[3].implementation:Be,hu=Gt?R2[4].implementation:Be,Du=Qt?R2[5].implementation:Be,pu=ct?R2[0].params.length:-1,du=Et?R2[1].params.length:-1,mu=Yt?R2[2].params.length:-1,gu=Rt?R2[3].params.length:-1,vu=Gt?R2[4].params.length:-1,Fu=Qt?R2[5].params.length:-1,wu=Ee?6:0,Eu=R2.length,Au=R2.map(nt=>nt.test),Cu=R2.map(nt=>nt.implementation),yu=function(){for(let Ut=wu;Ut<Eu;Ut++)if(Au[Ut](arguments))return Cu[Ut].apply(this,arguments);return o.onMismatch(v2,arguments,R2)};function Ye(nt,Ut){return arguments.length===pu&&Qe(nt)&&nu(Ut)?au.apply(this,arguments):arguments.length===du&&Qi(nt)&&ru(Ut)?fu.apply(this,arguments):arguments.length===mu&&Ki(nt)&&iu(Ut)?cu.apply(this,arguments):arguments.length===gu&&ji(nt)&&uu(Ut)?lu.apply(this,arguments):arguments.length===vu&&tu(nt)&&ou(Ut)?hu.apply(this,arguments):arguments.length===Fu&&eu(nt)&&su(Ut)?Du.apply(this,arguments):yu.apply(this,arguments)}try{Object.defineProperty(Ye,"name",{value:v2})}catch{}return Ye.signatures=P,Ye._typedFunctionData={signatures:R2,signatureMap:ut},Ye}function ht(v2,_,N){throw q(v2,_,N)}function zt(v2){return it(v2,0,v2.length-1)}function st(v2){return v2[v2.length-1]}function it(v2,_,N){return Array.prototype.slice.call(v2,_,N)}function yt(v2,_){return{referTo:{references:v2,callback:_}}}function Wt(v2){if("function"!=typeof v2)throw new TypeError("Callback function expected as first argument");return{referToSelf:{callback:v2}}}function ie(v2){return v2&&"object"==typeof v2.referTo&&Array.isArray(v2.referTo.references)&&"function"==typeof v2.referTo.callback}function ue(v2){return v2&&"object"==typeof v2.referToSelf&&"function"==typeof v2.referToSelf.callback}function Fe(v2,_){if(!v2)return _;if(_&&_!==v2){const N=new Error("Function names do not match (expected: "+v2+", actual: "+_+")");throw N.data={actual:_,expected:v2},N}return v2}function we(v2){let _;for(const N in v2)Object.prototype.hasOwnProperty.call(v2,N)&&(D2(v2[N])||"string"==typeof v2[N].signature)&&(_=Fe(_,v2[N].name));return _}function Mn(v2,_){let N;for(N in _)if(Object.prototype.hasOwnProperty.call(_,N)){if(N in v2&&_[N]!==v2[N]){const b4=new Error('Signature "'+N+'" is defined twice');throw b4.data={signature:N,sourceFunction:_[N],destFunction:v2[N]},b4}v2[N]=_[N]}}l(),f(e);const Gi=o;function Qn(v2){if(!v2||"string"!=typeof v2.from||"string"!=typeof v2.to||"function"!=typeof v2.convert)throw new TypeError("Object with properties {from: string, to: string, convert: function} expected");if(v2.to===v2.from)throw new SyntaxError('Illegal to define conversion from "'+v2.from+'" to itself.')}return o=function(v2){const _="string"==typeof v2;let b4=_?v2:"";const P={};for(let I=_?1:0;I<arguments.length;++I){const X=arguments[I];let $,Y={};if("function"==typeof X?($=X.name,"string"==typeof X.signature?Y[X.signature]=X:D2(X)&&(Y=X.signatures)):t2(X)&&(Y=X,_||($=we(X))),0===Object.keys(Y).length){const R2=new TypeError("Argument to 'typed' at index "+I+" is not a (typed) function, nor an object with signatures as keys and functions as values.");throw R2.data={index:I,argument:X},R2}_||(b4=Fe(b4,$)),Mn(P,Y)}return mt(b4||"",P)},o.create=gi,o.createCount=Gi.createCount,o.onMismatch=ht,o.throwMismatchError=ht,o.createError=q,o.clear=l,o.clearConversions=function(){let v2;for(v2 of i)r2.get(v2).conversionsTo=[];u2=0},o.addTypes=f,o._findType=s,o.referTo=function(){const v2=zt(arguments).map(N=>g(A(N))),_=st(arguments);if("function"!=typeof _)throw new TypeError("Callback function expected as last argument");return yt(v2,_)},o.referToSelf=Wt,o.convert=function(v2,_){const N=s(_);if(N.test(v2))return v2;const b4=N.conversionsTo;if(0===b4.length)throw new Error("There are no conversions to "+_+" defined.");for(let P=0;P<b4.length;P++)if(s(b4[P].from).test(v2))return b4[P].convert(v2);throw new Error("Cannot convert "+v2+" to "+_)},o.findSignature=w,o.find=function(v2,_,N){return w(v2,_,N).implementation},o.isTypedFunction=D2,o.warnAgainstDeprecatedThis=!0,o.addType=function(v2,_){let N="any";!1!==_&&r2.has("Object")&&(N="Object"),o.addTypes([v2],N)},o.addConversion=function(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{override:!1};Qn(v2);const N=s(v2.to),b4=N.conversionsTo.find(P=>P.from===v2.from);if(b4){if(!_||!_.override)throw new Error('There is already a conversion from "'+v2.from+'" to "'+N.name+'"');o.removeConversion({from:b4.from,to:v2.to,convert:b4.convert})}N.conversionsTo.push({from:v2.from,convert:v2.convert,index:u2++})},o.addConversions=function(v2,_){v2.forEach(N=>o.addConversion(N,_))},o.removeConversion=function(v2){Qn(v2);const _=s(v2.to),N=function(v2,_){for(let N=0;N<v2.length;N++)if(_(v2[N]))return v2[N]}(_.conversionsTo,P=>P.from===v2.from);if(!N)throw new Error("Attempt to remove nonexistent conversion from "+v2.from+" to "+v2.to);if(N.convert!==v2.convert)throw new Error("Conversion to remove does not match existing conversion");const b4=_.conversionsTo.indexOf(N);_.conversionsTo.splice(b4,1)},o.resolve=function(v2,_){if(!D2(v2))throw new TypeError(Dr);const N=v2._typedFunctionData.signatures;for(let b4=0;b4<N.length;++b4)if(N[b4].test(_))return N[b4];return null},o}();function Ft(t2,e,n,r2){function i(u2){var o=function(t2,e){for(var n={},r2=0;r2<e.length;r2++){var i=e[r2],u2=t2[i];void 0!==u2&&(n[i]=u2)}return n}(u2,e.map(vi));return function(t2,e,n){var r2=e.filter(u2=>!function(t2){return t2&&"?"===t2[0]}(u2)).every(u2=>void 0!==n[u2]);if(!r2){var i=e.filter(u2=>void 0===n[u2]);throw new Error('Cannot create function "'.concat(t2,'", ')+"some dependencies are missing: ".concat(i.map(u2=>'"'.concat(u2,'"')).join(", "),"."))}}(t2,e,u2),n(o)}return i.isFactory=!0,i.fn=t2,i.dependencies=e.slice().sort(),r2&&(i.meta=r2),i}function We(t2){return"function"==typeof t2&&"string"==typeof t2.fn&&Array.isArray(t2.dependencies)}function vi(t2){return t2&&"?"===t2[0]?t2.slice(1):t2}function St(t2){return"boolean"==typeof t2||!!isFinite(t2)&&t2===Math.round(t2)}function zn(t2,e,n){var i={2:"0b",8:"0o",16:"0x"}[e],u2="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!St(n))throw new Error("size must be an integer");if(t2>2**(n-1)-1||t2<-(2**(n-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!St(t2))throw new Error("Value must be an integer");t2<0&&(t2+=2**n),u2="i".concat(n)}var o="";return t2<0&&(t2=-t2,o="-"),"".concat(o).concat(i).concat(t2.toString(e)).concat(u2)}function Un(t2,e){if("function"==typeof e)return e(t2);if(t2===1/0)return"Infinity";if(t2===-1/0)return"-Infinity";if(isNaN(t2))return"NaN";var{notation:n,precision:r2,wordSize:i}=Fi(e);switch(n){case"fixed":return function(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2="number"==typeof e?An(n,n.exponent+1+e):n,i=r2.coefficients,u2=r2.exponent+1,o=u2+(e||0);return i.length<o&&(i=i.concat(Oe(o-i.length))),u2<0&&(i=Oe(1-u2).concat(i),u2=1),u2<i.length&&i.splice(u2,0,0===u2?"0.":"."),r2.sign+i.join("")}(t2,r2);case"exponential":return wi(t2,r2);case"engineering":return function(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2=An(n,e),i=r2.exponent,u2=r2.coefficients,o=i%3==0?i:i<0?i-3-i%3:i-i%3;if(lt(e))for(;e>u2.length||i-o+1>u2.length;)u2.push(0);else for(var s=Math.abs(i-o)-(u2.length-1),f=0;f<s;f++)u2.push(0);for(var l=Math.abs(i-o),a2=1;l>0;)a2++,l--;var c=u2.slice(a2).join(""),D2=lt(e)&&c.length||c.match(/[1-9]/)?"."+c:"",w=u2.slice(0,a2).join("")+D2+"e"+(i>=0?"+":"")+o.toString();return r2.sign+w}(t2,r2);case"bin":return zn(t2,2,i);case"oct":return zn(t2,8,i);case"hex":return zn(t2,16,i);case"auto":return function(t2,e,n){if(isNaN(t2)||!isFinite(t2))return String(t2);var r2=dr(n?.lowerExp,-3),i=dr(n?.upperExp,5),u2=En(t2),o=e?An(u2,e):u2;if(o.exponent<r2||o.exponent>=i)return wi(t2,e);var s=o.coefficients,f=o.exponent;s.length<e&&(s=s.concat(Oe(e-s.length))),s=s.concat(Oe(f-s.length+1+(s.length<e?e-s.length:0))),s=Oe(-f).concat(s);var l=f>0?f:0;return l<s.length-1&&s.splice(l+1,0,"."),o.sign+s.join("")}(t2,r2,e).replace(/((\.\d*?)(0+))($|e)/,function(){var u2=arguments[2],o=arguments[4];return"."!==u2?u2+o:o});default:throw new Error('Unknown notation "'+n+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function Fi(t2){var n,r2,e="auto";if(void 0!==t2)if(lt(t2))n=t2;else if(Nt(t2))n=t2.toNumber();else{if(!qe(t2))throw new Error("Unsupported type of options, number, BigNumber, or object expected");void 0!==t2.precision&&(n=pr(t2.precision,()=>{throw new Error('Option "precision" must be a number or BigNumber')})),void 0!==t2.wordSize&&(r2=pr(t2.wordSize,()=>{throw new Error('Option "wordSize" must be a number or BigNumber')})),t2.notation&&(e=t2.notation)}return{notation:e,precision:n,wordSize:r2}}function En(t2){var e=String(t2).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);if(!e)throw new SyntaxError("Invalid number "+t2);var n=e[1],r2=e[2],i=parseFloat(e[4]||"0"),u2=r2.indexOf(".");i+=-1!==u2?u2-1:r2.length-1;var o=r2.replace(".","").replace(/^0*/,function(s){return i-=s.length,""}).replace(/0*$/,"").split("").map(function(s){return parseInt(s)});return 0===o.length&&(o.push(0),i++),{sign:n,coefficients:o,exponent:i}}function wi(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2=e?An(n,e):n,i=r2.coefficients,u2=r2.exponent;i.length<e&&(i=i.concat(Oe(e-i.length)));var o=i.shift();return r2.sign+o+(i.length>0?"."+i.join(""):"")+"e"+(u2>=0?"+":"")+u2}function An(t2,e){for(var n={sign:t2.sign,coefficients:t2.coefficients,exponent:t2.exponent},r2=n.coefficients;e<=0;)r2.unshift(0),n.exponent++,e++;if(r2.length>e&&r2.splice(e,r2.length-e)[0]>=5){var u2=e-1;for(r2[u2]++;10===r2[u2];)r2.pop(),0===u2&&(r2.unshift(0),n.exponent++,u2++),r2[--u2]++}return n}function Oe(t2){for(var e=[],n=0;n<t2;n++)e.push(0);return e}function ln(t2,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e-8,r2=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n<=0)throw new Error("Relative tolerance must be greater than 0");if(r2<0)throw new Error("Absolute tolerance must be at least 0");return!isNaN(t2)&&!isNaN(e)&&(isFinite(t2)&&isFinite(e)?t2===e||Math.abs(t2-e)<=Math.max(n*Math.max(Math.abs(t2),Math.abs(e)),r2):t2===e)}function pr(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():void e()}function dr(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():e}var Ei=function(){return Ei=Je.create,Je},Co=/* @__PURE__ */Ft("typed",["?BigNumber","?Complex","?DenseMatrix","?Fraction"],function(e){var{BigNumber:n,Complex:r2,DenseMatrix:i,Fraction:u2}=e,o=Ei();return o.clear(),o.addTypes([{name:"number",test:lt},{name:"Complex",test:gn},{name:"BigNumber",test:Nt},{name:"bigint",test:Ur},{name:"Fraction",test:vn},{name:"Unit",test:Fn},{name:"identifier",test:s=>jt&&/^(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC4\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC4\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])*$/.test(s)},{name:"string",test:jt},{name:"Chain",test:pi},{name:"Array",test:At},{name:"Matrix",test:Mt},{name:"DenseMatrix",test:Xr},{name:"SparseMatrix",test:$r},{name:"Range",test:Lr},{name:"Index",test:wn},{name:"boolean",test:Zr},{name:"ResultSet",test:Wr},{name:"Help",test:Vr},{name:"function",test:Hr},{name:"Date",test:Jr},{name:"RegExp",test:kr},{name:"null",test:Gr},{name:"undefined",test:Qr},{name:"AccessorNode",test:Kr},{name:"ArrayNode",test:jr},{name:"AssignmentNode",test:ti},{name:"BlockNode",test:ei},{name:"ConditionalNode",test:ni},{name:"ConstantNode",test:ri},{name:"FunctionNode",test:ui},{name:"FunctionAssignmentNode",test:ii},{name:"IndexNode",test:oi},{name:"Node",test:si},{name:"ObjectNode",test:ai},{name:"OperatorNode",test:fi},{name:"ParenthesisNode",test:ci},{name:"RangeNode",test:li},{name:"RelationalNode",test:hi},{name:"SymbolNode",test:Di},{name:"Map",test:Ie},{name:"Object",test:qe}]),o.addConversions([{from:"number",to:"BigNumber",convert:function(f){if(n||nn(f),f.toExponential().replace(/e.*$/,"").replace(/^0\.?0*|\./,"").length>15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+f+"). Use function bignumber(x) to convert to BigNumber.");return new n(f)}},{from:"number",to:"Complex",convert:function(f){return r2||rn(f),new r2(f,0)}},{from:"BigNumber",to:"Complex",convert:function(f){return r2||rn(f),new r2(f.toNumber(),0)}},{from:"bigint",to:"number",convert:function(f){if(f>Number.MAX_SAFE_INTEGER)throw new TypeError("Cannot implicitly convert bigint to number: value exceeds the max safe integer value (value: "+f+")");return Number(f)}},{from:"bigint",to:"BigNumber",convert:function(f){return n||nn(f),new n(f.toString())}},{from:"bigint",to:"Fraction",convert:function(f){return u2||un(f),new u2(f)}},{from:"Fraction",to:"BigNumber",convert:function(f){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(f){return r2||rn(f),new r2(f.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(f){u2||un(f);var l=new u2(f);if(l.valueOf()!==f)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+f+"). Use function fraction(x) to convert to Fraction.");return l}},{from:"string",to:"number",convert:function(f){var l=Number(f);if(isNaN(l))throw new Error('Cannot convert "'+f+'" to a number');return l}},{from:"string",to:"BigNumber",convert:function(f){n||nn(f);try{return new n(f)}catch{throw new Error('Cannot convert "'+f+'" to BigNumber')}}},{from:"string",to:"bigint",convert:function(f){try{return BigInt(f)}catch{throw new Error('Cannot convert "'+f+'" to BigInt')}}},{from:"string",to:"Fraction",convert:function(f){u2||un(f);try{return new u2(f)}catch{throw new Error('Cannot convert "'+f+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(f){r2||rn(f);try{return new r2(f)}catch{throw new Error('Cannot convert "'+f+'" to Complex')}}},{from:"boolean",to:"number",convert:function(f){return+f}},{from:"boolean",to:"BigNumber",convert:function(f){return n||nn(f),new n(+f)}},{from:"boolean",to:"bigint",convert:function(f){return BigInt(+f)}},{from:"boolean",to:"Fraction",convert:function(f){return u2||un(f),new u2(+f)}},{from:"boolean",to:"string",convert:function(f){return String(f)}},{from:"Array",to:"Matrix",convert:function(f){return i||function(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}(),new i(f)}},{from:"Matrix",to:"Array",convert:function(f){return f.valueOf()}}]),o.onMismatch=(s,f,l)=>{var a2=o.createError(s,f,l);if(["wrongType","mismatch"].includes(a2.data.category)&&1===f.length&&He(f[0])&&l.some(D2=>!D2.params.includes(","))){var c=new TypeError("Function '".concat(s,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(s,")'."));throw c.data=a2.data,c}throw a2},o.onMismatch=(s,f,l)=>{var a2=o.createError(s,f,l);if(["wrongType","mismatch"].includes(a2.data.category)&&1===f.length&&He(f[0])&&l.some(D2=>!D2.params.includes(","))){var c=new TypeError("Function '".concat(s,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(s,")'."));throw c.data=a2.data,c}throw a2},o});function nn(t2){throw new Error("Cannot convert value ".concat(t2," into a BigNumber: no class 'BigNumber' provided"))}function rn(t2){throw new Error("Cannot convert value ".concat(t2," into a Complex number: no class 'Complex' provided"))}function un(t2){throw new Error("Cannot convert value ".concat(t2," into a Fraction, no class 'Fraction' provided."))}var Ai,se,Te=9e15,De=1e9,Xn="0123456789abcdef",hn="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Dn="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",$n={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Te,maxE:Te,crypto:!1},K=!0,Cn="[DecimalError] ",he=Cn+"Invalid argument: ",Ci=Cn+"Precision limit exceeded",yi=Cn+"crypto unavailable",Bi="[object Decimal]",Pt=Math.floor,Ct=Math.pow,Bo=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,_o=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Mo=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,_i=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,te=1e7,xo=hn.length-1,Ln=Dn.length-1,O={toStringTag:Bi};function Tt(t2){var e,n,r2,i=t2.length-1,u2="",o=t2[0];if(i>0){for(u2+=o,e=1;e<i;e++)(n=7-(r2=t2[e]+"").length)&&(u2+=ce(n)),u2+=r2;(n=7-(r2=(o=t2[e])+"").length)&&(u2+=ce(n))}else if(0===o)return"0";for(;o%10==0;)o/=10;return u2+o}function $t(t2,e,n){if(t2!==~~t2||t2<e||t2>n)throw Error(he+t2)}function ke(t2,e,n,r2){var i,u2,o,s;for(u2=t2[0];u2>=10;u2/=10)--e;return--e<0?(e+=7,i=0):(i=Math.ceil((e+1)/7),e%=7),u2=Ct(10,7-e),s=t2[i]%u2|0,null==r2?e<3?(0==e?s=s/100|0:1==e&&(s=s/10|0),o=n<4&&99999==s||n>3&&49999==s||5e4==s||0==s):o=(n<4&&s+1==u2||n>3&&s+1==u2/2)&&(t2[i+1]/u2/100|0)==Ct(10,e-2)-1||(s==u2/2||0==s)&&!(t2[i+1]/u2/100|0):e<4?(0==e?s=s/1e3|0:1==e?s=s/100|0:2==e&&(s=s/10|0),o=(r2||n<4)&&9999==s||!r2&&n>3&&4999==s):o=((r2||n<4)&&s+1==u2||!r2&&n>3&&s+1==u2/2)&&(t2[i+1]/u2/1e3|0)==Ct(10,e-3)-1,o}function sn(t2,e,n){for(var r2,u2,i=[0],o=0,s=t2.length;o<s;){for(u2=i.length;u2--;)i[u2]*=e;for(i[0]+=Xn.indexOf(t2.charAt(o++)),r2=0;r2<i.length;r2++)i[r2]>n-1&&(void 0===i[r2+1]&&(i[r2+1]=0),i[r2+1]+=i[r2]/n|0,i[r2]%=n)}return i.reverse()}O.absoluteValue=O.abs=function(){var t2=new this.constructor(this);return t2.s<0&&(t2.s=1),H(t2)},O.ceil=function(){return H(new this.constructor(this),this.e+1,2)},O.clampedTo=O.clamp=function(t2,e){var i=this.constructor;if(t2=new i(t2),e=new i(e),!t2.s||!e.s)return new i(NaN);if(t2.gt(e))throw Error(he+e);return this.cmp(t2)<0?t2:this.cmp(e)>0?e:new i(this)},O.comparedTo=O.cmp=function(t2){var e,n,r2,i,u2=this,o=u2.d,s=(t2=new u2.constructor(t2)).d,f=u2.s,l=t2.s;if(!o||!s)return f&&l?f!==l?f:o===s?0:!o^f<0?1:-1:NaN;if(!o[0]||!s[0])return o[0]?f:s[0]?-l:0;if(f!==l)return f;if(u2.e!==t2.e)return u2.e>t2.e^f<0?1:-1;for(e=0,n=(r2=o.length)<(i=s.length)?r2:i;e<n;++e)if(o[e]!==s[e])return o[e]>s[e]^f<0?1:-1;return r2===i?0:r2>i^f<0?1:-1},O.cosine=O.cos=function(){var t2,e,n=this,r2=n.constructor;return n.d?n.d[0]?(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(n.e,n.sd())+7,r2.rounding=1,n=function(t2,e){var n,r2,i;if(e.isZero())return e;r2=e.d.length,r2<32?(n=Math.ceil(r2/3),i=(1/Bn(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),t2.precision+=n,e=ze(t2,1,e.times(i),new t2(1));for(var u2=n;u2--;){var o=e.times(e);e=o.times(o).minus(o).times(8).plus(1)}return t2.precision-=n,e}(r2,Ti(r2,n)),r2.precision=t2,r2.rounding=e,H(2==se||3==se?n.neg():n,t2,e,!0)):new r2(1):new r2(NaN)},O.cubeRoot=O.cbrt=function(){var t2,e,n,r2,i,u2,o,s,f,l,a2=this,c=a2.constructor;if(!a2.isFinite()||a2.isZero())return new c(a2);for(K=!1,(u2=a2.s*Ct(a2.s*a2,1/3))&&Math.abs(u2)!=1/0?r2=new c(u2.toString()):(n=Tt(a2.d),(u2=((t2=a2.e)-n.length+1)%3)&&(n+=1==u2||-2==u2?"0":"00"),u2=Ct(n,1/3),t2=Pt((t2+1)/3)-(t2%3==(t2<0?-1:2)),u2==1/0?n="5e"+t2:n=(n=u2.toExponential()).slice(0,n.indexOf("e")+1)+t2,(r2=new c(n)).s=a2.s),o=(t2=c.precision)+3;;)if(l=(f=(s=r2).times(s).times(s)).plus(a2),r2=ft(l.plus(a2).times(s),l.plus(f),o+2,1),Tt(s.d).slice(0,o)===(n=Tt(r2.d)).slice(0,o)){if("9999"!=(n=n.slice(o-3,o+1))&&(i||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(H(r2,t2+1,1),e=!r2.times(r2).times(r2).eq(a2));break}if(!i&&(H(s,t2+1,0),s.times(s).times(s).eq(a2))){r2=s;break}o+=4,i=1}return K=!0,H(r2,t2,c.rounding,e)},O.decimalPlaces=O.dp=function(){var t2,e=this.d,n=NaN;if(e){if(n=7*((t2=e.length-1)-Pt(this.e/7)),t2=e[t2])for(;t2%10==0;t2/=10)n--;n<0&&(n=0)}return n},O.dividedBy=O.div=function(t2){return ft(this,new this.constructor(t2))},O.dividedToIntegerBy=O.divToInt=function(t2){var n=this.constructor;return H(ft(this,new n(t2),0,1,1),n.precision,n.rounding)},O.equals=O.eq=function(t2){return 0===this.cmp(t2)},O.floor=function(){return H(new this.constructor(this),this.e+1,3)},O.greaterThan=O.gt=function(t2){return this.cmp(t2)>0},O.greaterThanOrEqualTo=O.gte=function(t2){var e=this.cmp(t2);return 1==e||0===e},O.hyperbolicCosine=O.cosh=function(){var t2,e,n,r2,i,u2=this,o=u2.constructor,s=new o(1);if(!u2.isFinite())return new o(u2.s?1/0:NaN);if(u2.isZero())return s;n=o.precision,r2=o.rounding,o.precision=n+Math.max(u2.e,u2.sd())+4,o.rounding=1,(i=u2.d.length)<32?e=(1/Bn(4,t2=Math.ceil(i/3))).toString():(t2=16,e="2.3283064365386962890625e-10"),u2=ze(o,1,u2.times(e),new o(1),!0);for(var f,l=t2,a2=new o(8);l--;)f=u2.times(u2),u2=s.minus(f.times(a2.minus(f.times(a2))));return H(u2,o.precision=n,o.rounding=r2,!0)},O.hyperbolicSine=O.sinh=function(){var t2,e,n,r2,i=this,u2=i.constructor;if(!i.isFinite()||i.isZero())return new u2(i);if(e=u2.precision,n=u2.rounding,u2.precision=e+Math.max(i.e,i.sd())+4,u2.rounding=1,(r2=i.d.length)<3)i=ze(u2,2,i,i,!0);else{t2=(t2=1.4*Math.sqrt(r2))>16?16:0|t2,i=ze(u2,2,i=i.times(1/Bn(5,t2)),i,!0);for(var o,s=new u2(5),f=new u2(16),l=new u2(20);t2--;)o=i.times(i),i=i.times(s.plus(o.times(f.times(o).plus(l))))}return u2.precision=e,u2.rounding=n,H(i,e,n,!0)},O.hyperbolicTangent=O.tanh=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+7,r2.rounding=1,ft(n.sinh(),n.cosh(),r2.precision=t2,r2.rounding=e)):new r2(n.s)},O.inverseCosine=O.acos=function(){var t2=this,e=t2.constructor,n=t2.abs().cmp(1),r2=e.precision,i=e.rounding;return-1!==n?0===n?t2.isNeg()?ee(e,r2,i):new e(0):new e(NaN):t2.isZero()?ee(e,r2+4,i).times(.5):(e.precision=r2+6,e.rounding=1,t2=new e(1).minus(t2).div(t2.plus(1)).sqrt().atan(),e.precision=r2,e.rounding=i,t2.times(2))},O.inverseHyperbolicCosine=O.acosh=function(){var t2,e,n=this,r2=n.constructor;return n.lte(1)?new r2(n.eq(1)?0:NaN):n.isFinite()?(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(Math.abs(n.e),n.sd())+4,r2.rounding=1,K=!1,n=n.times(n).minus(1).sqrt().plus(n),K=!0,r2.precision=t2,r2.rounding=e,n.ln()):new r2(n)},O.inverseHyperbolicSine=O.asinh=function(){var t2,e,n=this,r2=n.constructor;return!n.isFinite()||n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+2*Math.max(Math.abs(n.e),n.sd())+6,r2.rounding=1,K=!1,n=n.times(n).plus(1).sqrt().plus(n),K=!0,r2.precision=t2,r2.rounding=e,n.ln())},O.inverseHyperbolicTangent=O.atanh=function(){var t2,e,n,r2,i=this,u2=i.constructor;return i.isFinite()?i.e>=0?new u2(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(t2=u2.precision,e=u2.rounding,r2=i.sd(),Math.max(r2,t2)<2*-i.e-1?H(new u2(i),t2,e,!0):(u2.precision=n=r2-i.e,i=ft(i.plus(1),new u2(1).minus(i),n+t2,1),u2.precision=t2+4,u2.rounding=1,i=i.ln(),u2.precision=t2,u2.rounding=e,i.times(.5))):new u2(NaN)},O.inverseSine=O.asin=function(){var t2,e,n,r2,i=this,u2=i.constructor;return i.isZero()?new u2(i):(e=i.abs().cmp(1),n=u2.precision,r2=u2.rounding,-1!==e?0===e?((t2=ee(u2,n+4,r2).times(.5)).s=i.s,t2):new u2(NaN):(u2.precision=n+6,u2.rounding=1,i=i.div(new u2(1).minus(i.times(i)).sqrt().plus(1)).atan(),u2.precision=n,u2.rounding=r2,i.times(2)))},O.inverseTangent=O.atan=function(){var t2,e,n,r2,i,u2,o,s,f,l=this,a2=l.constructor,c=a2.precision,D2=a2.rounding;if(l.isFinite()){if(l.isZero())return new a2(l);if(l.abs().eq(1)&&c+4<=Ln)return(o=ee(a2,c+4,D2).times(.25)).s=l.s,o}else{if(!l.s)return new a2(NaN);if(c+4<=Ln)return(o=ee(a2,c+4,D2).times(.5)).s=l.s,o}for(a2.precision=s=c+10,a2.rounding=1,t2=n=Math.min(28,s/7+2|0);t2;--t2)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(K=!1,e=Math.ceil(s/7),r2=1,f=l.times(l),o=new a2(l),i=l;-1!==t2;)if(i=i.times(f),u2=o.minus(i.div(r2+=2)),i=i.times(f),void 0!==(o=u2.plus(i.div(r2+=2))).d[e])for(t2=e;o.d[t2]===u2.d[t2]&&t2--;);return n&&(o=o.times(2<<n-1)),K=!0,H(o,a2.precision=c,a2.rounding=D2,!0)},O.isFinite=function(){return!!this.d},O.isInteger=O.isInt=function(){return!!this.d&&Pt(this.e/7)>this.d.length-2},O.isNaN=function(){return!this.s},O.isNegative=O.isNeg=function(){return this.s<0},O.isPositive=O.isPos=function(){return this.s>0},O.isZero=function(){return!!this.d&&0===this.d[0]},O.lessThan=O.lt=function(t2){return this.cmp(t2)<0},O.lessThanOrEqualTo=O.lte=function(t2){return this.cmp(t2)<1},O.logarithm=O.log=function(t2){var e,n,r2,i,u2,o,s,f,l=this,a2=l.constructor,c=a2.precision,D2=a2.rounding;if(null==t2)t2=new a2(10),e=!0;else{if(n=(t2=new a2(t2)).d,t2.s<0||!n||!n[0]||t2.eq(1))return new a2(NaN);e=t2.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new a2(n&&!n[0]?-1/0:1!=l.s?NaN:n?0:1/0);if(e)if(n.length>1)u2=!0;else{for(i=n[0];i%10==0;)i/=10;u2=1!==i}if(K=!1,o=le(l,s=c+5),r2=e?pn(a2,s+10):le(t2,s),ke((f=ft(o,r2,s,1)).d,i=c,D2))do{if(o=le(l,s+=10),r2=e?pn(a2,s+10):le(t2,s),f=ft(o,r2,s,1),!u2){+Tt(f.d).slice(i+1,i+15)+1==1e14&&(f=H(f,c+1,0));break}}while(ke(f.d,i+=10,D2));return K=!0,H(f,c,D2)},O.minus=O.sub=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c,D2,w=this,M=w.constructor;if(t2=new M(t2),!w.d||!t2.d)return w.s&&t2.s?w.d?t2.s=-t2.s:t2=new M(t2.d||w.s!==t2.s?w:NaN):t2=new M(NaN),t2;if(w.s!=t2.s)return t2.s=-t2.s,w.plus(t2);if(l=w.d,D2=t2.d,s=M.precision,f=M.rounding,!l[0]||!D2[0]){if(D2[0])t2.s=-t2.s;else{if(!l[0])return new M(3===f?-0:0);t2=new M(w)}return K?H(t2,s,f):t2}if(n=Pt(t2.e/7),a2=Pt(w.e/7),l=l.slice(),u2=a2-n){for((c=u2<0)?(e=l,u2=-u2,o=D2.length):(e=D2,n=a2,o=l.length),u2>(r2=Math.max(Math.ceil(s/7),o)+2)&&(u2=r2,e.length=1),e.reverse(),r2=u2;r2--;)e.push(0);e.reverse()}else{for((c=(r2=l.length)<(o=D2.length))&&(o=r2),r2=0;r2<o;r2++)if(l[r2]!=D2[r2]){c=l[r2]<D2[r2];break}u2=0}for(c&&(e=l,l=D2,D2=e,t2.s=-t2.s),o=l.length,r2=D2.length-o;r2>0;--r2)l[o++]=0;for(r2=D2.length;r2>u2;){if(l[--r2]<D2[r2]){for(i=r2;i&&0===l[--i];)l[i]=te-1;--l[i],l[r2]+=te}l[r2]-=D2[r2]}for(;0===l[--o];)l.pop();for(;0===l[0];l.shift())--n;return l[0]?(t2.d=l,t2.e=yn(l,n),K?H(t2,s,f):t2):new M(3===f?-0:0)},O.modulo=O.mod=function(t2){var e,n=this,r2=n.constructor;return t2=new r2(t2),!n.d||!t2.s||t2.d&&!t2.d[0]?new r2(NaN):!t2.d||n.d&&!n.d[0]?H(new r2(n),r2.precision,r2.rounding):(K=!1,9==r2.modulo?(e=ft(n,t2.abs(),0,3,1)).s*=t2.s:e=ft(n,t2,0,r2.modulo,1),e=e.times(t2),K=!0,n.minus(e))},O.naturalExponential=O.exp=function(){return Zn(this)},O.naturalLogarithm=O.ln=function(){return le(this)},O.negated=O.neg=function(){var t2=new this.constructor(this);return t2.s=-t2.s,H(t2)},O.plus=O.add=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c=this,D2=c.constructor;if(t2=new D2(t2),!c.d||!t2.d)return c.s&&t2.s?c.d||(t2=new D2(t2.d||c.s===t2.s?c:NaN)):t2=new D2(NaN),t2;if(c.s!=t2.s)return t2.s=-t2.s,c.minus(t2);if(l=c.d,a2=t2.d,s=D2.precision,f=D2.rounding,!l[0]||!a2[0])return a2[0]||(t2=new D2(c)),K?H(t2,s,f):t2;if(u2=Pt(c.e/7),r2=Pt(t2.e/7),l=l.slice(),i=u2-r2){for(i<0?(n=l,i=-i,o=a2.length):(n=a2,r2=u2,o=l.length),i>(o=(u2=Math.ceil(s/7))>o?u2+1:o+1)&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for((o=l.length)-(i=a2.length)<0&&(i=o,n=a2,a2=l,l=n),e=0;i;)e=(l[--i]=l[i]+a2[i]+e)/te|0,l[i]%=te;for(e&&(l.unshift(e),++r2),o=l.length;0==l[--o];)l.pop();return t2.d=l,t2.e=yn(l,r2),K?H(t2,s,f):t2},O.precision=O.sd=function(t2){var e,n=this;if(void 0!==t2&&t2!==!!t2&&1!==t2&&0!==t2)throw Error(he+t2);return n.d?(e=Mi(n.d),t2&&n.e+1>e&&(e=n.e+1)):e=NaN,e},O.round=function(){var e=this.constructor;return H(new e(this),this.e+1,e.rounding)},O.sine=O.sin=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(n.e,n.sd())+7,r2.rounding=1,n=function(t2,e){var n,r2=e.d.length;if(r2<3)return e.isZero()?e:ze(t2,2,e,e);n=1.4*Math.sqrt(r2),n=n>16?16:0|n,e=e.times(1/Bn(5,n)),e=ze(t2,2,e,e);for(var i,u2=new t2(5),o=new t2(16),s=new t2(20);n--;)i=e.times(e),e=e.times(u2.plus(i.times(o.times(i).minus(s))));return e}(r2,Ti(r2,n)),r2.precision=t2,r2.rounding=e,H(se>2?n.neg():n,t2,e,!0)):new r2(NaN)},O.squareRoot=O.sqrt=function(){var t2,e,n,r2,i,u2,o=this,s=o.d,f=o.e,l=o.s,a2=o.constructor;if(1!==l||!s||!s[0])return new a2(!l||l<0&&(!s||s[0])?NaN:s?o:1/0);for(K=!1,0==(l=Math.sqrt(+o))||l==1/0?(((e=Tt(s)).length+f)%2==0&&(e+="0"),l=Math.sqrt(e),f=Pt((f+1)/2)-(f<0||f%2),l==1/0?e="5e"+f:e=(e=l.toExponential()).slice(0,e.indexOf("e")+1)+f,r2=new a2(e)):r2=new a2(l.toString()),n=(f=a2.precision)+3;;)if(r2=(u2=r2).plus(ft(o,u2,n+2,1)).times(.5),Tt(u2.d).slice(0,n)===(e=Tt(r2.d)).slice(0,n)){if("9999"!=(e=e.slice(n-3,n+1))&&(i||"4999"!=e)){(!+e||!+e.slice(1)&&"5"==e.charAt(0))&&(H(r2,f+1,1),t2=!r2.times(r2).eq(o));break}if(!i&&(H(u2,f+1,0),u2.times(u2).eq(o))){r2=u2;break}n+=4,i=1}return K=!0,H(r2,f,a2.rounding,t2)},O.tangent=O.tan=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+10,r2.rounding=1,(n=n.sin()).s=1,n=ft(n,new r2(1).minus(n.times(n)).sqrt(),t2+10,0),r2.precision=t2,r2.rounding=e,H(2==se||4==se?n.neg():n,t2,e,!0)):new r2(NaN)},O.times=O.mul=function(t2){var e,n,r2,i,u2,o,s,f,l,c=this.constructor,D2=this.d,w=(t2=new c(t2)).d;if(t2.s*=this.s,!(D2&&D2[0]&&w&&w[0]))return new c(!t2.s||D2&&!D2[0]&&!w||w&&!w[0]&&!D2?NaN:D2&&w?0*t2.s:t2.s/0);for(n=Pt(this.e/7)+Pt(t2.e/7),(f=D2.length)<(l=w.length)&&(u2=D2,D2=w,w=u2,o=f,f=l,l=o),u2=[],r2=o=f+l;r2--;)u2.push(0);for(r2=l;--r2>=0;){for(e=0,i=f+r2;i>r2;)s=u2[i]+w[r2]*D2[i-r2-1]+e,u2[i--]=s%te|0,e=s/te|0;u2[i]=(u2[i]+e)%te|0}for(;!u2[--o];)u2.pop();return e?++n:u2.shift(),t2.d=u2,t2.e=yn(u2,n),K?H(t2,c.precision,c.rounding):t2},O.toBinary=function(t2,e){return Vn(this,2,t2,e)},O.toDecimalPlaces=O.toDP=function(t2,e){var n=this,r2=n.constructor;return n=new r2(n),void 0===t2?n:($t(t2,0,De),void 0===e?e=r2.rounding:$t(e,0,8),H(n,t2+n.e+1,e))},O.toExponential=function(t2,e){var n,r2=this,i=r2.constructor;return void 0===t2?n=ne(r2,!0):($t(t2,0,De),void 0===e?e=i.rounding:$t(e,0,8),n=ne(r2=H(new i(r2),t2+1,e),!0,t2+1)),r2.isNeg()&&!r2.isZero()?"-"+n:n},O.toFixed=function(t2,e){var n,r2,i=this,u2=i.constructor;return void 0===t2?n=ne(i):($t(t2,0,De),void 0===e?e=u2.rounding:$t(e,0,8),n=ne(r2=H(new u2(i),t2+i.e+1,e),!1,t2+r2.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n},O.toFraction=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c,D2,w=this,M=w.d,h2=w.constructor;if(!M)return new h2(w);if(l=n=new h2(1),r2=f=new h2(0),o=(u2=(e=new h2(r2)).e=Mi(M)-w.e-1)%7,e.d[0]=Ct(10,o<0?7+o:o),null==t2)t2=u2>0?e:l;else{if(!(s=new h2(t2)).isInt()||s.lt(l))throw Error(he+s);t2=s.gt(e)?u2>0?e:l:s}for(K=!1,s=new h2(Tt(M)),a2=h2.precision,h2.precision=u2=7*M.length*2;c=ft(s,e,0,1,1),1!=(i=n.plus(c.times(r2))).cmp(t2);)n=r2,r2=i,i=l,l=f.plus(c.times(i)),f=i,i=e,e=s.minus(c.times(i)),s=i;return i=ft(t2.minus(n),r2,0,1,1),f=f.plus(i.times(l)),n=n.plus(i.times(r2)),f.s=l.s=w.s,D2=ft(l,r2,u2,1).minus(w).abs().cmp(ft(f,n,u2,1).minus(w).abs())<1?[l,r2]:[f,n],h2.precision=a2,K=!0,D2},O.toHexadecimal=O.toHex=function(t2,e){return Vn(this,16,t2,e)},O.toNearest=function(t2,e){var n=this,r2=n.constructor;if(n=new r2(n),null==t2){if(!n.d)return n;t2=new r2(1),e=r2.rounding}else{if(t2=new r2(t2),void 0===e?e=r2.rounding:$t(e,0,8),!n.d)return t2.s?n:t2;if(!t2.d)return t2.s&&(t2.s=n.s),t2}return t2.d[0]?(K=!1,n=ft(n,t2,0,e,1).times(t2),K=!0,H(n)):(t2.s=n.s,n=t2),n},O.toNumber=function(){return+this},O.toOctal=function(t2,e){return Vn(this,8,t2,e)},O.toPower=O.pow=function(t2){var e,n,r2,i,u2,o,s=this,f=s.constructor,l=+(t2=new f(t2));if(!(s.d&&t2.d&&s.d[0]&&t2.d[0]))return new f(Ct(+s,l));if((s=new f(s)).eq(1))return s;if(r2=f.precision,u2=f.rounding,t2.eq(1))return H(s,r2,u2);if((e=Pt(t2.e/7))>=t2.d.length-1&&(n=l<0?-l:l)<=9007199254740991)return i=Ni(f,s,n,r2),t2.s<0?new f(1).div(i):H(i,r2,u2);if((o=s.s)<0){if(e<t2.d.length-1)return new f(NaN);if(!(1&t2.d[e])&&(o=1),0==s.e&&1==s.d[0]&&1==s.d.length)return s.s=o,s}return(e=0!=(n=Ct(+s,l))&&isFinite(n)?new f(n+"").e:Pt(l*(Math.log("0."+Tt(s.d))/Math.LN10+s.e+1)))>f.maxE+1||e<f.minE-1?new f(e>0?o/0:0):(K=!1,f.rounding=s.s=1,n=Math.min(12,(e+"").length),(i=Zn(t2.times(le(s,r2+n)),r2)).d&&(ke((i=H(i,r2+5,1)).d,r2,u2)&&(e=r2+10,+Tt((i=H(Zn(t2.times(le(s,e+n)),e),e+5,1)).d).slice(r2+1,r2+15)+1==1e14&&(i=H(i,r2+1,0)))),i.s=o,K=!0,f.rounding=u2,H(i,r2,u2))},O.toPrecision=function(t2,e){var n,r2=this,i=r2.constructor;return void 0===t2?n=ne(r2,r2.e<=i.toExpNeg||r2.e>=i.toExpPos):($t(t2,1,De),void 0===e?e=i.rounding:$t(e,0,8),n=ne(r2=H(new i(r2),t2,e),t2<=r2.e||r2.e<=i.toExpNeg,t2)),r2.isNeg()&&!r2.isZero()?"-"+n:n},O.toSignificantDigits=O.toSD=function(t2,e){var r2=this.constructor;return void 0===t2?(t2=r2.precision,e=r2.rounding):($t(t2,1,De),void 0===e?e=r2.rounding:$t(e,0,8)),H(new r2(this),t2,e)},O.toString=function(){var t2=this,e=t2.constructor,n=ne(t2,t2.e<=e.toExpNeg||t2.e>=e.toExpPos);return t2.isNeg()&&!t2.isZero()?"-"+n:n},O.truncated=O.trunc=function(){return H(new this.constructor(this),this.e+1,1)},O.valueOf=O.toJSON=function(){var t2=this,e=t2.constructor,n=ne(t2,t2.e<=e.toExpNeg||t2.e>=e.toExpPos);return t2.isNeg()?"-"+n:n};var ft=/* @__PURE__ */function(){function t2(r2,i,u2){var o,s=0,f=r2.length;for(r2=r2.slice();f--;)o=r2[f]*i+s,r2[f]=o%u2|0,s=o/u2|0;return s&&r2.unshift(s),r2}function e(r2,i,u2,o){var s,f;if(u2!=o)f=u2>o?1:-1;else for(s=f=0;s<u2;s++)if(r2[s]!=i[s]){f=r2[s]>i[s]?1:-1;break}return f}function n(r2,i,u2,o){for(var s=0;u2--;)r2[u2]-=s,s=r2[u2]<i[u2]?1:0,r2[u2]=s*o+r2[u2]-i[u2];for(;!r2[0]&&r2.length>1;)r2.shift()}return function(r2,i,u2,o,s,f){var l,a2,c,D2,w,M,h2,g,p2,E,F,A,d2,m,C,y,B2,x,T,q,Z=r2.constructor,W=r2.s==i.s?1:-1,L=r2.d,z=i.d;if(!(L&&L[0]&&z&&z[0]))return new Z(r2.s&&i.s&&(L?!z||L[0]!=z[0]:z)?L&&0==L[0]||!z?0*W:W/0:NaN);for(f?(w=1,a2=r2.e-i.e):(f=te,w=7,a2=Pt(r2.e/w)-Pt(i.e/w)),T=z.length,B2=L.length,E=(p2=new Z(W)).d=[],c=0;z[c]==(L[c]||0);c++);if(z[c]>(L[c]||0)&&a2--,null==u2?(m=u2=Z.precision,o=Z.rounding):m=s?u2+(r2.e-i.e)+1:u2,m<0)E.push(1),M=!0;else{if(m=m/w+2|0,c=0,1==T){for(D2=0,z=z[0],m++;(c<B2||D2)&&m--;c++)C=D2*f+(L[c]||0),E[c]=C/z|0,D2=C%z|0;M=D2||c<B2}else{for((D2=f/(z[0]+1)|0)>1&&(z=t2(z,D2,f),L=t2(L,D2,f),T=z.length,B2=L.length),y=T,A=(F=L.slice(0,T)).length;A<T;)F[A++]=0;(q=z.slice()).unshift(0),x=z[0],z[1]>=f/2&&++x;do{D2=0,(l=e(z,F,T,A))<0?(d2=F[0],T!=A&&(d2=d2*f+(F[1]||0)),(D2=d2/x|0)>1?(D2>=f&&(D2=f-1),1==(l=e(h2=t2(z,D2,f),F,g=h2.length,A=F.length))&&(D2--,n(h2,T<g?q:z,g,f))):(0==D2&&(l=D2=1),h2=z.slice()),(g=h2.length)<A&&h2.unshift(0),n(F,h2,A,f),-1==l&&((l=e(z,F,T,A=F.length))<1&&(D2++,n(F,T<A?q:z,A,f))),A=F.length):0===l&&(D2++,F=[0]),E[c++]=D2,l&&F[0]?F[A++]=L[y]||0:(F=[L[y]],A=1)}while((y++<B2||void 0!==F[0])&&m--);M=void 0!==F[0]}E[0]||E.shift()}if(1==w)p2.e=a2,Ai=M;else{for(c=1,D2=E[0];D2>=10;D2/=10)c++;p2.e=c+a2*w-1,H(p2,s?u2+p2.e+1:u2,o,M)}return p2}}();function H(t2,e,n,r2){var i,u2,o,s,f,l,a2,c,D2,w=t2.constructor;t:if(null!=e){if(!(c=t2.d))return t2;for(i=1,s=c[0];s>=10;s/=10)i++;if((u2=e-i)<0)u2+=7,o=e,f=(a2=c[D2=0])/Ct(10,i-o-1)%10|0;else if((D2=Math.ceil((u2+1)/7))>=(s=c.length)){if(!r2)break t;for(;s++<=D2;)c.push(0);a2=f=0,i=1,o=(u2%=7)-7+1}else{for(a2=s=c[D2],i=1;s>=10;s/=10)i++;f=(o=(u2%=7)-7+i)<0?0:a2/Ct(10,i-o-1)%10|0}if(r2=r2||e<0||void 0!==c[D2+1]||(o<0?a2:a2%Ct(10,i-o-1)),l=n<4?(f||r2)&&(0==n||n==(t2.s<0?3:2)):f>5||5==f&&(4==n||r2||6==n&&(u2>0?o>0?a2/Ct(10,i-o):0:c[D2-1])%10&1||n==(t2.s<0?8:7)),e<1||!c[0])return c.length=0,l?(e-=t2.e+1,c[0]=Ct(10,(7-e%7)%7),t2.e=-e||0):c[0]=t2.e=0,t2;if(0==u2?(c.length=D2,s=1,D2--):(c.length=D2+1,s=Ct(10,7-u2),c[D2]=o>0?(a2/Ct(10,i-o)%Ct(10,o)|0)*s:0),l)for(;;){if(0==D2){for(u2=1,o=c[0];o>=10;o/=10)u2++;for(o=c[0]+=s,s=1;o>=10;o/=10)s++;u2!=s&&(t2.e++,c[0]==te&&(c[0]=1));break}if(c[D2]+=s,c[D2]!=te)break;c[D2--]=0,s=1}for(u2=c.length;0===c[--u2];)c.pop()}return K&&(t2.e>w.maxE?(t2.d=null,t2.e=NaN):t2.e<w.minE&&(t2.e=0,t2.d=[0])),t2}function ne(t2,e,n){if(!t2.isFinite())return Si(t2);var r2,i=t2.e,u2=Tt(t2.d),o=u2.length;return e?(n&&(r2=n-o)>0?u2=u2.charAt(0)+"."+u2.slice(1)+ce(r2):o>1&&(u2=u2.charAt(0)+"."+u2.slice(1)),u2=u2+(t2.e<0?"e":"e+")+t2.e):i<0?(u2="0."+ce(-i-1)+u2,n&&(r2=n-o)>0&&(u2+=ce(r2))):i>=o?(u2+=ce(i+1-o),n&&(r2=n-i-1)>0&&(u2=u2+"."+ce(r2))):((r2=i+1)<o&&(u2=u2.slice(0,r2)+"."+u2.slice(r2)),n&&(r2=n-o)>0&&(i+1===o&&(u2+="."),u2+=ce(r2))),u2}function yn(t2,e){var n=t2[0];for(e*=7;n>=10;n/=10)e++;return e}function pn(t2,e,n){if(e>xo)throw K=!0,n&&(t2.precision=n),Error(Ci);return H(new t2(hn),e,1,!0)}function ee(t2,e,n){if(e>Ln)throw Error(Ci);return H(new t2(Dn),e,n,!0)}function Mi(t2){var e=t2.length-1,n=7*e+1;if(e=t2[e]){for(;e%10==0;e/=10)n--;for(e=t2[0];e>=10;e/=10)n++}return n}function ce(t2){for(var e="";t2--;)e+="0";return e}function Ni(t2,e,n,r2){var i,u2=new t2(1),o=Math.ceil(r2/7+4);for(K=!1;;){if(n%2&&(gr((u2=u2.times(e)).d,o)&&(i=!0)),0===(n=Pt(n/2))){n=u2.d.length-1,i&&0===u2.d[n]&&++u2.d[n];break}gr((e=e.times(e)).d,o)}return K=!0,u2}function mr(t2){return 1&t2.d[t2.d.length-1]}function xi(t2,e,n){for(var r2,i,u2=new t2(e[0]),o=0;++o<e.length;){if(!(i=new t2(e[o])).s){u2=i;break}((r2=u2.cmp(i))===n||0===r2&&u2.s===n)&&(u2=i)}return u2}function Zn(t2,e){var n,r2,i,u2,o,s,f,l=0,a2=0,c=0,D2=t2.constructor,w=D2.rounding,M=D2.precision;if(!t2.d||!t2.d[0]||t2.e>17)return new D2(t2.d?t2.d[0]?t2.s<0?0:1/0:1:t2.s?t2.s<0?0:t2:NaN);for(null==e?(K=!1,f=M):f=e,s=new D2(.03125);t2.e>-2;)t2=t2.times(s),c+=5;for(f+=r2=Math.log(Ct(2,c))/Math.LN10*2+5|0,n=u2=o=new D2(1),D2.precision=f;;){if(u2=H(u2.times(t2),f,1),n=n.times(++a2),Tt((s=o.plus(ft(u2,n,f,1))).d).slice(0,f)===Tt(o.d).slice(0,f)){for(i=c;i--;)o=H(o.times(o),f,1);if(null!=e)return D2.precision=M,o;if(!(l<3&&ke(o.d,f-r2,w,l)))return H(o,D2.precision=M,w,K=!0);D2.precision=f+=10,n=u2=s=new D2(1),a2=0,l++}o=s}}function le(t2,e){var n,r2,i,u2,o,s,f,l,a2,c,D2,w=1,h2=t2,g=h2.d,p2=h2.constructor,E=p2.rounding,F=p2.precision;if(h2.s<0||!g||!g[0]||!h2.e&&1==g[0]&&1==g.length)return new p2(g&&!g[0]?-1/0:1!=h2.s?NaN:g?0:h2);if(null==e?(K=!1,a2=F):a2=e,p2.precision=a2+=10,r2=(n=Tt(g)).charAt(0),!(Math.abs(u2=h2.e)<15e14))return l=pn(p2,a2+2,F).times(u2+""),h2=le(new p2(r2+"."+n.slice(1)),a2-10).plus(l),p2.precision=F,null==e?H(h2,F,E,K=!0):h2;for(;r2<7&&1!=r2||1==r2&&n.charAt(1)>3;)r2=(n=Tt((h2=h2.times(t2)).d)).charAt(0),w++;for(u2=h2.e,r2>1?(h2=new p2("0."+n),u2++):h2=new p2(r2+"."+n.slice(1)),c=h2,f=o=h2=ft(h2.minus(1),h2.plus(1),a2,1),D2=H(h2.times(h2),a2,1),i=3;;){if(o=H(o.times(D2),a2,1),Tt((l=f.plus(ft(o,new p2(i),a2,1))).d).slice(0,a2)===Tt(f.d).slice(0,a2)){if(f=f.times(2),0!==u2&&(f=f.plus(pn(p2,a2+2,F).times(u2+""))),f=ft(f,new p2(w),a2,1),null!=e)return p2.precision=F,f;if(!ke(f.d,a2-10,E,s))return H(f,p2.precision=F,E,K=!0);p2.precision=a2+=10,l=o=h2=ft(c.minus(1),c.plus(1),a2,1),D2=H(h2.times(h2),a2,1),i=s=1}f=l,i+=2}}function Si(t2){return String(t2.s*t2.s/0)}function an(t2,e){var n,r2,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r2=e.search(/e/i))>0?(n<0&&(n=r2),n+=+e.slice(r2+1),e=e.substring(0,r2)):n<0&&(n=e.length),r2=0;48===e.charCodeAt(r2);r2++);for(i=e.length;48===e.charCodeAt(i-1);--i);if(e=e.slice(r2,i)){if(i-=r2,t2.e=n=n-r2-1,t2.d=[],r2=(n+1)%7,n<0&&(r2+=7),r2<i){for(r2&&t2.d.push(+e.slice(0,r2)),i-=7;r2<i;)t2.d.push(+e.slice(r2,r2+=7));r2=7-(e=e.slice(r2)).length}else r2-=i;for(;r2--;)e+="0";t2.d.push(+e),K&&(t2.e>t2.constructor.maxE?(t2.d=null,t2.e=NaN):t2.e<t2.constructor.minE&&(t2.e=0,t2.d=[0]))}else t2.e=0,t2.d=[0];return t2}function ze(t2,e,n,r2,i){var u2,o,s,f,l=t2.precision,a2=Math.ceil(l/7);for(K=!1,f=n.times(n),s=new t2(r2);;){if(o=ft(s.times(f),new t2(e++*e++),l,1),s=i?r2.plus(o):r2.minus(o),r2=ft(o.times(f),new t2(e++*e++),l,1),void 0!==(o=s.plus(r2)).d[a2]){for(u2=a2;o.d[u2]===s.d[u2]&&u2--;);if(-1==u2)break}u2=s,s=r2,r2=o,o=u2}return K=!0,o.d.length=a2+1,o}function Bn(t2,e){for(var n=t2;--e;)n*=t2;return n}function Ti(t2,e){var n,r2=e.s<0,i=ee(t2,t2.precision,1),u2=i.times(.5);if((e=e.abs()).lte(u2))return se=r2?4:1,e;if((n=e.divToInt(i)).isZero())se=r2?3:2;else{if((e=e.minus(n.times(i))).lte(u2))return se=mr(n)?r2?2:3:r2?4:1,e;se=mr(n)?r2?1:4:r2?3:2}return e.minus(i).abs()}function Vn(t2,e,n,r2){var i,u2,o,s,f,l,a2,c,D2,w=t2.constructor,M=void 0!==n;if(M?($t(n,1,De),void 0===r2?r2=w.rounding:$t(r2,0,8)):(n=w.precision,r2=w.rounding),t2.isFinite()){for(M?(i=2,16==e?n=4*n-3:8==e&&(n=3*n-2)):i=e,(o=(a2=ne(t2)).indexOf("."))>=0&&(a2=a2.replace(".",""),(D2=new w(1)).e=a2.length-o,D2.d=sn(ne(D2),10,i),D2.e=D2.d.length),u2=f=(c=sn(a2,10,i)).length;0==c[--f];)c.pop();if(c[0]){if(o<0?u2--:((t2=new w(t2)).d=c,t2.e=u2,c=(t2=ft(t2,D2,n,r2,0,i)).d,u2=t2.e,l=Ai),o=c[n],s=i/2,l=l||void 0!==c[n+1],l=r2<4?(void 0!==o||l)&&(0===r2||r2===(t2.s<0?3:2)):o>s||o===s&&(4===r2||l||6===r2&&1&c[n-1]||r2===(t2.s<0?8:7)),c.length=n,l)for(;++c[--n]>i-1;)c[n]=0,n||(++u2,c.unshift(1));for(f=c.length;!c[f-1];--f);for(o=0,a2="";o<f;o++)a2+=Xn.charAt(c[o]);if(M){if(f>1)if(16==e||8==e){for(o=16==e?4:3,--f;f%o;f++)a2+="0";for(f=(c=sn(a2,i,e)).length;!c[f-1];--f);for(o=1,a2="1.";o<f;o++)a2+=Xn.charAt(c[o])}else a2=a2.charAt(0)+"."+a2.slice(1);a2=a2+(u2<0?"p":"p+")+u2}else if(u2<0){for(;++u2;)a2="0"+a2;a2="0."+a2}else if(++u2>f)for(u2-=f;u2--;)a2+="0";else u2<f&&(a2=a2.slice(0,u2)+"."+a2.slice(u2))}else a2=M?"0p+0":"0";a2=(16==e?"0x":2==e?"0b":8==e?"0o":"")+a2}else a2=Si(t2);return t2.s<0?"-"+a2:a2}function gr(t2,e){if(t2.length>e)return t2.length=e,!0}function Io(t2){return new this(t2).abs()}function Oo(t2){return new this(t2).acos()}function Po(t2){return new this(t2).acosh()}function zo(t2,e){return new this(t2).plus(e)}function Ro(t2){return new this(t2).asin()}function qo(t2){return new this(t2).asinh()}function Yo(t2){return new this(t2).atan()}function Uo(t2){return new this(t2).atanh()}function Xo(t2,e){t2=new this(t2),e=new this(e);var n,r2=this.precision,i=this.rounding,u2=r2+4;return t2.s&&e.s?t2.d||e.d?!e.d||t2.isZero()?(n=e.s<0?ee(this,r2,i):new this(0)).s=t2.s:!t2.d||e.isZero()?(n=ee(this,u2,1).times(.5)).s=t2.s:e.s<0?(this.precision=u2,this.rounding=1,n=this.atan(ft(t2,e,u2,1)),e=ee(this,u2,1),this.precision=r2,this.rounding=i,n=t2.s<0?n.minus(e):n.plus(e)):n=this.atan(ft(t2,e,u2,1)):(n=ee(this,u2,1).times(e.s>0?.25:.75)).s=t2.s:n=new this(NaN),n}function $o(t2){return new this(t2).cbrt()}function Lo(t2){return H(t2=new this(t2),t2.e+1,2)}function Zo(t2,e,n){return new this(t2).clamp(e,n)}function Wo(t2){if(!t2||"object"!=typeof t2)throw Error(Cn+"Object expected");var e,n,r2,i=!0===t2.defaults,u2=["precision",1,De,"rounding",0,8,"toExpNeg",-Te,0,"toExpPos",0,Te,"maxE",0,Te,"minE",-Te,0,"modulo",0,9];for(e=0;e<u2.length;e+=3)if(n=u2[e],i&&(this[n]=$n[n]),void 0!==(r2=t2[n])){if(!(Pt(r2)===r2&&r2>=u2[e+1]&&r2<=u2[e+2]))throw Error(he+n+": "+r2);this[n]=r2}if(n="crypto",i&&(this[n]=$n[n]),void 0!==(r2=t2[n])){if(!0!==r2&&!1!==r2&&0!==r2&&1!==r2)throw Error(he+n+": "+r2);if(r2){if(!(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes)))throw Error(yi);this[n]=!0}else this[n]=!1}return this}function Vo(t2){return new this(t2).cos()}function Ho(t2){return new this(t2).cosh()}function Jo(t2,e){return new this(t2).div(e)}function ko(t2){return new this(t2).exp()}function Go(t2){return H(t2=new this(t2),t2.e+1,3)}function Qo(){var t2,e,n=new this(0);for(K=!1,t2=0;t2<arguments.length;)if((e=new this(arguments[t2++])).d)n.d&&(n=n.plus(e.times(e)));else{if(e.s)return K=!0,new this(1/0);n=e}return K=!0,n.sqrt()}function vr(t2){return t2 instanceof Re||t2&&t2.toStringTag===Bi||!1}function Ko(t2){return new this(t2).ln()}function jo(t2,e){return new this(t2).log(e)}function ts(t2){return new this(t2).log(2)}function es(t2){return new this(t2).log(10)}function ns(){return xi(this,arguments,-1)}function rs(){return xi(this,arguments,1)}function is(t2,e){return new this(t2).mod(e)}function us(t2,e){return new this(t2).mul(e)}function os(t2,e){return new this(t2).pow(e)}function ss(t2){var e,n,r2,i,u2=0,o=new this(1),s=[];if(void 0===t2?t2=this.precision:$t(t2,1,De),r2=Math.ceil(t2/7),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r2));u2<r2;)(i=e[u2])>=429e7?e[u2]=crypto.getRandomValues(new Uint32Array(1))[0]:s[u2++]=i%1e7;else{if(!crypto.randomBytes)throw Error(yi);for(e=crypto.randomBytes(r2*=4);u2<r2;)(i=e[u2]+(e[u2+1]<<8)+(e[u2+2]<<16)+((127&e[u2+3])<<24))>=214e7?crypto.randomBytes(4).copy(e,u2):(s.push(i%1e7),u2+=4);u2=r2/4}else for(;u2<r2;)s[u2++]=1e7*Math.random()|0;for(t2%=7,(r2=s[--u2])&&t2&&(i=Ct(10,7-t2),s[u2]=(r2/i|0)*i);0===s[u2];u2--)s.pop();if(u2<0)n=0,s=[0];else{for(n=-1;0===s[0];n-=7)s.shift();for(r2=1,i=s[0];i>=10;i/=10)r2++;r2<7&&(n-=7-r2)}return o.e=n,o.d=s,o}function as(t2){return H(t2=new this(t2),t2.e+1,this.rounding)}function fs(t2){return(t2=new this(t2)).d?t2.d[0]?t2.s:0*t2.s:t2.s||NaN}function cs(t2){return new this(t2).sin()}function ls(t2){return new this(t2).sinh()}function hs(t2){return new this(t2).sqrt()}function Ds(t2,e){return new this(t2).sub(e)}function ps(){var t2=0,e=arguments,n=new this(e[t2]);for(K=!1;n.s&&++t2<e.length;)n=n.plus(e[t2]);return K=!0,H(n,this.precision,this.rounding)}function ds(t2){return new this(t2).tan()}function ms(t2){return new this(t2).tanh()}function gs(t2){return H(t2=new this(t2),t2.e+1,1)}O[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")]=O.toString,O[Symbol.toStringTag]="Decimal";var Re=O.constructor=function bi(t2){var e,n,r2;function i(u2){var o,s,f,l=this;if(!(l instanceof i))return new i(u2);if(l.constructor=i,vr(u2))return l.s=u2.s,void(K?!u2.d||u2.e>i.maxE?(l.e=NaN,l.d=null):u2.e<i.minE?(l.e=0,l.d=[0]):(l.e=u2.e,l.d=u2.d.slice()):(l.e=u2.e,l.d=u2.d?u2.d.slice():u2.d));if("number"===(f=typeof u2)){if(0===u2)return l.s=1/u2<0?-1:1,l.e=0,void(l.d=[0]);if(u2<0?(u2=-u2,l.s=-1):l.s=1,u2===~~u2&&u2<1e7){for(o=0,s=u2;s>=10;s/=10)o++;return void(K?o>i.maxE?(l.e=NaN,l.d=null):o<i.minE?(l.e=0,l.d=[0]):(l.e=o,l.d=[u2]):(l.e=o,l.d=[u2]))}return 0*u2!=0?(u2||(l.s=NaN),l.e=NaN,void(l.d=null)):an(l,u2.toString())}if("string"===f)return 45===(s=u2.charCodeAt(0))?(u2=u2.slice(1),l.s=-1):(43===s&&(u2=u2.slice(1)),l.s=1),_i.test(u2)?an(l,u2):function(t2,e){var n,r2,i,u2,o,s,f,l,a2;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),_i.test(e))return an(t2,e)}else if("Infinity"===e||"NaN"===e)return+e||(t2.s=NaN),t2.e=NaN,t2.d=null,t2;if(_o.test(e))n=16,e=e.toLowerCase();else if(Bo.test(e))n=2;else{if(!Mo.test(e))throw Error(he+e);n=8}for((u2=e.search(/p/i))>0?(f=+e.slice(u2+1),e=e.substring(2,u2)):e=e.slice(2),o=(u2=e.indexOf("."))>=0,r2=t2.constructor,o&&(u2=(s=(e=e.replace(".","")).length)-u2,i=Ni(r2,new r2(n),u2,2*u2)),u2=a2=(l=sn(e,n,te)).length-1;0===l[u2];--u2)l.pop();return u2<0?new r2(0*t2.s):(t2.e=yn(l,a2),t2.d=l,K=!1,o&&(t2=ft(t2,i,4*s)),f&&(t2=t2.times(Math.abs(f)<54?Ct(2,f):Re.pow(2,f))),K=!0,t2)}(l,u2);if("bigint"===f)return u2<0?(u2=-u2,l.s=-1):l.s=1,an(l,u2.toString());throw Error(he+u2)}if(i.prototype=O,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Wo,i.clone=bi,i.isDecimal=vr,i.abs=Io,i.acos=Oo,i.acosh=Po,i.add=zo,i.asin=Ro,i.asinh=qo,i.atan=Yo,i.atanh=Uo,i.atan2=Xo,i.cbrt=$o,i.ceil=Lo,i.clamp=Zo,i.cos=Vo,i.cosh=Ho,i.div=Jo,i.exp=ko,i.floor=Go,i.hypot=Qo,i.ln=Ko,i.log=jo,i.log10=es,i.log2=ts,i.max=ns,i.min=rs,i.mod=is,i.mul=us,i.pow=os,i.random=ss,i.round=as,i.sign=fs,i.sin=cs,i.sinh=ls,i.sqrt=hs,i.sub=Ds,i.sum=ps,i.tan=ds,i.tanh=ms,i.trunc=gs,void 0===t2&&(t2={}),t2&&!0!==t2.defaults)for(r2=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r2.length;)t2.hasOwnProperty(n=r2[e++])||(t2[n]=this[n]);return i.config(t2),i}($n);hn=new Re(hn),Dn=new Re(Dn);var ws=/* @__PURE__ */Ft("BigNumber",["?on","config"],t2=>{var{on:e,config:n}=t2,r2=Re.clone({precision:n.precision,modulo:Re.EUCLID});return r2.prototype=Object.create(r2.prototype),r2.prototype.type="BigNumber",r2.prototype.isBigNumber=!0,r2.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},r2.fromJSON=function(i){return new r2(i.value)},e&&e("config",function(i,u2){i.precision!==u2.precision&&r2.config({precision:i.precision})}),r2},{isClass:!0});const It=Math.cosh||function(t2){return Math.abs(t2)<1e-9?1-t2:.5*(Math.exp(t2)+Math.exp(-t2))},Ht=Math.sinh||function(t2){return Math.abs(t2)<1e-9?t2:.5*(Math.exp(t2)-Math.exp(-t2))},Rn=function(t2,e){return(t2=Math.abs(t2))<(e=Math.abs(e))&&([t2,e]=[e,t2]),t2<1e8?Math.sqrt(t2*t2+e*e):(e/=t2,t2*Math.sqrt(1+e*e))},_e=function(){throw SyntaxError("Invalid Param")};function qn(t2,e){const n=Math.abs(t2),r2=Math.abs(e);return 0===t2?Math.log(r2):0===e?Math.log(n):n<3e3&&r2<3e3?.5*Math.log(t2*t2+e*e):(t2*=.5,e*=.5,.5*Math.log(t2*t2+e*e)+Math.LN2)}const As={re:0,im:0},pe=function(t2,e){const n=As;if(null==t2)n.re=n.im=0;else if(void 0!==e)n.re=t2,n.im=e;else switch(typeof t2){case"object":if("im"in t2&&"re"in t2)n.re=t2.re,n.im=t2.im;else if("abs"in t2&&"arg"in t2){if(!isFinite(t2.abs)&&isFinite(t2.arg))return S.INFINITY;n.re=t2.abs*Math.cos(t2.arg),n.im=t2.abs*Math.sin(t2.arg)}else if("r"in t2&&"phi"in t2){if(!isFinite(t2.r)&&isFinite(t2.phi))return S.INFINITY;n.re=t2.r*Math.cos(t2.phi),n.im=t2.r*Math.sin(t2.phi)}else 2===t2.length?(n.re=t2[0],n.im=t2[1]):_e();break;case"string":n.im=n.re=0;const r2=t2.replace(/_/g,"").match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g);let i=1,u2=0;null===r2&&_e();for(let o=0;o<r2.length;o++){const s=r2[o];" "===s||"\t"===s||"\n"===s||("+"===s?i++:"-"===s?u2++:"i"===s||"I"===s?(i+u2===0&&_e()," "===r2[o+1]||isNaN(r2[o+1])?n.im+=parseFloat((u2%2?"-":"")+"1"):(n.im+=parseFloat((u2%2?"-":"")+r2[o+1]),o++),i=u2=0):((i+u2===0||isNaN(s))&&_e(),"i"===r2[o+1]||"I"===r2[o+1]?(n.im+=parseFloat((u2%2?"-":"")+s),o++):n.re+=parseFloat((u2%2?"-":"")+s),i=u2=0))}i+u2>0&&_e();break;case"number":n.im=0,n.re=t2;break;default:_e()}return isNaN(n.re)||isNaN(n.im),n};function S(t2,e){if(!(this instanceof S))return new S(t2,e);const n=pe(t2,e);this.re=n.re,this.im=n.im}S.prototype={re:0,im:0,sign:function(){const t2=Rn(this.re,this.im);return new S(this.re/t2,this.im/t2)},add:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r2||i?r2&&i?S.NAN:S.INFINITY:new S(this.re+n.re,this.im+n.im)},sub:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r2||i?r2&&i?S.NAN:S.INFINITY:new S(this.re-n.re,this.im-n.im)},mul:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),u2=0===this.re&&0===this.im,o=0===n.re&&0===n.im;return r2&&o||i&&u2?S.NAN:r2||i?S.INFINITY:0===n.im&&0===this.im?new S(this.re*n.re,0):new S(this.re*n.re-this.im*n.im,this.re*n.im+this.im*n.re)},div:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),u2=0===this.re&&0===this.im,o=0===n.re&&0===n.im;if(u2&&o||r2&&i)return S.NAN;if(o||r2)return S.INFINITY;if(u2||i)return S.ZERO;if(0===n.im)return new S(this.re/n.re,this.im/n.re);if(Math.abs(n.re)<Math.abs(n.im)){const s=n.re/n.im,f=n.re*s+n.im;return new S((this.re*s+this.im)/f,(this.im*s-this.re)/f)}{const s=n.im/n.re,f=n.im*s+n.re;return new S((this.re+this.im*s)/f,(this.im-this.re*s)/f)}},pow:function(t2,e){const n=pe(t2,e),r2=0===this.re&&0===this.im;if(0===n.re&&0===n.im)return S.ONE;if(0===n.im){if(0===this.im&&this.re>0)return new S(Math.pow(this.re,n.re),0);if(0===this.re)switch((n.re%4+4)%4){case 0:return new S(Math.pow(this.im,n.re),0);case 1:return new S(0,Math.pow(this.im,n.re));case 2:return new S(-Math.pow(this.im,n.re),0);case 3:return new S(0,-Math.pow(this.im,n.re))}}if(r2&&n.re>0)return S.ZERO;const u2=Math.atan2(this.im,this.re),o=qn(this.re,this.im);let s=Math.exp(n.re*o-n.im*u2),f=n.im*o+n.re*u2;return new S(s*Math.cos(f),s*Math.sin(f))},sqrt:function(){const t2=this.re,e=this.im;if(0===e)return t2>=0?new S(Math.sqrt(t2),0):new S(0,Math.sqrt(-t2));const n=Rn(t2,e);let r2=Math.sqrt(.5*(n+Math.abs(t2))),i=Math.abs(e)/(2*r2);return t2>=0?new S(r2,e<0?-i:i):new S(i,e<0?-r2:r2)},exp:function(){const t2=Math.exp(this.re);return 0===this.im?new S(t2,0):new S(t2*Math.cos(this.im),t2*Math.sin(this.im))},expm1:function(){const t2=this.re,e=this.im;return new S(Math.expm1(t2)*Math.cos(e)+function(t2){const e=Math.PI/4;if(-e>t2||t2>e)return Math.cos(t2)-1;const n=t2*t2;return n*(n*(n*(n*(n*(n*(n*(n/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5)}(e),Math.exp(t2)*Math.sin(e))},log:function(){const t2=this.re,e=this.im;return 0===e&&t2>0?new S(Math.log(t2),0):new S(qn(t2,e),Math.atan2(e,t2))},abs:function(){return Rn(this.re,this.im)},arg:function(){return Math.atan2(this.im,this.re)},sin:function(){const t2=this.re,e=this.im;return new S(Math.sin(t2)*It(e),Math.cos(t2)*Ht(e))},cos:function(){const t2=this.re,e=this.im;return new S(Math.cos(t2)*It(e),-Math.sin(t2)*Ht(e))},tan:function(){const t2=2*this.re,e=2*this.im,n=Math.cos(t2)+It(e);return new S(Math.sin(t2)/n,Ht(e)/n)},cot:function(){const t2=2*this.re,e=2*this.im,n=Math.cos(t2)-It(e);return new S(-Math.sin(t2)/n,Ht(e)/n)},sec:function(){const t2=this.re,e=this.im,n=.5*It(2*e)+.5*Math.cos(2*t2);return new S(Math.cos(t2)*It(e)/n,Math.sin(t2)*Ht(e)/n)},csc:function(){const t2=this.re,e=this.im,n=.5*It(2*e)-.5*Math.cos(2*t2);return new S(Math.sin(t2)*It(e)/n,-Math.cos(t2)*Ht(e)/n)},asin:function(){const t2=this.re,e=this.im,n=new S(e*e-t2*t2+1,-2*t2*e).sqrt(),r2=new S(n.re-e,n.im+t2).log();return new S(r2.im,-r2.re)},acos:function(){const t2=this.re,e=this.im,n=new S(e*e-t2*t2+1,-2*t2*e).sqrt(),r2=new S(n.re-e,n.im+t2).log();return new S(Math.PI/2-r2.im,r2.re)},atan:function(){const t2=this.re,e=this.im;if(0===t2){if(1===e)return new S(0,1/0);if(-1===e)return new S(0,-1/0)}const n=t2*t2+(1-e)*(1-e),r2=new S((1-e*e-t2*t2)/n,-2*t2/n).log();return new S(-.5*r2.im,.5*r2.re)},acot:function(){const t2=this.re,e=this.im;if(0===e)return new S(Math.atan2(1,t2),0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).atan():new S(0!==t2?t2/0:0,0!==e?-e/0:0).atan()},asec:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(0,1/0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).acos():new S(0!==t2?t2/0:0,0!==e?-e/0:0).acos()},acsc:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(Math.PI/2,1/0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).asin():new S(0!==t2?t2/0:0,0!==e?-e/0:0).asin()},sinh:function(){const t2=this.re,e=this.im;return new S(Ht(t2)*Math.cos(e),It(t2)*Math.sin(e))},cosh:function(){const t2=this.re,e=this.im;return new S(It(t2)*Math.cos(e),Ht(t2)*Math.sin(e))},tanh:function(){const t2=2*this.re,e=2*this.im,n=It(t2)+Math.cos(e);return new S(Ht(t2)/n,Math.sin(e)/n)},coth:function(){const t2=2*this.re,e=2*this.im,n=It(t2)-Math.cos(e);return new S(Ht(t2)/n,-Math.sin(e)/n)},csch:function(){const t2=this.re,e=this.im,n=Math.cos(2*e)-It(2*t2);return new S(-2*Ht(t2)*Math.cos(e)/n,2*It(t2)*Math.sin(e)/n)},sech:function(){const t2=this.re,e=this.im,n=Math.cos(2*e)+It(2*t2);return new S(2*It(t2)*Math.cos(e)/n,-2*Ht(t2)*Math.sin(e)/n)},asinh:function(){let t2=this.im;this.im=-this.re,this.re=t2;const e=this.asin();return this.re=-this.im,this.im=t2,t2=e.re,e.re=-e.im,e.im=t2,e},acosh:function(){const t2=this.acos();if(t2.im<=0){const e=t2.re;t2.re=-t2.im,t2.im=e}else{const e=t2.im;t2.im=-t2.re,t2.re=e}return t2},atanh:function(){const t2=this.re,e=this.im,n=t2>1&&0===e,r2=1-t2,i=1+t2,u2=r2*r2+e*e,o=0!==u2?new S((i*r2-e*e)/u2,(e*r2+i*e)/u2):new S(-1!==t2?t2/0:0,0!==e?e/0:0),s=o.re;return o.re=qn(o.re,o.im)/2,o.im=Math.atan2(o.im,s)/2,n&&(o.im=-o.im),o},acoth:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(0,Math.PI/2);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).atanh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).atanh()},acsch:function(){const t2=this.re,e=this.im;if(0===e)return new S(0!==t2?Math.log(t2+Math.sqrt(t2*t2+1)):1/0,0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).asinh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).asinh()},asech:function(){const t2=this.re,e=this.im;if(this.isZero())return S.INFINITY;const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).acosh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).acosh()},inverse:function(){if(this.isZero())return S.INFINITY;if(this.isInfinite())return S.ZERO;const t2=this.re,e=this.im,n=t2*t2+e*e;return new S(t2/n,-e/n)},conjugate:function(){return new S(this.re,-this.im)},neg:function(){return new S(-this.re,-this.im)},ceil:function(t2){return t2=Math.pow(10,t2||0),new S(Math.ceil(this.re*t2)/t2,Math.ceil(this.im*t2)/t2)},floor:function(t2){return t2=Math.pow(10,t2||0),new S(Math.floor(this.re*t2)/t2,Math.floor(this.im*t2)/t2)},round:function(t2){return t2=Math.pow(10,t2||0),new S(Math.round(this.re*t2)/t2,Math.round(this.im*t2)/t2)},equals:function(t2,e){const n=pe(t2,e);return Math.abs(n.re-this.re)<=S.EPSILON&&Math.abs(n.im-this.im)<=S.EPSILON},clone:function(){return new S(this.re,this.im)},toString:function(){let t2=this.re,e=this.im,n="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(t2)<S.EPSILON&&(t2=0),Math.abs(e)<S.EPSILON&&(e=0),0===e?n+t2:(0!==t2?(n+=t2,n+=" ",e<0?(e=-e,n+="-"):n+="+",n+=" "):e<0&&(e=-e,n+="-"),1!==e&&(n+=e),n+"i"))},toVector:function(){return[this.re,this.im]},valueOf:function(){return 0===this.im?this.re:null},isNaN:function(){return isNaN(this.re)||isNaN(this.im)},isZero:function(){return 0===this.im&&0===this.re},isFinite:function(){return isFinite(this.re)&&isFinite(this.im)},isInfinite:function(){return!this.isFinite()}},S.ZERO=new S(0,0),S.ONE=new S(1,0),S.I=new S(0,1),S.PI=new S(Math.PI,0),S.E=new S(Math.E,0),S.INFINITY=new S(1/0,1/0),S.NAN=new S(NaN,NaN),S.EPSILON=1e-15;var Bs=/* @__PURE__ */Ft("Complex",[],()=>(Object.defineProperty(S,"name",{value:"Complex"}),S.prototype.constructor=S,S.prototype.type="Complex",S.prototype.isComplex=!0,S.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},S.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},S.prototype.format=function(t2){var n=this.im,r2=this.re,i=Un(this.re,t2),u2=Un(this.im,t2),o=lt(t2)?t2:t2?t2.precision:null;if(null!==o){var s=Math.pow(10,-o);Math.abs(r2/n)<s&&(r2=0),Math.abs(n/r2)<s&&(n=0)}return 0===n?i:0===r2?1===n?"i":-1===n?"-i":u2+"i":n<0?-1===n?i+" - i":i+" - "+u2.substring(1)+"i":1===n?i+" + i":i+" + "+u2+"i"},S.fromPolar=function(t2){switch(arguments.length){case 1:var e=arguments[0];if("object"==typeof e)return S(e);throw new TypeError("Input has to be an object with r and phi keys.");case 2:var n=arguments[0],r2=arguments[1];if(lt(n)){if(Fn(r2)&&r2.hasBase("ANGLE")&&(r2=r2.toNumber("rad")),lt(r2))return new S({r:n,phi:r2});throw new TypeError("Phi is not a number nor an angle unit.")}throw new TypeError("Radius r is not a number.");default:throw new SyntaxError("Wrong number of arguments in function fromPolar")}},S.prototype.valueOf=S.prototype.toString,S.fromJSON=function(t2){return new S(t2)},S.compare=function(t2,e){return t2.re>e.re?1:t2.re<e.re?-1:t2.im>e.im?1:t2.im<e.im?-1:0},S),{isClass:!0});typeof BigInt>"u"&&(BigInt=function(t2){if(isNaN(t2))throw new Error("");return t2});const V=BigInt(0),tt=BigInt(1),_t=BigInt(2),Ve=BigInt(3),be=BigInt(5),Xt=BigInt(10);BigInt(Number.MAX_SAFE_INTEGER);const U={s:tt,n:V,d:tt};function oe(t2,e){try{t2=BigInt(t2)}catch{throw fe()}return t2*e}function Kt(t2){return"bigint"==typeof t2?t2:Math.floor(t2)}function dt(t2,e){if(e===V)throw Hn();const n=Object.create(Jt.prototype);n.s=t2<V?-tt:tt;const r2=de(t2=t2<V?-t2:t2,e);return n.n=t2/r2,n.d=e/r2,n}const Ms=[_t*_t,_t,_t*_t,_t,_t*_t,_t*Ve,_t,_t*Ve];function Me(t2){const e=/* @__PURE__ */Object.create(null);if(t2<=tt)return e[t2]=tt,e;const n=r2=>{e[r2]=(e[r2]||V)+tt};for(;t2%_t===V;)n(_t),t2/=_t;for(;t2%Ve===V;)n(Ve),t2/=Ve;for(;t2%be===V;)n(be),t2/=be;for(let r2=0,i=_t+be;i*i<=t2;){for(;t2%i===V;)n(i),t2/=i;i+=Ms[r2],r2=r2+1&7}return t2>tt&&n(t2),e}const Bt=function(t2,e){let n=V,r2=tt,i=tt;if(null!=t2)if(void 0!==e){if("bigint"==typeof t2)n=t2;else{if(isNaN(t2))throw fe();if(t2%1!=0)throw Fr();n=BigInt(t2)}if("bigint"==typeof e)r2=e;else{if(isNaN(e))throw fe();if(e%1!=0)throw Fr();r2=BigInt(e)}i=n*r2}else if("object"==typeof t2){if("d"in t2&&"n"in t2)n=BigInt(t2.n),r2=BigInt(t2.d),"s"in t2&&(n*=BigInt(t2.s));else if(0 in t2)n=BigInt(t2[0]),1 in t2&&(r2=BigInt(t2[1]));else{if("bigint"!=typeof t2)throw fe();n=t2}i=n*r2}else if("number"==typeof t2){if(isNaN(t2))throw fe();if(t2<0&&(i=-tt,t2=-t2),t2%1==0)n=BigInt(t2);else{let u2=1,o=0,s=1,f=1,l=1,a2=1e7;for(t2>=1&&(u2=10**Math.floor(1+Math.log10(t2)),t2/=u2);s<=a2&&l<=a2;){let c=(o+f)/(s+l);if(t2===c){s+l<=a2?(n=o+f,r2=s+l):l>s?(n=f,r2=l):(n=o,r2=s);break}t2>c?(o+=f,s+=l):(f+=o,l+=s),s>a2?(n=f,r2=l):(n=o,r2=s)}n=BigInt(n)*BigInt(u2),r2=BigInt(r2)}}else if("string"==typeof t2){let u2=0,o=V,s=V,f=V,l=tt,a2=tt,c=t2.replace(/_/g,"").match(/\d+|./g);if(null===c)throw fe();if("-"===c[u2]?(i=-tt,u2++):"+"===c[u2]&&u2++,c.length===u2+1?s=oe(c[u2++],i):"."===c[u2+1]||"."===c[u2]?("."!==c[u2]&&(o=oe(c[u2++],i)),u2++,(u2+1===c.length||"("===c[u2+1]&&")"===c[u2+3]||"'"===c[u2+1]&&"'"===c[u2+3])&&(s=oe(c[u2],i),l=Xt**BigInt(c[u2].length),u2++),("("===c[u2]&&")"===c[u2+2]||"'"===c[u2]&&"'"===c[u2+2])&&(f=oe(c[u2+1],i),a2=Xt**BigInt(c[u2+1].length)-tt,u2+=3)):"/"===c[u2+1]||":"===c[u2+1]?(s=oe(c[u2],i),l=oe(c[u2+2],tt),u2+=3):"/"===c[u2+3]&&" "===c[u2+1]&&(o=oe(c[u2],i),s=oe(c[u2+2],i),l=oe(c[u2+4],tt),u2+=5),!(c.length<=u2))throw fe();r2=l*a2,i=n=f+r2*o+a2*s}else{if("bigint"!=typeof t2)throw fe();n=t2,i=t2,r2=tt}if(r2===V)throw Hn();U.s=i<V?-tt:tt,U.n=n<V?-n:n,U.d=r2<V?-r2:r2};function Ss(t2,e,n){let r2=tt,i=function(t2,e,n){let r2=tt;for(;e>V;t2=t2*t2%n,e>>=tt)e&tt&&(r2=r2*t2%n);return r2}(Xt,n,e);for(let u2=0;u2<300;u2++){if(r2===i)return BigInt(u2);r2=r2*Xt%e,i=i*Xt%e}return 0}function de(t2,e){if(!t2)return e;if(!e)return t2;for(;;){if(!(t2%=e))return e;if(!(e%=t2))return t2}}function Jt(t2,e){if(Bt(t2,e),!(this instanceof Jt))return dt(U.s*U.n,U.d);t2=de(U.d,U.n),this.s=U.s,this.n=U.n/t2,this.d=U.d/t2}const Hn=function(){return new Error("Division by Zero")},fe=function(){return new Error("Invalid argument")},Fr=function(){return new Error("Parameters must be integer")};Jt.prototype={s:tt,n:V,d:tt,abs:function(){return dt(this.n,this.d)},neg:function(){return dt(-this.s*this.n,this.d)},add:function(t2,e){return Bt(t2,e),dt(this.s*this.n*U.d+U.s*this.d*U.n,this.d*U.d)},sub:function(t2,e){return Bt(t2,e),dt(this.s*this.n*U.d-U.s*this.d*U.n,this.d*U.d)},mul:function(t2,e){return Bt(t2,e),dt(this.s*U.s*this.n*U.n,this.d*U.d)},div:function(t2,e){return Bt(t2,e),dt(this.s*U.s*this.n*U.d,this.d*U.n)},clone:function(){return dt(this.s*this.n,this.d)},mod:function(t2,e){if(void 0===t2)return dt(this.s*this.n%this.d,tt);if(Bt(t2,e),V===U.n*this.d)throw Hn();return dt(this.s*(U.d*this.n)%(U.n*this.d),U.d*this.d)},gcd:function(t2,e){return Bt(t2,e),dt(de(U.n,this.n)*de(U.d,this.d),U.d*this.d)},lcm:function(t2,e){return Bt(t2,e),U.n===V&&this.n===V?dt(V,tt):dt(U.n*this.n,de(U.n,this.n)*de(U.d,this.d))},inverse:function(){return dt(this.s*this.d,this.n)},pow:function(t2,e){if(Bt(t2,e),U.d===tt)return U.s<V?dt((this.s*this.d)**U.n,this.n**U.n):dt((this.s*this.n)**U.n,this.d**U.n);if(this.s<V)return null;let n=Me(this.n),r2=Me(this.d),i=tt,u2=tt;for(let o in n)if("1"!==o){if("0"===o){i=V;break}if(n[o]*=U.n,n[o]%U.d!==V)return null;n[o]/=U.d,i*=BigInt(o)**n[o]}for(let o in r2)if("1"!==o){if(r2[o]*=U.n,r2[o]%U.d!==V)return null;r2[o]/=U.d,u2*=BigInt(o)**r2[o]}return U.s<V?dt(u2,i):dt(i,u2)},log:function(t2,e){if(Bt(t2,e),this.s<=V||U.s<=V)return null;const n=/* @__PURE__ */Object.create(null),r2=Me(U.n),i=Me(U.d),u2=Me(this.n),o=Me(this.d);for(const l in i)r2[l]=(r2[l]||V)-i[l];for(const l in o)u2[l]=(u2[l]||V)-o[l];for(const l in r2)"1"!==l&&(n[l]=!0);for(const l in u2)"1"!==l&&(n[l]=!0);let s=null,f=null;for(const l in n){const a2=r2[l]||V,c=u2[l]||V;if(a2===V){if(c!==V)return null;continue}let D2=c,w=a2;const M=de(D2,w);if(D2/=M,w/=M,null===s&&null===f)s=D2,f=w;else if(D2*f!==s*w)return null}return null!==s&&null!==f?dt(s,f):null},equals:function(t2,e){return Bt(t2,e),this.s*this.n*U.d===U.s*U.n*this.d},lt:function(t2,e){return Bt(t2,e),this.s*this.n*U.d<U.s*U.n*this.d},lte:function(t2,e){return Bt(t2,e),this.s*this.n*U.d<=U.s*U.n*this.d},gt:function(t2,e){return Bt(t2,e),this.s*this.n*U.d>U.s*U.n*this.d},gte:function(t2,e){return Bt(t2,e),this.s*this.n*U.d>=U.s*U.n*this.d},compare:function(t2,e){Bt(t2,e);let n=this.s*this.n*U.d-U.s*U.n*this.d;return(V<n)-(n<V)},ceil:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)+(t2*this.n%this.d>V&&this.s>=V?tt:V),t2)},floor:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)-(t2*this.n%this.d>V&&this.s<V?tt:V),t2)},round:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)+this.s*((this.s>=V?tt:V)+_t*(t2*this.n%this.d)>this.d?tt:V),t2)},roundTo:function(t2,e){Bt(t2,e);const n=this.n*U.d,r2=this.d*U.n,i=n%r2;let u2=Kt(n/r2);return i+i>=r2&&u2++,dt(this.s*u2*U.n,U.d)},divisible:function(t2,e){return Bt(t2,e),U.n!==V&&this.n*U.d%(U.n*this.d)===V},valueOf:function(){return Number(this.s*this.n)/Number(this.d)},toString:function(t2=15){let e=this.n,n=this.d,r2=function(t2,e){for(;e%_t===V;e/=_t);for(;e%be===V;e/=be);if(e===tt)return V;let n=Xt%e,r2=1;for(;n!==tt;r2++)if(n=n*Xt%e,r2>2e3)return V;return BigInt(r2)}(0,n),i=Ss(0,n,r2),u2=this.s<V?"-":"";if(u2+=Kt(e/n),e%=n,e*=Xt,e&&(u2+="."),r2){for(let o=i;o--;)u2+=Kt(e/n),e%=n,e*=Xt;u2+="(";for(let o=r2;o--;)u2+=Kt(e/n),e%=n,e*=Xt;u2+=")"}else for(let o=t2;e&&o--;)u2+=Kt(e/n),e%=n,e*=Xt;return u2},toFraction:function(t2=!1){let e=this.n,n=this.d,r2=this.s<V?"-":"";if(n===tt)r2+=e;else{const i=Kt(e/n);t2&&i>V&&(r2+=i,r2+=" ",e%=n),r2+=e,r2+="/",r2+=n}return r2},toLatex:function(t2=!1){let e=this.n,n=this.d,r2=this.s<V?"-":"";if(n===tt)r2+=e;else{const i=Kt(e/n);t2&&i>V&&(r2+=i,e%=n),r2+="\\frac{",r2+=e,r2+="}{",r2+=n,r2+="}"}return r2},toContinued:function(){let t2=this.n,e=this.d;const n=[];for(;e;){n.push(Kt(t2/e));const r2=t2%e;t2=e,e=r2}return n},simplify:function(t2=.001){const e=BigInt(Math.ceil(1/t2)),n=this.abs(),r2=n.toContinued();for(let i=1;i<r2.length;i++){let u2=dt(r2[i-1],tt);for(let s=i-2;s>=0;s--)u2=u2.inverse().add(r2[s]);let o=u2.sub(n);if(o.n*e<o.d)return u2.mul(this.s)}return this}};var Is=/* @__PURE__ */Ft("Fraction",[],()=>(Object.defineProperty(Jt,"name",{value:"Fraction"}),Jt.prototype.constructor=Jt,Jt.prototype.type="Fraction",Jt.prototype.isFraction=!0,Jt.prototype.toJSON=function(){return{mathjs:"Fraction",n:String(this.s*this.n),d:String(this.d)}},Jt.fromJSON=function(t2){return new Jt(t2)},Jt),{isClass:!0}),zs=/* @__PURE__ */Ft("Matrix",[],()=>{function t2(){if(!(this instanceof t2))throw new SyntaxError("Constructor must be called with the new operator")}return t2.prototype.type="Matrix",t2.prototype.isMatrix=!0,t2.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},t2.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},t2.prototype.create=function(e,n){throw new Error("Cannot invoke create on a Matrix interface")},t2.prototype.subset=function(e,n,r2){throw new Error("Cannot invoke subset on a Matrix interface")},t2.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},t2.prototype.set=function(e,n,r2){throw new Error("Cannot invoke set on a Matrix interface")},t2.prototype.resize=function(e,n){throw new Error("Cannot invoke resize on a Matrix interface")},t2.prototype.reshape=function(e,n){throw new Error("Cannot invoke reshape on a Matrix interface")},t2.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},t2.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},t2.prototype.map=function(e,n){throw new Error("Cannot invoke map on a Matrix interface")},t2.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},t2.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},t2.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},t2.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},t2.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},t2.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},t2},{isClass:!0});function Yn(t2,e,n){var i=new(0,t2.constructor)(2),u2="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!St(n))throw new Error("size must be an integer");if(t2.greaterThan(i.pow(n-1).sub(1))||t2.lessThan(i.pow(n-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!t2.isInteger())throw new Error("Value must be an integer");t2.lessThan(0)&&(t2=t2.add(i.pow(n))),u2="i".concat(n)}switch(e){case 2:return"".concat(t2.toBinary()).concat(u2);case 8:return"".concat(t2.toOctal()).concat(u2);case 16:return"".concat(t2.toHexadecimal()).concat(u2);default:throw new Error("Base ".concat(e," not supported "))}}function Rs(t2,e){if("function"==typeof e)return e(t2);if(!t2.isFinite())return t2.isNaN()?"NaN":t2.gt(0)?"Infinity":"-Infinity";var{notation:n,precision:r2,wordSize:i}=Fi(e);switch(n){case"fixed":return function(t2,e){return t2.toFixed(e)}(t2,r2);case"exponential":return wr(t2,r2);case"engineering":return function(t2,e){var n=t2.e,r2=n%3==0?n:n<0?n-3-n%3:n-n%3,i=t2.mul(Math.pow(10,-r2)),u2=i.toPrecision(e);if(u2.includes("e")){u2=new(0,t2.constructor)(u2).toFixed()}return u2+"e"+(n>=0?"+":"")+r2.toString()}(t2,r2);case"bin":return Yn(t2,2,i);case"oct":return Yn(t2,8,i);case"hex":return Yn(t2,16,i);case"auto":var u2=Er(e?.lowerExp,-3),o=Er(e?.upperExp,5);if(t2.isZero())return"0";var f=t2.toSignificantDigits(r2),l=f.e;return(l>=u2&&l<o?f.toFixed():wr(t2,r2)).replace(/((\.\d*?)(0+))($|e)/,function(){var a2=arguments[2],c=arguments[4];return"."!==a2?a2+c:c});default:throw new Error('Unknown notation "'+n+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function wr(t2,e){return void 0!==e?t2.toExponential(e-1):t2.toExponential()}function Er(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():e}function Ot(t2,e){var n=function(t2,e){if("number"==typeof t2)return Un(t2,e);if(Nt(t2))return Rs(t2,e);if(function(t2){return t2&&"object"==typeof t2&&"bigint"==typeof t2.s&&"bigint"==typeof t2.n&&"bigint"==typeof t2.d||!1}(t2))return e&&"decimal"===e.fraction?t2.toString():"".concat(t2.s*t2.n,"/").concat(t2.d);if(Array.isArray(t2))return Ii(t2,e);if(jt(t2))return Ar(t2);if("function"==typeof t2)return t2.syntax?String(t2.syntax):"function";if(t2&&"object"==typeof t2){return"function"==typeof t2.format?t2.format(e):t2&&t2.toString(e)!=={}.toString()?t2.toString(e):"{"+Object.keys(t2).map(r2=>Ar(r2)+": "+Ot(t2[r2],e)).join(", ")+"}"}return String(t2)}(t2,e);return e&&"object"==typeof e&&"truncate"in e&&n.length>e.truncate?n.substring(0,e.truncate-3)+"...":n}function Ar(t2){for(var e=String(t2),n="",r2=0;r2<e.length;){var i=e.charAt(r2);n+=i in Cr?Cr[i]:i,r2++}return'"'+n+'"'}var Cr={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function Ii(t2,e){if(Array.isArray(t2)){for(var n="[",r2=t2.length,i=0;i<r2;i++)0!==i&&(n+=", "),n+=Ii(t2[i],e);return n+="]"}return Ot(t2,e)}function pt(t2,e,n){if(!(this instanceof pt))throw new SyntaxError("Constructor must be called with the new operator");this.actual=t2,this.expected=e,this.relation=n,this.message="Dimension mismatch ("+(Array.isArray(t2)?"["+t2.join(", ")+"]":t2)+" "+(this.relation||"!=")+" "+(Array.isArray(e)?"["+e.join(", ")+"]":e)+")",this.stack=(new Error).stack}function ge(t2,e,n){if(!(this instanceof ge))throw new SyntaxError("Constructor must be called with the new operator");this.index=t2,arguments.length<3?(this.min=0,this.max=e):(this.min=e,this.max=n),void 0!==this.min&&this.index<this.min?this.message="Index out of range ("+this.index+" < "+this.min+")":void 0!==this.max&&this.index>=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=(new Error).stack}function Lt(t2){for(var e=[];Array.isArray(t2);)e.push(t2.length),t2=t2[0];return e}function Oi(t2,e,n){var r2,i=t2.length;if(i!==e[n])throw new pt(i,e[n]);if(n<e.length-1){var u2=n+1;for(r2=0;r2<i;r2++){var o=t2[r2];if(!Array.isArray(o))throw new pt(e.length-1,e.length,"<");Oi(t2[r2],e,u2)}}else for(r2=0;r2<i;r2++)if(Array.isArray(t2[r2]))throw new pt(e.length+1,e.length,">")}function yr(t2,e){if(0===e.length){if(Array.isArray(t2))throw new pt(t2.length,0)}else Oi(t2,e,0)}function gt(t2,e){if(void 0!==t2){if(!lt(t2)||!St(t2))throw new TypeError("Index must be an integer (value: "+t2+")");if(t2<0||"number"==typeof e&&t2>=e)throw new ge(t2,e)}}function Br(t2,e,n){if(!Array.isArray(e))throw new TypeError("Array expected");if(0===e.length)throw new Error("Resizing to scalar is not supported");return e.forEach(function(i){if(!lt(i)||!St(i)||i<0)throw new TypeError("Invalid size, must contain positive integers (size: "+Ot(e)+")")}),(lt(t2)||Nt(t2))&&(t2=[t2]),Wn(t2,e,0,void 0!==n?n:0),t2}function Wn(t2,e,n,r2){var i,u2,o=t2.length,s=e[n],f=Math.min(o,s);if(t2.length=s,n<e.length-1){var l=n+1;for(i=0;i<f;i++)u2=t2[i],Array.isArray(u2)||(u2=[u2],t2[i]=u2),Wn(u2,e,l,r2);for(i=f;i<s;i++)u2=[],t2[i]=u2,Wn(u2,e,l,r2)}else{for(i=0;i<f;i++)for(;Array.isArray(t2[i]);)t2[i]=t2[i][0];for(i=f;i<s;i++)t2[i]=r2}}function Pi(t2,e){var n=function(t2){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Array.isArray(t2))return t2;if("boolean"!=typeof e)throw new TypeError("Boolean expected for second argument of flatten");var n=[];return e?i(t2):r2(t2),n;function r2(u2){for(var o=0;o<u2.length;o++){var s=u2[o];Array.isArray(s)?r2(s):n.push(s)}}function i(u2){if(Array.isArray(u2[0]))for(var o=0;o<u2.length;o++)i(u2[o]);else for(var s=0;s<u2.length;s++)n.push(u2[s])}}(t2,!0),r2=n.length;if(!Array.isArray(t2)||!Array.isArray(e))throw new TypeError("Array expected");if(0===e.length)throw new pt(0,r2,"!=");var i=zi(e=Jn(e,r2));if(r2!==i)throw new pt(i,r2,"!=");try{return function(t2,e){for(var r2,n=t2,i=e.length-1;i>0;i--){var u2=e[i];r2=[];for(var o=n.length/u2,s=0;s<o;s++)r2.push(n.slice(s*u2,(s+1)*u2));n=r2}return n}(n,e)}catch(u2){throw u2 instanceof pt?new pt(i,r2,"!="):u2}}function Jn(t2,e){var n=zi(t2),r2=t2.slice(),u2=t2.indexOf(-1);if(t2.indexOf(-1,u2+1)>=0)throw new Error("More than one wildcard in sizes");if(u2>=0){if(!(e%n===0))throw new Error("Could not replace wildcard, since "+e+" is no multiple of "+-n);r2[u2]=-e/n}return r2}function zi(t2){return t2.reduce((e,n)=>e*n,1)}function Ri(t2,e,n,r2){var i=r2||Lt(t2);if(n)for(var u2=0;u2<n;u2++)t2=[t2],i.unshift(1);for(t2=qi(t2,e,0);i.length<e;)i.push(1);return t2}function qi(t2,e,n){var r2,i;if(Array.isArray(t2)){var u2=n+1;for(r2=0,i=t2.length;r2<i;r2++)t2[r2]=qi(t2[r2],e,u2)}else for(var o=n;o<e;o++)t2=[t2];return t2}function kn(t2,e){for(var n,r2=0,i=0;i<t2.length;i++){var u2=t2[i],o=Array.isArray(u2);if(0===i&&o&&(r2=u2.length),o&&u2.length!==r2)return;var s=o?kn(u2,e):e(u2);if(void 0===n)n=s;else if(n!==s)return"mixed"}return n}function Yi(t2,e,n,r2){if(r2<n){if(t2.length!==e.length)throw new pt(t2.length,e.length);for(var i=[],u2=0;u2<t2.length;u2++)i[u2]=Yi(t2[u2],e[u2],n,r2+1);return i}return t2.concat(e)}function Zs(){var t2=Array.prototype.slice.call(arguments,0,-1),e=Array.prototype.slice.call(arguments,-1);if(1===t2.length)return t2[0];if(t2.length>1)return t2.slice(1).reduce(function(n,r2){return Yi(n,r2,e,0)},t2[0]);throw new Error("Wrong number of arguments in function concat")}function Ui(t2,e){for(var n=e.length,r2=t2.length,i=0;i<r2;i++){var u2=n-r2+i;if(t2[i]<e[u2]&&t2[i]>1||t2[i]>e[u2])throw new Error("shape mismatch: mismatch is found in arg with shape (".concat(t2,") not possible to broadcast dimension ").concat(r2," with size ").concat(t2[i]," to size ").concat(e[u2]))}}function _r(t2,e){var n=Lt(t2);if(Pe(n,e))return t2;Ui(n,e);var r2=function(){for(var t2=arguments.length,e=new Array(t2),n=0;n<t2;n++)e[n]=arguments[n];for(var r2=e.map(D2=>D2.length),i=Math.max(...r2),u2=new Array(i).fill(null),o=0;o<e.length;o++)for(var s=e[o],f=r2[o],l=0;l<f;l++){var a2=i-f+l;s[l]>u2[a2]&&(u2[a2]=s[l])}for(var c=0;c<e.length;c++)Ui(e[c],u2);return u2}(n,e),i=r2.length,u2=[...Array(i-n.length).fill(1),...n],o=function(t2){return fn([],t2)}(t2);n.length<i&&(n=Lt(o=Pi(o,u2)));for(var s=0;s<i;s++)n[s]<r2[s]&&(n=Lt(o=Vs(o,r2[s],s)));return o}function Vs(t2,e,n){return Zs(...Array(e).fill(t2),n)}function Xi(t2,e){if(!Array.isArray(t2))throw new Error("Array expected");var n=Lt(t2);if(e.length!==n.length)throw new pt(e.length,n.length);for(var r2=0;r2<e.length;r2++)gt(e[r2],n[r2]);return e.reduce((i,u2)=>i[u2],t2)}function dn(t2,e,n){var r2=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(Je.isTypedFunction(t2)){var i,s;if(r2)i=1;else{var u2=(e.isMatrix?e.size():Lt(e)).map(()=>0),o=e.isMatrix?e.get(u2):Xi(e,u2);i=function(t2,e,n,r2){for(var i=[e,n,r2],u2=3;u2>0;u2--){var o=i.slice(0,u2);if(null!==Je.resolve(t2,o))return u2}}(t2,o,u2,e)}if(e.isMatrix&&"mixed"!==e.dataType&&void 0!==e.dataType){var f=function(t2,e){var n=[];if(Object.entries(t2.signatures).forEach(r2=>{var[i,u2]=r2;i.split(",").length===e&&n.push(u2)}),1===n.length)return n[0]}(t2,i);s=void 0!==f?f:t2}else s=t2;return i>=1&&i<=3?{isUnary:1===i,fn:function(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return Mr(s,c.slice(0,i),n,t2.name)}}:{isUnary:!1,fn:function(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return Mr(s,c,n,t2.name)}}}return void 0===r2?{isUnary:Gs(t2),fn:t2}:{isUnary:r2,fn:t2}}function Gs(t2){if(1!==t2.length)return!1;var e=t2.toString();if(/arguments/.test(e))return!1;var n=e.match(/\(.*?\)/);return!/\.\.\./.test(n)}function Mr(t2,e,n,r2){try{return t2(...e)}catch(i){!function(t2,e,n,r2){var i;if(t2 instanceof TypeError&&"wrongType"===(null===(i=t2.data)||void 0===i?void 0:i.category)){var u2=[];throw u2.push("value: ".concat(me(e[0]))),e.length>=2&&u2.push("index: ".concat(me(e[1]))),e.length>=3&&u2.push("array: ".concat(me(e[2]))),new TypeError("Function ".concat(n," cannot apply callback arguments ")+"".concat(r2,"(").concat(u2.join(", "),") at index ").concat(JSON.stringify(e[1])))}throw new TypeError("Function ".concat(n," cannot apply callback arguments ")+"to function ".concat(r2,": ").concat(t2.message))}(i,e,n,r2)}}pt.prototype=new RangeError,pt.prototype.constructor=RangeError,pt.prototype.name="DimensionError",pt.prototype.isDimensionError=!0,ge.prototype=new RangeError,ge.prototype.constructor=RangeError,ge.prototype.name="IndexError",ge.prototype.isIndexError=!0;var ea=/* @__PURE__ */Ft("DenseMatrix",["Matrix"],t2=>{var{Matrix:e}=t2;function n(a2,c){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(c&&!jt(c))throw new Error("Invalid datatype: "+c);if(Mt(a2))"DenseMatrix"===a2.type?(this._data=Dt(a2._data),this._size=Dt(a2._size),this._datatype=c||a2._datatype):(this._data=a2.toArray(),this._size=a2.size(),this._datatype=c||a2._datatype);else if(a2&&At(a2.data)&&At(a2.size))this._data=a2.data,this._size=a2.size,yr(this._data,this._size),this._datatype=c||a2.datatype;else if(At(a2))this._data=l(a2),this._size=Lt(this._data),yr(this._data,this._size),this._datatype=c;else{if(a2)throw new TypeError("Unsupported type of data ("+me(a2)+")");this._data=[],this._size=[0],this._datatype=c}}function s(a2,c,D2){if(0===c.length){for(var w=a2._data;At(w);)w=w[0];return w}return a2._size=c.slice(0),a2._data=Br(a2._data,a2._size,D2),a2}function f(a2,c,D2){for(var w=a2._size.slice(0),M=!1;w.length<c.length;)w.push(0),M=!0;for(var h2=0,g=c.length;h2<g;h2++)c[h2]>w[h2]&&(w[h2]=c[h2],M=!0);M&&s(a2,w,D2)}function l(a2){return Mt(a2)?l(a2.valueOf()):At(a2)?a2.map(l):a2}return n.prototype=new e,n.prototype.createDenseMatrix=function(a2,c){return new n(a2,c)},Object.defineProperty(n,"name",{value:"DenseMatrix"}),n.prototype.constructor=n,n.prototype.type="DenseMatrix",n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return kn(this._data,me)},n.prototype.storage=function(){return"dense"},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(a2,c){return new n(a2,c)},n.prototype.subset=function(a2,c,D2){switch(arguments.length){case 1:return function(a2,c){if(!wn(c))throw new TypeError("Invalid index");var D2=c.isScalar();if(D2)return a2.get(c.min());var w=c.size();if(w.length!==a2._size.length)throw new pt(w.length,a2._size.length);for(var M=c.min(),h2=c.max(),g=0,p2=a2._size.length;g<p2;g++)gt(M[g],a2._size[g]),gt(h2[g],a2._size[g]);var E=new n([]),F=function(a2,c){var D2=c.size().length-1,w=Array(D2);return{data:M(a2),size:w};function M(h2){var g=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,p2=c.dimension(g);return w[g]=p2.size()[0],g<D2?p2.map(E=>(gt(E,h2.length),M(h2[E],g+1))).valueOf():p2.map(E=>(gt(E,h2.length),h2[E])).valueOf()}}(a2._data,c);return E._size=F.size,E._datatype=a2._datatype,E._data=F.data,E}(this,a2);case 2:case 3:return function(a2,c,D2,w){if(!c||!0!==c.isIndex)throw new TypeError("Invalid index");var g,M=c.size(),h2=c.isScalar();if(Mt(D2)?(g=D2.size(),D2=D2.valueOf()):g=Lt(D2),h2){if(0!==g.length)throw new TypeError("Scalar expected");a2.set(c.min(),D2,w)}else{if(!Pe(g,M))try{g=Lt(D2=0===g.length?_r([D2],M):_r(D2,M))}catch{}if(M.length<a2._size.length)throw new pt(M.length,a2._size.length,"<");if(g.length<M.length){for(var p2=0,E=0;1===M[p2]&&1===g[p2];)p2++;for(;1===M[p2];)E++,p2++;D2=Ri(D2,M.length,E,g)}if(!Pe(M,g))throw new pt(M,g,">");f(a2,c.max().map(function(A){return A+1}),w),function(a2,c,D2){var w=c.size().length-1;function M(h2,g){var p2=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,E=c.dimension(p2);p2<w?E.forEach((F,A)=>{gt(F,h2.length),M(h2[F],g[A[0]],p2+1)}):E.forEach((F,A)=>{gt(F,h2.length),h2[F]=g[A[0]]})}M(a2,D2)}(a2._data,c,D2)}return a2}(this,a2,c,D2);default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.get=function(a2){return Xi(this._data,a2)},n.prototype.set=function(a2,c,D2){if(!At(a2))throw new TypeError("Array expected");if(a2.length<this._size.length)throw new pt(a2.length,this._size.length,"<");var w,M,h2;f(this,a2.map(function(E){return E+1}),D2);var p2=this._data;for(w=0,M=a2.length-1;w<M;w++)gt(h2=a2[w],p2.length),p2=p2[h2];return gt(h2=a2[a2.length-1],p2.length),p2[h2]=c,this},n.prototype.resize=function(a2,c,D2){if(!He(a2))throw new TypeError("Array or Matrix expected");var w=a2.valueOf().map(h2=>Array.isArray(h2)&&1===h2.length?h2[0]:h2);return s(D2?this.clone():this,w,c)},n.prototype.reshape=function(a2,c){var D2=c?this.clone():this;D2._data=Pi(D2._data,a2);var w=D2._size.reduce((M,h2)=>M*h2);return D2._size=Jn(a2,w),D2},n.prototype.clone=function(){return new n({data:Dt(this._data),size:Dt(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(a2){var c=arguments.length>2&&void 0!==arguments[2]&&arguments[2],D2=this,w=D2._size.length-1;if(w<0)return D2.clone();var M=dn(a2,D2,"map",c),h2=M.fn,g=D2.create(void 0,D2._datatype);if(g._size=D2._size,c||M.isUnary)return g._data=function m(C){var y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,B2=Array(C.length);if(y<w)for(var x=0;x<C.length;x++)B2[x]=m(C[x],y+1);else for(var T=0;T<C.length;T++)B2[T]=h2(C[T]);return B2}(D2._data),g;if(0===w){for(var p2=D2.valueOf(),E=Array(p2.length),F=0;F<p2.length;F++)E[F]=h2(p2[F],[F],D2);return g._data=E,g}var A=[];return g._data=function d2(C){var y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,B2=Array(C.length);if(y<w)for(var x=0;x<C.length;x++)A[y]=x,B2[x]=d2(C[x],y+1);else for(var T=0;T<C.length;T++)A[y]=T,B2[T]=h2(C[T],A.slice(),D2);return B2}(D2._data),g},n.prototype.forEach=function(a2){var c=arguments.length>2&&void 0!==arguments[2]&&arguments[2],D2=this,w=D2._size.length-1;if(!(w<0)){var M=dn(a2,D2,"map",c),h2=M.fn;if(c||M.isUnary)(function F(A){var d2=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(d2<w)for(var m=0;m<A.length;m++)F(A[m],d2+1);else for(var C=0;C<A.length;C++)h2(A[C])})(D2._data);else if(0!==w){var p2=[];!function E(A){var d2=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(d2<w)for(var m=0;m<A.length;m++)p2[d2]=m,E(A[m],d2+1);else for(var C=0;C<A.length;C++)p2[d2]=C,h2(A[C],p2.slice(),D2)}(D2._data)}else for(var g=0;g<D2._data.length;g++)h2(D2._data[g],[g],D2)}},n.prototype[Symbol.iterator]=function*(){var a2=this._size.length-1;if(!(a2<0)){if(0===a2){for(var c=0;c<this._data.length;c++)yield{value:this._data[c],index:[c]};return}var D2=[],w=function*(h2,g){if(g<a2)for(var p2=0;p2<h2.length;p2++)D2[g]=p2,yield*w(h2[p2],g+1);else for(var E=0;E<h2.length;E++)D2[g]=E,yield{value:h2[E],index:D2.slice()}};yield*w(this._data,0)}},n.prototype.rows=function(){var a2=[];if(2!==this.size().length)throw new TypeError("Rows can only be returned for a 2D matrix.");var D2=this._data;for(var w of D2)a2.push(new n([w],this._datatype));return a2},n.prototype.columns=function(){var a2=this,c=[],D2=this.size();if(2!==D2.length)throw new TypeError("Rows can only be returned for a 2D matrix.");for(var w=this._data,M=function(p2){var E=w.map(F=>[F[p2]]);c.push(new n(E,a2._datatype))},h2=0;h2<D2[1];h2++)M(h2);return c},n.prototype.toArray=function(){return Dt(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(a2){return Ot(this._data,a2)},n.prototype.toString=function(){return Ot(this._data)},n.prototype.toJSON=function(){return{mathjs:"DenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(a2){if(a2){if(Nt(a2)&&(a2=a2.toNumber()),!lt(a2)||!St(a2))throw new TypeError("The parameter k must be an integer number")}else a2=0;for(var c=a2>0?a2:0,D2=a2<0?-a2:0,w=this._size[0],M=this._size[1],h2=Math.min(w-D2,M-c),g=[],p2=0;p2<h2;p2++)g[p2]=this._data[p2+D2][p2+c];return new n({data:g,size:[h2],datatype:this._datatype})},n.diagonal=function(a2,c,D2,w){if(!At(a2))throw new TypeError("Array expected, size parameter");if(2!==a2.length)throw new Error("Only two dimensions matrix are supported");if(a2=a2.map(function(C){if(Nt(C)&&(C=C.toNumber()),!lt(C)||!St(C)||C<1)throw new Error("Size values must be positive integers");return C}),D2){if(Nt(D2)&&(D2=D2.toNumber()),!lt(D2)||!St(D2))throw new TypeError("The parameter k must be an integer number")}else D2=0;var F,M=D2>0?D2:0,h2=D2<0?-D2:0,g=a2[0],p2=a2[1],E=Math.min(g-h2,p2-M);if(At(c)){if(c.length!==E)throw new Error("Invalid value array length");F=function(y){return c[y]}}else if(Mt(c)){var A=c.size();if(1!==A.length||A[0]!==E)throw new Error("Invalid matrix length");F=function(y){return c.get([y])}}else F=function(){return c};w||(w=Nt(F(0))?F(0).mul(0):0);var d2=[];if(a2.length>0){d2=Br(d2,a2,w);for(var m=0;m<E;m++)d2[m+h2][m+M]=F(m)}return new n({data:d2,size:[g,p2]})},n.fromJSON=function(a2){return new n(a2)},n.prototype.swapRows=function(a2,c){if(!(lt(a2)&&St(a2)&<(c)&&St(c)))throw new Error("Row index must be positive integers");if(2!==this._size.length)throw new Error("Only two dimensional matrix is supported");return gt(a2,this._size[0]),gt(c,this._size[0]),n._swapRows(a2,c,this._data),this},n._swapRows=function(a2,c,D2){var w=D2[a2];D2[a2]=D2[c],D2[c]=w},n},{isClass:!0});function na(t2,e,n){return Mt(t2)?t2.map(r2=>e(r2),!1,!0):function(t2,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(0===t2.length)return[];if(n)return function u2(o){if(Array.isArray(o)){for(var s=o.length,f=Array(s),l=0;l<s;l++)f[l]=u2(o[l]);return f}return e(o)}(t2);var r2=[];return function i(o,s){if(Array.isArray(o)){for(var f=o.length,l=Array(f),a2=0;a2<f;a2++)r2[s]=a2,l[a2]=i(o[a2],s+1);return l}return e(o,r2.slice(0,s),t2)}(t2,0)}(t2,e,!0)}var $i="number, number";function Li(t2,e){return t2+e}function Zi(t2,e){return t2*e}Li.signature=$i,Zi.signature=$i;var ua=/* @__PURE__ */Ft("compareUnits",["typed"],t2=>{var{typed:e}=t2;return{"Unit, Unit":e.referToSelf(n=>(r2,i)=>{if(!r2.equalBase(i))throw new Error("Cannot compare units with different base");return e.find(n,[r2.valueType(),i.valueType()])(r2.value,i.value)})}}),mn="equalScalar",sa=/* @__PURE__ */Ft(mn,["typed","config"],t2=>{var{typed:e,config:n}=t2,r2=ua({typed:e});return e(mn,{"boolean, boolean":function(u2,o){return u2===o},"number, number":function(u2,o){return ln(u2,o,n.relTol,n.absTol)},"BigNumber, BigNumber":function(u2,o){return u2.eq(o)||function(t2,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e-9,r2=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n<=0)throw new Error("Relative tolerance must be greater than 0");if(r2<0)throw new Error("Absolute tolerance must be at least 0");return!t2.isNaN()&&!e.isNaN()&&(t2.isFinite()&&e.isFinite()?!!t2.eq(e)||t2.minus(e).abs().lte(t2.constructor.max(t2.constructor.max(t2.abs(),e.abs()).mul(n),r2)):t2.eq(e))}(u2,o,n.relTol,n.absTol)},"bigint, bigint":function(u2,o){return u2===o},"Fraction, Fraction":function(u2,o){return u2.equals(o)},"Complex, Complex":function(u2,o){return function(t2,e,n,r2){return ln(t2.re,e.re,n,r2)&&ln(t2.im,e.im,n,r2)}(u2,o,n.relTol,n.absTol)}},r2)});Ft(mn,["typed","config"],t2=>{var{typed:e,config:n}=t2;return e(mn,{"number, number":function(i,u2){return ln(i,u2,n.relTol,n.absTol)}})});var ca=/* @__PURE__ */Ft("SparseMatrix",["typed","equalScalar","Matrix"],t2=>{var{typed:e,equalScalar:n,Matrix:r2}=t2;function i(h2,g){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if(g&&!jt(g))throw new Error("Invalid datatype: "+g);if(Mt(h2))!function(h2,g,p2){"SparseMatrix"===g.type?(h2._values=g._values?Dt(g._values):void 0,h2._index=Dt(g._index),h2._ptr=Dt(g._ptr),h2._size=Dt(g._size),h2._datatype=p2||g._datatype):o(h2,g.valueOf(),p2||g._datatype)}(this,h2,g);else if(h2&&At(h2.index)&&At(h2.ptr)&&At(h2.size))this._values=h2.values,this._index=h2.index,this._ptr=h2.ptr,this._size=h2.size,this._datatype=g||h2.datatype;else if(At(h2))o(this,h2,g);else{if(h2)throw new TypeError("Unsupported type of data ("+me(h2)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=g}}function o(h2,g,p2){h2._values=[],h2._index=[],h2._ptr=[],h2._datatype=p2;var E=g.length,F=0,A=n,d2=0;if(jt(p2)&&(A=e.find(n,[p2,p2])||n,d2=e.convert(0,p2)),E>0){var m=0;do{h2._ptr.push(h2._index.length);for(var C=0;C<E;C++){var y=g[C];if(At(y)){if(0===m&&F<y.length&&(F=y.length),m<y.length){var B2=y[m];A(B2,d2)||(h2._values.push(B2),h2._index.push(C))}}else 0===m&&F<1&&(F=1),A(y,d2)||(h2._values.push(y),h2._index.push(C))}m++}while(m<F)}h2._ptr.push(h2._index.length),h2._size=[E,F]}function l(h2,g,p2,E){if(p2-g===0)return p2;for(var F=g;F<p2;F++)if(E[F]===h2)return F;return g}function c(h2,g,p2,E,F,A,d2){F.splice(h2,0,E),A.splice(h2,0,g);for(var m=p2+1;m<d2.length;m++)d2[m]++}function D2(h2,g,p2,E){var F=E||0,A=n,d2=0;jt(h2._datatype)&&(A=e.find(n,[h2._datatype,h2._datatype])||n,d2=e.convert(0,h2._datatype),F=e.convert(F,h2._datatype));var B2,x,T,m=!A(F,d2),C=h2._size[0],y=h2._size[1];if(p2>y){for(x=y;x<p2;x++)if(h2._ptr[x]=h2._values.length,m)for(B2=0;B2<C;B2++)h2._values.push(F),h2._index.push(B2);h2._ptr[p2]=h2._values.length}else p2<y&&(h2._ptr.splice(p2+1,y-p2),h2._values.splice(h2._ptr[p2],h2._values.length),h2._index.splice(h2._ptr[p2],h2._index.length));if(y=p2,g>C){if(m){var q=0;for(x=0;x<y;x++){h2._ptr[x]=h2._ptr[x]+q,T=h2._ptr[x+1]+q;var Z=0;for(B2=C;B2<g;B2++,Z++)h2._values.splice(T+Z,0,F),h2._index.splice(T+Z,0,B2),q++}h2._ptr[y]=h2._values.length}}else if(g<C){var W=0;for(x=0;x<y;x++){h2._ptr[x]=h2._ptr[x]-W;var L=h2._ptr[x],z=h2._ptr[x+1]-W;for(T=L;T<z;T++)(B2=h2._index[T])>g-1&&(h2._values.splice(T,1),h2._index.splice(T,1),W++)}h2._ptr[x]=h2._values.length}return h2._size[0]=g,h2._size[1]=p2,h2}function M(h2,g,p2,E,F){var C,y,A=E[0],d2=E[1],m=[];for(C=0;C<A;C++)for(m[C]=[],y=0;y<d2;y++)m[C][y]=0;for(y=0;y<d2;y++)for(var B2=p2[y],x=p2[y+1],T=B2;T<x;T++)m[C=g[T]][y]=h2?F?Dt(h2[T]):h2[T]:1;return m}return i.prototype=new r2,i.prototype.createSparseMatrix=function(h2,g){return new i(h2,g)},Object.defineProperty(i,"name",{value:"SparseMatrix"}),i.prototype.constructor=i,i.prototype.type="SparseMatrix",i.prototype.isSparseMatrix=!0,i.prototype.getDataType=function(){return kn(this._values,me)},i.prototype.storage=function(){return"sparse"},i.prototype.datatype=function(){return this._datatype},i.prototype.create=function(h2,g){return new i(h2,g)},i.prototype.density=function(){var h2=this._size[0],g=this._size[1];return 0!==h2&&0!==g?this._index.length/(h2*g):0},i.prototype.subset=function(h2,g,p2){if(!this._values)throw new Error("Cannot invoke subset on a Pattern only matrix");switch(arguments.length){case 1:return function(h2,g){if(!wn(g))throw new TypeError("Invalid index");var p2=g.isScalar();if(p2)return h2.get(g.min());var E=g.size();if(E.length!==h2._size.length)throw new pt(E.length,h2._size.length);var F,A,d2,m,C=g.min(),y=g.max();for(F=0,A=h2._size.length;F<A;F++)gt(C[F],h2._size[F]),gt(y[F],h2._size[F]);var B2=h2._values,x=h2._index,T=h2._ptr,q=g.dimension(0),Z=g.dimension(1),W=[],L=[];q.forEach(function(G,j){L[G]=j[0],W[G]=!0});var z=B2?[]:void 0,J=[],k=[];return Z.forEach(function(G){for(k.push(J.length),d2=T[G],m=T[G+1];d2<m;d2++)F=x[d2],!0===W[F]&&(J.push(L[F]),z&&z.push(B2[d2]))}),k.push(J.length),new i({values:z,index:J,ptr:k,size:E,datatype:h2._datatype})}(this,h2);case 2:case 3:return function(h2,g,p2,E){if(!g||!0!==g.isIndex)throw new TypeError("Invalid index");var d2,F=g.size(),A=g.isScalar();if(Mt(p2)?(d2=p2.size(),p2=p2.toArray()):d2=Lt(p2),A){if(0!==d2.length)throw new TypeError("Scalar expected");h2.set(g.min(),p2,E)}else{if(1!==F.length&&2!==F.length)throw new pt(F.length,h2._size.length,"<");if(d2.length<F.length){for(var m=0,C=0;1===F[m]&&1===d2[m];)m++;for(;1===F[m];)C++,m++;p2=Ri(p2,F.length,C,d2)}if(!Pe(F,d2))throw new pt(F,d2,">");if(1===F.length){g.dimension(0).forEach(function(T,q){gt(T),h2.set([T,0],p2[q[0]],E)})}else{var B2=g.dimension(0),x=g.dimension(1);B2.forEach(function(T,q){gt(T),x.forEach(function(Z,W){gt(Z),h2.set([T,Z],p2[q[0]][W[0]],E)})})}}return h2}(this,h2,g,p2);default:throw new SyntaxError("Wrong number of arguments")}},i.prototype.get=function(h2){if(!At(h2))throw new TypeError("Array expected");if(h2.length!==this._size.length)throw new pt(h2.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var g=h2[0],p2=h2[1];gt(g,this._size[0]),gt(p2,this._size[1]);var E=l(g,this._ptr[p2],this._ptr[p2+1],this._index);return E<this._ptr[p2+1]&&this._index[E]===g?this._values[E]:0},i.prototype.set=function(h2,g,p2){if(!At(h2))throw new TypeError("Array expected");if(h2.length!==this._size.length)throw new pt(h2.length,this._size.length);if(!this._values)throw new Error("Cannot invoke set on a Pattern only matrix");var E=h2[0],F=h2[1],A=this._size[0],d2=this._size[1],m=n,C=0;jt(this._datatype)&&(m=e.find(n,[this._datatype,this._datatype])||n,C=e.convert(0,this._datatype)),(E>A-1||F>d2-1)&&(D2(this,Math.max(E+1,A),Math.max(F+1,d2),p2),A=this._size[0],d2=this._size[1]),gt(E,A),gt(F,d2);var y=l(E,this._ptr[F],this._ptr[F+1],this._index);return y<this._ptr[F+1]&&this._index[y]===E?m(g,C)?function(h2,g,p2,E,F){p2.splice(h2,1),E.splice(h2,1);for(var A=g+1;A<F.length;A++)F[A]--}(y,F,this._values,this._index,this._ptr):this._values[y]=g:m(g,C)||c(y,E,F,g,this._values,this._index,this._ptr),this},i.prototype.resize=function(h2,g,p2){if(!He(h2))throw new TypeError("Array or Matrix expected");var E=h2.valueOf().map(A=>Array.isArray(A)&&1===A.length?A[0]:A);if(2!==E.length)throw new Error("Only two dimensions matrix are supported");return E.forEach(function(A){if(!lt(A)||!St(A)||A<0)throw new TypeError("Invalid size, must contain positive integers (size: "+Ot(E)+")")}),D2(p2?this.clone():this,E[0],E[1],g)},i.prototype.reshape=function(h2,g){if(!At(h2))throw new TypeError("Array expected");if(2!==h2.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");h2.forEach(function(G){if(!lt(G)||!St(G)||G<=-2||0===G)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+Ot(h2)+")")});var p2=this._size[0]*this._size[1];if(p2!==(h2=Jn(h2,p2))[0]*h2[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var F=g?this.clone():this;if(this._size[0]===h2[0]&&this._size[1]===h2[1])return F;for(var A=[],d2=0;d2<F._ptr.length;d2++)for(var m=0;m<F._ptr[d2+1]-F._ptr[d2];m++)A.push(d2);for(var C=F._values.slice(),y=F._index.slice(),B2=0;B2<F._index.length;B2++){var x=y[B2],T=A[B2],q=x*F._size[1]+T;A[B2]=q%h2[1],y[B2]=Math.floor(q/h2[1])}F._values.length=0,F._index.length=0,F._ptr.length=h2[1]+1,F._size=h2.slice();for(var Z=0;Z<F._ptr.length;Z++)F._ptr[Z]=0;for(var W=0;W<C.length;W++){var L=y[W],z=A[W],J=C[W];c(l(L,F._ptr[z],F._ptr[z+1],F._index),L,z,J,F._values,F._index,F._ptr)}return F},i.prototype.clone=function(){return new i({values:this._values?Dt(this._values):void 0,index:Dt(this._index),ptr:Dt(this._ptr),size:Dt(this._size),datatype:this._datatype})},i.prototype.size=function(){return this._size.slice(0)},i.prototype.map=function(h2,g){if(!this._values)throw new Error("Cannot invoke map on a Pattern only matrix");var p2=this,E=this._size[0],F=this._size[1],A=dn(h2,p2,"map");return function(h2,g,p2,E,F,A,d2){var m=[],C=[],y=[],B2=n,x=0;jt(h2._datatype)&&(B2=e.find(n,[h2._datatype,h2._datatype])||n,x=e.convert(0,h2._datatype));for(var T=function(ot,wt,vt){var mt=A(ot,wt,vt);B2(mt,x)||(m.push(mt),C.push(wt))},q=E;q<=F;q++){y.push(m.length);var Z=h2._ptr[q],W=h2._ptr[q+1];if(d2)for(var L=Z;L<W;L++){var z=h2._index[L];z>=g&&z<=p2&&T(h2._values[L],z-g,q-E)}else{for(var J={},k=Z;k<W;k++){J[h2._index[k]]=h2._values[k]}for(var j=g;j<=p2;j++){T(j in J?J[j]:0,j-g,q-E)}}}return y.push(m.length),new i({values:m,index:C,ptr:y,size:[p2-g+1,F-E+1]})}(this,0,E-1,0,F-1,function(C,y,B2){return A.fn(C,[y,B2],p2)},g)},i.prototype.forEach=function(h2,g){if(!this._values)throw new Error("Cannot invoke forEach on a Pattern only matrix");for(var E=this._size[0],F=this._size[1],A=dn(h2,this,"forEach"),d2=0;d2<F;d2++){var m=this._ptr[d2],C=this._ptr[d2+1];if(g)for(var y=m;y<C;y++){var B2=this._index[y];A.fn(this._values[y],[B2,d2],this)}else{for(var x={},T=m;T<C;T++){x[this._index[T]]=this._values[T]}for(var Z=0;Z<E;Z++){var W=Z in x?x[Z]:0;A.fn(W,[Z,d2],this)}}}},i.prototype[Symbol.iterator]=function*(){if(!this._values)throw new Error("Cannot iterate a Pattern only matrix");for(var h2=this._size[1],g=0;g<h2;g++)for(var p2=this._ptr[g],E=this._ptr[g+1],F=p2;F<E;F++){var A=this._index[F];yield{value:this._values[F],index:[A,g]}}},i.prototype.toArray=function(){return M(this._values,this._index,this._ptr,this._size,!0)},i.prototype.valueOf=function(){return M(this._values,this._index,this._ptr,this._size,!1)},i.prototype.format=function(h2){for(var g=this._size[0],p2=this._size[1],E=this.density(),F="Sparse Matrix ["+Ot(g,h2)+" x "+Ot(p2,h2)+"] density: "+Ot(E,h2)+"\n",A=0;A<p2;A++)for(var d2=this._ptr[A],m=this._ptr[A+1],C=d2;C<m;C++){F+="\n ("+Ot(this._index[C],h2)+", "+Ot(A,h2)+") ==> "+(this._values?Ot(this._values[C],h2):"X")}return F},i.prototype.toString=function(){return Ot(this.toArray())},i.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},i.prototype.diagonal=function(h2){if(h2){if(Nt(h2)&&(h2=h2.toNumber()),!lt(h2)||!St(h2))throw new TypeError("The parameter k must be an integer number")}else h2=0;var g=h2>0?h2:0,p2=h2<0?-h2:0,E=this._size[0],F=this._size[1],A=Math.min(E-p2,F-g),d2=[],m=[],C=[];C[0]=0;for(var y=g;y<F&&d2.length<A;y++)for(var B2=this._ptr[y],x=this._ptr[y+1],T=B2;T<x;T++){var q=this._index[T];if(q===y-g+p2){d2.push(this._values[T]),m[d2.length-1]=q-p2;break}}return C.push(d2.length),new i({values:d2,index:m,ptr:C,size:[A,1]})},i.fromJSON=function(h2){return new i(h2)},i.diagonal=function(h2,g,p2,E,F){if(!At(h2))throw new TypeError("Array expected, size parameter");if(2!==h2.length)throw new Error("Only two dimensions matrix are supported");if(h2=h2.map(function(G){if(Nt(G)&&(G=G.toNumber()),!lt(G)||!St(G)||G<1)throw new Error("Size values must be positive integers");return G}),p2){if(Nt(p2)&&(p2=p2.toNumber()),!lt(p2)||!St(p2))throw new TypeError("The parameter k must be an integer number")}else p2=0;var A=n,d2=0;jt(F)&&(A=e.find(n,[F,F])||n,d2=e.convert(0,F));var T,m=p2>0?p2:0,C=p2<0?-p2:0,y=h2[0],B2=h2[1],x=Math.min(y-C,B2-m);if(At(g)){if(g.length!==x)throw new Error("Invalid value array length");T=function(j){return g[j]}}else if(Mt(g)){var q=g.size();if(1!==q.length||q[0]!==x)throw new Error("Invalid matrix length");T=function(j){return g.get([j])}}else T=function(){return g};for(var Z=[],W=[],L=[],z=0;z<B2;z++){L.push(Z.length);var J=z-m;if(J>=0&&J<x){var k=T(J);A(k,d2)||(W.push(J+C),Z.push(k))}}return L.push(Z.length),new i({values:Z,index:W,ptr:L,size:[y,B2]})},i.prototype.swapRows=function(h2,g){if(!(lt(h2)&&St(h2)&<(g)&&St(g)))throw new Error("Row index must be positive integers");if(2!==this._size.length)throw new Error("Only two dimensional matrix is supported");return gt(h2,this._size[0]),gt(g,this._size[0]),i._swapRows(h2,g,this._size[1],this._values,this._index,this._ptr),this},i._forEachRow=function(h2,g,p2,E,F){for(var A=E[h2],d2=E[h2+1],m=A;m<d2;m++)F(p2[m],g[m])},i._swapRows=function(h2,g,p2,E,F,A){for(var d2=0;d2<p2;d2++){var m=A[d2],C=A[d2+1],y=l(h2,m,C,F),B2=l(g,m,C,F);if(y<C&&B2<C&&F[y]===h2&&F[B2]===g){if(E){var x=E[y];E[y]=E[B2],E[B2]=x}}else if(y<C&&F[y]===h2&&(B2>=C||F[B2]!==g)){var T=E?E[y]:void 0;F.splice(B2,0,g),E&&E.splice(B2,0,T),F.splice(B2<=y?y+1:y,1),E&&E.splice(B2<=y?y+1:y,1)}else if(B2<C&&F[B2]===g&&(y>=C||F[y]!==h2)){var q=E?E[B2]:void 0;F.splice(y,0,h2),E&&E.splice(y,0,q),F.splice(y<=B2?B2+1:B2,1),E&&E.splice(y<=B2?B2+1:B2,1)}}},i},{isClass:!0}),ha=/* @__PURE__ */Ft("matrix",["typed","Matrix","DenseMatrix","SparseMatrix"],t2=>{var{typed:e,Matrix:n,DenseMatrix:r2,SparseMatrix:i}=t2;return e("matrix",{"":function(){return u2([])},string:function(s){return u2([],s)},"string, string":function(s,f){return u2([],s,f)},Array:function(s){return u2(s)},Matrix:function(s){return u2(s,s.storage())},"Array | Matrix, string":u2,"Array | Matrix, string, string":u2});function u2(o,s,f){if("dense"===s||"default"===s||void 0===s)return new r2(o,f);if("sparse"===s)return new i(o,f);throw new TypeError("Unknown matrix type "+JSON.stringify(s)+".")}}),xr="addScalar",pa=/* @__PURE__ */Ft(xr,["typed"],t2=>{var{typed:e}=t2;return e(xr,{"number, number":Li,"Complex, Complex":function(r2,i){return r2.add(i)},"BigNumber, BigNumber":function(r2,i){return r2.plus(i)},"bigint, bigint":function(r2,i){return r2+i},"Fraction, Fraction":function(r2,i){return r2.add(i)},"Unit, Unit":e.referToSelf(n=>(r2,i)=>{if(null===r2.value||void 0===r2.value)throw new Error("Parameter x contains a unit with undefined value");if(null===i.value||void 0===i.value)throw new Error("Parameter y contains a unit with undefined value");if(!r2.equalBase(i))throw new Error("Units do not match");var u2=r2.clone();return u2.value=e.find(n,[u2.valueType(),i.valueType()])(u2.value,i.value),u2.fixPrefix=!1,u2})})}),ga=/* @__PURE__ */Ft("matAlgo11xS0s",["typed","equalScalar"],t2=>{var{typed:e,equalScalar:n}=t2;return function(i,u2,o,s){var f=i._values,l=i._index,a2=i._ptr,c=i._size,D2=i._datatype;if(!f)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h2,w=c[0],M=c[1],g=n,p2=0,E=o;"string"==typeof D2&&(h2=D2,g=e.find(n,[h2,h2]),p2=e.convert(0,h2),u2=e.convert(u2,h2),E=e.find(o,[h2,h2]));for(var F=[],A=[],d2=[],m=0;m<M;m++){d2[m]=A.length;for(var C=a2[m],y=a2[m+1],B2=C;B2<y;B2++){var x=l[B2],T=s?E(u2,f[B2]):E(f[B2],u2);g(T,p2)||(A.push(x),F.push(T))}}return d2[M]=A.length,i.createSparseMatrix({values:F,index:A,ptr:d2,size:[w,M],datatype:h2})}}),wa=/* @__PURE__ */Ft("matAlgo14xDs",["typed"],t2=>{var{typed:e}=t2;return function(i,u2,o,s){var c,f=i._data,l=i._size,a2=i._datatype,D2=o;"string"==typeof a2&&(c=a2,u2=e.convert(u2,c),D2=e.find(o,[c,c]));var w=l.length>0?n(D2,0,l,l[0],f,u2,s):[];return i.createDenseMatrix({data:w,size:Dt(l),datatype:c})};function n(r2,i,u2,o,s,f,l){var a2=[];if(i===u2.length-1)for(var c=0;c<o;c++)a2[c]=l?r2(f,s[c]):r2(s[c],f);else for(var D2=0;D2<o;D2++)a2[D2]=n(r2,i+1,u2,u2[i+1],s[D2],f,l);return a2}});function ve(t2,e,n,r2){if(!(this instanceof ve))throw new SyntaxError("Constructor must be called with the new operator");this.fn=t2,this.count=e,this.min=n,this.max=r2,this.message="Wrong number of arguments in function "+t2+" ("+e+" provided, "+n+(null!=r2?"-"+r2:"")+" expected)",this.stack=(new Error).stack}ve.prototype=new Error,ve.prototype.constructor=Error,ve.prototype.name="ArgumentsError",ve.prototype.isArgumentsError=!0;var Ca=/* @__PURE__ */Ft("multiplyScalar",["typed"],t2=>{var{typed:e}=t2;return e("multiplyScalar",{"number, number":Zi,"Complex, Complex":function(r2,i){return r2.mul(i)},"BigNumber, BigNumber":function(r2,i){return r2.times(i)},"bigint, bigint":function(r2,i){return r2*i},"Fraction, Fraction":function(r2,i){return r2.mul(i)},"number | Fraction | BigNumber | Complex, Unit":(n,r2)=>r2.multiply(n),"Unit, number | Fraction | BigNumber | Complex | Unit":(n,r2)=>n.multiply(r2)})}),Sr="multiply",Ba=/* @__PURE__ */Ft(Sr,["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],t2=>{var{typed:e,matrix:n,addScalar:r2,multiplyScalar:i,equalScalar:u2,dot:o}=t2,s=ga({typed:e,equalScalar:u2}),f=wa({typed:e});function l(d2,m){switch(d2.length){case 1:switch(m.length){case 1:if(d2[0]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(d2[0]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+d2[0]+") must match Matrix rows ("+m[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+m.length+" dimensions)")}break;case 2:switch(m.length){case 1:if(d2[1]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+d2[1]+") must match Vector length ("+m[0]+")");break;case 2:if(d2[1]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+d2[1]+") must match Matrix B rows ("+m[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+m.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+d2.length+" dimensions)")}}function c(d2,m){if("dense"!==m.storage())throw new Error("Support for SparseMatrix not implemented");return function(d2,m){var L,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._size,q=m._datatype||m.getDataType(),Z=y[0],W=T[1],z=r2,J=i;B2&&q&&B2===q&&"string"==typeof B2&&"mixed"!==B2&&(L=B2,z=e.find(r2,[L,L]),J=e.find(i,[L,L]));for(var k=[],G=0;G<W;G++){for(var j=J(C[0],x[0][G]),rt=1;rt<Z;rt++)j=z(j,J(C[rt],x[rt][G]));k[G]=j}return d2.createDenseMatrix({data:k,size:[W],datatype:B2===d2._datatype&&q===m._datatype?L:void 0})}(d2,m)}var w=e("_multiplyMatrixVector",{"DenseMatrix, any":function(d2,m){var W,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._datatype||m.getDataType(),q=y[0],Z=y[1],L=r2,z=i;B2&&T&&B2===T&&"string"==typeof B2&&"mixed"!==B2&&(W=B2,L=e.find(r2,[W,W]),z=e.find(i,[W,W]));for(var J=[],k=0;k<q;k++){for(var G=C[k],j=z(G[0],x[0]),rt=1;rt<Z;rt++)j=L(j,z(G[rt],x[rt]));J[k]=j}return d2.createDenseMatrix({data:J,size:[q],datatype:B2===d2._datatype&&T===m._datatype?W:void 0})},"SparseMatrix, any":function(d2,m){var C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType();if(!C)throw new Error("Cannot multiply Pattern only Matrix times Dense Matrix");var k,T=m._data,q=m._datatype||m.getDataType(),Z=d2._size[0],W=m._size[0],L=[],z=[],J=[],G=r2,j=i,rt=u2,et=0;x&&q&&x===q&&"string"==typeof x&&"mixed"!==x&&(k=x,G=e.find(r2,[k,k]),j=e.find(i,[k,k]),rt=e.find(u2,[k,k]),et=e.convert(0,k));var ot=[],wt=[];J[0]=0;for(var vt=0;vt<W;vt++){var mt=T[vt];if(!rt(mt,et))for(var ht=B2[vt],zt=B2[vt+1],st=ht;st<zt;st++){var it=y[st];wt[it]?ot[it]=G(ot[it],j(mt,C[st])):(wt[it]=!0,z.push(it),ot[it]=j(mt,C[st]))}}for(var Zt=z.length,xt=0;xt<Zt;xt++){var at=z[xt];L[xt]=ot[at]}return J[1]=z.length,d2.createSparseMatrix({values:L,index:z,ptr:J,size:[Z,1],datatype:x===d2._datatype&&q===m._datatype?k:void 0})}}),M=e("_multiplyMatrixMatrix",{"DenseMatrix, DenseMatrix":function(d2,m){var z,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._size,q=m._datatype||m.getDataType(),Z=y[0],W=y[1],L=T[1],J=r2,k=i;B2&&q&&B2===q&&"string"==typeof B2&&"mixed"!==B2&&"mixed"!==B2&&(z=B2,J=e.find(r2,[z,z]),k=e.find(i,[z,z]));for(var G=[],j=0;j<Z;j++){var rt=C[j];G[j]=[];for(var et=0;et<L;et++){for(var ot=k(rt[0],x[0][et]),wt=1;wt<W;wt++)ot=J(ot,k(rt[wt],x[wt][et]));G[j][et]=ot}}return d2.createDenseMatrix({data:G,size:[Z,L],datatype:B2===d2._datatype&&q===m._datatype?z:void 0})},"DenseMatrix, SparseMatrix":function(d2,m){var C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._values,T=m._index,q=m._ptr,Z=m._size,W=m._datatype||void 0===m._data?m._datatype:m.getDataType();if(!x)throw new Error("Cannot multiply Dense Matrix times Pattern only Matrix");var J,L=y[0],z=Z[1],k=r2,G=i,j=u2,rt=0;B2&&W&&B2===W&&"string"==typeof B2&&"mixed"!==B2&&(J=B2,k=e.find(r2,[J,J]),G=e.find(i,[J,J]),j=e.find(u2,[J,J]),rt=e.convert(0,J));for(var et=[],ot=[],wt=[],vt=m.createSparseMatrix({values:et,index:ot,ptr:wt,size:[L,z],datatype:B2===d2._datatype&&W===m._datatype?J:void 0}),mt=0;mt<z;mt++){wt[mt]=ot.length;var ht=q[mt],zt=q[mt+1];if(zt>ht)for(var st=0,it=0;it<L;it++){for(var Zt=it+1,xt=void 0,at=ht;at<zt;at++){var yt=T[at];st!==Zt?(xt=G(C[it][yt],x[at]),st=Zt):xt=k(xt,G(C[it][yt],x[at]))}st===Zt&&!j(xt,rt)&&(ot.push(it),et.push(xt))}}return wt[z]=ot.length,vt},"SparseMatrix, DenseMatrix":function(d2,m){var C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType();if(!C)throw new Error("Cannot multiply Pattern only Matrix times Dense Matrix");var z,T=m._data,q=m._datatype||m.getDataType(),Z=d2._size[0],W=m._size[0],L=m._size[1],J=r2,k=i,G=u2,j=0;x&&q&&x===q&&"string"==typeof x&&"mixed"!==x&&(z=x,J=e.find(r2,[z,z]),k=e.find(i,[z,z]),G=e.find(u2,[z,z]),j=e.convert(0,z));for(var rt=[],et=[],ot=[],wt=d2.createSparseMatrix({values:rt,index:et,ptr:ot,size:[Z,L],datatype:x===d2._datatype&&q===m._datatype?z:void 0}),vt=[],mt=[],ht=0;ht<L;ht++){ot[ht]=et.length;for(var zt=ht+1,st=0;st<W;st++){var it=T[st][ht];if(!G(it,j))for(var Zt=B2[st],xt=B2[st+1],at=Zt;at<xt;at++){var yt=y[at];mt[yt]!==zt?(mt[yt]=zt,et.push(yt),vt[yt]=k(it,C[at])):vt[yt]=J(vt[yt],k(it,C[at]))}}for(var Wt=ot[ht],ie=et.length,ue=Wt;ue<ie;ue++){var Fe=et[ue];rt[ue]=vt[Fe]}}return ot[L]=et.length,wt},"SparseMatrix, SparseMatrix":function(d2,m){var k,C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType(),T=m._values,q=m._index,Z=m._ptr,W=m._datatype||void 0===m._data?m._datatype:m.getDataType(),L=d2._size[0],z=m._size[1],J=C&&T,G=r2,j=i;x&&W&&x===W&&"string"==typeof x&&"mixed"!==x&&(k=x,G=e.find(r2,[k,k]),j=e.find(i,[k,k]));for(var ht,zt,st,it,Zt,xt,at,yt,rt=J?[]:void 0,et=[],ot=[],wt=d2.createSparseMatrix({values:rt,index:et,ptr:ot,size:[L,z],datatype:x===d2._datatype&&W===m._datatype?k:void 0}),vt=J?[]:void 0,mt=[],Wt=0;Wt<z;Wt++){ot[Wt]=et.length;var ie=Wt+1;for(Zt=Z[Wt],xt=Z[Wt+1],it=Zt;it<xt;it++)if(yt=q[it],J)for(zt=B2[yt],st=B2[yt+1],ht=zt;ht<st;ht++)mt[at=y[ht]]!==ie?(mt[at]=ie,et.push(at),vt[at]=j(T[it],C[ht])):vt[at]=G(vt[at],j(T[it],C[ht]));else for(zt=B2[yt],st=B2[yt+1],ht=zt;ht<st;ht++)mt[at=y[ht]]!==ie&&(mt[at]=ie,et.push(at));if(J)for(var ue=ot[Wt],Fe=et.length,we=ue;we<Fe;we++){var Mn=et[we];rt[we]=vt[Mn]}}return ot[z]=et.length,wt}});return e(Sr,i,{"Array, Array":e.referTo("Matrix, Matrix",d2=>(m,C)=>{l(Lt(m),Lt(C));var y=d2(n(m),n(C));return Mt(y)?y.valueOf():y}),"Matrix, Matrix":function(m,C){var y=m.size(),B2=C.size();return l(y,B2),1===y.length?1===B2.length?function(d2,m,C){if(0===C)throw new Error("Cannot multiply two empty vectors");return o(d2,m)}(m,C,y[0]):c(m,C):1===B2.length?w(m,C):M(m,C)},"Matrix, Array":e.referTo("Matrix,Matrix",d2=>(m,C)=>d2(m,n(C))),"Array, Matrix":e.referToSelf(d2=>(m,C)=>d2(n(m,C.storage()),C)),"SparseMatrix, any":function(m,C){return s(m,C,i,!1)},"DenseMatrix, any":function(m,C){return f(m,C,i,!1)},"any, SparseMatrix":function(m,C){return s(C,m,i,!0)},"any, DenseMatrix":function(m,C){return f(C,m,i,!0)},"Array, any":function(m,C){return f(n(m),C,i,!1).valueOf()},"any, Array":function(m,C){return f(n(C),m,i,!0).valueOf()},"any, any":i,"any, any, ...any":e.referToSelf(d2=>(m,C,y)=>{for(var B2=d2(m,C),x=0;x<y.length;x++)B2=d2(B2,y[x]);return B2})})}),Ma=/* @__PURE__ */Ft("conj",["typed"],t2=>{var{typed:e}=t2;return e("conj",{"number | BigNumber | Fraction":n=>n,Complex:n=>n.conjugate(),Unit:e.referToSelf(n=>r2=>new r2.constructor(n(r2.toNumeric()),r2.formatUnits())),"Array | Matrix":e.referToSelf(n=>r2=>na(r2,n))})});var Pr,Sa=/* @__PURE__ */Ft("size",["typed","config","?matrix"],t2=>{var{typed:e,config:n,matrix:r2}=t2;return e("size",{Matrix:function(u2){return u2.create(u2.size(),"number")},Array:Lt,string:function(u2){return"Array"===n.matrix?[u2.length]:r2([u2.length],"dense","number")},"number | Complex | BigNumber | Unit | boolean | null":function(u2){return"Array"===n.matrix?[]:r2?r2([],"dense","number"):function(){throw new Error('No "matrix" implementation available')}()}})}),Ir="transpose",ba=/* @__PURE__ */Ft(Ir,["typed","matrix"],t2=>{var{typed:e,matrix:n}=t2;return e(Ir,{Array:o=>r2(n(o)).valueOf(),Matrix:r2,any:Dt});function r2(o){var f,s=o.size();switch(s.length){case 1:f=o.clone();break;case 2:var l=s[0],a2=s[1];if(0===a2)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+Ot(s)+")");switch(o.storage()){case"dense":f=function(o,s,f){for(var c,l=o._data,a2=[],D2=0;D2<f;D2++){c=a2[D2]=[];for(var w=0;w<s;w++)c[w]=Dt(l[w][D2])}return o.createDenseMatrix({data:a2,size:[f,s],datatype:o._datatype})}(o,l,a2);break;case"sparse":f=function(o,s,f){for(var l=o._values,a2=o._index,c=o._ptr,D2=l?[]:void 0,w=[],M=[],h2=[],g=0;g<s;g++)h2[g]=0;var p2,E,F;for(p2=0,E=a2.length;p2<E;p2++)h2[a2[p2]]++;for(var A=0,d2=0;d2<s;d2++)M.push(A),A+=h2[d2],h2[d2]=M[d2];for(M.push(A),F=0;F<f;F++)for(var m=c[F],C=c[F+1],y=m;y<C;y++){var B2=h2[a2[y]]++;w[B2]=F,l&&(D2[B2]=Dt(l[y]))}return o.createSparseMatrix({values:D2,index:w,ptr:M,size:[f,s],datatype:o._datatype})}(o,l,a2)}break;default:throw new RangeError("Matrix must be a vector or two dimensional (size: "+Ot(s)+")")}return f}}),Gn={createMatrixClass:zs},Wi={MatrixDependencies:Gn,createDenseMatrixClass:ea},re={BigNumberDependencies:{createBigNumberClass:ws},ComplexDependencies:{createComplexClass:Bs},DenseMatrixDependencies:Wi,FractionDependencies:{createFractionClass:Is},createTyped:Co},Vi={typedDependencies:re,createEqualScalar:sa},Hi={typedDependencies:re,createAddScalar:pa},_n={DenseMatrixDependencies:Wi,MatrixDependencies:Gn,SparseMatrixDependencies:{MatrixDependencies:Gn,equalScalarDependencies:Vi,typedDependencies:re,createSparseMatrixClass:ca},typedDependencies:re,createMatrix:ha},Ji={typedDependencies:re,createMultiplyScalar:Ca},$a={addScalarDependencies:Hi,dotDependencies:{addScalarDependencies:Hi,conjDependencies:{typedDependencies:re,createConj:Ma},multiplyScalarDependencies:Ji,sizeDependencies:{matrixDependencies:_n,typedDependencies:re,createSize:Sa},typedDependencies:re,createDot:/* @__PURE__ */Ft("dot",["typed","addScalar","multiplyScalar","conj","size"],t2=>{var{typed:e,addScalar:n,multiplyScalar:r2,conj:i,size:u2}=t2;return e("dot",{"Array | DenseMatrix, Array | DenseMatrix":function(a2,c){var D2=o(a2,c),w=Mt(a2)?a2._data:a2,M=Mt(a2)?a2._datatype||a2.getDataType():void 0,h2=Mt(c)?c._data:c,g=Mt(c)?c._datatype||c.getDataType():void 0,p2=2===l(a2).length,E=2===l(c).length,F=n,A=r2;if(M&&g&&M===g&&"string"==typeof M&&"mixed"!==M){var d2=M;F=e.find(n,[d2,d2]),A=e.find(r2,[d2,d2])}if(!p2&&!E){for(var m=A(i(w[0]),h2[0]),C=1;C<D2;C++)m=F(m,A(i(w[C]),h2[C]));return m}if(!p2&&E){for(var y=A(i(w[0]),h2[0][0]),B2=1;B2<D2;B2++)y=F(y,A(i(w[B2]),h2[B2][0]));return y}if(p2&&!E){for(var x=A(i(w[0][0]),h2[0]),T=1;T<D2;T++)x=F(x,A(i(w[T][0]),h2[T]));return x}if(p2&&E){for(var q=A(i(w[0][0]),h2[0][0]),Z=1;Z<D2;Z++)q=F(q,A(i(w[Z][0]),h2[Z][0]));return q}},"SparseMatrix, SparseMatrix":function(a2,c){o(a2,c);for(var D2=a2._index,w=a2._values,M=c._index,h2=c._values,g=0,p2=n,E=r2,F=0,A=0;F<D2.length&&A<M.length;){var d2=D2[F],m=M[A];d2<m?F++:d2>m?A++:d2===m&&(g=p2(g,E(w[F],h2[A])),F++,A++)}return g}});function o(a2,c){var M,h2,D2=l(a2),w=l(c);if(1===D2.length)M=D2[0];else{if(2!==D2.length||1!==D2[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+D2.join(", ")+")");M=D2[0]}if(1===w.length)h2=w[0];else{if(2!==w.length||1!==w[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+w.join(", ")+")");h2=w[0]}if(M!==h2)throw new RangeError("Vectors must have equal length ("+M+" != "+h2+")");if(0===M)throw new RangeError("Cannot calculate the dot product of empty vectors");return M}function l(a2){return Mt(a2)?a2.size():u2(a2)}})},equalScalarDependencies:Vi,matrixDependencies:_n,multiplyScalarDependencies:Ji,typedDependencies:re,createMultiply:Ba},La={matrixDependencies:_n,typedDependencies:re,createTranspose:ba},on={exports:{}};const Va=/* @__PURE__ */qr(function(){if(Pr)return on.exports;function t2(){}return Pr=1,t2.prototype={on:function(e,n,r2){var i=this.e||(this.e={});return(i[e]||(i[e]=[])).push({fn:n,ctx:r2}),this},once:function(e,n,r2){var i=this;function u2(){i.off(e,u2),n.apply(r2,arguments)}return u2._=n,this.on(e,u2,r2)},emit:function(e){for(var n=[].slice.call(arguments,1),r2=((this.e||(this.e={}))[e]||[]).slice(),i=0,u2=r2.length;i<u2;i++)r2[i].fn.apply(r2[i].ctx,n);return this},off:function(e,n){var r2=this.e||(this.e={}),i=r2[e],u2=[];if(i&&n)for(var o=0,s=i.length;o<s;o++)i[o].fn!==n&&i[o].fn._!==n&&u2.push(i[o]);return u2.length?r2[e]=u2:delete r2[e],this}},on.exports=t2,on.exports.TinyEmitter=t2,on.exports}());function Ja(t2,e,n,r2){function u2(p2,E,F){var A;if(F.wrap&&"function"==typeof E&&(E=function(p2){var E=function(){for(var A=[],d2=0,m=arguments.length;d2<m;d2++){var C=arguments[d2];A[d2]=C&&C.valueOf()}return p2.apply(n,A)};return p2.transform&&(E.transform=p2.transform),E}(E)),function(p2){return"function"==typeof p2&&"string"==typeof p2.signature}(E)&&(E=t2(p2,{[E.signature]:E})),t2.isTypedFunction(n[p2])&&t2.isTypedFunction(E))return E=F.override?t2(p2,E.signatures):t2(n[p2],E),n[p2]=E,delete r2[p2],o(p2,E),void n.emit("import",p2,function(){return E});var d2=void 0!==n[p2],m=null===(A=n.Unit)||void 0===A?void 0:A.isValuelessUnit(p2);if(!d2&&!m||F.override)return n[p2]=E,delete r2[p2],o(p2,E),void n.emit("import",p2,function(){return E});if(!F.silent)throw new Error('Cannot import "'+p2+'": already exists')}function o(p2,E){E&&"function"==typeof E.transform?(n.expression.transform[p2]=E.transform,w(p2)&&(n.expression.mathWithTransform[p2]=E.transform)):(delete n.expression.transform[p2],w(p2)&&(n.expression.mathWithTransform[p2]=E))}function s(p2){delete n.expression.transform[p2],w(p2)?n.expression.mathWithTransform[p2]=n[p2]:delete n.expression.mathWithTransform[p2]}function l(p2,E){var F,A,d2=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p2.fn;if(d2.includes("."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(d2));var m=h2(p2)?n.expression.transform:n,C=d2 in n.expression.transform,y=kt(m,d2)?m[d2]:void 0,B2=function(){var W={};p2.dependencies.map(vi).forEach(z=>{if(z.includes("."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(z));"math"===z?W.math=n:"mathWithTransform"===z?W.mathWithTransform=n.expression.mathWithTransform:"classes"===z?W.classes=n:W[z]=n[z]});var L=/* @__PURE__ */p2(W);if(L&&"function"==typeof L.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with export const path = "expression.transform"');if(void 0===y||E.override)return L;if(t2.isTypedFunction(y)&&t2.isTypedFunction(L))return t2(y,L);if(E.silent)return y;throw new Error('Cannot import "'+d2+'": already exists')},x=null!==(F=null===(A=p2.meta)||void 0===A?void 0:A.formerly)&&void 0!==F?F:"",T=h2(p2)||function(p2){return!(p2.fn.includes(".")||kt(g,p2.fn)||p2.meta&&p2.meta.isClass)}(p2),q=n.expression.mathWithTransform;p2.meta&&!1===p2.meta.lazy?(m[d2]=B2(),x&&(m[x]=m[d2]),y&&C?(s(d2),x&&s(x)):T&&(ye(q,d2,()=>m[d2]),x&&ye(q,x,()=>m[d2]))):(ye(m,d2,B2),x&&ye(m,x,B2),y&&C?(s(d2),x&&s(x)):T&&(ye(q,d2,()=>m[d2]),x&&ye(q,x,()=>m[d2]))),r2[d2]=p2,n.emit("import",d2,B2)}function a2(p2){return"function"==typeof p2||"number"==typeof p2||"string"==typeof p2||"boolean"==typeof p2||null===p2||Fn(p2)||gn(p2)||Nt(p2)||vn(p2)||Mt(p2)||Array.isArray(p2)}function w(p2){return!kt(g,p2)}function h2(p2){return void 0!==p2&&void 0!==p2.meta&&!0===p2.meta.isTransformFunction||!1}var g={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(p2,E){var F=arguments.length;if(1!==F&&2!==F)throw new ve("import",F,1,2);E||(E={});var d2={};for(var m in function A(y,B2,x){if(Array.isArray(B2))B2.forEach(Z=>A(y,Z));else if(qe(B2)||function(p2){return"object"==typeof p2&&"Module"===p2[Symbol.toStringTag]}(B2))for(var T in B2)kt(B2,T)&&A(y,B2[T],T);else if(We(B2)||void 0!==x){var q=We(B2)?h2(B2)?B2.fn+".transform":B2.fn:x;if(kt(y,q)&&y[q]!==B2&&!E.silent)throw new Error('Cannot import "'+q+'" twice');y[q]=B2}else if(!E.silent)throw new TypeError("Factory, Object, or Array expected")}(d2,p2),d2)if(kt(d2,m)){var C=d2[m];if(We(C))l(C,E);else if(a2(C))u2(m,C,E);else if(!E.silent)throw new TypeError("Factory, Object, or Array expected")}}}const{matrix:zr,transpose:ka,multiply:Ne}=function ki(t2,e){var n=fn({},Yr,e);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r2=function(t2){var e=new Va;return t2.on=e.on.bind(e),t2.off=e.off.bind(e),t2.once=e.once.bind(e),t2.emit=e.emit.bind(e),t2}({isNumber:lt,isComplex:gn,isBigNumber:Nt,isBigInt:Ur,isFraction:vn,isUnit:Fn,isString:jt,isArray:At,isMatrix:Mt,isCollection:He,isDenseMatrix:Xr,isSparseMatrix:$r,isRange:Lr,isIndex:wn,isBoolean:Zr,isResultSet:Wr,isHelp:Vr,isFunction:Hr,isDate:Jr,isRegExp:kr,isObject:qe,isMap:Ie,isPartitionedMap:ao,isObjectWrappingMap:fo,isNull:Gr,isUndefined:Qr,isAccessorNode:Kr,isArrayNode:jr,isAssignmentNode:ti,isBlockNode:ei,isConditionalNode:ni,isConstantNode:ri,isFunctionAssignmentNode:ii,isFunctionNode:ui,isIndexNode:oi,isNode:si,isObjectNode:ai,isOperatorNode:fi,isParenthesisNode:ci,isRangeNode:li,isRelationalNode:hi,isSymbolNode:Di,isChain:pi});r2.config=po(n,r2.emit),r2.expression={transform:{},mathWithTransform:{config:r2.config}};var s={};function f(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return r2.typed.apply(r2.typed,c)}f.isTypedFunction=Je.isTypedFunction;var l=Ja(f,0,r2,s);return r2.import=l,r2.on("config",()=>{Object.values(s).forEach(a2=>{a2&&a2.meta&&a2.meta.recreateOnConfigChange&&l(a2,{override:!0})})}),r2.create=ki.bind(null,t2),r2.factory=Ft,r2.import(Object.values(lo(t2))),r2.ArgumentsError=ve,r2.DimensionError=pt,r2.IndexError=ge,r2}({matrixDependencies:_n,multiplyDependencies:$a,transposeDependencies:La}),Qa=t2=>{const e=Vu(t2,1/0),n=(t2=>{const e=[];for(let r2=0;r2<t2.length-1;r2++)e.push([t2[r2+1][0]-t2[r2][0],t2[r2+1][1]-t2[r2][1]]);return[...new Set(e.map(r2=>Math.abs(Math.atan2(r2[1],r2[0])%(Math.PI/2))))].map(r2=>[[Math.cos(r2),Math.cos(r2-Math.PI/2)],[Math.cos(r2+Math.PI/2),Math.cos(r2)]])})(e),r2=n.map(p2=>{const E=zr(p2),F=ka(zr(e));return Ne(E,F).toArray()}),i=r2.map(p2=>{const E=p2;return[Math.min(...E[0]),Math.min(...E[1])]}),u2=r2.map(p2=>{const E=p2;return[Math.max(...E[0]),Math.max(...E[1])]}),o=i.map(p2=>p2[0]),s=i.map(p2=>p2[1]),f=u2.map(p2=>p2[0]),l=u2.map(p2=>p2[1]),c=o.map((p2,E)=>(f[E]-o[E])*(l[E]-s[E])).reduce((p2,E,F,A)=>E<A[p2]?F:p2,0),[D2,w]=[f[c],l[c]],[M,h2]=[o[c],s[c]],g=n[c];return[Ne([D2,h2],g),Ne([M,h2],g),Ne([M,w],g),Ne([D2,w],g),Ne([D2,h2],g)]};function quickselect(arr,k,left=0,right=arr.length-1,compare=defaultCompare){for(;right>left;){if(right-left>600){const n=right-left+1,m=k-left+1,z=Math.log(n),s=.5*Math.exp(2*z/3),sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);quickselect(arr,k,Math.max(left,Math.floor(k-m*s/n+sd)),Math.min(right,Math.floor(k+(n-m)*s/n+sd)),compare)}const t2=arr[k];let i=left,j=right;for(swap(arr,left,k),compare(arr[right],t2)>0&&swap(arr,left,right);i<j;){for(swap(arr,i,j),i++,j--;compare(arr[i],t2)<0;)i++;for(;compare(arr[j],t2)>0;)j--}0===compare(arr[left],t2)?swap(arr,left,j):(j++,swap(arr,j,right)),j<=k&&(left=j+1),k<=j&&(right=j-1)}}function swap(arr,i,j){const tmp=arr[i];arr[i]=arr[j],arr[j]=tmp}function defaultCompare(a2,b4){return a2<b4?-1:a2>b4?1:0}class RBush{constructor(maxEntries=9){this._maxEntries=Math.max(4,maxEntries),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(bbox2){let node=this.data;const result=[];if(!intersects$1(bbox2,node))return result;const toBBox=this.toBBox,nodesToSearch=[];for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],childBBox=node.leaf?toBBox(child):child;intersects$1(bbox2,childBBox)&&(node.leaf?result.push(child):contains(bbox2,childBBox)?this._all(child,result):nodesToSearch.push(child))}node=nodesToSearch.pop()}return result}collides(bbox2){let node=this.data;if(!intersects$1(bbox2,node))return!1;const nodesToSearch=[];for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],childBBox=node.leaf?this.toBBox(child):child;if(intersects$1(bbox2,childBBox)){if(node.leaf||contains(bbox2,childBBox))return!0;nodesToSearch.push(child)}}node=nodesToSearch.pop()}return!1}load(data){if(!data||!data.length)return this;if(data.length<this._minEntries){for(let i=0;i<data.length;i++)this.insert(data[i]);return this}let node=this._build(data.slice(),0,data.length-1,0);if(this.data.children.length)if(this.data.height===node.height)this._splitRoot(this.data,node);else{if(this.data.height<node.height){const tmpNode=this.data;this.data=node,node=tmpNode}this._insert(node,this.data.height-node.height-1,!0)}else this.data=node;return this}insert(item){return item&&this._insert(item,this.data.height-1),this}clear(){return this.data=createNode([]),this}remove(item,equalsFn){if(!item)return this;let node=this.data;const bbox2=this.toBBox(item),path=[],indexes=[];let i,parent,goingUp;for(;node||path.length;){if(node||(node=path.pop(),parent=path[path.length-1],i=indexes.pop(),goingUp=!0),node.leaf){const index2=findItem(item,node.children,equalsFn);if(-1!==index2)return node.children.splice(index2,1),path.push(node),this._condense(path),this}goingUp||node.leaf||!contains(node,bbox2)?parent?(i++,node=parent.children[i],goingUp=!1):node=null:(path.push(node),indexes.push(i),i=0,parent=node,node=node.children[0])}return this}toBBox(item){return item}compareMinX(a2,b4){return a2.minX-b4.minX}compareMinY(a2,b4){return a2.minY-b4.minY}toJSON(){return this.data}fromJSON(data){return this.data=data,this}_all(node,result){const nodesToSearch=[];for(;node;)node.leaf?result.push(...node.children):nodesToSearch.push(...node.children),node=nodesToSearch.pop();return result}_build(items,left,right,height){const N=right-left+1;let node,M=this._maxEntries;if(N<=M)return node=createNode(items.slice(left,right+1)),calcBBox(node,this.toBBox),node;height||(height=Math.ceil(Math.log(N)/Math.log(M)),M=Math.ceil(N/Math.pow(M,height-1))),node=createNode([]),node.leaf=!1,node.height=height;const N2=Math.ceil(N/M),N1=N2*Math.ceil(Math.sqrt(M));multiSelect(items,left,right,N1,this.compareMinX);for(let i=left;i<=right;i+=N1){const right2=Math.min(i+N1-1,right);multiSelect(items,i,right2,N2,this.compareMinY);for(let j=i;j<=right2;j+=N2){const right3=Math.min(j+N2-1,right2);node.children.push(this._build(items,j,right3,height-1))}}return calcBBox(node,this.toBBox),node}_chooseSubtree(bbox2,node,level,path){for(;path.push(node),!node.leaf&&path.length-1!==level;){let targetNode,minArea=1/0,minEnlargement=1/0;for(let i=0;i<node.children.length;i++){const child=node.children[i],area2=bboxArea(child),enlargement=enlargedArea(bbox2,child)-area2;enlargement<minEnlargement?(minEnlargement=enlargement,minArea=area2<minArea?area2:minArea,targetNode=child):enlargement===minEnlargement&&area2<minArea&&(minArea=area2,targetNode=child)}node=targetNode||node.children[0]}return node}_insert(item,level,isNode){const bbox2=isNode?item:this.toBBox(item),insertPath=[],node=this._chooseSubtree(bbox2,this.data,level,insertPath);for(node.children.push(item),extend(node,bbox2);level>=0&&insertPath[level].children.length>this._maxEntries;)this._split(insertPath,level),level--;this._adjustParentBBoxes(bbox2,insertPath,level)}_split(insertPath,level){const node=insertPath[level],M=node.children.length,m=this._minEntries;this._chooseSplitAxis(node,m,M);const splitIndex=this._chooseSplitIndex(node,m,M),newNode=createNode(node.children.splice(splitIndex,node.children.length-splitIndex));newNode.height=node.height,newNode.leaf=node.leaf,calcBBox(node,this.toBBox),calcBBox(newNode,this.toBBox),level?insertPath[level-1].children.push(newNode):this._splitRoot(node,newNode)}_splitRoot(node,newNode){this.data=createNode([node,newNode]),this.data.height=node.height+1,this.data.leaf=!1,calcBBox(this.data,this.toBBox)}_chooseSplitIndex(node,m,M){let index2,minOverlap=1/0,minArea=1/0;for(let i=m;i<=M-m;i++){const bbox1=distBBox(node,0,i,this.toBBox),bbox2=distBBox(node,i,M,this.toBBox),overlap=intersectionArea(bbox1,bbox2),area2=bboxArea(bbox1)+bboxArea(bbox2);overlap<minOverlap?(minOverlap=overlap,index2=i,minArea=area2<minArea?area2:minArea):overlap===minOverlap&&area2<minArea&&(minArea=area2,index2=i)}return index2||M-m}_chooseSplitAxis(node,m,M){const compareMinX=node.leaf?this.compareMinX:compareNodeMinX,compareMinY=node.leaf?this.compareMinY:compareNodeMinY;this._allDistMargin(node,m,M,compareMinX)<this._allDistMargin(node,m,M,compareMinY)&&node.children.sort(compareMinX)}_allDistMargin(node,m,M,compare){node.children.sort(compare);const toBBox=this.toBBox,leftBBox=distBBox(node,0,m,toBBox),rightBBox=distBBox(node,M-m,M,toBBox);let margin=bboxMargin(leftBBox)+bboxMargin(rightBBox);for(let i=m;i<M-m;i++){const child=node.children[i];extend(leftBBox,node.leaf?toBBox(child):child),margin+=bboxMargin(leftBBox)}for(let i=M-m-1;i>=m;i--){const child=node.children[i];extend(rightBBox,node.leaf?toBBox(child):child),margin+=bboxMargin(rightBBox)}return margin}_adjustParentBBoxes(bbox2,path,level){for(let i=level;i>=0;i--)extend(path[i],bbox2)}_condense(path){for(let siblings,i=path.length-1;i>=0;i--)0===path[i].children.length?i>0?(siblings=path[i-1].children,siblings.splice(siblings.indexOf(path[i]),1)):this.clear():calcBBox(path[i],this.toBBox)}}function findItem(item,items,equalsFn){if(!equalsFn)return items.indexOf(item);for(let i=0;i<items.length;i++)if(equalsFn(item,items[i]))return i;return-1}function calcBBox(node,toBBox){distBBox(node,0,node.children.length,toBBox,node)}function distBBox(node,k,p2,toBBox,destNode){destNode||(destNode=createNode(null)),destNode.minX=1/0,destNode.minY=1/0,destNode.maxX=-1/0,destNode.maxY=-1/0;for(let i=k;i<p2;i++){const child=node.children[i];extend(destNode,node.leaf?toBBox(child):child)}return destNode}function extend(a2,b4){return a2.minX=Math.min(a2.minX,b4.minX),a2.minY=Math.min(a2.minY,b4.minY),a2.maxX=Math.max(a2.maxX,b4.maxX),a2.maxY=Math.max(a2.maxY,b4.maxY),a2}function compareNodeMinX(a2,b4){return a2.minX-b4.minX}function compareNodeMinY(a2,b4){return a2.minY-b4.minY}function bboxArea(a2){return(a2.maxX-a2.minX)*(a2.maxY-a2.minY)}function bboxMargin(a2){return a2.maxX-a2.minX+(a2.maxY-a2.minY)}function enlargedArea(a2,b4){return(Math.max(b4.maxX,a2.maxX)-Math.min(b4.minX,a2.minX))*(Math.max(b4.maxY,a2.maxY)-Math.min(b4.minY,a2.minY))}function intersectionArea(a2,b4){const minX=Math.max(a2.minX,b4.minX),minY=Math.max(a2.minY,b4.minY),maxX=Math.min(a2.maxX,b4.maxX),maxY=Math.min(a2.maxY,b4.maxY);return Math.max(0,maxX-minX)*Math.max(0,maxY-minY)}function contains(a2,b4){return a2.minX<=b4.minX&&a2.minY<=b4.minY&&b4.maxX<=a2.maxX&&b4.maxY<=a2.maxY}function intersects$1(a2,b4){return b4.minX<=a2.maxX&&b4.minY<=a2.maxY&&b4.maxX>=a2.minX&&b4.maxY>=a2.minY}function createNode(children){return{children:children,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function multiSelect(arr,left,right,n,compare){const stack=[left,right];for(;stack.length;){if((right=stack.pop())-(left=stack.pop())<=n)continue;const mid=left+Math.ceil((right-left)/n/2)*n;quickselect(arr,mid,left,right,compare),stack.push(left,mid,mid,right)}}class TinyQueue2{constructor(data=[],compare=(a2,b4)=>a2<b4?-1:a2>b4?1:0){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos<halfLength;){let bestChild=1+(pos<<1);const right=bestChild+1;if(right<this.length&&compare(data[right],data[bestChild])<0&&(bestChild=right),compare(data[bestChild],item)>=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const pointInPolygon=/* @__PURE__ */getDefaultExportFromCjs(requirePointInPolygon());function sum(elen,e,flen,f,h2){let Q2,Qnew,hh,bvirt,enow=e[0],fnow=f[0],eindex=0,findex=0;fnow>enow==fnow>-enow?(Q2=enow,enow=e[++eindex]):(Q2=fnow,fnow=f[++findex]);let hindex=0;if(eindex<elen&&findex<flen)for(fnow>enow==fnow>-enow?(Qnew=enow+Q2,hh=Q2-(Qnew-enow),enow=e[++eindex]):(Qnew=fnow+Q2,hh=Q2-(Qnew-fnow),fnow=f[++findex]),Q2=Qnew,0!==hh&&(h2[hindex++]=hh);eindex<elen&&findex<flen;)fnow>enow==fnow>-enow?(Qnew=Q2+enow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(enow-bvirt),enow=e[++eindex]):(Qnew=Q2+fnow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(fnow-bvirt),fnow=f[++findex]),Q2=Qnew,0!==hh&&(h2[hindex++]=hh);for(;eindex<elen;)Qnew=Q2+enow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(enow-bvirt),enow=e[++eindex],Q2=Qnew,0!==hh&&(h2[hindex++]=hh);for(;findex<flen;)Qnew=Q2+fnow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(fnow-bvirt),fnow=f[++findex],Q2=Qnew,0!==hh&&(h2[hindex++]=hh);return 0===Q2&&0!==hindex||(h2[hindex++]=Q2),hindex}function vec(n){return new Float64Array(n)}const B=vec(4),C1=vec(8),C2=vec(12),D=vec(16),u=vec(4);function orient2d(ax,ay,bx,by,cx,cy){const detleft=(ay-cy)*(bx-cx),detright=(ax-cx)*(by-cy),det=detleft-detright,detsum=Math.abs(detleft+detright);return Math.abs(det)>=33306690738754716e-32*detsum?det:-function(ax,ay,bx,by,cx,cy,detsum){let acxtail,acytail,bcxtail,bcytail,bvirt,c,ahi,alo,bhi,blo,_i2,_j,_0,s1,s0,t1,t0,u3;const acx=ax-cx,bcx=bx-cx,acy=ay-cy,bcy=by-cy;s1=acx*bcy,c=134217729*acx,ahi=c-(c-acx),alo=acx-ahi,c=134217729*bcy,bhi=c-(c-bcy),blo=bcy-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acy*bcx,c=134217729*acy,ahi=c-(c-acy),alo=acy-ahi,c=134217729*bcx,bhi=c-(c-bcx),blo=bcx-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,B[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,B[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,B[2]=_j-(u3-bvirt)+(_i2-bvirt),B[3]=u3;let det=function(elen,e){let Q2=e[0];for(let i=1;i<elen;i++)Q2+=e[i];return Q2}(4,B),errbound=22204460492503146e-32*detsum;if(det>=errbound||-det>=errbound)return det;if(bvirt=ax-acx,acxtail=ax-(acx+bvirt)+(bvirt-cx),bvirt=bx-bcx,bcxtail=bx-(bcx+bvirt)+(bvirt-cx),bvirt=ay-acy,acytail=ay-(acy+bvirt)+(bvirt-cy),bvirt=by-bcy,bcytail=by-(bcy+bvirt)+(bvirt-cy),0===acxtail&&0===acytail&&0===bcxtail&&0===bcytail)return det;if(errbound=11093356479670487e-47*detsum+33306690738754706e-32*Math.abs(det),det+=acx*bcytail+bcy*acxtail-(acy*bcxtail+bcx*acytail),det>=errbound||-det>=errbound)return det;s1=acxtail*bcy,c=134217729*acxtail,ahi=c-(c-acxtail),alo=acxtail-ahi,c=134217729*bcy,bhi=c-(c-bcy),blo=bcy-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acytail*bcx,c=134217729*acytail,ahi=c-(c-acytail),alo=acytail-ahi,c=134217729*bcx,bhi=c-(c-bcx),blo=bcx-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const C1len=sum(4,B,4,u,C1);s1=acx*bcytail,c=134217729*acx,ahi=c-(c-acx),alo=acx-ahi,c=134217729*bcytail,bhi=c-(c-bcytail),blo=bcytail-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acy*bcxtail,c=134217729*acy,ahi=c-(c-acy),alo=acy-ahi,c=134217729*bcxtail,bhi=c-(c-bcxtail),blo=bcxtail-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const C2len=sum(C1len,C1,4,u,C2);s1=acxtail*bcytail,c=134217729*acxtail,ahi=c-(c-acxtail),alo=acxtail-ahi,c=134217729*bcytail,bhi=c-(c-bcytail),blo=bcytail-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acytail*bcxtail,c=134217729*acytail,ahi=c-(c-acytail),alo=acytail-ahi,c=134217729*bcxtail,bhi=c-(c-bcxtail),blo=bcxtail-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const Dlen=sum(C2len,C2,4,u,D);return D[Dlen-1]}(ax,ay,bx,by,cx,cy,detsum)}function concaveman(points,concavity,lengthThreshold){concavity=Math.max(0,void 0===concavity?2:concavity),lengthThreshold=lengthThreshold||0;const hull=function(points){let left=points[0],top=points[0],right=points[0],bottom=points[0];for(let i=0;i<points.length;i++){const p2=points[i];p2[0]<left[0]&&(left=p2),p2[0]>right[0]&&(right=p2),p2[1]<top[1]&&(top=p2),p2[1]>bottom[1]&&(bottom=p2)}const cull2=[left,top,right,bottom],filtered=cull2.slice();for(let i=0;i<points.length;i++)pointInPolygon(points[i],cull2)||filtered.push(points[i]);return function(points){points.sort(compareByX);const lower=[];for(let i=0;i<points.length;i++){for(;lower.length>=2&&cross(lower[lower.length-2],lower[lower.length-1],points[i])<=0;)lower.pop();lower.push(points[i])}const upper=[];for(let ii2=points.length-1;ii2>=0;ii2--){for(;upper.length>=2&&cross(upper[upper.length-2],upper[upper.length-1],points[ii2])<=0;)upper.pop();upper.push(points[ii2])}return upper.pop(),lower.pop(),lower.concat(upper)}(filtered)}(points),tree=new RBush(16);tree.toBBox=function(a2){return{minX:a2[0],minY:a2[1],maxX:a2[0],maxY:a2[1]}},tree.compareMinX=function(a2,b4){return a2[0]-b4[0]},tree.compareMinY=function(a2,b4){return a2[1]-b4[1]},tree.load(points);const queue=[];let last;for(let i=0;i<hull.length;i++){const p2=hull[i];tree.remove(p2),last=insertNode(p2,last),queue.push(last)}const segTree=new RBush(16);for(let i=0;i<queue.length;i++)segTree.insert(updateBBox(queue[i]));const sqConcavity=concavity*concavity,sqLenThreshold=lengthThreshold*lengthThreshold;for(;queue.length;){const node2=queue.shift(),a2=node2.p,b4=node2.next.p,sqLen=getSqDist(a2,b4);if(sqLen<sqLenThreshold)continue;const maxSqLen=sqLen/sqConcavity,p2=findCandidate(tree,node2.prev.p,a2,b4,node2.next.next.p,maxSqLen,segTree);p2&&Math.min(getSqDist(p2,a2),getSqDist(p2,b4))<=maxSqLen&&(queue.push(node2),queue.push(insertNode(p2,node2)),tree.remove(p2),segTree.remove(node2),segTree.insert(updateBBox(node2)),segTree.insert(updateBBox(node2.next)))}let node=last;const concave=[];do{concave.push(node.p),node=node.next}while(node!==last);return concave.push(node.p),concave}function findCandidate(tree,a2,b4,c,d2,maxDist,segTree){const queue=new TinyQueue2([],compareDist);let node=tree.data;for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],dist=node.leaf?sqSegDist(child,b4,c):sqSegBoxDist(b4,c,child);dist>maxDist||queue.push({node:child,dist:dist})}for(;queue.length&&!queue.peek().node.children;){const item=queue.pop(),p2=item.node,d0=sqSegDist(p2,a2,b4),d1=sqSegDist(p2,c,d2);if(item.dist<d0&&item.dist<d1&&noIntersections(b4,p2,segTree)&&noIntersections(c,p2,segTree))return p2}node=queue.pop(),node&&(node=node.node)}return null}function compareDist(a2,b4){return a2.dist-b4.dist}function sqSegBoxDist(a2,b4,bbox2){if(inside(a2,bbox2)||inside(b4,bbox2))return 0;const d1=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.maxX,bbox2.minY);if(0===d1)return 0;const d2=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.minX,bbox2.maxY);if(0===d2)return 0;const d3=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.maxX,bbox2.minY,bbox2.maxX,bbox2.maxY);if(0===d3)return 0;const d4=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.maxY,bbox2.maxX,bbox2.maxY);return 0===d4?0:Math.min(d1,d2,d3,d4)}function inside(a2,bbox2){return a2[0]>=bbox2.minX&&a2[0]<=bbox2.maxX&&a2[1]>=bbox2.minY&&a2[1]<=bbox2.maxY}function noIntersections(a2,b4,segTree){const minX=Math.min(a2[0],b4[0]),minY=Math.min(a2[1],b4[1]),maxX=Math.max(a2[0],b4[0]),maxY=Math.max(a2[1],b4[1]),edges=segTree.search({minX:minX,minY:minY,maxX:maxX,maxY:maxY});for(let i=0;i<edges.length;i++)if(intersects(edges[i].p,edges[i].next.p,a2,b4))return!1;return!0}function cross(p1,p2,p3){return orient2d(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1])}function intersects(p1,q1,p2,q2){return p1!==q2&&q1!==p2&&cross(p1,q1,p2)>0!=cross(p1,q1,q2)>0&&cross(p2,q2,p1)>0!=cross(p2,q2,q1)>0}function updateBBox(node){const p1=node.p,p2=node.next.p;return node.minX=Math.min(p1[0],p2[0]),node.minY=Math.min(p1[1],p2[1]),node.maxX=Math.max(p1[0],p2[0]),node.maxY=Math.max(p1[1],p2[1]),node}function insertNode(p2,prev){const node={p:p2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return prev?(node.next=prev.next,node.prev=prev,prev.next.prev=node,prev.next=node):(node.prev=node,node.next=node),node}function getSqDist(p1,p2){const dx=p1[0]-p2[0],dy=p1[1]-p2[1];return dx*dx+dy*dy}function sqSegDist(p2,p1,p22){let x=p1[0],y=p1[1],dx=p22[0]-x,dy=p22[1]-y;if(0!==dx||0!==dy){const t2=((p2[0]-x)*dx+(p2[1]-y)*dy)/(dx*dx+dy*dy);t2>1?(x=p22[0],y=p22[1]):t2>0&&(x+=dx*t2,y+=dy*t2)}return dx=p2[0]-x,dy=p2[1]-y,dx*dx+dy*dy}function sqSegSegDist(x0,y0,x1,y1,x2,y2,x3,y3){const ux=x1-x0,uy=y1-y0,vx=x3-x2,vy=y3-y2,wx=x0-x2,wy=y0-y2,a2=ux*ux+uy*uy,b4=ux*vx+uy*vy,c=vx*vx+vy*vy,d2=ux*wx+uy*wy,e=vx*wx+vy*wy,D2=a2*c-b4*b4;let sN,tN,sD=D2,tD=D2;0===D2?(sN=0,sD=1,tN=e,tD=c):(sN=b4*e-c*d2,tN=a2*e-b4*d2,sN<0?(sN=0,tN=e,tD=c):sN>sD&&(sN=sD,tN=e+b4,tD=c)),tN<0?(tN=0,-d2<0?sN=0:-d2>a2?sN=sD:(sN=-d2,sD=a2)):tN>tD&&(tN=tD,-d2+b4<0?sN=0:-d2+b4>a2?sN=sD:(sN=-d2+b4,sD=a2));const sc=0===sN?0:sN/sD,tc=0===tN?0:tN/tD,dx=(1-tc)*x2+tc*x3-((1-sc)*x0+sc*x1),dy=(1-tc)*y2+tc*y3-((1-sc)*y0+sc*y1);return dx*dx+dy*dy}function compareByX(a2,b4){return a2[0]===b4[0]?a2[1]-b4[1]:a2[0]-b4[0]}function findRooms(lines,trajectory2,option){const{clone:clone2=!0,split:split=!0}=option??{};clone2&&(lines=lines.map(line=>line.clone())),split&&(lines=splitIntersectedLine(lines,0));const rooms=[],pool2=PointUtils.createPool(),psh=trajectory2?PointSpatialHash.from(Object.values(trajectory2).map(p2=>pool2.point.set(p2.x,p2.y))):void 0,maxiCircles=new MaxiCircles,center=pool2.point;return LineSegmentUtils.groupByPath(lines).forEach(group2=>{const removeSet=findDiscretePointLine2(group2,null,!0);lines=group2.filter(line=>!removeSet.has(line)&&!line.userData.isBayWindow);const circles=maxiCircles.miniCircle(lines).circles.filter(function(psh){return lines=>{const doubleLines=lines.filter(line=>WH.isDouble(line));if(WH.isPairing(doubleLines))return!1;const ply=Polygon.fromByLinePath(lines);return!psh||psh.queryPolygon(ply,"inside").length>0}}(psh));circles.map(p2=>Polygon.fromByLinePath(p2)).forEach((ploy,i)=>{const xList=[],yList=[];ploy.forEach(p2=>{xList.push(p2.x),yList.push(p2.y)});const minX=Math.min(...xList),maxX=Math.max(...xList),minY=Math.min(...yList),maxY=Math.max(...yList);center.set(.5*(maxX-minX)+minX,.5*(maxY-minY)+minY),rooms.push({lines:circles[i],ploy:ploy,center:center,uuid:uuid()})})}),pool2.freeAll(),rooms}function mergeAttributes(attributes){let TypedArray,itemSize,normalized,gpuType=-1,arrayLength=0;for(let i=0;i<attributes.length;++i){const attribute=attributes[i];if(void 0===TypedArray&&(TypedArray=attribute.array.constructor),TypedArray!==attribute.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(void 0===itemSize&&(itemSize=attribute.itemSize),itemSize!==attribute.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(void 0===normalized&&(normalized=attribute.normalized),normalized!==attribute.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(-1===gpuType&&(gpuType=attribute.gpuType),gpuType!==attribute.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;arrayLength+=attribute.count*itemSize}const array=new TypedArray(arrayLength),result=new BufferAttribute(array,itemSize,normalized);let offset=0;for(let i=0;i<attributes.length;++i){const attribute=attributes[i];if(attribute.isInterleavedBufferAttribute){const tupleOffset=offset/itemSize;for(let j=0,l=attribute.count;j<l;j++)for(let c=0;c<itemSize;c++){const value=attribute.getComponent(j,c);result.setComponent(j+tupleOffset,c,value)}}else array.set(attribute.array,offset);offset+=attribute.count*itemSize}return void 0!==gpuType&&(result.gpuType=gpuType),result}function toTrianglesDrawMode(geometry,drawMode){if(drawMode===TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),geometry;if(drawMode===TriangleFanDrawMode||drawMode===TriangleStripDrawMode){let index2=geometry.getIndex();if(null===index2){const indices=[],position=geometry.getAttribute("position");if(void 0===position)return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),geometry;for(let i=0;i<position.count;i++)indices.push(i);geometry.setIndex(indices),index2=geometry.getIndex()}const numberOfTriangles=index2.count-2,newIndices=[];if(drawMode===TriangleFanDrawMode)for(let i=1;i<=numberOfTriangles;i++)newIndices.push(index2.getX(0)),newIndices.push(index2.getX(i)),newIndices.push(index2.getX(i+1));else for(let i=0;i<numberOfTriangles;i++)i%2==0?(newIndices.push(index2.getX(i)),newIndices.push(index2.getX(i+1)),newIndices.push(index2.getX(i+2))):(newIndices.push(index2.getX(i+2)),newIndices.push(index2.getX(i+1)),newIndices.push(index2.getX(i)));newIndices.length/3!==numberOfTriangles&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const newGeometry=geometry.clone();return newGeometry.setIndex(newIndices),newGeometry.clearGroups(),newGeometry}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",drawMode),geometry}let globalScenario;const box3=new THREE.Box3,polygon=new Polygon;class SceneAutoGenerat{lines;itemList;z;scene=new THREE.Group;trajectory;angle=0;constructor(lines,itemList,z,trajectory2){this.lines=lines,this.itemList=itemList,this.z=z,this.trajectory=trajectory2,globalScenario=globalScenario??Scenario.Instance??new Scenario(new THREE.Scene,{},{},{});const vrLine=LineSegmentUtils.findDominantDirectionLine(lines);this.angle=-vrLine.direction().angleBetween(new Point(0,1),"angle","360")*(Math.PI/180)}async init(){await this.buildWall(),globalScenario.scene.add(this.scene),globalScenario.scene.traverse(child=>{child.updateWorldMatrix(!1,!1)})}createGeometryByLines(lines){const shape=new THREE.Shape;Polygon.fromByLinePath(lines,polygon),polygon.forEach((p2,i)=>0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y)),shape.closePath();return new THREE.ShapeGeometry(shape)}findRoom(lines){const queryLines=lines.filter(line=>line.userData.isDoor||line.userData.isPassageEntrance),{circles:circles}=MaxiCircles.instance.miniCircle(lines,{circleEdges:queryLines,side:Side.IN});return circles.map(circle=>[Polygon.fromByLinePath(circle),uuid()])}findByWindow(lines){return LineGroupType.getGroupsByType(lines,"bayWindow").map(lines2=>Polygon.fromByLines2(lines2))}findOutline(lines,type){if("closed-loop"===type){const set2=findDiscretePointLine(lines);lines=lines.filter(line=>!set2.has(line));const{circles:circles}=MaxiCircles.instance.miniCircle(lines,{side:Side.OUT});return circles.map(circle=>Polygon.fromByLinePath(circle))}const counterMap=new CounterMap;findDiscretePoint(this.lines).forEach(l=>counterMap.increment(l));const ls2=counterMap.getByCount(2);let removeSet=new Set(ls2);const points=this.lines.filter(line=>!removeSet.has(line)).filter(line=>!line.userData.isBayWindow&&!line.userData.miscellaneous).flatMap(line=>[...line.points,...LineSegmentUtils.sampleSegmentBydistance(line,.01)]);if(0===points.length)return[];const hull=concaveman(points.map(p2=>p2.toArray()),2);return[new Polygon(Point.fromByList(hull))]}buildPlane(lines,type,roomList){lines=splitIntersectedLine(lines.map(line=>line.clone()),0),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4);let rooms=roomList.length>0?roomList.map(i=>[i.ploy.clone(),i.uuid]):this.findRoom(lines),byWindows=this.findByWindow(lines),outCircles=this.findOutline(lines,type);rooms.forEach(([room])=>room.close());const group2=new THREE.Group,geometries=[];if(rooms.forEach(([polygon2,uuid2],j)=>{const geometry=this.createGeometryByLines(polygon2.toLines());geometries.push(geometry);const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_${j}`,mesh.userData.category="plane",mesh.userData.planeType="room",mesh.userData.uuid=uuid2,mesh.userData.area=polygon2.area(),mesh.userData.room=!0,group2.add(mesh)}),byWindows.forEach((polygon2,j)=>{const geometry=this.createGeometryByLines(polygon2.toLines());geometries.push(geometry);const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_飘窗_${j}`,mesh.userData.category="plane",mesh.userData.planeType="byWindow",mesh.userData.uuid=uuid(),mesh.userData.area=polygon2.area(),mesh.userData.room=!0,group2.add(mesh)}),outCircles.length){let brush1;if(geometries.length){const merged=function(geometries,useGroups=!1){const isIndexed=null!==geometries[0].index,attributesUsed=new Set(Object.keys(geometries[0].attributes)),morphAttributesUsed=new Set(Object.keys(geometries[0].morphAttributes)),attributes={},morphAttributes={},morphTargetsRelative=geometries[0].morphTargetsRelative,mergedGeometry=new BufferGeometry;let offset=0;for(let i=0;i<geometries.length;++i){const geometry=geometries[i];let attributesCount=0;if(isIndexed!==(null!==geometry.index))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const name in geometry.attributes){if(!attributesUsed.has(name))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+'. All geometries must have compatible attributes; make sure "'+name+'" attribute exists among all geometries, or in none of them.'),null;void 0===attributes[name]&&(attributes[name]=[]),attributes[name].push(geometry.attributes[name]),attributesCount++}if(attributesCount!==attributesUsed.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". Make sure all geometries have the same number of attributes."),null;if(morphTargetsRelative!==geometry.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const name in geometry.morphAttributes){if(!morphAttributesUsed.has(name))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". .morphAttributes must be consistent throughout all geometries."),null;void 0===morphAttributes[name]&&(morphAttributes[name]=[]),morphAttributes[name].push(geometry.morphAttributes[name])}if(useGroups){let count;if(isIndexed)count=geometry.index.count;else{if(void 0===geometry.attributes.position)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". The geometry must have either an index or a position attribute"),null;count=geometry.attributes.position.count}mergedGeometry.addGroup(offset,count,i),offset+=count}}if(isIndexed){let indexOffset=0;const mergedIndex=[];for(let i=0;i<geometries.length;++i){const index2=geometries[i].index;for(let j=0;j<index2.count;++j)mergedIndex.push(index2.getX(j)+indexOffset);indexOffset+=geometries[i].attributes.position.count}mergedGeometry.setIndex(mergedIndex)}for(const name in attributes){const mergedAttribute=mergeAttributes(attributes[name]);if(!mergedAttribute)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+name+" attribute."),null;mergedGeometry.setAttribute(name,mergedAttribute)}for(const name in morphAttributes){const numMorphTargets=morphAttributes[name][0].length;if(0===numMorphTargets)break;mergedGeometry.morphAttributes=mergedGeometry.morphAttributes||{},mergedGeometry.morphAttributes[name]=[];for(let i=0;i<numMorphTargets;++i){const morphAttributesToMerge=[];for(let j=0;j<morphAttributes[name].length;++j)morphAttributesToMerge.push(morphAttributes[name][j][i]);const mergedMorphAttribute=mergeAttributes(morphAttributesToMerge);if(!mergedMorphAttribute)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+name+" morphAttribute."),null;mergedGeometry.morphAttributes[name].push(mergedMorphAttribute)}}return mergedGeometry}(geometries);brush1=new Brush(merged),brush1.updateMatrixWorld()}const evaluator=new Evaluator;outCircles.forEach((poly,j)=>{let geometry=this.createGeometryByLines(poly.toLines());if(brush1){const brush2=new Brush(geometry);brush2.updateMatrixWorld();geometry=evaluator.evaluate(brush2,brush1,SUBTRACTION).geometry}const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_out_${j}`,mesh.userData.category="plane",mesh.userData.planeType="outline",mesh.userData.uuid=uuid(),mesh.userData.area=poly.area(),group2.add(mesh)})}this.scene.add(group2)}wallGroup=null;async buildWall(){this.wallGroup=await globalScenario.drawGraphics(this.lines,this.z,this.trajectory),this.scene.add(this.wallGroup)}async getModel(item){let model=await LoadModel.loadGlb(item.category);if(!model)return;model=model.clone(!0),model.rotateX(.5*Math.PI),model.traverse(mesh=>{if(mesh instanceof THREE.Mesh){const material=mesh.material;mesh.material.map=null,material.vertexColors=!1,material.color=new THREE.Color(16777215)}});const contour=Point.fromByList(item.contour??[]),rectangle=new Polygon(Qa(contour.map(p2=>[p2.x,p2.y])).map(p2=>Point.from(p2)));rectangle.pop();const z=item.box.min.z,max=rectangle.getMaxLengthInfo(),min=rectangle.getMinLengthInfo(),center=rectangle.getCenter(),direction=max.start.y<max.end.y?max.start.directionFrom(max.end):max.end.directionFrom(max.start),height=Math.abs(item.box.max.z-z),group2=new THREE.Group;group2.position.set(center.x,center.y,z),group2.add(model),this.scene.add(group2);const box32=new THREE.Box3;box32.setFromObject(group2);const size2=box32.getSize(new THREE.Vector3),maxKey=size2.x>size2.y?"x":"y",mimKey=size2.x<size2.y?"x":"y",maxS=max.length/size2[maxKey],minS=min.length/size2[mimKey],scale2=height/size2.z;group2.scale[maxKey]*=maxS,group2.scale[mimKey]*=minS,group2.scale.z*=scale2,box32.setFromObject(group2),box32.getSize(size2);const point1=new Point,point2=new Point;size2.x>size2.y?(point1.set(box32.min.x,box32.min.y),point2.set(box32.max.x,box32.min.y)):(point1.set(box32.min.x,box32.min.y),point2.set(box32.min.x,box32.max.y));const direction2=point1.y<point2.y?point1.directionFrom(point2):point2.directionFrom(point1);group2.rotateZ(direction2.angleBetween2(direction)),this.scene.add(SceneAutoGenerat.itemParse(item).box)}static itemParse(item){const contourData=item.quadContour??item.contour;if(!Array.isArray(contourData)||!contourData.length)return null;const contour=Point.fromByList(contourData??[]),rectangle=new Polygon(Qa(contour.map(p2=>[p2.x,p2.y])).map(p2=>Point.from(p2)));rectangle.pop();const z=item.box.min.z,height=Math.abs(item.box.max.z-z),max=rectangle.getMaxLengthInfo(),min=rectangle.getMinLengthInfo(),direction=max.start.y<max.end.y?max.start.directionFrom(max.end):max.end.directionFrom(max.start),shape=new THREE.Shape;rectangle.forEach((p2,i)=>{0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y),i===rectangle.length-1&&shape.lineTo(rectangle[0].x,rectangle[0].y)});const geometry=new THREE.ExtrudeGeometry(shape,{depth:height,bevelEnabled:!1}),edges=new THREE.EdgesGeometry(geometry),lineSegments=new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:16776960}));lineSegments.position.z=z,box3.setFromObject(lineSegments);const center=box3.getCenter(new THREE.Vector3),maxLine=new LineSegment(max.start,max.end),minLine=new LineSegment(min.start,min.end),zStart=(new THREE.Vector3).copy(rectangle[0].toJson(z)),zEnd=zStart.clone();return zEnd.z+=height,{geometry:geometry,box:lineSegments,center:center,category:item.category,angle:direction.angleBetween(new Point(0,1),"angle","360")*(Math.PI/180)+.5*Math.PI,info:[{center:(new THREE.Vector3).copy(maxLine.center.toJson(z)),start:(new THREE.Vector3).copy(maxLine.start.toJson(z)),end:(new THREE.Vector3).copy(maxLine.start.toJson(z)),length:maxLine.length},{center:(new THREE.Vector3).copy(minLine.center.toJson(z)),start:(new THREE.Vector3).copy(minLine.start.toJson(z)),end:(new THREE.Vector3).copy(minLine.start.toJson(z)),length:minLine.length},{center:zStart.clone().add(zEnd).multiplyScalar(.5),start:zStart,end:zEnd,length:height}]}}}function proj(line,baseline,verticalLine){const startProj=baseline.projectPointValue(line.start),endProj=baseline.projectPointValue(line.end);return{pos:verticalLine.projectPointValue(line.start),startProj:Math.min(startProj,endProj),endProj:Math.max(startProj,endProj)}}function insertRangeIndex(track,range){if(0===track.length)return 0;let left=0,right=track.length;for(;left<right;){const mid=left+right>>1;track[mid][0]<range[0]?left=mid+1:right=mid}const i=left,prev=track[i-1],next=track[i];return prev&&range[0]<prev[1]||next&&range[1]>next[0]?-1:i}function getSize(ranges){let min=1/0,max=-1/0;return ranges.forEach(ranges2=>{ranges2.forEach(range=>{min=Math.min(min,range[0],range[1]),max=Math.max(max,range[0],range[1])})}),{min:min,max:max,length:max-min}}class DimensionLine{static build(lines,opt){if(0===lines.length)return[];const{maxTracks:maxTracks=3,besideLines:besideLines=[],minLen:minLen=.04,besideLinesPosFunc:besideLinesPosFunc,besideLineOffset:besideLineOffset=.2}=opt??{},geometryCenter=LineSegmentUtils.getLinesCenter(lines),dimensionAxis=LineSegmentUtils.findDominantDirectionLine(lines).clone().setLength(4),axisOffset=geometryCenter.subtract(dimensionAxis.center);dimensionAxis.translate(1,axisOffset);const normalAxis=dimensionAxis.clone().rotate(.5*-Math.PI),negativeParallelRanges=[],positiveParallelRanges=[],negativeNormalRanges=[],positiveNormalRanges=[];lines.forEach((line,index2)=>{if(dimensionAxis.isParallelTo(line)){const{pos:pos,startProj:startProj,endProj:endProj}=proj(line,dimensionAxis,normalAxis);pos<=.5?negativeParallelRanges.push([startProj,endProj,index2]):positiveParallelRanges.push([startProj,endProj,index2])}else{const{pos:pos,startProj:startProj,endProj:endProj}=proj(line,normalAxis,dimensionAxis);pos<=.5?negativeNormalRanges.push([startProj,endProj,index2]):positiveNormalRanges.push([startProj,endProj,index2])}});const besideRanges=besideLines.reduce((ranges,line,index2)=>{if(dimensionAxis.isParallelTo(line)){const{startProj:startProj,endProj:endProj}=proj(line,dimensionAxis,normalAxis);ranges[0].push([startProj,endProj,index2])}else{const{startProj:startProj,endProj:endProj}=proj(line,normalAxis,dimensionAxis);ranges[1].push([startProj,endProj,index2])}return ranges},[[],[]]),dimensionSize=getSize([negativeParallelRanges,positiveParallelRanges,besideRanges[0]]),normalSize=getSize([negativeNormalRanges,positiveNormalRanges,besideRanges[1]]);function handle(ranges,dimensionAxis2,normalAxis2,dimensionSize2,normalSize2,direction=1){if(0===ranges.length)return[];const normalDirection=normalAxis2.direction(),{tracks:tracks,untreated:untreated}=function(ranges,maxTracks=3,minLen=1e-6){(ranges=ranges.map(d2=>d2.map(v2=>Number(v2.toFixed(3))))).sort((a2,b4)=>a2[0]-b4[0]),ranges=ranges.filter((range,i)=>{if(0===i)return!0;const prev=ranges[i-1];return!(Math.abs(range[0]-prev[0])<=1e-4&&Math.abs(range[1]-prev[1])<=1e-4)});const map=/* @__PURE__ */new Map;for(let i=0;i<ranges.length;i++){const range=ranges[i];for(let j=0;j<2;j++){const value=range[j],item=map.get(value);item?(0===item.mode&&1==j||1===item.mode&&0==j)&&(item.mode=2):map.set(value,{value:value,mode:j})}}let list=Array.from(map.values());list=list.filter((value,i)=>{if(0===i||i===list.length-1)return!0;switch(value.mode){case 0:return 1===list[i-1].mode;case 1:return 0===list[i+1].mode;case 2:return!0}return!1}).sort((a2,b4)=>a2.value-b4.value).filter((item,i,arr)=>0===i||i===arr.length-1||item.value-arr[i-1].value>minLen);const mainTrackRanges=[];for(let i=1;i<list.length;i++)mainTrackRanges.push([list[i-1].value,list[i].value,0]);const mainMap=/* @__PURE__ */new Map;list.forEach((item,i)=>mainMap.set(item.value,i));let others=[];ranges=ranges.filter(range=>{const startIndex=mainMap.get(range[0]),endIndex=mainMap.get(range[1]);return void 0!==startIndex&&void 0!==endIndex?1!==endIndex-startIndex:(others.push(range),!1)}),others.sort((a2,b4)=>-(a2[1]-a2[0])-(b4[1]-b4[0]));const tracks=[],trackSet=/* @__PURE__ */new Set;for(let i=0;i<maxTracks-1;i++){trackSet.clear();let currValue=-1/0;ranges.forEach((range,i2)=>{if(!(range[0]<currValue)){for(let j=i2+1;j<ranges.length;j++)if(ranges[j][1]<=range[1])return;trackSet.add(i2),currValue=range[1]}});const track=Array.from(trackSet.values()).map(i2=>ranges[i2]);tracks.push(track),ranges=ranges.filter((_,i2)=>!trackSet.has(i2)),others=others.filter(range=>{const index2=insertRangeIndex(track,range);return-1==index2||(track.splice(index2,0,range),!1)})}return others.push(...ranges),{tracks:[mainTrackRanges,...tracks],untreated:others}}(ranges,maxTracks,minLen/dimensionAxis2.length),height=(-1===direction?.5-normalSize2.min:normalSize2.max-.5)*normalAxis2.length;return untreated.forEach(d2=>besideLines.push(lines[d2[2]])),tracks.push([[dimensionSize2.min,dimensionSize2.max,0]]),tracks.filter(t2=>t2.length).map((track2,i)=>{let dimensionOffset=direction*(.2*i+height+1.4),dimensionLine=new LineSegment(dimensionAxis2.pointAt(dimensionSize2.min),dimensionAxis2.pointAt(dimensionSize2.max));dimensionLine.translate(dimensionOffset,normalDirection);const result={track:{start:dimensionLine.start.toJson2D(),end:dimensionLine.end.toJson2D()},fragments:[]};return track2.forEach(([start,end,index2])=>{const points=[dimensionAxis2.pointAt(start),dimensionAxis2.pointAt(end)].map(point2=>(point2.x+=normalDirection.x*dimensionOffset,point2.y+=normalDirection.y*dimensionOffset,point2)),length=points[1].distance(points[0]);result.fragments.push({start:points[0].toJson2D(),end:points[1].toJson2D(),length:length,index:index2})}),result})}const results=[handle(negativeParallelRanges,dimensionAxis,normalAxis,dimensionSize,normalSize,-1),handle(positiveParallelRanges,dimensionAxis,normalAxis,dimensionSize,normalSize,1),handle(negativeNormalRanges,normalAxis,dimensionAxis,normalSize,dimensionSize,-1),handle(positiveNormalRanges,normalAxis,dimensionAxis,normalSize,dimensionSize,1)],track={track:{start:{x:0,y:0},end:{x:0,y:0}},fragments:[]};results.push([track]);const drawSegmentRuler=(line,point2)=>{const direct=point2.directionFrom(line.center),ruler=line.clone().translate(besideLineOffset,direct);track.fragments.push({start:ruler.start.toJson2D(),end:ruler.end.toJson2D(),length:ruler.length,index:0})},lsh=LineSegmentSpatialHash.from([.../* @__PURE__ */new Set([...besideLines,...lines])]),queryLine2=new LineSegment;for(const line of besideLines){let pos=null;if(besideLinesPosFunc&&(pos=besideLinesPosFunc(line,lsh)),"discard"!==pos){if(!pos){const step=line.normal().multiplyScalar(2*besideLineOffset),center=line.center;queryLine2.start.copy(center),queryLine2.end.copy(center).add(step);const result=[];let results2=lsh.queryLine(queryLine2).filter(l=>l!==line);if(0===results2.length&&result.push(queryLine2.center.clone()),queryLine2.end.copy(center).add(step.multiplyScalar(-1)),results2=lsh.queryLine(queryLine2).filter(l=>l!==line),0===results2.length&&result.push(queryLine2.center.clone()),2===result.length){const countList=result.map(p2=>{const projpoint=line.projectPoint(p2,!1),dist=p2.distance(projpoint),ql=line.clone().translate(dist,p2.directionFrom(projpoint));return ql.setLength(ql.length+.001),lsh.queryLine(ql).length}),[c1,c22]=countList;if(c1+c22===0)pos=result[0];else{if(c1===c22)continue;pos=c1<c22?result[0]:result[1]}}else pos=result[0]}pos&&drawSegmentRuler(line,pos)}}return results}}function getHoleLine(line){const holeLines=WallHoleDrawData.singleHoleLine(line)??[];return holeLines.forEach(holeLine=>{holeLine.userData.wallWidth=line.userData.wallWidth??holeLine.userData.wallWidth}),{lines:LineSegmentUtils.clippingByLines(line,holeLines,clippingLineUserData),holeLines:holeLines}}const SIDE_KEY=/* @__PURE__ */Symbol("SIDE_KEY");class DxfDataPlugin extends Pipeline{manager;lines=[];wallWidthLine=[];wallLengthLine=[];holeLine=[];constructor(lines){super(),lines=lines.filter(line=>!(line.userData.boundExtAppendLine&&Math.abs(line.length-(line.userData.boundExtAppendLineLen??0))<1e-6)),lines=builtinFun.DoubleWallAlignment(lines),this.use({type:"bayWindow",handle:this.bayWindow.bind(this)}),this.use({type:"wall",handle:this.wall.bind(this)}),this.use({type:"railing",handle:this.railing.bind(this)}),this.use({type:"pillar",handle:this.pillar.bind(this)}),this.use({type:"hole",handle:this.hole.bind(this)}),this.lines=lines,this.manager=WallGroupManager.fromByLines1_5(lines)}bayWindow({data:{lines:lines},cache:{cad:cad2}}){const center=LineSegmentUtils.getLinesCenter(lines);lines=lines.filter(line=>line.userData.isBayWindow?(cad2.addGroup([line],"bayWindow"),!1):!LineGroupType.hasType(line,"doubleWall"));const psh=PointSpatialHash.fromByLines(lines),visited=/* @__PURE__ */new Set,relationshipTable=[];lines.forEach(line=>line.points.forEach(point2=>{if(visited.has(point2))return;const result=psh.queryPoint(point2,!0).filter(r2=>r2.userData?.isPerpendicularTo(line,35));result.length&&(relationshipTable.push({l1:line,p1:point2,l2:result[0].userData,p2:result[0].point}),visited.add(point2).add(result[0].point))})),lines.forEach(line=>{const projPoint=line.projectPoint(center,!1);if(projPoint){const direction=projPoint.directionFrom(center);line.translate(.5*DEFAULT_WALL_WIDTH,direction)}}),relationshipTable.forEach(({l1:l1,p1:p1,l2:l2,p2:p2})=>{const point2=l1.getIntersection(l2);point2&&(p1.copy(point2),p2.copy(point2))}),lines.forEach(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);cad2.addGroup(lines2,"wall",{bayWindow:!0}),this.manager.add({type:"hole",lines:holeLines})})}wall({data:{lines:lines},cache:{cad:cad2}}){let{doubleWall:doubleWall=[],wall:wall=[]}=LineSegmentUtils.group(lines,line=>line.currentData.doubleWall?"doubleWall":"wall");const holes=[];doubleWall=doubleWall.flatMap(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);return holes.push(...holeLines),lines2}),doubleWall.flatMap(line=>{const lines2=line.toRectangle(line.userData.wallWidth,"butt").toLines();cad2.addGroup(lines2,"doubleWall")}),wall=wall.flatMap(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);return holes.push(...holeLines),lines2}),cad2.addGroup(wall,"wall"),this.manager.add({type:"hole",lines:holes})}railing({cache:{cad:cad2},data:{lines:lines}}){cad2.addGroupAndOffset(lines,{offsetHalfWidth:.025,type:"balconyRailing"}),cad2.addGroup(lines.flatMap(line=>{const dirct=line.normal(),moveDirct=line.direction(),length=line.length,newLine=line.start.expandAsLine(dirct,.05).translate(.025,dirct.multiplyScalar(-1)),distance2=length/4,count2=Math.floor(length/distance2),lines2=[];for(let i=1;i<=count2;i++)lines2.push(newLine.clone().translate(i*distance2,moveDirct));return lines2}),"balconyRailing")}pillar(ctx){try{ctx.cache.cad.addGroups([ctx.data.lines],"pillar");let poly=Polygon.fromByLines2(ctx.data.lines).getMinimumBoundingRectangle();if(poly){const line1=new LineSegment(poly[0],poly[1]),line2=new LineSegment(poly[1],poly[2]);this.wallWidthLine.push(line1,line2)}}catch(error){this.manager.add({type:"wall",lines:ctx.data.lines})}}hole({cache:{cad:cad2},data:{lines:lines}}){lines.forEach(line=>{switch(line.userData.type){case"beam":cad2.addGroup([line],"beam");break;case"door":cad2.addGroup([line],"door");break;case"window":cad2.addGroup([line],"window");break;case"byWindow":const{structure:structure}=WallHole.byWindowStructure(line,line.userData);this.manager.add({type:"bayWindow",lines:structure});break;default:cad2.addGroup([line],"passageEntrance")}})}dimensionLine(cad2){const besideLines=[...this.holeLine,...this.wallWidthLine].filter(line=>line.length>.1),lines=[...this.wallLengthLine],data=DimensionLine.build(lines,{maxTracks:3,besideLines:besideLines}),leaderLine=data.pop();data.forEach(list=>list.forEach(track=>{let trackLine=LineSegment.from(track.track);const fragmentLines=track.fragments.map(fragment=>LineSegment.from(fragment));let trackLines=LineSegmentUtils.clippingByLines(trackLine,fragmentLines);trackLines&&cad2.addGroup(trackLines,"dimensionLine"),cad2.addGroup(fragmentLines,"dimensionFragmentLine")})),leaderLine?.forEach(track=>{const fragmentLines=track.fragments.map(fragment=>LineSegment.from(fragment));cad2.addGroup(fragmentLines,"leaderLine")})}finally(cad2){const walls=cad2.filterGroups(g=>"wall"!=g.type).flatMap(g=>g.lines),holes=cad2.findGroups(g=>["beam","door","window","passageEntrance"].includes(g.type)).flatMap(g=>g.lines),modifier=PointUtils.createDeferredModifier();!function(lines,avoidanceTargets,modifier){const lsh=LineSegmentSpatialHash.from(avoidanceTargets);lines.forEach(line=>{line.points.forEach(point2=>{if(lsh.queryPoint(point2).filter(result=>result!==line&&result.isPerpendicularTo(line,35)).length){const step=line.getAnotherPoint(point2).directionFrom(point2).multiplyScalar(.5*DEFAULT_WALL_WIDTH);modifier.add(point2,[step.x,step.y])}})})}(holes,walls,modifier),function(lines,avoidanceTargets,modifier){const psh=PointSpatialHash.fromByLines([...lines,...avoidanceTargets]),avoidanceTargetsSet=new Set(avoidanceTargets);lines.forEach(line=>{line.points.forEach(point2=>{let relation=0;if(psh.queryCircle(point2,1e-4).filter(result=>result.userData!==line).forEach(result=>{const target=result.userData;avoidanceTargetsSet.has(target)?target.isPerpendicularTo(line,25)&&(relation|=1):target.isParallelTo(line,45)&&(relation|=2)}),!(2&~relation))return;if(1&~relation)return;const otherPoint=line.getAnotherPoint(point2),step=point2.directionFrom(otherPoint).multiplyScalar(.5*DEFAULT_WALL_WIDTH);modifier.add(point2,[step.x,step.y])})})}(walls,holes,modifier),modifier.apply(),this.holeLine.push(...LineSegmentUtils.clone(holes));const groups=LineSegmentUtils.group(walls,line=>line.userData.wallWidth??DEFAULT_WALL_WIDTH);Object.keys(groups).forEach(key=>{const lines=groups[key];LineSegmentUtils.groupByLeafPath(lines).forEach(lines2=>{cad2.addGroupAndOffset([...lines2],{type:"wall",offsetHalfWidth:.5*Number(key)})})}),cad2.unionGroup(g=>"wall"===g.type||"doubleWall"===g.type,{type:"wall",connectingBridge:!1});let walls2=cad2.filterGroups(g=>"wall"!==g.type).flatMap(item=>item.lines);cad2.addGroup(walls2,"wall");const{widthLines:widthLines,lengthLines:lengthLines}=function(lines){const psh=PointSpatialHash.fromByLines(lines),hasLongerPerpendicularSegment=(point2,line)=>{const list=psh.queryPoint(point2,!0).filter(target=>target.userData.length>line.length).filter(target=>target.userData.isPerpendicularTo(line,25)),side=list.map(l=>line.getPointSideOfLine(l.userData.center));return{is:list.length>0,side:new Set(side)}},widthLines=[],lengthLines=lines.filter(line=>{const sideList=[];for(const point2 of line.points){const{is:is2,side:side}=hasLongerPerpendicularSegment(point2,line);if(sideList.push(side),!is2)return!0}return widthLines.push(line),line.currentData[SIDE_KEY]=new Set(sideList.flatMap(set2=>[...set2.values()].filter(v2=>"on"!==v2))),!1});return{widthLines:widthLines,lengthLines:lengthLines}}(walls2);this.wallWidthLine.push(...widthLines),this.wallLengthLine.push(...lengthLines)}install(cad2){const config={cad:cad2};this.manager.forEach(group2=>{const option={lines:group2.lines};this.run(group2.type,option,config),group2.lines=option.lines}),this.finally(cad2),this.dimensionLine(cad2)}}class DxfDrawPlugin{dimension=!1;constructor(dimension=!1){this.dimension=dimension}getArcAngleRange(center,p1,p2){const x1=p1.x-center.x,y1=p1.y-center.y,x2=p2.x-center.x,y2=p2.y-center.y;let r1,r2,angle1=Math.atan2(y1,x1),angle2=Math.atan2(y2,x2);angle1=angle1<0?angle1+2*Math.PI:angle1,angle2=angle2<0?angle2+2*Math.PI:angle2;return Math.abs(angle2-angle1)<=Math.PI?(r1=Math.min(angle1,angle2),r2=Math.max(angle1,angle2)):(r1=Math.max(angle1,angle2),r2=Math.min(angle1,angle2)+2*Math.PI),[r1/(Math.PI/180),r2/(Math.PI/180)]}install(cad2){cad2.addDrawHandler({type:["wall"],handler({group:group2,drawLine:drawLine,setColor:setColor}){setColor("white"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["pillar"],handler({drawLine:drawLine,setColor:setColor,group:group2}){setColor("white"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["door"],handler:({group:group2,drawArc:drawArc,drawLine:drawLine,setColor:setColor})=>{group2.lines.forEach(lineSegment=>{const line=lineSegment.clone(),doorThickness=.2*DEFAULT_WALL_WIDTH,list=[];if(setColor("yellow"),line.length<1.5){line.extendAlongDirection(.5*-doorThickness);const normal=lineSegment.normal();lineSegment.userData.openDirect&&normal.angle(lineSegment.userData.openDirect,{unit:"degree",range:"180"})>90&&normal.multiplyScalar(-1);let door=new LineSegment(line.start.clone(),line.start.clone().add(normal.clone().multiplyScalar(line.length)));const box=door.clone().translate(-.5*line.length,door.normal()).toRectangle(line.length,"butt");for(let j=0;j<list.length;j++)if(list[j].intersectRectangle(box)){door=new LineSegment(line.start.clone(),line.start.clone().add(normal.clone().multiplyScalar(-line.length)));break}door.extendAlongDirection(.5*-doorThickness).toRectangle(.2*DEFAULT_WALL_WIDTH,"butt").path2D((p1,p2)=>drawLine(p1,p2));const a2=line.length,b4=door.length,r2=(a2**2+b4**2)/(2*b4),center=door.end.clone().add(door.direction().multiplyScalar(-r2)),[startAngle,endAngle]=this.getArcAngleRange(center,line.end,door.end);drawArc(center,r2,Math.min(startAngle,endAngle),Math.max(startAngle,endAngle)),list.push(box)}else line.clone().extendAlongDirection(.5*-DEFAULT_WALL_WIDTH).toRectangle(DEFAULT_WALL_WIDTH).path2D((p1,p2)=>drawLine(p1,p2)),line.clone().translate(.5*doorThickness,line.normal()).translate(.5*doorThickness,line.direction()).extendAlongDirection(.45*-line.length,"end").translate(.5*doorThickness).toRectangle(doorThickness).path2D((p1,p2)=>drawLine(p1,p2)),line.clone().translate(.5*-doorThickness,line.normal()).translate(.5*-doorThickness,line.direction()).extendAlongDirection(.45*-line.length,"start").translate(.5*-doorThickness).toRectangle(doorThickness).path2D((p1,p2)=>drawLine(p1,p2))})}}),cad2.addDrawHandler({type:["window"],handler:({group:group2,drawLine:drawLine,setColor:setColor})=>{setColor("cyan"),group2.lines.forEach(line=>{drawLine(line.start,line.end),line.toRectangle(line?.userData?.wallWidth??DEFAULT_WALL_WIDTH,"butt").path2D((p1,p2)=>drawLine(p1,p2))})}}),cad2.addDrawHandler({type:["bayWindow"],handler({drawDottedLine:drawDottedLine,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("cyan"),line=line.clone().extendAlongDirection(.5*-DEFAULT_WALL_WIDTH),drawDottedLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["balconyRailing"],handler({group:group2,setColor:setColor,drawLine:drawLine}){group2.lines.forEach(line=>{setColor("green"),drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["passageEntrance"],handler({group:group2,setColor:setColor,drawDottedLine:drawDottedLine}){group2.lines.forEach(line=>{setColor("white");const direction=line.normal(),width=line?.userData?.wallWidth??DEFAULT_WALL_WIDTH,line1=line.clone().translate(.5*width,direction),line2=line.clone().translate(.5*-width,direction);drawDottedLine(line1.start,line1.end),drawDottedLine(line2.start,line2.end),drawDottedLine(line1.start,line2.start),drawDottedLine(line1.end,line2.end)})}}),cad2.addDrawHandler({type:["beam"],handler({drawDottedLine:drawDottedLine,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("red");const width=line?.userData?.wallWidth??DEFAULT_WALL_WIDTH;if(width!=DEFAULT_WALL_WIDTH){const direction=line.normal(),line1=line.clone().translate(.5*width,direction),line2=line.clone().translate(.5*-width,direction);drawDottedLine(line1.start,line1.end),drawDottedLine(line2.start,line2.end),drawDottedLine(line1.start,line2.start),drawDottedLine(line1.end,line2.end)}else drawDottedLine(line.start,line.end)})}}),!0!==this.dimension&&"out"!==this.dimension||(cad2.addDrawHandler({type:["dimensionLine"],handler({drawLine:drawLine,setColor:setColor,group:group2}){setColor("ruler_deep"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["dimensionFragmentLine"],handler({drawLine:drawLine,drawText:drawText2,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("ruler_deep"),drawLine(line.start,line.end);const dirct=line.direction(),l1=line.clone().rotate(.5*Math.PI);l1.setLength(.1);const l2=l1.clone();if(setColor("ruler"),l1.translate(.5*line.length,dirct),drawLine(l1.start,l1.end),l1.rotate(Math.PI/180*-35),drawLine(l1.start,l1.end),l2.translate(.5*-line.length,dirct),drawLine(l2.start,l2.end),l2.rotate(Math.PI/180*-35),drawLine(l2.start,l2.end),line.length>.12){setColor("text");const dirct2=line.direction();(line.start.x>line.end.x||line.start.x===line.end.x&&line.start.y>line.end.y)&&dirct2.multiplyScalar(-1);let angle=Math.atan2(dirct2.y,dirct2.x);angle/=Math.PI/180,drawText2((1e3*line.length).toFixed(0),line.center,{rotation:angle,fontSize:.01})}})}})),!0!==this.dimension&&"in"!==this.dimension||cad2.addDrawHandler({type:["leaderLine"],handler({drawLine:drawLine,drawText:drawText2,setColor:setColor,group:group2}){group2.lines.forEach(line=>{if(line.length<.12)return;setColor("ruler_deep"),drawLine(line.start,line.end);const dirct=line.direction(),l1=line.clone().rotate(.5*Math.PI);l1.setLength(.08);const l2=l1.clone();setColor("ruler"),l1.translate(.5*line.length,dirct),drawLine(l1.start,l1.end),l2.translate(.5*-line.length,dirct),drawLine(l2.start,l2.end);{setColor("text");const dirct2=line.direction();(line.start.x>line.end.x||line.start.x===line.end.x&&line.start.y>line.end.y)&&dirct2.multiplyScalar(-1);let angle=Math.atan2(dirct2.y,dirct2.x);angle/=Math.PI/180,drawText2((1e3*line.length).toFixed(0),line.center,{rotation:angle,fontSize:.001})}})}})}}const cad={CAD:CAD,DxfDataPlugin:DxfDataPlugin,DxfDrawPlugin:DxfDrawPlugin};function doubleWallAlignmentFun(lines){const singleWall=lines.filter(line=>!LineGroupType.hasType(line,"doubleWall")&&!line.userData.isDoor),doorLines=lines.filter(line=>line.userData.isDoor),grid=Quadtree.from(singleWall.filter(line=>!line.userData.isDoor)),allGrid=PointSpatialHash.fromByLines(lines),doubleWalls=LineGroupType.getGroupsByType(lines,"doubleWall"),offset=.5*-DEFAULT_WALL_WIDTH,tree=Quadtree.from(doubleWalls.flat());return(lines=splitIntersectedLine(lines=[singleWall,doubleWalls.flatMap(doubleWall=>{const poly=Polygon.fromByLines2(doubleWall);Polygon.ensureCCW(poly),poly.toLines().forEach(line=>{const list=tree.queryCircle(line.center,1e-6);list.length&&(list[0].line.start.copy(line.start),list[0].line.end.copy(line.end),list[0].line.points.forEach(p2=>allGrid.update(p2)))});const expLines=doubleWall.filter(line=>{if(line.length<.001)return!1;for(let i=0;i<line.points.length;i++){const point2=line.points[i];let list=grid.queryPoint(point2);if(1===list.length&&(list=grid.queryPoint(point2).filter(item=>item.userData?.isParallelTo(line)),1===list.length))return!0}return!1});return[expLines.flatMap(line=>{const normal=line.normal(),id=LineGroupType.getIdByType(line,"doubleWall");let step=normal.multiplyScalar(offset);const newLines2=[],old_line=line.clone();return line.points.forEach(p2=>{const newPoint=p2.clone().add(step);let newLine=((point2,newPoint,line)=>{let list=allGrid.queryPoint(point2,!0),direct=newPoint.directionFrom(point2),isParallel2=!1;if(list=list.filter(item=>!item.userData.isParallelTo(line,25)||(isParallel2=!0,!1)),list.forEach(item=>{const direct2=item.userData.getAnotherPoint(item.point).directionFrom(item.point);direct.angle(direct2,{unit:"degree",range:"180"})>145&&isParallel2||(item.point.copy(newPoint),allGrid.update(item.point))}),isParallel2){let newLine=(new LineSegment).set(point2,newPoint);return allGrid.insert(newLine.start,newLine).insert(newLine.end,newLine),point2.copy(newPoint),newLine}point2.copy(newPoint)})(p2,newPoint,old_line);newLine&&newLines2.push(newLine)}),allGrid.update(line.start),allGrid.update(line.end),newLines2.forEach(newLine=>{LineGroupType.set(newLine,id,"doubleWall")}),newLines2}),doubleWall].flat(10)})].flat(10))).push(...doorLines),WallHole.filterIllegal(lines),lines.filter(line=>line.length>1e-4)}const point=new Point;class HeightQuery{static query(line,rootTopContourInfo){const inLinePoints=[],len=line.length,newLine=line.clone(),center=line.center;newLine.offsetStart(.2*len),newLine.offsetEnd(.2*len),inLinePoints.push([center.x,center.y],[newLine.start.x,newLine.start.y],[newLine.end.x,newLine.end.y]);const contoursData=this.whichContourContainsPoint(inLinePoints,rootTopContourInfo);contoursData.sort((a2,b4)=>b4.averagePz-a2.averagePz);return contoursData[0]?.averagePz??2.8}static whichContourContainsPoint(points,rootTopContourInfo){const contoursData=[],{contours:contours,maxContourIndex:maxContourIndex,quadtree:quadtree}=rootTopContourInfo;return points.filter(p2=>{point.set(p2[0],p2[1]);for(let i=0;i<contours.length;i++){const{contour:contour,polygon:polygon2}=contours[i];contour.length&&i!==maxContourIndex&&(polygon2?.pointIn(point)&&contoursData.push({i:i,averagePz:contours[i].averagePz}))}}),contoursData.length||points.filter(p2=>{point.set(p2[0],p2[1]),new Array(...new Set(quadtree?.queryCircle(point,.6).map(item=>item.line.currentData.contourIndex))).forEach(index2=>{index2!==maxContourIndex&&contoursData.push({i:index2,averagePz:contours[index2].averagePz})})}),contoursData}}const builtinFun={init:function(lines,option){const group2=WallGroupManager.createGroup(lines);return lines=LineSegmentUtils.GroupBuilder(group2).handleAll(lines2=>{const map=new ArrayMap;lines2.forEach(line=>{const width=line.userData.wallWidth??DEFAULT_WALL_WIDTH;map.append(width,line)});const newLines=[];return map.forEach(lines3=>{newLines.push(...function(lines){let defaultLines=[],doorLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isDoor?doorLines.push(line):defaultLines.push(line)}return defaultLines=mergeChainsLine(defaultLines),doorLines=mergeChainsLine(doorLines),[...defaultLines,...doorLines]}(lines3))}),newLines}).handle("wall",lines2=>(lines2=splitIntersectedLine(lines2,1e-9,{balconyRailing:{behavior:"discard",filteringRatio:.2}}),WallHole.filterIllegal(lines2).merge(lines2),lines2)).merge(),option.trajectory&&(sparse(option.trajectory,.2),sparse(option.trajectory,.5),function(lines,trajectory2){const holeLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];for(const hole of WallHole.getIterator(line))if("door"===hole.type||"passageEntrance"===hole.type){const holeLine=WallHole.holeDataToLine(line,hole);holeLines.push(holeLine)}}const lsh=LineSegmentSpatialHash.from(holeLines),p2=new Point;Object.keys(trajectory2).forEach(k=>{Point.from(trajectory2[k],p2);const dircts=lsh.queryPoint(p2,.3).map(line=>{const pp=line.projectPoint(p2);if(pp)return pp.directionFrom(p2)}).filter(p22=>!!p22);for(let i=0;i<dircts.length;i++){const dirct1=dircts[i];for(let j=0;j<dircts.length;j++){const dirct2=dircts[j];if(dirct1.dot(dirct2)<0)return void delete trajectory2[k]}}})}(lines,option.trajectory)),BuildGroup.doubleWall.setTrajectory(option.trajectory),lines.forEach(line=>{for(const hole of WallHole.getIterator(line))hole.uuid||(hole.uuid=uuid())}),lines},DoorToHole:function(lines,option){return lines.forEach(line=>{line.userData.isDoor&&(delete line.userData.isDoor,line.userData.isPassageEntrance=!0,line.userData.passageEntrance=[{p:line.center.toJson(option?.originalZ),width:line.length,full:!1,groundClearance:line.userData.drawDoorData?.groundClearance,type:"door",height:line.userData.drawDoorData?.height??Math.min(2,.8*(line.userData?.height??line.length))}])}),lines},AxisAlignCorr:function(lines,option,verticalReferenceLine){if(!(verticalReferenceLine=verticalReferenceLine??LineSegmentUtils.findDominantDirectionLine(lines)))return console.error("未找到一条垂直纠正基准轴线, 未做垂直纠正处理"),lines;const t2=performance.now();return lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle(["wall","railing"],lines2=>function(lines,targettLine,option){return lines=preprocessing(lines),lines=splitIntersectedLine(lines=AxisAlignCorr.start(lines,targettLine),1e-9),WallHole.miniWidthFilter(lines).filterIllegal(lines).merge(lines),lines=removeDangline(lines=splitIntersectedLine(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",lines2=>(lines2=AlignToParallelSegments.align(lines2,{...alignConfig(),gap:option?.alignGroupGap,esp:option?.alignGroupEsp}),WallHole.merge(lines2),adsorption(lines2,option))).handle("railing",lines2=>AlignToParallelSegments.align(lines2)).merge(),1e-9),.1,!1),WallHole.miniWidthFilter(lines),lines=removeDangline(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",newLines=>{newLines=BuildGroup.bayWindow(newLines,!1);const{wallGroup:wallGroup=!0}=option??{};return wallGroup&&(newLines=breakpointMerging$1(newLines=DoubleWallFinder.buildGroup(newLines)),newLines=BuildGroup.bayWindow(newLines,!1)),newLines}).merge(),.15,!0),WallHole.merge(lines).miniWidthFilter(lines),lines.filter(line=>line.length>1e-9)}(lines2,verticalReferenceLine,option)).handle("pillar",(lines2,group2)=>function(lines,group2,option){return LineGroupType.getGroupsByType(lines,"pillar").flatMap(lines2=>{if(4===(lines2=breakpointMerging$1(lines2)).length){const verticalReferenceLine=LineSegmentUtils.findDominantDirectionLine(lines2);lines2=adsorption(lines2=AxisAlignCorr.start(lines2,verticalReferenceLine),option,group2.wall)}const id=uuid();return lines2.forEach(line=>LineGroupType.set(line,id,"pillar")),lines2})}(lines2,group2,option)).handle("beam",(lines2,group2)=>function(lines,verticalReferenceLine,group2,option){return lines=AxisAlignCorr.start(lines,verticalReferenceLine),lines=adsorption(lines=AlignToParallelSegments.align(lines,{...alignConfig({max_wall_width:.8}),onMergeLine:(target,source)=>{const maxHeight=Math.max(target.userData.height??0,source.userData.height??0);mergeLineUserData(target,source),maxHeight&&(target.userData.height=maxHeight),target.userData.tags=target.userData.tags??[],target.userData.tags.push("merge")},esp:.8}),option,group2.wall),WallHole.merge(lines),lines}(lines2,verticalReferenceLine,group2,option)).merge(),console.log("垂直纠正耗时:",performance.now()-t2),lines},DoorFind:lines=>new DoorFind(lines).getLines(),BoundExt:function(lines,{trajectory:trajectory2,onBoundExt:onBoundExt}){if(!trajectory2)return console.error("没有传入轨迹文件"),lines;let t2=performance.now();return lines=BoundExt.boundExtbyTraj({lines:lines,trajectory:trajectory2,wallWidth:DEFAULT_WALL_WIDTH,findCallBack:onBoundExt}).lines,console.log(`外墙外扩总消耗时间: ${(performance.now()-t2).toFixed(2)} ms 处理线段数量:`,lines.length),lines},DoubleWallAlignment:function(lines){return LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",doubleWallAlignmentFun).merge()},WallHeightHandle:function(lineSegments,option){if(option?.publicInfo?.rootTopContourInfo){const polygons=option.publicInfo.rootTopContourInfo.contours.map(item=>(item.polygon||Object.defineProperty(item,"polygon",{value:new Polygon(Point.fromByList(item.contour))}),item.polygon));if(!option.publicInfo.rootTopContourInfo.quadtree){const lines=polygons.flatMap((polygon2,index2)=>{const lines2=polygon2?.toLines()??[];return lines2.forEach(line=>line.currentData.contourIndex=index2),lines2}),quadtree=Quadtree.from(lines);Object.defineProperty(option.publicInfo.rootTopContourInfo,"quadtree",{value:quadtree})}}const psh=PointSpatialHash.fromByLines(lineSegments);return lineSegments.forEach(line=>{if(!("height"in line.userData)){if(!line.userData.rooftopPz&&option?.publicInfo?.rootTopContourInfo){const list=psh.queryPoints(line.points,!0).map(item=>item.userData?.userData.rooftopPz??0);list.length?line.userData.rooftopPz=Math.max(...list):line.userData.rooftopPz=HeightQuery.query(line,option.publicInfo.rootTopContourInfo)}"rooftopPz"in line.userData&&(line.userData.height=Math.abs(line.userData.rooftopPz-(option.originalZ??0)))}}),lineSegments},DoorSpaceHandle:function(lineSegments){const noDoorLines=lineSegments.filter(line=>!line.userData.isDoor),quadtree=Quadtree.from(noDoorLines),pvg=PointSpatialHash.fromByLines(noDoorLines),doors=lineSegments.filter(line=>{if(!line.userData.isDoor)return!1;let startCount=pvg.queryPoint(line.start,!0).length,endCount=pvg.queryPoint(line.end,!0).length;return 0===startCount&&(startCount=quadtree.queryPoint(line.start).length),0===endCount&&(endCount=quadtree.queryPoint(line.end).length),0===startCount&&0===endCount||startCount>0&&endCount>0}),removeLines=[],appendLines=[];doors.forEach(doorLine=>{const length=doorLine.length,rectangle=doorLine.clone().extendAlongDirection(-.1,"all").toRectangle(.8,"butt"),results=quadtree.queryRect(rectangle).map(item=>{const projectLine=item.line.projectLineSegment(doorLine);return{...item,projectLine:projectLine,plLength:projectLine.length}}).filter(opt=>opt.projectLine.length/length>.7);results.sort((a2,b4)=>b4.plLength-a2.plLength),results.forEach(({line:line,projectLine:projectLine},i)=>{0===i&&doorLine.copy(projectLine);const lines=LineSegmentUtils.clippingByLine(line,projectLine);lines&&(removeLines.push(line),appendLines.push(...lines))})});const removeLinesSet=new Set(removeLines);return(lineSegments=lineSegments.filter(line=>!removeLinesSet.has(line))).push(...appendLines),lineSegments},RemoveShortDoubleWall:function(lineSegments){const doubleWalls=LineGroupType.getGroupsByType(lineSegments,"doubleWall"),freePointLines=[...findDiscretePointLine2(lineSegments)].filter(line=>line.length<.3),grid=PointSpatialHash.fromByLines(doubleWalls.flat(4)),lines=freePointLines.filter(line=>grid.queryPoint(line.start).length>0||grid.queryPoint(line.end).length>0),removeSet=new Set(lines);return lineSegments.filter(line=>!removeSet.has(line))},BeamSupportLine:function(lines,{}){const lsh=Quadtree.from(lines.filter(line=>!line.userData.isBalconyRailing));return lines.forEach(line=>{if(!line.userData.wallWidth&&WallHole.isBeam(line)){const findLine=line.clone();findLine.setLength(findLine.length-.002);let rectangle=findLine.toRectangle(2,"butt");const center=findLine.center,beamNearWallVec=function(line){const iterator=WallHole.getIterator(line);for(const hole of iterator)if("beamNearWallVec"in hole)return Point.from(hole.beamNearWallVec)}(line),list=lsh.queryRect(rectangle).filter(target=>{if(target.line===line)return!1;if(!target.line.isParallelTo(findLine,10))return!1;if(beamNearWallVec){if(target.line.center.directionFrom(center).dot(beamNearWallVec)<0)return!1}return!0}).map(item=>item.line).sort((a2,b4)=>a2.distanceToPoint(center)-b4.distanceToPoint(center));if(list.length){const point2=list[0].projectPoint(center,!1);line.userData.expansionWidth=Math.max(point2.distance(center),DEFAULT_WALL_WIDTH),line.userData.expansionDirction=point2.directionFrom(center).toJson2D()}}}),lines},RemoveRoomSundries:function(lines,{trajectory:trajectory2}){return trajectory2&&(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",lines2=>{const rooms=findRooms(lines2,trajectory2,{clone:!1,split:!1}),counterMap=new CounterMap;findDiscretePoint(lines2).forEach(l=>counterMap.increment(l));const ls2=counterMap.getByCount(2);ls2.push(...lines2.filter(line=>line.userData.isBalconyRailing));let removeLines=[...new Set(ls2)].filter(line=>{const center=line.center;return!!rooms.find(room=>room.ploy.pointWithin(center)&&!room.lines.find(l=>l==line))});const set2=new Set(removeLines);return lines2=lines2.filter(line=>!set2.has(line))}).merge()),lines},BaywindowToHole:function(lines,_){const{walls:walls=[],bayWindows:bayWindows=[]}=LineSegmentUtils.group(lines,line=>LineGroupType.hasType(line,"bayWindow")?"bayWindows":"walls"),appends=[];return LineGroupType.getGroupsByType(bayWindows,"bayWindow").forEach(bayWindows2=>{bayWindows2=mergeChainsLine(bayWindows2=splitIntersectedLine(bayWindows2,0),mergeLineUserData),bayWindows2=MaxiCircles.instance.maxiCircles(bayWindows2).circles.sort((a2,b4)=>b4.length-a2.length)[0];let{walls:walls2=[],path:path=[]}=LineSegmentUtils.group(bayWindows2,line=>line.userData.isBayWindow?"walls":"path");if(!walls2.length)return appends.push(...bayWindows2);if(path.length<3)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);const windowIndex=path.findIndex(line=>line.userData.isWindow),wall=walls2[0];if(-1===windowIndex)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);const windowLine=path[windowIndex],windowHole=windowLine.userData.drawWindow?.[0];if(!windowHole)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);if(delete wall.userData.isBayWindow,LineGroupType.clear(wall),path.length<=4){let h2=0,dirct=Point.zero();return path.flatMap(line=>line.points.forEach(p2=>{const dist=wall.distanceToPoint(p2);if(dist>h2){h2=dist;const proP=wall.projectPoint(p2,!1);p2.directionFrom(proP,dirct)}})),WallHole.addHole(wall,{p:wall.center.toJson(),width:wall.length,full:!1,type:"byWindow",groundClearance:windowHole.groundClearance,height:windowHole.height,extrusion:{direction:dirct.toJson(),distance:h2}}),void appends.push(wall)}const ploy=Polygon.fromByLines2(path),center=windowLine.center;let index2=0;for(let i=0;i<ploy.length-1;i++){const point1=ploy[i],point2=ploy[i+1],center2=point1.clone().add(point2).multiplyScalar(.5);if(center.distanceSquared(center2)<1e-4){index2=i;break}}WallHole.addHole(wall,{p:wall.center.toJson(),width:wall.length,full:!1,type:"byWindow",groundClearance:windowHole.groundClearance,height:windowHole.height,shape:{path:ploy.map(p2=>p2.toJson2D()),fragmentAttr:[{type:"window",index:index2}]}}),appends.push(wall)}),[...walls,...appends]},SplitCollinearWallsAndBeams:function(lineSegments,_){return lineSegments=lineSegments.flatMap(lineSegment=>{let ranges=[],holeDatas=[...WallHole.getIterator(lineSegment)];for(const holeData of holeDatas)if("beam"===holeData.type){const holeLine=WallHole.holeDataToLine(lineSegment,holeData),startV=lineSegment.projectPointValue(holeLine.start),endV=lineSegment.projectPointValue(holeLine.end);ranges.push(startV<endV?[startV,endV]:[endV,startV])}if(0===ranges.length)return[lineSegment];ranges=RangeCore.union(ranges);const points=ranges.flatMap(range=>range.map(t2=>lineSegment.pointAt(t2))),lines=LineSegmentUtils.clippingByPoints(lineSegment,points,line=>{WallHole.clear(line)});return WallHole.splitHoleByProjectPoint(lineSegment,lines),holeDatas.forEach(holeData=>holeData.full=!0),lines})}};class LinePipeline extends Pipeline{static get builtin(){return builtinFun}fronts=[];nofront=!0;constructor(){super()}add(handle,index2){if("number"==typeof index2){const list=this.map.get("LINE");if(list)return index2=Math.max(0,Math.min(index2,list.length)),list.splice(index2,0,{type:"LINE",handle:ctx=>{ctx.data=handle(ctx.data,ctx.cache)}}),this}return this.use({type:"LINE",handle:ctx=>{ctx.data=handle(ctx.data,ctx.cache)}}),this}clear(){return super.clear(),this.nofront=!0,this}execute(data,option){return this.nofront&&(this.fronts.forEach(fun=>this.add(fun,0)),this.nofront=!1),super.run("LINE",data,option)}}class Dxf extends Component{static name="Dxf";originalData=[];data=[];box=new Box2(0,0,0,0);cadQueue=/* @__PURE__ */new Map;angle=0;lineSegments=[];verticalReferenceLine;originalZAverage=0;linePipeline=new LinePipeline;get lines(){return this.lineSegments}constructor(){super(),this.linePipeline.fronts.push(LinePipeline.builtin.init,LinePipeline.builtin.WallHeightHandle,LinePipeline.builtin.SplitCollinearWallsAndBeams,LinePipeline.builtin.DoorToHole,LinePipeline.builtin.BaywindowToHole)}getLineSegments(clone2=!1){let lines=this.lineSegments;return clone2&&(lines=lines.map(line=>line.clone(!0,!0))),lines}preprocessing(data,options){let{lineSegments:lineSegments,originalZAverage:originalZAverage}=originalDataToLineData(data);return this.originalZAverage=originalZAverage,options.originalZ=options.originalZ??originalZAverage,lineSegments=this.linePipeline.execute(lineSegments,options),this.verticalReferenceLine=LineSegmentUtils.findDominantDirectionLine(lineSegments),this.verticalReferenceLine.userData.isVerticalReferenceLine=!0,{lineSegments:lineSegments,data:data}}options={};rooms=[];async set(data,options={}){if("string"==typeof data){if("undefined"!=typeof global){const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(data),json=JSON.parse(buffer.toString("utf-8"));return this.set(json,options)}throw new Error("非node环境不允许使用路径")}if(0===data.length)return;if(this.cadQueue.clear(),this.options=options,0===data.length)this.lineSegments=[],this.originalData=data;else{const res=this.preprocessing(data,options);data=res.data,this.lineSegments=res.lineSegments,this.originalData=data}const zList=[];data.forEach(({start:start,end:end})=>zList.push(start.z??0,end.z??0)),this.originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length,this.box=Box2.fromByLineSegment(...this.lineSegments),this.rooms=findRooms(this.lineSegments,options.trajectory),this.dispatchEvent({type:"dataChange",originalData:this.originalData,data:this.data,options:options}),this.dispatchEvent({type:"setDta",originalData:this.originalData,data:this.data,options:options});let lines=this.getLineSegments(!0);const doors=lines.filter(line=>line.userData.isDoor);lines=lines.filter(line=>!line.userData.isDoor),lines=BuildGroup.doubleWall(lines),lines.push(...doors);const{cad:cad2}=this.generateCad(lines);this.dispatchEvent({type:"cadChange",cad:cad2,options:options}),this.dispatchEvent({type:"lineOffset",cad:cad2,options:options})}async setTrajectory(trajectory2,clear=!1){this.options.trajectory=trajectory2,await this.set(lineDataToOriginalData(this.getLineSegments(),this.originalZAverage),this.options),clear&&(this.options.trajectory=void 0)}generateCad(lines){const cad2=(new CAD).usePlugin(new DxfDataPlugin(lines)).usePlugin(new DxfDrawPlugin),dimensionCad=cad2.clone(!1).usePlugin(new DxfDrawPlugin(!0));this.cadQueue.set("cad",cad2),this.cadQueue.set("dimCad",dimensionCad);const degCorrCad=cad2.clone(),{angle:angle}=CAD.obliquity(degCorrCad);degCorrCad.rotateAndResetOrigin(angle),this.angle=angle;const dimensionCorrCad=degCorrCad.clone(!1).usePlugin(new DxfDrawPlugin(!0));return this.cadQueue.set("degCorrCad",degCorrCad),this.cadQueue.set("degCorrDimCad",dimensionCorrCad),{cad:cad2,dimensionCad:dimensionCad,degCorrCad:degCorrCad,dimensionCorrCad:dimensionCorrCad}}getCAD(cadName){return this.cadQueue.get(cadName)}toOriginalData(quadtree){return lineDataToOriginalData(this.getLineSegments(!0),this.originalZAverage,quadtree)}async downloadOriginalData(filename){const data=lineDataToOriginalData(this.getLineSegments(),this.originalZAverage),content=JSON.stringify(data);if("undefined"!=typeof window){const blob=new Blob([content],{type:"application/json"}),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,content)}}toDrawData(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDrawData(unit)}toDxfString(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfString(unit)}toDxfBlob(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfBlob(unit)}toDxfObject3D(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfObject3D(unit)}async downloadDxf(cadName,filename,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.downloadDxf(filename,unit)}async toDxfImageBlob(cadName,unit="Centimeters",type="image/jpeg",background="#000"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfImageBlob(unit,type,background)}async downloadDxfImage(cadName,filename,unit="Centimeters",type="image/jpeg"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return!cad2.downloadDxfImage(filename,unit,type)}}class BoundExtDxf extends Dxf{static name="BoundExtDxf";angle=0;constructor(){super(),this.linePipeline.fronts.length=0}onAddFromParent(parent){parent.Dxf.addEventListener("cadChange",e=>{e.options.trajectory&&this.linePipeline.add(LinePipeline.builtin.BoundExt),this.linePipeline.add(LinePipeline.builtin.DoubleWallAlignment);const lines=parent.Dxf.getLineSegments(!0);this.set(lineDataToOriginalData(lines,parent.Dxf.originalZAverage),{trajectory:e.options.trajectory,publicInfo:e.options.publicInfo,onBoundExt:e.options.onBoundExt}),this.linePipeline.clear()})}set(data,options={}){if(0===data.length)return;if(this.cadQueue.clear(),0===data.length)this.lineSegments=[],this.originalData=data;else{const res=this.preprocessing(data,options);data=res.data,this.lineSegments=res.lineSegments,this.originalData=data,this.lineSegments=LinePipeline.builtin.WallHeightHandle(this.lineSegments,options)}this.options=options;const zList=[];data.forEach(({start:start,end:end})=>zList.push(start.z??0,end.z??0)),this.lineSegments=function(lineSegments){let appendLines=[];const newHoleLines=[],clipLineMap=new ArrayMap,removeHoleMap=new ArrayMap,{matchQueues:matchQueues,originMap:originMap}=WallHole.buildPairing(lineSegments);matchQueues.forEach(matchQueue=>matchQueue.forEach(([holeLine1,holeLine2])=>{const line1=originMap.get(holeLine1),line2=originMap.get(holeLine2),newLine=LineSegmentUtils.mergeLinesByMaxlength(holeLine1,holeLine2);holeLine1.projectLineSegment(newLine,newLine),holeLine2.projectLineSegment(newLine,newLine);const clipLine1=line1.projectLineSegment(newLine),clipLine2=line2.projectLineSegment(newLine),appendLine1=new LineSegment(clipLine1.start,clipLine2.start),appendLine2=new LineSegment(clipLine1.end,clipLine2.end),newHoleLine=line1.clone().set(appendLine1.center,appendLine2.center);newHoleLine.userData.wallWidth=Math.max(appendLine1.length,appendLine2.length),newHoleLine.userData.tags=["hole-independent"],WallHole.clear(newHoleLine),WallHole.addHole(newHoleLine,holeLine1.userData),WallHole.addHole(newHoleLine,holeLine2.userData),WallHole.merge(newHoleLine),appendLines.push(appendLine1,appendLine2),newHoleLines.push(newHoleLine),clipLineMap.append(line1,clipLine1).append(line2,clipLine2),removeHoleMap.append(line1,holeLine1.userData).append(line2,holeLine2.userData)})),(lineSegments=lineSegments.flatMap(lineSegment=>{const clipLines=clipLineMap.get(lineSegment);if(clipLines){const newLines=LineSegmentUtils.clippingByLines(lineSegment,clipLines,clippingLineUserData);return newLines.forEach(line=>WallHole.clear(line)),WallHole.splitHoleByProjectPoint(lineSegment,newLines),WallHole.merge(newLines),newLines}return[lineSegment]})).push(...newHoleLines);let lsh=LineSegmentSpatialHash.from(lineSegments);return appendLines=appendLines.filter(line=>line.points.every(point2=>lsh.queryPoint(point2,1e-4).filter(res=>!res.userData.tags?.includes("hole-independent")).length>0)),appendLines=LineSegmentUtils.deduplicate(appendLines,{necessaryLines:lineSegments}),lineSegments.push(...appendLines),lineSegments}(LineSegmentUtils.clone(this.lineSegments)),this.originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length,this.box=Box2.fromByLineSegment(...this.lineSegments),this.dispatchEvent({type:"dataChange",originalData:this.originalData,data:this.data});let lines=this.getLineSegments(!0);lines=BuildGroup.doubleWall(lines);const{cad:cad2}=this.generateCad(lines);this.dispatchEvent({type:"cadChange",cad:cad2})}}class ExternalDataPipeline extends Pipeline{manager;index=0;lines;constructor(lines){super(),this.lines=lines,this.manager=WallGroupManager.fromByLines1_5(lines),this.use({type:"bayWindow",handle:this.bayWindow.bind(this)}),this.use({type:"wall",handle:this.wall.bind(this)}),this.use({type:"railing",handle:this.railing.bind(this)}),this.use({type:"pillar",handle:this.pillar.bind(this)}),this.use({type:"beam",handle:this.beam.bind(this)}),this.use({type:"holeBayWindow",handle:this.holeBayWindow.bind(this)})}wall({data:{lines:lines,json:json}}){lines.map(line=>{if(WallHole.isBeam(line))return void this.manager.add({type:"beam",lines:[line]});const holeDatas=[...WallHole.getIterator(line)];for(let i=0;i<holeDatas.length;i++)if("byWindow"===holeDatas[i].type&&!holeDatas[i].shape)return void this.manager.add({type:"holeBayWindow",lines:[line]});const id=uuid(),thickness=line.userData.wallWidth??DEFAULT_WALL_WIDTH,index2=json.walls.length;json.walls.push({id:id,start:line.start.toJson2D(),end:line.end.toJson2D(),thickness:thickness,height:line.userData.height??2.8}),holeDatas.forEach(holeData=>{const holeLine=WallHole.holeDataToLine(line,holeData);json.holes.push({id:uuid(),wallId:id,wallIndex:index2,type:holeLine.userData.type,start:holeLine.start.toJson2D(),end:holeLine.end.toJson2D(),height:holeLine.userData.height,thickness:thickness,shape:holeData.shape&&cloneUserData(holeData.shape),groundClearance:holeData.groundClearance})})})}beam({data:{lines:lines,json:json}}){lines.forEach(line=>{const beamLines=[];for(const holeData of WallHole.getIterator(line))if("beam"===holeData.type){const beamLine=WallHole.holeDataToLine(line,holeData);let{groundClearance:groundClearance=0,height:height=0}=holeData;groundClearance+=height,json.beams.push({id:uuid(),start:beamLine.start.toJson2D(),end:beamLine.end.toJson2D(),height:(line.userData.height??2.8)-groundClearance,groundClearance:groundClearance,thickness:line.userData.wallWidth??DEFAULT_WALL_WIDTH}),beamLines.push(beamLine),WallHole.removeHole(line,holeData)}const newLines=LineSegmentUtils.clippingByLines(line,beamLines,clippingLineUserData);newLines.length&&this.manager.add({type:"wall",lines:newLines})})}holeBayWindow({data:{lines:lines}}){lines.forEach(line=>{const holeBayWindowLines=[];for(const holeData of WallHole.getIterator(line))if("byWindow"===holeData.type){const holeLine=WallHole.holeDataToLine(line,holeData),{structure:structure}=WallHole.byWindowStructure(holeLine,holeData);this.manager.add({type:"bayWindow",lines:structure}),holeBayWindowLines.push(holeLine),WallHole.removeHole(line,holeData)}const newLines=LineSegmentUtils.clippingByLines(line,holeBayWindowLines,clippingLineUserData);newLines.length&&this.manager.add({type:"wall",lines:newLines})})}bayWindow({data:{lines:lines}}){let{bwlines:bwlines,path:path=[]}=LineSegmentUtils.group(lines,line=>line.userData.isBayWindow?"bwlines":"path");if(bwlines?.length){const line=bwlines[0].clone();line.userData.isBayWindow=!1;const lug=new LineSegmentUndirectedGraph(path);let startIndex=lug.getIndex(line.start);const visited=/* @__PURE__ */new Set([startIndex]);for(;null!=startIndex;){const set2=lug.getNeighbors(startIndex);if(!set2)return;if(0===set2.size)break;startIndex=[...set2.values()].filter(v2=>!visited.has(v2))[0],void 0!==startIndex&&visited.add(startIndex)}const values=[...visited],points=values.map(v2=>lug.getPoint(v2)),fragmentAttr=[];for(let i=1;i<values.length;i++){const v2=values[i],preV=values[i-1],line2=lug.getLine(v2,preV);line2&&line2.userData.isWindow&&fragmentAttr.push({type:"window",index:i-1})}const windowLine=path.filter(line2=>line2.userData.isWindow);let groundClearance=0,height=0;if(windowLine.length)for(const holes of WallHole.getStorageDataIterator(windowLine[0]))for(let i=0;i<holes.length;i++){const hole=holes[i];if("window"===hole.type){groundClearance=hole.groundClearance??0,height=hole.height??0;break}}WallHole.addHole(line,{p:line.start.toJson(),width:line.length,full:!0,groundClearance:groundClearance,height:height,type:"byWindow",shape:{path:points.map(point2=>point2.toJson()),fragmentAttr:fragmentAttr}}),this.manager.add({type:"wall",lines:[line]})}}railing({data:{lines:lines,json:json}}){lines.forEach(line=>{json.railings.push({id:uuid(),start:line.start.toJson2D(),end:line.end.toJson2D(),thickness:line.userData.wallWidth??DEFAULT_WALL_WIDTH,height:line.userData.height??2.8})})}pillar({data:{lines:lines,json:json}}){const poly=Polygon.fromByLines2(lines),height=lines.reduce((h2,l)=>Math.max(h2,l.userData.height??0),0);json.pillars.push({id:uuid(),height:height,shape:poly.map(p2=>p2.toJson2D())})}transform(){const option={version:"1.0",walls:[],pillars:[],beams:[],holes:[],railings:[],rooms:[],angleCorre:{center:{x:0,y:0},angle:0}},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),option}static appendRooms(json,rooms,z){return Array.isArray(json.rooms)||(json.rooms=[]),rooms.map(room=>{json.rooms.push({position:room.center.clone().toJson(z),shape:room.ploy.map(p2=>p2.clone().toJson2D()),id:room.uuid})}),json}static rotate(json){const{center:center,angle:angle}=json.angleCorre;if(!angle)return json;const cos=Math.cos(angle),sin=Math.sin(angle),rotatePoint=point2=>{const x=point2.x-center.x,y=point2.y-center.y;point2.x=center.x+x*cos-y*sin,point2.y=center.y+x*sin+y*cos};return json.walls.forEach(wall=>{rotatePoint(wall.start),rotatePoint(wall.end)}),json.pillars.forEach(pillar=>{pillar.shape.forEach(rotatePoint)}),json.beams.forEach(beam=>{rotatePoint(beam.start),rotatePoint(beam.end)}),json.holes.forEach(hole=>{rotatePoint(hole.start),rotatePoint(hole.end),hole.shape?.path.forEach(rotatePoint)}),json.railings.forEach(railing=>{rotatePoint(railing.start),rotatePoint(railing.end)}),json.rooms.forEach(room=>{rotatePoint(room.position),room.shape.forEach(rotatePoint)}),json}static toJson(lineSegments,angle=0,updateGroup=!0){let centerVec2=Box2.fromByLineSegment(...lineSegments).center.toJson2D();updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));const json=new ExternalDataPipeline(lineSegments).transform();return json.angleCorre.angle=angle,json.angleCorre.center=centerVec2,json}}class ThreeVJia extends Component{static name="ThreeVJia";lineSegments=[];neededUpdate=!0;trajectory;onAddFromParent(){const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf");angleCorrectionDxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0,this.trajectory=angleCorrectionDxf.options.trajectory})}cacheJson;updateData(){if(!this.neededUpdate)return;const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf"),dxf=this.parent?.findComponentByName("Dxf"),rooms=dxf.rooms,lines=angleCorrectionDxf.getLineSegments();this.cacheJson=ThreeVJiaPipeline.externalDataToThreeVJia(ExternalDataPipeline.rotate(ExternalDataPipeline.toJson(lines,angleCorrectionDxf.angle)),getDrawingMaxHeight(lines)),ThreeVJiaPipeline.appendRooms(this.cacheJson,rooms),this.neededUpdate=!1}toJson(name="测试",communityName=""){return this.neededUpdate&&this.updateData(),this.cacheJson.name=name,this.cacheJson.communityName=communityName,this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class Variable extends Component{static name="Variable";originalLineVisible=!0;dxfVisible=!0;whiteModelVisible=!0;isLook=!1;currentWheel=0;pointerMove={x:0,y:0};currentKeyUp="";currentKeyDown="";currentMouseUp="";currentMouseDown="";focus=!1;set(key,value){if(key in this){const oldValue=this[key];this[key]=value,this.dispatchEvent({type:key,value:value,oldValue:oldValue})}}get(key){if(key in this)return this[key]}}const WALL_HEIGHT_KEY=/* @__PURE__ */Symbol("height");class RunJianPipeline extends Pipeline{manager;index=0;z;floor;lines;constructor(lines,z,floor){super(),this.z=z,this.floor=floor,this.lines=lines,this.manager=WallGroupManager.fromByLines(lines),this.use({type:"bayWindow",handle:this.bayWindowHandle.bind(this)}),this.use({type:"doubleWall",handle:this.doubleWallHandle.bind(this)}),this.use({type:"pillar",handle:this.pillarHandle.bind(this)}),this.use({type:"wall",handle:this.wallHandle.bind(this)}),this.use({type:"door",handle:this.doorHandle.bind(this)}),this.use({type:"window",handle:this.wallHandle.bind(this)}),this.use({type:"balconyRailing",handle:this.balconyRailing.bind(this)}),this.use({type:"wallHole",handle:this.wallHoleHandle.bind(this)})}doubleWallHandle({data:{lines:lines},cache:cache2}){const groups=clippingInsertObjectDoubleWall(lines),{door:door,window:windowLines,passageEntrance:passageEntrance,untreatedDoubleWallGroup:untreatedDoubleWallGroup}=WallHoleDrawData.handleHoleDrawData(groups,[]),walls=untreatedDoubleWallGroup.flatMap(lines2=>{if(lines2.length<4)return lines2;if(lines2.length>4){const polygon2=Polygon.fromByLinePath(lines2).getMinimumBoundingRectangle();polygon2&&(lines2=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines2=[...lines2].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines2[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines2),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,[newLine]});this.manager.add({type:"wallHole",lines:windowLines}),this.manager.add({type:"wallHole",lines:door}),this.manager.add({type:"wallHole",lines:passageEntrance}),cache2.wallLines=[...cache2.wallLines,...walls,...windowLines,...door,...passageEntrance]}pillarHandle({data:{lines:lines,json:json}}){try{const rect=Polygon.fromByLines2(lines).getMinimumBoundingRectangle();if(!rect)return;const heights=lines.map(line=>"number"==typeof line.userData.height?line.userData.height:"number"==typeof line.userData.rooftopPz?line.userData.rooftopPz-this.z:0),center=rect.getCenter(),dist1=rect[1].distance(rect[0]),dist2=rect[2].distance(rect[1]),width=Math.min(dist1,dist2),height=Math.max(...heights);json.components.push({index:json.components.length,id:json.components.length,name:"柱",floor:this.floor,length:Math.max(dist1,dist2),width:width,height:height,x:center.x,y:center.y,z:this.z+.5*height})}catch(error){this.manager.add({type:"wall",lines:lines})}}wallHandle({data:{lines:lines},cache:cache2}){const alignConfig2={esp:.3,onMergeLine:mergeLineUserData,onGroup(group2,projValues,axis){if(group2.length<=1)return;const dist=precision4((Math.max(...projValues)-Math.min(...projValues))*axis.length);dist<DEFAULT_WALL_WIDTH||group2.forEach(line=>{line.userData.wallWidth=Math.min(dist,MAX_WALL_WIDTH)})},onLayoutDesign(lines2,delKey){const holes=[];lines2=lines2.filter(line=>(holes.push(...WallHole.getIterator(line)),WallHole.clear(line),!line.currentData[delKey])),WallHole.splitHole(holes,lines2)}},holeLines=(lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,line=>WallHole.isBeam(line)?"beam":"line")).handle("beam",beamLines=>beamLines=AlignToParallelSegments.align(beamLines,alignConfig2)).merge()).flatMap(line=>WallHoleDrawData.singleHoleLine(line)??[]);this.manager.add({type:"wallHole",lines:holeLines}),cache2.wallLines.push(...lines.filter(line=>!WallHole.isBeam(line)))}doorHandle({data:{lines:lines},cache:cache2}){const doors=lines.map(line=>{const doorLine=new LineSegment(line.start.clone(),line.end.clone());return doorLine.userData={groundClearance:line.userData.drawDoorData?.sillHeight,height:line.userData.drawDoorData?.height,type:"door",wallHeight:line.userData.drawDoorData?.height,wallWidth:void 0},doorLine});this.manager.add({type:"wallHole",lines:doors}),cache2.wallLines.push(...doors)}bayWindowHandle({data:{lines:lines},cache:cache2}){const info=BayWindowHelper.computedInfo(lines);if(info){const{dottedLine:dottedLine,windowLine:windowLine,depth:depth,side:side}=info,line=new LineSegment(dottedLine.start.clone(),dottedLine.end.clone()),win=windowLine?.userData.drawWindow&&windowLine.userData.drawWindow[0];"LEFT"===side&&line.swapValue(),line.translate(.5*-DEFAULT_WALL_WIDTH,line.normal()),line.userData={groundClearance:win?.groundClearance??0,height:win?.height,type:"bay_window",wallHeight:win?.height,wallWidth:void 0,depth:depth??.5,openSide:side},this.manager.add({type:"wallHole",lines:[line]}),line.setLength(line.length+.001),cache2.wallLines.push(line)}}balconyRailing({data:{lines:lines},cache:cache2}){const brls=lines.map(line=>{line.currentData[WALL_HEIGHT_KEY]=line.userData.height;const brl=new LineSegment(line.start.clone(),line.end.clone());return brl.userData={groundClearance:0,height:line.userData.height,type:"RAILING",wallWidth:void 0},brl});this.manager.add({type:"wallHole",lines:brls}),cache2.wallLines.push(...lines)}wallHoleHandle({data:{lines:lines,json:json}}){lines.forEach(line=>{if(line.length<1e-4)return;if("beam"!==line.userData.type)return;const center=line.center,startZ=precision4Nullable(line.userData?.height??2.1),height=line.userData.maxHeight-startZ,width=line.userData.wallWidth??DEFAULT_WALL_WIDTH;json.components.push({index:json.components.length,id:json.components.length,name:"梁",floor:this.floor,length:line.length,width:width,height:height,x:center.x,y:center.y,z:this.z+startZ+.5*height})})}transform(){const option={version:"1.0",components:[],title:"1F",rooms:[],floor:this.floor},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),cache2.wallLines.forEach(line=>{const center=line.center,height=precision4(line.userData.height??0),width=precision4(Math.max(line.userData.wallWidth?line.userData.wallWidth:DEFAULT_WALL_WIDTH,DEFAULT_WALL_WIDTH));option.components.push({index:option.components.length,id:option.components.length,name:"墙",floor:this.floor,length:line.length,width:width,height:height,x:center.x,y:center.y,z:this.z+.5*height})}),option}static toJson(lineSegments,opt){const{z:z=0,floor:floor=1,angle:angle=0,updateGroup:updateGroup=!1}=opt??{};let centerVec2=null;lineSegments=LineSegmentUndirectedGraph.rotate(lineSegments.map(line=>line.clone()),angle,(line,center,angle2)=>{centerVec2||(centerVec2={x:center.x,y:center.y}),WallHole.forEachStorageType(line,data=>{data.forEach(item=>{const point2=Point.from(item.p);point2.rotate(center,angle2),item.p=point2.toJson(item.p.z)})})}),updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));return new RunJianPipeline(lineSegments,z,floor).transform()}}class RunJian extends Component{static name="RunJian";lineSegments=[];neededUpdate=!0;trajectory;onAddFromParent(){const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf");angleCorrectionDxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0,this.trajectory=angleCorrectionDxf.options.trajectory})}cacheJson;updateData(){if(!this.neededUpdate)return;const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf"),dxf=this.parent?.findComponentByName("Dxf");this.cacheJson=RunJianPipeline.toJson(angleCorrectionDxf.getLineSegments(),{angle:angleCorrectionDxf.angle,floor:1});dxf.rooms.forEach(room=>{this.cacheJson?.rooms.push({...room.center.toJson(dxf.originalZAverage),area:room.ploy.area()})}),this.neededUpdate=!1}toJson(floor=1){return this.neededUpdate&&this.updateData(),this.cacheJson.floor=floor,this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class ExternalData extends Component{static name="ExternalData";lineSegments=[];neededUpdate=!0;onAddFromParent(){const dxf=this.parent?.findComponentByName("Dxf");dxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0})}cacheJson;updateData(){if(!this.neededUpdate)return;const dxf=this.parent?.findComponentByName("Dxf"),lines=dxf.getLineSegments(!0),rooms=dxf.rooms;this.cacheJson=ExternalDataPipeline.toJson(lines,dxf.angle),ExternalDataPipeline.appendRooms(this.cacheJson,rooms,dxf.originalZAverage),this.neededUpdate=!1}toJson(){return this.neededUpdate&&this.updateData(),this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class DxfSystem extends ComponentContainer{Dxf;Variable;BoundExtDxf;environment;static finalInstance;constructor(){super(),this.environment="undefined"!=typeof window?"browser":"undefined"!=typeof global?"node":"unknown",this.Dxf=new Dxf,this.BoundExtDxf=new BoundExtDxf,this.Variable=new Variable,this.addComponent(this.Variable),this.addComponent(this.Dxf),this.addComponent(this.BoundExtDxf),this.addComponent(new ThreeVJia),this.addComponent(new RunJian),this.addComponent(new ExternalData),DxfSystem.finalInstance=this}usePlugin(plugin){return"function"==typeof plugin&&plugin.call(this,this),this}destroy(){this.components.concat().forEach(com=>{com.destroy()}),this.components.concat().forEach(com=>{this.removeComponent(com)})}}const components={ThreeVJia:ThreeVJia,Variable:Variable,Dxf:Dxf,BoundExtDxf:BoundExtDxf},index$2=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BoundExt:BoundExt,DoubleWallFinder:DoubleWallFinder,DxfSystem:DxfSystem,LineGroupType:LineGroupType,SceneAutoGenerat:SceneAutoGenerat,ThreeVJiaPipeline:ThreeVJiaPipeline,cad:cad,clippingDoubleWall:clippingDoubleWall,clippingInsertObjectDoubleWall:clippingInsertObjectDoubleWall,components:components,findDiscretePoint:findDiscretePoint,findDiscretePoint2:findDiscretePoint2,findDiscretePointLine:findDiscretePointLine,findDiscretePointLine2:findDiscretePointLine2,tools:tools},Symbol.toStringTag,{value:"Module"}));function drawText$1(text,point2,style,offset=.001){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer"),editor=dxfSystem.findComponentByName("EditorView");if(renderer){const obj3d=renderer.createText(text,point2,style,editor?.container2);return obj3d.position.z=offset,obj3d}}}const exporter=new OBJExporter;let glbExporter;class WhiteModel extends Component{static name="WhiteModel";Dxf=null;Variable=null;whiteModelGroup=new THREE.Group;groundBuildMode="none";itemList=[];promise;setItemList(itemList){Array.isArray(itemList)?this.itemList=itemList:"itemInfo"in itemList&&(this.itemList=itemList.itemInfo)}onAddFromParent(parent){this.Dxf=parent.findComponentByName("Dxf"),this.Variable=parent.findComponentByName("Variable"),this.Dxf?.addEventListener("cadChange",({options:options})=>{this.setItemList(options?.publicInfo??[]),this.promise=this.updateModel()})}regenerateModel(){this.promise=this.updateModel()}rotateAroundPoint(object,point2,angle,axis=new THREE.Vector3(0,0,1)){object.position.sub(point2),object.position.applyAxisAngle(axis,angle),object.position.add(point2),object.rotateOnWorldAxis(axis,angle)}center=Point.zero();angle=0;async updateModel(){const dxfSystem=this.parent;this.Variable?.set("whiteModelVisible",!1);let lines=dxfSystem.BoundExtDxf.getLineSegments(!0);lines=lines.flatMap(line=>{const holes=Array.from(WallHole.getIterator(line)).filter(hole=>"byWindow"===hole.type);return[...LineSegmentUtils.clippingByLines(line,holes.map(hole=>WallHole.holeDataToLine(line,hole)),clippingLineUserData),...holes.flatMap(hole=>WallHole.byWindowStructure(line,hole).structure)]});const sceneAutoGenerat=new SceneAutoGenerat(lines,this.itemList,dxfSystem.Dxf.originalZAverage,dxfSystem.Dxf.options.trajectory);await sceneAutoGenerat.init(),"none"!==this.groundBuildMode&&sceneAutoGenerat.buildPlane(dxfSystem.Dxf.getLineSegments(),this.groundBuildMode,dxfSystem.Dxf.rooms);let group2=sceneAutoGenerat.scene;if(group2){this.whiteModelGroup.clear(),group2=group2.clone(!0);const center=dxfSystem.BoundExtDxf.box.center;this.center.copy(center),group2.position.sub(new THREE.Vector3(center.x,center.y,0));const container=new THREE.Group;container.add(group2),container.rotation.z=dxfSystem.BoundExtDxf.angle,container.position.z=this.Dxf?.originalZAverage??0,container.userData.correction=!0,container.userData.angle=dxfSystem.BoundExtDxf.angle,this.angle=dxfSystem.BoundExtDxf.angle,this.whiteModelGroup.add(container)}return this.dispatchEvent({type:"updateModel",whiteModelGroup:this.whiteModelGroup}),this.whiteModelGroup}toOBJ(){return new Promise(async resolve=>{await this.promise;const group2=this.whiteModelGroup.clone(!0),center=this.center,angle=this.angle,cos=Math.cos(angle),sin=Math.sin(angle),vertex=new THREE.Vector3;group2.traverse(obj=>{if(!(obj instanceof THREE.Mesh))return;obj.geometry=obj.geometry.clone();const geometry=obj.geometry,position=geometry.attributes.position;if(!position)return;obj.updateMatrixWorld(!0);const matrixWorld=obj.matrixWorld,inverseMatrix=matrixWorld.clone().invert();for(let i=0;i<position.count;i++){vertex.fromBufferAttribute(position,i),vertex.applyMatrix4(matrixWorld);const x=vertex.x-center.x,y=vertex.y-center.y;vertex.x=center.x+x*cos-y*sin,vertex.y=center.y+x*sin+y*cos,vertex.applyMatrix4(inverseMatrix),position.setXYZ(i,vertex.x,vertex.y,vertex.z)}position.needsUpdate=!0,geometry.computeBoundingBox(),geometry.computeBoundingSphere()}),resolve(exporter.parse(group2))})}toGltf(binary=!0){return glbExporter||(glbExporter=new gltf.GLTFExporter),new Promise(async resolve=>{await this.promise,glbExporter.parse(this.whiteModelGroup.children,gltf2=>{resolve(gltf2)},()=>{resolve(void 0)},{binary:binary})})}async toOBJBlob(){const buffer=await this.toOBJ();if(buffer)return new Blob([buffer],{type:"application/octet-stream"})}async toGltfBlob(binary=!0){const buffer=await this.toGltf(binary);if(buffer)return binary?new Blob([buffer],{type:"application/octet-stream"}):new Blob([JSON.stringify(buffer)],{type:"application/json"})}async downloadOBJ(filename){if("undefined"!=typeof window){const blob=await this.toOBJBlob();if(!blob)return;const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){const buffer=await this.toOBJ();if(buffer){(await include("fs",!1)).writeFileSync(filename,buffer)}}}async downloadGltf(filename,binary=!0){if("undefined"!=typeof window){const blob=await this.toGltfBlob(binary);if(!blob)return;const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){const buffer=await this.toGltf(binary);if(buffer){(await include("fs",!1)).writeFileSync(filename,binary?Buffer.from(buffer):JSON.stringify(buffer))}}}}class DxfLineModel extends Component{static name="DxfLineModel";dxfLineModel=new THREE.LineSegments;dxfModelGroup=new THREE.Group;onAddFromParent(parent){const dxf=parent.findComponentByName("BoundExtDxf");this.dxfModelGroup.add(this.dxfLineModel),dxf?.addEventListener("cadChange",()=>this.updateMode())}updateMode(){const dxf=this.parent?.findComponentByName("BoundExtDxf");this.dxfLineModel.clear();const cad2=dxf.cadQueue.get("cad"),dxfArray=new Float32Array(cad2.groups.flatMap(group2=>"wall"!==group2.type?[]:group2.lines.flatMap(line=>line.points.flatMap(p2=>[p2.x,p2.y,0]))));this.dxfLineModel.geometry=(new THREE.BufferGeometry).setAttribute("position",new THREE.BufferAttribute(dxfArray,3,!0)),this.dxfModelGroup.position.z=dxf.originalZAverage,this.dispatchEvent({type:"modelUpdate",model:this.dxfModelGroup})}}const index$1=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,DxfLineModel:DxfLineModel,WhiteModel:WhiteModel},Symbol.toStringTag,{value:"Module"}));function Model3dPlugin_(dxfSystem,option={}){const{whiteModel:whiteModel=!0,dxfLineModel:dxfLineModel=!0}=option;dxfLineModel&&dxfSystem.addComponent(new DxfLineModel),whiteModel&&dxfSystem.addComponent(new WhiteModel)}const ModelDataPlugin=Object.assign(Model3dPlugin_,{create:(option={})=>dxfSystem=>Model3dPlugin_(dxfSystem,option)}),index=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ModelDataPlugin:ModelDataPlugin,components:index$1},Symbol.toStringTag,{value:"Module"})),inBrowser="undefined"!=typeof window;let mark,measure;if("production"!==process.env.NODE_ENV){const perf2=inBrowser&&window.performance;perf2&&perf2.mark&&perf2.measure&&perf2.clearMarks&&perf2.clearMeasures&&(mark=tag=>{perf2.mark(tag)},measure=(name,startTag,endTag)=>{perf2.measure(name,startTag,endTag),perf2.clearMarks(startTag),perf2.clearMarks(endTag)})}const RE_ARGS=/\{([0-9a-zA-Z]+)\}/g;function format$1(message,...args){return 1===args.length&&isObject(args[0])&&(args=args[0]),args&&args.hasOwnProperty||(args={}),message.replace(RE_ARGS,(match,identifier)=>args.hasOwnProperty(identifier)?args[identifier]:"")}const makeSymbol=(name,shareable=!1)=>shareable?Symbol.for(name):Symbol(name),friendlyJSONstringify=json=>JSON.stringify(json).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),isNumber=val=>"number"==typeof val&&isFinite(val);function toDevtoolsGroupId(type,key){return isString(key)||isNumber(key)?`${type}:${key}`:type}const isDate=val=>"[object Date]"===toTypeString(val),isRegExp=val=>"[object RegExp]"===toTypeString(val),isEmptyObject=val=>isPlainObject(val)&&0===Object.keys(val).length,assign=Object.assign,_create=Object.create,create=(obj=null)=>_create(obj);let _globalThis;const getGlobalThis=()=>_globalThis||(_globalThis="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:create()),hasOwnProperty=Object.prototype.hasOwnProperty;function hasOwn(obj,key){return hasOwnProperty.call(obj,key)}const isArray=Array.isArray,isFunction=val=>"function"==typeof val,isString=val=>"string"==typeof val,isBoolean=val=>"boolean"==typeof val,isObject=val=>null!==val&&"object"==typeof val,objectToString=Object.prototype.toString,toTypeString=value=>objectToString.call(value),isPlainObject=val=>"[object Object]"===toTypeString(val);function join(items,separator=""){return items.reduce((str,item,index2)=>0===index2?str+item:str+separator+item,"")}function warn(msg,err){"undefined"!=typeof console&&(console.warn("[intlify] "+msg),err&&console.warn(err.stack))}const hasWarned={};function warnOnce(msg){hasWarned[msg]||(hasWarned[msg]=!0,warn(msg))}function escapeHtml(rawText){return rawText.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/").replace(/=/g,"=")}const javascriptSchemePattern=/^javascript:/i,urlAttributePattern=/^(?:href|src|action|formaction)$/i,numericCharacterReferencePattern=/&#(?:x([0-9a-f]+)|(\d+));?/gi,namedWhitespaceCharacterReferencePattern=/&(?:Tab|NewLine);/g,colonCharacterReferencePattern=/:?/gi,controlOrWhitespacePattern=/[\u0000-\u0020\u007f-\u009f]/g,eventHandlerPattern=/(?:^|[\s"'<>/])on\w+\s*=\s*["']?[^"'>]+["']?/i,eventHandlerAttributePattern=/(^|[\s"'<>/])on(\w+\s*=)/gi,unquotedUrlAttributePattern=/(^|[\s"'<>/])((?:href|src|action|formaction)\s*=\s*)([^\s"'=<>`]+)/gi;function decodeNumericCharacterReference(match,hex,decimal){const digits=hex||decimal;if(!digits)return match;const codePoint=Number.parseInt(digits,hex?16:10);return codePoint<=127?String.fromCharCode(codePoint):match}function hasJavascriptScheme(value){const normalized=value.replace(numericCharacterReferencePattern,decodeNumericCharacterReference).replace(namedWhitespaceCharacterReferencePattern,"").replace(colonCharacterReferencePattern,":").replace(controlOrWhitespacePattern,"");return javascriptSchemePattern.test(normalized)}function sanitizeAttributeValue(attrName,value){if(urlAttributePattern.test(attrName)&&hasJavascriptScheme(value))return"about:blank";const sanitizedValue="style"===attrName.toLowerCase()?function(value){const urlPattern=/url\s*\(/gi;let match,sanitized="",cursor=0;for(;null!==(match=urlPattern.exec(value));){const urlStart=match.index,openParenIndex=urlPattern.lastIndex-1;let index2=openParenIndex+1,depth=1,quote=null;for(;index2<value.length;index2++){const char=value[index2];if(quote)char===quote&&(quote=null);else if('"'===char||"'"===char)quote=char;else if("("===char)depth++;else if(")"===char&&(depth--,0===depth))break}if(0!==depth)break;const rawUrlValue=value.slice(openParenIndex+1,index2).trim(),unquotedUrlValue=rawUrlValue.startsWith('"')&&rawUrlValue.endsWith('"')||rawUrlValue.startsWith("'")&&rawUrlValue.endsWith("'")?rawUrlValue.slice(1,-1).trim():rawUrlValue;sanitized+=value.slice(cursor,urlStart),sanitized+=hasJavascriptScheme(unquotedUrlValue)?"url(about:blank)":value.slice(urlStart,index2+1),cursor=index2+1}return sanitized+value.slice(cursor)}(value):value;return function(value){return value.replace(/&(?![a-z0-9#]{2,6};)/gi,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}(sanitizedValue)}function createEmitter(){const events=/* @__PURE__ */new Map;return{events:events,on(event,handler){const handlers=events.get(event);handlers&&handlers.push(handler)||events.set(event,[handler])},off(event,handler){const handlers=events.get(event);handlers&&handlers.splice(handlers.indexOf(handler)>>>0,1)},emit(event,payload){(events.get(event)||[]).slice().map(handler=>handler(payload)),(events.get("*")||[]).slice().map(handler=>handler(event,payload))}}}const isNotObjectOrIsArray=val=>!isObject(val)||isArray(val);function deepCopy(src,des){if(isNotObjectOrIsArray(src)||isNotObjectOrIsArray(des))throw new Error("Invalid value");const stack=[{src:src,des:des}];for(;stack.length;){const{src:src2,des:des2}=stack.pop();Object.keys(src2).forEach(key=>{if("__proto__"===key)return;const value=src2[key];if(isArray(value)){const copied=[];copied.length=value.length,des2[key]=copied,stack.push({src:value,des:copied})}else isObject(value)?(isObject(des2[key])&&!isArray(des2[key])||(des2[key]=create()),stack.push({src:value,des:des2[key]})):des2[key]=value})}}function createLocation(start,end,source){return{start:start,end:end}}const CompileErrorCodes_EXPECTED_TOKEN=1,CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER=2,CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER=3,CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE=4,CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE=5,CompileErrorCodes_UNBALANCED_CLOSING_BRACE=6,CompileErrorCodes_UNTERMINATED_CLOSING_BRACE=7,CompileErrorCodes_EMPTY_PLACEHOLDER=8,CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER=9,CompileErrorCodes_INVALID_LINKED_FORMAT=10,CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL=11,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER=12,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY=13,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS=14,CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE=15,CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE=16,errorMessages$2={[CompileErrorCodes_EXPECTED_TOKEN]:"Expected token: '{0}'",[CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER]:"Invalid token in placeholder: '{0}'",[CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]:"Unterminated single quote in placeholder",[CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE]:"Unknown escape sequence: \\{0}",[CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE]:"Invalid unicode escape sequence: {0}",[CompileErrorCodes_UNBALANCED_CLOSING_BRACE]:"Unbalanced closing brace",[CompileErrorCodes_UNTERMINATED_CLOSING_BRACE]:"Unterminated closing brace",[CompileErrorCodes_EMPTY_PLACEHOLDER]:"Empty placeholder",[CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER]:"Not allowed nest placeholder",[CompileErrorCodes_INVALID_LINKED_FORMAT]:"Invalid linked format",[CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL]:"Plural must have messages",[CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER]:"Unexpected empty linked modifier",[CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY]:"Unexpected empty linked key",[CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS]:"Unexpected lexical analysis in token: '{0}'",[CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE]:"unhandled codegen node type: '{0}'",[CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE]:"unhandled mimifier node type: '{0}'"};function createCompileError(code,loc,options={}){const{domain:domain,messages:messages2,args:args}=options,msg="production"!==process.env.NODE_ENV?format$1((messages2||errorMessages$2)[code]||"",...args||[]):code,error=new SyntaxError(String(msg));return error.code=code,loc&&(error.location=loc),error.domain=domain,error}function defaultOnError(error){throw error}const RE_HTML_TAG=/<\/?[\w\s="/.':;#-\/]+>/,CHAR_LS=String.fromCharCode(8232),CHAR_PS=String.fromCharCode(8233);function createScanner(str){const _buf=str;let _index=0,_line=1,_column=1,_peekOffset=0;const isCRLF=index3=>"\r"===_buf[index3]&&"\n"===_buf[index3+1],isPS=index3=>_buf[index3]===CHAR_PS,isLS=index3=>_buf[index3]===CHAR_LS,isLineEnd=index3=>isCRLF(index3)||(index3=>"\n"===_buf[index3])(index3)||isPS(index3)||isLS(index3),charAt=offset=>isCRLF(offset)||isPS(offset)||isLS(offset)?"\n":_buf[offset];function next(){return _peekOffset=0,isLineEnd(_index)&&(_line++,_column=0),isCRLF(_index)&&_index++,_index++,_column++,_buf[_index]}return{index:()=>_index,line:()=>_line,column:()=>_column,peekOffset:()=>_peekOffset,charAt:charAt,currentChar:()=>charAt(_index),currentPeek:()=>charAt(_index+_peekOffset),next:next,peek:function(){return isCRLF(_index+_peekOffset)&&_peekOffset++,_peekOffset++,_buf[_index+_peekOffset]},reset:function(){_index=0,_line=1,_column=1,_peekOffset=0},resetPeek:function(offset=0){_peekOffset=offset},skipToPeek:function(){const target=_index+_peekOffset;for(;target!==_index;)next();_peekOffset=0}}}const EOF=void 0;function createTokenizer(source,options={}){const location=!1!==options.location,_scnr=createScanner(source),currentOffset=()=>_scnr.index(),currentPosition=()=>{return line=_scnr.line(),column=_scnr.column(),offset=_scnr.index(),{line:line,column:column,offset:offset};var line,column,offset},_initLoc=currentPosition(),_initOffset=currentOffset(),_context={currentType:13,offset:_initOffset,startLoc:_initLoc,endLoc:_initLoc,lastType:13,lastOffset:_initOffset,lastStartLoc:_initLoc,lastEndLoc:_initLoc,braceNest:0,inLinked:!1,text:""},context=()=>_context,{onError:onError}=options;function emitError(code,pos,offset,...args){const ctx=context();if(pos.column+=offset,pos.offset+=offset,onError){const err=createCompileError(code,location?createLocation(ctx.startLoc,pos):null,{domain:"tokenizer",args:args});onError(err)}}function getToken(context2,type,value){context2.endLoc=currentPosition(),context2.currentType=type;const token={type:type};return location&&(token.loc=createLocation(context2.startLoc,context2.endLoc)),null!=value&&(token.value=value),token}const getEndToken=context2=>getToken(context2,13);function eat(scnr,ch){return scnr.currentChar()===ch?(scnr.next(),ch):(emitError(CompileErrorCodes_EXPECTED_TOKEN,currentPosition(),0,ch),"")}function peekSpaces(scnr){let buf="";for(;" "===scnr.currentPeek()||"\n"===scnr.currentPeek();)buf+=scnr.currentPeek(),scnr.peek();return buf}function skipSpaces(scnr){const buf=peekSpaces(scnr);return scnr.skipToPeek(),buf}function isIdentifierStart(ch){if(ch===EOF)return!1;const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||95===cc}function isListIdentifierStart(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret=function(ch){if(ch===EOF)return!1;const cc=ch.charCodeAt(0);return cc>=48&&cc<=57}("-"===scnr.currentPeek()?scnr.peek():scnr.currentPeek());return scnr.resetPeek(),ret}function isPluralStart(scnr){peekSpaces(scnr);const ret="|"===scnr.currentPeek();return scnr.resetPeek(),ret}function isTextStart(scnr,reset=!0){const fn2=(hasSpace=!1,prev="")=>{const ch=scnr.currentPeek();return"{"===ch?hasSpace:"@"!==ch&&ch?"|"===ch?!(" "===prev||"\n"===prev):" "===ch?(scnr.peek(),fn2(!0," ")):"\n"!==ch||(scnr.peek(),fn2(!0,"\n")):hasSpace},ret=fn2();return reset&&scnr.resetPeek(),ret}function takeChar(scnr,fn2){const ch=scnr.currentChar();return ch===EOF?EOF:fn2(ch)?(scnr.next(),ch):null}function isIdentifier(ch){const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||95===cc||36===cc}function takeIdentifierChar(scnr){return takeChar(scnr,isIdentifier)}function isNamedIdentifier(ch){const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||95===cc||36===cc||45===cc}function takeNamedIdentifierChar(scnr){return takeChar(scnr,isNamedIdentifier)}function isDigit(ch){const cc=ch.charCodeAt(0);return cc>=48&&cc<=57}function takeDigit(scnr){return takeChar(scnr,isDigit)}function isHexDigit(ch){const cc=ch.charCodeAt(0);return cc>=48&&cc<=57||cc>=65&&cc<=70||cc>=97&&cc<=102}function takeHexDigit(scnr){return takeChar(scnr,isHexDigit)}function getDigits(scnr){let ch="",num="";for(;ch=takeDigit(scnr);)num+=ch;return num}function isLiteral2(ch){return"'"!==ch&&"\n"!==ch}function readEscapeSequence(scnr){const ch=scnr.currentChar();switch(ch){case"\\":case"'":return scnr.next(),`\\${ch}`;case"u":return readUnicodeEscapeSequence(scnr,ch,4);case"U":return readUnicodeEscapeSequence(scnr,ch,6);default:return emitError(CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE,currentPosition(),0,ch),""}}function readUnicodeEscapeSequence(scnr,unicode,digits){eat(scnr,unicode);let sequence="";for(let i=0;i<digits;i++){const ch=takeHexDigit(scnr);if(!ch){emitError(CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE,currentPosition(),0,`\\${unicode}${sequence}${scnr.currentChar()}`);break}sequence+=ch}return`\\${unicode}${sequence}`}function isInvalidIdentifier(ch){return"{"!==ch&&"}"!==ch&&" "!==ch&&"\n"!==ch}function readInvalidIdentifier(scnr){skipSpaces(scnr);let ch="",identifiers="";for(;ch=takeChar(scnr,isInvalidIdentifier);)identifiers+=ch;return identifiers}function readPlural(scnr){skipSpaces(scnr);const plural=eat(scnr,"|");return skipSpaces(scnr),plural}function readTokenInPlaceholder(scnr,context2){let token=null;switch(scnr.currentChar()){case"{":return context2.braceNest>=1&&emitError(CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER,currentPosition(),0),scnr.next(),token=getToken(context2,2,"{"),skipSpaces(scnr),context2.braceNest++,token;case"}":return context2.braceNest>0&&2===context2.currentType&&emitError(CompileErrorCodes_EMPTY_PLACEHOLDER,currentPosition(),0),scnr.next(),token=getToken(context2,3,"}"),context2.braceNest--,context2.braceNest>0&&skipSpaces(scnr),context2.inLinked&&0===context2.braceNest&&(context2.inLinked=!1),token;case"@":return context2.braceNest>0&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),token=readTokenInLinked(scnr,context2)||getEndToken(context2),context2.braceNest=0,token;default:{let validNamedIdentifier=!0,validListIdentifier=!0,validLiteral=!0;if(isPluralStart(scnr))return context2.braceNest>0&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token;if(context2.braceNest>0&&(4===context2.currentType||5===context2.currentType||6===context2.currentType))return emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),context2.braceNest=0,readToken(scnr,context2);if(validNamedIdentifier=function(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret=isIdentifierStart(scnr.currentPeek());return scnr.resetPeek(),ret}(scnr,context2))return token=getToken(context2,4,function(scnr){skipSpaces(scnr);let ch="",name="";for(;ch=takeNamedIdentifierChar(scnr);)name+=ch;const currentChar=scnr.currentChar();if(currentChar&&"}"!==currentChar&¤tChar!==EOF&&" "!==currentChar&&"\n"!==currentChar&&" "!==currentChar){const invalidPart=readInvalidIdentifier(scnr);return emitError(CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER,currentPosition(),0,name+invalidPart),name+invalidPart}return scnr.currentChar()===EOF&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),name}(scnr)),skipSpaces(scnr),token;if(validListIdentifier=isListIdentifierStart(scnr,context2))return token=getToken(context2,5,function(scnr){skipSpaces(scnr);let value="";return"-"===scnr.currentChar()?(scnr.next(),value+=`-${getDigits(scnr)}`):value+=getDigits(scnr),scnr.currentChar()===EOF&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),value}(scnr)),skipSpaces(scnr),token;if(validLiteral=function(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret="'"===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2))return token=getToken(context2,6,function(scnr){skipSpaces(scnr),eat(scnr,"'");let ch="",literal="";for(;ch=takeChar(scnr,isLiteral2);)literal+="\\"===ch?readEscapeSequence(scnr):ch;const current=scnr.currentChar();return"\n"===current||current===EOF?(emitError(CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER,currentPosition(),0),"\n"===current&&(scnr.next(),eat(scnr,"'")),literal):(eat(scnr,"'"),literal)}(scnr)),skipSpaces(scnr),token;if(!validNamedIdentifier&&!validListIdentifier&&!validLiteral)return token=getToken(context2,12,readInvalidIdentifier(scnr)),emitError(CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER,currentPosition(),0,token.value),skipSpaces(scnr),token;break}}return token}function readTokenInLinked(scnr,context2){const{currentType:currentType}=context2;let token=null;const ch=scnr.currentChar();switch(7!==currentType&&8!==currentType&&11!==currentType&&9!==currentType||"\n"!==ch&&" "!==ch||emitError(CompileErrorCodes_INVALID_LINKED_FORMAT,currentPosition(),0),ch){case"@":return scnr.next(),token=getToken(context2,7,"@"),context2.inLinked=!0,token;case".":return skipSpaces(scnr),scnr.next(),getToken(context2,8,".");case":":return skipSpaces(scnr),scnr.next(),getToken(context2,9,":");default:return isPluralStart(scnr)?(token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token):function(scnr,context2){const{currentType:currentType}=context2;if(7!==currentType)return!1;peekSpaces(scnr);const ret="."===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2)||function(scnr,context2){const{currentType:currentType}=context2;if(7!==currentType&&11!==currentType)return!1;peekSpaces(scnr);const ret=":"===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),readTokenInLinked(scnr,context2)):function(scnr,context2){const{currentType:currentType}=context2;if(8!==currentType)return!1;peekSpaces(scnr);const ret=isIdentifierStart(scnr.currentPeek());return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),getToken(context2,11,function(scnr){let ch="",name="";for(;ch=takeIdentifierChar(scnr);)name+=ch;return name}(scnr))):function(scnr,context2){const{currentType:currentType}=context2;if(9!==currentType)return!1;const fn2=()=>{const ch=scnr.currentPeek();return"{"===ch?isIdentifierStart(scnr.peek()):!("@"===ch||"|"===ch||":"===ch||"."===ch||" "===ch||!ch)&&("\n"===ch?(scnr.peek(),fn2()):isTextStart(scnr,!1))},ret=fn2();return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),"{"===ch?readTokenInPlaceholder(scnr,context2)||token:getToken(context2,10,function(scnr){const fn2=buf=>{const ch=scnr.currentChar();return"{"!==ch&&"@"!==ch&&"|"!==ch&&"("!==ch&&")"!==ch&&ch?" "===ch?buf:(buf+=ch,scnr.next(),fn2(buf)):buf};return fn2("")}(scnr))):(7===currentType&&emitError(CompileErrorCodes_INVALID_LINKED_FORMAT,currentPosition(),0),context2.braceNest=0,context2.inLinked=!1,readToken(scnr,context2))}}function readToken(scnr,context2){let token={type:13};if(context2.braceNest>0)return readTokenInPlaceholder(scnr,context2)||getEndToken(context2);if(context2.inLinked)return readTokenInLinked(scnr,context2)||getEndToken(context2);switch(scnr.currentChar()){case"{":return readTokenInPlaceholder(scnr,context2)||getEndToken(context2);case"}":return emitError(CompileErrorCodes_UNBALANCED_CLOSING_BRACE,currentPosition(),0),scnr.next(),getToken(context2,3,"}");case"@":return readTokenInLinked(scnr,context2)||getEndToken(context2);default:if(isPluralStart(scnr))return token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token;if(isTextStart(scnr))return getToken(context2,0,function(scnr){let buf="";for(;;){const ch=scnr.currentChar();if("\\"===ch){const nextCh=scnr.peek();"{"===nextCh||"}"===nextCh||"@"===nextCh||"|"===nextCh||"\\"===nextCh?(buf+=ch+nextCh,scnr.next(),scnr.next()):(scnr.resetPeek(),buf+=ch,scnr.next())}else{if("{"===ch||"}"===ch||"@"===ch||"|"===ch||!ch)break;if(" "===ch||"\n"===ch)if(isTextStart(scnr))buf+=ch,scnr.next();else{if(isPluralStart(scnr))break;buf+=ch,scnr.next()}else buf+=ch,scnr.next()}}return buf}(scnr))}return token}return{nextToken:function(){const{currentType:currentType,offset:offset,startLoc:startLoc,endLoc:endLoc}=_context;return _context.lastType=currentType,_context.lastOffset=offset,_context.lastStartLoc=startLoc,_context.lastEndLoc=endLoc,_context.offset=currentOffset(),_context.startLoc=currentPosition(),_scnr.currentChar()===EOF?getToken(_context,13):readToken(_scnr,_context)},currentOffset:currentOffset,currentPosition:currentPosition,context:context}}const KNOWN_ESCAPES=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g,TEXT_ESCAPES=/\\([\\@{}|])/g;function fromTextEscapeSequence(_match,char){return char}function fromEscapeSequence(match,codePoint4,codePoint6){switch(match){case"\\\\":return"\\";case"\\'":return"'";default:{const codePoint=parseInt(codePoint4||codePoint6,16);return codePoint<=55295||codePoint>=57344?String.fromCodePoint(codePoint):"�"}}}function createParser(options={}){const location=!1!==options.location,{onError:onError}=options;function emitError(tokenzer,code,start,offset,...args){const end=tokenzer.currentPosition();if(end.offset+=offset,end.column+=offset,onError){const err=createCompileError(code,location?createLocation(start,end):null,{domain:"parser",args:args});onError(err)}}function startNode(type,offset,loc){const node={type:type};return location&&(node.start=offset,node.end=offset,node.loc={start:loc,end:loc}),node}function endNode(node,offset,pos,type){location&&(node.end=offset,node.loc&&(node.loc.end=pos))}function parseText(tokenizer,value){const context=tokenizer.context(),node=startNode(3,context.offset,context.startLoc);return node.value=value.replace(TEXT_ESCAPES,fromTextEscapeSequence),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseList(tokenizer,index2){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(5,offset,loc);return node.index=parseInt(index2,10),tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseNamed(tokenizer,key){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(4,offset,loc);return node.key=key,tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseLiteral(tokenizer,value){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(9,offset,loc);return node.value=value.replace(KNOWN_ESCAPES,fromEscapeSequence),tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseLinked(tokenizer){const context=tokenizer.context(),linkedNode=startNode(6,context.offset,context.startLoc);let token=tokenizer.nextToken();if(8===token.type){const parsed=function(tokenizer){const token=tokenizer.nextToken(),context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(8,offset,loc);return 11!==token.type?(emitError(tokenizer,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER,context.lastStartLoc,0),node.value="",endNode(node,offset,loc),{nextConsumeToken:token,node:node}):(null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.value=token.value||"",endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),{node:node})}(tokenizer);linkedNode.modifier=parsed.node,token=parsed.nextConsumeToken||tokenizer.nextToken()}switch(9!==token.type&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),token=tokenizer.nextToken(),2===token.type&&(token=tokenizer.nextToken()),token.type){case 10:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=function(tokenizer,value){const context=tokenizer.context(),node=startNode(7,context.offset,context.startLoc);return node.value=value,endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}(tokenizer,token.value||"");break;case 4:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseNamed(tokenizer,token.value||"");break;case 5:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseList(tokenizer,token.value||"");break;case 6:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseLiteral(tokenizer,token.value||"");break;default:{emitError(tokenizer,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY,context.lastStartLoc,0);const nextContext=tokenizer.context(),emptyLinkedKeyNode=startNode(7,nextContext.offset,nextContext.startLoc);return emptyLinkedKeyNode.value="",endNode(emptyLinkedKeyNode,nextContext.offset,nextContext.startLoc),linkedNode.key=emptyLinkedKeyNode,endNode(linkedNode,nextContext.offset,nextContext.startLoc),{nextConsumeToken:token,node:linkedNode}}}return endNode(linkedNode,tokenizer.currentOffset(),tokenizer.currentPosition()),{node:linkedNode}}function parseMessage(tokenizer){const context=tokenizer.context(),node=startNode(2,1===context.currentType?tokenizer.currentOffset():context.offset,1===context.currentType?context.endLoc:context.startLoc);node.items=[];let nextToken=null;do{const token=nextToken||tokenizer.nextToken();switch(nextToken=null,token.type){case 0:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseText(tokenizer,token.value||""));break;case 5:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseList(tokenizer,token.value||""));break;case 4:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseNamed(tokenizer,token.value||""));break;case 6:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseLiteral(tokenizer,token.value||""));break;case 7:{const parsed=parseLinked(tokenizer);node.items.push(parsed.node),nextToken=parsed.nextConsumeToken||null;break}}}while(13!==context.currentType&&1!==context.currentType);return endNode(node,1===context.currentType?context.lastOffset:tokenizer.currentOffset(),1===context.currentType?context.lastEndLoc:tokenizer.currentPosition()),node}function parseResource(tokenizer){const context=tokenizer.context(),{offset:offset,startLoc:startLoc}=context,msgNode=parseMessage(tokenizer);return 13===context.currentType?msgNode:function(tokenizer,offset,loc,msgNode){const context=tokenizer.context();let hasEmptyMessage=0===msgNode.items.length;const node=startNode(1,offset,loc);node.cases=[],node.cases.push(msgNode);do{const msg=parseMessage(tokenizer);hasEmptyMessage||(hasEmptyMessage=0===msg.items.length),node.cases.push(msg)}while(13!==context.currentType);return hasEmptyMessage&&emitError(tokenizer,CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL,loc,0),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}(tokenizer,offset,startLoc,msgNode)}return{parse:function(source){const tokenizer=createTokenizer(source,assign({},options)),context=tokenizer.context(),node=startNode(0,context.offset,context.startLoc);return location&&node.loc&&(node.loc.source=source),node.body=parseResource(tokenizer),options.onCacheKey&&(node.cacheKey=options.onCacheKey(source)),13!==context.currentType&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,source[context.offset]||""),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}}}function getTokenCaption(token){if(13===token.type)return"EOF";const name=(token.value||"").replace(/\r?\n/gu,"\\n");return name.length>10?name.slice(0,9)+"…":name}function traverseNodes(nodes,transformer){for(let i=0;i<nodes.length;i++)traverseNode(nodes[i],transformer)}function traverseNode(node,transformer){switch(node.type){case 1:traverseNodes(node.cases,transformer),transformer.helper("plural");break;case 2:traverseNodes(node.items,transformer);break;case 6:traverseNode(node.key,transformer),transformer.helper("linked"),transformer.helper("type");break;case 5:transformer.helper("interpolate"),transformer.helper("list");break;case 4:transformer.helper("interpolate"),transformer.helper("named")}}function transform(ast,options={}){const transformer=function(ast){const _context={ast:ast,helpers:/* @__PURE__ */new Set};return{context:()=>_context,helper:name=>(_context.helpers.add(name),name)}}(ast);transformer.helper("normalize"),ast.body&&traverseNode(ast.body,transformer);const context=transformer.context();ast.helpers=Array.from(context.helpers)}function optimizeMessageNode(message){if(1===message.items.length){const item=message.items[0];3!==item.type&&9!==item.type||(message.static=item.value,delete item.value)}else{const values=[];for(let i=0;i<message.items.length;i++){const item=message.items[i];if(3!==item.type&&9!==item.type)break;if(null==item.value)break;values.push(item.value)}if(values.length===message.items.length){message.static=join(values);for(let i=0;i<message.items.length;i++){const item=message.items[i];3!==item.type&&9!==item.type||delete item.value}}}}function minify(node){switch(node.t=node.type,node.type){case 0:{const resource=node;minify(resource.body),resource.b=resource.body,delete resource.body;break}case 1:{const plural=node,cases=plural.cases;for(let i=0;i<cases.length;i++)minify(cases[i]);plural.c=cases,delete plural.cases;break}case 2:{const message=node,items=message.items;for(let i=0;i<items.length;i++)minify(items[i]);message.i=items,delete message.items,message.static&&(message.s=message.static,delete message.static);break}case 3:case 9:case 8:case 7:{const valueNode=node;valueNode.value&&(valueNode.v=valueNode.value,delete valueNode.value);break}case 6:{const linked=node;minify(linked.key),linked.k=linked.key,delete linked.key,linked.modifier&&(minify(linked.modifier),linked.m=linked.modifier,delete linked.modifier);break}case 5:{const list=node;list.i=list.index,delete list.index;break}case 4:{const named=node;named.k=named.key,delete named.key;break}default:if("production"!==process.env.NODE_ENV)throw createCompileError(CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE,null,{domain:"minifier",args:[node.type]})}delete node.type}function generateNode(generator,node){const{helper:helper}=generator;switch(node.type){case 0:!function(generator,node){node.body?generateNode(generator,node.body):generator.push("null")}(generator,node);break;case 1:!function(generator,node){const{helper:helper,needIndent:needIndent}=generator;if(node.cases.length>1){generator.push(`${helper("plural")}([`),generator.indent(needIndent());const length=node.cases.length;for(let i=0;i<length&&(generateNode(generator,node.cases[i]),i!==length-1);i++)generator.push(", ");generator.deindent(needIndent()),generator.push("])")}}(generator,node);break;case 2:!function(generator,node){const{helper:helper,needIndent:needIndent}=generator;generator.push(`${helper("normalize")}([`),generator.indent(needIndent());const length=node.items.length;for(let i=0;i<length&&(generateNode(generator,node.items[i]),i!==length-1);i++)generator.push(", ");generator.deindent(needIndent()),generator.push("])")}(generator,node);break;case 6:!function(generator,node){const{helper:helper}=generator;generator.push(`${helper("linked")}(`),generateNode(generator,node.key),node.modifier?(generator.push(", "),generateNode(generator,node.modifier),generator.push(", _type")):generator.push(", undefined, _type"),generator.push(")")}(generator,node);break;case 8:case 7:case 9:case 3:generator.push(JSON.stringify(node.value),node);break;case 5:generator.push(`${helper("interpolate")}(${helper("list")}(${node.index}))`,node);break;case 4:generator.push(`${helper("interpolate")}(${helper("named")}(${JSON.stringify(node.key)}))`,node);break;default:if("production"!==process.env.NODE_ENV)throw createCompileError(CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE,null,{domain:"parser",args:[node.type]})}}function baseCompile$1(source,options={}){const assignedOptions=assign({},options),jit=!!assignedOptions.jit,enalbeMinify=!!assignedOptions.minify,enambeOptimize=null==assignedOptions.optimize||assignedOptions.optimize,ast=createParser(assignedOptions).parse(source);return jit?(enambeOptimize&&function(ast){const body=ast.body;2===body.type?optimizeMessageNode(body):body.cases.forEach(c=>optimizeMessageNode(c))}(ast),enalbeMinify&&minify(ast),{ast:ast,code:""}):(transform(ast,assignedOptions),((ast,options={})=>{const mode=isString(options.mode)?options.mode:"normal",filename=isString(options.filename)?options.filename:"message.intl";options.sourceMap;const breakLineCode=null!=options.breakLineCode?options.breakLineCode:"arrow"===mode?";":"\n",needIndent=options.needIndent?options.needIndent:"arrow"!==mode,helpers=ast.helpers||[],generator=function(ast,options){const{filename:filename,breakLineCode:breakLineCode,needIndent:_needIndent}=options,location=!1!==options.location,_context={filename:filename,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:breakLineCode,needIndent:_needIndent,indentLevel:0};function push(code,node){_context.code+=code}function _newline(n,withBreakLine=!0){const _breakLineCode=withBreakLine?breakLineCode:"";push(_needIndent?_breakLineCode+" ".repeat(n):_breakLineCode)}return location&&ast.loc&&(_context.source=ast.loc.source),{context:()=>_context,push:push,indent:function(withNewLine=!0){const level=++_context.indentLevel;withNewLine&&_newline(level)},deindent:function(withNewLine=!0){const level=--_context.indentLevel;withNewLine&&_newline(level)},newline:function(){_newline(_context.indentLevel)},helper:key=>`_${key}`,needIndent:()=>_context.needIndent}}(ast,{filename:filename,breakLineCode:breakLineCode,needIndent:needIndent});generator.push("normal"===mode?"function __msg__ (ctx) {":"(ctx) => {"),generator.indent(needIndent),helpers.length>0&&(generator.push(`const { ${join(helpers.map(s=>`${s}: _${s}`),", ")} } = ctx`),generator.newline()),generator.push("return "),generateNode(generator,ast),generator.deindent(needIndent),generator.push("}"),delete ast.helpers;const{code:code,map:map}=generator.context();return{ast:ast,code:code,map:map?map.toJSON():void 0}})(ast,assignedOptions))}function isMessageAST(val){return isObject(val)&&0===resolveType(val)&&(hasOwn(val,"b")||hasOwn(val,"body"))}const PROPS_BODY=["b","body"];const PROPS_CASES=["c","cases"];const PROPS_STATIC=["s","static"];const PROPS_ITEMS=["i","items"];const PROPS_TYPE=["t","type"];function resolveType(node){return resolveProps(node,PROPS_TYPE)}const PROPS_VALUE=["v","value"];function resolveValue$1(node,type){const resolved=resolveProps(node,PROPS_VALUE);if(null!=resolved)return resolved;throw createUnhandleNodeError(type)}const PROPS_MODIFIER=["m","modifier"];const PROPS_KEY=["k","key"];function resolveProps(node,props,defaultValue){for(let i=0;i<props.length;i++){const prop=props[i];if(hasOwn(node,prop)&&null!=node[prop])return node[prop]}return defaultValue}const AST_NODE_PROPS_KEYS=[...PROPS_BODY,...PROPS_CASES,...PROPS_STATIC,...PROPS_ITEMS,...PROPS_KEY,...PROPS_MODIFIER,...PROPS_VALUE,...PROPS_TYPE];function createUnhandleNodeError(type){return new Error(`unhandled node type: ${type}`)}function format(ast){return ctx=>function(ctx,ast){const body=(node=ast,resolveProps(node,PROPS_BODY));var node;if(null==body)throw createUnhandleNodeError(0);if(1===resolveType(body)){const cases=function(node){return resolveProps(node,PROPS_CASES,[])}(body);return ctx.plural(cases.reduce((messages2,c)=>[...messages2,formatMessageParts(ctx,c)],[]))}return formatMessageParts(ctx,body)}(ctx,ast)}function formatMessageParts(ctx,node){const static_=function(node){return resolveProps(node,PROPS_STATIC)}(node);if(null!=static_)return"text"===ctx.type?static_:ctx.normalize([static_]);{const messages2=function(node){return resolveProps(node,PROPS_ITEMS,[])}(node).reduce((acm,c)=>[...acm,formatMessagePart(ctx,c)],[]);return ctx.normalize(messages2)}}function formatMessagePart(ctx,node){const type=resolveType(node);switch(type){case 3:case 9:case 7:case 8:return resolveValue$1(node,type);case 4:{const named=node;if(hasOwn(named,"k")&&named.k)return ctx.interpolate(ctx.named(named.k));if(hasOwn(named,"key")&&named.key)return ctx.interpolate(ctx.named(named.key));throw createUnhandleNodeError(type)}case 5:{const list=node;if(hasOwn(list,"i")&&isNumber(list.i))return ctx.interpolate(ctx.list(list.i));if(hasOwn(list,"index")&&isNumber(list.index))return ctx.interpolate(ctx.list(list.index));throw createUnhandleNodeError(type)}case 6:{const linked=node,modifier=function(node){return resolveProps(node,PROPS_MODIFIER)}(linked),key=function(node){const resolved=resolveProps(node,PROPS_KEY);if(resolved)return resolved;throw createUnhandleNodeError(6)}(linked);return ctx.linked(formatMessagePart(ctx,key),modifier?formatMessagePart(ctx,modifier):void 0,ctx.type)}default:throw new Error(`unhandled node on format message part: ${type}`)}}function checkHtmlMessage(source,warnHtmlMessage){warnHtmlMessage&&(source=>RE_HTML_TAG.test(source))(source)&&warn(format$1("Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.",{source:source}))}const defaultOnCacheKey=message=>message;let compileCache=create();let devtools=null;const translateDevTools=/* @__PURE__ */createDevToolsHook("function:translate");function createDevToolsHook(hook){return payloads=>devtools&&devtools.emit(hook,payloads)}const CoreErrorCodes_INVALID_ARGUMENT=17,CoreErrorCodes_INVALID_DATE_ARGUMENT=18,CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT=19,CoreErrorCodes_NOT_SUPPORT_NON_STRING_MESSAGE=20,CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE=21,CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION=22,CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE=23;function createCoreError(code){return createCompileError(code,null,"production"!==process.env.NODE_ENV?{messages:errorMessages$1}:void 0)}const errorMessages$1={[CoreErrorCodes_INVALID_ARGUMENT]:"Invalid arguments",[CoreErrorCodes_INVALID_DATE_ARGUMENT]:"The date provided is an invalid Date object.Make sure your Date represents a valid date.",[CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT]:"The argument provided is not a valid ISO date string",[CoreErrorCodes_NOT_SUPPORT_NON_STRING_MESSAGE]:"Not support non-string message",[CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE]:"cannot support promise value",[CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]:"cannot support async function",[CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE]:"cannot support locale type"};function getLocale(context,options){return null!=options.locale?resolveLocale(options.locale):resolveLocale(context.locale)}let _resolveLocale;function resolveLocale(locale2){if(isString(locale2))return locale2;if(isFunction(locale2)){if(locale2.resolvedOnce&&null!=_resolveLocale)return _resolveLocale;if("Function"===locale2.constructor.name){const resolve=locale2();if(isObject(val=resolve)&&isFunction(val.then)&&isFunction(val.catch))throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE);return _resolveLocale=resolve}throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION)}throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE);var val}function fallbackWithSimple(ctx,fallback,start){return[.../* @__PURE__ */new Set([start,...isArray(fallback)?fallback:isObject(fallback)?Object.keys(fallback).filter(locale2=>"default"!==locale2):isString(fallback)?[fallback]:[start]])]}function fallbackWithLocaleChain(ctx,fallback,start){const startLocale=isString(start)?start:DEFAULT_LOCALE,context=ctx;context.__localeChainCache||(context.__localeChainCache=/* @__PURE__ */new Map);const fallbackKey=friendlyJSONstringify(fallback);let chains=context.__localeChainCache.get(startLocale);chains||(chains=/* @__PURE__ */new Map,context.__localeChainCache.set(startLocale,chains));const cached=chains.get(fallbackKey);if(cached)return cached;const chain=[];let block=[start];for(;isArray(block);)block=appendBlockToChain(chain,block,fallback);const defaults=isArray(fallback)||!isPlainObject(fallback)?fallback:fallback.default?fallback.default:null;return block=isString(defaults)?[defaults]:defaults,isArray(block)&&appendBlockToChain(chain,block,!1),chains.set(fallbackKey,chain),chain}function appendBlockToChain(chain,block,blocks){let follow=!0;for(let i=0;i<block.length&&isBoolean(follow);i++){const locale2=block[i];isString(locale2)&&(follow=appendLocaleToChain(chain,block[i],blocks))}return follow}function appendLocaleToChain(chain,locale2,blocks){let follow;const tokens=locale2.split("-");do{follow=appendItemToChain(chain,tokens.join("-"),blocks),tokens.splice(-1,1)}while(tokens.length&&!0===follow);return follow}function appendItemToChain(chain,target,blocks){let follow=!1;if(!chain.includes(target)&&(follow=!0,target)){follow="!"!==target[target.length-1];const locale2=target.replace(/!/g,"");chain.push(locale2),(isArray(blocks)||isPlainObject(blocks))&&blocks[locale2]&&(follow=blocks[locale2])}return follow}const pathStateMachine=[];pathStateMachine[0]={w:[0],i:[3,0],"[":[4],o:[7]},pathStateMachine[1]={w:[1],".":[2],"[":[4],o:[7]},pathStateMachine[2]={w:[2],i:[3,0],0:[3,0]},pathStateMachine[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},pathStateMachine[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},pathStateMachine[5]={"'":[4,0],o:8,l:[5,0]},pathStateMachine[6]={'"':[4,0],o:8,l:[6,0]};const literalValueRE=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function getPathCharType(ch){if(null==ch)return"o";switch(ch.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return ch;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function formatSubPath(path){const trimmed=path.trim();return("0"!==path.charAt(0)||!isNaN(parseInt(path)))&&(exp=trimmed,literalValueRE.test(exp)?function(str){const a2=str.charCodeAt(0);return a2!==str.charCodeAt(str.length-1)||34!==a2&&39!==a2?str:str.slice(1,-1)}(trimmed):"*"+trimmed);var exp}const cache=/* @__PURE__ */new Map;function resolveWithKeyValue(obj,path){return isObject(obj)?obj[path]:null}const CoreWarnCodes_NOT_FOUND_KEY=1,CoreWarnCodes_FALLBACK_TO_TRANSLATE=2,CoreWarnCodes_CANNOT_FORMAT_NUMBER=3,CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT=4,CoreWarnCodes_CANNOT_FORMAT_DATE=5,CoreWarnCodes_FALLBACK_TO_DATE_FORMAT=6,CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER=7,CoreWarnCodes_INVALID_NUMBER_ARGUMENT=8,CoreWarnCodes_INVALID_DATE_ARGUMENT=9,warnMessages$1={[CoreWarnCodes_NOT_FOUND_KEY]:"Not found '{key}' key in '{locale}' locale messages.",[CoreWarnCodes_FALLBACK_TO_TRANSLATE]:"Fall back to translate '{key}' key with '{target}' locale.",[CoreWarnCodes_CANNOT_FORMAT_NUMBER]:"Cannot format a number value due to not supported Intl.NumberFormat.",[CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT]:"Fall back to number format '{key}' key with '{target}' locale.",[CoreWarnCodes_CANNOT_FORMAT_DATE]:"Cannot format a date value due to not supported Intl.DateTimeFormat.",[CoreWarnCodes_FALLBACK_TO_DATE_FORMAT]:"Fall back to datetime format '{key}' key with '{target}' locale.",[CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]:"This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.",[CoreWarnCodes_INVALID_NUMBER_ARGUMENT]:"Invalid argument for number formatting: expected a number but received '{value}'.",[CoreWarnCodes_INVALID_DATE_ARGUMENT]:"Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'."};function getWarnMessage$1(code,...args){return format$1(warnMessages$1[code],...args)}const DEFAULT_LOCALE="en-US",capitalize=str=>`${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;let _compiler,_resolver,_fallbacker;let _additionalMeta=null;const getAdditionalMeta=()=>_additionalMeta;let _fallbackContext=null;const setFallbackContext=context=>{_fallbackContext=context};let _cid=0;function createCoreContext(options={}){const onWarn=isFunction(options.onWarn)?options.onWarn:warn,version=isString(options.version)?options.version:"11.4.10",locale2=isString(options.locale)||isFunction(options.locale)?options.locale:DEFAULT_LOCALE,_locale=isFunction(locale2)?DEFAULT_LOCALE:locale2,fallbackLocale=isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||isString(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:_locale,messages2=isPlainObject(options.messages)?options.messages:createResources(_locale),datetimeFormats=isPlainObject(options.datetimeFormats)?options.datetimeFormats:createResources(_locale),numberFormats=isPlainObject(options.numberFormats)?options.numberFormats:createResources(_locale),modifiers=assign(create(),options.modifiers,{upper:(val,type)=>"text"===type&&isString(val)?val.toUpperCase():"vnode"===type&&isObject(val)&&"__v_isVNode"in val?val.children.toUpperCase():val,lower:(val,type)=>"text"===type&&isString(val)?val.toLowerCase():"vnode"===type&&isObject(val)&&"__v_isVNode"in val?val.children.toLowerCase():val,capitalize:(val,type)=>"text"===type&&isString(val)?capitalize(val):"vnode"===type&&isObject(val)&&"__v_isVNode"in val?capitalize(val.children):val}),pluralRules=options.pluralRules||create(),missing=isFunction(options.missing)?options.missing:null,missingWarn=!isBoolean(options.missingWarn)&&!isRegExp(options.missingWarn)||options.missingWarn,fallbackWarn=!isBoolean(options.fallbackWarn)&&!isRegExp(options.fallbackWarn)||options.fallbackWarn,fallbackFormat=!!options.fallbackFormat,unresolving=!!options.unresolving,postTranslation=isFunction(options.postTranslation)?options.postTranslation:null,processor=isPlainObject(options.processor)?options.processor:null,warnHtmlMessage=!isBoolean(options.warnHtmlMessage)||options.warnHtmlMessage,escapeParameter=!!options.escapeParameter,messageCompiler=isFunction(options.messageCompiler)?options.messageCompiler:_compiler;"production"!==process.env.NODE_ENV&&isFunction(options.messageCompiler)&&warnOnce(getWarnMessage$1(CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));const messageResolver=isFunction(options.messageResolver)?options.messageResolver:_resolver||resolveWithKeyValue,localeFallbacker=isFunction(options.localeFallbacker)?options.localeFallbacker:_fallbacker||fallbackWithSimple,fallbackContext=isObject(options.fallbackContext)?options.fallbackContext:void 0,internalOptions=options,__datetimeFormatters=isObject(internalOptions.__datetimeFormatters)?internalOptions.__datetimeFormatters:/* @__PURE__ */new Map,__numberFormatters=isObject(internalOptions.__numberFormatters)?internalOptions.__numberFormatters:/* @__PURE__ */new Map,__meta=isObject(internalOptions.__meta)?internalOptions.__meta:{};_cid++;const context={version:version,cid:_cid,locale:locale2,fallbackLocale:fallbackLocale,messages:messages2,modifiers:modifiers,pluralRules:pluralRules,missing:missing,missingWarn:missingWarn,fallbackWarn:fallbackWarn,fallbackFormat:fallbackFormat,unresolving:unresolving,postTranslation:postTranslation,processor:processor,warnHtmlMessage:warnHtmlMessage,escapeParameter:escapeParameter,messageCompiler:messageCompiler,messageResolver:messageResolver,localeFallbacker:localeFallbacker,fallbackContext:fallbackContext,onWarn:onWarn,__meta:__meta};return context.datetimeFormats=datetimeFormats,context.numberFormats=numberFormats,context.__datetimeFormatters=__datetimeFormatters,context.__numberFormatters=__numberFormatters,"production"!==process.env.NODE_ENV&&(context.__v_emitter=null!=internalOptions.__v_emitter?internalOptions.__v_emitter:void 0),("production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__)&&function(i18n2,version,meta){devtools&&devtools.emit("i18n:init",{timestamp:Date.now(),i18n:i18n2,version:version,meta:meta})}(context,version,__meta),context}const createResources=locale2=>({[locale2]:create()});function isTranslateFallbackWarn(fallback,key){return fallback instanceof RegExp?fallback.test(key):fallback}function isTranslateMissingWarn(missing,key){return missing instanceof RegExp?missing.test(key):missing}function handleMissing(context,key,locale2,missingWarn,type){const{missing:missing,onWarn:onWarn}=context;if("production"!==process.env.NODE_ENV){const emitter=context.__v_emitter;emitter&&emitter.emit("missing",{locale:locale2,key:key,type:type,groupId:toDevtoolsGroupId(type,key)})}if(null!==missing){const ret=missing(context,locale2,key,type);return isString(ret)?ret:key}return"production"!==process.env.NODE_ENV&&isTranslateMissingWarn(missingWarn,key)&&onWarn(getWarnMessage$1(CoreWarnCodes_NOT_FOUND_KEY,{key:key,locale:locale2})),key}function updateFallbackLocale(ctx,locale2,fallback){ctx.__localeChainCache=/* @__PURE__ */new Map,ctx.localeFallbacker(ctx,fallback,locale2)}function isAlmostSameLocale(locale2,compareLocale){return locale2!==compareLocale&&locale2.split("-")[0]===compareLocale.split("-")[0]}function isImplicitFallback(targetLocale,locales){const index2=locales.indexOf(targetLocale);if(-1===index2)return!1;for(let i=index2+1;i<locales.length;i++)if(isAlmostSameLocale(targetLocale,locales[i]))return!0;return!1}function resolveFormatLocale(context,key,locale2,formats,missingWarn,fallbackWarn,type){const{fallbackLocale:fallbackLocale,localeFallbacker:localeFallbacker,onWarn:onWarn}=context,locales=localeFallbacker(context,fallbackLocale,locale2);let from=locale2;for(let i=0;i<locales.length;i++){const targetLocale=locales[i];if("production"!==process.env.NODE_ENV&&locale2!==targetLocale&&isTranslateFallbackWarn(fallbackWarn,key)&&onWarn(getWarnMessage$1("datetime format"===type?CoreWarnCodes_FALLBACK_TO_DATE_FORMAT:CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT,{key:key,target:targetLocale})),"production"!==process.env.NODE_ENV&&locale2!==targetLocale){const emitter=context.__v_emitter;emitter&&emitter.emit("fallback",{type:type,key:key,from:from,to:targetLocale,groupId:toDevtoolsGroupId(type,key)})}const format2=(formats[targetLocale]||{})[key];if(isPlainObject(format2)&&isString(targetLocale))return targetLocale;handleMissing(context,key,targetLocale,missingWarn,type),from=targetLocale}return null}function getFormatterCacheKey(locale2,key,overrides){let id=`${locale2}__${key}`;return isPlainObject(overrides)&&!isEmptyObject(overrides)&&(id=`${id}__${JSON.stringify(overrides)}`),id}function clearFormatCache(formatters,locale2,format2){for(const key in format2){const prefix=`${locale2}__${key}`;for(const id of formatters.keys())(id===prefix||id.startsWith(`${prefix}__`))&&formatters.delete(id)}}function parseFormatArgs(args,options,initialOverrides,optionsKeys){const[,arg2,arg3,arg4]=args;let overrides=initialOverrides;return isString(arg2)?options.key=arg2:isPlainObject(arg2)&&Object.keys(arg2).forEach(key=>{optionsKeys.includes(key)?overrides[key]=arg2[key]:options[key]=arg2[key]}),isString(arg3)?options.locale=arg3:isPlainObject(arg3)&&(overrides=arg3),isPlainObject(arg4)&&(overrides=arg4),overrides}const intlDefined="undefined"!=typeof Intl,Availabilities_dateTimeFormat=intlDefined&&void 0!==Intl.DateTimeFormat,Availabilities_numberFormat=intlDefined&&void 0!==Intl.NumberFormat;function datetime(context,...args){const{datetimeFormats:datetimeFormats,unresolving:unresolving,onWarn:onWarn}=context,{__datetimeFormatters:__datetimeFormatters}=context;if("production"!==process.env.NODE_ENV&&!Availabilities_dateTimeFormat)return onWarn(getWarnMessage$1(CoreWarnCodes_CANNOT_FORMAT_DATE)),"";if(!isString(args[0])&&!isDate(args[0])&&!isNumber(args[0]))return"production"!==process.env.NODE_ENV&&onWarn(getWarnMessage$1(CoreWarnCodes_INVALID_DATE_ARGUMENT,{value:String(args[0])})),"";const[key,value,options,overrides]=parseDateTimeArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,part=!!options.part,locale2=getLocale(context,options);if(!isString(key)||""===key){const formatter2=new Intl.DateTimeFormat(locale2.replace(/!/g,""),overrides);return part?formatter2.formatToParts(value):formatter2.format(value)}const targetLocale=resolveFormatLocale(context,key,locale2,datetimeFormats,missingWarn,fallbackWarn,"datetime format");if(!isString(targetLocale))return unresolving?-1:key;const format2=datetimeFormats[targetLocale][key],id=getFormatterCacheKey(targetLocale,key,overrides);let formatter=__datetimeFormatters.get(id);return formatter||(formatter=new Intl.DateTimeFormat(targetLocale,assign({},format2,overrides)),__datetimeFormatters.set(id,formatter)),part?formatter.formatToParts(value):formatter.format(value)}const DATETIME_FORMAT_OPTIONS_KEYS=["localeMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName","formatMatcher","hour12","timeZone","dateStyle","timeStyle","calendar","dayPeriod","numberingSystem","hourCycle","fractionalSecondDigits"];function parseDateTimeArgs(...args){const[arg1]=args,options=create(),initialOverrides=create();let value;if(isString(arg1)){const matches=arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);if(!matches)throw createCoreError(CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT);const dateTime=matches[3]?matches[3].trim().startsWith("T")?`${matches[1].trim()}${matches[3].trim()}`:`${matches[1].trim()}T${matches[3].trim()}`:matches[1].trim();value=new Date(dateTime);try{value.toISOString()}catch{throw createCoreError(CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT)}}else if(isDate(arg1)){if(isNaN(arg1.getTime()))throw createCoreError(CoreErrorCodes_INVALID_DATE_ARGUMENT);value=arg1}else{if(!isNumber(arg1))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);value=arg1}const overrides=parseFormatArgs(args,options,initialOverrides,DATETIME_FORMAT_OPTIONS_KEYS);return[options.key||"",value,options,overrides]}function clearDateTimeFormat(ctx,locale2,format2){clearFormatCache(ctx.__datetimeFormatters,locale2,format2)}function number(context,...args){const{numberFormats:numberFormats,unresolving:unresolving,onWarn:onWarn}=context,{__numberFormatters:__numberFormatters}=context;if("production"!==process.env.NODE_ENV&&!Availabilities_numberFormat)return onWarn(getWarnMessage$1(CoreWarnCodes_CANNOT_FORMAT_NUMBER)),"";if(!isNumber(args[0]))return"production"!==process.env.NODE_ENV&&onWarn(getWarnMessage$1(CoreWarnCodes_INVALID_NUMBER_ARGUMENT,{value:String(args[0])})),"";const[key,value,options,overrides]=parseNumberArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,part=!!options.part,locale2=getLocale(context,options);if(!isString(key)||""===key){const formatter2=new Intl.NumberFormat(locale2.replace(/!/g,""),overrides);return part?formatter2.formatToParts(value):formatter2.format(value)}const targetLocale=resolveFormatLocale(context,key,locale2,numberFormats,missingWarn,fallbackWarn,"number format");if(!isString(targetLocale))return unresolving?-1:key;const format2=numberFormats[targetLocale][key],id=getFormatterCacheKey(targetLocale,key,overrides);let formatter=__numberFormatters.get(id);return formatter||(formatter=new Intl.NumberFormat(targetLocale,assign({},format2,overrides)),__numberFormatters.set(id,formatter)),part?formatter.formatToParts(value):formatter.format(value)}const NUMBER_FORMAT_OPTIONS_KEYS=["localeMatcher","style","currency","currencyDisplay","currencySign","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","compactDisplay","notation","signDisplay","unit","unitDisplay","roundingMode","roundingPriority","roundingIncrement","trailingZeroDisplay"];function parseNumberArgs(...args){const[arg1]=args,options=create(),initialOverrides=create();if(!isNumber(arg1))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);const value=arg1,overrides=parseFormatArgs(args,options,initialOverrides,NUMBER_FORMAT_OPTIONS_KEYS);return[options.key||"",value,options,overrides]}function clearNumberFormat(ctx,locale2,format2){clearFormatCache(ctx.__numberFormatters,locale2,format2)}const DEFAULT_MODIFIER=str=>str,DEFAULT_MESSAGE=ctx=>"",DEFAULT_NORMALIZE=values=>0===values.length?"":join(values),DEFAULT_INTERPOLATE=val=>null==val?"":isArray(val)||isPlainObject(val)&&val.toString===objectToString?JSON.stringify(val,null,2):String(val);function pluralDefault(choice,choicesLength){return choice=Math.abs(choice),2===choicesLength?1===choice?0:1:Math.min(choice,2)}function createMessageContext(options={}){const locale2=options.locale,pluralIndex=function(options){const index2=isNumber(options.pluralIndex)?options.pluralIndex:-1;return isNumber(options.named?.count)?options.named.count:isNumber(options.named?.n)?options.named.n:index2}(options),pluralRule=isString(locale2)&&isFunction(options.pluralRules?.[locale2])?options.pluralRules[locale2]:pluralDefault,orgPluralRule=pluralRule===pluralDefault?void 0:pluralDefault,_list=options.list||[],_named=options.named||create();isNumber(options.pluralIndex)&&(_named.count||=options.pluralIndex,_named.n||=options.pluralIndex);function message(key,useLinked){const msg=isFunction(options.messages)?options.messages(key,!!useLinked):!!isObject(options.messages)&&options.messages[key];return msg||(options.parent?options.parent.message(key):DEFAULT_MESSAGE)}const normalize=isFunction(options.processor?.normalize)?options.processor.normalize:DEFAULT_NORMALIZE,interpolate=isFunction(options.processor?.interpolate)?options.processor.interpolate:DEFAULT_INTERPOLATE,ctx={list:index2=>_list[index2],named:key=>_named[key],plural:messages2=>messages2[pluralRule(pluralIndex,messages2.length,orgPluralRule)],linked:(key,...args)=>{const[arg1,arg2]=args;let type2="text",modifier="";1===args.length?isObject(arg1)?(modifier=arg1.modifier||modifier,type2=arg1.type||type2):isString(arg1)&&(modifier=arg1||modifier):2===args.length&&(isString(arg1)&&(modifier=arg1||modifier),isString(arg2)&&(type2=arg2||type2));const ret=message(key,!0)(ctx),resolved=""===ret||void 0===ret?key:ret,msg="vnode"===type2&&isArray(resolved)&&modifier?resolved[0]:resolved;return modifier?(name=modifier,options.modifiers?options.modifiers[name]:DEFAULT_MODIFIER)(msg,type2):msg;var name},message:message,type:isString(options.processor?.type)?options.processor.type:"text",interpolate:interpolate,normalize:normalize,values:assign(create(),_list,_named)};return ctx}const NOOP_MESSAGE_FUNCTION=()=>"",isMessageFunction=val=>isFunction(val);function translate(context,...args){const{fallbackFormat:fallbackFormat,postTranslation:postTranslation,unresolving:unresolving,messageCompiler:messageCompiler,fallbackLocale:fallbackLocale,messages:messages2}=context,[key,options]=parseTranslateArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,escapeParameter=isBoolean(options.escapeParameter)?options.escapeParameter:context.escapeParameter,resolvedMessage=!!options.resolvedMessage,defaultMsgOrKey=isString(options.default)||isBoolean(options.default)?isBoolean(options.default)?messageCompiler?key:()=>key:options.default:fallbackFormat?messageCompiler?key:()=>key:null,enableDefaultMsg=fallbackFormat||null!=defaultMsgOrKey&&(isString(defaultMsgOrKey)||isFunction(defaultMsgOrKey)),locale2=getLocale(context,options);escapeParameter&&function(options){isArray(options.list)?options.list=options.list.map(item=>isString(item)?escapeHtml(item):item):isObject(options.named)&&Object.keys(options.named).forEach(key=>{isString(options.named[key])&&(options.named[key]=escapeHtml(options.named[key]))})}(options);let[formatScope,targetLocale,message]=resolvedMessage?[key,locale2,messages2[locale2]||create()]:resolveMessageFormat(context,key,locale2,fallbackLocale,fallbackWarn,missingWarn),format2=formatScope,cacheBaseKey=key;if(resolvedMessage||isString(format2)||isMessageAST(format2)||isMessageFunction(format2)||enableDefaultMsg&&(format2=defaultMsgOrKey,cacheBaseKey=format2),!(resolvedMessage||(isString(format2)||isMessageAST(format2)||isMessageFunction(format2))&&isString(targetLocale)))return unresolving?-1:key;if("production"!==process.env.NODE_ENV&&isString(format2)&&null==context.messageCompiler)return warn(`The message format compilation is not supported in this build. Because message compiler isn't included. You need to pre-compilation all message format. So translate function return '${key}'.`),key;let occurred=!1;const msg=isMessageFunction(format2)?format2:compileMessageFormat(context,key,targetLocale,format2,cacheBaseKey,()=>{occurred=!0});if(occurred)return format2;const ctxOptions=function(context,locale2,message,options){const{modifiers:modifiers,pluralRules:pluralRules,messageResolver:resolveValue2,fallbackLocale:fallbackLocale,fallbackWarn:fallbackWarn,missingWarn:missingWarn,fallbackContext:fallbackContext}=context,resolveMessage=(key,useLinked)=>{let val=resolveValue2(message,key);if(null==val&&(fallbackContext||useLinked)){const[format2,,message2]=resolveMessageFormat(fallbackContext||context,key,locale2,fallbackLocale,fallbackWarn,missingWarn);val=format2??resolveValue2(message2,key)}if(isString(val)||isMessageAST(val)){let occurred=!1;const msg=compileMessageFormat(context,key,locale2,val,key,()=>{occurred=!0});return occurred?NOOP_MESSAGE_FUNCTION:msg}return isMessageFunction(val)?val:NOOP_MESSAGE_FUNCTION},ctxOptions={locale:locale2,modifiers:modifiers,pluralRules:pluralRules,messages:resolveMessage};context.processor&&(ctxOptions.processor=context.processor);options.list&&(ctxOptions.list=options.list);options.named&&(ctxOptions.named=options.named);isNumber(options.plural)&&(ctxOptions.pluralIndex=options.plural);return ctxOptions}(context,targetLocale,message,options),messaged=function(context,msg,msgCtx){const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;let startTag,endTag,start=null;"production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-evaluation-start",endTag="intlify-message-evaluation-end",mark&&mark(startTag));const messaged=msg(msgCtx);if("production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&emitter.emit("message-evaluation",{type:"message-evaluation",value:messaged,time:end-start,groupId:toDevtoolsGroupId("translate",msg.key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message evaluation",startTag,endTag))}return messaged}(context,msg,createMessageContext(ctxOptions));let ret=postTranslation?postTranslation(messaged,key):messaged;var html;if(escapeParameter&&isString(ret)&&(html=(html=(html=ret).replace(/([\w:-]+)\s*=\s*"([^"]*)"/g,(_,attrName,attrValue)=>`${attrName}="${sanitizeAttributeValue(attrName,attrValue)}"`)).replace(/([\w:-]+)\s*=\s*'([^']*)'/g,(_,attrName,attrValue)=>`${attrName}='${sanitizeAttributeValue(attrName,attrValue)}'`),eventHandlerPattern.test(html)&&("production"!==process.env.NODE_ENV&&warn("Potentially dangerous event handlers detected in translation. Consider removing onclick, onerror, etc. from your translation messages."),html=html.replace(eventHandlerAttributePattern,"$1on$2")),ret=html.replace(unquotedUrlAttributePattern,(match,boundary,prefix,attrValue)=>hasJavascriptScheme(attrValue)?`${boundary}${prefix}about:blank`:match)),"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__){const payloads={timestamp:Date.now(),key:isString(key)?key:isMessageFunction(format2)?format2.key:"",locale:targetLocale||(isMessageFunction(format2)?format2.locale:""),format:isString(format2)?format2:isMessageFunction(format2)?format2.source:"",message:ret};payloads.meta=assign({},context.__meta,/* @__PURE__ */getAdditionalMeta()||{}),translateDevTools(payloads)}return ret}function resolveMessageFormat(context,key,locale2,fallbackLocale,fallbackWarn,missingWarn){const{messages:messages2,onWarn:onWarn,messageResolver:resolveValue2,localeFallbacker:localeFallbacker}=context,locales=localeFallbacker(context,fallbackLocale,locale2);let targetLocale,message=create(),format2=null,from=locale2,to2=null;const type="translate";for(let i=0;i<locales.length;i++){targetLocale=to2=locales[i],"production"!==process.env.NODE_ENV&&locale2!==targetLocale&&!isAlmostSameLocale(locale2,targetLocale)&&isTranslateFallbackWarn(fallbackWarn,key)&&onWarn(getWarnMessage$1(CoreWarnCodes_FALLBACK_TO_TRANSLATE,{key:key,target:targetLocale}));const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;"production"!==process.env.NODE_ENV&&locale2!==targetLocale&&emitter&&emitter.emit("fallback",{type:type,key:key,from:from,to:to2,groupId:toDevtoolsGroupId(type,key)}),message=messages2[targetLocale]||create();let startTag,endTag,start=null;if("production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-resolve-start",endTag="intlify-message-resolve-end",mark&&mark(startTag)),null===(format2=resolveValue2(message,key))&&(format2=message[key]),"production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&format2&&emitter.emit("message-resolve",{type:"message-resolve",key:key,message:format2,time:end-start,groupId:toDevtoolsGroupId(type,key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message resolve",startTag,endTag))}if(isString(format2)||isMessageAST(format2)||isMessageFunction(format2))break;if(!isImplicitFallback(targetLocale,locales)){const missingRet=handleMissing(context,key,targetLocale,missingWarn,type);missingRet!==key&&(format2=missingRet)}from=to2}return[format2,targetLocale,message]}function compileMessageFormat(context,key,targetLocale,format2,cacheBaseKey,onError){const{messageCompiler:messageCompiler,warnHtmlMessage:warnHtmlMessage}=context;if(isMessageFunction(format2)){const msg2=format2;return msg2.locale=msg2.locale||targetLocale,msg2.key=msg2.key||key,msg2}if(null==messageCompiler){const msg2=()=>format2;return msg2.locale=targetLocale,msg2.key=key,msg2}const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;let startTag,endTag,start=null;"production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-compilation-start",endTag="intlify-message-compilation-end",mark&&mark(startTag));const msg=messageCompiler(format2,function(context,locale2,key,source,warnHtmlMessage,onError){return{locale:locale2,key:key,warnHtmlMessage:warnHtmlMessage,onError:err=>{if(onError&&onError(err),"production"!==process.env.NODE_ENV){const _source=function(source){if(isString(source))return source;if(source.loc&&source.loc.source)return source.loc.source}(source),codeFrame=err.location&&_source&&function(source,start=0,end=source.length){const lines=source.split(/\r?\n/);let count=0;const res=[];for(let i=0;i<lines.length;i++)if(count+=lines[i].length+1,count>=start){for(let j=i-2;j<=i+2||end>count;j++){if(j<0||j>=lines.length)continue;const line=j+1;res.push(`${line}${" ".repeat(3-String(line).length)}| ${lines[j]}`);const lineLength=lines[j].length;if(j===i){const pad=start-(count-lineLength)+1,length=Math.max(1,end>count?lineLength-pad:end-start);res.push(" | "+" ".repeat(pad)+"^".repeat(length))}else if(j>i){if(end>count){const length=Math.max(Math.min(end-count,lineLength),1);res.push(" | "+"^".repeat(length))}count+=lineLength+1}}break}return res.join("\n")}(_source,err.location.start.offset,err.location.end.offset),emitter=context.__v_emitter;emitter&&_source&&emitter.emit("compile-error",{message:_source,error:err.message,start:err.location&&err.location.start.offset,end:err.location&&err.location.end.offset,groupId:toDevtoolsGroupId("translate",key)});const message=`Message compilation error: ${err.message}`;throw new SyntaxError(codeFrame?`${message}\n${codeFrame}`:message)}throw err},onCacheKey:source2=>((locale2,key,source)=>friendlyJSONstringify({l:locale2,k:key,s:source}))(locale2,key,source2)}}(context,targetLocale,cacheBaseKey,format2,warnHtmlMessage,onError));if("production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&emitter.emit("message-compilation",{type:"message-compilation",message:format2,time:end-start,groupId:toDevtoolsGroupId("translate",key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message compilation",startTag,endTag))}return msg.locale=targetLocale,msg.key=key,msg.source=format2,msg}function parseTranslateArgs(...args){const[arg1,arg2,arg3]=args,options=create();if(!(isString(arg1)||isNumber(arg1)||isMessageFunction(arg1)||isMessageAST(arg1)))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);const key=isNumber(arg1)?String(arg1):(isMessageFunction(arg1),arg1);return isNumber(arg2)?options.plural=arg2:isString(arg2)?options.default=arg2:isPlainObject(arg2)&&!isEmptyObject(arg2)?options.named=arg2:isArray(arg2)&&(options.list=arg2),isNumber(arg3)?options.plural=arg3:isString(arg3)?options.default=arg3:isPlainObject(arg3)&&assign(options,arg3),[key,options]}function getTarget(){return"undefined"!=typeof navigator&&"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:{}}"boolean"!=typeof __INTLIFY_PROD_DEVTOOLS__&&(getGlobalThis().__INTLIFY_PROD_DEVTOOLS__=!1),"boolean"!=typeof __INTLIFY_DROP_MESSAGE_COMPILER__&&(getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__=!1);const isProxyAvailable="function"==typeof Proxy;let supported,perf;function now(){return void 0!==supported||("undefined"!=typeof window&&window.performance?(supported=!0,perf=window.performance):"undefined"!=typeof globalThis&&(null===(_a2=globalThis.perf_hooks)||void 0===_a2?void 0:_a2.performance)?(supported=!0,perf=globalThis.perf_hooks.performance):supported=!1),supported?perf.now():Date.now();var _a2}class ApiProxy{constructor(plugin,hook){this.target=null,this.targetQueue=[],this.onQueue=[],this.plugin=plugin,this.hook=hook;const defaultSettings={};if(plugin.settings)for(const id in plugin.settings){const item=plugin.settings[id];defaultSettings[id]=item.defaultValue}const localSettingsSaveId=`__vue-devtools-plugin-settings__${plugin.id}`;let currentSettings=Object.assign({},defaultSettings);try{const raw=localStorage.getItem(localSettingsSaveId),data=JSON.parse(raw);Object.assign(currentSettings,data)}catch(e){}this.fallbacks={getSettings:()=>currentSettings,setSettings(value){try{localStorage.setItem(localSettingsSaveId,JSON.stringify(value))}catch(e){}currentSettings=value},now:()=>now()},hook&&hook.on("plugin:settings:set",(pluginId,value)=>{pluginId===this.plugin.id&&this.fallbacks.setSettings(value)}),this.proxiedOn=new Proxy({},{get:(_target,prop)=>this.target?this.target.on[prop]:(...args)=>{this.onQueue.push({method:prop,args:args})}}),this.proxiedTarget=new Proxy({},{get:(_target,prop)=>this.target?this.target[prop]:"on"===prop?this.proxiedOn:Object.keys(this.fallbacks).includes(prop)?(...args)=>(this.targetQueue.push({method:prop,args:args,resolve:()=>{}}),this.fallbacks[prop](...args)):(...args)=>new Promise(resolve=>{this.targetQueue.push({method:prop,args:args,resolve:resolve})})})}async setRealTarget(target){this.target=target;for(const item of this.onQueue)this.target.on[item.method](...item.args);for(const item of this.targetQueue)item.resolve(await this.target[item.method](...item.args))}}function setupDevtoolsPlugin(pluginDescriptor,setupFn){const descriptor=pluginDescriptor,target=getTarget(),hook=getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__,enableProxy=isProxyAvailable&&descriptor.enableEarlyProxy;if(!hook||!target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__&&enableProxy){const proxy=enableProxy?new ApiProxy(descriptor,hook):null;(target.__VUE_DEVTOOLS_PLUGINS__=target.__VUE_DEVTOOLS_PLUGINS__||[]).push({pluginDescriptor:descriptor,setupFn:setupFn,proxy:proxy}),proxy&&setupFn(proxy.proxiedTarget)}else hook.emit("devtools-plugin:setup",pluginDescriptor,setupFn)}const I18nErrorCodes_UNEXPECTED_RETURN_TYPE=24,I18nErrorCodes_INVALID_ARGUMENT=25,I18nErrorCodes_MUST_BE_CALL_SETUP_TOP=26,I18nErrorCodes_NOT_INSTALLED=27,I18nErrorCodes_REQUIRED_VALUE=28,I18nErrorCodes_INVALID_VALUE=29,I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN=30,I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE=31,I18nErrorCodes_UNEXPECTED_ERROR=32,I18nErrorCodes_NOT_COMPATIBLE_LEGACY_VUE_I18N=33,I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY=34;function createI18nError(code,...args){return createCompileError(code,null,"production"!==process.env.NODE_ENV?{messages:errorMessages,args:args}:void 0)}const errorMessages={[I18nErrorCodes_UNEXPECTED_RETURN_TYPE]:"Unexpected return type in composer",[I18nErrorCodes_INVALID_ARGUMENT]:"Invalid argument",[I18nErrorCodes_MUST_BE_CALL_SETUP_TOP]:"Must be called at the top of a `setup` function",[I18nErrorCodes_NOT_INSTALLED]:"Need to install with `app.use` function",[I18nErrorCodes_UNEXPECTED_ERROR]:"Unexpected error",[I18nErrorCodes_REQUIRED_VALUE]:"Required in value: {0}",[I18nErrorCodes_INVALID_VALUE]:"Invalid value",[I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]:"Cannot setup vue-devtools plugin",[I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE]:"Need to install with `provide` function",[I18nErrorCodes_NOT_COMPATIBLE_LEGACY_VUE_I18N]:"Not compatible legacy VueI18n.",[I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY]:"Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly"},TranslateVNodeSymbol=/* @__PURE__ */makeSymbol("__translateVNode"),DatetimePartsSymbol=/* @__PURE__ */makeSymbol("__datetimeParts"),NumberPartsSymbol=/* @__PURE__ */makeSymbol("__numberParts"),EnableEmitter=/* @__PURE__ */makeSymbol("__enableEmitter"),DisableEmitter=/* @__PURE__ */makeSymbol("__disableEmitter"),SetPluralRulesSymbol=makeSymbol("__setPluralRules"),InejctWithOptionSymbol=/* @__PURE__ */makeSymbol("__injectWithOption"),DisposeSymbol=/* @__PURE__ */makeSymbol("__dispose"),I18nWarnCodes={FALLBACK_TO_ROOT:10,NOT_FOUND_PARENT_SCOPE:11,IGNORE_OBJ_FLATTEN:12,DEPRECATE_LEGACY_MODE:13,DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE:14,DUPLICATE_USE_I18N_CALLING:15},warnMessages={[I18nWarnCodes.FALLBACK_TO_ROOT]:"Fall back to {type} '{key}' with root locale.",[I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]:"Not found parent scope. use the global scope.",[I18nWarnCodes.IGNORE_OBJ_FLATTEN]:"Ignore object flatten: '{key}' key has an string value",[I18nWarnCodes.DEPRECATE_LEGACY_MODE]:"Legacy API mode has been deprecated in v11. Use Composition API mode instead.\nAbout how to use the Composition API mode, see https://vue-i18n.intlify.dev/guide/advanced/composition.html",[I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE]:"'v-t' has been deprecated in v11. Use translate APIs ('t' or '$t') instead.",[I18nWarnCodes.DUPLICATE_USE_I18N_CALLING]:"Duplicate `useI18n` calling by local scope. Please don't call it on local scope, due to it does not work properly in component."};function getWarnMessage(code,...args){return format$1(warnMessages[code],...args)}let mirroredCurrentInstance=null;{const setters=getGlobalThis().__VUE_INSTANCE_SETTERS__;isArray(setters)&&setters.push(instance=>{mirroredCurrentInstance=instance})}function handleFlatJson(obj){if(!isObject(obj))return obj;if(isMessageAST(obj))return obj;for(const key in obj)if(hasOwn(obj,key))if(key.includes(".")){const subKeys=key.split("."),lastIndex=subKeys.length-1;let currentObj=obj,hasStringValue=!1;for(let i=0;i<lastIndex;i++){if("__proto__"===subKeys[i])throw new Error(`unsafe key: ${subKeys[i]}`);if(subKeys[i]in currentObj||(currentObj[subKeys[i]]=create()),!isObject(currentObj[subKeys[i]])){"production"!==process.env.NODE_ENV&&warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN,{key:subKeys[i]})),hasStringValue=!0;break}currentObj=currentObj[subKeys[i]]}if(hasStringValue||(isMessageAST(currentObj)?AST_NODE_PROPS_KEYS.includes(subKeys[lastIndex])||delete obj[key]:(currentObj[subKeys[lastIndex]]=obj[key],delete obj[key])),!isMessageAST(currentObj)){const target=currentObj[subKeys[lastIndex]];isObject(target)&&handleFlatJson(target)}}else isObject(obj[key])&&handleFlatJson(obj[key]);return obj}function getLocaleMessages(locale2,options){const{messages:messages2,__i18n:__i18n,messageResolver:messageResolver,flatJson:flatJson}=options,ret=isPlainObject(messages2)?messages2:isArray(__i18n)?create():{[locale2]:create()};if(isArray(__i18n)&&__i18n.forEach(custom=>{if("locale"in custom&&"resource"in custom){const{locale:locale22,resource:resource}=custom;locale22?(ret[locale22]=ret[locale22]||create(),deepCopy(resource,ret[locale22])):deepCopy(resource,ret)}else isString(custom)&&deepCopy(JSON.parse(custom),ret)}),null==messageResolver&&flatJson)for(const key in ret)hasOwn(ret,key)&&handleFlatJson(ret[key]);return ret}function getComponentOptions(instance){return instance.type}function adjustI18nResources(gl,options,componentOptions){let messages2=isObject(options.messages)?options.messages:create();"__i18nGlobal"in componentOptions&&(messages2=getLocaleMessages(gl.locale.value,{messages:messages2,__i18n:componentOptions.__i18nGlobal}));const locales=Object.keys(messages2);if(locales.length&&locales.forEach(locale2=>{gl.mergeLocaleMessage(locale2,messages2[locale2])}),isObject(options.datetimeFormats)){const locales2=Object.keys(options.datetimeFormats);locales2.length&&locales2.forEach(locale2=>{gl.mergeDateTimeFormat(locale2,options.datetimeFormats[locale2])})}if(isObject(options.numberFormats)){const locales2=Object.keys(options.numberFormats);locales2.length&&locales2.forEach(locale2=>{gl.mergeNumberFormat(locale2,options.numberFormats[locale2])})}}function createTextNode(key){return createVNode(Text,null,key,0)}function getCurrentInstance(){return mirroredCurrentInstance??getCurrentInstance$1()}const NOOP_RETURN_ARRAY=()=>[],NOOP_RETURN_FALSE=()=>!1;let composerID=0;function defineCoreMissingHandler(missing){return(ctx,locale2,key,type)=>missing(locale2,key,getCurrentInstance()||void 0,type)}function createComposer(options={}){const{__root:__root,__injectWithOption:__injectWithOption}=options,_isGlobal=void 0===__root,flatJson=options.flatJson,_ref=inBrowser?ref:shallowRef;let _inheritLocale=!isBoolean(options.inheritLocale)||options.inheritLocale;const _locale=_ref(__root&&_inheritLocale?__root.locale.value:isString(options.locale)?options.locale:DEFAULT_LOCALE),_fallbackLocale=_ref(__root&&_inheritLocale?__root.fallbackLocale.value:isString(options.fallbackLocale)||isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:_locale.value),_messages=_ref(getLocaleMessages(_locale.value,options)),_datetimeFormats=_ref(isPlainObject(options.datetimeFormats)?options.datetimeFormats:{[_locale.value]:{}}),_numberFormats=_ref(isPlainObject(options.numberFormats)?options.numberFormats:{[_locale.value]:{}});let _missingWarn=__root?__root.missingWarn:!isBoolean(options.missingWarn)&&!isRegExp(options.missingWarn)||options.missingWarn,_fallbackWarn=__root?__root.fallbackWarn:!isBoolean(options.fallbackWarn)&&!isRegExp(options.fallbackWarn)||options.fallbackWarn,_fallbackRoot=__root?__root.fallbackRoot:!isBoolean(options.fallbackRoot)||options.fallbackRoot,_fallbackFormat=!!options.fallbackFormat,_missing=isFunction(options.missing)?options.missing:null,_runtimeMissing=isFunction(options.missing)?defineCoreMissingHandler(options.missing):null,_postTranslation=isFunction(options.postTranslation)?options.postTranslation:null,_warnHtmlMessage=__root?__root.warnHtmlMessage:!isBoolean(options.warnHtmlMessage)||options.warnHtmlMessage,_escapeParameter=!!options.escapeParameter;const _modifiers=__root?__root.modifiers:isPlainObject(options.modifiers)?options.modifiers:{};let _context,_pluralRules=options.pluralRules||__root&&__root.pluralRules;_context=(()=>{_isGlobal&&setFallbackContext(null);const ctxOptions={version:"11.4.10",locale:_locale.value,fallbackLocale:_fallbackLocale.value,messages:_messages.value,modifiers:_modifiers,pluralRules:_pluralRules,missing:null===_runtimeMissing?void 0:_runtimeMissing,missingWarn:_missingWarn,fallbackWarn:_fallbackWarn,fallbackFormat:_fallbackFormat,unresolving:!0,postTranslation:null===_postTranslation?void 0:_postTranslation,warnHtmlMessage:_warnHtmlMessage,escapeParameter:_escapeParameter,messageResolver:options.messageResolver,messageCompiler:options.messageCompiler,__meta:{framework:"vue"}};ctxOptions.datetimeFormats=_datetimeFormats.value,ctxOptions.numberFormats=_numberFormats.value,ctxOptions.__datetimeFormatters=isPlainObject(_context)?_context.__datetimeFormatters:void 0,ctxOptions.__numberFormatters=isPlainObject(_context)?_context.__numberFormatters:void 0,"production"!==process.env.NODE_ENV&&(ctxOptions.__v_emitter=isPlainObject(_context)?_context.__v_emitter:void 0);const ctx=createCoreContext(ctxOptions);return _isGlobal&&setFallbackContext(ctx),ctx})(),updateFallbackLocale(_context,_locale.value,_fallbackLocale.value);const locale2=computed({get:()=>_locale.value,set:val=>{_context.locale=val,_locale.value=val}}),fallbackLocale=computed({get:()=>_fallbackLocale.value,set:val=>{_context.fallbackLocale=val,_fallbackLocale.value=val,updateFallbackLocale(_context,_locale.value,val)}}),messages2=computed(()=>_messages.value),datetimeFormats=/* @__PURE__ */computed(()=>_datetimeFormats.value),numberFormats=/* @__PURE__ */computed(()=>_numberFormats.value);const wrapWithDeps=(fn2,argumentParser,warnType,fallbackSuccess,fallbackFail,successCondition)=>{let ret;_locale.value,_fallbackLocale.value,_messages.value,_datetimeFormats.value,_numberFormats.value;try{"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__,_isGlobal||(_context.fallbackContext=__root?_fallbackContext:void 0),ret=fn2(_context)}finally{"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__,_isGlobal||(_context.fallbackContext=void 0)}if("translate exists"!==warnType&&isNumber(ret)&&-1===ret||"translate exists"===warnType&&!ret){const[key,arg2]=argumentParser();if("production"!==process.env.NODE_ENV&&__root&&isString(key)&&(arg=arg2,"translate"!==warnType||!arg.resolvedMessage)&&(_fallbackRoot&&(isTranslateFallbackWarn(_fallbackWarn,key)||isTranslateMissingWarn(_missingWarn,key))&&warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT,{key:key,type:warnType})),"production"!==process.env.NODE_ENV)){const{__v_emitter:emitter}=_context;emitter&&_fallbackRoot&&emitter.emit("fallback",{type:warnType,key:key,to:"global",groupId:toDevtoolsGroupId(warnType,key)})}return __root&&_fallbackRoot?fallbackSuccess(__root):fallbackFail(key)}if(successCondition(ret))return ret;throw createI18nError(I18nErrorCodes_UNEXPECTED_RETURN_TYPE);var arg};function t2(...args){return wrapWithDeps(context=>Reflect.apply(translate,null,[context,...args]),()=>parseTranslateArgs(...args),"translate",root=>Reflect.apply(root.t,root,[...args]),key=>key,val=>isString(val))}const processor={normalize:function(values){return values.map(val=>isString(val)||isNumber(val)||isBoolean(val)?createTextNode(String(val)):val)},interpolate:val=>val,type:"vnode"};function getLocaleMessage(locale22){return _messages.value[locale22]||{}}composerID++,__root&&inBrowser&&(watch(__root.locale,val=>{_inheritLocale&&(_locale.value=val,_context.locale=val,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))}),watch(__root.fallbackLocale,val=>{_inheritLocale&&(_fallbackLocale.value=val,_context.fallbackLocale=val,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))}));const composer={id:composerID,locale:locale2,fallbackLocale:fallbackLocale,get inheritLocale(){return _inheritLocale},set inheritLocale(val){_inheritLocale=val,val&&__root&&(_locale.value=__root.locale.value,_fallbackLocale.value=__root.fallbackLocale.value,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))},get availableLocales(){return Object.keys(_messages.value).sort()},messages:messages2,get modifiers(){return _modifiers},get pluralRules(){return _pluralRules||{}},get isGlobal(){return _isGlobal},get missingWarn(){return _missingWarn},set missingWarn(val){_missingWarn=val,_context.missingWarn=_missingWarn},get fallbackWarn(){return _fallbackWarn},set fallbackWarn(val){_fallbackWarn=val,_context.fallbackWarn=_fallbackWarn},get fallbackRoot(){return _fallbackRoot},set fallbackRoot(val){_fallbackRoot=val},get fallbackFormat(){return _fallbackFormat},set fallbackFormat(val){_fallbackFormat=val,_context.fallbackFormat=_fallbackFormat},get warnHtmlMessage(){return _warnHtmlMessage},set warnHtmlMessage(val){_warnHtmlMessage=val,_context.warnHtmlMessage=val},get escapeParameter(){return _escapeParameter},set escapeParameter(val){_escapeParameter=val,_context.escapeParameter=val},t:t2,getLocaleMessage:getLocaleMessage,setLocaleMessage:function(locale22,message){if(flatJson){const _message={[locale22]:message};for(const key in _message)hasOwn(_message,key)&&handleFlatJson(_message[key]);message=_message[locale22]}_messages.value[locale22]=message,_context.messages=_messages.value},mergeLocaleMessage:function(locale22,message){_messages.value[locale22]=_messages.value[locale22]||{};const _message={[locale22]:message};if(flatJson)for(const key in _message)hasOwn(_message,key)&&handleFlatJson(_message[key]);deepCopy(message=_message[locale22],_messages.value[locale22]),_context.messages=_messages.value},getPostTranslationHandler:function(){return isFunction(_postTranslation)?_postTranslation:null},setPostTranslationHandler:function(handler){_postTranslation=handler,_context.postTranslation=handler},getMissingHandler:function(){return _missing},setMissingHandler:function(handler){null!==handler&&(_runtimeMissing=defineCoreMissingHandler(handler)),_missing=handler,_context.missing=_runtimeMissing},[SetPluralRulesSymbol]:function(rules){_pluralRules=rules,_context.pluralRules=_pluralRules}};return composer.datetimeFormats=datetimeFormats,composer.numberFormats=numberFormats,composer.rt=function(...args){const[arg1,arg2,arg3]=args;if(arg3&&!isObject(arg3))throw createI18nError(I18nErrorCodes_INVALID_ARGUMENT);return t2(arg1,arg2,assign({resolvedMessage:!0},arg3||{}))},composer.te=function(key,locale22){return wrapWithDeps(()=>{if(!key)return!1;const targetLocale=isString(locale22)?locale22:_locale.value,locales=isString(locale22)?[targetLocale]:fallbackWithLocaleChain(_context,_fallbackLocale.value,targetLocale);for(let i=0;i<locales.length;i++){const message=getLocaleMessage(locales[i]);let resolved=_context.messageResolver(message,key);if(null===resolved&&(resolved=message[key]),isMessageAST(resolved)||isMessageFunction(resolved)||isString(resolved))return!0}return!1},()=>[key],"translate exists",root=>Reflect.apply(root.te,root,[key,locale22]),NOOP_RETURN_FALSE,val=>isBoolean(val))},composer.tm=function(key){const messages22=function(key){let messages22=null;const locales=fallbackWithLocaleChain(_context,_fallbackLocale.value,_locale.value);for(let i=0;i<locales.length;i++){const targetLocaleMessages=_messages.value[locales[i]]||{},messageValue=_context.messageResolver(targetLocaleMessages,key);if(null!=messageValue){messages22=messageValue;break}}return messages22}(key);return null!=messages22?messages22:__root&&__root.tm(key)||{}},composer.d=function(...args){return wrapWithDeps(context=>Reflect.apply(datetime,null,[context,...args]),()=>parseDateTimeArgs(...args),"datetime format",root=>Reflect.apply(root.d,root,[...args]),()=>"",val=>isString(val)||isArray(val))},composer.n=function(...args){return wrapWithDeps(context=>Reflect.apply(number,null,[context,...args]),()=>parseNumberArgs(...args),"number format",root=>Reflect.apply(root.n,root,[...args]),()=>"",val=>isString(val)||isArray(val))},composer.getDateTimeFormat=function(locale22){return _datetimeFormats.value[locale22]||{}},composer.setDateTimeFormat=function(locale22,format2){_datetimeFormats.value[locale22]=format2,_context.datetimeFormats=_datetimeFormats.value,clearDateTimeFormat(_context,locale22,format2)},composer.mergeDateTimeFormat=function(locale22,format2){_datetimeFormats.value[locale22]=assign(_datetimeFormats.value[locale22]||{},format2),_context.datetimeFormats=_datetimeFormats.value,clearDateTimeFormat(_context,locale22,format2)},composer.getNumberFormat=function(locale22){return _numberFormats.value[locale22]||{}},composer.setNumberFormat=function(locale22,format2){_numberFormats.value[locale22]=format2,_context.numberFormats=_numberFormats.value,clearNumberFormat(_context,locale22,format2)},composer.mergeNumberFormat=function(locale22,format2){_numberFormats.value[locale22]=assign(_numberFormats.value[locale22]||{},format2),_context.numberFormats=_numberFormats.value,clearNumberFormat(_context,locale22,format2)},composer[InejctWithOptionSymbol]=__injectWithOption,composer[TranslateVNodeSymbol]=function(...args){return wrapWithDeps(context=>{let ret;const _context2=context;try{_context2.processor=processor,ret=Reflect.apply(translate,null,[_context2,...args])}finally{_context2.processor=null}return ret},()=>parseTranslateArgs(...args),"translate",root=>root[TranslateVNodeSymbol](...args),key=>[createTextNode(key)],val=>isArray(val))},composer[DatetimePartsSymbol]=function(...args){return wrapWithDeps(context=>Reflect.apply(datetime,null,[context,...args]),()=>parseDateTimeArgs(...args),"datetime format",root=>root[DatetimePartsSymbol](...args),NOOP_RETURN_ARRAY,val=>isString(val)||isArray(val))},composer[NumberPartsSymbol]=function(...args){return wrapWithDeps(context=>Reflect.apply(number,null,[context,...args]),()=>parseNumberArgs(...args),"number format",root=>root[NumberPartsSymbol](...args),NOOP_RETURN_ARRAY,val=>isString(val)||isArray(val))},"production"!==process.env.NODE_ENV&&(composer[EnableEmitter]=emitter=>{_context.__v_emitter=emitter},composer[DisableEmitter]=()=>{_context.__v_emitter=void 0}),composer}const VueDevToolsLabels_vue_devtools_plugin_vue_i18n="Vue I18n DevTools",VueDevToolsLabels_vue_i18n_resource_inspector="Vue I18n DevTools",VueDevToolsLabels_vue_i18n_timeline="Vue I18n",VueDevToolsPlaceholders_vue_i18n_resource_inspector="Search for scopes ...",VueDevToolsTimelineColors_vue_i18n_timeline=16764185;let devtoolsApi;async function enableDevTools(app,i18n2){return new Promise((resolve,reject)=>{try{setupDevtoolsPlugin({id:"vue-devtools-plugin-vue-i18n",label:VueDevToolsLabels_vue_devtools_plugin_vue_i18n,packageName:"vue-i18n",homepage:"https://vue-i18n.intlify.dev",logo:"https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png",componentStateTypes:["vue-i18n: composer properties"],app:app},api=>{devtoolsApi=api,api.on.visitComponentTree(({componentInstance:componentInstance,treeNode:treeNode})=>{!function(instance,treeNode,i18n2){const global2="composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;if(instance&&instance.__VUE_I18N__&&instance.__VUE_I18N__!==global2){const tag={label:`i18n (${getI18nScopeLable(instance)} Scope)`,textColor:0,backgroundColor:16764185};treeNode.tags.push(tag)}}(componentInstance,treeNode,i18n2)}),api.on.inspectComponent(({componentInstance:componentInstance,instanceData:instanceData})=>{componentInstance.__VUE_I18N__&&instanceData&&("legacy"===i18n2.mode?componentInstance.__VUE_I18N__!==i18n2.global.__composer&&inspectComposer(instanceData,componentInstance.__VUE_I18N__):inspectComposer(instanceData,componentInstance.__VUE_I18N__))}),api.addInspector({id:"vue-i18n-resource-inspector",label:VueDevToolsLabels_vue_i18n_resource_inspector,icon:"language",treeFilterPlaceholder:VueDevToolsPlaceholders_vue_i18n_resource_inspector}),api.on.getInspectorTree(payload=>{payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId&&function(payload,i18n2){payload.rootNodes.push({id:"global",label:"Global Scope"});const global2="composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;for(const[keyInstance,instance]of i18n2.__instances){const composer="composition"===i18n2.mode?instance:instance.__composer;global2!==composer&&payload.rootNodes.push({id:composer.id.toString(),label:`${getI18nScopeLable(keyInstance)} Scope`})}}(payload,i18n2)});const roots=/* @__PURE__ */new Map;api.on.getInspectorState(async payload=>{if(payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId)if(api.unhighlightElement(),function(payload,i18n2){const composer=getComposer$2(payload.nodeId,i18n2);composer&&(payload.state=function(composer){const state={},localeType="Locale related info",localeStates=[{type:localeType,key:"locale",editable:!0,value:composer.locale.value},{type:localeType,key:"fallbackLocale",editable:!0,value:composer.fallbackLocale.value},{type:localeType,key:"availableLocales",editable:!1,value:composer.availableLocales},{type:localeType,key:"inheritLocale",editable:!0,value:composer.inheritLocale}];state[localeType]=localeStates;const localeMessagesType="Locale messages info",localeMessagesStates=[{type:localeMessagesType,key:"messages",editable:!1,value:getLocaleMessageValue(composer.messages.value)}];state[localeMessagesType]=localeMessagesStates;{const datetimeFormatsType="Datetime formats info",datetimeFormatsStates=[{type:datetimeFormatsType,key:"datetimeFormats",editable:!1,value:composer.datetimeFormats.value}];state[datetimeFormatsType]=datetimeFormatsStates;const numberFormatsType="Datetime formats info",numberFormatsStates=[{type:numberFormatsType,key:"numberFormats",editable:!1,value:composer.numberFormats.value}];state[numberFormatsType]=numberFormatsStates}return state}(composer))}(payload,i18n2),"global"===payload.nodeId){if(!roots.has(payload.app)){const[root]=await api.getComponentInstances(payload.app);roots.set(payload.app,root)}api.highlightElement(roots.get(payload.app))}else{const instance=function(nodeId,i18n2){let instance=null;if("global"!==nodeId)for(const[component,composer]of i18n2.__instances.entries())if(composer.id.toString()===nodeId){instance=component;break}return instance}(payload.nodeId,i18n2);instance&&api.highlightElement(instance)}}),api.on.editInspectorState(payload=>{payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId&&function(payload,i18n2){const composer=getComposer$2(payload.nodeId,i18n2);if(composer){const[field]=payload.path;"locale"===field&&isString(payload.state.value)?composer.locale.value=payload.state.value:"fallbackLocale"===field&&(isString(payload.state.value)||isArray(payload.state.value)||isObject(payload.state.value))?composer.fallbackLocale.value=payload.state.value:"inheritLocale"===field&&isBoolean(payload.state.value)&&(composer.inheritLocale=payload.state.value)}}(payload,i18n2)}),api.addTimelineLayer({id:"vue-i18n-timeline",label:VueDevToolsLabels_vue_i18n_timeline,color:VueDevToolsTimelineColors_vue_i18n_timeline}),resolve(!0)})}catch(e){console.error(e),reject(!1)}})}function getI18nScopeLable(instance){return instance.type.name||instance.type.displayName||instance.type.__file||"Anonymous"}function inspectComposer(instanceData,composer){const type="vue-i18n: composer properties";instanceData.state.push({type:type,key:"locale",editable:!0,value:composer.locale.value}),instanceData.state.push({type:type,key:"availableLocales",editable:!1,value:composer.availableLocales}),instanceData.state.push({type:type,key:"fallbackLocale",editable:!0,value:composer.fallbackLocale.value}),instanceData.state.push({type:type,key:"inheritLocale",editable:!0,value:composer.inheritLocale}),instanceData.state.push({type:type,key:"messages",editable:!1,value:getLocaleMessageValue(composer.messages.value)}),instanceData.state.push({type:type,key:"datetimeFormats",editable:!1,value:composer.datetimeFormats.value}),instanceData.state.push({type:type,key:"numberFormats",editable:!1,value:composer.numberFormats.value})}function getLocaleMessageValue(messages2){const value={};return Object.keys(messages2).forEach(key=>{const v2=messages2[key];var func;isFunction(v2)&&"source"in v2?value[key]={_custom:{type:"function",display:"<span>ƒ</span> "+((func=v2).source?`("${escape(func.source)}")`:"(?)")}}:isMessageAST(v2)&&v2.loc&&v2.loc.source?value[key]=v2.loc.source:isObject(v2)?value[key]=getLocaleMessageValue(v2):value[key]=v2}),value}const ESC={"<":"<",">":">",'"':""","&":"&"};function escape(s){return s.replace(/[<>"&]/g,escapeChar)}function escapeChar(a2){return ESC[a2]||a2}function getComposer$2(nodeId,i18n2){if("global"===nodeId)return"composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;{const instance=Array.from(i18n2.__instances.values()).find(item=>item.id.toString()===nodeId);return instance?"composition"===i18n2.mode?instance:instance.__composer:null}}function addTimelineEvent(event,payload){if(devtoolsApi){let groupId;payload&&"groupId"in payload&&(groupId=payload.groupId,delete payload.groupId),devtoolsApi.addTimelineEvent({layerId:"vue-i18n-timeline",event:{title:event,groupId:groupId,time:Date.now(),meta:{},data:payload||{},logType:"compile-error"===event?"error":"fallback"===event||"missing"===event?"warning":"default"}})}}function createVueI18n(options={}){const composer=createComposer(function(options){const locale2=isString(options.locale)?options.locale:DEFAULT_LOCALE,fallbackLocale=isString(options.fallbackLocale)||isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:locale2,missing=isFunction(options.missing)?options.missing:void 0,missingWarn=!isBoolean(options.silentTranslationWarn)&&!isRegExp(options.silentTranslationWarn)||!options.silentTranslationWarn,fallbackWarn=!isBoolean(options.silentFallbackWarn)&&!isRegExp(options.silentFallbackWarn)||!options.silentFallbackWarn,fallbackRoot=!isBoolean(options.fallbackRoot)||options.fallbackRoot,fallbackFormat=!!options.formatFallbackMessages,modifiers=isPlainObject(options.modifiers)?options.modifiers:{},pluralizationRules=options.pluralizationRules,postTranslation=isFunction(options.postTranslation)?options.postTranslation:void 0,warnHtmlMessage=!isString(options.warnHtmlInMessage)||"off"!==options.warnHtmlInMessage,escapeParameter=!!options.escapeParameterHtml,inheritLocale=!isBoolean(options.sync)||options.sync;let messages2=options.messages;if(isPlainObject(options.sharedMessages)){const sharedMessages=options.sharedMessages;messages2=Object.keys(sharedMessages).reduce((messages22,locale22)=>{const message=messages22[locale22]||(messages22[locale22]={});return assign(message,sharedMessages[locale22]),messages22},messages2||{})}const{__i18n:__i18n,__root:__root,__injectWithOption:__injectWithOption}=options,datetimeFormats=options.datetimeFormats,numberFormats=options.numberFormats;return{locale:locale2,fallbackLocale:fallbackLocale,messages:messages2,flatJson:options.flatJson,datetimeFormats:datetimeFormats,numberFormats:numberFormats,missing:missing,missingWarn:missingWarn,fallbackWarn:fallbackWarn,fallbackRoot:fallbackRoot,fallbackFormat:fallbackFormat,modifiers:modifiers,pluralRules:pluralizationRules,postTranslation:postTranslation,warnHtmlMessage:warnHtmlMessage,escapeParameter:escapeParameter,messageResolver:options.messageResolver,inheritLocale:inheritLocale,__i18n:__i18n,__root:__root,__injectWithOption:__injectWithOption}}(options)),{__extender:__extender}=options,vueI18n={id:composer.id,get locale(){return composer.locale.value},set locale(val){composer.locale.value=val},get fallbackLocale(){return composer.fallbackLocale.value},set fallbackLocale(val){composer.fallbackLocale.value=val},get messages(){return composer.messages.value},get datetimeFormats(){return composer.datetimeFormats.value},get numberFormats(){return composer.numberFormats.value},get availableLocales(){return composer.availableLocales},get missing(){return composer.getMissingHandler()},set missing(handler){composer.setMissingHandler(handler)},get silentTranslationWarn(){return isBoolean(composer.missingWarn)?!composer.missingWarn:composer.missingWarn},set silentTranslationWarn(val){composer.missingWarn=isBoolean(val)?!val:val},get silentFallbackWarn(){return isBoolean(composer.fallbackWarn)?!composer.fallbackWarn:composer.fallbackWarn},set silentFallbackWarn(val){composer.fallbackWarn=isBoolean(val)?!val:val},get modifiers(){return composer.modifiers},get formatFallbackMessages(){return composer.fallbackFormat},set formatFallbackMessages(val){composer.fallbackFormat=val},get postTranslation(){return composer.getPostTranslationHandler()},set postTranslation(handler){composer.setPostTranslationHandler(handler)},get sync(){return composer.inheritLocale},set sync(val){composer.inheritLocale=val},get warnHtmlInMessage(){return composer.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(val){composer.warnHtmlMessage="off"!==val},get escapeParameterHtml(){return composer.escapeParameter},set escapeParameterHtml(val){composer.escapeParameter=val},get pluralizationRules(){return composer.pluralRules||{}},__composer:composer,t:(...args)=>Reflect.apply(composer.t,composer,[...args]),rt:(...args)=>Reflect.apply(composer.rt,composer,[...args]),te:(key,locale2)=>composer.te(key,locale2),tm:key=>composer.tm(key),getLocaleMessage:locale2=>composer.getLocaleMessage(locale2),setLocaleMessage(locale2,message){composer.setLocaleMessage(locale2,message)},mergeLocaleMessage(locale2,message){composer.mergeLocaleMessage(locale2,message)},d:(...args)=>Reflect.apply(composer.d,composer,[...args]),getDateTimeFormat:locale2=>composer.getDateTimeFormat(locale2),setDateTimeFormat(locale2,format2){composer.setDateTimeFormat(locale2,format2)},mergeDateTimeFormat(locale2,format2){composer.mergeDateTimeFormat(locale2,format2)},n:(...args)=>Reflect.apply(composer.n,composer,[...args]),getNumberFormat:locale2=>composer.getNumberFormat(locale2),setNumberFormat(locale2,format2){composer.setNumberFormat(locale2,format2)},mergeNumberFormat(locale2,format2){composer.mergeNumberFormat(locale2,format2)}};return vueI18n.__extender=__extender,"production"!==process.env.NODE_ENV&&(vueI18n.__enableEmitter=emitter=>{const __composer=composer;__composer[EnableEmitter]&&__composer[EnableEmitter](emitter)},vueI18n.__disableEmitter=()=>{const __composer=composer;__composer[DisableEmitter]&&__composer[DisableEmitter]()}),vueI18n}function mergeToGlobal(g,options){g.locale=options.locale||g.locale,g.fallbackLocale=options.fallbackLocale||g.fallbackLocale,g.missing=options.missing||g.missing,g.silentTranslationWarn=options.silentTranslationWarn||g.silentFallbackWarn,g.silentFallbackWarn=options.silentFallbackWarn||g.silentFallbackWarn,g.formatFallbackMessages=options.formatFallbackMessages||g.formatFallbackMessages,g.postTranslation=options.postTranslation||g.postTranslation,g.warnHtmlInMessage=options.warnHtmlInMessage||g.warnHtmlInMessage,g.escapeParameterHtml=options.escapeParameterHtml||g.escapeParameterHtml,g.sync=options.sync||g.sync,g.__composer[SetPluralRulesSymbol](options.pluralizationRules||g.pluralizationRules);const messages2=getLocaleMessages(g.locale,{messages:options.messages,__i18n:options.__i18n});return Object.keys(messages2).forEach(locale2=>g.mergeLocaleMessage(locale2,messages2[locale2])),options.datetimeFormats&&Object.keys(options.datetimeFormats).forEach(locale2=>g.mergeDateTimeFormat(locale2,options.datetimeFormats[locale2])),options.numberFormats&&Object.keys(options.numberFormats).forEach(locale2=>g.mergeNumberFormat(locale2,options.numberFormats[locale2])),g}const baseFormatProps={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:val=>"parent"===val||"global"===val,default:"parent"},i18n:{type:Object}};function getFragmentableTag(){return Fragment}const Translation=/* @__PURE__ */defineComponent({name:"i18n-t",props:assign({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:val=>isNumber(val)||!isNaN(val)}},baseFormatProps),setup(props,context){const{slots:slots,attrs:attrs}=context,i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return()=>{const renderChildren=()=>{const keys=Object.keys(slots).filter(key=>"_"!==key[0]),options=create();props.locale&&(options.locale=props.locale),void 0!==props.plural&&(options.plural=isString(props.plural)?+props.plural:props.plural);const arg=function({slots:slots},keys){if(1===keys.length&&"default"===keys[0])return(slots.default?slots.default():[]).reduce((slot,current)=>[...slot,...current.type===Fragment?current.children:[current]],[]);return keys.reduce((arg,key)=>{const slot=slots[key];return slot&&(arg[key]=slot()),arg},create())}(context,keys);return i18n2[TranslateVNodeSymbol](props.keypath,arg,options)},assignedAttrs=assign(create(),attrs),tag=isString(props.tag)||isObject(props.tag)?props.tag:getFragmentableTag();return isObject(tag)?h(tag,assignedAttrs,{default:renderChildren}):h(tag,assignedAttrs,renderChildren())}}});function renderFormatter(props,context,slotKeys,partFormatter){const{slots:slots,attrs:attrs}=context;return()=>{const renderChildren=()=>{const options={part:!0};let overrides=create();props.locale&&(options.locale=props.locale),isString(props.format)?options.key=props.format:isObject(props.format)&&(isString(props.format.key)&&(options.key=props.format.key),overrides=Object.keys(props.format).reduce((options2,prop)=>slotKeys.includes(prop)?assign(create(),options2,{[prop]:props.format[prop]}):options2,create()));const parts=partFormatter(props.value,options,overrides);let children=[options.key];return isArray(parts)?children=parts.map((part,index2)=>{const slot=slots[part.type],node=slot?slot({[part.type]:part.value,index:index2,parts:parts}):[part.value];var target;return isArray(target=node)&&!isString(target[0])&&(node[0].key=`${part.type}-${index2}`),node}):isString(parts)&&(children=[parts]),children},assignedAttrs=assign(create(),attrs),tag=isString(props.tag)||isObject(props.tag)?props.tag:getFragmentableTag();return isObject(tag)?h(tag,assignedAttrs,{default:renderChildren}):h(tag,assignedAttrs,renderChildren())}}const NumberFormat=/* @__PURE__ */defineComponent({name:"i18n-n",props:assign({value:{type:Number,required:!0},format:{type:[String,Object]}},baseFormatProps),setup(props,context){const i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return renderFormatter(props,context,NUMBER_FORMAT_OPTIONS_KEYS,(...args)=>i18n2[NumberPartsSymbol](...args))}});function parseValue(value){if(isString(value))return{path:value};if(isPlainObject(value)){if(!("path"in value))throw createI18nError(I18nErrorCodes_REQUIRED_VALUE,"path");return value}throw createI18nError(I18nErrorCodes_INVALID_VALUE)}function makeParams(value){const{path:path,locale:locale2,args:args,choice:choice,plural:plural}=value,options={},named=args||{};return isString(locale2)&&(options.locale=locale2),isNumber(choice)&&(options.plural=choice),isNumber(plural)&&(options.plural=plural),[path,named,options]}function apply(app,i18n2,...options){const pluginOptions=isPlainObject(options[0])?options[0]:{};(!isBoolean(pluginOptions.globalInstall)||pluginOptions.globalInstall)&&([Translation.name,"I18nT"].forEach(name=>app.component(name,Translation)),[NumberFormat.name,"I18nN"].forEach(name=>app.component(name,NumberFormat)),[DatetimeFormat.name,"I18nD"].forEach(name=>app.component(name,DatetimeFormat))),app.directive("t",function(i18n2){const _process=binding=>{"production"!==process.env.NODE_ENV&&warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE));const{instance:instance,value:value}=binding;if(!instance||!instance.$)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const composer=function(i18n2,instance){const i18nInternal=i18n2;if("composition"===i18n2.mode)return i18nInternal.__getInstance(instance)||i18n2.global;{const vueI18n=i18nInternal.__getInstance(instance);return null!=vueI18n?vueI18n.__composer:i18n2.global.__composer}}(i18n2,instance.$),parsedValue=parseValue(value);return[Reflect.apply(composer.t,composer,[...makeParams(parsedValue)]),composer]};return{created:(el,binding)=>{const[textContent,composer]=_process(binding);inBrowser&&(el.__i18nWatcher=watch(composer.locale,()=>{binding.instance&&binding.instance.$forceUpdate()})),el.__composer=composer,el.textContent=textContent},unmounted:el=>{inBrowser&&el.__i18nWatcher&&(el.__i18nWatcher(),el.__i18nWatcher=void 0,delete el.__i18nWatcher),el.__composer&&(el.__composer=void 0,delete el.__composer)},beforeUpdate:(el,{value:value})=>{if(el.__composer){const composer=el.__composer,parsedValue=parseValue(value);el.textContent=Reflect.apply(composer.t,composer,[...makeParams(parsedValue)])}},getSSRProps:binding=>{const[textContent]=_process(binding);return{textContent:textContent}}}}(i18n2))}const I18nInjectionKey=/* @__PURE__ */makeSymbol("global-vue-i18n");function useI18n(options={}){const instance=getCurrentInstance();if(null==instance)throw createI18nError(I18nErrorCodes_MUST_BE_CALL_SETUP_TOP);if(!instance.isCE&&null!=instance.appContext.app&&!instance.appContext.app.__VUE_I18N_SYMBOL__)throw createI18nError(I18nErrorCodes_NOT_INSTALLED);const i18n2=function(instance){const i18n2=inject(instance.isCE?I18nInjectionKey:instance.appContext.app.__VUE_I18N_SYMBOL__);if(!i18n2)throw createI18nError(instance.isCE?I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE:I18nErrorCodes_UNEXPECTED_ERROR);return i18n2}(instance),gl=function(i18n2){return"composition"===i18n2.mode?i18n2.global:i18n2.global.__composer}(i18n2),componentOptions=getComponentOptions(instance),scope=function(options,componentOptions){return isEmptyObject(options)?"__i18n"in componentOptions?"local":"global":options.useScope?options.useScope:"local"}(options,componentOptions);if("global"===scope)return adjustI18nResources(gl,options,componentOptions),gl;if("parent"===scope){let composer2=getComposer(i18n2,instance,options.__useComponent);return null==composer2&&("production"!==process.env.NODE_ENV&&warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE)),composer2=gl),composer2}if("isolated"===scope){if("composition"!==i18n2.mode)throw createI18nError(I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY);const i18nInternalIso=i18n2,composerOptions=assign({},options),parentComposer=getComposer(i18n2,instance);composerOptions.__root=parentComposer||gl;const composer2=createComposer(composerOptions);i18nInternalIso.__composerExtend&&(composer2[DisposeSymbol]=i18nInternalIso.__composerExtend(composer2));let emitter=null;if("production"!==process.env.NODE_ENV){emitter=createEmitter();const _composer=composer2;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter),emitter.on("*",addTimelineEvent)}return getCurrentScope()&&onScopeDispose(()=>{if("production"!==process.env.NODE_ENV){emitter&&emitter.off("*",addTimelineEvent);const _composer=composer2;_composer[DisableEmitter]&&_composer[DisableEmitter]()}const dispose=composer2[DisposeSymbol];dispose&&(dispose(),delete composer2[DisposeSymbol])}),composer2}const i18nInternal=i18n2;let composer=i18nInternal.__getInstance(instance);if(null==composer){const composerOptions=assign({},options);"__i18n"in componentOptions&&(composerOptions.__i18n=componentOptions.__i18n),gl&&(composerOptions.__root=gl),composer=createComposer(composerOptions),i18nInternal.__composerExtend&&(composer[DisposeSymbol]=i18nInternal.__composerExtend(composer)),function(i18n2,target,composer){let emitter=null;onMounted(()=>{if("production"!==process.env.NODE_ENV){target.__VUE_I18N__=composer,emitter=createEmitter();const _composer=composer;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter),emitter.on("*",addTimelineEvent)}},target),onUnmounted(()=>{const _composer=composer;"production"!==process.env.NODE_ENV&&(emitter&&emitter.off("*",addTimelineEvent),_composer[DisableEmitter]&&_composer[DisableEmitter](),delete target.__VUE_I18N__),i18n2.__deleteInstance(target);const dispose=_composer[DisposeSymbol];dispose&&(dispose(),delete _composer[DisposeSymbol])},target)}(i18nInternal,instance,composer),i18nInternal.__setInstance(instance,composer)}else"production"!==process.env.NODE_ENV&&"local"===scope&&warn(getWarnMessage(I18nWarnCodes.DUPLICATE_USE_I18N_CALLING));return composer}function getComposer(i18n2,target,useComponent=!1){let composer=null;const root=target.root;let current=function(target,useComponent=!1){if(null==target)return null;return useComponent&&target.vnode.ctx||target.parent}(target,useComponent);for(;null!=current;){const i18nInternal=i18n2;if("composition"===i18n2.mode)composer=i18nInternal.__getInstance(current);else if(__VUE_I18N_LEGACY_API__){const vueI18n=i18nInternal.__getInstance(current);null!=vueI18n&&(composer=vueI18n.__composer,useComponent&&composer&&!composer[InejctWithOptionSymbol]&&(composer=null))}if(null!=composer)break;if(root===current)break;current=current.parent}return composer}const globalExportProps=["locale","fallbackLocale","availableLocales"],globalExportMethods=["t","rt","d","n","tm","te"];const DatetimeFormat=/* @__PURE__ */defineComponent({name:"i18n-d",props:assign({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},baseFormatProps),setup(props,context){const i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return renderFormatter(props,context,DATETIME_FORMAT_OPTIONS_KEYS,(...args)=>i18n2[DatetimePartsSymbol](...args))}});var hook;if("boolean"!=typeof __VUE_I18N_FULL_INSTALL__&&(getGlobalThis().__VUE_I18N_FULL_INSTALL__=!0),"boolean"!=typeof __VUE_I18N_LEGACY_API__&&(getGlobalThis().__VUE_I18N_LEGACY_API__=!0),"boolean"!=typeof __INTLIFY_DROP_MESSAGE_COMPILER__&&(getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__=!1),"boolean"!=typeof __INTLIFY_PROD_DEVTOOLS__&&(getGlobalThis().__INTLIFY_PROD_DEVTOOLS__=!1),_compiler=function(message,context){if(!__INTLIFY_DROP_MESSAGE_COMPILER__&&isString(message)){const warnHtmlMessage=!isBoolean(context.warnHtmlMessage)||context.warnHtmlMessage;"production"!==process.env.NODE_ENV&&checkHtmlMessage(message,warnHtmlMessage);const cacheKey=(context.onCacheKey||defaultOnCacheKey)(message),cached=compileCache[cacheKey];if(cached)return cached;const{ast:ast,detectError:detectError}=function(message,options={}){let detectError=!1;const onError=options.onError||defaultOnError;return options.onError=err=>{detectError=!0,onError(err)},{...baseCompile$1(message,options),detectError:detectError}}(message,{...context,location:"production"!==process.env.NODE_ENV,jit:!0}),msg=format(ast);return detectError?msg:compileCache[cacheKey]=msg}{if("production"!==process.env.NODE_ENV&&!isMessageAST(message))return warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`),()=>message;const cacheKey=message.cacheKey;if(cacheKey){const cached=compileCache[cacheKey];return cached||(compileCache[cacheKey]=format(message))}return format(message)}},_resolver=function(obj,path){if(!isObject(obj))return null;let hit=cache.get(path);if(hit||(hit=function(path){const keys=[];let c,key,newChar,type,transition,action,typeMap,index2=-1,mode=0,subPathDepth=0;const actions=[];function maybeUnescapeQuote(){const nextChar=path[index2+1];if(5===mode&&"'"===nextChar||6===mode&&'"'===nextChar)return index2++,newChar="\\"+nextChar,actions[0](),!0}for(actions[0]=()=>{void 0===key?key=newChar:key+=newChar},actions[1]=()=>{void 0!==key&&(keys.push(key),key=void 0)},actions[2]=()=>{actions[0](),subPathDepth++},actions[3]=()=>{if(subPathDepth>0)subPathDepth--,mode=4,actions[0]();else{if(subPathDepth=0,void 0===key)return!1;if(key=formatSubPath(key),!1===key)return!1;actions[1]()}};null!==mode;)if(index2++,c=path[index2],"\\"!==c||!maybeUnescapeQuote()){if(type=getPathCharType(c),typeMap=pathStateMachine[mode],transition=typeMap[type]||typeMap.l||8,8===transition)return;if(mode=transition[0],void 0!==transition[1]&&(action=actions[transition[1]],action&&(newChar=c,!1===action())))return;if(7===mode)return keys}}(path),hit&&cache.set(path,hit)),!hit)return null;const len=hit.length;let last=obj,i=0;for(;i<len;){const key=hit[i];if(AST_NODE_PROPS_KEYS.includes(key)&&isMessageAST(last))return null;if(!isObject(last))return null;if(!hasOwn(last,key))return null;const val=last[key];if(void 0===val)return null;if(isFunction(last))return null;last=val,i++}return last},_fallbacker=fallbackWithLocaleChain,"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__){const target=getGlobalThis();target.__INTLIFY__=!0,hook=target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__,devtools=hook}process.env.NODE_ENV;const modules=/* @__PURE__ */Object.assign({"./locales/en.ts":{"帮助":"Help","线吸附":"LineSnap","点吸附":"PointSnap","取消命令":"Cancel Command","确认命令":"Confirm Command","其他功能":"Other Functions","默认":"Default","绘制线段":"Line","绘制门线":"Door","绘制普通窗":"Window","绘制飘窗":"Bay Window","绘制垭口":"Wall Opening","绘制房梁":"Beam","绘制柱子":"Column","绘制栏杆":"Railing","修改模式":"Edit Mode","裁剪线段":"Trim Line","手动测距":"Manual Measurement","射线测距":"Ray Measurement","操作回滚":"Undo","撤销操作回滚":"Redo","合并":"Merge","两点连接":"Connect Two Points","两线连接":"Connect Two Lines","垂直纠正":"Correct Vertical Alignment","连续垂直纠正":"Continuous Vertical Alignment","角度显示":"Show Angle","全选":"Select All","删除":"Delete","属性面板":"Properties Panel","更多":"More","预览白膜":"Preview White Model","预览CAD":"Preview CAD","预览":"Preview","请选择线段":"Please select a line segment","删除成功":"Deleted Successfully","进入命令失败":"Failed to Enter Command","绘制完成":"Drawing Complete","绘制飘窗不合法提示":"Bay window width cannot be 0","长度":"Length","高度":"Height","离地高":"Height Above Floor","鼠标滚轮":"Mouse Wheel","绘制孔洞提示":"Please select a line segment as the wall for the opening, %s to modify the default opening length, %s to quickly increase the length, %s to quickly decrease the length, %s to cancel the command","修改绘制的长度":"Modify Drawing Length","修改绘制的宽度":"Modify Drawing Width","修改绘制的离地高":"Modify Height Above Floor","请输入长度":"Please enter the length","请输入高度":"Please enter the height","请输入离地高":"Please enter the height above floor","绘制线段提示":"Click two points to draw a line segment. Multiple line segments can be drawn continuously, %s to lock the direction, %s to cancel the command","绘制线段方向锁定漫游引导提示":"When drawing, the direction of the previous line is automatically detected, allowing the new line to extend only in the same direction (parallel) or at a right angle (perpendicular).","方向锁定":"Direction Lock (%s)","方向锁定无快捷键":"Direction Lock","绘制线段不合法提示":"At least %s line segments are required","手动测距提示":"Please select two points, %s to cancel the command","合并线段进入不合法提示":"Line merge not executed. Please select at least two line segments","已合并":"Merged","合并失败提示":"Merge failed. No shared point was found","选择线段小于2提醒":"Please select 2 line segments","两条线段夹角大于135度提醒":"The angle between the two line segments must be less than 135°","连接成功":"Connected Successfully","未选择1条线段提醒":"Please select one line segment","选择两条有端点相交的线段提醒":"Please select two line segments that intersect at their endpoints","修改线段提示":"Please select the line segment to modify, %s to cancel the command","跟随移动":"Follow Movement","重置位置":"Reset Position","确认":"Confirm","返回":"Back","加载中":"Loading","操作提示":"Instructions","跳过":"Skip","下一步":"Next","完成":"Finish","控制面板":"Control Panel","宽度":"Width","飘窗宽度":"Bay Window Width","修改":"Modify","门":"Door","窗户":"Window","梁":"Beam","飘窗":"Bay Window","垭口":"Wall Opening","栏杆":"Railing","墙线":"Wall Line","柱子":"Column","数值小于提醒":"Value cannot be less than %s mm","数值大于提醒":"Value cannot be greater than %s mm","取消命令漫游引导":"Clear the current drawing and return to the default state","确认命令漫游引导":"Confirm the current drawing, then continue drawing or return to the default state","提示漫游引导":"Tips about the drawing process and commonly used keyboard shortcuts","清空":"Clear","取消":"Cancel","设置最大值":"Set Maximum","设置最小值":"Set Minimum","射线测距提示":"Please select a point on the line segment as the ray origin, %s to cancel the command","转化为墙壁":"Convert to Wall","已撤回":"Withdrawn","已回退":"Reverted","转化成功":"Conversion Successful","选择需要转化的柱子提示":"Please select the columns to convert","请选择相同类型的结构":"Please select the same type of structure","请选择需要合并的结构":"Please select the structures to merge","柱子结构不支持合并":"Column structure does not support merging","请选择需要合并的结构, 且选择数量大于1":"Please select the structures to merge, and select more than 1","选择的孔洞类型数量不能大于1种":"The number of selected hole types cannot exceed 1.","复制":"Copy","粘贴":"Paste","已复制":"Copied","粘贴失败":"Paste failed","裁断":"Cut","裁断失败":"Cutting failed","成功":"Success","应用":"Apply","矩形":"Rectangle","非标准":"Non-standard","自定义":"Custom","转移":"Transfer","引用":"Quote","确定":"OK","请选择":"Please select","请选择需要粘贴的属性":"Select the property to paste","高":"High","长":"Long","请选择需要引用的属性":"Please select the attributes to reference","转化失败":"Conversion failed","逆转方向":"Reverse direction"},"./locales/zh-CN.ts":{"帮助":"帮助","线吸附":"线吸附","点吸附":"点吸附","取消命令":"取消命令","确认命令":"确认命令","其他功能":"其他功能","默认":"默认","绘制线段":"绘制线段","绘制门线":"绘制门线","绘制普通窗":"绘制普通窗","绘制飘窗":"绘制飘窗","绘制垭口":"绘制垭口","绘制房梁":"绘制房梁","绘制柱子":"绘制柱子","绘制栏杆":"绘制栏杆","修改模式":"修改模式","裁剪线段":"裁剪线段","手动测距":"手动测距","射线测距":"射线测距","操作回滚":"操作回滚","撤销操作回滚":"撤销操作回滚","合并":"合并","两点连接":"两点连接","两线连接":"两线连接","垂直纠正":"垂直纠正","连续垂直纠正":"连续垂直纠正","角度显示":"角度显示","全选":"全选","删除":"删除","属性面板":"属性面板","更多":"更多","预览白膜":"预览白膜","预览CAD":"预览CAD","预览":"预览","请选择线段":"请选择线段","删除成功":"删除成功","进入命令失败":"进入命令失败","绘制完成":"绘制完成","绘制飘窗不合法提示":"飘窗宽度不能为0","长度":"长度","高度":"高度","离地高":"离地高","鼠标滚轮":"鼠标滚轮","绘制孔洞提示":"请选择一条线段作为空洞依附墙体, %s 修改孔洞默认长度, %s 快速修改长度, %s 快速增加长度, %s 快速减少长度, %s 取消命令","修改绘制的长度":"修改绘制的长度","修改绘制的宽度":"修改绘制的宽度","修改绘制的离地高":"修改绘制的离地高","请输入长度":"请输入长度","请输入高度":"请输入高度","请输入离地高":"请输入离地高","绘制线段提示":"两个点绘制一条线段,可连续绘制多条线段, %s 键锁定方向, %s 取消命令","绘制线段方向锁定漫游引导提示":"绘制时,会自动捕捉上一条线的走势,让新线只能沿着它的同向(平行)或直角(垂直)延伸。","方向锁定":"方向锁定( %s )","方向锁定无快捷键":"方向锁定","绘制线段不合法提示":"需要绘制的线段不得低于%s条","手动测距提示":"请选择两个点, %s 取消命令","合并线段进入不合法提示":"未执行线段合并,请选择至少两条线段","已合并":"已合并","合并失败提示":"合并失败,未找到共用点","选择线段小于2提醒":"请选择2条线段","两条线段夹角大于135度提醒":"两条线段角度需要小于135度","连接成功":"连接成功","未选择1条线段提醒":"请选择一条线段","选择两条有端点相交的线段提醒":"请选择两条具有端点相交的线段","修改线段提示":"请选择需要修改的线段, %s 取消命令","跟随移动":"跟随移动","重置位置":"重置位置","确认":"确认","返回":"返回","加载中":"加载中","操作提示":"操作提示","跳过":"跳过","下一步":"下一步","完成":"完成","控制面板":"控制面板","宽度":"宽度","飘窗宽度":"飘窗宽度","修改":"修改","门":"门","窗户":"窗户","梁":"梁","飘窗":"飘窗","垭口":"垭口","栏杆":"栏杆","墙线":"墙线","柱子":"柱子","数值小于提醒":"数值不能小于%smm","数值大于提醒":"数值不能大于%smm","取消命令漫游引导":"清空当前的绘制内容,并退回到默认状态","确认命令漫游引导":"确认完成当前的绘制内容,继续新的绘制或者退回默认状态","提示漫游引导":"绘制过程中的一些注意事项和常用的键盘快捷键提示","清空":"清空","取消":"取消","设置最大值":"设置最大值","设置最小值":"设置最小值","射线测距提示":"请选择线段上的一个点作为发射点, %s 取消命令","转化为墙壁":"转化为墙壁","已撤回":"已撤回","已回退":"已回退","转化成功":"转化成功","选择需要转化的柱子提示":"请选择需要转化的柱子","请选择相同类型的结构":"请选择相同类型的结构","请选择需要合并的结构":"请选择需要合并的结构","柱子结构不支持合并":"柱子结构不支持合并","请选择需要合并的结构, 且选择数量大于1":"请选择需要合并的结构 且选择数量大于1","选择的孔洞类型数量不能大于1种":"选择的孔洞类型数量不能大于1种","复制":"复制","粘贴":"粘贴","已复制":"已复制","粘贴失败":"粘贴失败","裁断":"裁断","裁断失败":"裁断失败","成功":"成功","应用":"应用","矩形":"矩形","非标准":"非标准","自定义":"自定义","转移":"转移","引用":"引用","确定":"确定","请选择":"请选择","请选择需要粘贴的属性":"请选择需要粘贴的属性","高":"高","长":"长","请选择需要引用的属性":"请选择需要引用的属性","转化失败":"转化失败","逆转方向":"逆转方向"},"./locales/zh-TW.ts":{"帮助":"幫助","线吸附":"線吸附","点吸附":"點吸附","取消命令":"取消命令","确认命令":"確認命令","其他功能":"其他功能","默认":"預設","绘制线段":"繪製線段","绘制门线":"繪製門線","绘制普通窗":"繪製普通窗","绘制飘窗":"繪製飄窗","绘制垭口":"繪製埡口","绘制房梁":"繪製房樑","绘制柱子":"繪製柱子","绘制栏杆":"繪製欄杆","修改模式":"修改模式","裁剪线段":"裁剪線段","手动测距":"手動測距","射线测距":"射線測距","操作回滚":"操作回滾","撤销操作回滚":"撤銷操作回滾","合并":"合併","两点连接":"兩點連接","两线连接":"兩線連接","垂直纠正":"垂直糾正","连续垂直纠正":"連續垂直糾正","角度显示":"角度顯示","全选":"全選","删除":"刪除","属性面板":"屬性面板","更多":"更多","预览白膜":"預覽白膜","预览CAD":"預覽CAD","预览":"預覽","请选择线段":"請選擇線段","删除成功":"刪除成功","进入命令失败":"進入命令失敗","绘制完成":"繪製完成","绘制飘窗不合法提示":"飄窗寬度不能為0","长度":"長度","高度":"高度","离地高":"離地高","鼠标滚轮":"滑鼠滾輪","绘制孔洞提示":"請選擇一條線段作為空洞依附牆體, %s 修改孔洞預設長度, %s 快速修改長度, %s 快速增加長度, %s 快速減少長度, %s 取消命令","修改绘制的长度":"修改繪製的長度","修改绘制的宽度":"修改繪製的寬度","修改绘制的离地高":"修改繪製的離地高","请输入长度":"請輸入長度","请输入高度":"請輸入高度","请输入离地高":"請輸入離地高","绘制线段提示":"兩個點繪製一條線段,可連續繪製多條線段, %s 鍵鎖定方向, %s 取消命令","绘制线段方向锁定漫游引导提示":"繪製時,會自動捕捉上一條線的走勢,讓新線只能沿著它的同向(平行)或直角(垂直)延伸。","方向锁定":"方向鎖定( %s )","方向锁定无快捷键":"方向鎖定","绘制线段不合法提示":"需要繪製的線段不得低於%s條","手动测距提示":"請選擇兩個點, %s 取消命令","合并线段进入不合法提示":"未執行線段合併,請選擇至少兩條線段","已合并":"已合併","合并失败提示":"合併失敗,未找到共用點","选择线段小于2提醒":"請選擇2條線段","两条线段夹角大于135度提醒":"兩條線段角度需要小於135度","连接成功":"連接成功","未选择1条线段提醒":"請選擇一條線段","选择两条有端点相交的线段提醒":"請選擇兩條具有端點相交的線段","修改线段提示":"請選擇需要修改的線段, %s 取消命令","跟随移动":"跟隨移動","重置位置":"重置位置","确认":"確認","返回":"返回","加载中":"載入中","操作提示":"操作提示","跳过":"跳過","下一步":"下一步","完成":"完成","控制面板":"控制面板","宽度":"寬度","飘窗宽度":"飄窗寬度","修改":"修改","门":"門","窗户":"窗戶","梁":"樑","飘窗":"飄窗","垭口":"埡口","栏杆":"欄杆","墙线":"牆線","柱子":"柱子","数值小于提醒":"數值不能小於%smm","数值大于提醒":"數值不能大於%smm","取消命令漫游引导":"清空當前的繪製內容,並退回到預設狀態","确认命令漫游引导":"確認完成當前的繪製內容,繼續新的繪製或者退回預設狀態","提示漫游引导":"繪製過程中的一些注意事項和常用的鍵盤快捷鍵提示","清空":"清空","取消":"取消","设置最大值":"設定最大值","设置最小值":"設定最小值","射线测距提示":"請選擇線段上的一個點作為射線起點,%s 取消命令","转化为墙壁":"轉化為牆壁","已撤回":"已撤回","已回退":"已回退","转化成功":"轉化成功","选择需要转化的柱子提示":"請選擇需要轉化的柱子","请选择相同类型的结构":"請選擇相同類型的結構","请选择需要合并的结构":"請選擇需要合併的結構","柱子结构不支持合并":"柱結構不支援合併","请选择需要合并的结构, 且选择数量大于1":"請選擇需要合併的結構,且選擇數量需大於1","选择的孔洞类型数量不能大于1种":"選擇的孔洞類型數量不能大於1種","复制":"複製","粘贴":"貼上","已复制":"已複製","粘贴失败":"貼上失敗","裁断":"裁切","裁断失败":"裁切失敗","成功":"成功","应用":"應用","矩形":"矩形","非标准":"非標準","自定义":"自訂","转移":"轉移","引用":"引用","确定":"確定","请选择":"請選擇","请选择需要粘贴的属性":"請選擇需要貼上的屬性","高":"高","长":"長","请选择需要引用的属性":"請選擇需要引用的屬性","转化失败":"轉換失敗","逆转方向":"反轉方向"}}),messages={};for(const[path,message]of Object.entries(modules)){const locale2=path.match(/\.\/locales\/(.+)\.ts$/)?.[1];locale2&&(messages[locale2]=message)}const i18n=function(options={}){const __legacyMode=__VUE_I18N_LEGACY_API__&&isBoolean(options.legacy)?options.legacy:__VUE_I18N_LEGACY_API__;"production"!==process.env.NODE_ENV&&__legacyMode&&warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_LEGACY_MODE));const __globalInjection=!isBoolean(options.globalInjection)||options.globalInjection,__instances=/* @__PURE__ */new Map,[globalScope,__global]=function(options,legacyMode){const scope=effectScope(),obj=__VUE_I18N_LEGACY_API__&&legacyMode?scope.run(()=>createVueI18n(options)):scope.run(()=>createComposer(options));if(null==obj)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);return[scope,obj]}(options,__legacyMode),symbol=/* @__PURE__ */makeSymbol("production"!==process.env.NODE_ENV?"vue-i18n":""),i18n2={get mode(){return __VUE_I18N_LEGACY_API__&&__legacyMode?"legacy":"composition"},async install(app,...options2){if("production"!==process.env.NODE_ENV&&(app.__VUE_I18N__=i18n2),app.__VUE_I18N_SYMBOL__=symbol,app.provide(app.__VUE_I18N_SYMBOL__,i18n2),isPlainObject(options2[0])){const opts=options2[0];i18n2.__composerExtend=opts.__composerExtend,i18n2.__vueI18nExtend=opts.__vueI18nExtend}let globalReleaseHandler=null;!__legacyMode&&__globalInjection&&(globalReleaseHandler=function(app,composer){const i18n2=/* @__PURE__ */Object.create(null);globalExportProps.forEach(prop=>{const desc=Object.getOwnPropertyDescriptor(composer,prop);if(!desc)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const wrap=isRef(desc.value)?{get:()=>desc.value.value,set(val){desc.value.value=val}}:{get:()=>desc.get&&desc.get()};Object.defineProperty(i18n2,prop,wrap)}),app.config.globalProperties.$i18n=i18n2,globalExportMethods.forEach(method=>{const desc=Object.getOwnPropertyDescriptor(composer,method);if(!desc||!desc.value)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);Object.defineProperty(app.config.globalProperties,`$${method}`,desc)});const dispose=()=>{delete app.config.globalProperties.$i18n,globalExportMethods.forEach(method=>{delete app.config.globalProperties[`$${method}`]})};return dispose}(app,i18n2.global)),__VUE_I18N_FULL_INSTALL__&&apply(app,i18n2,...options2),__VUE_I18N_LEGACY_API__&&__legacyMode&&app.mixin(function(vuei18n,composer,i18n2){return{beforeCreate(){const instance=getCurrentInstance();if(!instance)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const options=this.$options;if(options.i18n){const optionsI18n=options.i18n;if(options.__i18n&&(optionsI18n.__i18n=options.__i18n),optionsI18n.__root=composer,this===this.$root)this.$i18n=mergeToGlobal(vuei18n,optionsI18n);else{optionsI18n.__injectWithOption=!0,optionsI18n.__extender=i18n2.__vueI18nExtend,this.$i18n=createVueI18n(optionsI18n);const _vueI18n=this.$i18n;_vueI18n.__extender&&(_vueI18n.__disposer=_vueI18n.__extender(this.$i18n))}}else if(options.__i18n)if(this===this.$root)this.$i18n=mergeToGlobal(vuei18n,options);else{this.$i18n=createVueI18n({__i18n:options.__i18n,__injectWithOption:!0,__extender:i18n2.__vueI18nExtend,__root:composer});const _vueI18n=this.$i18n;_vueI18n.__extender&&(_vueI18n.__disposer=_vueI18n.__extender(this.$i18n))}else this.$i18n=vuei18n;options.__i18nGlobal&&adjustI18nResources(composer,options,options),this.$t=(...args)=>this.$i18n.t(...args),this.$rt=(...args)=>this.$i18n.rt(...args),this.$te=(key,locale2)=>this.$i18n.te(key,locale2),this.$d=(...args)=>this.$i18n.d(...args),this.$n=(...args)=>this.$i18n.n(...args),this.$tm=key=>this.$i18n.tm(key),i18n2.__setInstance(instance,this.$i18n)},mounted(){if("production"!==process.env.NODE_ENV&&this.$i18n){const instance=getCurrentInstance();if(!instance)return;const _vueI18n=this.$i18n;instance.__VUE_I18N__=_vueI18n.__composer;const emitter=this.__v_emitter=createEmitter();_vueI18n.__enableEmitter&&_vueI18n.__enableEmitter(emitter),emitter.on("*",addTimelineEvent)}},unmounted(){const instance=getCurrentInstance();if(!instance)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const _vueI18n=this.$i18n;"production"!==process.env.NODE_ENV&&instance.__VUE_I18N__&&(this.__v_emitter&&(this.__v_emitter.off("*",addTimelineEvent),delete this.__v_emitter),_vueI18n&&(_vueI18n.__disableEmitter&&_vueI18n.__disableEmitter(),delete instance.__VUE_I18N__)),_vueI18n&&(delete this.$t,delete this.$rt,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,_vueI18n?.__disposer&&(_vueI18n.__disposer(),delete _vueI18n.__disposer,delete _vueI18n.__extender),i18n2.__deleteInstance(instance),delete this.$i18n)}}}(__global,__global.__composer,i18n2));const unmountApp=app.unmount;if(app.unmount=()=>{globalReleaseHandler&&globalReleaseHandler(),i18n2.dispose(),unmountApp()},"production"!==process.env.NODE_ENV){if(!(await enableDevTools(app,i18n2)))throw createI18nError(I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);const emitter=createEmitter();if(__legacyMode){const _vueI18n=__global;_vueI18n.__enableEmitter&&_vueI18n.__enableEmitter(emitter)}else{const _composer=__global;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter)}emitter.on("*",addTimelineEvent)}},get global(){return __global},dispose(){globalScope.stop()},__instances:__instances,__getInstance:function(component){return __instances.get(component)||null},__setInstance:function(component,instance){__instances.set(component,instance)},__deleteInstance:function(component){__instances.delete(component)}};return i18n2}({legacy:!1,locale:"zh-CN",fallbackLocale:"zh-CN",messages:messages}),t=(key,...formats)=>{let str=i18n.global.t(key);if(formats.length){let index2=0;str=str.replace(/%s/g,()=>index2<formats.length?formats[index2++]+"":"%s")}return str},locale=computed({set(v2){i18n.global.locale.value=v2},get:()=>i18n.global.locale.value});let gloabalDxfSystem=null;class Log{static preTime=performance.now();static firstTime=performance.now();static clear(){this.preTime=performance.now(),this.firstTime=this.preTime}static timeConsuming(msg=""){const t2=performance.now(),diff=t2-this.preTime;return console.log(msg+" %c time "+parseFloat(diff.toFixed(6))+"ms","color: green;"),this.preTime=t2,diff}static totalTime(msg=""){const t2=performance.now(),diff=t2-this.firstTime;return console.log(msg+" %c totalTime "+parseFloat(diff.toFixed(6))+"ms","color: green;"),this.preTime=t2,diff}}async function createEditor(opt){const{dom:dom,camera:camera,orbitControls:orbitControls=!1,viewPermission:viewPermission,bgTransparent:bgTransparent=!1,language:language}=opt??{},mp=await Promise.resolve().then(()=>index),rp=await import("./index2.js"),editor2=await import("./index3.js");language&&(locale.value=language);const dxfSystem=(new DxfSystem).usePlugin(mp.ModelDataPlugin.create({whiteModel:!0})).usePlugin(rp.RenderPlugin.create({modelData:!1,orbitControls:orbitControls,camera:camera,bgTransparent:bgTransparent})).usePlugin(editor2.EditorPlugin.create({viewPermission:viewPermission})),domContainer=dxfSystem.findComponentByType(rp.components.DomContainer);return domContainer&&dom.appendChild(domContainer.container),gloabalDxfSystem=dxfSystem,{dxfSystem:dxfSystem,getFileAll:()=>getFileAll("closed-loop",dxfSystem)}}async function getModels(originData,trajectory2,itemList){"itemInfo"in itemList&&(itemList=itemList.itemInfo),Array.isArray(itemList)||(itemList=[]);const{lineSegments:lineSegments,originalZAverage:originalZAverage}=originalDataToLineData(originData),lines=BoundExt.boundExtbyTraj({lines:lineSegments,trajectory:trajectory2,updateDoubleWallGroup:!0,wallWidth:DEFAULT_WALL_WIDTH}).lines,sceneAutoGenerat=new SceneAutoGenerat(lines,itemList,originalZAverage,trajectory2);await sceneAutoGenerat.init();const model=sceneAutoGenerat.scene,whiteModel=new WhiteModel;whiteModel.whiteModelGroup.add(model);return{glb:new File([await whiteModel.toGltfBlob(!0)||""],"model.glb",{type:"application/octet-stream"}),gltf:new File([await whiteModel.toGltfBlob(!1)||""],"model.gltf",{type:"application/json"})}}"undefined"!=typeof window&&(window.drawLines=function drawLines(lines,parameters,offset=.001){if(Array.isArray(lines)&&lines[0]instanceof Point){const _lines=lines;lines=[..._lines].map((p2,i)=>{const nextP=_lines[(i+1)%_lines.length];return new LineSegment(p2,nextP)})}if(lines instanceof LineSegment)return drawLines([lines],parameters,offset);const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");if(renderer){if(0===lines.length)return;const obj3d=renderer.createLineSegments(lines,0,parameters,renderer?.container2);return obj3d.position.z=offset,obj3d}}},window.drawPoint=function(point2,parameters,offset=.001){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");if(renderer){const obj3d=renderer.createCircle(point2,parameters,renderer?.container2);return obj3d.position.z=offset,obj3d}}},window.drawText=drawText$1,window.enableRotate=function(b4=!0){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");renderer&&(renderer.orbitControls.enableRotate=b4)}},window.randomColor=()=>Math.floor(16777215*Math.random()),window.Log=Log,window.TEST=!1),"undefined"!=typeof globalThis&&(globalThis.Log=Log,globalThis.TEST=!1);var DrawingFeature=/* @__PURE__ */(DrawingFeature2=>(DrawingFeature2[DrawingFeature2.RotationCorr=1]="RotationCorr",DrawingFeature2[DrawingFeature2.Dimension=2]="Dimension",DrawingFeature2[DrawingFeature2.BoundExt=4]="BoundExt",DrawingFeature2))(DrawingFeature||{});async function buildJson(opt,dxfSystem=new DxfSystem){const mp=await Promise.resolve().then(()=>index);let{json:json,trajectory:trajectory2,axisAlignCorrOption:axisAlignCorrOption,download:download,itemInfo:itemInfo,doorFind:doorFind=!0,groundBuildMode:groundBuildMode="closed-loop"}=opt;dxfSystem.usePlugin(mp.ModelDataPlugin);const whiteModel=dxfSystem.findComponentByType(mp.components.WhiteModel),threeVJia=dxfSystem.findComponentByName("ThreeVJia"),runJian=dxfSystem.findComponentByName("RunJian"),externalData=dxfSystem.findComponentByName("ExternalData");if(whiteModel.groundBuildMode=groundBuildMode,itemInfo&&"string"==typeof itemInfo){if("undefined"==typeof global)throw new Error("非node环境不允许使用路径");{const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(itemInfo);itemInfo=JSON.parse(buffer.toString("utf-8"))}}if(doorFind&&dxfSystem.Dxf.linePipeline.add(LinePipeline.builtin.DoorFind),!1!==opt.axisAlignCorr&&dxfSystem.Dxf.linePipeline.add(LinePipeline.builtin.AxisAlignCorr).add(LinePipeline.builtin.RemoveShortDoubleWall).add(LinePipeline.builtin.BeamSupportLine).add(LinePipeline.builtin.RemoveRoomSundries),trajectory2&&"string"==typeof trajectory2){if("undefined"==typeof global)throw new Error("非node环境不允许使用路径");{const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(trajectory2);trajectory2=JSON.parse(buffer.toString("utf-8"))}}await dxfSystem.Dxf.set(json,{wallGroup:!0,...axisAlignCorrOption,publicInfo:itemInfo,trajectory:trajectory2}),download?.json&&await dxfSystem.Dxf.downloadOriginalData(download.json),download?.gltf&&await(whiteModel?.downloadGltf(download.gltf,!1)),download?.glb&&await(whiteModel?.downloadGltf(download.glb)),download?.obj&&await(whiteModel?.downloadOBJ(download.obj));for await(const{files:files,features:features}of opt.download?.cad??[]){let dxfCom=dxfSystem.Dxf;4&features&&(dxfCom=dxfSystem.BoundExtDxf);const list=["cad"];2&features&&list.push("dim"),1&features&&list.push("deg_corr");const mode=toCamelCase(list.reverse().join("_"));for await(const{path:path,type:type}of files)"dxf"===type?await dxfCom.downloadDxf(mode,path):"image"===type&&await dxfCom.downloadDxfImage(mode,path)}return{dxfSystem:dxfSystem,threeVJia:threeVJia,whiteModel:whiteModel,runJian:runJian,externalData:externalData}}async function getFileAll(groundBuildMode="closed-loop",dxfSystem=gloabalDxfSystem){const whiteModel=dxfSystem.findComponentByName("WhiteModel");whiteModel.groundBuildMode=groundBuildMode,whiteModel.regenerateModel();const dxf=new File([dxfSystem.BoundExtDxf.toDxfBlob("dimCad")??""],"dxf.dxf",{type:"application/dxf"}),correctionDxf=new File([dxfSystem.BoundExtDxf.toDxfBlob("degCorrCad")??""],"dxf.dxf",{type:"application/dxf"}),jpg=new File([await dxfSystem.BoundExtDxf.toDxfImageBlob("degCorrDimCad")],"img.jpg",{type:"image/jpeg"}),obj=new File([await whiteModel.toOBJBlob()],"model.obj",{type:"application/octet-stream"}),glb=new File([await whiteModel.toGltfBlob(!0)],"model.glb",{type:"application/octet-stream"}),gltf2=new File([await whiteModel.toGltfBlob(!1)],"model.gltf",{type:"application/json"}),originalData=lineDataToOriginalData(dxfSystem.Dxf.getLineSegments(),dxfSystem.Dxf.originalZAverage);return{dxf:dxf,obj:obj,glb:glb,gltf:gltf2,json:new File([JSON.stringify(originalData)],"json.json",{type:"application/json"}),jpg:jpg,correctionDxf:correctionDxf,dwg:new File([await dxfToDwgByBlob(dxf)],"dwg.dwg",{type:"application/dwg"}),correctionDwg:new File([await dxfToDwgByBlob(correctionDxf)],"dwg.dwg",{type:"application/dwg"})}}function getGlobalDxfSystem(){return gloabalDxfSystem}function hasCircle(lineData,startIndex,direction){let lines=originalDataToLineData(lineData).lineSegments;const center=lines[startIndex].center;let findlines=splitIntersectedLine(lines.map(line2=>line2.clone()),1e-9),removeSet=findDiscretePointLine(findlines);findlines=findlines.filter(line2=>!removeSet.has(line2));const list=findlines.filter(line2=>line2.userData.isBayWindow&&line2.isPointOnSegment(center));if(0===list.length)return null;const miniCircles2=new MiniCircles,line=list[0],testPoint=line.center.add(Point.from(direction).multiplyScalar(1e-4));let circle=miniCircles2.miniCircle(findlines,{circleEdges:[line]}).circles.filter(circle2=>Polygon.fromByLines2(circle2).pointWithin(testPoint))[0];if(circle){let indices=lazy(()=>getLineIndexByCenter(circle,findlines).filter(i=>i>-1)),originalDataIndices=lazy(()=>getLineIndexByCenter(circle,lines).filter(i=>i>-1));return{get originalIndices(){return originalDataIndices.value},get indices(){return indices.value},circle:circle,originalLines:lines,lines:findlines}}return null}export{ArrayMap as A,Box2 as B,Component as C,DEFAULT_WALL_WIDTH as D,EventDispatcher as E,buildJson as F,createEditor as G,HeightQuery as H,index$2 as I,getFileAll as J,getGlobalDxfSystem as K,LineSegmentUtils as L,MiniCircles as M,getModels as N,hasCircle as O,PointSpatialHash as P,Quadtree as Q,Rectangle as R,SelectLocalFile as S,ThreeVJia as T,locale as U,Variable as V,WallGroupManager as W,index$3 as X,Pipeline as a,WallHole as b,cloneUserData as c,createPromise as d,earcut as e,mmTom as f,getDefaultExportFromCjs as g,WH as h,Point as i,Lines as j,PointUtils as k,LineSegment as l,mToMm as m,LineGroupType as n,Polygon as o,LineDashed as p,clippingLineUserData as q,LinePipeline as r,drawText$1 as s,t,uuid as u,toTrianglesDrawMode as v,WhiteModel as w,CommandManager as x,DrawingFeature as y,index as z};
|
|
1
|
+
import*as THREE from"three";import{EventDispatcher as EventDispatcher$1,Vector3,Matrix3,MathUtils,Box3,Matrix4,Ray,Group as Group$1,Shape,BufferGeometry,BufferAttribute,TrianglesDrawMode,TriangleFanDrawMode,TriangleStripDrawMode}from"three";import ClipperLib from"clipper-lib";import{GLTFLoader}from"three/addons/loaders/GLTFLoader.js";import{GLTFExporter}from"three/addons/exporters/GLTFExporter.js";import init$1,{dxf_to_dwg}from"rm-rust-dxf-lib";import Drawing from"dxf-writer";import{Brush,Evaluator,SUBTRACTION}from"three-bvh-csg";import{OBJExporter}from"three/examples/jsm/exporters/OBJExporter.js";import{effectScope,computed,watch,isRef,ref,shallowRef,defineComponent,h,getCurrentInstance as getCurrentInstance$1,getCurrentScope,onScopeDispose,Fragment,inject,onMounted,onUnmounted,createVNode,Text}from"vue";function uuid(){return"xxxx-xxxx-4xxx-yxxx-xxxx".replace(/[xy]/g,function(c){var r2=16*Math.random()|0;return("x"==c?r2:3&r2|8).toString(16)})}class EventDispatcher extends EventDispatcher$1{uuid=uuid();addEventListener(type,listener,option){const{once:once=!1}=option??{},callBack=event=>{listener(event),once&&canceCallBack()},canceCallBack=()=>this.removeEventListener(type,callBack);return super.addEventListener(type,callBack),canceCallBack}eventRecordStack=/* @__PURE__ */new Map;addEventRecord(name,...cancels){if(Array.isArray(name)){const list=name.map(n=>this.addEventRecord(n,...cancels)),add2=cancel=>(list.forEach(({add:add3})=>add3(cancel)),{add:add2});return{add:add2}}this.eventRecordStack.has(name)||this.eventRecordStack.set(name,[]),cancels.forEach(cancel=>{this.eventRecordStack.get(name)?.push(cancel)});const add=cancel=>(this.addEventRecord(name,cancel),{add:add});return{add:add}}cancelEventRecord(name){if(Array.isArray(name))return name.forEach(name2=>this.cancelEventRecord(name2));const list=this.eventRecordStack.get(name);list&&(list.reverse().forEach(cancel=>cancel()),this.eventRecordStack.delete(name))}eventLock=!1;dispatchEvent(event){this.eventLock||(super.dispatchEvent(event),super.dispatchEvent({type:"EVENT_TRIGGER",event:event}))}static EVENT_TRIGGER="EVENT_TRIGGER"}class Component extends EventDispatcher{parent;destroyed=!1;constructor(...arg){super(),this.addEventListener("addFromParent",e=>{this.parent=e.parent,this.onAddFromParent(e.parent)}),this.addEventListener("removeFromParent",e=>{this.parent=void 0,this.onRemoveFromParent(e.parent)})}onAddFromParent(parent){}onRemoveFromParent(parent){}destroy(){this.destroyed=!0}}class ComponentContainer extends EventDispatcher{static EventType={ADD_COMPONENT:"addComponent"};components=[];addComponent(component){return component&&(this.components.push(component),this.dispatchEvent({type:"addComponent",component:component}),component.dispatchEvent({type:"addFromParent",parent:this})),this}removeComponent(component){if(component instanceof Component){const index2=this.components.indexOf(component);index2>-1&&(this.components.splice(index2,1),this.dispatchEvent({type:"removeComponent",component:component}),component.dispatchEvent({type:"removeFromParent",parent:this}))}}findComponent(predicate){for(let i=0;i<this.components.length;i++){const component=this.components[i];if(predicate(component,i))return component}}findComponents(predicate){return this.components.filter(predicate)}findComponentByType(type){const component=this.findComponent(c=>c instanceof type);return component||null}findComponentByName(name){const component=this.findComponent(c=>c.constructor.name===name);return component||null}}function cloneUserData(userData){if(!userData||"object"!=typeof userData)return userData;const cloned=Array.isArray(userData)?[]:{},keys=Object.keys(userData);for(const key of keys){const value=userData[key];null!==value&&"object"==typeof value?Array.isArray(value)?cloned[key]=value.map(item=>cloneUserData(item)):Object.getPrototypeOf(value)!==Object.prototype||(cloned[key]=cloneUserData(value)):cloned[key]=value}return cloned}const POW10=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Point{_x;_y;_version=0;get version(){return this._version}get X(){return this._x}get Y(){return this._y}get x(){return this._x}get y(){return this._y}set x(x){this.setX(x)}set y(y){this.setY(y)}userData={};currentData={};constructor(x=0,y=0){this._x=x,this._y=y}_set(x,y){return this._x=x,this._y=y,this._version++,this}set(x,y){return x===this._x&&this._y===y||this._set(x,y),this}setByDirect(direct,origin,width){this.copy(origin.clone().add(direct.clone().multiplyScalar(width)))}setX(x){return x===this._x||(this._x=x,this._version++),this}setY(y){return this._y===y||(this._y=y,this._version++),this}equal(point2,eps=1e-9){return Math.abs(point2._x-this._x)<eps&&Math.abs(point2._y-this._y)<eps}setByArray(arr){return this._set(arr[0],arr[1]),this}multiply(point2){return this._set(this._x*point2._x,this._y*point2._y),this}multiplyScalar(scalar){return this._set(this._x*scalar,this._y*scalar),this}division(point2){return this._set(this._x/point2._x,this._y/point2._y),this}divisionScalar(scalar){return this._set(this._x/scalar,this._y/scalar),this}subtract(point2){return this._set(this._x-point2._x,this._y-point2._y),this}subtractScalar(value){return this._set(this._x-value,this._y-value),this}add(point2){return this._set(this._x+point2._x,this._y+point2._y),this}addScalar(value){return this._set(this._x+value,this._y+value),this}added(point2,out=new Point){return out._set(this._x+point2._x,this._y+point2._y)}subtracted(point2,out=new Point){return out._set(this._x-point2._x,this._y-point2._y)}parseInt(){return this._set(~~this._x,~~this._y),this}rotate(point2,angle){const dx=this._x-point2.x,dy=this._y-point2.y,cosAngle=Math.cos(angle),sinAngle=Math.sin(angle),rotatedX=dx*cosAngle-dy*sinAngle,rotatedY=dx*sinAngle+dy*cosAngle;return this._set(rotatedX+point2.x,rotatedY+point2.y),this}rotated(center,angle,out=new Point){const dx=this._x-center.x,dy=this._y-center.y,cos=Math.cos(angle),sin=Math.sin(angle);return out._set(dx*cos-dy*sin+center.x,dx*sin+dy*cos+center.y)}precision(count){const factor=POW10[count]??10**count;return this._set(Math.round(this._x*factor)/factor,Math.round(this._y*factor)/factor),this}precision4(){return this._set(Math.round(1e4*this._x)/1e4,Math.round(1e4*this._y)/1e4),this}normalize(){const length=Math.sqrt(this._x*this._x+this._y*this._y);return 0===length||this._set(this._x/length,this._y/length),this}normalized(out=new Point){const length=Math.hypot(this._x,this._y);return 0===length?out._set(0,0):out._set(this._x/length,this._y/length)}leftNormal(point2,out=new Point){const dx=this._x-point2._x,dy=this._y-point2._y,length=Math.sqrt(dx*dx+dy*dy);if(0===length)return Point.zero();const nx=-dy/length,ny=dx/length;return out._set(nx,ny)}directionFrom(point2,out=new Point){const dx=this._x-point2._x,dy=this._y-point2._y,length=Math.sqrt(dx*dx+dy*dy);return 0!==length&&out._set(dx/length,dy/length),out}expandAsLine(direction,length,userData,out=new LineSegment){return out.set(this.clone(),this.clone().add(direction.clone().multiplyScalar(length))),out.userData=userData??{},out}magnitude(){return Math.hypot(this._x,this._y)}dot(point2){return this._x*point2._x+this._y*point2._y}cross(point2){return this._x*point2._y-this._y*point2._x}angleBetween(point2,type="radian",angle="180"){const dotProduct=this.dot(point2),magnitude1=this.magnitude(),magnitude2=point2.magnitude();if(0===magnitude1||0===magnitude2)return 0;const cosTheta=dotProduct/(magnitude1*magnitude2),clampedCosTheta=Math.max(-1,Math.min(1,cosTheta));return"radian"===type?Math.acos(clampedCosTheta):"cos"===type?clampedCosTheta:"180"===angle||this.cross(point2)<0?Math.acos(clampedCosTheta)/(Math.PI/180):360-Math.acos(clampedCosTheta)/(Math.PI/180)}angleBetween2(point2){const magnitude1=this.magnitude(),magnitude2=point2.magnitude();if(0===magnitude1||0===magnitude2)return 0;const dot=this.dot(point2),cross2=this.cross(point2);return Math.atan2(cross2,dot)}angle(point2,opt={}){const{unit:unit="radian",range:range="180"}=opt,dot=this.dot(point2),cross2=this.cross(point2);if("cos"===unit){const mag=this.magnitude()*point2.magnitude();return 0===mag?0:Math.max(-1,Math.min(1,dot/mag))}let theta=Math.atan2(cross2,dot);return"180"===range?theta=Math.abs(theta):theta<0&&(theta+=2*Math.PI),"degree"===unit?180*theta/Math.PI:theta}length(){const magnitude=Math.sqrt(this._x*this._x+this._y*this._y);return Math.abs(magnitude-Math.round(magnitude))<1e-9?Math.round(magnitude):magnitude}distance(point2){return Math.sqrt((this._x-point2.x)*(this._x-point2.x)+(this._y-point2.y)*(this._y-point2.y))}lerp(point2,t2,out=this){return out.set(this.x+(point2.x-this.x)*t2,this.y+(point2.y-this.y)*t2),out}distanceSquared(point2){const dx=this._x-point2.x,dy=this._y-point2.y;return dx*dx+dy*dy}hashCode(fixed=6){return`${this._x.toFixed(fixed)},${this._y.toFixed(fixed)}`}encode(){return BigInt(Math.round(this._x/1e-4))<<32n|0xffffffffn&BigInt(Math.round(this._y/1e-4))}clone(out=new Point){return out._set(this._x,this._y),out}copy(p2){return p2&&"x"in p2&&"y"in p2?this._set(Number(p2.x),Number(p2.y)):Array.isArray(p2)&&this._set(Number(p2[0]),Number(p2[1])),this}toArray(){return[this._x,this._y]}toJson(z=0){return{x:this._x,y:this._y,z:z}}toJson2D(){return{x:this._x,y:this._y}}toVector3(z=0){return new Vector3(this._x,this._y,z)}static from(arr,out=new Point){return arr?Array.isArray(arr)?out.set(arr[0],arr[1]):"x"in arr&&"y"in arr?out.set(arr.x,arr.y):"X"in arr&&"Y"in arr?out.set(arr.X,arr.Y):out:out}static fromByList(arr){return arr.map(item=>Point.from(item))}static zero(){return new Point(0,0)}}class Rectangle{points=[Point.zero(),Point.zero(),Point.zero(),Point.zero()];get p0(){return this.points[0]}get p1(){return this.points[1]}get p2(){return this.points[2]}get p3(){return this.points[3]}get path(){return this.points.flatMap((p2,i)=>{const np=this.points[(i+1)%this.points.length];return[p2.x,p2.y,0,np.x,np.y,0]})}constructor(points){points&&points.forEach((p2,i)=>this.points[i].copy(p2))}path2D(callback){return this.points.flatMap((p2,i)=>{const np=this.points[(i+1)%this.points.length];return callback&&callback(new Point(p2.x,p2.y),new Point(np.x,np.y)),[p2.x,p2.y,np.x,np.y]})}toLines(){return this.points.map((p2,i)=>{const np=this.points[(i+1)%this.points.length];return new LineSegment(new Point(p2.x,p2.y),new Point(np.x,np.y))})}createGeometry(){const data=[this.p0,this.p2,this.p1,this.p2,this.p0,this.p3].flatMap(p2=>[p2.x,p2.y,0]);return new Float32Array(data)}intersectLineSegment(line){if(2!==line.points.length)throw new Error("LineSegment must have exactly 2 points");const[p1,p2]=line.points,rdx=p2.x-p1.x,rdy=p2.y-p1.y;for(let i=0;i<4;i++){const a2=this.points[i],b4=this.points[(i+1)%4],sdx=b4.x-a2.x,sdy=b4.y-a2.y,denom=rdx*sdy-rdy*sdx;if(0===denom){if(0!==(p1.x-a2.x)*sdy-(p1.y-a2.y)*sdx)continue;const edgeLenSq=sdx*sdx+sdy*sdy,t0=((p1.x-a2.x)*sdx+(p1.y-a2.y)*sdy)/edgeLenSq,t1=((p2.x-a2.x)*sdx+(p2.y-a2.y)*sdy)/edgeLenSq;if(Math.max(t0,t1)>=0&&Math.min(t0,t1)<=1)return!0}else{const t2=((a2.x-p1.x)*sdy-(a2.y-p1.y)*sdx)/denom,u2=((a2.x-p1.x)*rdy-(a2.y-p1.y)*rdx)/denom;if(t2>=0&&t2<=1&&u2>=0&&u2<=1)return!0}}return!!this.containsLineSegment(line)}containsLineSegment(line){if(2!==line.points.length)throw new Error("LineSegment must have exactly 2 points");const isPointInRectangle=point2=>{let sign=0;for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4],edge={x:p2.x-p1.x,y:p2.y-p1.y},toPoint={x:point2.x-p1.x,y:point2.y-p1.y},cross2=edge.x*toPoint.y-edge.y*toPoint.x;if(0===cross2){const t2=0!==edge.x?(point2.x-p1.x)/edge.x:(point2.y-p1.y)/edge.y;if(t2>=0&&t2<=1)return!0}else{const currentSign=cross2>0?1:-1;if(0===sign&&(sign=currentSign),sign!==currentSign)return!1}}return!0};return isPointInRectangle(line.points[0])&&isPointInRectangle(line.points[1])}projectRectangle(rect,axis){const projections=rect.points.map(point2=>point2.dot(axis));return[Math.min(...projections),Math.max(...projections)]}isProjectionOverlap(proj1,proj2){return proj1[0]<proj2[1]&&proj2[0]<proj1[1]}intersectRectangle(rectangle){const axes=[];for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4];axes.push(p1.leftNormal(p2))}for(let i=0;i<4;i++){const p1=rectangle.points[i],p2=rectangle.points[(i+1)%4];axes.push(p1.leftNormal(p2))}for(const axis of axes){const proj1=this.projectRectangle(this,axis),proj2=this.projectRectangle(rectangle,axis);if(!this.isProjectionOverlap(proj1,proj2))return!1}return!0}containsPoint(point2){let positiveCount=0,negativeCount=0;for(let i=0;i<4;i++){const p1=this.points[i],p2=this.points[(i+1)%4],cross2=(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x);if(cross2>0)positiveCount++;else{if(!(cross2<0))return!1;negativeCount++}}return 4===positiveCount||4===negativeCount}toBox(out=new Box2){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return this.points.forEach(p2=>{maxX=Math.max(p2.x,maxX),minX=Math.min(p2.x,minX),maxY=Math.max(p2.y,maxY),minY=Math.min(p2.y,minY)}),out.set(minX,minY,maxX,maxY)}static fromByLineSegment(line,width=.1,horizontal=!1,hScale=.5){const p1=line.points[0],p2=line.points[1],normal=p2.leftNormal(p1),pDirect=horizontal?p2.directionFrom(p1).multiplyScalar(width*hScale):Point.zero(),nDirect=horizontal?p1.directionFrom(p2).multiplyScalar(width*hScale):Point.zero(),offsetX=normal.x*width*.5,offsetY=normal.y*width*.5;return new Rectangle([new Point(p1.x+offsetX,p1.y+offsetY).add(nDirect),new Point(p2.x+offsetX,p2.y+offsetY).add(pDirect),new Point(p2.x-offsetX,p2.y-offsetY).add(pDirect),new Point(p1.x-offsetX,p1.y-offsetY).add(nDirect)])}}function lazy(fn2){let value,type,cached=!1;return Object.freeze({get isValueCreated(){return cached},get value(){return cached||(value=fn2(),cached=!0),value},get cachedValue(){return cached?value:void 0},get valueType(){return void 0===type&&(type=typeof this.value),type},reset(){cached=!1,type=void 0,value=void 0}})}const hasFinalizationRegistry="undefined"!=typeof FinalizationRegistry;class GCHandler{static map=/* @__PURE__ */new Map;static registry=hasFinalizationRegistry?new FinalizationRegistry(({value:value,onGc:onGc})=>{onGc(value)}):null;static add(target,opt){if(!hasFinalizationRegistry)return;const token=/* @__PURE__ */Symbol(),{key:key=token,value:value,onGc:onGc}=opt;this.remove(key),this.map.set(key,token),this.registry.register(target,{key:key,value:value,onGc:onGc},token)}static remove(key){if(!hasFinalizationRegistry)return;const token=this.map.get(key);token&&(this.registry.unregister(token),this.map.delete(key))}}class PointSpatialHash{map=/* @__PURE__ */new Map;gridSize;id;constructor(gridSize=.5){this.gridSize=gridSize,this.id=/* @__PURE__ */Symbol("id"),GCHandler.add(this,{value:{map:this.map,id:this.id},onGc:value=>{value.map.forEach(nodeSet=>{nodeSet.forEach(target=>{delete target.point.currentData?.pointVirtualGridMap,delete target.point.currentData[value.id]}),nodeSet.clear()}),value.map.clear()}})}insert(point2,userData){if(!point2||isNaN(point2.x)||isNaN(point2.y))return console.error("无效的点坐标"),this;point2.currentData[this.id]&&this.remove(point2);const id=this.getGridIdByPoint(point2);this.map.has(id)||this.map.set(id,/* @__PURE__ */new Set);const set2=this.map.get(id),target={point:point2,userData:userData};set2.add(target);const opt={set:set2,target:target,id:id};return point2.currentData.pointVirtualGrid=opt,point2.currentData[this.id]=opt,this}insertBatch(points){for(const{point:point2,userData:userData}of points)this.insert(point2,userData)}remove(point2){if(point2.currentData[this.id]){const{target:target,set:set2,id:id}=point2.currentData[this.id];set2&&(set2.delete(target),delete point2?.currentData?.pointVirtualGridMap,delete point2.currentData[this.id],0===set2.size&&this.map.delete(id))}return this}removes(points){return points.forEach(this.remove.bind(this)),this}update(point2){const{target:target,set:set2}=point2.currentData[this.id];if(!target)return!1;const id=this.getGridIdByPoint(point2);let newSet=this.map.get(id);return newSet!==set2&&(set2.delete(target),newSet||(newSet=/* @__PURE__ */new Set,this.map.set(id,newSet)),newSet.add(target),point2.currentData[this.id].set=newSet,point2.currentData[this.id].id=id,!0)}updates(point2){point2.forEach(p2=>this.update(p2))}getGridIdByPoint(point2){const i=Math.ceil(point2.x/this.gridSize),j=Math.ceil(point2.y/this.gridSize);return this.getGridId(i,j)}getGridId(i,j){return`${i}.${j}`}clear(){for(const set2 of this.map.values())for(const target of set2)delete target.point.currentData[this.id],delete target.point.currentData.pointVirtualGrid;this.map.clear()}forEachGrid(minI,maxI,minJ,maxJ,fn2){for(let i=minI;i<=maxI;i++)for(let j=minJ;j<=maxJ;j++){const id=this.getGridId(i,j),set2=this.map.get(id);set2&&fn2(set2)}}queryRect(rectangle){const box2=rectangle.toBox(),minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[];return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{rectangle.containsPoint(item.point)&&list.push(item)})}),list}queryCircle(pos,radius,excludeOneself=!1){const box2=new Box2(pos.x-radius,pos.x+radius,pos.y-radius,pos.y+radius),minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[],radius2=radius*radius;return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{if(excludeOneself&&pos===item.point)return;const dx=pos.x-item.point.x,dy=pos.y-item.point.y;dx*dx+dy*dy<=radius2&&list.push(item)})}),list}queryBox(box2){const minI=Math.ceil(box2.minX/this.gridSize),maxI=Math.ceil(box2.maxX/this.gridSize),minJ=Math.ceil(box2.minY/this.gridSize),maxJ=Math.ceil(box2.maxY/this.gridSize),list=[];return this.forEachGrid(minI,maxI,minJ,maxJ,set2=>{set2.forEach(item=>{box2.containsPoint(item.point)&&list.push(item)})}),list}queryPoint(point2,excludeOneself=!1){const list=[];let set2;if(point2.currentData[this.id])set2=point2.currentData[this.id]?.set;else{const id=this.getGridIdByPoint(point2);set2=this.map.get(id)}return set2?.forEach(item=>{if(point2.equal(item.point)){if(excludeOneself&&point2===item.point)return;list.push(item)}}),list}queryPoints(points,excludeOneself=!1){const result=[];for(const p2 of points)result.push(...this.queryPoint(p2,excludeOneself));return result}queryPolygon(polygon2,position="all"){const box2=polygon2.getBox2();return this.queryBox(box2).filter(result=>{const m=polygon2.getPointSideOfLine(result.point);return"inside"==m&&("inside"==position||"all"==position)||"on"==m&&("on"==position||"all"==position)})}queryPointSelf(point2){if(point2.currentData[this.id]){const{target:target}=point2.currentData[this.id];return target}return null}searchByRing(point2,fn2,maxRing=1e3){let gridCount=this.map.size;const centerI=Math.floor(point2.x/this.gridSize),centerJ=Math.floor(point2.y/this.gridSize),currentCircle=[],appendGrid=(i,j)=>{const set2=this.map.get(this.getGridId(i,j));if(set2){gridCount--;for(const target of set2)currentCircle.push({point:target.point,userData:target.userData,distanceSq:point2.distanceSquared(target.point)})}};if(appendGrid(centerI,centerJ),fn2(currentCircle,0))return currentCircle;if(0===gridCount)return null;for(let r2=1;r2<=maxRing;r2++){currentCircle.length=0;const minI=centerI-r2,maxI=centerI+r2,minJ=centerJ-r2,maxJ=centerJ+r2;for(let i=minI;i<=maxI;i++)appendGrid(i,minJ),appendGrid(i,maxJ);for(let j=minJ+1;j<maxJ;j++)appendGrid(minI,j),appendGrid(maxI,j);if(fn2(currentCircle,r2))return currentCircle;if(0===gridCount)return null}return null}findNearest(point2,excludeSelf=!0){let nearest=null;return this.searchByRing(point2,circle=>{for(const item of circle)excludeSelf&&item.point===point2||(!nearest||item.distanceSq<nearest.distanceSq)&&(nearest=item);return null!==nearest}),nearest}isFreePoint(point2){return 0===this.queryPoint(point2,!0).length}getFreePoint(){const targets=[];for(const list of this.map.values())1===list.size&&targets.push(...list);return targets}getFreePointFirst(){for(const list of this.map.values())if(1===list.size)return[...list][0]}static from(points,gridSize=.5){const psh=new PointSpatialHash(gridSize);return points.forEach((p2,index2)=>psh.insert(p2,index2)),psh}static fromByLines(lines){const psh=new PointSpatialHash;return lines.forEach(line=>psh.insert(line.start,line).insert(line.end,line)),psh}}class PointUtils{static _globalPoint=lazy(()=>new Point);static get globalPoint(){return this._globalPoint.value}static getCenter(points){let area2=0,cx=0,cy=0;for(let i=0,n=points.length;i<n;i++){const p1=points[i],p2=points[(i+1)%n],cross2=p1.x*p2.y-p2.x*p1.y;area2+=cross2,cx+=(p1.x+p2.x)*cross2,cy+=(p1.y+p2.y)*cross2}return area2*=.5,new Point(cx/(6*area2),cy/(6*area2))}static quantize(points,tolerance=.002){const gridSize=tolerance;for(const p2 of points)p2.x=Math.round(p2.x/gridSize)*gridSize,p2.y=Math.round(p2.y/gridSize)*gridSize;return points}static precision(points,count){for(const p2 of points)p2.precision(count);return points}static precision4(points){for(const p2 of points)p2.precision4();return points}static adsorb(points,tolerance=1e-4,mode="average"){const grid=new PointSpatialHash;points.forEach(p2=>grid.insert(p2));const visited=/* @__PURE__ */new Set;for(let i=0;i<points.length;i++){const point2=points[i];if(visited.has(point2))continue;const results=grid.queryCircle(point2,tolerance).map(item=>item.point);let x=0,y=0;if("average"===mode){let countX=0,countY=0;results.forEach(point22=>(countX+=point22.x,countY+=point22.y)),x=countX/results.length,y=countY/results.length}else x=point2.x,y=point2.y;results.forEach(p2=>{p2.set(x,y),visited.add(p2),grid.remove(p2)})}return visited.clear(),points}static _baseNormalLine=lazy(()=>new LineSegment);static get baseNormalLine(){return this._baseNormalLine.value}static constrainPointToAxis(point2,baseLine,normalStartPoint,baseNormalLine){if(!baseNormalLine&&normalStartPoint){const normal=baseLine.normal();baseNormalLine=this.baseNormalLine.set(normalStartPoint.clone().add(normal.clone().multiplyScalar(10)),normalStartPoint.clone().add(normal.multiplyScalar(-10)))}const point1=baseLine.projectPoint(point2,!1);if(!baseNormalLine)return point1&&point2.copy(point1),point2;const point22=baseNormalLine.projectPoint(point2,!1);return point1&&point22?point2.distance(point1)<point2.distance(point22)?point2.copy(point1):point2.copy(point22):point1?point2.copy(point1):point22&&point2.copy(point22),point2}static toArray(points){const array=new Float32Array(2*points.length);for(let i=0;i<points.length;i++){const point2=points[i];array[2*i+0]=point2.x,array[2*i+1]=point2.y}return array}static fromArray(array){const points=new Array;for(let i=0;i<array.length;i+=2)points.push(new Point(array[i],array[i+1]));return points}static createDeferredModifier(){const changes=[];return{push(targetPoint,value){return changes.push([targetPoint,value]),this},add(targetPoint,value){return changes.push([targetPoint,[targetPoint.x+value[0],targetPoint.y+value[1]]]),this},apply(){for(const[point2,value]of changes)point2.copy(value);return changes.length=0,this}}}static globalPoolArray=new Array;static globalPool=lazy(()=>PointUtils.createPool());static createPool(pool2=this.globalPoolArray){const usePool=[];return{get point(){const point2=pool2.pop()??new Point;return usePool.push(point2),point2},free(point2){const index2=usePool.indexOf(point2);index2<0||(usePool[index2]=usePool[usePool.length-1],usePool.pop(),pool2.push(point2))},freeAll(){for(let i=0;i<usePool.length;i++)pool2.push(usePool[i]);usePool.length=0}}}}const LINE_SYMBOL=/* @__PURE__ */Symbol("LINE_SYMBOL");class LineSegment{static get LINE_SYMBOL(){return LINE_SYMBOL}points=[new Point,new Point];userData={};currentData={};uuid=uuid();_length=null;get length(){return this._update(),null===this._length&&(this._length=this.start.distance(this.end)),this._length}get start(){return this.points[0]}get end(){return this.points[1]}_center=null;get center(){return this.getCenter()}_version="";get version(){return this._update(),this._version}_direction=null;constructor(p1,p2){this.set(p1??this.start,p2??this.end),this.start.currentData[LineSegment.LINE_SYMBOL]=this,this.end.currentData[LineSegment.LINE_SYMBOL]=this}_startVersion=-1;_endVersion=-1;_update(){this.start.version===this._startVersion&&this.end.version===this._endVersion||(this._center=null,this._direction=null,this._length=null,this._startVersion=this.start.version,this._endVersion=this.end.version,this._version=`${this.uuid}-${this._startVersion}-${this._endVersion}`)}getCenter(out=new Point){return this._update(),null===this._center&&(this._center=(new Point).set(.5*(this.start.x+this.end.x),.5*(this.start.y+this.end.y))),this._center.clone(out)}set(p1,p2){return this.start.copy(p1),this.end.copy(p2),this}setCenter(point2){const center=this.center,dirct=point2.directionFrom(center),dist=center.distance(point2);this.translate(dist,dirct)}setLength(len){const direct=this.direction(),half=.5*len,dx=direct.x*half,dy=direct.y*half,cx=.5*(this.start.x+this.end.x),cy=.5*(this.start.y+this.end.y);return this.start.set(cx-dx,cy-dy),this.end.set(cx+dx,cy+dy),this}getAnotherPoint(point2){return point2===this.start?this.end:this.start}offsetStart(width){const d2=this.end.directionFrom(this.start);return this.start.add(d2.multiplyScalar(width)),this}offsetEnd(width){const d2=this.start.directionFrom(this.end);return this.end.add(d2.multiplyScalar(width)),this}isSameEndpoint(line,eps=1e-9){return this.start.equal(line.start,eps)||this.start.equal(line.end,eps)||this.end.equal(line.start,eps)||this.end.equal(line.end,eps)}isSameEndpointAsStart(line,eps=1e-9){return this.start.equal(line.start,eps)||this.start.equal(line.end,eps)}isSameEndpointAsEnd(line,eps=1e-9){return this.end.equal(line.start,eps)||this.end.equal(line.end,eps)}getSameEndpoint(line,eps=1e-9){return this.start.equal(line.start,eps)?[this.start,line.start]:this.start.equal(line.end,eps)?[this.start,line.end]:this.end.equal(line.start,eps)?[this.end,line.start]:this.end.equal(line.end,eps)?[this.end,line.end]:null}isPointOnSegment(point2){const{start:start,end:end}=this,cross2=(point2.y-start.y)*(end.x-start.x)-(point2.x-start.x)*(end.y-start.y);if(Math.abs(cross2)>1e-10)return!1;return(point2.x-start.x)*(point2.x-end.x)+(point2.y-start.y)*(point2.y-end.y)<=1e-10}extendAlongDirection(width,direction="all"){const step=this.direction().multiplyScalar(width);return"end"!==direction&&"all"!==direction||this.end.add(step),"start"!==direction&&"all"!==direction||this.start.add(step.multiplyScalar(-1)),this}translate(dist,direction=this.direction()){const step=direction.clone().multiplyScalar(dist);return this.start.add(step),this.end.add(step),this}rotate(angle,center=this.center){return this.start.rotate(center,angle),this.end.rotate(center,angle),this}mirror(){this.end.rotate(this.start,Math.PI)}swap(){const p2=this.points[0];this.points[0]=this.points[1],this.points[1]=p2}swapValue(){const p2=this.points[0].clone();this.points[0].copy(this.points[1]),this.points[1].copy(p2)}cross(point2){const p1=this.start,p2=this.end;return(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x)}direction(out=Point.zero()){return this._update(),null===this._direction&&(this._direction=this.end.directionFrom(this.start)),this._direction.clone(out)}normal(){return this.points[1].leftNormal(this.points[0])}pointAt(t2,out=new Point){return out.set(this.start.x+(this.end.x-this.start.x)*t2,this.start.y+(this.end.y-this.start.y)*t2)}toRectangle(width=.1,cap="square",out=new Rectangle){const p1=this.start,p2=this.end,halfWidth=.5*width,normal=p2.leftNormal(p1);let extendX=0,extendY=0;if("square"===cap){const dir=p2.directionFrom(p1);extendX=dir.x*halfWidth,extendY=dir.y*halfWidth}const offsetX=normal.x*halfWidth,offsetY=normal.y*halfWidth;return out.p0.set(p1.x+offsetX-extendX,p1.y+offsetY-extendY),out.p1.set(p2.x+offsetX+extendX,p2.y+offsetY+extendY),out.p2.set(p2.x-offsetX+extendX,p2.y-offsetY+extendY),out.p3.set(p1.x-offsetX-extendX,p1.y-offsetY-extendY),out}getPointSideOfLine(point2){const cross2=this.cross(point2);return Math.abs(cross2)<1e-10?"on":cross2>0?"left":"right"}getRightDirection(){return this.normal().multiplyScalar(-1)}getLeftDirection(){return this.normal()}distanceToPoint(point2){const A=this.start,B2=this.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return point2.distance(A);const t2=((point2.x-A.x)*ABx+(point2.y-A.y)*ABy)/ABLengthSquared,clampedT=Math.max(0,Math.min(1,t2)),projX=A.x+clampedT*ABx,projY=A.y+clampedT*ABy;return PointUtils.globalPoint.set(projX,projY),point2.distance(PointUtils.globalPoint)}distanceSquaredToPoint(point2){const A=this.start,B2=this.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return A.distanceSquared(point2);const t2=((point2.x-A.x)*ABx+(point2.y-A.y)*ABy)/ABLengthSquared,clampedT=Math.max(0,Math.min(1,t2)),projX=A.x+clampedT*ABx,projY=A.y+clampedT*ABy;return PointUtils.globalPoint.set(projX,projY),PointUtils.globalPoint.distanceSquared(point2)}distanceToSegment(line){if(this.intersectLineSegment(line))return 0;const distancePointToSegment=(pt2,seg)=>{const A=seg.start,B2=seg.end,ABx=B2.x-A.x,ABy=B2.y-A.y,ABLengthSquared=ABx*ABx+ABy*ABy;if(ABLengthSquared<1e-10)return pt2.distance(A);const t2=((pt2.x-A.x)*ABx+(pt2.y-A.y)*ABy)/ABLengthSquared;if(t2<0)return pt2.distance(A);if(t2>1)return pt2.distance(B2);{const projX=A.x+t2*ABx,projY=A.y+t2*ABy;return pt2.distance(new Point(projX,projY))}};return Math.min(distancePointToSegment(this.start,line),distancePointToSegment(this.end,line),distancePointToSegment(line.start,this),distancePointToSegment(line.end,this))}isParallelTo(line,eps=1){const d1=this.direction(),d2=line.direction(),angle=d1.angle(d2,{unit:"degree",range:"180"});return Math.min(angle,180-angle)<eps}isPerpendicularTo(line,eps=1){const d1=this.direction(),d2=line.direction(),angle=d1.angle(d2,{unit:"degree",range:"180"});return Math.abs(angle-90)<eps}isCollinearOverlap(line,eps=1e-6){const p1=this.start,p2=this.end,p3=line.start,p4=line.end,d1=this.direction(),d2=line.direction();if(Math.abs(d1.cross(d2))>eps)return!1;const v2=p3.clone().subtract(p1);if(Math.abs(d1.cross(v2))>eps)return!1;const useX=Math.abs(d1.x)>Math.abs(d1.y),a1=useX?p1.x:p1.y,a2=useX?p2.x:p2.y,b1=useX?p3.x:p3.y,b22=useX?p4.x:p4.y,minA=Math.min(a1,a2),maxA=Math.max(a1,a2),minB=Math.min(b1,b22),maxB=Math.max(b1,b22),overlapStart=Math.max(minA,minB);return Math.min(maxA,maxB)-overlapStart>eps}projectLineSegment(line,out=new LineSegment){if(2!==line.points.length||2!==this.points.length)throw new Error("每条线段必须由两个点定义");const[p1,p2]=line.points,[q1,q2]=this.points,dir=new Point(q2.x-q1.x,q2.y-q1.y);if(0===dir.x&&0===dir.y)return out;const projectPoint=point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y,t3=(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared,projX=q1.x+t3*dir.x,projY=q1.y+t3*dir.y;return new Point(projX,projY)};let projP1=projectPoint(p1),projP2=projectPoint(p2);const getT=point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y;return(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared};let t1=getT(projP1),t2=getT(projP2);const clampPoint=t3=>{const clampedT=Math.max(0,Math.min(1,t3)),x=q1.x+clampedT*dir.x,y=q1.y+clampedT*dir.y;return new Point(x,y)};return(t1<0||t1>1)&&(projP1=clampPoint(t1)),(t2<0||t2>1)&&(projP2=clampPoint(t2)),projP1.x===projP2.x&&projP1.y===projP2.y?out.set(projP1,projP1):out.set(projP1,projP2)}projectPoint(p1,clip=!0){const[q1,q2]=this.points,dir=new Point(q2.x-q1.x,q2.y-q1.y);if(0===dir.x&&0===dir.y)return null;let projP1=(point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y,t2=(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared,projX=q1.x+t2*dir.x,projY=q1.y+t2*dir.y;return new Point(projX,projY)})(p1);if(!clip)return projP1;let t1=(point2=>{const pq=new Point(point2.x-q1.x,point2.y-q1.y),dirLengthSquared=dir.x*dir.x+dir.y*dir.y;return(pq.x*dir.x+pq.y*dir.y)/dirLengthSquared})(projP1);return t1<0||t1>1?null:projP1}projectPointValue(point2,eps=1e-12){const q1=this.start,q2=this.end,dx=q2.x-q1.x,dy=q2.y-q1.y,len2=dx*dx+dy*dy;if(len2<eps)return 0;return((point2.x-q1.x)*dx+(point2.y-q1.y)*dy)/len2}includedAngle(line){const d1=this.direction(),d2=line.direction();return d1.angleBetween(d2)/(Math.PI/180)}angle(line,opt){const d1=this.direction(),d2=line.direction();return d1.angle(d2,opt)}sameLine(line){const a2=this.start,b4=this.end,c=line.start,d2=line.end,isCollinear=(p1,p2,p3)=>Math.abs((p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x))<1e-10;return isCollinear(a2,b4,c)&&isCollinear(a2,b4,d2)?this.containsPoint(c)||this.containsPoint(d2)||line.containsPoint(a2)||line.containsPoint(b4)?1:0:-1}crossProduct(a2,b4,c){return(b4.x-a2.x)*(c.y-a2.y)-(b4.y-a2.y)*(c.x-a2.x)}isPointInSegmentBounds(pt2,segStart,segEnd,EPSILON=1e-10){return Math.min(segStart.x,segEnd.x)-EPSILON<=pt2.x&&pt2.x<=Math.max(segStart.x,segEnd.x)+EPSILON&&Math.min(segStart.y,segEnd.y)-EPSILON<=pt2.y&&pt2.y<=Math.max(segStart.y,segEnd.y)+EPSILON}intersectLineSegment(line,endpoint=!0){const p1=this.start,p2=this.end,p3=line.start,p4=line.end;if(Math.max(p1.x,p2.x)<Math.min(p3.x,p4.x)||Math.max(p3.x,p4.x)<Math.min(p1.x,p2.x)||Math.max(p1.y,p2.y)<Math.min(p3.y,p4.y)||Math.max(p3.y,p4.y)<Math.min(p1.y,p2.y))return!1;const d1=this.crossProduct(p1,p2,p3),d2=this.crossProduct(p1,p2,p4),d3=this.crossProduct(p3,p4,p1),d4=this.crossProduct(p3,p4,p2);if(d1*d2<0&&d3*d4<0)return!0;if(endpoint){if(Math.abs(d1)<1e-10&&this.isPointInSegmentBounds(p3,p1,p2,1e-10))return!0;if(Math.abs(d2)<1e-10&&this.isPointInSegmentBounds(p4,p1,p2,1e-10))return!0;if(Math.abs(d3)<1e-10&&this.isPointInSegmentBounds(p1,p3,p4,1e-10))return!0;if(Math.abs(d4)<1e-10&&this.isPointInSegmentBounds(p2,p3,p4,1e-10))return!0}return!1}containsPoint(pt2){const d1=pt2.distance(this.start),d2=pt2.distance(this.end),len=this.length;return Math.abs(d1+d2-len)<1e-10}getIntersection(line){const p1=this.start,p2=this.end,p3=line.start,p4=line.end,denom=(p1.x-p2.x)*(p3.y-p4.y)-(p1.y-p2.y)*(p3.x-p4.x);if(Math.abs(denom)<1e-10)return null;const t2=((p1.x-p3.x)*(p3.y-p4.y)-(p1.y-p3.y)*(p3.x-p4.x))/denom,x=p1.x+t2*(p2.x-p1.x),y=p1.y+t2*(p2.y-p1.y);return new Point(x,y)}directionEqual(line,errAngle=.1){return this.includedAngle(line)<errAngle}clone(userData=!0,cloneUUid=!1,out=new LineSegment){return out.set(this.points[0],this.points[1]),cloneUUid&&(out.uuid=this.uuid),userData&&(out.userData=cloneUserData(this.userData)),out}copy(line){return this.start.copy(line.start),this.end.copy(line.end),this}static getSegmentFromPoint(point2){return point2.currentData[LINE_SYMBOL]??null}static axisY(width,out=new LineSegment){const helf=.5*width;return out.set([0,-helf],[0,helf])}static axisX(width,out=new LineSegment){const helf=.5*width;return out.set([-helf,0],[helf,0])}static angleToYAxis(line){const dx=line.end.x-line.start.x,dy=line.end.y-line.start.y;return Math.atan2(dx,dy)}static from(line){return new LineSegment(Point.from(line.start),Point.from(line.end))}}class Box2{minX=0;maxX=0;minY=0;maxY=0;get points(){return[new Point(this.minX,this.minY),new Point(this.maxX,this.minY),new Point(this.maxX,this.maxY),new Point(this.minX,this.maxY)]}get width(){return this.maxX-this.minX}get height(){return this.maxY-this.minY}get center(){return new Point(.5*(this.maxX+this.minX),.5*(this.maxY+this.minY))}constructor(minX=0,maxX=0,minY=0,maxY=0){this.minX=minX,this.maxX=maxX,this.minY=minY,this.maxY=maxY}addPoints(points){points.forEach(p2=>{Number.isFinite(p2.x)&&(this.minX=Math.min(this.minX,p2.x),this.maxX=Math.max(this.maxX,p2.x)),Number.isFinite(p2.y)&&(this.minY=Math.min(this.minY,p2.y),this.maxY=Math.max(this.maxY,p2.y))})}getPaths3D(z=0){const points=this.points,list=[];return points.forEach((p2,i)=>{const nextP=points[(i+1)%points.length];list.push(p2.x,p2.y,z),list.push(nextP.x,nextP.y,z)}),list}intersectLineSegment(line){const p1=line.points[0],p2=line.points[1],dx=p2.x-p1.x,dy=p2.y-p1.y;if(0===dx&&0===dy)return this.minX<=p1.x&&p1.x<=this.maxX&&this.minY<=p1.y&&p1.y<=this.maxY;let tNear=Number.NEGATIVE_INFINITY,tFar=Number.POSITIVE_INFINITY;if(0!==dx){const tx1=(this.minX-p1.x)/dx,tx2=(this.maxX-p1.x)/dx;tNear=Math.max(tNear,Math.min(tx1,tx2)),tFar=Math.min(tFar,Math.max(tx1,tx2))}else if(p1.x<this.minX||p1.x>this.maxX)return!1;if(0!==dy){const ty1=(this.minY-p1.y)/dy,ty2=(this.maxY-p1.y)/dy;tNear=Math.max(tNear,Math.min(ty1,ty2)),tFar=Math.min(tFar,Math.max(ty1,ty2))}else if(p1.y<this.minY||p1.y>this.maxY)return!1;return tNear<=tFar&&tNear<=1&&tFar>=0}containsLineSegment(line){const[p1,p2]=line.points;return this.minX<=p1.x&&p1.x<=this.maxX&&this.minY<=p1.y&&p1.y<=this.maxY&&this.minX<=p2.x&&p2.x<=this.maxX&&this.minY<=p2.y&&p2.y<=this.maxY}intersectRectangle(rectangle){const rPoints=rectangle.points;let rMinX=rPoints[0].x,rMinY=rPoints[0].y,rMaxX=rPoints[0].x,rMaxY=rPoints[0].y;for(let i=1;i<4;i++){const p2=rPoints[i];p2.x<rMinX&&(rMinX=p2.x),p2.y<rMinY&&(rMinY=p2.y),p2.x>rMaxX&&(rMaxX=p2.x),p2.y>rMaxY&&(rMaxY=p2.y)}if(this.maxX<rMinX||this.minX>rMaxX||this.maxY<rMinY||this.minY>rMaxY)return!1;const bPoints=this.points;for(let i=0;i<4;i++){const bp1=bPoints[i],bp2=bPoints[(i+1)%4];for(let j=0;j<4;j++){const rp1=rPoints[j],rp2=rPoints[(j+1)%4],o1=(bp2.x-bp1.x)*(rp1.y-bp1.y)-(bp2.y-bp1.y)*(rp1.x-bp1.x),o2=(bp2.x-bp1.x)*(rp2.y-bp1.y)-(bp2.y-bp1.y)*(rp2.x-bp1.x),o3=(rp2.x-rp1.x)*(bp1.y-rp1.y)-(rp2.y-rp1.y)*(bp1.x-rp1.x),o4=(rp2.x-rp1.x)*(bp2.y-rp1.y)-(rp2.y-rp1.y)*(bp2.x-rp1.x);if(o1*o2<0&&o3*o4<0)return!0;if(0===o1&&Math.min(bp1.x,bp2.x)<=rp1.x&&rp1.x<=Math.max(bp1.x,bp2.x)&&Math.min(bp1.y,bp2.y)<=rp1.y&&rp1.y<=Math.max(bp1.y,bp2.y))return!0;if(0===o2&&Math.min(bp1.x,bp2.x)<=rp2.x&&rp2.x<=Math.max(bp1.x,bp2.x)&&Math.min(bp1.y,bp2.y)<=rp2.y&&rp2.y<=Math.max(bp1.y,bp2.y))return!0;if(0===o3&&Math.min(rp1.x,rp2.x)<=bp1.x&&bp1.x<=Math.max(rp1.x,rp2.x)&&Math.min(rp1.y,rp2.y)<=bp1.y&&bp1.y<=Math.max(rp1.y,rp2.y))return!0;if(0===o4&&Math.min(rp1.x,rp2.x)<=bp2.x&&bp2.x<=Math.max(rp1.x,rp2.x)&&Math.min(rp1.y,rp2.y)<=bp2.y&&bp2.y<=Math.max(rp1.y,rp2.y))return!0}}for(let i=0;i<4;i++){const p2=rPoints[i];if(p2.x>=this.minX&&p2.x<=this.maxX&&p2.y>=this.minY&&p2.y<=this.maxY)return!0}const isPointInRect=point2=>{let sign=0;for(let i=0;i<4;i++){const p1=rPoints[i],p2=rPoints[(i+1)%4],cross2=(p2.x-p1.x)*(point2.y-p1.y)-(p2.y-p1.y)*(point2.x-p1.x);if(0===cross2){const denom=Math.abs(p2.x-p1.x)>1e-10?p2.x-p1.x:p2.y-p1.y,t2=denom?(point2.x-p1.x)/denom:0;if(t2>=0&&t2<=1)return!0}else{const currentSign=cross2>0?1:-1;if(0===sign)sign=currentSign;else if(sign!==currentSign)return!1}}return!0};for(let i=0;i<4;i++)if(isPointInRect(bPoints[i]))return!0;return!1}containsRectangle(rectangle){return rectangle.points.every(p2=>this.minX<=p2.x&&p2.x<=this.maxX&&this.minY<=p2.y&&p2.y<=this.maxY)}intersectBox(box){return!(this.maxX<box.minX||this.minX>box.maxX||this.maxY<box.minY||this.minY>box.maxY)}containsBox(box){return this.minX<=box.minX&&box.maxX<=this.maxX&&this.minY<=box.minY&&box.maxY<=this.maxY}containsPoint(point2){return point2.x>=this.minX&&point2.x<=this.maxX&&point2.y>=this.minY&&point2.y<=this.maxY}set(minX,minY,maxX,maxY){return this.minX=minX,this.minY=minY,this.maxX=maxX,this.maxY=maxY,this}scaleSize(maxWidth,maxHeight,mode="min"){const scaleX=maxWidth/this.width,scaleY=maxHeight/this.height;return Math[mode](scaleX,scaleY)}multiplyScalar(scalar){return this.minX*=scalar,this.minY*=scalar,this.maxX*=scalar,this.maxY*=scalar,this}expansion(w){return this.minX-=w,this.minY-=w,this.maxX+=w,this.maxY+=w,this}clone(){return new Box2(this.minX,this.maxX,this.minY,this.maxY)}static fromByPoints(...points){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return points.forEach(p2=>{minX=Math.min(minX,p2.x),maxX=Math.max(maxX,p2.x),minY=Math.min(minY,p2.y),maxY=Math.max(maxY,p2.x)}),new Box2(minX,maxX,minY,maxY)}static fromByLineSegment(line1,...lines){Array.isArray(line1)?line1.forEach(line=>lines.push(line)):line1 instanceof LineSegment&&lines.push(line1);let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;return lines.forEach(line=>{line?.points?.forEach(p2=>{Number.isFinite(p2.x)&&(minX=Math.min(minX,p2.x),maxX=Math.max(maxX,p2.x)),Number.isFinite(p2.y)&&(minY=Math.min(minY,p2.y),maxY=Math.max(maxY,p2.y))})}),new Box2(minX,maxX,minY,maxY)}}class Quadtree{bounds;capacity;maxDepth;depth;isLeaf=!0;children=null;nodes=[];color=[Math.random(),Math.random(),Math.random()];id;constructor(bounds,capacity=8,maxDepth=10,depth=1,id=/* @__PURE__ */Symbol("id")){this.bounds=bounds,this.capacity=capacity,this.depth=depth,this.maxDepth=maxDepth,this.id=id,GCHandler.add(this,{value:{quadtrees:this.children,nodes:this.nodes,id:this.id},onGc:({quadtrees:quadtrees,nodes:nodes,id:id2})=>{const clear=nodes2=>nodes2.forEach(node=>delete node.line.currentData[id2]),clearEach=quadtrees2=>{quadtrees2?.forEach(quadtree=>{clear(quadtree.nodes),clearEach(quadtree.children)})};clear(nodes),quadtrees&&clearEach(quadtrees)}})}insert(node,userData){if(node instanceof LineSegment)this.insert({line:node,userData:userData??{}});else{if(!this.isLeaf){const quadrant=this.getQuadrant(node.line);if(-1!==quadrant)return void this.children[quadrant].insert(node)}if(this.nodes.push(node),node.line.currentData[this.id]=node,node.parent=this,this.isLeaf&&this.nodes.length>this.capacity&&this.depth<this.maxDepth){this.subdivide();const nodes=this.nodes;this.nodes=[];for(const n of nodes){const quadrant=this.getQuadrant(n.line);-1!==quadrant?this.children[quadrant].insert(n):(n.parent=this,this.nodes.push(n),node.line.currentData[this.id]=node)}}}}remove(node){if(node instanceof LineSegment)return void((node=node.currentData[this.id])&&this.remove(node));const index2=node.parent?.nodes.indexOf(node);index2>-1&&(node.parent?.nodes.splice(index2,1),delete node.line.currentData[this.id])}update(node){this.remove(node),this.insert(node)}clear(){this.isLeaf||(this.children?.forEach(child=>child.clear()),this.children=null,this.isLeaf=!0),this.nodes.forEach(node=>{delete node.line.currentData[this.id]}),this.nodes=[]}getQuadrant(line){let count=0,quadrant=-1;return this.children[0].bounds.intersectLineSegment(line)&&(count++,quadrant=0),this.children[1].bounds.intersectLineSegment(line)&&(count++,quadrant=1),this.children[2].bounds.intersectLineSegment(line)&&(count++,quadrant=2),this.children[3].bounds.intersectLineSegment(line)&&(count++,quadrant=3),1===count?quadrant:-1}subdivide(){if(!this.isLeaf)return;this.isLeaf=!1,this.children=[];const midX=(this.bounds.minX+this.bounds.maxX)/2,midY=(this.bounds.minY+this.bounds.maxY)/2;this.children[0]=new Quadtree(new Box2(this.bounds.minX,midX,this.bounds.minY,midY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[1]=new Quadtree(new Box2(midX,this.bounds.maxX,this.bounds.minY,midY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[2]=new Quadtree(new Box2(this.bounds.minX,midX,midY,this.bounds.maxY),this.capacity,this.maxDepth,this.depth+1,this.id),this.children[3]=new Quadtree(new Box2(midX,this.bounds.maxX,midY,this.bounds.maxY),this.capacity,this.maxDepth,this.depth+1,this.id)}queryBox(box2){const result=[];if(!this.bounds.intersectBox(box2))return result;for(const node of this.nodes)box2.intersectLineSegment(node.line)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryBox(box2));return result}queryCircle(pos,radius){const result=[],circleBox=new Box2(pos.x-radius,pos.x+radius,pos.y-radius,pos.y+radius);if(!this.bounds.intersectBox(circleBox))return result;for(const node of this.nodes){const[p1,p2]=node.line.points,dx=p2.x-p1.x,dy=p2.y-p1.y,l2=dx*dx+dy*dy;let t2=((pos.x-p1.x)*dx+(pos.y-p1.y)*dy)/l2;t2=Math.max(0,Math.min(1,t2));const closestX=p1.x+t2*dx,closestY=p1.y+t2*dy;pos.distance(new Point(closestX,closestY))<=radius&&result.push(node)}if(!this.isLeaf)for(const child of this.children)result.push(...child.queryCircle(pos,radius));return result.sort(l=>l.line.length),result}queryPoint(point2){const result=[];if(point2.x<this.bounds.minX||point2.x>this.bounds.maxX||point2.y<this.bounds.minY||point2.y>this.bounds.maxY)return result;for(const node of this.nodes)node.line.isPointOnSegment(point2)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryPoint(point2));return result}queryRect(rectangle){const result=[];if(!this.bounds.intersectRectangle(rectangle))return result;for(const node of this.nodes)rectangle.intersectLineSegment(node.line)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryRect(rectangle));return result}queryLineSegment(lineSegment,endpoint=!0){const result=[];if(!this.bounds.intersectLineSegment(lineSegment))return result;for(const node of this.nodes)lineSegment.intersectLineSegment(node.line,endpoint)&&result.push(node);if(!this.isLeaf)for(const child of this.children)result.push(...child.queryLineSegment(lineSegment));return result}raycast(origin,direct,near=0,far=10){const result=[],rayBox=new Box2(Math.min(origin.x,origin.x+direct.x*far),Math.max(origin.x,origin.x+direct.x*far),Math.min(origin.y,origin.y+direct.y*far),Math.max(origin.y,origin.y+direct.y*far));if(!this.bounds.intersectBox(rayBox))return result;const len=Math.hypot(direct.x,direct.y),dir_x=direct.x/len,dir_y=direct.y/len;for(const node of this.nodes){const[p1,p2]=node.line.points,dx=p2.x-p1.x,dy=p2.y-p1.y,det=dir_x*dy-dir_y*dx;if(Math.abs(det)<1e-10)continue;const ox=origin.x,oy=origin.y,t2=((p1.x-ox)*dy-(p1.y-oy)*dx)/det,u2=((p1.x-ox)*dir_y-(p1.y-oy)*dir_x)/det;if(t2>=near&&t2<=far&&u2>=0&&u2<=1){const point2=new Point(ox+dir_x*t2,oy+dir_y*t2);result.push({targetLine:node.line,intersectPoint:point2,distance:t2})}}if(!this.isLeaf)for(const child of this.children)result.push(...child.raycast(origin,direct,near,far));return 1==this.depth&&result.sort((a2,b4)=>a2.distance-b4.distance),result}boundsToArray(array=[],colors2,recursion=!0){return!this.isLeaf&&recursion&&this.children?.forEach(child=>child.boundsToArray(array,colors2)),array.push(...this.bounds.points.flatMap((p2,i,array2)=>{const np=array2[(i+1)%array2.length];return colors2?.push(...this.color),colors2?.push(...this.color),[p2.x,p2.y,0,np.x,np.y,0]})),array}static from(lines,userDataFun){const quadtree=new Quadtree(Box2.fromByLineSegment(lines));return lines.forEach((line,index2)=>quadtree.insert({line:line,userData:userDataFun?userDataFun(line,index2):void 0})),quadtree}}class MapEnhance extends Map{get valueArray(){return[...this.values()]}map(callbackfn){const result=[];for(const[k,v2]of this)result.push(callbackfn(v2,k));return result}filter(callbackfn){const result=[];for(const[k,v2]of this)callbackfn(v2,k)&&result.push(v2);return result}filterKey(callbackfn){const result=[];for(const[k,v2]of this)callbackfn(v2,k)&&result.push(k);return result}reduce(callbackfn,result){for(const[k,v2]of this)result=callbackfn(result,v2,k);return result}some(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return!0;return!1}every(callbackfn){for(const[k,v2]of this)if(!callbackfn(v2,k))return!1;return!0}find(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return v2}findKey(callbackfn){for(const[k,v2]of this)if(callbackfn(v2,k))return k}someKeys(keys){return keys.some(key=>this.has(key))}everyKeys(keys){return keys.every(key=>this.has(key))}group(callbackfn){const map=new ArrayMap;for(const[k,v2]of this){const groupKey=callbackfn(v2,k);map.append(groupKey,v2)}return map}toObject(){return this.reduce((obj,v2,k)=>(obj[`${k}`]=v2,obj),{})}first(){return this.values().next().value}firstKey(){return this.keys().next().value}last(){let last;for(const v2 of this.values())last=v2;return last}sortBy(callback){return[...this.entries()].sort((a2,b4)=>{const va2=callback(a2[1],a2[0]),vb=callback(b4[1],b4[0]);return va2<vb?-1:va2>vb?1:0})}pluck(keyPath){return this.map(v2=>v2[keyPath])}}class ArrayMap extends MapEnhance{maxLength=1/0;append(k,...arr){return arr.forEach(v2=>{this.has(k)||this.set(k,[]);const list=this.get(k);list.push(v2),list.length>this.maxLength&&list.splice(0,list.length-this.maxLength)}),this}setLength(key,len){const list=this.get(key);list&&(list.length=Math.max(0,len))}remove(k,...arr){const set2=this.get(k);return set2&&arr.forEach(v2=>set2.splice(set2.indexOf(v2),1)),this}getOrCreate(key){return this.has(key)||this.set(key,[]),this.get(key)}}class SetMap extends MapEnhance{append(k,...arr){return Array.isArray(k)?(k.forEach(k2=>this.append(k2,...arr)),this):(arr.forEach(v2=>{this.has(k)||this.set(k,/* @__PURE__ */new Set),this.get(k)?.add(v2)}),this)}hasValue(key,value){return this.get(key)?.has(value)??!1}}class CounterMap extends MapEnhance{set(key,step=1){return console.warn("Use increment() instead of set() in CounterMap"),this.increment(key,step),this}increment(key,step=1){const count=super.get(key)??0;return super.set(key,count+step),this}getByCount(count){return this.filterKey(v2=>v2===count)}getAllCount(){return this.reduce((count,v2)=>count+v2,0)}getMaxKey(){let maxKey,maxValue=-1/0;for(const[k,v2]of this)v2>maxValue&&(maxValue=v2,maxKey=k);return maxKey}getminKey(){let maxKey,maxValue=-1/0;for(const[k,v2]of this)v2<maxValue&&(maxValue=v2,maxKey=k);return maxKey}}class UnionFindSet{parent;rank;constructor(size2){this.parent=new Uint32Array(size2),this.rank=new Uint8Array(size2).fill(1);for(let i=0;i<size2;i++)this.parent[i]=i}find(x){return this.parent[x]!==x&&(this.parent[x]=this.find(this.parent[x])),this.parent[x]}union(x,y){let rootX=this.find(x),rootY=this.find(y);rootX!==rootY&&(this.rank[rootX]>this.rank[rootY]?this.parent[rootY]=rootX:this.rank[rootX]<this.rank[rootY]?this.parent[rootX]=rootY:(this.parent[rootY]=rootX,this.rank[rootX]+=1))}getAllSets(){const sets=new ArrayMap;for(const el of this.parent.keys()){const root=this.find(el);sets.append(root,el)}return sets}}class LineSegmentSpatialHash{constructor(cellSize=.2){this.cellSize=cellSize}buckets=/* @__PURE__ */new Map;lineCells=/* @__PURE__ */new Map;insert(line){const keys=this.getLineCellKeys(line);this.lineCells.set(line,keys);for(const key of keys){let bucket=this.buckets.get(key);bucket||(bucket=/* @__PURE__ */new Set,this.buckets.set(key,bucket)),bucket.add(line)}return this}insertLines(lines){for(const line of lines)this.insert(line);return this}remove(line){const keys=this.lineCells.get(line);if(!keys)return this;for(const key of keys){const bucket=this.buckets.get(key);bucket&&(bucket.delete(line),0===bucket.size&&this.buckets.delete(key))}return this.lineCells.delete(line),this}update(line){return this.remove(line),this.insert(line),this}clear(){return this.buckets.clear(),this.lineCells.clear(),this}visited=/* @__PURE__ */new Set;queryPoint(point2,radius=0,out=[]){const radiusSq=radius*radius;this.visited.clear(),out.length=0;const minX=point2.x-radius,minY=point2.y-radius,maxX=point2.x+radius,maxY=point2.y+radius,minCellX=this.toCell(minX),minCellY=this.toCell(minY),maxCellX=this.toCell(maxX),maxCellY=this.toCell(maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket){if(this.visited.has(line))continue;this.visited.add(line);line.distanceSquaredToPoint(point2)<=radiusSq&&out.push(line)}}return out}queryBounds(bounds,out=[]){this.visited.clear(),out.length=0;const minCellX=this.toCell(bounds.minX),minCellY=this.toCell(bounds.minY),maxCellX=this.toCell(bounds.maxX),maxCellY=this.toCell(bounds.maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket)this.visited.has(line)||(this.visited.add(line),out.push(line))}return out}queryPotentialLine(line,out=[]){this.visited.clear(),out.length=0;const keys=this.getLineCellKeys(line);for(const key of keys){const bucket=this.buckets.get(key);if(bucket)for(const other of bucket)this.visited.has(other)||(this.visited.add(other),other!==line&&out.push(other))}return out}queryLine(line,out=[]){this.queryPotentialLine(line,out);let write=0;for(let i=0;i<out.length;i++){const other=out[i];line.intersectLineSegment(other)&&(out[write++]=other)}return out.length=write,out}rectangleBounds=new Box2;queryRectangle(rectangle,out=[]){const bounds=rectangle.toBox(this.rectangleBounds);this.visited.clear(),out.length=0;const minCellX=this.toCell(bounds.minX),minCellY=this.toCell(bounds.minY),maxCellX=this.toCell(bounds.maxX),maxCellY=this.toCell(bounds.maxY);for(let x=minCellX;x<=maxCellX;x++)for(let y=minCellY;y<=maxCellY;y++){const bucket=this.buckets.get(this.getKey(x,y));if(bucket)for(const line of bucket)this.visited.has(line)||(this.visited.add(line),(rectangle.containsPoint(line.start)||rectangle.containsPoint(line.end)||rectangle.intersectLineSegment(line))&&out.push(line))}return out}rayIntersectSegment(origin,dir,seg){const x1=origin.x,y1=origin.y,x2=origin.x+dir.x,y2=origin.y+dir.y,x3=seg.start.x,y3=seg.start.y,x4=seg.end.x,y4=seg.end.y,denom=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);if(Math.abs(denom)<1e-9)return null;const t2=((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/denom,u2=-((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))/denom;return t2<0||u2<0||u2>1?null:{t:t2,point:new Point(x1+dir.x*t2,y1+dir.y*t2)}}raycast(origin,direction,maxDistance=1/0,out){this.visited.clear();const cellSize=this.cellSize,ox=origin.x/cellSize,oy=origin.y/cellSize;let cellX=Math.floor(ox),cellY=Math.floor(oy);const dx=direction.x,dy=direction.y,stepX=dx>0?1:dx<0?-1:0,stepY=dy>0?1:dy<0?-1:0,tDeltaX=0===stepX?1/0:Math.abs(1/dx),tDeltaY=0===stepY?1/0:Math.abs(1/dy);let tMaxX=stepX>0?(Math.floor(ox)+1-ox)*tDeltaX:(ox-Math.floor(ox))*tDeltaX,tMaxY=stepY>0?(Math.floor(oy)+1-oy)*tDeltaY:(oy-Math.floor(oy))*tDeltaY,bestT=1/0,bestLine=null,bestPoint=null;for(;;){const bucket=this.buckets.get(this.getKey(cellX,cellY));if(bucket)for(const line of bucket){if(this.visited.has(line))continue;this.visited.add(line);const hit=this.rayIntersectSegment(origin,direction,line);hit&&(hit.t<0||hit.t>maxDistance||hit.t<bestT&&(bestT=hit.t,bestLine=line,bestPoint=hit.point))}const nextT=Math.min(tMaxX,tMaxY);if(nextT*cellSize>bestT)break;if(nextT>maxDistance)break;tMaxX<tMaxY?(tMaxX+=tDeltaX,cellX+=stepX):(tMaxY+=tDeltaY,cellY+=stepY)}return bestLine&&bestPoint?out?(out.line=bestLine,out.point=bestPoint,out.distance=bestT,out.t=bestT,out):{line:bestLine,point:bestPoint,distance:bestT,t:bestT}:null}getLineCellKeys(line,out=[]){out.length=0;const x0=line.start.x/this.cellSize,y0=line.start.y/this.cellSize,x1=line.end.x/this.cellSize,y1=line.end.y/this.cellSize;let cellX=Math.floor(x0),cellY=Math.floor(y0);const endX=Math.floor(x1),endY=Math.floor(y1),dx=x1-x0,dy=y1-y0,stepX=dx>0?1:dx<0?-1:0,stepY=dy>0?1:dy<0?-1:0,tDeltaX=0===stepX?1/0:Math.abs(1/dx),tDeltaY=0===stepY?1/0:Math.abs(1/dy);let tMaxX=stepX>0?(Math.floor(x0)+1-x0)*tDeltaX:(x0-Math.floor(x0))*tDeltaX,tMaxY=stepY>0?(Math.floor(y0)+1-y0)*tDeltaY:(y0-Math.floor(y0))*tDeltaY;try{for(;;){if(out.length>1e4){out.length=0;break}if(out.push(this.getKey(cellX,cellY)),cellX===endX&&cellY===endY)break;tMaxX<tMaxY?(tMaxX+=tDeltaX,cellX+=stepX):(tMaxY+=tDeltaY,cellY+=stepY)}}catch(error){console.log(out.length)}return out}toCell(value){return Math.floor(value/this.cellSize)}getKey(x,y){return 73856093n*BigInt(x)^19349663n*BigInt(y)}static from(lines,cellSize){const lsh=new LineSegmentSpatialHash(cellSize);return lsh.insertLines(lines),lsh}}class LineIndexGenerator{index=0;get size(){return this.index}constructor(lines=[]){lines.forEach(key=>{const id=this.next();this.map.set(key,id),this.lineMap.set(id,key)})}next(){return this.index++}reset(){this.index=0}map=/* @__PURE__ */new Map;lineMap=/* @__PURE__ */new Map;getIndex(key){if(!this.map.has(key)){const id=this.next();this.map.set(key,id),this.lineMap.set(id,key)}return this.map.get(key)}getLine(index2){return this.lineMap.get(index2)}}class UndirectedGraph{adjacencyList;get size(){return this.adjacencyList.size}constructor(){this.adjacencyList=/* @__PURE__ */new Map}addNode(node){this.adjacencyList.has(node)||this.adjacencyList.set(node,/* @__PURE__ */new Set)}addEdge(u2,v2){this.adjacencyList.get(u2)?.add(v2)??this.adjacencyList.set(u2,/* @__PURE__ */new Set([v2])),this.adjacencyList.get(v2)?.add(u2)??this.adjacencyList.set(v2,/* @__PURE__ */new Set([u2]))}removeEdge(u2,v2){this.adjacencyList.get(u2)?.delete(v2),this.adjacencyList.get(v2)?.delete(u2)}removeNode(node){const neighbors=this.adjacencyList.get(node);if(neighbors){for(const neighbor of neighbors)this.adjacencyList.get(neighbor)?.delete(node);this.adjacencyList.delete(node)}}getNeighbors(node){return this.adjacencyList.get(node)}printGraph(){for(let[node,neighbors]of this.adjacencyList.entries())console.log(`${node} -> ${[...neighbors].join(", ")}`)}getPaths(){let paths=[];const visited=/* @__PURE__ */new Set,dfs=(node,path)=>{path.push(node),visited.add(node);let hasUnvisitedNeighbor=!1;const neighbors=this.getNeighbors(node);if(neighbors)for(const neighbor of neighbors)visited.has(neighbor)||(hasUnvisitedNeighbor=!0,dfs(neighbor,path));!hasUnvisitedNeighbor&&path.length>1&&paths.push([...path]),path.pop()};for(const node of this.adjacencyList.keys())visited.has(node)||dfs(node,[]);return paths}forEach(callbackFun){for(let[node,neighbors]of this.adjacencyList.entries())callbackFun(node,neighbors)}forEachEdge(callbackFun){for(const[node,neighbors]of this.adjacencyList.entries())for(const neighbor of neighbors)neighbor>node&&callbackFun(node,neighbor)}}class LineSegmentUndirectedGraph extends UndirectedGraph{lineMap=/* @__PURE__ */new Map;pointToIndex=/* @__PURE__ */new Map;indexToPoint=/* @__PURE__ */new Map;nextIndex=0;constructor(lines=[]){super(),lines.length>0&&this.buildFromLines(lines)}buildFromLines(lines){lines.length>1e3&&(this.pointToIndex.clear(),this.indexToPoint.clear(),this.nextIndex=0);for(const line of lines){const i1=this.getOrCreateIndex(line.start),i2=this.getOrCreateIndex(line.end);super.addEdge(i1,i2);const key=i1<i2?`${i1}-${i2}`:`${i2}-${i1}`;this.lineMap.set(key,line)}}getLine(a2,b4){const key=a2<b4?`${a2}-${b4}`:`${b4}-${a2}`;return this.lineMap.get(key)}getLineAll(){return Array.from(this.lineMap.values())}getOrCreateIndex(point2){const code=point2.hashCode();let index2=this.pointToIndex.get(code);return void 0===index2&&(index2=this.nextIndex++,this.pointToIndex.set(code,index2),this.indexToPoint.set(index2,point2)),index2}getIndex(point2){return this.pointToIndex.get(point2.hashCode())}getPoint(index2){return this.indexToPoint.get(index2)}get points(){return Array.from(this.indexToPoint.values())}get lines(){return Array.from(this.lineMap.values())}addLines(lines){return this.buildFromLines(lines),this}removeLines(lines){for(const line of lines){const i1=this.getIndex(line.start),i2=this.getIndex(line.end);if(void 0!==i1&&void 0!==i2){super.removeEdge(i1,i2);const key=i1<i2?`${i1}-${i2}`:`${i2}-${i1}`;this.lineMap.delete(key)}}}pathToLines(path){const lines=[];for(let i=0;i<path.length;i++){const line=this.getLine(path[i],path[(i+1)%path.length]);line&&lines.push(line)}return lines}clear(){this.adjacencyList.clear(),this.lineMap.clear(),this.pointToIndex.clear(),this.indexToPoint.clear(),this.nextIndex=0}breakpointMerging(callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){const unionFindSet=new UnionFindSet(this.lineMap.size),lineIndexGenerator=new LineIndexGenerator;this.adjacencyList.forEach((set2,k)=>{if(2!==set2.size)return;const values=set2.values(),v12=values.next().value,v2=values.next().value,line1=this.getLine(k,v12),line2=this.getLine(k,v2);line1.isParallelTo(line2)&&unionFindSet.union(lineIndexGenerator.getIndex(line1),lineIndexGenerator.getIndex(line2))}),unionFindSet.getAllSets().forEach(list=>{if(list.length<=1)return;const lines=list.map(i=>lineIndexGenerator.getLine(i)),newLine=LineSegmentUtils.mergeCollinearSegments(lines);callBack&&callBack(newLine,lines),lines.forEach(line=>removeLines.add(line)),newLines.push(newLine),this.removeLines(lines),this.addLines([newLine])})}forEachPathLine(fun){const leafVertices=[];this.adjacencyList.forEach((v2,k)=>1===v2.size&&leafVertices.push(k));const getEdgeKey=(a2,b4)=>a2<b4?`${a2}_${b4}`:`${b4}_${a2}`,visitedEdge=/* @__PURE__ */new Set,vertexIndexMap=new ArrayMap;let index2=0;const traverseEdges=v2=>{const set2=this.getNeighbors(v2);if(!set2)return;const start=this.getPoint(v2);for(const v12 of set2){const key=getEdgeKey(v2,v12);if(visitedEdge.has(key))continue;const end=this.getPoint(v12),line=this.getLine(v2,v12);let endType="none";1===this.getNeighbors(v12).size?endType="isolated":vertexIndexMap.has(v12)&&(endType="intersect");const indexList=[...vertexIndexMap.get(v2)??[]];vertexIndexMap.append(v2,index2),vertexIndexMap.append(v12,index2),fun(start,end,line,index2++,endType,indexList),visitedEdge.add(key),traverseEdges(v12)}};for(let i=0;i<leafVertices.length;i++){const v2=leafVertices[i];index2=0,traverseEdges(v2)}for(const v2 of this.adjacencyList.keys())vertexIndexMap.has(v2)||(index2=0,traverseEdges(v2))}static breakpointMerging(lines,callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){PointUtils.adsorb(LineSegmentUtils.flatPoints(lines),1e-4);const lud=new LineSegmentUndirectedGraph(lines);return lud.breakpointMerging(callBack,removeLines,newLines),lines=lud.getLineAll()}static rotate(lines,angle,callbackFun){const center=Box2.fromByLineSegment(lines).center;return lines.map(line=>(line.start.rotate(center,angle),line.end.rotate(center,angle),callbackFun&&callbackFun(line,center,angle),line))}toJson(){const edges=[],ids=/* @__PURE__ */new Set;return this.adjacencyList.forEach((list,v2)=>list.forEach(v22=>{const id=v2>v22?`${v2}_${v22}`:`${v22}_${v2}`;ids.has(id)||(edges.push([v2,v22]),ids.add(id))})),{points:this.points,edges:edges}}}class LineSegmentUtils{static clone(lines){return lines.map(line=>line.clone())}static precision(lines,count){for(const l of lines)l.start.precision(count),l.end.precision(count);return lines}static legitimacy(line){return[line.start.x,line.start.y,line.end.x,line.end.y].every(v2=>"number"==typeof v2&&!Number.isNaN(v2))}static precision4(lines){for(const l of lines)l.start.precision4(),l.end.precision4();return lines}static maxLengthLineIndex(lines,excludeCallBack){let maxLength=-1/0,maxIndex=-1;for(let i=0;i<lines.length;i++){if(excludeCallBack&&excludeCallBack(lines[i]))continue;const length=lines[i].length;length>maxLength&&(maxLength=length,maxIndex=i)}return maxIndex}static getLinesCenter(lines){let totalWeight=0,x=0,y=0;for(const line of lines){const len=line.length,center=line.center;x+=center.x*len,y+=center.y*len,totalWeight+=len}return new Point(x/totalWeight,y/totalWeight)}static GroupBuilder(groups){const builder={handle(k,fn2){return Array.isArray(k)?(k.forEach(k2=>this.handle(k2,fn2)),builder):(groups[k]&&(groups[k]=fn2(groups[k],groups)),builder)},handleAll:fn2=>(Object.keys(groups).forEach(k=>{groups[k]=fn2(groups[k],k,groups)}),builder),merge:()=>Object.values(groups).flat()};return builder}static group(lines,fn2){const arrayMap=new ArrayMap;for(let i=0;i<lines.length;i++){const line=lines[i],key=fn2(line);arrayMap.append(key,line)}return arrayMap.reduce((list,lines2,key)=>(list[key]=lines2,list),{})}static groupByPathAndParallel(lines){const pointVirtualGrid=new PointSpatialHash,quadtree=new Quadtree(Box2.fromByLineSegment(lines));lines.forEach(line=>{line.points.forEach(p2=>pointVirtualGrid.insert(p2,line)),quadtree.insert(line)});const visited=/* @__PURE__ */new Set;function dfs(line,visited2,group2){if(visited2.has(line))return;const waitLines=[];return waitLines.push(...pointVirtualGrid.queryPoint(line.start).filter(result=>result.userData!==line&&line.isParallelTo(result.userData,.1)).map(item=>item.userData),...pointVirtualGrid.queryPoint(line.end).filter(result=>result.userData!==line&&line.isParallelTo(result.userData,.1)).map(item=>item.userData),...quadtree.queryPoint(line.start).filter(result=>result.line!==line&&line.isParallelTo(result.line,.1)).map(item=>item.line),...quadtree.queryPoint(line.end).filter(result=>result.line!==line&&line.isParallelTo(result.line,.1)).map(item=>item.line)),waitLines.forEach(line1=>{line1&&!group2.has(line1)&&(group2.add(line1),dfs(line1,visited2,group2))}),visited2.add(line),group2}const groups=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(visited.has(line))continue;const group2=dfs(line,visited,/* @__PURE__ */new Set([line]));group2&&groups.push([...group2])}return groups}static groupByCenterPointSide(lines,line){const map=/* @__PURE__ */new Map;return lines.forEach(l=>{const m=line.getPointSideOfLine(l.center);map.has(m)||map.set(m,[]),map.get(m)?.push(l)}),[...map.values()]}static groupByPath(lines){const pointVirtualGrid=new PointSpatialHash;function dfs(point2,group2,visted2){pointVirtualGrid.queryPoint(point2,!0).forEach(item=>{const line=item.userData;if(visted2.has(line))return;visted2.add(line),group2.push(line);dfs(line.getAnotherPoint(item.point),group2,visted2)})}lines.forEach(line=>line.points.forEach(p2=>pointVirtualGrid.insert(p2,line)));const visted=/* @__PURE__ */new Set,groups=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(visted.has(line))continue;const group2=[line];visted.add(line),dfs(line.start,group2,visted),dfs(line.end,group2,visted),groups.push(group2)}return groups}static groupBySharedPoints(lines){const unionFindSet=new UnionFindSet(lines.length),map=/* @__PURE__ */new Map;for(let i=0;i<lines.length;i++)lines[i].points.forEach(point2=>{const id=point2.hashCode();map.has(id)&&unionFindSet.union(map.get(id),i),map.set(id,i)});return unionFindSet.getAllSets().valueArray.map(list=>list.map(i=>lines[i]))}static groupByLeafPath(lines){PointUtils.adsorb(lines.flatMap(line=>line.points));const paths=[],lud=new LineSegmentUndirectedGraph(lines);let path=[];return lud.forEachPathLine((_start,_end,line,_,endType)=>{path.push(line),"none"!==endType&&(paths.push(path),path=[])}),paths}static groupByParallelToAxis(lines,axisLine,errAngle=1e-9){const parallelLines=[],otherLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];axisLine.isParallelTo(line,errAngle)?parallelLines.push(line):otherLines.push(line)}return[parallelLines,otherLines]}static groupByProjectedOverlap(lines,parallelAxis,verticalAxis,esp=.05,gap=.01,onGroup){esp/=verticalAxis.length,gap/=parallelAxis.length;const vls=lines.map(line=>[verticalAxis.projectPointValue(line.start),line,[parallelAxis.projectPointValue(line.start),parallelAxis.projectPointValue(line.end)].sort((a2,b4)=>a2-b4)]).sort((a2,b4)=>a2[0]-b4[0]),unionFindSet=new UnionFindSet(vls.length);for(let i2=0;i2<vls.length;i2++){const[ipv,_iline,[istart,iend]]=vls[i2];for(let j=i2+1;j<vls.length;j++){const[jpv,_jline,[jstart,jend]]=vls[j];if(jpv-ipv>esp)break;Math.min(iend,jend)-Math.max(istart,jstart)>-gap&&unionFindSet.union(i2,j)}}const map=unionFindSet.getAllSets(),groups=new Array(map.size);let i=0;return map.forEach(list=>{const group2=new Array(list.length),verticalPvList=new Array(list.length),parallelPvList=new Array(list.length);groups[i++]=group2;for(let i2=0;i2<list.length;i2++){const[pv,line,pv2]=vls[list[i2]];group2[i2]=line,verticalPvList[i2]=pv,parallelPvList[i2]=pv2}onGroup?.(group2,verticalPvList,verticalAxis,parallelPvList,parallelAxis)}),groups}static merge(lines,out=new LineSegment){if(1===lines.length)return lines[0];let mainLine=lines[0];for(const l of lines)l.length>mainLine.length&&(mainLine=l);let maxPValue=-1/0,minPValue=1/0,maxPoint=null,minPoint=null;for(let i=0;i<lines.length;i++){const line=lines[i];for(let j=0;j<line.points.length;j++){const p2=line.points[j],pValue=mainLine.projectPointValue(p2);pValue>maxPValue&&(maxPValue=pValue,maxPoint=p2),pValue<minPValue&&(minPValue=pValue,minPoint=p2)}}if(!minPoint||!maxPoint)throw new Error("mergeCollinearSegments: 无效输入");const newStart=minPoint.clone(),newEnd=maxPoint.clone(),fittedLine=out.set(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeLinesByMaxlength(...lines){if(1===lines.length)return lines[0];const baseLine=lines.slice(0).sort((a2,b4)=>b4.length-a2.length)[0],principal=baseLine.direction().normalize();let newStart=baseLine.start.clone(),newEnd=baseLine.end.clone();const getScalar=pt2=>pt2.x*principal.x+pt2.y*principal.y;let minScalar=getScalar(newStart),maxScalar=getScalar(newEnd);for(const line of lines)for(const pt2 of line.points){const scalar=getScalar(pt2);scalar<minScalar&&(minScalar=scalar,newStart=baseLine.projectPoint(pt2,!1)),scalar>maxScalar&&(maxScalar=scalar,newEnd=baseLine.projectPoint(pt2,!1))}const fittedLine=new LineSegment(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeCollinearSegments(lines,out=new LineSegment){if(1===lines.length)return lines[0];let mainLine=lines[0];for(const l of lines)l.length>mainLine.length&&(mainLine=l);let maxPValue=-1/0,minPValue=1/0,maxPoint=null,minPoint=null;for(let i=0;i<lines.length;i++){const line=lines[i];for(let j=0;j<line.points.length;j++){const p2=line.points[j],pValue=mainLine.projectPointValue(p2);pValue>maxPValue&&(maxPValue=pValue,maxPoint=p2),pValue<minPValue&&(minPValue=pValue,minPoint=p2)}}if(!minPoint||!maxPoint)throw new Error("mergeCollinearSegments: 无效输入");const newStart=minPoint.clone(),newEnd=maxPoint.clone(),fittedLine=out.set(newStart,newEnd);return lines.forEach(line=>line.currentData.fittedLine=fittedLine),fittedLine}static mergeParallelSegments(lines,callBack){const groups=this.groupByPathAndParallel(lines),newLines=[],deleteLines=[];return groups.forEach(group2=>{if(group2.length<=1)return;const newLine=this.mergeCollinearSegments(group2);newLine&&(newLines.push(newLine),deleteLines.push(...group2),callBack&&callBack(newLine,group2))}),lines.push(...newLines),{lines:lines.filter(line=>!deleteLines.includes(line)),newLines:newLines,deleteLines:deleteLines}}static mergeCollinearSegmentsAll(lines,callBack,removeLines=/* @__PURE__ */new Set,newLines=[]){const map=/* @__PURE__ */new Map;lines.forEach(line=>line.points.forEach(p2=>{const id=`${p2.X.toFixed(6)}_${p2.Y.toFixed(6)}`;map.has(id)||map.set(id,[]),map.get(id)?.push(line)}));const statistics=/* @__PURE__ */new Map,ids=/* @__PURE__ */new Map;function push(lines2){const id1=ids.get(lines2[0]),id2=ids.get(lines2[1]);let id;if(id1&&id2){id=id1;const list1=statistics.get(id1);[...statistics.get(id2)].forEach(line=>{list1.add(line),ids.set(line,id)})}else id=id1??id2??(16777215*Math.random()).toString(16);statistics.has(id)||statistics.set(id,/* @__PURE__ */new Set);const list=statistics.get(id);lines2.forEach(line=>{ids.set(line,id),list?.add(line)})}for(const list of map.values()){if(2!==list.length)continue;const startLine=list[0],endLine=list[1];startLine.isParallelTo(endLine)&&push(list)}for(const set2 of statistics.values()){const list=[...set2],newLine=this.mergeCollinearSegments(list);callBack&&callBack(newLine,list),list.forEach(line=>removeLines.add(line)),newLines.push(newLine)}return(lines=lines.filter(line=>!removeLines.has(line))).push(...newLines),lines}static deduplicate(lines,opt){const{precision:precision=4,necessaryLines:necessaryLines=[]}=opt??{},scale2=10**precision,seen=/* @__PURE__ */new Set;return necessaryLines.filter(line=>{const a2=`${Math.round(line.start.x*scale2)}_${Math.round(line.start.y*scale2)}`,b4=`${Math.round(line.end.x*scale2)}_${Math.round(line.end.y*scale2)}`,key=a2<b4?`${a2}_${b4}`:`${b4}_${a2}`;seen.add(key)}),lines.filter(line=>{const a2=`${Math.round(line.start.x*scale2)}_${Math.round(line.start.y*scale2)}`,b4=`${Math.round(line.end.x*scale2)}_${Math.round(line.end.y*scale2)}`,key=a2<b4?`${a2}_${b4}`:`${b4}_${a2}`;return!seen.has(key)&&(seen.add(key),!0)})}static clippingByPoints(line,points,callBack){if(!(line instanceof LineSegment))throw new Error("参数1并非线段");let ts2=points.map(p2=>Math.min(1,Math.max(0,line.projectPointValue(p2)))).filter(t2=>!Number.isNaN(t2)).concat([0,1]);ts2=ts2.filter(t2=>t2>=-1e-8&&t2<=1+1e-8),ts2.sort((a2,b4)=>a2-b4);const uniqueTs=[];for(let i=0;i<ts2.length;i++)(0===i||Math.abs(ts2[i]-ts2[i-1])>1e-8)&&uniqueTs.push(ts2[i]);const result=[],newPoints=uniqueTs.map(t2=>line.pointAt(t2));for(let i=0;i<uniqueTs.length-1;i++){const p1=newPoints[i],p2=newPoints[i+1],newLine=line.clone();newLine.set(p1,p2),callBack&&callBack(newLine,line),result.push(newLine)}return result}static clippingByLines(target,clippingLines,callBack){if(0===clippingLines.length)return[target];const eps=1e-6,intervals=clippingLines.map(line=>{const ts2=line.points.map(p2=>target.projectPointValue(p2)).sort((a2,b4)=>a2-b4);return[Math.max(0,ts2[0]),Math.min(1,ts2[1])]}).filter(([s,e])=>e-s>eps).sort((a2,b4)=>a2[0]-b4[0]);if(0===intervals.length)return callBack?.(target.clone(),target),[target];const merged=[];let cur=intervals[0];for(let i=1;i<intervals.length;i++){const next=intervals[i];next[0]<=cur[1]+eps?cur[1]=Math.max(cur[1],next[1]):(merged.push(cur),cur=next)}merged.push(cur);const newLines=[];let prev=0;for(const[s,e]of merged){if(s>prev+eps){const newLine=new LineSegment(target.pointAt(prev),target.pointAt(s));newLine.length>1e-4&&(newLines.push(newLine),callBack?.(newLine,target))}prev=Math.max(prev,e)}if(prev<1-eps){const newLine=new LineSegment(target.pointAt(prev),target.pointAt(1));newLine.length>1e-4&&(newLines.push(newLine),callBack?.(newLine,target))}return newLines}static clippingByLine(target,clippingLine,callBack){return LineSegmentUtils.clippingByLines(target,[clippingLine],callBack)}static constrainLine(line,base){const center=line.center,width=line.length;if(base.length<width)return line.start.copy(base.start),line.end.copy(base.end),line;const hw=.5*width,start=base.start.clone().add(base.end.directionFrom(base.start).multiplyScalar(.5*width)),end=base.end.clone().add(base.start.directionFrom(base.end).multiplyScalar(.5*width)),dir=base.direction(),pl=new LineSegment(start,end);return center.copy(pl.projectPoint(center,!1)),pl.projectPoint(center,!0)||(center.distance(start)<center.distance(end)?center.copy(start):center.copy(end),line.start.copy(center).add(dir.clone().multiplyScalar(-hw)),line.end.copy(center).add(dir.clone().multiplyScalar(hw))),line}static flatPoints(lines){if(lines instanceof LineSegment)return[...lines.points];const points=new Array(2*lines.length);for(let i=0;i<lines.length;i++){const line=lines[i];points[2*i]=line.start,points[2*i+1]=line.end}return points}static splitIntersections(lines,opt){const{onSplit:onSplit,obstacle:obstacle=[]}=opt??{},queryLines=[...lines,...obstacle],lsh=LineSegmentSpatialHash.from(queryLines),queryLine2=new LineSegment,arrayMap=new ArrayMap,obstacleSet=new Set(obstacle);for(let i=0;i<queryLines.length;i++){const line=queryLines[i];queryLine2.copy(line).setLength(line.length+.04),lsh.queryLine(queryLine2).forEach(resLine=>{if(obstacleSet.has(resLine))return;if(line.isSameEndpoint(resLine,1e-4))return;const point2=resLine.getIntersection(line);point2&&arrayMap.append(resLine,point2)})}const newLines=[],removeSet=/* @__PURE__ */new Set;return arrayMap.forEach((points,line)=>{if(points.length){let lines2=LineSegmentUtils.clippingByPoints(line,points);onSplit?.(line,lines2),newLines.push(...lines2),removeSet.add(line)}else newLines.push(line)}),(lines=lines.filter(line=>!removeSet.has(line))).push(...newLines),lines}static findDominantDirectionLine(lineSegments,bin=5){const yAxisLine=new LineSegment(new Point(0,0),new Point(0,1)),lines=[...lineSegments].sort((a2,b4)=>b4.length-a2.length).slice(0,20),angles=lines.map(line2=>{let angle=yAxisLine.angle(line2,{unit:"degree",range:"180"});return angle>90&&(angle=180-angle),Math.round(angle/bin)*bin}),lineMap=/* @__PURE__ */new Map;angles.forEach((angle,index2)=>{lineMap.has(angle)||lineMap.set(angle,[]),lineMap.get(angle)?.push(lines[index2])});const line=[...lineMap.values()].sort((a2,b4)=>b4.length-a2.length)[0]?.sort((a2,b4)=>b4.length-a2.length)[0];return line??new LineSegment}static createModifyManager(){const modifyMap=new MapEnhance;function setPoint(line,point2,value){modifyMap.has(line)||modifyMap.set(line,new ArrayMap);modifyMap.get(line).append(point2,value)}function modify(){modifyMap.forEach((arrayMap,line)=>{arrayMap.forEach((list,point2)=>{const otherPoint=line.getAnotherPoint(point2);list.push(point2),list.sort((p1,p2)=>p2.distance(otherPoint)-p1.distance(otherPoint)),list[0]===point2?point2.copy(list[1]):point2.copy(list[0])})}),modifyMap.clear()}return{get setPoint(){return setPoint},get modify(){return modify},clear(){modifyMap.clear()}}}static dash(line,pattern){const result=[],length=line.length;if(length<=0||0===pattern.length)return result;const dirX=(line.end.x-line.start.x)/length,dirY=(line.end.y-line.start.y)/length;let offset=0,patternIndex=0;for(;offset<length;){const value=pattern[patternIndex%pattern.length],abs=Math.abs(value);if(abs<=0){patternIndex++;continue}const startOffset=offset,endOffset=Math.min(offset+abs,length);if(patternIndex%2==0){const x1=line.start.x+dirX*startOffset,y1=line.start.y+dirY*startOffset,x2=line.start.x+dirX*endOffset,y2=line.start.y+dirY*endOffset;result.push(new LineSegment(new Point(x1,y1),new Point(x2,y2)))}offset=endOffset,patternIndex++}return result}static findBestReferenceSegment(opt){const{lines:lines}=opt,lsh=LineSegmentSpatialHash.from(opt.referenceLines),results=new Array(lines.length);function parallelWeight(angle){return Math.abs(angle-90)/90}for(let i=0;i<lines.length;i++){const line=lines[i],rectangle=line.toRectangle(.5,"butt"),findResult=lsh.queryRectangle(rectangle).filter(quLine=>quLine.isParallelTo(line,20)).sort((l1,l2)=>{const angle1=line.angle(l1,{unit:"degree",range:"180"}),angle2=line.angle(l2,{unit:"degree",range:"180"}),aW1=5*parallelWeight(angle1),aW2=5*parallelWeight(angle2),dist1=line.distanceToSegment(l1),dist2=line.distanceToSegment(l2),maxDist=Math.max(dist1,dist2);return aW2+3*(1-dist2/maxDist)-(aW1+3*(1-dist1/maxDist))});results[i]=findResult.length?findResult[0]:null}return results}static sampleSegment(line,count){let step=1/count;const result=[];for(let i=0;i<=count;i++){const t2=i*step;result.push(line.pointAt(t2))}return result}static sampleSegmentBydistance(line,dist=.001){let count=1/dist;const result=[];for(let i=0;i<=count;i++){const t2=i*dist;result.push(line.pointAt(t2))}return result}static globalPoolArray=new Array;static globalPool=lazy(()=>LineSegmentUtils.createPool());static createPool(pool2=this.globalPoolArray){const usePool=[];return{get line(){const line=pool2.pop()??new LineSegment;return usePool.push(line),line},getUse:()=>[...usePool],free(line){const index2=usePool.indexOf(line);index2<0||(usePool[index2]=usePool[usePool.length-1],usePool.pop(),pool2.push(line))},freeAll(){for(let i=0;i<usePool.length;i++)pool2.push(usePool[i]);usePool.length=0}}}}class Lines extends THREE.LineSegments{geometry=new THREE.BufferGeometry;points=[];pointsObject3D;continuous=!0;constructor(points=[],color=16777215){super(),this.geometry=this.geometry,this.addPoint(...points),this.frustumCulled=!1,this.pointsObject3D=new THREE.Points(this.geometry,new THREE.PointsMaterial({sizeAttenuation:!1,size:10})),this.material=new THREE.LineBasicMaterial({color:color})}addPoint(...points){this.points.push(...points),this.updateGeometry()}addPoints(points){this.points.push(...points),this.updateGeometry()}setPoint(...points){this.points.length=0,this.addPoint(...points)}setPoints(points){this.points.length=0,this.addPoints(points)}setColor(color){return this.material.color instanceof THREE.Color?this.material.color.setHex(color):this.material.color=new THREE.Color(color),this}setOpacity(opacity){return this.material.transparent=!0,this.material.opacity=opacity,this}getCenter(startIndex,endIndex){if(endIndex=endIndex??startIndex,startIndex<=this.points.length-1&&endIndex<=this.points.length-1){const start=this.points[startIndex],end=this.points[endIndex];return start.clone().add(end).multiplyScalar(.5)}throw new Error("索引不在可取范围")}getDistance(startIndex,endIndex){if(endIndex=endIndex??startIndex,startIndex<=this.points.length-1&&endIndex<=this.points.length-1){const start=this.points[startIndex],end=this.points[endIndex];return start.distanceTo(end)}throw new Error("索引不在可取范围")}_timer=null;updateGeometry(){this._timer&&clearTimeout(this._timer),this._timer=setTimeout(()=>{const array=[];if(this.continuous)this.points.forEach((p2,i)=>{if(0===i)return;const p0=this.points[i-1];array.push(p0.x,p0.y,p0.z,p2.x,p2.y,p2.z)});else for(let i=0;i<this.points.length;i+=2){const p0=this.points[i],p2=this.points[i+1];p0&&p2&&array.push(p0.x,p0.y,p0.z,p2.x,p2.y,p2.z)}const position=new THREE.BufferAttribute(new Float32Array(array),3);this.geometry.setAttribute("position",position),this._timer=null,this.dispatchEvent({type:"updateGeometry"})})}}class LineDashed extends Lines{constructor(points,color,dashSize=.02,gapSize=.02){super(points,color),this.material=new THREE.LineDashedMaterial({color:color,dashSize:dashSize,gapSize:gapSize}),this.addEventListener("updateGeometry",()=>{this.computeLineDistances()})}setDashSize(dashSize){this.material.dashSize=dashSize,this.computeLineDistances()}setGapSize(gapSize){this.material.gapSize=gapSize,this.computeLineDistances()}}var factors={centimeters:637100880,centimetres:637100880,degrees:360/(2*Math.PI),feet:20902260.511392,inches:6371008.8*39.37,kilometers:6371.0088,kilometres:6371.0088,meters:6371008.8,metres:6371008.8,miles:3958.761333810546,millimeters:6371008800,millimetres:6371008800,nauticalmiles:6371008.8/1852,radians:1,yards:6371008.8*1.0936};function feature(geom,properties,options={}){const feat={type:"Feature"};return(0===options.id||options.id)&&(feat.id=options.id),options.bbox&&(feat.bbox=options.bbox),feat.properties=properties||{},feat.geometry=geom,feat}function point$1(coordinates,properties,options={}){if(!coordinates)throw new Error("coordinates is required");if(!Array.isArray(coordinates))throw new Error("coordinates must be an Array");if(coordinates.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!isNumber$1(coordinates[0])||!isNumber$1(coordinates[1]))throw new Error("coordinates must contain numbers");return feature({type:"Point",coordinates:coordinates},properties,options)}function polygon$2(coordinates,properties,options={}){for(const ring of coordinates){if(ring.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(ring[ring.length-1].length!==ring[0].length)throw new Error("First and last Position are not equivalent.");for(let j=0;j<ring[ring.length-1].length;j++)if(ring[ring.length-1][j]!==ring[0][j])throw new Error("First and last Position are not equivalent.")}return feature({type:"Polygon",coordinates:coordinates},properties,options)}function radiansToDegrees(radians){return 180*(radians%(2*Math.PI))/Math.PI}function degreesToRadians(degrees){return degrees%360*Math.PI/180}function convertLength(length,originalUnit="kilometers",finalUnit="kilometers"){if(!(length>=0))throw new Error("length must be a positive number");return function(radians,units2="kilometers"){const factor=factors[units2];if(!factor)throw new Error(units2+" units is invalid");return radians*factor}(function(distance2,units2="kilometers"){const factor=factors[units2];if(!factor)throw new Error(units2+" units is invalid");return distance2/factor}(length,originalUnit),finalUnit)}function isNumber$1(num){return!isNaN(num)&&null!==num&&!Array.isArray(num)}function coordEach(geojson,callback,excludeWrapCoord){if(null!==geojson)for(var j,k,l,geometry,stopG,coords,geometryMaybeCollection,isGeometryCollection,wrapShrink=0,coordIndex=0,type=geojson.type,isFeatureCollection="FeatureCollection"===type,isFeature="Feature"===type,stop=isFeatureCollection?geojson.features.length:1,featureIndex=0;featureIndex<stop;featureIndex++){stopG=(isGeometryCollection=!!(geometryMaybeCollection=isFeatureCollection?geojson.features[featureIndex].geometry:isFeature?geojson.geometry:geojson)&&"GeometryCollection"===geometryMaybeCollection.type)?geometryMaybeCollection.geometries.length:1;for(var geomIndex=0;geomIndex<stopG;geomIndex++){var multiFeatureIndex=0,geometryIndex=0;if(null!==(geometry=isGeometryCollection?geometryMaybeCollection.geometries[geomIndex]:geometryMaybeCollection)){coords=geometry.coordinates;var geomType=geometry.type;switch(wrapShrink=!excludeWrapCoord||"Polygon"!==geomType&&"MultiPolygon"!==geomType?0:1,geomType){case null:break;case"Point":if(!1===callback(coords,coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++,multiFeatureIndex++;break;case"LineString":case"MultiPoint":for(j=0;j<coords.length;j++){if(!1===callback(coords[j],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++,"MultiPoint"===geomType&&multiFeatureIndex++}"LineString"===geomType&&multiFeatureIndex++;break;case"Polygon":case"MultiLineString":for(j=0;j<coords.length;j++){for(k=0;k<coords[j].length-wrapShrink;k++){if(!1===callback(coords[j][k],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++}"MultiLineString"===geomType&&multiFeatureIndex++,"Polygon"===geomType&&geometryIndex++}"Polygon"===geomType&&multiFeatureIndex++;break;case"MultiPolygon":for(j=0;j<coords.length;j++){for(geometryIndex=0,k=0;k<coords[j].length;k++){for(l=0;l<coords[j][k].length-wrapShrink;l++){if(!1===callback(coords[j][k][l],coordIndex,featureIndex,multiFeatureIndex,geometryIndex))return!1;coordIndex++}geometryIndex++}multiFeatureIndex++}break;case"GeometryCollection":for(j=0;j<geometry.geometries.length;j++)if(!1===coordEach(geometry.geometries[j],callback,excludeWrapCoord))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function geomReduce(geojson,callback,initialValue){var previousValue=initialValue;return function(geojson,callback){var i,j,g,geometry,stopG,geometryMaybeCollection,isGeometryCollection,featureProperties,featureBBox,featureId,featureIndex=0,isFeatureCollection="FeatureCollection"===geojson.type,isFeature="Feature"===geojson.type,stop=isFeatureCollection?geojson.features.length:1;for(i=0;i<stop;i++){for(geometryMaybeCollection=isFeatureCollection?geojson.features[i].geometry:isFeature?geojson.geometry:geojson,featureProperties=isFeatureCollection?geojson.features[i].properties:isFeature?geojson.properties:{},featureBBox=isFeatureCollection?geojson.features[i].bbox:isFeature?geojson.bbox:void 0,featureId=isFeatureCollection?geojson.features[i].id:isFeature?geojson.id:void 0,stopG=(isGeometryCollection=!!geometryMaybeCollection&&"GeometryCollection"===geometryMaybeCollection.type)?geometryMaybeCollection.geometries.length:1,g=0;g<stopG;g++)if(null!==(geometry=isGeometryCollection?geometryMaybeCollection.geometries[g]:geometryMaybeCollection))switch(geometry.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===callback(geometry,featureIndex,featureProperties,featureBBox,featureId))return!1;break;case"GeometryCollection":for(j=0;j<geometry.geometries.length;j++)if(!1===callback(geometry.geometries[j],featureIndex,featureProperties,featureBBox,featureId))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===callback(null,featureIndex,featureProperties,featureBBox,featureId))return!1;featureIndex++}}(geojson,function(currentGeometry,featureIndex,featureProperties,featureBBox,featureId){previousValue=0===featureIndex&&void 0===initialValue?currentGeometry:callback(previousValue,currentGeometry,featureIndex,featureProperties,featureBBox,featureId)}),previousValue}function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if("function"==typeof f){var a2=function a3(){var isInstance=!1;try{isInstance=this instanceof a3}catch{}return isInstance?Reflect.construct(f,arguments,this.constructor):f.apply(this,arguments)};a2.prototype=f.prototype}else a2={};return Object.defineProperty(a2,"__esModule",{value:!0}),Object.keys(n).forEach(function(k){var d2=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a2,k,d2.get?d2:{enumerable:!0,get:function(){return n[k]}})}),a2}var hasRequiredRbush_min,concaveman$2={exports:{}},rbush_min$1={exports:{}};function requireRbush_min(){return hasRequiredRbush_min?rbush_min$1.exports:(hasRequiredRbush_min=1,rbush_min$1.exports=function(){function t2(t3,r3,e2,a3,h3){!function t4(n2,r4,e3,a4,h4){for(;a4>e3;){if(a4-e3>600){var o2=a4-e3+1,s2=r4-e3+1,l2=Math.log(o2),f2=.5*Math.exp(2*l2/3),u3=.5*Math.sqrt(l2*f2*(o2-f2)/o2)*(s2-o2/2<0?-1:1);t4(n2,r4,Math.max(e3,Math.floor(r4-s2*f2/o2+u3)),Math.min(a4,Math.floor(r4+(o2-s2)*f2/o2+u3)),h4)}var p3=n2[r4],d3=e3,x=a4;for(i(n2,e3,r4),h4(n2[a4],p3)>0&&i(n2,e3,a4);d3<x;){for(i(n2,d3,x),d3++,x--;h4(n2[d3],p3)<0;)d3++;for(;h4(n2[x],p3)>0;)x--}0===h4(n2[e3],p3)?i(n2,e3,x):i(n2,++x,a4),x<=r4&&(e3=x+1),r4<=x&&(a4=x-1)}}(t3,r3,e2||0,a3||t3.length-1,h3||n)}function i(t3,i2,n2){var r3=t3[i2];t3[i2]=t3[n2],t3[n2]=r3}function n(t3,i2){return t3<i2?-1:t3>i2?1:0}var r2=function(t3){void 0===t3&&(t3=9),this._maxEntries=Math.max(4,t3),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function e(t3,i2,n2){if(!n2)return i2.indexOf(t3);for(var r3=0;r3<i2.length;r3++)if(n2(t3,i2[r3]))return r3;return-1}function a2(t3,i2){h2(t3,0,t3.children.length,i2,t3)}function h2(t3,i2,n2,r3,e2){e2||(e2=p2(null)),e2.minX=1/0,e2.minY=1/0,e2.maxX=-1/0,e2.maxY=-1/0;for(var a3=i2;a3<n2;a3++){var h3=t3.children[a3];o(e2,t3.leaf?r3(h3):h3)}return e2}function o(t3,i2){return t3.minX=Math.min(t3.minX,i2.minX),t3.minY=Math.min(t3.minY,i2.minY),t3.maxX=Math.max(t3.maxX,i2.maxX),t3.maxY=Math.max(t3.maxY,i2.maxY),t3}function s(t3,i2){return t3.minX-i2.minX}function l(t3,i2){return t3.minY-i2.minY}function f(t3){return(t3.maxX-t3.minX)*(t3.maxY-t3.minY)}function u2(t3){return t3.maxX-t3.minX+(t3.maxY-t3.minY)}function m(t3,i2){return t3.minX<=i2.minX&&t3.minY<=i2.minY&&i2.maxX<=t3.maxX&&i2.maxY<=t3.maxY}function c(t3,i2){return i2.minX<=t3.maxX&&i2.minY<=t3.maxY&&i2.maxX>=t3.minX&&i2.maxY>=t3.minY}function p2(t3){return{children:t3,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function d2(i2,n2,r3,e2,a3){for(var h3=[n2,r3];h3.length;)if(!((r3=h3.pop())-(n2=h3.pop())<=e2)){var o2=n2+Math.ceil((r3-n2)/e2/2)*e2;t2(i2,o2,n2,r3,a3),h3.push(n2,o2,o2,r3)}}return r2.prototype.all=function(){return this._all(this.data,[])},r2.prototype.search=function(t3){var i2=this.data,n2=[];if(!c(t3,i2))return n2;for(var r3=this.toBBox,e2=[];i2;){for(var a3=0;a3<i2.children.length;a3++){var h3=i2.children[a3],o2=i2.leaf?r3(h3):h3;c(t3,o2)&&(i2.leaf?n2.push(h3):m(t3,o2)?this._all(h3,n2):e2.push(h3))}i2=e2.pop()}return n2},r2.prototype.collides=function(t3){var i2=this.data;if(!c(t3,i2))return!1;for(var n2=[];i2;){for(var r3=0;r3<i2.children.length;r3++){var e2=i2.children[r3],a3=i2.leaf?this.toBBox(e2):e2;if(c(t3,a3)){if(i2.leaf||m(t3,a3))return!0;n2.push(e2)}}i2=n2.pop()}return!1},r2.prototype.load=function(t3){if(!t3||!t3.length)return this;if(t3.length<this._minEntries){for(var i2=0;i2<t3.length;i2++)this.insert(t3[i2]);return this}var n2=this._build(t3.slice(),0,t3.length-1,0);if(this.data.children.length)if(this.data.height===n2.height)this._splitRoot(this.data,n2);else{if(this.data.height<n2.height){var r3=this.data;this.data=n2,n2=r3}this._insert(n2,this.data.height-n2.height-1,!0)}else this.data=n2;return this},r2.prototype.insert=function(t3){return t3&&this._insert(t3,this.data.height-1),this},r2.prototype.clear=function(){return this.data=p2([]),this},r2.prototype.remove=function(t3,i2){if(!t3)return this;for(var n2,r3,a3,h3=this.data,o2=this.toBBox(t3),s2=[],l2=[];h3||s2.length;){if(h3||(h3=s2.pop(),r3=s2[s2.length-1],n2=l2.pop(),a3=!0),h3.leaf){var f2=e(t3,h3.children,i2);if(-1!==f2)return h3.children.splice(f2,1),s2.push(h3),this._condense(s2),this}a3||h3.leaf||!m(h3,o2)?r3?(n2++,h3=r3.children[n2],a3=!1):h3=null:(s2.push(h3),l2.push(n2),n2=0,r3=h3,h3=h3.children[0])}return this},r2.prototype.toBBox=function(t3){return t3},r2.prototype.compareMinX=function(t3,i2){return t3.minX-i2.minX},r2.prototype.compareMinY=function(t3,i2){return t3.minY-i2.minY},r2.prototype.toJSON=function(){return this.data},r2.prototype.fromJSON=function(t3){return this.data=t3,this},r2.prototype._all=function(t3,i2){for(var n2=[];t3;)t3.leaf?i2.push.apply(i2,t3.children):n2.push.apply(n2,t3.children),t3=n2.pop();return i2},r2.prototype._build=function(t3,i2,n2,r3){var e2,h3=n2-i2+1,o2=this._maxEntries;if(h3<=o2)return a2(e2=p2(t3.slice(i2,n2+1)),this.toBBox),e2;r3||(r3=Math.ceil(Math.log(h3)/Math.log(o2)),o2=Math.ceil(h3/Math.pow(o2,r3-1))),(e2=p2([])).leaf=!1,e2.height=r3;var s2=Math.ceil(h3/o2),l2=s2*Math.ceil(Math.sqrt(o2));d2(t3,i2,n2,l2,this.compareMinX);for(var f2=i2;f2<=n2;f2+=l2){var u3=Math.min(f2+l2-1,n2);d2(t3,f2,u3,s2,this.compareMinY);for(var m2=f2;m2<=u3;m2+=s2){var c3=Math.min(m2+s2-1,u3);e2.children.push(this._build(t3,m2,c3,r3-1))}}return a2(e2,this.toBBox),e2},r2.prototype._chooseSubtree=function(t3,i2,n2,r3){for(;r3.push(i2),!i2.leaf&&r3.length-1!==n2;){for(var e2=1/0,a3=1/0,h3=void 0,o2=0;o2<i2.children.length;o2++){var s2=i2.children[o2],l2=f(s2),u3=(m2=t3,c3=s2,(Math.max(c3.maxX,m2.maxX)-Math.min(c3.minX,m2.minX))*(Math.max(c3.maxY,m2.maxY)-Math.min(c3.minY,m2.minY))-l2);u3<a3?(a3=u3,e2=l2<e2?l2:e2,h3=s2):u3===a3&&l2<e2&&(e2=l2,h3=s2)}i2=h3||i2.children[0]}var m2,c3;return i2},r2.prototype._insert=function(t3,i2,n2){var r3=n2?t3:this.toBBox(t3),e2=[],a3=this._chooseSubtree(r3,this.data,i2,e2);for(a3.children.push(t3),o(a3,r3);i2>=0&&e2[i2].children.length>this._maxEntries;)this._split(e2,i2),i2--;this._adjustParentBBoxes(r3,e2,i2)},r2.prototype._split=function(t3,i2){var n2=t3[i2],r3=n2.children.length,e2=this._minEntries;this._chooseSplitAxis(n2,e2,r3);var h3=this._chooseSplitIndex(n2,e2,r3),o2=p2(n2.children.splice(h3,n2.children.length-h3));o2.height=n2.height,o2.leaf=n2.leaf,a2(n2,this.toBBox),a2(o2,this.toBBox),i2?t3[i2-1].children.push(o2):this._splitRoot(n2,o2)},r2.prototype._splitRoot=function(t3,i2){this.data=p2([t3,i2]),this.data.height=t3.height+1,this.data.leaf=!1,a2(this.data,this.toBBox)},r2.prototype._chooseSplitIndex=function(t3,i2,n2){for(var r3,e2,a3,o2,s2,l2,u3,m2=1/0,c3=1/0,p3=i2;p3<=n2-i2;p3++){var d3=h2(t3,0,p3,this.toBBox),x=h2(t3,p3,n2,this.toBBox),v2=(e2=d3,a3=x,o2=void 0,s2=void 0,l2=void 0,u3=void 0,o2=Math.max(e2.minX,a3.minX),s2=Math.max(e2.minY,a3.minY),l2=Math.min(e2.maxX,a3.maxX),u3=Math.min(e2.maxY,a3.maxY),Math.max(0,l2-o2)*Math.max(0,u3-s2)),M=f(d3)+f(x);v2<m2?(m2=v2,r3=p3,c3=M<c3?M:c3):v2===m2&&M<c3&&(c3=M,r3=p3)}return r3||n2-i2},r2.prototype._chooseSplitAxis=function(t3,i2,n2){var r3=t3.leaf?this.compareMinX:s,e2=t3.leaf?this.compareMinY:l;this._allDistMargin(t3,i2,n2,r3)<this._allDistMargin(t3,i2,n2,e2)&&t3.children.sort(r3)},r2.prototype._allDistMargin=function(t3,i2,n2,r3){t3.children.sort(r3);for(var e2=this.toBBox,a3=h2(t3,0,i2,e2),s2=h2(t3,n2-i2,n2,e2),l2=u2(a3)+u2(s2),f2=i2;f2<n2-i2;f2++){var m2=t3.children[f2];o(a3,t3.leaf?e2(m2):m2),l2+=u2(a3)}for(var c3=n2-i2-1;c3>=i2;c3--){var p3=t3.children[c3];o(s2,t3.leaf?e2(p3):p3),l2+=u2(s2)}return l2},r2.prototype._adjustParentBBoxes=function(t3,i2,n2){for(var r3=n2;r3>=0;r3--)o(i2[r3],t3)},r2.prototype._condense=function(t3){for(var i2=t3.length-1,n2=void 0;i2>=0;i2--)0===t3[i2].children.length?i2>0?(n2=t3[i2-1].children).splice(n2.indexOf(t3[i2]),1):this.clear():a2(t3[i2],this.toBBox)},r2}())}function defaultCompare$1(a2,b4){return a2<b4?-1:a2>b4?1:0}const require$$1=/* @__PURE__ */getAugmentedNamespace(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(data=[],compare=defaultCompare$1){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return this.length--,this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos<halfLength;){let left=1+(pos<<1),best=data[left];const right=left+1;if(right<this.length&&compare(data[right],best)<0&&(left=right,best=data[right]),compare(best,item)>=0)break;data[pos]=best,pos=left}data[pos]=item}}},Symbol.toStringTag,{value:"Module"})));var flat,hasRequiredFlat,nested,hasRequiredNested,hasRequiredPointInPolygon,pointInPolygon$1={exports:{}};function requirePointInPolygon(){if(hasRequiredPointInPolygon)return pointInPolygon$1.exports;hasRequiredPointInPolygon=1;var pointInPolygonFlat=hasRequiredFlat?flat:(hasRequiredFlat=1,flat=function(point2,vs2,start,end){var x=point2[0],y=point2[1],inside2=!1;void 0===start&&(start=0),void 0===end&&(end=vs2.length);for(var len=(end-start)/2,i=0,j=len-1;i<len;j=i++){var xi2=vs2[start+2*i+0],yi2=vs2[start+2*i+1],xj=vs2[start+2*j+0],yj=vs2[start+2*j+1];yi2>y!=yj>y&&x<(xj-xi2)*(y-yi2)/(yj-yi2)+xi2&&(inside2=!inside2)}return inside2}),pointInPolygonNested=hasRequiredNested?nested:(hasRequiredNested=1,nested=function(point2,vs2,start,end){var x=point2[0],y=point2[1],inside2=!1;void 0===start&&(start=0),void 0===end&&(end=vs2.length);for(var len=end-start,i=0,j=len-1;i<len;j=i++){var xi2=vs2[i+start][0],yi2=vs2[i+start][1],xj=vs2[j+start][0],yj=vs2[j+start][1];yi2>y!=yj>y&&x<(xj-xi2)*(y-yi2)/(yj-yi2)+xi2&&(inside2=!inside2)}return inside2});return pointInPolygon$1.exports=function(point2,vs2,start,end){return vs2.length>0&&Array.isArray(vs2[0])?pointInPolygonNested(point2,vs2,start,end):pointInPolygonFlat(point2,vs2,start,end)},pointInPolygon$1.exports.nested=pointInPolygonNested,pointInPolygon$1.exports.flat=pointInPolygonFlat,pointInPolygon$1.exports}var hasRequiredOrient2d_min,hasRequiredConcaveman,orient2d_min$1={exports:{}};function requireOrient2d_min(){return hasRequiredOrient2d_min||(hasRequiredOrient2d_min=1,function(t2){const e=134217729,n=33306690738754706e-32;function r2(t3,e2,n2,r3,o2){let f2,i2,u3,c3,s2=e2[0],a3=r3[0],d3=0,l2=0;a3>s2==a3>-s2?(f2=s2,s2=e2[++d3]):(f2=a3,a3=r3[++l2]);let p2=0;if(d3<t3&&l2<n2)for(a3>s2==a3>-s2?(u3=f2-((i2=s2+f2)-s2),s2=e2[++d3]):(u3=f2-((i2=a3+f2)-a3),a3=r3[++l2]),f2=i2,0!==u3&&(o2[p2++]=u3);d3<t3&&l2<n2;)a3>s2==a3>-s2?(u3=f2-((i2=f2+s2)-(c3=i2-f2))+(s2-c3),s2=e2[++d3]):(u3=f2-((i2=f2+a3)-(c3=i2-f2))+(a3-c3),a3=r3[++l2]),f2=i2,0!==u3&&(o2[p2++]=u3);for(;d3<t3;)u3=f2-((i2=f2+s2)-(c3=i2-f2))+(s2-c3),s2=e2[++d3],f2=i2,0!==u3&&(o2[p2++]=u3);for(;l2<n2;)u3=f2-((i2=f2+a3)-(c3=i2-f2))+(a3-c3),a3=r3[++l2],f2=i2,0!==u3&&(o2[p2++]=u3);return 0===f2&&0!==p2||(o2[p2++]=f2),p2}function o(t3){return new Float64Array(t3)}const f=33306690738754716e-32,i=22204460492503146e-32,u2=11093356479670487e-47,c=o(4),s=o(8),a2=o(12),d2=o(16),l=o(4);t2.orient2d=function(t3,o2,p2,b4,y,h2){const M=(o2-h2)*(p2-y),x=(t3-y)*(b4-h2),j=M-x;if(0===M||0===x||M>0!=x>0)return j;const m=Math.abs(M+x);return Math.abs(j)>=f*m?j:-function(t4,o3,f2,p3,b5,y2,h3){let M2,x2,j2,m2,_,v2,w,A,F,O2,P,g,k,q,z,B2,C,D2;const E=t4-b5,G=f2-b5,H2=o3-y2,I=p3-y2;_=(z=(A=E-(w=(v2=e*E)-(v2-E)))*(O2=I-(F=(v2=e*I)-(v2-I)))-((q=E*I)-w*F-A*F-w*O2))-(P=z-(C=(A=H2-(w=(v2=e*H2)-(v2-H2)))*(O2=G-(F=(v2=e*G)-(v2-G)))-((B2=H2*G)-w*F-A*F-w*O2))),c[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),c[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,c[2]=g-(D2-_)+(P-_),c[3]=D2;let J=function(t5,e2){let n2=e2[0];for(let r3=1;r3<t5;r3++)n2+=e2[r3];return n2}(4,c),K2=i*h3;if(J>=K2||-J>=K2)return J;if(M2=t4-(E+(_=t4-E))+(_-b5),j2=f2-(G+(_=f2-G))+(_-b5),x2=o3-(H2+(_=o3-H2))+(_-y2),m2=p3-(I+(_=p3-I))+(_-y2),0===M2&&0===x2&&0===j2&&0===m2)return J;if(K2=u2*h3+n*Math.abs(J),(J+=E*m2+I*M2-(H2*j2+G*x2))>=K2||-J>=K2)return J;_=(z=(A=M2-(w=(v2=e*M2)-(v2-M2)))*(O2=I-(F=(v2=e*I)-(v2-I)))-((q=M2*I)-w*F-A*F-w*O2))-(P=z-(C=(A=x2-(w=(v2=e*x2)-(v2-x2)))*(O2=G-(F=(v2=e*G)-(v2-G)))-((B2=x2*G)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const L=r2(4,c,4,l,s);_=(z=(A=E-(w=(v2=e*E)-(v2-E)))*(O2=m2-(F=(v2=e*m2)-(v2-m2)))-((q=E*m2)-w*F-A*F-w*O2))-(P=z-(C=(A=H2-(w=(v2=e*H2)-(v2-H2)))*(O2=j2-(F=(v2=e*j2)-(v2-j2)))-((B2=H2*j2)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const N=r2(L,s,4,l,a2);_=(z=(A=M2-(w=(v2=e*M2)-(v2-M2)))*(O2=m2-(F=(v2=e*m2)-(v2-m2)))-((q=M2*m2)-w*F-A*F-w*O2))-(P=z-(C=(A=x2-(w=(v2=e*x2)-(v2-x2)))*(O2=j2-(F=(v2=e*j2)-(v2-j2)))-((B2=x2*j2)-w*F-A*F-w*O2))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B2),l[1]=k-(P+_)+(_-B2),_=(D2=g+P)-g,l[2]=g-(D2-_)+(P-_),l[3]=D2;const Q2=r2(N,a2,4,l,d2);return d2[Q2-1]}(t3,o2,p2,b4,y,h2,m)},t2.orient2dfast=function(t3,e2,n2,r3,o2,f2){return(e2-f2)*(n2-o2)-(t3-o2)*(r3-f2)},Object.defineProperty(t2,"__esModule",{value:!0})}(orient2d_min$1.exports)),orient2d_min$1.exports}const concaveman$1=/* @__PURE__ */getDefaultExportFromCjs(function(){if(hasRequiredConcaveman)return concaveman$2.exports;hasRequiredConcaveman=1;var RBush2=requireRbush_min(),Queue=require$$1,pointInPolygon2=requirePointInPolygon(),orient=requireOrient2d_min().orient2d;function concaveman2(points,concavity,lengthThreshold){concavity=Math.max(0,void 0===concavity?2:concavity),lengthThreshold=lengthThreshold||0;var hull=function(points){for(var left=points[0],top=points[0],right=points[0],bottom=points[0],i=0;i<points.length;i++){var p2=points[i];p2[0]<left[0]&&(left=p2),p2[0]>right[0]&&(right=p2),p2[1]<top[1]&&(top=p2),p2[1]>bottom[1]&&(bottom=p2)}var cull2=[left,top,right,bottom],filtered=cull2.slice();for(i=0;i<points.length;i++)pointInPolygon2(points[i],cull2)||filtered.push(points[i]);return function(points){points.sort(compareByX2);for(var lower=[],i=0;i<points.length;i++){for(;lower.length>=2&&cross2(lower[lower.length-2],lower[lower.length-1],points[i])<=0;)lower.pop();lower.push(points[i])}for(var upper=[],ii2=points.length-1;ii2>=0;ii2--){for(;upper.length>=2&&cross2(upper[upper.length-2],upper[upper.length-1],points[ii2])<=0;)upper.pop();upper.push(points[ii2])}return upper.pop(),lower.pop(),lower.concat(upper)}(filtered)}(points),tree=new RBush2(16);tree.toBBox=function(a3){return{minX:a3[0],minY:a3[1],maxX:a3[0],maxY:a3[1]}},tree.compareMinX=function(a3,b5){return a3[0]-b5[0]},tree.compareMinY=function(a3,b5){return a3[1]-b5[1]},tree.load(points);for(var last,queue=[],i=0;i<hull.length;i++){var p2=hull[i];tree.remove(p2),last=insertNode2(p2,last),queue.push(last)}var segTree=new RBush2(16);for(i=0;i<queue.length;i++)segTree.insert(updateBBox2(queue[i]));for(var sqConcavity=concavity*concavity,sqLenThreshold=lengthThreshold*lengthThreshold;queue.length;){var node=queue.shift(),a2=node.p,b4=node.next.p,sqLen=getSqDist2(a2,b4);if(!(sqLen<sqLenThreshold)){var maxSqLen=sqLen/sqConcavity;(p2=findCandidate2(tree,node.prev.p,a2,b4,node.next.next.p,maxSqLen,segTree))&&Math.min(getSqDist2(p2,a2),getSqDist2(p2,b4))<=maxSqLen&&(queue.push(node),queue.push(insertNode2(p2,node)),tree.remove(p2),segTree.remove(node),segTree.insert(updateBBox2(node)),segTree.insert(updateBBox2(node.next)))}}node=last;var concave=[];do{concave.push(node.p),node=node.next}while(node!==last);return concave.push(node.p),concave}function findCandidate2(tree,a2,b4,c,d2,maxDist,segTree){for(var queue=new Queue([],compareDist2),node=tree.data;node;){for(var i=0;i<node.children.length;i++){var child=node.children[i],dist=node.leaf?sqSegDist2(child,b4,c):sqSegBoxDist2(b4,c,child);dist>maxDist||queue.push({node:child,dist:dist})}for(;queue.length&&!queue.peek().node.children;){var item=queue.pop(),p2=item.node,d0=sqSegDist2(p2,a2,b4),d1=sqSegDist2(p2,c,d2);if(item.dist<d0&&item.dist<d1&&noIntersections2(b4,p2,segTree)&&noIntersections2(c,p2,segTree))return p2}(node=queue.pop())&&(node=node.node)}return null}function compareDist2(a2,b4){return a2.dist-b4.dist}function sqSegBoxDist2(a2,b4,bbox2){if(inside2(a2,bbox2)||inside2(b4,bbox2))return 0;var d1=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.maxX,bbox2.minY);if(0===d1)return 0;var d2=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.minX,bbox2.maxY);if(0===d2)return 0;var d3=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.maxX,bbox2.minY,bbox2.maxX,bbox2.maxY);if(0===d3)return 0;var d4=sqSegSegDist2(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.maxY,bbox2.maxX,bbox2.maxY);return 0===d4?0:Math.min(d1,d2,d3,d4)}function inside2(a2,bbox2){return a2[0]>=bbox2.minX&&a2[0]<=bbox2.maxX&&a2[1]>=bbox2.minY&&a2[1]<=bbox2.maxY}function noIntersections2(a2,b4,segTree){for(var minX=Math.min(a2[0],b4[0]),minY=Math.min(a2[1],b4[1]),maxX=Math.max(a2[0],b4[0]),maxY=Math.max(a2[1],b4[1]),edges=segTree.search({minX:minX,minY:minY,maxX:maxX,maxY:maxY}),i=0;i<edges.length;i++)if(intersects2(edges[i].p,edges[i].next.p,a2,b4))return!1;return!0}function cross2(p1,p2,p3){return orient(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1])}function intersects2(p1,q1,p2,q2){return p1!==q2&&q1!==p2&&cross2(p1,q1,p2)>0!=cross2(p1,q1,q2)>0&&cross2(p2,q2,p1)>0!=cross2(p2,q2,q1)>0}function updateBBox2(node){var p1=node.p,p2=node.next.p;return node.minX=Math.min(p1[0],p2[0]),node.minY=Math.min(p1[1],p2[1]),node.maxX=Math.max(p1[0],p2[0]),node.maxY=Math.max(p1[1],p2[1]),node}function insertNode2(p2,prev){var node={p:p2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return prev?(node.next=prev.next,node.prev=prev,prev.next.prev=node,prev.next=node):(node.prev=node,node.next=node),node}function getSqDist2(p1,p2){var dx=p1[0]-p2[0],dy=p1[1]-p2[1];return dx*dx+dy*dy}function sqSegDist2(p2,p1,p22){var x=p1[0],y=p1[1],dx=p22[0]-x,dy=p22[1]-y;if(0!==dx||0!==dy){var t2=((p2[0]-x)*dx+(p2[1]-y)*dy)/(dx*dx+dy*dy);t2>1?(x=p22[0],y=p22[1]):t2>0&&(x+=dx*t2,y+=dy*t2)}return(dx=p2[0]-x)*dx+(dy=p2[1]-y)*dy}function sqSegSegDist2(x0,y0,x1,y1,x2,y2,x3,y3){var sc,sN,tc,tN,ux=x1-x0,uy=y1-y0,vx=x3-x2,vy=y3-y2,wx=x0-x2,wy=y0-y2,a2=ux*ux+uy*uy,b4=ux*vx+uy*vy,c=vx*vx+vy*vy,d2=ux*wx+uy*wy,e=vx*wx+vy*wy,D2=a2*c-b4*b4,sD=D2,tD=D2;0===D2?(sN=0,sD=1,tN=e,tD=c):(tN=a2*e-b4*d2,(sN=b4*e-c*d2)<0?(sN=0,tN=e,tD=c):sN>sD&&(sN=sD,tN=e+b4,tD=c)),tN<0?(tN=0,-d2<0?sN=0:-d2>a2?sN=sD:(sN=-d2,sD=a2)):tN>tD&&(tN=tD,-d2+b4<0?sN=0:-d2+b4>a2?sN=sD:(sN=-d2+b4,sD=a2));var dx=(1-(tc=0===tN?0:tN/tD))*x2+tc*x3-((1-(sc=0===sN?0:sN/sD))*x0+sc*x1),dy=(1-tc)*y2+tc*y3-((1-sc)*y0+sc*y1);return dx*dx+dy*dy}function compareByX2(a2,b4){return a2[0]===b4[0]?a2[1]-b4[1]:a2[0]-b4[0]}return Queue.default&&(Queue=Queue.default),concaveman$2.exports=concaveman2,concaveman$2.exports.default=concaveman2,concaveman$2.exports}());function centroid(geojson,options={}){let xSum=0,ySum=0,len=0;return coordEach(geojson,function(coord){xSum+=coord[0],ySum+=coord[1],len++},!0),point$1([xSum/len,ySum/len],options.properties)}function getCoord(coord){if(!coord)throw new Error("coord is required");if(!Array.isArray(coord)){if("Feature"===coord.type&&null!==coord.geometry&&"Point"===coord.geometry.type)return[...coord.geometry.coordinates];if("Point"===coord.type)return[...coord.coordinates]}if(Array.isArray(coord)&&coord.length>=2&&!Array.isArray(coord[0])&&!Array.isArray(coord[1]))return[...coord];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function calculateRhumbBearing(from,to2){const phi1=degreesToRadians(from[1]),phi2=degreesToRadians(to2[1]);let deltaLambda=degreesToRadians(to2[0]-from[0]);deltaLambda>Math.PI&&(deltaLambda-=2*Math.PI),deltaLambda<-Math.PI&&(deltaLambda+=2*Math.PI);const deltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4));return(radiansToDegrees(Math.atan2(deltaLambda,deltaPsi))+360)%360}function rhumbDistance(from,to2,options={}){const origin=getCoord(from),destination=getCoord(to2);destination[0]+=destination[0]-origin[0]>180?-360:origin[0]-destination[0]>180?360:0;const distanceInMeters=function(origin,destination,radius){const R2=radius=void 0===radius?6371008.8:Number(radius),phi1=origin[1]*Math.PI/180,phi2=destination[1]*Math.PI/180,DeltaPhi=phi2-phi1;let DeltaLambda=Math.abs(destination[0]-origin[0])*Math.PI/180;DeltaLambda>Math.PI&&(DeltaLambda-=2*Math.PI);const DeltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4)),q=Math.abs(DeltaPsi)>1e-11?DeltaPhi/DeltaPsi:Math.cos(phi1),delta2=Math.sqrt(DeltaPhi*DeltaPhi+q*q*DeltaLambda*DeltaLambda);return delta2*R2}(origin,destination);return convertLength(distanceInMeters,"meters",options.units)}function rhumbDestination(origin,distance2,bearing2,options={}){const wasNegativeDistance=distance2<0;let distanceInMeters=convertLength(Math.abs(distance2),options.units,"meters");wasNegativeDistance&&(distanceInMeters=-Math.abs(distanceInMeters));const coords=getCoord(origin),destination=function(origin,distance2,bearing2,radius){radius=void 0===radius?6371008.8:Number(radius);const delta2=distance2/radius,lambda1=origin[0]*Math.PI/180,phi1=degreesToRadians(origin[1]),theta=degreesToRadians(bearing2),DeltaPhi=delta2*Math.cos(theta);let phi2=phi1+DeltaPhi;Math.abs(phi2)>Math.PI/2&&(phi2=phi2>0?Math.PI-phi2:-Math.PI-phi2);const DeltaPsi=Math.log(Math.tan(phi2/2+Math.PI/4)/Math.tan(phi1/2+Math.PI/4)),q=Math.abs(DeltaPsi)>1e-11?DeltaPhi/DeltaPsi:Math.cos(phi1),DeltaLambda=delta2*Math.sin(theta)/q;return[(180*(lambda1+DeltaLambda)/Math.PI+540)%360-180,180*phi2/Math.PI]}(coords,distanceInMeters,bearing2);return destination[0]+=destination[0]-coords[0]>180?-360:coords[0]-destination[0]>180?360:0,point$1(destination,options.properties)}function clone(geojson){if(!geojson)throw new Error("geojson is required");switch(geojson.type){case"Feature":return cloneFeature(geojson);case"FeatureCollection":return function(geojson){const cloned={type:"FeatureCollection"};return Object.keys(geojson).forEach(key=>{switch(key){case"type":case"features":return;default:cloned[key]=geojson[key]}}),cloned.features=geojson.features.map(feature2=>cloneFeature(feature2)),cloned}(geojson);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return cloneGeometry(geojson);default:throw new Error("unknown GeoJSON type")}}function cloneFeature(geojson){const cloned={type:"Feature"};return Object.keys(geojson).forEach(key=>{switch(key){case"type":case"properties":case"geometry":return;default:cloned[key]=geojson[key]}}),cloned.properties=cloneProperties(geojson.properties),null==geojson.geometry?cloned.geometry=null:cloned.geometry=cloneGeometry(geojson.geometry),cloned}function cloneProperties(properties){const cloned={};return properties?(Object.keys(properties).forEach(key=>{const value=properties[key];"object"==typeof value?null===value?cloned[key]=null:Array.isArray(value)?cloned[key]=value.map(item=>item):cloned[key]=cloneProperties(value):cloned[key]=value}),cloned):cloned}function cloneGeometry(geometry){const geom={type:geometry.type};return geometry.bbox&&(geom.bbox=geometry.bbox),"GeometryCollection"===geometry.type?(geom.geometries=geometry.geometries.map(g=>cloneGeometry(g)),geom):(geom.coordinates=deepSlice(geometry.coordinates),geom)}function deepSlice(coords){const cloned=coords;return"object"!=typeof cloned[0]?cloned.slice():cloned.map(coord=>deepSlice(coord))}function transformRotate(geojson,angle,options){if(null===(input=options=options||{})||"object"!=typeof input||Array.isArray(input))throw new Error("options is invalid");var input;const pivot=options.pivot,mutate=options.mutate;if(!geojson)throw new Error("geojson is required");if(null==angle||isNaN(angle))throw new Error("angle is required");if(0===angle)return geojson;const pivotCoord=null!=pivot?pivot:centroid(geojson);return!1!==mutate&&void 0!==mutate||(geojson=clone(geojson)),coordEach(geojson,function(pointCoords){const initialAngle=function(start,end,options={}){let bear360;return bear360=options.final?calculateRhumbBearing(getCoord(end),getCoord(start)):calculateRhumbBearing(getCoord(start),getCoord(end)),bear360>180?-(360-bear360):bear360}(pivotCoord,pointCoords),finalAngle=initialAngle+angle,distance2=rhumbDistance(pivotCoord,pointCoords),newCoords=function(coords){if(Array.isArray(coords))return coords;if("Feature"===coords.type){if(null!==coords.geometry)return coords.geometry.coordinates}else if(coords.coordinates)return coords.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}(rhumbDestination(pivotCoord,distance2,finalAngle));pointCoords[0]=newCoords[0],pointCoords[1]=newCoords[1]}),geojson}function bearing(start,end,options={}){if(!0===options.final)return function(start,end){let bear=bearing(end,start);return bear=(bear+180)%360,bear}(start,end);const coordinates1=getCoord(start),coordinates2=getCoord(end),lon1=degreesToRadians(coordinates1[0]),lon2=degreesToRadians(coordinates2[0]),lat1=degreesToRadians(coordinates1[1]),lat2=degreesToRadians(coordinates2[1]),a2=Math.sin(lon2-lon1)*Math.cos(lat2),b4=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1);return radiansToDegrees(Math.atan2(a2,b4))}function envelope(geojson){return function(bbox2,options={}){const west=Number(bbox2[0]),south=Number(bbox2[1]),east=Number(bbox2[2]),north=Number(bbox2[3]);if(6===bbox2.length)throw new Error("@turf/bbox-polygon does not support BBox with 6 positions");const lowLeft=[west,south];return polygon$2([[lowLeft,[east,south],[east,north],[west,north],lowLeft]],options.properties,{bbox:bbox2,id:options.id})}(function(geojson,options={}){if(null!=geojson.bbox&&!0!==options.recompute)return geojson.bbox;const result=[1/0,1/0,-1/0,-1/0];return coordEach(geojson,coord=>{result[0]>coord[0]&&(result[0]=coord[0]),result[1]>coord[1]&&(result[1]=coord[1]),result[2]<coord[0]&&(result[2]=coord[0]),result[3]<coord[1]&&(result[3]=coord[1])}),result}(geojson))}function area$1(geojson){return geomReduce(geojson,(value,geom)=>value+function(geom){let i,total=0;switch(geom.type){case"Polygon":return polygonArea(geom.coordinates);case"MultiPolygon":for(i=0;i<geom.coordinates.length;i++)total+=polygonArea(geom.coordinates[i]);return total;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}(geom),0)}function polygonArea(coords){let total=0;if(coords&&coords.length>0){total+=Math.abs(ringArea(coords[0]));for(let i=1;i<coords.length;i++)total-=Math.abs(ringArea(coords[i]))}return total}var FACTOR=20294876564838.72,PI_OVER_180=Math.PI/180;function ringArea(coords){const coordsLength=coords.length-1;if(coordsLength<=2)return 0;let total=0,i=0;for(;i<coordsLength;){const lower=coords[i],middle=coords[i+1===coordsLength?0:i+1],upper=coords[i+2>=coordsLength?(i+2)%coordsLength:i+2],lowerX=lower[0]*PI_OVER_180,middleY=middle[1]*PI_OVER_180;total+=(upper[0]*PI_OVER_180-lowerX)*Math.sin(middleY),i++}return total*FACTOR}function smallestSurroundingRectangleByArea(geoJsonInput){const convexHull2=function(geojson,options={}){options.concavity=options.concavity||1/0;const points=[];if(coordEach(geojson,coord=>{points.push([coord[0],coord[1]])}),!points.length)return null;const convexHull2=concaveman$1(points,options.concavity);return convexHull2.length>3?polygon$2([convexHull2]):null}(geoJsonInput);if(!convexHull2)throw new Error("Can't calculate smallestSurroundingRectangleByArea for given geometry");const centroidCoords=centroid(convexHull2),allHullCoords=(coords=[],coordEach(convexHull2,function(coord){coords.push(coord)}),coords);var coords;let minArea=Number.MAX_SAFE_INTEGER,resultPolygon=null;for(let index2=0;index2<allHullCoords.length-1;index2++){let angle=bearing(allHullCoords[index2],allHullCoords[index2+1]),envelopeOfHull=envelope(transformRotate(convexHull2,-1*angle,{pivot:centroidCoords})),envelopeArea=area$1(envelopeOfHull);envelopeArea<minArea&&(minArea=envelopeArea,resultPolygon=transformRotate(envelopeOfHull,angle,{pivot:centroidCoords}))}return resultPolygon}class Polygon extends Array{[Symbol.iterator](){return super[Symbol.iterator]()}constructor(points=[]){Array.isArray(points)?(super(),this.set(points)):super(points)}set(points=[]){this.length=0,points.forEach(p2=>this.push(p2))}getCenter(out=new Point){const len=this.length;if(0===len)return out.set(0,0);let area2=0,centerX=0,centerY=0;for(let i=0;i<len;i++){const p1=this[i],p2=this[(i+1)%len],cross2=p1.x*p2.y-p2.x*p1.y;area2+=cross2,centerX+=(p1.x+p2.x)*cross2,centerY+=(p1.y+p2.y)*cross2}if(area2*=.5,Math.abs(area2)<1e-9){let sumX=0,sumY=0;for(let i=0;i<len;i++)sumX+=this[i].x,sumY+=this[i].y;const inv=1/len;return out.set(sumX*inv,sumY*inv)}const factor=1/(6*area2);return out.set(centerX*factor,centerY*factor)}getPathCenter(out=new Point){if(0===this.length)return null;if(1===this.length)return out.x=this[0].x,out.y=this[0].y,out;let len=0;const distList=[];for(let i=1;i<this.length;i++){const p0=this[i-1],p1=this[i];len+=p0.distance(p1),distList.push(len)}const target=.5*len,index2=distList.findIndex(v2=>v2>=target);if(index2>-1){const p0=this[index2],p1=this[index2+1],start=index2>0?distList[index2-1]:0,t2=(target-start)/(distList[index2]-start);return p0.lerp(p1,t2,out)}const p2=this[this.length-1];return out.x=p2.x,out.y=p2.y,out}getBox2(){if(0===this.length)return new Box2;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(const p2 of this)p2.x<minX&&(minX=p2.x),p2.y<minY&&(minY=p2.y),p2.x>maxX&&(maxX=p2.x),p2.y>maxY&&(maxY=p2.y);return new Box2(minX,maxX,minY,maxY)}getMinimumBoundingRectangle(polygon2=new Polygon){if(this.length<3)return null;const result=smallestSurroundingRectangleByArea({type:"Polygon",coordinates:[this.toArrays()]});if(!result)return null;const rectangle=result.geometry.coordinates[0];return polygon2.set(rectangle.map(arr=>Point.from(arr))),polygon2}area(signed=!1){if(this.length<3)return 0;let area2=0;const n=this.length;for(let i=0;i<n;i++){const j=(i+1)%n;area2+=this[i].x*this[j].y,area2-=this[j].x*this[i].y}return signed?area2/2:Math.abs(area2)/2}signedArea(){return this.area(!0)}closedLoop(){if(this.length<2)return!1;const first=this[0],last=this[this.length-1];return first.equal(last)}closedExpansion(width,scale2=100){if(this.length<3)return null;const inv=1/scale2,path=this.clone().scale(scale2).round(),co2=new ClipperLib.ClipperOffset(2,.25*scale2);co2.AddPath(path,ClipperLib.JoinType.jtMiter,ClipperLib.EndType.etClosedPolygon);const solution=[];if(co2.Execute(solution,width*scale2),!solution.length)return null;const result=solution[0].map(p2=>new Point(p2.X*inv,p2.Y*inv));return this.set(result),this}clipByLine(line){if(this.length<3)return[];const intersections=[],lines=this.toLines(!0);for(let i=0;i<lines.length;i++){const p2=lines[i].getIntersection(line);p2&&intersections.push({index:i,point:p2})}if(intersections.length<2)return[this.clone()];intersections.sort((a22,b22)=>a22.index-b22.index);const newPoints=[];for(let i=0;i<this.length;i++){const p2=this[i].clone();newPoints.push(p2),intersections.forEach(inter=>{inter.index===i&&newPoints.push(inter.point.clone())})}const polygon2=new Polygon(newPoints),left=[],right=[],a2=line.start,b4=line.end,side=p2=>(b4.x-a2.x)*(p2.y-a2.y)-(b4.y-a2.y)*(p2.x-a2.x);polygon2.forEach(p2=>{side(p2)>=0&&left.push(p2.clone()),side(p2)<=0&&right.push(p2.clone())});const results=[];return left.length>=3&&results.push(new Polygon(left)),right.length>=3&&results.push(new Polygon(right)),results}getPointSideOfLine(point2){if(this.length<3)return"outside";for(let i=0,j=this.length-1;i<this.length;j=i++){const a2=this[j],b4=this[i],cross2=(b4.x-a2.x)*(point2.y-a2.y)-(b4.y-a2.y)*(point2.x-a2.x);if(Math.abs(cross2)<1e-10){const minX=Math.min(a2.x,b4.x),maxX=Math.max(a2.x,b4.x),minY=Math.min(a2.y,b4.y),maxY=Math.max(a2.y,b4.y);if(point2.x>=minX-1e-10&&point2.x<=maxX+1e-10&&point2.y>=minY-1e-10&&point2.y<=maxY+1e-10)return"on"}}let inside2=!1;for(let i=0,j=this.length-1;i<this.length;j=i++){const xi2=this[i].x,yi2=this[i].y,xj=this[j].x,yj=this[j].y;if(yi2>point2.y!=yj>point2.y){const intersectionX=(xj-xi2)*(point2.y-yi2)/(yj-yi2)+xi2;point2.x<intersectionX&&(inside2=!inside2)}}return inside2?"inside":"outside"}getMaxLengthInfo(){let len=-1/0,start=Point.zero(),end=start;for(let i=0;i<this.length-1;i++){const p1=this[i],p2=this[i+1],l=p1.distance(p2);p1.distance(p2)>len&&(len=l,start=p1,end=p2)}return{start:start,end:end,length:len}}getMinLengthInfo(){let len=1/0,start=Point.zero(),end=start;for(let i=0;i<this.length-1;i++){const p1=this[i],p2=this[i+1],l=p1.distance(p2);p1.distance(p2)<len&&(len=l,start=p1,end=p2)}return{start:start,end:end,length:len}}pointIn(point2){return"outside"!==this.getPointSideOfLine(point2)}pointWithin(point2){let inside2=!1;for(let i=0,j=this.length-1;i<this.length;j=i++){const xi2=this[i].x,yi2=this[i].y,xj=this[j].x,yj=this[j].y;if(yi2>point2.y!=yj>point2.y){const intersectionX=(xj-xi2)*(point2.y-yi2)/(yj-yi2)+xi2;point2.x<intersectionX&&(inside2=!inside2)}}return inside2}scale(scale2=1){return this.forEach(p2=>p2.multiplyScalar(scale2)),this}round(){return this.forEach(p2=>{p2.x=Math.round(p2.x),p2.y=Math.round(p2.y)}),this}union(polygons,scale2=1){return 1===(polygons=Polygon.booleanOp(this,polygons,{scale:scale2,type:"Union"})).length&&(this.set(polygons[0]),!0)}difference(polygons,scale2=1){return 1===(polygons=Polygon.booleanOp(this,polygons,{scale:scale2,type:"Difference"})).length&&(this.set(polygons[0]),!0)}intersectsBox(box){const thisBox=this.getBox2();return!(thisBox.maxX<box.minX||thisBox.minX>box.maxX||thisBox.maxY<box.minY||thisBox.minY>box.maxY)}toLines(closed=!0){const lines=[];for(let i=0;i<this.length&&(closed||i!==this.length-1);i++){const p2=this[i].clone(),nextP=this[(i+1)%this.length].clone();lines.push(new LineSegment(p2,nextP))}return lines.filter(line=>line.length>1e-9)}toRectangle(out=new Rectangle){const polygon2=this.getMinimumBoundingRectangle();if(polygon2)return out.points=[polygon2[0],polygon2[1],polygon2[2],polygon2[3]],out}toArrays(){return this.map(p2=>p2.toArray())}close(){if(this.length<2)return this;const first=this[0],last=this[this.length-1];return first.equal(last)||this.push(first.clone()),this}clone(){return new Polygon([...this].map(p2=>p2.clone()))}static fromByLines(lines){const grid=new PointSpatialHash,points=/* @__PURE__ */new Set;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));const start=lines[0].start;let current=start;for(points.add(lines[0].end),points.add(current);;){const list=grid.queryPoint(current,!0);if(1!==list.length)break;const{point:point2,userData:userData}=list[0];if(current=userData?.getAnotherPoint(point2),points.has(current))break;points.add(current)}return points.add(start.clone()),new Polygon([...points].map(p2=>p2.clone()))}static fromByLines2(lines,skipGroup=!1){if(!lines.length)return new Polygon;if(skipGroup||(lines=LineSegmentUtils.groupByLeafPath(lines).sort((a2,b4)=>b4.length-a2.length)[0]),1===lines.length)return new Polygon(lines[0].points.map(p2=>p2.clone()));const grid=new PointSpatialHash,points=/* @__PURE__ */new Set;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));let start=lines[0].isSameEndpointAsEnd(lines[1])?lines[0].end:lines[0].start,current=start;points.add(lines[0].getAnotherPoint(start)),points.add(current);for(let i=1;i<lines.length;i++){const line=lines[i];line.start.equal(current)?(points.add(line.end),current=line.end):(points.add(line.start),current=line.start)}return new Polygon([...points].map(p2=>p2.clone()))}static multipleFromByLines(lines){return LineSegmentUtils.groupByLeafPath(lines).map(path=>this.fromByLines2(path,!0))}static fromByLinePath(lines,polygon2=new Polygon){if(lines.length<2)polygon2.set(lines[0].points);else{const points=lines.flatMap((line,index2)=>{if(0===index2){const lines2=lines[index2+1];return line.isSameEndpointAsStart(lines2)?[line.end,line.start]:[line.start,line.end]}{const lines2=lines[index2-1];return line.isSameEndpointAsStart(lines2)?[line.end]:[line.start]}});polygon2.set(points)}return polygon2}static ensureCCW(poly){ClipperLib.Clipper.Orientation(poly)||poly.reverse()}static booleanOp(subject,clips,opt){const{type:type="Union",subjectFillType:subjectFillType="NonZero",clipFillType:clipFillType="NonZero",scale:scale2=100}=opt;subject instanceof Polygon&&(subject=[subject]),clips instanceof Polygon&&(clips=[clips]),subject=subject.map(subject2=>subject2.clone().scale(scale2).round()),clips=clips.map(clips2=>clips2.clone().scale(scale2).round());const clipper=new ClipperLib.Clipper;clipper.StrictlySimple=!0,clipper.PreserveCollinear=!0,subject=subject.map(p2=>(p2=ClipperLib.Clipper.CleanPolygon(p2,.5*scale2/100),Polygon.ensureCCW(p2),p2)),clips=clips.map(p2=>(p2=ClipperLib.Clipper.CleanPolygon(p2,.5*scale2/100),Polygon.ensureCCW(p2),p2)),clipper.AddPaths(subject,ClipperLib.PolyType.ptSubject,!0),clipper.AddPaths(clips,ClipperLib.PolyType.ptClip,!0);let solutions=[];clipper.Execute(ClipperLib.ClipType["ct"+type],solutions,ClipperLib.PolyFillType["pft"+subjectFillType],ClipperLib.PolyFillType["pft"+clipFillType]);const inv=1/scale2;return solutions.map(solution=>(solution=solution.map(p2=>new Point(p2.X*inv,p2.Y*inv)),new Polygon(solution))).filter(poly=>Math.abs(poly.area())>.01)}static offset(poly,option){const{offsetHalfWidth:offsetHalfWidth,joinType:joinType="jtMiter",endType:endType="etOpenButt",scale:scale2=1e5}=option??{},offset=new ClipperLib.ClipperOffset(2,.25);let solutions=new ClipperLib.Paths;offset.AddPath(poly.map(p2=>p2.multiplyScalar(scale2)),ClipperLib.JoinType[joinType],ClipperLib.EndType[endType]),offset.Execute(solutions,offsetHalfWidth*scale2);const inv=1/scale2;return poly.map(p2=>p2.multiplyScalar(inv)),solutions.map(solution=>solution.map(p2=>Point.from(p2).multiplyScalar(1/scale2))).map(ps2=>new Polygon(ps2))[0]}}function selectLocalFileFun(){return new Promise(resolve=>{const input=document.createElement("input");input.type="file",input.accept="application/json",input.click(),input.onchange=()=>{input.files?.length?resolve(input.files[0]):resolve(null)}})}const SelectLocalFile=Object.assign(selectLocalFileFun,{arrayBuffer:()=>new Promise(async resolve=>{const file=await selectLocalFileFun();if(file instanceof File){const fileReader=new FileReader;fileReader.onload=()=>{resolve(fileReader.result)},fileReader.readAsArrayBuffer(file)}else resolve(null)}),text:()=>new Promise(async resolve=>{const file=await selectLocalFileFun();if(file instanceof File){const fileReader=new FileReader;fileReader.onload=()=>{resolve(fileReader.result)},fileReader.readAsText(file,"utf-8")}else resolve(null)}),async json(){const text=await this.text();if(text)return JSON.parse(text)}});class CommandFlow extends EventDispatcher{list=[];dataList=[];rollbacklist=[];revokeRollbacklist=[];writeOperationRecord=!0;loop=!1;currentIndex=0;userData={};setLoop(loop){return this.loop=loop,this}add(operation,data){return this.list.push(operation),this.dataList.push(data??{}),this}addRollback(callBack){return this.rollbacklist.push(callBack),this}addRevokeRollback(callBack){return this.revokeRollbacklist.push(callBack),this}getData(index2){return this.dataList[index2]}}class CommandManager extends EventDispatcher{commandFlowMap=/* @__PURE__ */new Map;lock=!1;abortController=null;resolve=null;currentName=null;_disabled=!1;set disabled(disabled){this._disabled=disabled,this._disabled&&this.cancel()}get disabled(){return this._disabled}operationList=[];rollbackList=[];constructor(){super()}addOperation(name,data){const commandFlow=this.getCommandFlow(name);if(!commandFlow)throw new Error(`${name} 命令不存在`);commandFlow.writeOperationRecord&&(this.operationList.push({name:name,data:data}),this.rollbackList.length=0)}addCommandFlow(name,custom){if(this.commandFlowMap.has(name))throw new Error(`${name} 命令已经存在`);const commandFlow=custom?custom():new CommandFlow;return this.commandFlowMap.set(name,commandFlow),commandFlow}getCommandFlow(name){return this.commandFlowMap.get(name)}executionPromise=null;executionResolve=null;async start(name,data=null,step=0){if(this.disabled)throw new Error("命令管理器已禁用,无法启动新的命令流");if(this.dispatchEvent({type:"startedBefore",name:name,currentName:this.currentName}),this.executionPromise&&await this.executionPromise,this.executionPromise=null,this.lock)throw new Error("命令管理器已被 "+this.currentName+" 命令锁定,无法启动新的命令流,请退出或等待命令执行结束");const commandFlow=this.commandFlowMap.get(name);if(!commandFlow)throw new Error(`命令流 ${name} 不存在`);this.lock=!0,this.abortController=new AbortController,this.currentName=name,commandFlow.dispatchEvent({type:"started"}),this.dispatchEvent({type:"started",name:name});try{for(let i=step;i<commandFlow.list.length;i++){const operation=commandFlow.list[i];if(commandFlow.currentIndex=i,commandFlow.dispatchEvent({type:"executing",index:i}),this.dispatchEvent({type:"executing",name:name,index:i}),data=await new Promise(resolve=>{this.resolve=resolve,operation(resolve,data)}),this.abortController.signal.aborted){commandFlow.dispatchEvent({type:"executionInterrupt",index:i}),this.dispatchEvent({type:"executionInterrupt",name:name,index:i}),this.dispatchEvent({type:"cancel",name:name});break}commandFlow.dispatchEvent({type:"executionCompleted",index:i,data:data}),this.dispatchEvent({type:"executionCompleted",name:name,index:i,data:data})}}catch(error){console.error(error)}finally{this.lock=!1,this.currentName=null,commandFlow.currentIndex=0,this.abortController&&!this.abortController.signal.aborted&&(commandFlow.dispatchEvent({type:"completed",data:data}),this.dispatchEvent({type:"completed",name:name,data:data}),commandFlow.writeOperationRecord&&(this.operationList.push({name:name,data:data}),this.rollbackList.length=0),commandFlow.loop&&queueMicrotask(()=>this.start(name))),this.abortController=null,commandFlow.dispatchEvent({type:"finally"}),this.dispatchEvent({type:"finally",name:name}),this.executionResolve&&(this.executionResolve(null),this.executionResolve=null)}return data}cancel(){this.abortController&&(this.abortController.abort(),this.resolve&&this.resolve(),this.executionPromise=new Promise(resolve=>this.executionResolve=resolve))}rollback(){try{const operation=this.operationList.pop();if(!operation)return!1;const commandFlow=this.commandFlowMap.get(operation.name);if(!commandFlow)return!1;const data=commandFlow.rollbacklist.reduce((data2,callBack)=>callBack(data2),operation.data);return this.dispatchEvent({type:"rollback",name:operation.name}),this.rollbackList.push({data:data,name:operation.name}),!0}catch(error){throw new Error(`回滚失败:${error}`)}}revokeRollback(){try{const operation=this.rollbackList.pop();if(!operation)return!1;const commandFlow=this.commandFlowMap.get(operation.name);if(!commandFlow)return!1;const data=commandFlow.revokeRollbacklist.reduce((data2,callBack)=>callBack(data2),operation.data);return this.dispatchEvent({type:"revokeRollback",name:operation.name}),this.operationList.push({name:operation.name,data:data}),!0}catch(error){throw new Error(`撤回回滚失败:${error}`)}}destroy(){this.cancel(),this.addEventListener("cancel",()=>{this.commandFlowMap.clear(),this.lock=!1,this.abortController=null,this.resolve=null,this.executionResolve=null,this.executionPromise=null,this.currentName=null,this.operationList.length=0,this.rollbackList.length=0},{once:!0})}}async function include(path,exportDefault=!0){if("undefined"!=typeof global&&"undefined"!=typeof require)return require(path);{let pack=await import(path);return exportDefault&&(pack=pack.default),pack}}"undefined"!=typeof globalThis&&"undefined"==typeof ProgressEvent&&(globalThis.ProgressEvent=class extends EventTarget{type;lengthComputable;loaded;total;bubbles;cancelable;defaultPrevented;eventPhase;timeStamp;isTrusted;constructor(type,options={}){super(),this.type=type,this.lengthComputable=options.lengthComputable||!1,this.loaded=options.loaded||0,this.total=options.total||0,this.bubbles=!1,this.cancelable=!1,this.defaultPrevented=!1,this.eventPhase=0,this.timeStamp=Date.now(),this.isTrusted=!0}preventDefault(){}stopPropagation(){}stopImmediatePropagation(){}});let promise,gltfLoader=GLTFExporter,gltfExporter=GLTFLoader;function GltfInit(){return promise||(promise=new Promise(async resolve=>{try{const{GLTFLoader:GLTFLoader2}=await("undefined"!=typeof window?import("three/addons/loaders/GLTFLoader.js"):include("node-three-gltf",!1));gltfLoader=GLTFLoader2;const{GLTFExporter:GLTFExporter2}=await("undefined"!=typeof window?import("three/addons/exporters/GLTFExporter.js"):include("node-three-gltf",!1));gltfExporter=GLTFExporter2}catch(error){console.error(error)}resolve(!0)}),promise)}const gltf={get GLTFLoader(){return gltfLoader},get GLTFExporter(){return gltfExporter}};const polygon$1=new Polygon;var Side=/* @__PURE__ */(Side2=>(Side2[Side2.ALL=0]="ALL",Side2[Side2.OUT=1]="OUT",Side2[Side2.IN=2]="IN",Side2))(Side||{});class MiniCircles{debug={angle:!1,edges:!1};scope=1e-4;findCycleEntryEdges(lineUG_){if(!(lineUG_ instanceof LineSegmentUndirectedGraph)){if(!Array.isArray(lineUG_))throw new Error("参数错误");lineUG_=new LineSegmentUndirectedGraph(lineUG_)}const lineUG=lineUG_,unionFind=new UnionFindSet(lineUG.size),ringEdges=[];return lineUG.forEachEdge((n1,n2)=>{const line=lineUG.getLine(n1,n2);unionFind.find(n1)===unionFind.find(n2)?ringEdges.push(line):unionFind.union(n1,n2)}),ringEdges}deduplicate(rings){const map=new ArrayMap,newRings=[];rings.forEach(ring=>map.append(ring.length,ring));for(const rings2 of map.values()){const lineIndexGenerator=new LineIndexGenerator(rings2.flat()),ringMap=new ArrayMap;rings2.map(ring=>{const key=ring.map(line=>lineIndexGenerator.getIndex(line)).sort((a2,b4)=>a2-b4).join(",");ringMap.append(key,ring)}),ringMap.forEach(list=>newRings.push(list[0]))}return newRings}sideTest(circles,side=0){if(circles.length<2||0===side)return circles;const result=[];for(const circle of circles){Polygon.fromByLinePath(circle,polygon$1);const isCCW=polygon$1.signedArea()<0;(2===side&&isCCW||1===side&&!isCCW)&&result.push(circle)}return result}findSameSidePath(opt){let count=0,{A:A,B:B2,exitPoint:exitPoint=A,grid:grid,path:path=/* @__PURE__ */new Set}=opt;if(Array.isArray(grid)){const lines=grid;grid=new PointSpatialHash;for(let i=0;i<lines.length;i++)grid.insert(lines[i].start,lines[i]).insert(lines[i].end,lines[i])}for(;;){if(++count>1e5)return void console.warn("超过最大循环次数");if(exitPoint.equal(B2))return[...path];const candidates=grid.queryCircle(B2,this.scope).filter(item=>item.point!==B2).filter(item=>!path.has(item.userData));if(0===candidates.length)return;const BA=A.directionFrom(B2);let minAngle=1/0,minC=null,mineLie=null;for(let i=0;i<candidates.length;i++){const candidateLine=candidates[i].userData,C=candidateLine.getAnotherPoint(candidates[i].point),BC=C.directionFrom(B2),angle=BA.angle(BC,{unit:"degree",range:"360"});angle<minAngle&&(minAngle=angle,minC=C,mineLie=candidateLine)}if(null==minC)return;A=B2,B2=minC,path.add(mineLie),this.debug.angle&&drawText(minAngle.toFixed(),mineLie?.center)}}miniCircle(lines,option){const{side:side=2,circleEdges:circleEdges=this.findCycleEntryEdges(lines)}=option??{},grid=PointSpatialHash.fromByLines(lines),findSetMap=new ArrayMap,getBaseCircle=line=>{const circles=[];return line.points.forEach(point2=>{const otherPoint=line.getAnotherPoint(point2),set2=/* @__PURE__ */new Set([line]),circle=this.findSameSidePath({grid:grid,B:point2,A:otherPoint,exitPoint:otherPoint,path:set2});findSetMap.append(line,set2),circle&&circles.push(circle)}),this.sideTest(circles,side)},circleList=[];for(let i=0;i<circleEdges.length;i++){const line=circleEdges[i];if(!(line instanceof LineSegment))continue;const circles=getBaseCircle(line);circleList.push(...circles)}return{circles:this.deduplicate(circleList),setMap:findSetMap,circleEdges:circleEdges}}}class MaxiCircles extends MiniCircles{static#instance=null;static get instance(){return this.#instance||(this.#instance=new MaxiCircles),this.#instance}mergeCircles(circles,internalEdges=[]){const visited=/* @__PURE__ */new Map,unionFindSet=new UnionFindSet(circles.length);circles.forEach((circle,index2)=>{for(let i=0;i<circle.length;i++){const line=circle[i];visited.has(line)?unionFindSet.union(index2,visited.get(line)):visited.set(line,index2)}});const countMap=new CounterMap,groups=unionFindSet.getAllSets().valueArray.map(list=>{let group2=list.map(i=>circles[i]);if(1===group2.length)return group2[0];countMap.clear(),group2=this.deduplicate(group2),group2.forEach(lines=>lines.forEach(line=>countMap.increment(line)));return countMap.reduce((lines,count,line)=>(1===count?lines.push(line):internalEdges.push(line),lines),[])});return{internalEdges:internalEdges,circles:groups}}maxiCircles(lines,findMinCirclesFilter=circles=>circles){let removeSet=findDiscretePointLine2(lines,/* @__PURE__ */new Set,!0);lines=lines.filter(line=>!removeSet.has(line));const linesGroup=LineSegmentUtils.groupByPath(lines),circles=[],internalEdges=[];linesGroup.forEach((lines2,_)=>{try{const miniCircles2=this.miniCircle(lines2).circles,findCircles=findMinCirclesFilter(miniCircles2),result=this.mergeCircles(findCircles);circles.push(...result.circles),internalEdges.push(...result.internalEdges)}catch(error){console.warn("环查找出现异常:",error)}});const internalEdgesSet=/* @__PURE__ */new Set([...internalEdges]),groupsSet=/* @__PURE__ */new Set([...circles.flat()]);return(lines=lines.filter(line=>!internalEdgesSet.has(line))).forEach(line=>!groupsSet.has(line)),lines.push(...removeSet),{newLines:lines=[...new Set(lines)],circles:circles,internalEdges:internalEdges}}}const a={c:null,u:[new Vector3,new Vector3,new Vector3],e:[]},b$1={c:null,u:[new Vector3,new Vector3,new Vector3],e:[]},R=[[],[],[]],AbsR=[[],[],[]],t$1=[],xAxis=new Vector3,yAxis=new Vector3,zAxis=new Vector3,v1=new Vector3,size=new Vector3,closestPoint=new Vector3,rotationMatrix=new Matrix3,aabb=new Box3,matrix=new Matrix4,inverse=new Matrix4,localRay=new Ray;let OBB$1=class{constructor(center=new Vector3,halfSize=new Vector3,rotation=new Matrix3){this.center=center,this.halfSize=halfSize,this.rotation=rotation}set(center,halfSize,rotation){return this.center=center,this.halfSize=halfSize,this.rotation=rotation,this}copy(obb2){return this.center.copy(obb2.center),this.halfSize.copy(obb2.halfSize),this.rotation.copy(obb2.rotation),this}clone(){return(new this.constructor).copy(this)}getSize(target){return target.copy(this.halfSize).multiplyScalar(2)}clampPoint(point2,target){const halfSize=this.halfSize;v1.subVectors(point2,this.center),this.rotation.extractBasis(xAxis,yAxis,zAxis),target.copy(this.center);const x=MathUtils.clamp(v1.dot(xAxis),-halfSize.x,halfSize.x);target.add(xAxis.multiplyScalar(x));const y=MathUtils.clamp(v1.dot(yAxis),-halfSize.y,halfSize.y);target.add(yAxis.multiplyScalar(y));const z=MathUtils.clamp(v1.dot(zAxis),-halfSize.z,halfSize.z);return target.add(zAxis.multiplyScalar(z)),target}containsPoint(point2){return v1.subVectors(point2,this.center),this.rotation.extractBasis(xAxis,yAxis,zAxis),Math.abs(v1.dot(xAxis))<=this.halfSize.x&&Math.abs(v1.dot(yAxis))<=this.halfSize.y&&Math.abs(v1.dot(zAxis))<=this.halfSize.z}intersectsBox3(box32){return this.intersectsOBB(obb.fromBox3(box32))}intersectsSphere(sphere){return this.clampPoint(sphere.center,closestPoint),closestPoint.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius}intersectsOBB(obb2,epsilon2=Number.EPSILON){a.c=this.center,a.e[0]=this.halfSize.x,a.e[1]=this.halfSize.y,a.e[2]=this.halfSize.z,this.rotation.extractBasis(a.u[0],a.u[1],a.u[2]),b$1.c=obb2.center,b$1.e[0]=obb2.halfSize.x,b$1.e[1]=obb2.halfSize.y,b$1.e[2]=obb2.halfSize.z,obb2.rotation.extractBasis(b$1.u[0],b$1.u[1],b$1.u[2]);for(let i=0;i<3;i++)for(let j=0;j<3;j++)R[i][j]=a.u[i].dot(b$1.u[j]);v1.subVectors(b$1.c,a.c),t$1[0]=v1.dot(a.u[0]),t$1[1]=v1.dot(a.u[1]),t$1[2]=v1.dot(a.u[2]);for(let i=0;i<3;i++)for(let j=0;j<3;j++)AbsR[i][j]=Math.abs(R[i][j])+epsilon2;let ra2,rb;for(let i=0;i<3;i++)if(ra2=a.e[i],rb=b$1.e[0]*AbsR[i][0]+b$1.e[1]*AbsR[i][1]+b$1.e[2]*AbsR[i][2],Math.abs(t$1[i])>ra2+rb)return!1;for(let i=0;i<3;i++)if(ra2=a.e[0]*AbsR[0][i]+a.e[1]*AbsR[1][i]+a.e[2]*AbsR[2][i],rb=b$1.e[i],Math.abs(t$1[0]*R[0][i]+t$1[1]*R[1][i]+t$1[2]*R[2][i])>ra2+rb)return!1;return ra2=a.e[1]*AbsR[2][0]+a.e[2]*AbsR[1][0],rb=b$1.e[1]*AbsR[0][2]+b$1.e[2]*AbsR[0][1],!(Math.abs(t$1[2]*R[1][0]-t$1[1]*R[2][0])>ra2+rb)&&(ra2=a.e[1]*AbsR[2][1]+a.e[2]*AbsR[1][1],rb=b$1.e[0]*AbsR[0][2]+b$1.e[2]*AbsR[0][0],!(Math.abs(t$1[2]*R[1][1]-t$1[1]*R[2][1])>ra2+rb)&&(ra2=a.e[1]*AbsR[2][2]+a.e[2]*AbsR[1][2],rb=b$1.e[0]*AbsR[0][1]+b$1.e[1]*AbsR[0][0],!(Math.abs(t$1[2]*R[1][2]-t$1[1]*R[2][2])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][0]+a.e[2]*AbsR[0][0],rb=b$1.e[1]*AbsR[1][2]+b$1.e[2]*AbsR[1][1],!(Math.abs(t$1[0]*R[2][0]-t$1[2]*R[0][0])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][1]+a.e[2]*AbsR[0][1],rb=b$1.e[0]*AbsR[1][2]+b$1.e[2]*AbsR[1][0],!(Math.abs(t$1[0]*R[2][1]-t$1[2]*R[0][1])>ra2+rb)&&(ra2=a.e[0]*AbsR[2][2]+a.e[2]*AbsR[0][2],rb=b$1.e[0]*AbsR[1][1]+b$1.e[1]*AbsR[1][0],!(Math.abs(t$1[0]*R[2][2]-t$1[2]*R[0][2])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][0]+a.e[1]*AbsR[0][0],rb=b$1.e[1]*AbsR[2][2]+b$1.e[2]*AbsR[2][1],!(Math.abs(t$1[1]*R[0][0]-t$1[0]*R[1][0])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][1]+a.e[1]*AbsR[0][1],rb=b$1.e[0]*AbsR[2][2]+b$1.e[2]*AbsR[2][0],!(Math.abs(t$1[1]*R[0][1]-t$1[0]*R[1][1])>ra2+rb)&&(ra2=a.e[0]*AbsR[1][2]+a.e[1]*AbsR[0][2],rb=b$1.e[0]*AbsR[2][1]+b$1.e[1]*AbsR[2][0],!(Math.abs(t$1[1]*R[0][2]-t$1[0]*R[1][2])>ra2+rb)))))))))}intersectsPlane(plane){this.rotation.extractBasis(xAxis,yAxis,zAxis);const r2=this.halfSize.x*Math.abs(plane.normal.dot(xAxis))+this.halfSize.y*Math.abs(plane.normal.dot(yAxis))+this.halfSize.z*Math.abs(plane.normal.dot(zAxis)),d2=plane.normal.dot(this.center)-plane.constant;return Math.abs(d2)<=r2}intersectRay(ray,target){return this.getSize(size),aabb.setFromCenterAndSize(v1.set(0,0,0),size),matrix.setFromMatrix3(this.rotation),matrix.setPosition(this.center),inverse.copy(matrix).invert(),localRay.copy(ray).applyMatrix4(inverse),localRay.intersectBox(aabb,target)?target.applyMatrix4(matrix):null}intersectsRay(ray){return null!==this.intersectRay(ray,v1)}fromBox3(box32){return box32.getCenter(this.center),box32.getSize(this.halfSize).multiplyScalar(.5),this.rotation.identity(),this}equals(obb2){return obb2.center.equals(this.center)&&obb2.halfSize.equals(this.halfSize)&&obb2.rotation.equals(this.rotation)}applyMatrix4(matrix2){const e=matrix2.elements;let sx=v1.set(e[0],e[1],e[2]).length();const sy=v1.set(e[4],e[5],e[6]).length(),sz=v1.set(e[8],e[9],e[10]).length();matrix2.determinant()<0&&(sx=-sx),rotationMatrix.setFromMatrix4(matrix2);const invSX=1/sx,invSY=1/sy,invSZ=1/sz;return rotationMatrix.elements[0]*=invSX,rotationMatrix.elements[1]*=invSX,rotationMatrix.elements[2]*=invSX,rotationMatrix.elements[3]*=invSY,rotationMatrix.elements[4]*=invSY,rotationMatrix.elements[5]*=invSY,rotationMatrix.elements[6]*=invSZ,rotationMatrix.elements[7]*=invSZ,rotationMatrix.elements[8]*=invSZ,this.rotation.multiply(rotationMatrix),this.halfSize.x*=sx,this.halfSize.y*=sy,this.halfSize.z*=sz,v1.setFromMatrixPosition(matrix2),this.center.add(v1),this}};const obb=new OBB$1;function distance(p1,p2){const dx=p2[0]-p1[0],dy=p2[1]-p1[1];return Math.sqrt(dx*dx+dy*dy)}class OBB2 extends OBB$1{getBoxMesh(){matrix4.identity(),matrix4.setFromMatrix3(this.rotation),matrix4.decompose(vec3$3,quat,new THREE.Vector3);const size2=this.halfSize.clone().multiplyScalar(2),box=new THREE.Mesh(new THREE.BoxGeometry(size2.x,size2.y,size2.z));return box.position.copy(this.center),box.rotation.setFromQuaternion(quat),box}getBoxEdge(color=16776960){const box=this.getBoxMesh();box3$2.setFromObject(box);const geometry_=new THREE.EdgesGeometry(box.geometry.clone().applyMatrix4(box.matrixWorld));return new THREE.LineSegments(geometry_,new THREE.LineBasicMaterial({color:color,toneMapped:!1}))}toJson(){return matrix4.identity(),matrix4.setFromMatrix3(this.rotation),matrix4.decompose(vec3$3,quat,new THREE.Vector3),{size:this.halfSize.toArray(),center:this.center.toArray(),quaternion:quat.toArray()}}static from(box,position,rotation,out=new OBB2){if(rotation instanceof THREE.Euler)quat.setFromEuler(rotation);else{if(!(rotation instanceof THREE.Quaternion))throw new Error("传入的旋转不是欧拉角或者四元数");quat.copy(rotation)}return matrix4.compose(position,quat,scale),out.center.copy(position),out.halfSize.copy(box.multiplyScalar(.5)),out.rotation.setFromMatrix4(matrix4),out}static fromByPath2D(path,origin,height,out=new OBB2){const result=smallestSurroundingRectangleByArea({type:"Polygon",coordinates:[path.map(p2=>[p2.x,p2.y])]});if(!result)throw new Error("2d obb 获取失败");const rectangle=result.geometry.coordinates[0],width1=distance(rectangle[0],rectangle[1]),width2=distance(rectangle[1],rectangle[2]),angle=Math.atan2(rectangle[1][1]-rectangle[0][1],rectangle[1][0]-rectangle[0][0]);vec3$3.set(width1,width2,height),euler.set(0,0,angle);const[x,y]=function(points){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(const[x,y]of points)x<minX&&(minX=x),x>maxX&&(maxX=x),y<minY&&(minY=y),y>maxY&&(maxY=y);return[.5*(maxX+minX),.5*(maxY+minY)]}(rectangle);return origin.x=x,origin.y=y,out=this.from(vec3$3,origin,euler,out)}}const matrix4=new THREE.Matrix4,quat=new THREE.Quaternion,euler=new THREE.Euler,scale=new THREE.Vector3(1,1,1),vec3$3=new THREE.Vector3,box3$2=new THREE.Box3;var layout=[new Uint8Array([0,0,0]),new Uint8Array([0,0,1]),new Uint8Array([0,1,0]),new Uint8Array([0,1,1]),new Uint8Array([1,0,0]),new Uint8Array([1,0,1]),new Uint8Array([1,1,0]),new Uint8Array([1,1,1])];new Vector3;var c2=new Vector3,Octant=class{min;max;children;data;constructor(min=new Vector3,max=new Vector3){this.min=min,this.max=max,this.children=null,this.data=null}getCenter(result){return result.addVectors(this.min,this.max).multiplyScalar(.5)}getDimensions(result){return result.subVectors(this.max,this.min)}split(){const min=this.min,max=this.max,mid=this.getCenter(c2),children=this.children=[];for(let i=0;i<8;++i){const combination=layout[i],child=new this.constructor;child.min.set(0===combination[0]?min.x:mid.x,0===combination[1]?min.y:mid.y,0===combination[2]?min.z:mid.z),child.max.set(0===combination[0]?mid.x:max.x,0===combination[1]?mid.y:max.y,0===combination[2]?mid.z:max.z),children[i]=child}}};var octantTable=[new Uint8Array([4,2,1]),new Uint8Array([5,3,8]),new Uint8Array([6,8,3]),new Uint8Array([7,8,8]),new Uint8Array([8,6,5]),new Uint8Array([8,7,8]),new Uint8Array([8,8,7]),new Uint8Array([8,8,8])];function findNextOctant(currentOctant,tx1,ty1,tz1){let min,exit;return tx1<ty1?(min=tx1,exit=0):(min=ty1,exit=1),tz1<min&&(exit=2),octantTable[currentOctant][exit]}var v=new Vector3,b=new Box3,d=new Box3,r=new Ray;var flags=new class{value;constructor(){this.value=0}};function raycastOctant(node,tx0,ty0,tz0,tx1,ty1,tz1,result){if(tx1>=0&&ty1>=0&&tz1>=0){const c3=node.children;if(null==c3)result.push(node);else{const txm=.5*(tx0+tx1),tym=.5*(ty0+ty1),tzm=.5*(tz0+tz1),f=flags.value;let currentOctant=function(tx0,ty0,tz0,txm,tym,tzm){let entry=0;return tx0>ty0&&tx0>tz0?(tym<tx0&&(entry|=2),tzm<tx0&&(entry|=1)):ty0>tz0?(txm<ty0&&(entry|=4),tzm<ty0&&(entry|=1)):(txm<tz0&&(entry|=4),tym<tz0&&(entry|=2)),entry}(tx0,ty0,tz0,txm,tym,tzm);for(;currentOctant<8;)switch(currentOctant){case 0:raycastOctant(c3[f],tx0,ty0,tz0,txm,tym,tzm,result),currentOctant=findNextOctant(currentOctant,txm,tym,tzm);break;case 1:raycastOctant(c3[1^f],tx0,ty0,tzm,txm,tym,tz1,result),currentOctant=findNextOctant(currentOctant,txm,tym,tz1);break;case 2:raycastOctant(c3[2^f],tx0,tym,tz0,txm,ty1,tzm,result),currentOctant=findNextOctant(currentOctant,txm,ty1,tzm);break;case 3:raycastOctant(c3[3^f],tx0,tym,tzm,txm,ty1,tz1,result),currentOctant=findNextOctant(currentOctant,txm,ty1,tz1);break;case 4:raycastOctant(c3[4^f],txm,ty0,tz0,tx1,tym,tzm,result),currentOctant=findNextOctant(currentOctant,tx1,tym,tzm);break;case 5:raycastOctant(c3[5^f],txm,ty0,tzm,tx1,tym,tz1,result),currentOctant=findNextOctant(currentOctant,tx1,tym,tz1);break;case 6:raycastOctant(c3[6^f],txm,tym,tz0,tx1,ty1,tzm,result),currentOctant=findNextOctant(currentOctant,tx1,ty1,tzm);break;case 7:raycastOctant(c3[7^f],txm,tym,tzm,tx1,ty1,tz1,result),currentOctant=8}}}}var OctreeRaycaster=class{static intersectOctree(node,ray){const result=[],t2=function(octree,ray,flags2){const min=b.min.set(0,0,0),max=b.max.subVectors(octree.max,octree.min),dimensions=octree.getDimensions(d.min),halfDimensions=d.max.copy(dimensions).multiplyScalar(.5),origin=r.origin.copy(ray.origin),direction=r.direction.copy(ray.direction);origin.sub(octree.getCenter(v)).add(halfDimensions),flags2.value=0,direction.x<0?(origin.x=dimensions.x-origin.x,direction.x=-direction.x,flags2.value|=4):0===direction.x&&(direction.x=Number.EPSILON),direction.y<0?(origin.y=dimensions.y-origin.y,direction.y=-direction.y,flags2.value|=2):0===direction.y&&(direction.y=Number.EPSILON),direction.z<0?(origin.z=dimensions.z-origin.z,direction.z=-direction.z,flags2.value|=1):0===direction.z&&(direction.z=Number.EPSILON);const invDirX=1/direction.x,invDirY=1/direction.y,invDirZ=1/direction.z,tx0=(min.x-origin.x)*invDirX,tx1=(max.x-origin.x)*invDirX,ty0=(min.y-origin.y)*invDirY,ty1=(max.y-origin.y)*invDirY,tz0=(min.z-origin.z)*invDirZ,tz1=(max.z-origin.z)*invDirZ;return Math.max(tx0,ty0,tz0)<Math.min(tx1,ty1,tz1)?[tx0,ty0,tz0,tx1,ty1,tz1]:null}(node,ray,flags);return null!==t2&&raycastOctant(node,t2[0],t2[1],t2[2],t2[3],t2[4],t2[5],result),result}},b2=new Box3,OctreeIterator=class{root;region;result;trace;indices;constructor(root,region=null){this.root=root,this.region=region,this.reset()}reset(){const root=this.root;return this.trace=[],this.indices=[],null!==root&&(b2.min=root.min,b2.max=root.max,(null===this.region||this.region.intersectsBox(b2))&&(this.trace.push(root),this.indices.push(0))),this.result={done:!1},this}next(){const region=this.region,indices=this.indices,trace=this.trace;let octant=null,depth=trace.length-1;for(;null===octant&&depth>=0;){const index2=indices[depth]++,children=trace[depth].children;if(index2<8)if(null!=children){const child=children[index2];if(null!==region&&(b2.min=child.min,b2.max=child.max,!region.intersectsBox(b2)))continue;trace.push(child),indices.push(0),++depth}else octant=trace.pop(),indices.pop();else trace.pop(),indices.pop(),--depth}return this.result.value=octant,this.result.done=null===octant,this.result}[Symbol.iterator](){return this}},b3=new Box3;function getDepth(node){const children=node.children;let result=0;if(null!=children)for(let i=0,l=children.length;i<l;++i){const d2=1+getDepth(children[i]);d2>result&&(result=d2)}return result}function cull(node,region,result){const children=node.children;if(b3.min=node.min,b3.max=node.max,region.intersectsBox(b3))if(null!=children)for(let i=0,l=children.length;i<l;++i)cull(children[i],region,result);else result.push(node)}function findNodesByLevel(node,level,depth,result){const children=node.children;if(depth===level)result.push(node);else if(null!=children){++depth;for(let i=0,l=children.length;i<l;++i)findNodesByLevel(children[i],level,depth,result)}}var Octree=class{root;constructor(root){this.root=root}get min(){return this.root.min}get max(){return this.root.max}get children(){return this.root.children||null}getCenter(result){return this.root.getCenter(result)}getDimensions(result){return this.root.getDimensions(result)}cull(region){const result=[];return cull(this.root,region,result),result}getDepth(){return getDepth(this.root)}findNodesByLevel(level){const result=[];return findNodesByLevel(this.root,level,0,result),result}getIntersectingNodes(raycaster){return OctreeRaycaster.intersectOctree(this.root,raycaster.ray)}leaves(region=null){return new OctreeIterator(this.root,region)}[Symbol.iterator](){return new OctreeIterator(this.root)}},PointContainer=class{data;point;distance;constructor(point2=null,data=null,distance2=0){this.point=point2,this.data=data,this.distance=distance2}},RayPointIntersection=class extends PointContainer{distanceToRay;constructor(distanceToOrigin,distanceToRay,point2,data=null){super(point2,data,distanceToOrigin),this.distanceToRay=distanceToRay}},PointData=class{points;data;constructor(){this.points=[],this.data=[]}testPoints(raycaster,result){const threshold=void 0!==raycaster.params.Points?raycaster.params.Points.threshold:0,thresholdSq=threshold*threshold,ray=raycaster.ray,points=this.points,data=this.data;for(let i=0,l=points.length;i<l;++i){const point2=points[i],distanceToRaySq=ray.distanceSqToPoint(point2);if(distanceToRaySq<thresholdSq){const closestPoint2=ray.closestPointToPoint(point2,new Vector3),distance2=ray.origin.distanceTo(closestPoint2);distance2>=raycaster.near&&distance2<=raycaster.far&&result.push(new RayPointIntersection(distance2,Math.sqrt(distanceToRaySq),closestPoint2,data[i]))}}}},p=new Vector3,PointOctant=class extends Octant{constructor(min,max){super(min,max)}distanceToSquared(point2){return p.copy(point2).clamp(this.min,this.max).sub(point2).lengthSq()}distanceToCenterSquared(point2){const center=this.getCenter(p),dx=point2.x-center.x,dy=point2.y-center.x,dz=point2.z-center.z;return dx*dx+dy*dy+dz*dz}contains(point2,bias){const min=this.min,max=this.max;return point2.x>=min.x-bias&&point2.y>=min.y-bias&&point2.z>=min.z-bias&&point2.x<=max.x+bias&&point2.y<=max.y+bias&&point2.z<=max.z+bias}redistribute(bias){const children=this.children,pointData=this.data;if(null!==children&&null!==pointData){const points=pointData.points,data=pointData.data;for(let i=0,il=points.length;i<il;++i){const point2=points[i],entry=data[i];for(let j=0,jl=children.length;j<jl;++j){const child=children[j];if(child.contains(point2,bias)){null===child.data&&(child.data=new PointData);const childData=child.data;childData.points.push(point2),childData.data.push(entry);break}}}this.data=null}}merge(){const children=this.children;if(null!==children){const pointData=new PointData;for(let i=0,l=children.length;i<l;++i){const childData=children[i].data;null!==childData&&(pointData.points=pointData.points.concat(childData.points),pointData.data=pointData.data.concat(childData.data))}this.children=null,this.data=pointData}}};function countPoints(octant){const children=octant.children;let result=0;if(null!==children)for(let i=0,l=children.length;i<l;++i)result+=countPoints(children[i]);else if(null!==octant.data){result=octant.data.points.length}return result}function set(point2,data,octree,octant,depth){let exists=!1,done=!1;if(null!==octant&&octant.contains(point2,octree.getBias())){let children=octant.children;if(null===children){let index2=0;if(null===octant.data)octant.data=new PointData;else{const points=octant.data.points;for(let i=0,l=points.length;!exists&&i<l;++i)exists=points[i].equals(point2),index2=i}const pointData=octant.data;exists?(pointData.data[index2]=data,done=!0):pointData.points.length<octree.getMaxPoints()||depth===octree.getMaxDepth()?(pointData.points.push(point2.clone()),pointData.data.push(data),done=!0):(octant.split(),octant.redistribute(octree.getBias()),children=octant.children)}if(null!==children){++depth;for(let i=0,l=children.length;!done&&i<l;++i)done=set(point2,data,octree,children[i],depth)}}return done}function remove(point2,octree,octant,parent){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(null!==children)for(let i=0,l=children.length;null===result&&i<l;++i)result=remove(point2,octree,children[i],octant);else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i)if(points[i].equals(point2)){const last=l-1;result=data[i],i<last&&(points[i]=points[last],data[i]=data[last]),points.pop(),data.pop(),null!==parent&&countPoints(parent)<=octree.getMaxPoints()&&parent.merge();break}}return result}function get(point2,octree,octant){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(null!==children)for(let i=0,l=children.length;null===result&&i<l;++i)result=get(point2,octree,children[i]);else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;null===result&&i<l;++i)point2.equals(points[i])&&(result=data[i])}return result}function move(point2,position,octree,octant,parent,depth){const children=octant.children;let result=null;if(octant.contains(point2,octree.getBias()))if(octant.contains(position,octree.getBias())){if(null!==children){++depth;for(let i=0,l=children.length;null===result&&i<l;++i){result=move(point2,position,octree,children[i],octant,depth)}}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i)if(point2.equals(points[i])){points[i].copy(position),result=data[i];break}}}else result=remove(point2,octree,octant,parent),set(position,result,octree,parent,depth-1);return result}function findNearestPoint(point2,maxDistance,skipSelf,octant){let result=null,bestDistance=maxDistance;if(null!==octant.children){const sortedChildren=octant.children.map(child=>{const octant2=child;return{distance:octant2.distanceToCenterSquared(point2),octant:octant2}}).sort((a2,b4)=>a2.distance-b4.distance);for(let i=0,l=sortedChildren.length;i<l;++i){const child=sortedChildren[i].octant;if(child.contains(point2,bestDistance)){const intermediateResult=findNearestPoint(point2,bestDistance,skipSelf,child);if(null!==intermediateResult&&(bestDistance=intermediateResult.distance,result=intermediateResult,0===bestDistance))break}}}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;let index2=-1;for(let i=0,l=points.length;i<l;++i)if(points[i].equals(point2)){if(!skipSelf){bestDistance=0,index2=i;break}}else{const distance2=point2.distanceTo(points[i]);distance2<bestDistance&&(bestDistance=distance2,index2=i)}index2>=0&&(result=new PointContainer(points[index2],data[index2],bestDistance))}return result}function findPoints(point2,radius,skipSelf,octant,result){const children=octant.children;if(null!==children)for(let i=0,l=children.length;i<l;++i){const child=children[i];child.contains(point2,radius)&&findPoints(point2,radius,skipSelf,child,result)}else if(null!==octant.data){const pointData=octant.data,points=pointData.points,data=pointData.data;for(let i=0,l=points.length;i<l;++i){const p2=points[i];if(p2.equals(point2))skipSelf||result.push(new PointContainer(p2.clone(),data[i],0));else{const rSq=radius*radius,dSq=p2.distanceToSquared(point2);dSq<=rSq&&result.push(new PointContainer(p2.clone(),data[i],Math.sqrt(dSq)))}}}}var PointOctree=class extends Octree{bias;maxPoints;maxDepth;constructor(min,max,bias=0,maxPoints=8,maxDepth=8){super(new PointOctant(min,max)),this.bias=Math.max(0,bias),this.maxPoints=Math.max(1,Math.round(maxPoints)),this.maxDepth=Math.max(0,Math.round(maxDepth))}getBias(){return this.bias}getMaxPoints(){return this.maxPoints}getMaxDepth(){return this.maxDepth}countPoints(octant=this.root){return countPoints(octant)}set(point2,data){return set(point2,data,this,this.root,0)}remove(point2){return remove(point2,this,this.root,null)}get(point2){return get(point2,this,this.root)}move(point2,position){return move(point2,position,this,this.root,null,0)}findNearestPoint(point2,maxDistance=Number.POSITIVE_INFINITY,skipSelf=!1){const result=findNearestPoint(point2,maxDistance,skipSelf,this.root);return null!==result&&null!==result.point&&(result.point=result.point.clone()),result}findPoints(point2,radius,skipSelf=!1){const result=[];return findPoints(point2,radius,skipSelf,this.root,result),result}raycast(raycaster){const result=[],octants=super.getIntersectingNodes(raycaster);if(octants.length>0)for(let i=0,l=octants.length;i<l;++i){const pointData=octants[i].data;null!==pointData&&pointData.testPoints(raycaster,result)}return result}};class PCSparseOctree{octree;bound;constructor(bound){this.octree=new PointOctree(bound.min,bound.max),this.bound=bound}insert(point2,data){this.octree.set(point2,data)}insertBatch(points,datas){if(points.length!==datas.length)throw new Error("Points and datas length mismatch");points.forEach((p2,i)=>{this.octree.set(p2,datas[i]??{})})}findNodeInOBB(queryOBB){const results=[],traverse=node=>{node&&(box3$1.set(node.min,node.max),queryOBB.intersectsBox3(box3$1)&&(node.data&&results.push(node),node.children?.forEach(child=>traverse(child))))};return traverse(this.octree.root),results}findPointsInOBB(queryOBB){const nodeList=this.findNodeInOBB(queryOBB),results=[];return nodeList.forEach(node=>{node.data?.points.forEach((point2,i)=>{queryOBB.containsPoint(point2)&&results.push({point:point2,data:node.data.data[i]})})}),results}findPointsByCircle(position,radius,skipSelf){return this.octree.findPoints(position,radius,skipSelf)}findNearestPoint(position,maxDistance,skipSelf){return this.octree.findNearestPoint(position,maxDistance,skipSelf)}findPointsInOBBBatch(obbList){return obbList.map(obb2=>this.findPointsInOBB(obb2))}static fromPoints(points){box3$1.setFromPoints(points);const octree=new PCSparseOctree(box3$1.clone());return octree.insertBatch(points,points.map((_,index2)=>({index:index2}))),octree}}const box3$1=new THREE.Box3,temp=new Vector3;function rectangleToLine(rectangle){const[l0,l1,l2,l3]=rectangle.toLines();return l0.length<l1.length?new LineSegment(l0.center,l2.center):new LineSegment(l1.center,l3.center)}function toCamelCase(str){return str.replace(/_([a-z])/g,(_,c)=>c.toUpperCase())}class Pipeline extends EventDispatcher{static defaultType="default";map=new ArrayMap;use(handlerOrType,func,tag){const defaultType=this.constructor.defaultType,handler="function"==typeof handlerOrType?{type:defaultType,handle:handlerOrType}:func?{type:handlerOrType,handle:func,tag:tag}:handlerOrType;return(Array.isArray(handler.type)?handler.type:[handler.type]).forEach(type=>this.map.append(type??defaultType,handler)),this}run(type,data,cache2){const ctx={type:type,data:data,cache:cache2??{}},list=this.map.get(type);if(!list)return data;this.dispatchEvent({type:"runStart",data:{type:type,context:ctx}});for(let i=0;i<list.length;i++){const handler=list[i];this.dispatchEvent({type:"handlerStart",data:{index:i,handler:handler,context:ctx}});const result=handler.handle(ctx);if(result instanceof Promise)throw new Error("当前管线存在异步任务,请使用异步执行 runAsync");if(void 0!==result&&(ctx.data=result),this.dispatchEvent({type:"handlerEnd",data:{index:i,handler:handler,context:ctx}}),ctx.stopped){this.dispatchEvent({type:"interrupt",data:{index:i,handler:handler,context:ctx}});break}}return this.dispatchEvent({type:"runEnd",data:{type:type,context:ctx}}),ctx.data}async runAsync(type,data,cache2){const ctx={type:type,data:data,cache:cache2??{}},list=this.map.get(type);if(!list)return data;this.dispatchEvent({type:"runStart",data:{type:type,context:ctx}});for(let i=0;i<list.length;i++){const handler=list[i];this.dispatchEvent({type:"handlerStart",data:{index:i,handler:handler,context:ctx}});const result=await handler.handle(ctx);if(void 0!==result&&(ctx.data=result),this.dispatchEvent({type:"handlerEnd",data:{index:i,handler:handler,context:ctx}}),ctx.stopped){this.dispatchEvent({type:"interrupt",data:{index:i,handler:handler,context:ctx}});break}}return this.dispatchEvent({type:"runEnd",data:{type:type,context:ctx}}),ctx.data}clear(){this.map.clear()}}class Feature{static getData(map){if(map)return map.get(this)?.data}static dependences=[];static run(line,opt,...arg){}static args(...args){const name=this.name,fn2=(...args2)=>this.run.apply(this,args2);return Object.defineProperty(fn2,"name",{value:name,configurable:!0}),Object.assign(fn2,{dependences:this.dependences,args:args,ontology:this})}static match(line,featureMatch,mode="every"){Array.isArray(featureMatch)||(featureMatch=[featureMatch]);let features=featureMatch;const list=features.map(key=>line.features?.get(key)).filter(v2=>!!v2);return"every"===mode&&list.length!==features.length||"some"===mode&&0===list.length?null:list}}class LineFreePoint extends Feature{constructor(mode){super(),this.mode=mode}static dependences=[];static run({start:start,end:end,line2D:line2D},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!start||!end||!line2D)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;let mode="none";1===queryTree.queryPoint(line2D.start,1e-4).length&&(mode="start"),1===queryTree.queryPoint(line2D.end,1e-4).length&&(mode="start"===mode?"all":"end"),"none"!==mode&&add(new LineFreePoint(mode))}}class FreePointRadiusNeighbor extends Feature{map=/* @__PURE__ */new Map;static intersection(m1,m2,radius){const map1=m1.map.get(radius),map2=m2.map.get(radius);if(!map1||!map2)return null;const result=/* @__PURE__ */new Map;for(const[key,value]of map1)map2.has(key)&&result.set(key,value);return result}static containLine(data,radius,line){const map=data.map.get(radius);return!!map&&map.has(line)}static dependences=[LineFreePoint];static run({line2D:line2D,features:features},{globalData:globalData,groupIndex:groupIndex,add:add},radius=.4){if(!line2D)return;const lineFreePointData=LineFreePoint.getData(features);if(!lineFreePointData)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const mode=lineFreePointData.mode,match=[["all","start"],["all","end"]],data=FreePointRadiusNeighbor.getData(features)??new FreePointRadiusNeighbor,map=/* @__PURE__ */new Map;line2D.points.forEach((point2,index2)=>{match[index2].includes(mode)&&queryTree.queryPoint(point2,radius).filter(line=>line!==line2D).forEach(line=>{map.set(line,{line:line,point:point2,isStart:0===index2})})}),map.size&&(data.map.set(radius,map),add(data))}static args(radius){return super.args(radius)}}class VoxelStatistic{voxelSize;voxelMap=new SetMap;lineVoxelSetLists;neighbors;constructor(lines,voxelSize=.083){this.voxelSize=voxelSize,this.lineVoxelSetLists=lines.map((line,i)=>{const setList=/* @__PURE__ */new Set,counterMap=new CounterMap;for(let j=0;j<line.originalPoints.length;j++){const point2=line.originalPoints[j],key=`${Math.floor(point2.x/voxelSize)},${Math.floor(point2.y/voxelSize)},${Math.floor(point2.z/voxelSize)}`;this.voxelMap.append(key,i),counterMap.increment(key,1),setList.add(key)}return[setList,counterMap]}),this.neighbors=Array.from({length:this.lineVoxelSetLists.length},()=>/* @__PURE__ */new Set),this.lineVoxelSetLists.forEach(([setList],i)=>{const result=this.neighbors[i];setList.forEach(key=>{this.voxelMap.get(key).forEach(v2=>result.add(v2))})})}getNeighbors(indices){const result=/* @__PURE__ */new Set;for(const index2 of indices)this.neighbors[index2].forEach(v2=>{result.add(v2)});return indices.forEach(v2=>result.delete(v2)),[...result]}getVoxels(indices,out=new CounterMap){out.clear();for(const index2 of indices){const[setList,counterMap]=this.lineVoxelSetLists[index2];setList.forEach(key=>{const count=counterMap.get(key)??0;out.increment(key,count)})}return out}createPipeline(index2){const indices=[index2],set2=this.getVoxels(indices),out=new CounterMap;return{getIntersectRatio:indices2=>{const list=this.getVoxels(indices2,out),size1=set2.getAllCount(),size2=list.getAllCount(),large=size1<size2?list:set2;let intersect=0;return(size1<size2?set2:list).forEach((count1,key)=>{const count2=large.get(key);count2&&(intersect+=Math.min(count1,count2))}),intersect/Math.max(1,Math.min(size1,size2))},add:indices2=>{this.getVoxels(indices2,out).forEach((count,key)=>{set2.increment(key,count)}),indices.push(...indices2)},getIndices:()=>indices}}}const delta=new Vector3,covMatrix=new Matrix3,vec3$2=new Vector3;class PointCloud3View{constructor(points){this.points=points}set(points){this.points=points}forEach(fun){if(Array.isArray(this.points))this.points.forEach(fun);else{let index2=0;for(let i=0;i<this.points.list.length;i++)for(let j=0;j<this.points.list[i].length;j++){fun(this.points.list[i][j],index2),index2++}}}*[Symbol.iterator](){const traverse=function*(value){if(Array.isArray(value))for(const item of value)yield*traverse(item);else yield value};yield*traverse(this.points)}get length(){if(Array.isArray(this.points))return this.points.length;let count=0;for(let i=0;i<this.points.list.length;i++)count+=this.points.list[i].length;return count}}function pointCloud3FitLine2(points){const pointView=new PointCloud3View(points),centroid2=new Vector3;pointView.forEach(p2=>centroid2.add(p2)),centroid2.divideScalar(pointView.length);let xx=0,xy=0,yy=0;pointView.forEach(p2=>{delta.subVectors(p2,centroid2),xx+=delta.x*delta.x,xy+=delta.x*delta.y,yy+=delta.y*delta.y}),covMatrix.set(xx,xy,0,xy,yy,0,0,0,0);let direction=new Vector3(1,0,0);for(let i=0;i<20;i++){const temp2=direction.clone().applyMatrix3(covMatrix).normalize();if(temp2.distanceToSquared(direction)<1e-10)break;direction=temp2}let minProj=1/0,maxProj=-1/0;pointView.forEach(p2=>{const projection=vec3$2.subVectors(p2,centroid2).dot(direction);projection<minProj&&(minProj=projection),projection>maxProj&&(maxProj=projection)});const start=centroid2.clone().add(direction.clone().multiplyScalar(minProj)),end=centroid2.clone().add(direction.clone().multiplyScalar(maxProj));return{direction:direction,start:start,end:end,get length(){return end.distanceTo(start)}}}class PcLineSegmentEvaluation{distances;dx=0;dy=0;lengthSquared=0;start;end;points;constructor(start,end,points){start&&end&&points&&this.set(start,end,points)}set(start,end,points){const dx=end.x-start.x,dy=end.y-start.y,lengthSquared=dx*dx+dy*dy;this.dx=dx,this.dy=dy,this.lengthSquared=lengthSquared;const distances=[];for(const point2 of points){let t2=((point2.x-start.x)*dx+(point2.y-start.y)*dy)/lengthSquared;t2=Math.max(0,Math.min(1,t2));const nearestX=start.x+t2*dx,nearestY=start.y+t2*dy,errorX=point2.x-nearestX,errorY=point2.y-nearestY;distances.push({t:t2,distance:Math.sqrt(errorX*errorX+errorY*errorY)})}this.distances=distances,this.start=start,this.end=end,this.points=points}rmse(){const dx=this.dx,dy=this.dy;if(0===this.lengthSquared){let squaredError2=0;for(const point2 of this.points){const px=point2.x-this.start.x,py=point2.y-this.start.y;squaredError2+=px*px+py*py}return Math.sqrt(squaredError2/this.points.length)}let squaredError=0,i=0;for(const point2 of this.points){let t2=this.distances[i].t;const nearestX=this.start.x+t2*dx,nearestY=this.start.y+t2*dy,errorX=point2.x-nearestX,errorY=point2.y-nearestY;squaredError+=errorX*errorX+errorY*errorY,i++}const mse=squaredError/this.points.length;return Math.sqrt(mse)}lengthWeightedRmse(binCount=100){const distances=this.distances;if(!distances.length||0===this.lengthSquared)return this.rmse();const sum2=new Float64Array(binCount),count=new Uint32Array(binCount);for(const item of distances){let index2=Math.floor(item.t*binCount);index2>=binCount&&(index2=binCount-1),sum2[index2]+=item.distance*item.distance,count[index2]++}let error=0,validBins=0;for(let i=0;i<binCount;i++)0!==count[i]&&(error+=sum2[i]/count[i],validBins++);return validBins?Math.sqrt(error/validBins):0}medianDistance(){const list=this.distances.map(item=>item.distance).sort((a2,b4)=>a2-b4),n=list.length;if(0===n)return 0;const mid=Math.floor(n/2);return n%2==1?list[mid]:(list[mid-1]+list[mid])/2}spatialOccupancyD2(gridSize){if(gridSize<=0)return 0;const dx=this.end.x-this.start.x,dy=this.end.y-this.start.y,length=Math.hypot(dx,dy);if(0===length||!this.points.length)return 0;const ux=dx/length,uy=dy/length,vx=-uy,vy=ux;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(const point2 of this.points){const x=point2.x*ux+point2.y*uy,y=point2.x*vx+point2.y*vy;x<minX&&(minX=x),x>maxX&&(maxX=x),y<minY&&(minY=y),y>maxY&&(maxY=y)}const width=maxX-minX,height=maxY-minY;if(width<=0||height<=0)return 0;const gridWidth=Math.ceil(width/gridSize),totalGridCount=gridWidth*Math.ceil(height/gridSize),grid=/* @__PURE__ */new Set;for(const point2 of this.points){const x=Math.floor((point2.x*ux+point2.y*uy-minX)/gridSize),y=Math.floor((point2.x*vx+point2.y*vy-minY)/gridSize);grid.add(y*gridWidth+x)}return grid.size/totalGridCount}}const vec3$1=new Vector3,up=new THREE.Vector3(0,0,1),line3=new THREE.Line3;function pointToLineDistanceSqFast(line,point2){line3.set(line.start,line.end);const projected=vec3$1;return line3.closestPointToPoint(point2,!1,projected),point2.distanceToSquared(projected)}const pool=LineSegmentUtils.createPool();class PointCloudLineMerger{constructor(data,opt={}){this.data=data,this.data=data,this.option=opt}averagePz=0;option;cache=/* @__PURE__ */new Map;static mergeLinePoints3d(indices,lines){let count=0;for(let i=0;i<indices.length;i++){count+=lines[indices[i]].originalPoints.length}const originalPoints=new Array(count);let offset=0;for(let i=0;i<indices.length;i++){const p2=lines[indices[i]].originalPoints;for(let j=0;j<p2.length;j++)originalPoints[offset++]=p2[j]}return{originalPoints:originalPoints}}fitLine3D2(points,key){let line=this.cache.get(key);if(!line){const info=pointCloud3FitLine2(points);info.start.z=this.averagePz,info.end.z=this.averagePz,line=Object.assign(info,{finalAvaregN:(new THREE.Vector3).crossVectors(info.direction,up).normalize()}),this.cache.set(key,line)}return line}canMerge(lineA,lineB,ratio){const dot=Math.abs(lineA.direction.dot(lineB.direction)),parallelThreshold=this.option.parallel?.threshold??.98,overlapThreshold=this.option.parallel?.overlapThreshold??1e-4,maxDistance=this.option.parallel?.maxDistance??.03;if(dot>parallelThreshold){if(ratio<overlapThreshold)return!1;const distanceSq=maxDistance*maxDistance;if(pointToLineDistanceSqFast(lineA,lineB.start)<distanceSq||pointToLineDistanceSqFast(lineA,lineB.end)<distanceSq||pointToLineDistanceSqFast(lineB,lineA.start)<distanceSq||pointToLineDistanceSqFast(lineB,lineA.end)<distanceSq)return!0;for(let t2=.3;t2<=.9;t2+=.3){if(pointToLineDistanceSqFast(lineA,(new Vector3).lerpVectors(lineB.start,lineB.end,t2))<distanceSq)return!0}return!1}const line1=pool.line.copy(lineA),line2=pool.line.copy(lineB);if(line1.intersectLineSegment(line2))return ratio>(this.option.intersectOverlap??.5);return ratio>(this.option.directMergeOverlap??.9)}merge(lines){const pcLineSegmentEvaluation=new PcLineSegmentEvaluation;lines.forEach(line=>{const originalPoints=line.originalPoints;let iLine2d=this.fitLine3D2(originalPoints,-1);pcLineSegmentEvaluation.set(iLine2d.start,iLine2d.end,originalPoints);const distances=pcLineSegmentEvaluation.distances.map(item=>item.distance).sort((a2,b4)=>a2-b4),maxDistance=distances[Math.floor(.9*distances.length)];line.originalPoints=originalPoints.filter((_,i)=>pcLineSegmentEvaluation.distances[i].distance<=maxDistance)}),lines.sort((a2,b4)=>b4.originalPoints.length-a2.originalPoints.length);const voxelStatistic=new VoxelStatistic(lines,this.option.voxelSize??.083),merged=/* @__PURE__ */new Set,results=[];for(let i=0;i<lines.length;i++){if(merged.has(i))continue;merged.add(i);const queue=voxelStatistic.getNeighbors([i]);let iLine2d=this.fitLine3D2(lines[i].originalPoints,i);const pipeline=voxelStatistic.createPipeline(i),jump=/* @__PURE__ */new Set;let index2;for(;void 0!==(index2=queue.pop());){if(merged.has(index2)||jump.has(index2))continue;const ratio=pipeline.getIntersectRatio([index2]),jLine2d=this.fitLine3D2(lines[index2].originalPoints,index2);if(this.canMerge(iLine2d,jLine2d,ratio)){merged.add(index2),pipeline.add([index2]);const indices2=pipeline.getIndices();queue.push(...voxelStatistic.getNeighbors([index2]).filter(index22=>!merged.has(index22))),iLine2d=this.fitLine3D2({list:indices2.map(i2=>lines[i2].originalPoints)},indices2.join("-"))}else jump.add(index2)}const indices=pipeline.getIndices();results.push({...PointCloudLineMerger.mergeLinePoints3d(indices,lines),...iLine2d})}return results}}function every(list=[]){return(matchLine1,matchLine2,match1,match2)=>list.every(fun=>fun(matchLine1,matchLine2,match1,match2))}function some(list=[]){return(matchLine1,matchLine2,match1,match2)=>list.some(fun=>fun(matchLine1,matchLine2,match1,match2))}function freePointIncludesNeighbor(line1,line2,_match1,_match2){const m1=FreePointRadiusNeighbor.getData(line1.features),m2=FreePointRadiusNeighbor.getData(line2.features);return!(!m1||!m2)&&(FreePointRadiusNeighbor.containLine(m1,.4,line2.line2D)&&FreePointRadiusNeighbor.containLine(m2,.4,line1.line2D))}function isParallel(l1,l2){return l1.line2D.isParallelTo(l2.line2D,1)}function isOpposition(l1,l2,_match1,_match2){const m1=FreePointRadiusNeighbor.getData(l1.features),m2=FreePointRadiusNeighbor.getData(l2.features);if(!m1||!m2)return!1;const list1=m1.map.get(.4),list2=m2.map.get(.4);if(!list1||!list2)return!1;let point1,point2;for(const[targetLine,opt]of list1)if(targetLine===l2.line2D){point1=opt.point;break}for(const[targetLine,opt]of list2)if(targetLine===l1.line2D){point2=opt.point;break}if(!point1||!point2)return!1;const point12=l1.line2D.getAnotherPoint(point1),point22=l2.line2D.getAnotherPoint(point2),dist1=point1.distanceSquared(point2),dist2=point1.distanceSquared(point22),dist3=point12.distanceSquared(point2),dist4=point12.distanceSquared(point22);let near1,near2;dist1<=dist2&&dist1<=dist3&&dist1<=dist4?(near1=point1,near2=point2):dist2<=dist3&&dist2<=dist4?(near1=point1,near2=point22):dist3<=dist4?(near1=point12,near2=point2):(near1=point12,near2=point22);const dir1=near1===point1?point1.directionFrom(point12):point12.directionFrom(point1),dir2=near2===point2?point2.directionFrom(point22):point22.directionFrom(point2);return dir1.dot(dir2)<-Math.cos(Math.PI/45)}const conditions={isParallel:isParallel,isOpposition:isOpposition,freePointIncludesNeighbor:freePointIncludesNeighbor,every:every,some:some},FeatureMerge=Object.assign(function(feature1,feature2,fun){function handle(data){const unionFindSet=new UnionFindSet(data.length);for(let j=0;j<data.length;j++){const line1=data[j],match1=Feature.match(line1,feature1),match2=Feature.match(line1,feature2);if(match1||match2)for(let k=j+1;k<data.length;k++){const line2=data[k],match3=Feature.match(line2,feature2);if(match1&&match3&&fun(line1,line2,match1,match3)){unionFindSet.union(j,k);continue}const match4=Feature.match(line2,feature1);match4&&match2&&fun(line2,line1,match4,match2)&&unionFindSet.union(j,k)}}return unionFindSet.getAllSets().map(list=>{if(1===list.length)return data[list[0]];const{originalPoints:originalPoints}=PointCloudLineMerger.mergeLinePoints3d(list,data);return{...pointCloud3FitLine2(originalPoints),originalPoints:originalPoints}})}return pipeline=>{pipeline.use({tag:"FeatureMerge",handle:ctx=>{const data=ctx.data;for(let i=0;i<data.length;i++)data[i]=handle(data[i]);return data}})}},{conditions:conditions});function FormatConversion(pipeline){pipeline.use({tag:"FormatConversion",handle:ctx=>ctx.data.map(data=>data.map(lineItems=>{const points=new Array(lineItems.length),originalPoints=new Array(lineItems.length);return lineItems.forEach((item,i)=>{points[i]={...item.p},originalPoints[i]={...item.originalP}}),{points:points,originalPoints:originalPoints}}))})}function Merge(opt){return pipeline=>{pipeline.use({tag:"Merge",handle:ctx=>[new PointCloudLineMerger([],opt).merge(ctx.data.flatMap(list=>list.map(({originalPoints:originalPoints})=>({originalPoints:originalPoints,points:[]}))))]})}}function getValue(data,key){let value=data;for(const name of key.split(".")){if(null==value)return;value=value[name]}return value}function forEachDimension(data,dimension,callback){Array.isArray(data)&&(dimension<0||(1!==dimension?data.forEach(item=>{forEachDimension(item,dimension-1,callback)}):data.forEach(callback)))}function getColor$1(color){return"number"==typeof color?color:color()}function RenderPointCloud({key:key="data",dimension:dimension=2,color:color=()=>randomColor(),pointCloud:pointCloud=!0,line:line=!0,offset:offset=new THREE.Vector3}={}){return pipeline=>{pipeline.use({tag:"RenderPointCloud",handle(ctx){if(!ctx.cache.scene)return;const scene=ctx.cache.scene,data=getValue(ctx,key),group2=new THREE.Group;group2.position.add(offset),scene.add(group2);const linePos=[];if(forEachDimension(data,dimension,pcline=>{const{originalPoints:originalPoints,start:start,end:end,line2D:line2D}=pcline;if(line){(line2D??new LineSegment(start,end)).points.forEach(p2=>linePos.push(p2.x,p2.y,0))}if(!pointCloud)return;const array=originalPoints.flatMap(p2=>[p2.x,p2.y,p2.z]),buffer=new THREE.BufferGeometry;buffer.setAttribute("position",new THREE.BufferAttribute(new Float32Array(array),3));const pointsMesh=new THREE.Points(buffer,new THREE.PointsMaterial({size:2,sizeAttenuation:!1,color:getColor$1(color)}));pointsMesh.position.z=.4,group2.add(pointsMesh)}),linePos.length){const buffer=new THREE.BufferGeometry;buffer.setAttribute("position",new THREE.BufferAttribute(new Float32Array(linePos),3));const line3d=new THREE.LineSegments(buffer,new THREE.LineBasicMaterial({color:16777215}));group2.add(line3d)}}})}}function TimeLog(pipeline){function addLog(...msg){console.log(...msg)}let time=0,runTime=0;pipeline.addEventListener(EventDispatcher.EVENT_TRIGGER,e=>{switch(e.event.type){case"runStart":runTime=performance.now();break;case"runEnd":addLog("总运行时间:",(performance.now()-runTime).toFixed(4),"ms");break;case"handlerStart":time=performance.now(),addLog(`${e.event.data?.handler?.tag??e.event.data.index}. 开始执行...`);break;case"handlerEnd":addLog(`${e.event.data?.handler?.tag??e.event.data.index}. 执行时间:${(performance.now()-time).toFixed(4)}ms`);break;case"interrupt":addLog("已中断")}})}const index$7=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ComputeBox3:function(pipeline){pipeline.use({tag:"ComputeBox3",handle(ctx){const box3s=ctx.cache.box3s??[],point2=new THREE.Vector3;ctx.data.forEach((list,i)=>{const box32=box3s[i]??new THREE.Box3;box32.makeEmpty(),list.forEach(line=>{line.originalPoints.forEach(p2=>{box32.expandByPoint(point2.set(p2.x,p2.y,p2.z))})}),box3s[i]=box32}),ctx.cache.box3s=box3s}})},FeatureExtraction:function(funs){return pipeline=>{pipeline.use({tag:"FeatureExtraction",handle:ctx=>function(lines,data){const list2=data.filterRemoveLine??[],visited=data.Features??/* @__PURE__ */new Set;data.Features=visited,data.filterRemoveLine=list2;for(let i=0;i<funs.length;i++){const fun=funs[i],dependences=fun?.dependences??[];if(0!==dependences.length){const list=dependences.filter(dependence=>!visited.has(dependence));if(0!==list.length)throw new Error(`${fun.name}特性 需要依赖前置特性:${list.map(item=>item.name).join(" | ")}`)}visited.add(fun?.ontology??fun)}lines.forEach((list,groupIndex)=>{list.map((pcLine,index2)=>{const feature2=pcLine.features??/* @__PURE__ */new Map;pcLine.features=feature2,funs.forEach(fun=>{const opt={add(feat){feat instanceof Feature?feature2.set(feat.constructor,{type:feat.constructor,data:feat}):feature2.set(feat.type,feat)},globalData:data,group:list,groupIndex:groupIndex,index:index2};"run"in fun&&"function"==typeof fun.run?fun.run(pcLine,opt):"function"==typeof fun&&fun(pcLine,opt,...fun?.args??[])})})})}(ctx.data,ctx.cache)})}},FeatureFilter:function(filters,removeSaveName="filterRemoveLine",noFeatureResult=!0){return pipeline=>{pipeline.use({tag:"FeatureFilter",handle:ctx=>function(data,cache2){const list2=cache2[removeSaveName]??[];return cache2[removeSaveName]=list2,data.map(list=>list.filter(pcLine=>{if(!pcLine.features)return noFeatureResult;for(let{feature:condition,fun:fun}of filters){const list3=Feature.match(pcLine,condition);if(list3&&!fun(list3,pcLine))return list2.push(pcLine),!1}return!0}))}(ctx.data,ctx.cache)})}},FeatureMerge:FeatureMerge,FeaturePrint:function(pipeline){pipeline.use({tag:"FeaturePrint",handle(ctx){ctx.data.forEach((list,groupIndex)=>list.forEach(({features:features},index2)=>{features&&(console.log(groupIndex,index2),[...features.values()].map(item=>{console.log("string"==typeof item.type?item.type:item.type?.name)}))}))}})},FormatConversion:FormatConversion,Merge:Merge,QueryTree:function(pipeline){pipeline.use({tag:"QueryTree",handle(ctx){ctx.cache.lineQueryTrees=[],ctx.cache.pointQueryTrees=[],ctx.data.forEach(pcLines=>{const tree=new LineSegmentSpatialHash,pointTree=new PointSpatialHash;pcLines.forEach(pcLine=>{const line=new LineSegment(pcLine.start,pcLine.end);tree.insert(line),pointTree.insert(line.start,line).insert(line.end,line),pcLine.line2D=line}),ctx.cache.lineQueryTrees?.push(tree),ctx.cache.pointQueryTrees?.push(pointTree)})}})},RenderPointCloud:RenderPointCloud,Slice:function(start,end){return pipeline=>{pipeline.use({tag:"Slice",handle:ctx=>ctx.data.map(data=>data.splice(start,end))})}},TimeLog:TimeLog,VoxelStatistics:function(voxelSize){return pipeline=>{pipeline.use({tag:"VoxelStatistics",handle(ctx){ctx.cache.voxelStatistics=[],ctx.data.forEach(pcLines=>{ctx.cache.voxelStatistics?.push(new VoxelStatistic(pcLines,voxelSize))})}})}},every:every,forEachDimension:forEachDimension,freePointIncludesNeighbor:freePointIncludesNeighbor,getValue:getValue,isOpposition:isOpposition,isParallel:isParallel,some:some},Symbol.toStringTag,{value:"Module"}));class PointCloudPipeline extends Pipeline{static defaultType="handle";async start(data,cache2){return await this.runAsync(PointCloudPipeline.defaultType,data,cache2)}usePlugin(plugin){return plugin(this),this}static template(){return(new PointCloudPipeline).usePlugin(FormatConversion).usePlugin(TimeLog).usePlugin(Merge({voxelSize:.083,parallel:{threshold:.98,overlapThreshold:1e-4,maxDistance:.02},directMergeOverlap:.8,intersectOverlap:.6})).usePlugin(RenderPointCloud({pointCloud:!0}))}}const queryLine=new LineSegment;class FreePointDirectionNeighbor extends Feature{constructor(list){super(),this.list=list}static run({line2D:line2D,features:features},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!line2D)return;const feature2=LineFreePoint.getData(features);if(!feature2)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const mode=feature2.mode,match=[["all","start"],["all","end"]],list=[];line2D.points.forEach((point2,index2)=>{if(!match[index2].includes(mode))return;const other=line2D.getAnotherPoint(point2),direct=point2.directionFrom(other);point2.expandAsLine(direct,.2,void 0,queryLine),queryTree.queryLine(queryLine).filter(line=>line!==line2D).forEach(line=>{const intersectPoint=line2D.getIntersection(line);intersectPoint&&list.push({intersectPoint:intersectPoint,line:line,angle:line.angle(line2D,{unit:"degree",range:"180"}),distanceSq:intersectPoint.distanceSquared(point2),point:point2,isStart:0===index2})})}),list.length&&(list.sort((a2,b4)=>a2.distanceSq-b4.distanceSq),add(new FreePointDirectionNeighbor(list)))}}class IntersectionPoint extends Feature{constructor(list){super(),this.list=list}static run({start:start,end:end,line2D:line2D},{globalData:globalData,groupIndex:groupIndex,add:add}){if(!start||!end||!line2D)return;const queryTree=globalData.lineQueryTrees?.[groupIndex];if(!queryTree)return;const list=queryTree.queryLine(line2D).filter(line=>line!==line2D).map(line=>{const intersectPoint=line.getIntersection(line2D);if(intersectPoint)return{line:line,intersectPoint:intersectPoint}}).filter(r2=>!!r2);list.length&&add(new IntersectionPoint(list))}}class IsolateLine extends Feature{static dependences=[LineFreePoint,IntersectionPoint];static run({features:features},{add:add}){const freePointData=LineFreePoint.getData(features);if(!freePointData)return;if("all"!==freePointData.mode)return;IntersectionPoint.getData(features)||add(new IsolateLine)}}class NearestEndpointIntersection extends Feature{constructor(start,end){super(),this.start=start,this.end=end}static run({features:features,line2D:line2D},{add:add}){if(!line2D)return;const feature2=IntersectionPoint.getData(features);if(!feature2)return;const ppv=feature2.list.map(({intersectPoint:intersectPoint})=>line2D.projectPointValue(intersectPoint)).sort((a2,b4)=>a2-b4);add(new NearestEndpointIntersection(ppv[0],ppv[ppv.length-1]))}}class PhagocyticRate extends Feature{constructor(value){super(),this.value=value}static dependences=[];static run({},{globalData:globalData,groupIndex:groupIndex,index:index2,add:add}){const voxelStatistic=globalData.voxelStatistics?.[groupIndex];if(!voxelStatistic)return;const neighbors=voxelStatistic.getNeighbors([index2]),ratio=voxelStatistic.createPipeline(index2).getIntersectRatio(neighbors);add(new PhagocyticRate(ratio))}}const vec3=new Vector3;class PointCloudLineBox3 extends Feature{constructor(box32,size2){super(),this.box3=box32,this.size=size2}static run({originalPoints:originalPoints},{add:add}){if(!originalPoints.length)return;const box32=new Box3;for(const point2 of originalPoints)box32.expandByPoint(vec3.set(point2.x,point2.y,point2.z));add(new PointCloudLineBox3(box32,box32.getSize(new Vector3)))}}class PointCloudsCount extends Feature{constructor(count){super(),this.count=count}static run(line,{add:add}){add(new PointCloudsCount(line.originalPoints.length))}}class PointCloudsLineLength extends Feature{constructor(length){super(),this.length=length}static run(line,{add:add}){add(new PointCloudsLineLength(line.start.distanceTo(line.end)))}}class PointCloudsMSE extends Feature{constructor(value){super(),this.value=value}static run({start:start,end:end,originalPoints:originalPoints},{add:add}){if(!start||!end)return;const mse=new PcLineSegmentEvaluation(start,end,originalPoints).rmse();add(new PointCloudsMSE(mse))}}const index$5={PointCloudLineBox3:PointCloudLineBox3,PointCloudsCount:PointCloudsCount,PointCloudsLineLength:PointCloudsLineLength,PointCloudsMSE:PointCloudsMSE,IntersectionPoint:IntersectionPoint,LineFreePoint:LineFreePoint,FreePointDirectionNeighbor:FreePointDirectionNeighbor,FreePointRadiusNeighbor:FreePointRadiusNeighbor,NearestEndpointIntersection:NearestEndpointIntersection,IsolateLine:IsolateLine,PhagocyticRate:PhagocyticRate},index$6=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:index$5},Symbol.toStringTag,{value:"Module"})),index$4=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,PointCloudPipeline:PointCloudPipeline,features:index$6,plugins:index$7},Symbol.toStringTag,{value:"Module"})),load=lazy(()=>init$1());async function dxfToDwgByBlob(blob){await load.value;const data=await dxf_to_dwg(new Uint8Array(await blob.arrayBuffer()));return new Blob([new Uint8Array(data)])}const index$3=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ArrayMap:ArrayMap,Box2:Box2,CheckPointCloudContinuity:class{static continuity(ts2,len,gridSize=.02,ratio=.6){if(ts2.length<2)return!1;const voxels=/* @__PURE__ */new Set;let min=1/0,max=-1/0;for(let i2=0;i2<ts2.length;i2++){const dist=ts2[i2]*len,voxel=Math.floor(dist/gridSize);voxels.add(voxel),min=Math.min(min,voxel),max=Math.max(max,voxel)}const values=[...voxels].sort((a2,b4)=>a2-b4);let start=values[0],i=0;const ranges=[];for(i=1;i<values.length;i++){const pre=values[i-1],v2=values[i];v2-pre>2&&(ranges.push([start,pre]),start=v2)}ranges.push([start,values[values.length-1]]);return!(ranges.reduce((sum2,[start2,end])=>sum2+(end-start2+1),0)/(max-min+1)<ratio)}static checkByProjectionContinuity(points,opt){let{ratio:ratio=.6,gridSize:gridSize=.02,axisLine:axisLine}=opt??{};if(axisLine)axisLine instanceof LineSegment||(axisLine=new LineSegment(Point.from(axisLine.start),Point.from(axisLine.end)));else{axisLine=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}const xline=axisLine,start=new Vector3,end=new Vector3;start.set(xline.start.x,xline.start.y,0),end.set(xline.end.x,xline.end.y,0);const xts=this.projectPoint(points,start,end);if(!this.continuity(xts,xline.length,gridSize,ratio))return!1;const yline2=xline.clone().rotate(.5*Math.PI);start.set(yline2.start.x,yline2.start.y,0),end.set(yline2.end.x,yline2.end.y,0);const yts=this.projectPoint(points,start,end);if(!this.continuity(yts,yline2.length,gridSize,ratio))return!1;const center=xline.center.clone();start.set(center.x,center.y,10),end.set(center.x,center.y,-10);const zts=this.projectPoint(points,start,end);return!!this.continuity(zts,20,gridSize,ratio)}static checkByVoxelDensity(points,opt){let{gridSize:gridSize=.08,xRatio:xRatio=.5,yRatio:yRatio=.4,overallRatio:overallRatio=.5,axisLine:axisLine}=opt??{};if(axisLine)axisLine instanceof LineSegment||(axisLine=new LineSegment(Point.from(axisLine.start),Point.from(axisLine.end)));else{axisLine=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}let xline=axisLine;if(!xline){xline=rectangleToLine(new Polygon(points.map(p2=>new Point(p2.x,p2.y))).toRectangle())}const dir=xline.direction(),angle=Math.atan2(dir.y,dir.x),center=xline.center,cos=Math.cos(-angle),sin=Math.sin(-angle),voxelizationPoints=[],xMap=new CounterMap,yMap=new CounterMap,occupied=/* @__PURE__ */new Set;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;points.forEach(p2=>{const dx=p2.x-center.x,dy=p2.y-center.y,x=Math.floor((dx*cos-dy*sin)/gridSize),y=Math.floor(p2.z/gridSize),key=BigInt(x)<<32n|0xffffffffn&BigInt(y);occupied.has(key)||(occupied.add(key),xMap.increment(x,1),yMap.increment(y,1),voxelizationPoints.push(x,y),minX=Math.min(minX,x),minY=Math.min(minY,y),maxX=Math.max(maxX,x),maxY=Math.max(maxY,y))});const xRange=maxX-minX+1,yRange=maxY-minY+1;let satisfyQuantity=0;for(let i=0;i<voxelizationPoints.length;i+=2){const x=voxelizationPoints[i],y=voxelizationPoints[i+1],xCount=xMap.get(x),yCount=yMap.get(y);xCount/yRange>xRatio&&yCount/xRange>yRatio&&satisfyQuantity++}return satisfyQuantity/(voxelizationPoints.length/2)>overallRatio}static projectPoint(points,start,end){const point2=new Vector3,dir=end.clone().sub(start);return points.map(p2=>(point2.copy(p2),function(point2,start,_end,dir){const len2=dir.lengthSq();if(len2<1e-12)return 0;temp.copy(point2);let t2=temp.sub(start).dot(dir)/len2;return t2=Math.max(0,Math.min(1,t2)),t2}(point2,start,0,dir)))}},CommandFlow:CommandFlow,CommandManager:CommandManager,Component:Component,ComponentContainer:ComponentContainer,CounterMap:CounterMap,EventDispatcher:EventDispatcher,GltfInit:GltfInit,LineDashed:LineDashed,LineIndexGenerator:LineIndexGenerator,LineSegment:LineSegment,LineSegmentUndirectedGraph:LineSegmentUndirectedGraph,LineSegmentUtils:LineSegmentUtils,Lines:Lines,MapEnhance:MapEnhance,MaxiCircles:MaxiCircles,MiniCircles:MiniCircles,OBB:OBB2,PCSparseOctree:PCSparseOctree,PcLineSegmentEvaluation:PcLineSegmentEvaluation,Point:Point,PointSpatialHash:PointSpatialHash,PointUtils:PointUtils,Polygon:Polygon,Quadtree:Quadtree,Rectangle:Rectangle,SelectLocalFile:SelectLocalFile,SetMap:SetMap,Side:Side,SnapLine:class{nearestPointCluster(lineDatas,referenceLineData){const referenceLines=[],referenceLinesScope=[];for(let i=0;i<referenceLineData.length;i++){const item=referenceLineData[i],points=item.originalPoints.map(p2=>Point.from(p2)),rectangle=new Polygon(points).toRectangle(),line=new LineSegment(Point.from(item.start),Point.from(item.end));referenceLines.push(line),referenceLinesScope.push(rectangle)}const lines=[],linesScope=[];for(let i=0;i<lineDatas.length;i++){const element=lineDatas[i],points=element.originalPoints.map(item=>Point.from(item)),rectangle=new Polygon(points).toRectangle(),line=new LineSegment(Point.from(element.start),Point.from(element.end));lines.push(line),linesScope.push(rectangle)}const results=LineSegmentUtils.findBestReferenceSegment({lines:lines,linesScope:linesScope,referenceLines:referenceLines,referenceLinesScope:referenceLinesScope});for(let i=0;i<results.length;i++){const result=results[i];result&&(lineDatas[i].start=result.start.toJson2D(),lineDatas[i].end=result.end.toJson2D())}return lineDatas}},UndirectedGraph:UndirectedGraph,UnionFindSet:UnionFindSet,cloneUserData:cloneUserData,dxfToDwgByBlob:dxfToDwgByBlob,gltf:gltf,pointCloundPipeline:index$4,toCamelCase:toCamelCase,uuid:uuid},Symbol.toStringTag,{value:"Module"}));class LineGroupType{static get(line){const group2=[];return void 0!==line.userData.groupId&&group2.push({id:line.userData.groupId,type:line.userData.groupType}),line.userData?.groups?.forEach(item=>group2.push({id:item.id,type:item.type})),group2}static set(line,id,type,repeat=!1){if(!(this.hasId(line,id)||!repeat&&this.hasType(line,type))){if(void 0===line.userData.groupId)return line.userData.groupId=id,void(line.userData.groupType=type);void 0===line.userData.groups&&(line.userData.groups=[]),line.userData?.groups?.push({id:id,type:type})}}static getIdByType(line,type){return line.userData.groupType==type?line.userData.groupId:line.userData?.groups?.find(item=>item.type===type)?.id}static getIdsByType(line,type){const ids=[];return line.userData.groupType==type&&ids.push(line.userData.groupId),line.userData?.groups?.forEach(group2=>{group2.type===type&&ids.push(group2.id)}),ids}static getGroupsByType(lines,type,remainingLines=[]){const list=lines.reduce((map,line)=>{const ids=LineGroupType.getIdsByType(line,type);return ids&&ids.length?ids.forEach(id=>map.append(id,line)):remainingLines.push(line),map},new ArrayMap).valueArray;return Object.defineProperty(list,"remainingLines",{value:remainingLines}),list}static getGroupById(lines,id){return lines.filter(line=>this.hasId(line,id))}static replace(line,id,type){if(line.userData.groupId===id)return line.userData.groupType=type,!0;if(line.userData.groupType===type)return line.userData.groupId=id,!0;if(line.userData.groups)for(let i=0;i<line.userData.groups.length;i++){const group2=line.userData.groups[i];if(group2.id===id)return group2.type=type,!0;if(group2.type===type)return group2.id=id,!0}return!1}static hasGroup(line){return!(void 0===line.userData.groupId&&!line.userData.groups?.length)}static hasId(line,id){return void 0!==line.userData.groupId&&line.userData.groupId===id||line.userData?.groups?.some(item=>item.id===id)}static hasType(line,type){return void 0!==line.userData.groupType&&line.userData.groupType===type||!!line.userData?.groups?.some(item=>item.type===type)}static hasTypes(line,types){return types.every(type=>this.hasType(line,type))}static everyType(lines,type){return!(!lines||0===lines.length)&&lines.every(line=>this.hasType(line,type))}static getIntersectionTypes(lines){const countMap=new CounterMap;lines.forEach(line=>{line.userData.groups&&line.userData.groups.forEach(group2=>countMap.set(group2.type)),line.userData.groupType&&countMap.increment(line.userData.groupType)});const types=[];return countMap.forEach((v2,k)=>{v2===lines.length&&types.push(k)}),types}static getUnionTypes(lines){const typeSet=/* @__PURE__ */new Set;return lines.forEach(line=>{line.userData.groups&&line.userData.groups.forEach(group2=>typeSet.add(group2.type)),line.userData.groupType&&typeSet.add(line.userData.groupType)}),Array.from(typeSet)}static isGroup(lines){return 0!==this.getIntersectionTypes(lines).length}static remove(line,id){if(void 0!==line.userData.groupType&&line.userData.groupId===id)return delete line.userData.groupId,delete line.userData.groupType,!0;if(line.userData?.groups)for(let i=0;i<line.userData.groups.length;i++){if(line.userData.groups[i].id===id)return line.userData.groups.splice(i,1),!0}return!1}static removeByType(line,type){let is2=!1;line.userData?.groupType===type&&(delete line.userData.groupId,delete line.userData.groupType,is2=!0);const groups=line.userData?.groups;if(groups)for(let i=groups.length-1;i>=0;i--){groups[i].type===type&&(groups.splice(i,1),is2=!0)}return is2}static removeByTypes(line,types){if(!line.userData)return;const typeSet=new Set(types);line.userData.groupType&&typeSet.has(line.userData.groupType)&&(delete line.userData.groupType,delete line.userData.groupId);const groups=line.userData.groups;Array.isArray(groups)&&groups.length>0&&(line.userData.groups=groups.filter(element=>!element?.type||!typeSet.has(element.type)))}static clear(line){delete line.userData.groupId,delete line.userData.groupType,delete line.userData.groups}}const steiners=/* @__PURE__ */new Set;let filteredOut=!1;function earcut(data,holeIndices,dim=2){const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;steiners.size&&steiners.clear();let outerNode=linkedList(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX=0,minY=0,invSize=0;if(hasHoles&&(outerNode=function(data,holeIndices,outerNode,dim){const queue=[];for(let i=0,len=holeIndices.length;i<len;i++){const list=linkedList(data,holeIndices[i]*dim,i<len-1?holeIndices[i+1]*dim:data.length,dim,!1);list===list.next&&steiners.add(list),queue.push(getLeftmost(list))}queue.sort(compareXYSlope),function(maxNodes,numHoles){const maxBlocks=Math.ceil((maxNodes+2*numHoles)/K$1)+numHoles+2;blockBBox.length<4*maxBlocks&&(blockBBox=new Float64Array(4*maxBlocks));numBlocks=0}(data.length/dim,holeIndices.length),indexSegment(outerNode,outerNode),indexActive=!0;for(let i=0;i<queue.length;i++)outerNode=eliminateHole(queue[i],outerNode);return indexActive=!1,filterPoints(outerNode)}(data,holeIndices,outerNode,dim)),data.length>80*dim){minX=data[0],minY=data[1];let maxX=minX,maxY=minY;for(let i=dim;i<outerLen;i+=dim){const x=data[i],y=data[i+1];x<minX&&(minX=x),y<minY&&(minY=y),x>maxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?32767/invSize:0}return earcutLinked(outerNode,triangles,minX,minY,invSize),triangles}function linkedList(data,start,end,dim,clockwise){let last=null;if(clockwise===function(data,start,end,dim){let sum2=0;for(let i=start,j=end-dim;i<end;i+=dim)sum2+=(data[j]-data[i])*(data[i+1]+data[j+1]),j=i;return sum2}(data,start,end,dim)>0)for(let i=start;i<end;i+=dim)last=insertNode$1(i/dim|0,data[i],data[i+1],last);else for(let i=end-dim;i>=start;i-=dim)last=insertNode$1(i/dim|0,data[i],data[i+1],last);return last&&equals(last,last.next)&&(removeNode(last),last=last.next),last}function filterPoints(start,end=start){const full=end===start;let again,p2=start;do{again=!1,p2===p2.next||0!==steiners.size&&steiners.has(p2)||!equals(p2,p2.next)&&0!==area(p2.prev,p2,p2.next)?(full||p2!==end)&&(p2=p2.next,again=!full):((full||p2===end)&&(end=p2.prev),filteredOut=!0,removeNode(p2),p2=p2.prev,again=!0)}while(again||p2!==end);return end}function earcutLinked(ear,triangles,minX,minY,invSize){invSize&&function(start,minX,minY,invSize){let p2=start,n=0;do{p2.z=zOrder(p2.x,p2.y,minX,minY,invSize),sortArr[n++]=p2,p2=p2.next}while(p2!==start);!function(n){if(n<=32){for(let i=1;i<n;i++){const node=sortArr[i],z=node.z;let j=i-1;for(;j>=0&&sortArr[j].z>z;)sortArr[j+1]=sortArr[j],j--;sortArr[j+1]=node}return}zArr.length<n&&(zArr=new Uint32Array(n),zBuf=new Uint32Array(n),sortBuf=new Array(n));for(let i=0;i<n;i++)zArr[i]=sortArr[i].z;radixPass(n,sortArr,zArr,sortBuf,zBuf,0),radixPass(n,sortBuf,zBuf,sortArr,zArr,8),radixPass(n,sortArr,zArr,sortBuf,zBuf,16),radixPass(n,sortBuf,zBuf,sortArr,zArr,24)}(n);let prev=null;for(let i=0;i<n;i++){const node=sortArr[i];node.prevZ=prev,prev&&(prev.nextZ=node),prev=node}prev.nextZ=null}(ear,minX,minY,invSize);let stop=ear,cured=!1;for(;ear.prev!==ear.next;){const prev=ear.prev,next=ear.next;if(area(prev,ear,next)<0&&(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)))triangles.push(prev.i,ear.i,next.i),removeNode(ear),ear=next,stop=next;else if((ear=next)===stop){if(filteredOut=!1,ear=filterPoints(ear),filteredOut){stop=ear;continue}if(!cured){stop=ear=cureLocalIntersections(ear,triangles),cured=!0;continue}splitEarcut(ear,triangles,minX,minY,invSize);break}}}function isEar(ear){const a2=ear.prev,b4=ear,c=ear.next,ax=a2.x,bx=b4.x,cx=c.x,ay=a2.y,by=b4.y,cy=c.y,x0=Math.min(ax,bx,cx),y0=Math.min(ay,by,cy),x1=Math.max(ax,bx,cx),y1=Math.max(ay,by,cy);let p2=c.next;for(;p2!==a2;){if(p2.x>=x0&&p2.x<=x1&&p2.y>=y0&&p2.y<=y1&&(ax!==p2.x||ay!==p2.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,p2.x,p2.y)&&area(p2.prev,p2,p2.next)>=0)return!1;p2=p2.next}return!0}function isEarHashed(ear,minX,minY,invSize){const a2=ear.prev,b4=ear,c=ear.next,ax=a2.x,bx=b4.x,cx=c.x,ay=a2.y,by=b4.y,cy=c.y,x0=Math.min(ax,bx,cx),y0=Math.min(ay,by,cy),x1=Math.max(ax,bx,cx),y1=Math.max(ay,by,cy),minZ=zOrder(x0,y0,minX,minY,invSize),maxZ=zOrder(x1,y1,minX,minY,invSize);let p2=ear.prevZ;for(;p2&&p2.z>=minZ;){if(p2.x>=x0&&p2.x<=x1&&p2.y>=y0&&p2.y<=y1&&p2!==c&&(ax!==p2.x||ay!==p2.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,p2.x,p2.y)&&area(p2.prev,p2,p2.next)>=0)return!1;p2=p2.prevZ}let n=ear.nextZ;for(;n&&n.z<=maxZ;){if(n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==c&&(ax!==n.x||ay!==n.y)&&pointInTriangle(ax,ay,bx,by,cx,cy,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0}function cureLocalIntersections(start,triangles){let p2=start,cured=!1;do{const a2=p2.prev,b4=p2.next.next;intersects$2(a2,p2,p2.next,b4,!1)&&locallyInside(a2,b4)&&locallyInside(b4,a2)&&(triangles.push(a2.i,p2.i,b4.i),removeNode(p2),removeNode(p2.next),p2=start=b4,cured=!0),p2=p2.next}while(p2!==start);return cured?filterPoints(p2):p2}function splitEarcut(start,triangles,minX,minY,invSize){let a2=start;do{let b4=a2.next.next;for(;b4!==a2.prev;){if(a2.i!==b4.i&&isValidDiagonal(a2,b4)){let c=splitPolygon(a2,b4);return a2=filterPoints(a2,a2.next),c=filterPoints(c,c.next),earcutLinked(a2,triangles,minX,minY,invSize),void earcutLinked(c,triangles,minX,minY,invSize)}b4=b4.next}a2=a2.next}while(a2!==start)}let indexActive=!1;function compareXYSlope(a2,b4){return a2.x-b4.x||a2.y-b4.y||(a2.next.y-a2.y)/(a2.next.x-a2.x)-(b4.next.y-b4.y)/(b4.next.x-b4.x)}function eliminateHole(hole,outerNode){const bridge=function(hole,outerNode){let p2=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;if(equals(hole,p2))return p2;for(let b4=0,g=0;b4<numBlocks;b4++,g+=4){if(hy<blockBBox[g+1]||hy>blockBBox[g+3]||blockBBox[g]>hx||blockBBox[g+2]<=qx)continue;const stop=liveBlockStop(b4);p2=liveBlockHead(b4);do{if(p2.prev.next===p2){if(equals(hole,p2.next))return p2.next;if(hy<=p2.y&&hy>=p2.next.y&&p2.next.y!==p2.y){const x=p2.x+(hy-p2.y)*(p2.next.x-p2.x)/(p2.next.y-p2.y);if(x<=hx&&x>qx&&(qx=x,m=p2.x<p2.next.x?p2:p2.next,x===hx))return m}}p2=p2.next}while(p2!==stop)}if(!m)return null;const mx=m.x,my=m.y,tminY=Math.min(hy,my),tmaxY=Math.max(hy,my);let tanMin=1/0;for(let b4=0,g=0;b4<numBlocks;b4++,g+=4){if(blockBBox[g+2]<mx||blockBBox[g]>hx||blockBBox[g+3]<tminY||blockBBox[g+1]>tmaxY)continue;const stop=liveBlockStop(b4);p2=liveBlockHead(b4);do{if(p2.prev.next===p2&&hx>=p2.x&&p2.x>=mx&&hx!==p2.x&&pointInTriangle(hy<my?hx:qx,hy,mx,my,hy<my?qx:hx,hy,p2.x,p2.y)){const tan=Math.abs(hy-p2.y)/(hx-p2.x);(locallyInside(p2,hole)||p2.y===hy&&p2.next.y===hy&&p2.next.x>hx)&&(tan<tanMin||tan===tanMin&&(p2.x>m.x||p2.x===m.x&§orContainsSector(m,p2)))&&(m=p2,tanMin=tan)}p2=p2.next}while(p2!==stop)}return m}(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole);return indexSegment(bridge,bridgeReverse.next.next),filterPoints(bridgeReverse,bridgeReverse.next),filterPoints(bridge,bridge.next)}const K$1=16;let blockBBox=new Float64Array(0),numBlocks=0;const blockHead=[],blockStop=[];function indexSegment(head,stop){let p2=head;do{const b4=numBlocks++;blockHead[b4]=p2;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,k=0;do{const c=p2.next;p2.z=b4,p2.x<minX&&(minX=p2.x),p2.x>maxX&&(maxX=p2.x),p2.y<minY&&(minY=p2.y),p2.y>maxY&&(maxY=p2.y),c.x<minX&&(minX=c.x),c.x>maxX&&(maxX=c.x),c.y<minY&&(minY=c.y),c.y>maxY&&(maxY=c.y),p2=c}while(++k<K$1&&p2!==stop);blockStop[b4]=p2;const g=4*b4;blockBBox[g]=minX,blockBBox[g+1]=minY,blockBBox[g+2]=maxX,blockBBox[g+3]=maxY}while(p2!==stop)}function liveBlockStop(b4){let stop=blockStop[b4];for(;stop.prev.next!==stop;)stop=stop.next;return blockStop[b4]=stop,stop}function liveBlockHead(b4){let head=blockHead[b4];for(;head.prev.next!==head;)head=head.next;return blockHead[b4]=head,head}function sectorContainsSector(m,p2){return area(m.prev,m,p2.prev)<0&&area(p2.next,m,m.next)<0}const sortArr=[];let sortBuf=[],zArr=new Uint32Array(0),zBuf=new Uint32Array(0);const counts=new Uint32Array(256);function radixPass(n,src,srcZ,dst,dstZ,shift){counts.fill(0);for(let i=0;i<n;i++)counts[srcZ[i]>>>shift&255]++;let sum2=0;for(let b4=0;b4<256;b4++){const c=counts[b4];counts[b4]=sum2,sum2+=c}for(let i=0;i<n;i++){const z=srcZ[i],pos=counts[z>>>shift&255]++;dst[pos]=src[i],dstZ[pos]=z}}function zOrder(x,y,minX,minY,invSize){return(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=(x-minX)*invSize|0)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=(y-minY)*invSize|0)|y<<8))|y<<4))|y<<2))|y<<1))<<1}function getLeftmost(start){let p2=start,leftmost=start;do{(p2.x<leftmost.x||p2.x===leftmost.x&&p2.y<leftmost.y)&&(leftmost=p2),p2=p2.next}while(p2!==start);return leftmost}function pointInTriangle(ax,ay,bx,by,cx,cy,px,py){return(cx-px)*(ay-py)>=(ax-px)*(cy-py)&&(ax-px)*(by-py)>=(bx-px)*(ay-py)&&(bx-px)*(cy-py)>=(cx-px)*(by-py)}function isValidDiagonal(a2,b4){const zeroLength=equals(a2,b4)&&area(a2.prev,a2,a2.next)>0&&area(b4.prev,b4,b4.next)>0;return a2.next.i!==b4.i&&(zeroLength||locallyInside(a2,b4)&&locallyInside(b4,a2)&&(0!==area(a2.prev,a2,b4.prev)||0!==area(a2,b4.prev,b4)))&&!function(a2,b4){const minX=Math.min(a2.x,b4.x),maxX=Math.max(a2.x,b4.x),minY=Math.min(a2.y,b4.y),maxY=Math.max(a2.y,b4.y);let p2=a2;do{const n=p2.next;if(p2.x>maxX&&n.x>maxX||p2.x<minX&&n.x<minX||p2.y>maxY&&n.y>maxY||p2.y<minY&&n.y<minY)p2=n;else{if(p2.i!==a2.i&&n.i!==a2.i&&p2.i!==b4.i&&n.i!==b4.i&&intersects$2(p2,n,a2,b4))return!0;p2=n}}while(p2!==a2);return!1}(a2,b4)&&(zeroLength||function(a2,b4){let p2=a2,inside2=!1;const px=(a2.x+b4.x)/2,py=(a2.y+b4.y)/2;do{const n=p2.next;p2.y>py!=n.y>py&&px<(n.x-p2.x)*(py-p2.y)/(n.y-p2.y)+p2.x&&(inside2=!inside2),p2=n}while(p2!==a2);return inside2}(a2,b4))}function area(p2,q,r2){return(q.y-p2.y)*(r2.x-q.x)-(q.x-p2.x)*(r2.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}function intersects$2(p1,q1,p2,q2,includeBoundary=!0){const o1=area(p1,q1,p2),o2=area(p1,q1,q2),o3=area(p2,q2,p1),o4=area(p2,q2,q1);return(o1>0&&o2<0||o1<0&&o2>0)&&(o3>0&&o4<0||o3<0&&o4>0)||!!includeBoundary&&(!(0!==o1||!onSegment(p1,p2,q1))||(!(0!==o2||!onSegment(p1,q2,q1))||(!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2)))))}function onSegment(p2,q,r2){return q.x<=Math.max(p2.x,r2.x)&&q.x>=Math.min(p2.x,r2.x)&&q.y<=Math.max(p2.y,r2.y)&&q.y>=Math.min(p2.y,r2.y)}function locallyInside(a2,b4){return area(a2.prev,a2,a2.next)<0?area(a2,b4,a2.next)>=0&&area(a2,a2.prev,b4)>=0:area(a2,b4,a2.prev)<0||area(a2,a2.next,b4)<0}function splitPolygon(a2,b4){const a22=createNode$1(a2.i,a2.x,a2.y),b22=createNode$1(b4.i,b4.x,b4.y),an2=a2.next,bp=b4.prev;return a2.next=b4,b4.prev=a2,a22.next=an2,an2.prev=a22,b22.next=a22,a22.prev=b22,bp.next=b22,b22.prev=bp,b22}function insertNode$1(i,x,y,last){const p2=createNode$1(i,x,y);return last?(p2.next=last.next,p2.prev=last,last.next.prev=p2,last.next=p2):(p2.prev=p2,p2.next=p2),p2}function removeNode(p2){p2.next.prev=p2.prev,p2.prev.next=p2.next,p2.prevZ&&(p2.prevZ.nextZ=p2.nextZ),p2.nextZ&&(p2.nextZ.prevZ=p2.prevZ),indexActive&&function(head,tail){const g=4*head.z;tail.x<blockBBox[g]&&(blockBBox[g]=tail.x),tail.y<blockBBox[g+1]&&(blockBBox[g+1]=tail.y),tail.x>blockBBox[g+2]&&(blockBBox[g+2]=tail.x),tail.y>blockBBox[g+3]&&(blockBBox[g+3]=tail.y)}(p2.prev,p2.next)}function createNode$1(i,x,y){return{i:i,x:x,y:y,prev:null,next:null,z:0,prevZ:null,nextZ:null}}class Heartbeat{static timer;static tasks=/* @__PURE__ */new Map;static nextId=0;static interval=5e3;static addTask(task){const id=++this.nextId;return this.tasks.set(id,task),this.timer||this.start(),id}static removeTask(id){this.tasks.delete(id)&&0===this.tasks.size&&this.stop()}static start(){this.timer||0===this.tasks.size||(this.timer=setInterval(()=>{this.tasks.forEach((task,id)=>{if(this.tasks.has(id))try{task()}catch(error){console.error("心跳任务执行失败:",error)}})},this.interval))}static stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}static createAutoWeakRefTask(fun){let id=null;const weakRefList=[];return{addHeartbeat:function(weakRef){0===weakRefList.length&&(id=Heartbeat.addTask(()=>{let index2=weakRefList.length-1;for(let i=index2;i>=0;i--){const data=weakRefList[i].deref();data?fun(data):(weakRefList[i]=weakRefList[index2],index2--)}weakRefList.length=index2+1,0===weakRefList.length&&null!==id&&(Heartbeat.removeTask(id),id=null)})),weakRefList.push(weakRef)}}}}const{addHeartbeat:addHeartbeat}=Heartbeat.createAutoWeakRefTask(bk=>{const map=bk.dataMap;map.forEach(({ref:ref2},key)=>{void 0===ref2.deref()&&map.delete(key)})});class BezierCurveKernel{constructor(segment=.1){this.segment=segment,addHeartbeat(new WeakRef(this))}dataMap=/* @__PURE__ */new Map;getData(line,segment=this.segment){let data=this.dataMap.get(line.uuid);if(data&&data.version===line.version)return data;const arrs=computeCubicBezierByLine(line,segment),points=arrs.map(arr=>Point.from(arr)),ts2=arrs.map(arr=>arr[2]);let len=0;for(let i=1;i<points.length;i++){const p0=points[i-1];len+=points[i].distance(p0)}return data={version:line.version,ts:ts2,len:len,points:points,ref:new WeakRef(line)},this.dataMap.set(line.uuid,data),data}delete(line){this.dataMap.delete(line.uuid)}getPath(line){return this.getData(line).points}getTs(line){return this.getData(line).ts}getLen(line){return this.getData(line).len}getLines(line){const data=this.getData(line);if(data.lines)return data.lines;const points=data.points,lines=[];for(let i=1;i<points.length;i++){const line2=new LineSegment(points[i-1],points[i]);lines.push(line2)}return data.lines=lines,lines}getQueryTree(line){const data=this.getData(line);if(data.quadtree)return data.quadtree;const lines=this.getLines(line);return data.quadtree=LineSegmentSpatialHash.from(lines),data.quadtree}getMiddlePoint(line){const data=this.getData(line);if(data.middlePoint)return data.middlePoint;const{points:points,len:len}=data,halfLen=.5*len;let currentLen=0;for(let i=1;i<points.length;i++){const prev=points[i-1],curr=points[i],segmentLen=prev.distance(curr);if(currentLen+segmentLen>=halfLen)return data.middlePoint=prev.clone().lerp(curr,(halfLen-currentLen)/segmentLen),data.middlePoint;currentLen+=segmentLen}return data.middlePoint=points[points.length-1].clone(),data.middlePoint}getTByPoint(line,point2){const queryTree=this.getQueryTree(line),lines=this.getLines(line),ts2=this.getTs(line),results=queryTree.queryPoint(point2,.4);let targetLine,minDist=1/0;for(const rline of results){const dist=rline.distanceSquaredToPoint(point2);dist<minDist&&(minDist=dist,targetLine=rline)}if(!targetLine)return;const index2=lines.indexOf(targetLine);if(index2<0||index2+1>=ts2.length)return;const pv=targetLine.projectPointValue(point2);return ts2[index2]+(ts2[index2+1]-ts2[index2])*pv}getOffset(line,width){const data=this.getData(line);data.offsetMap||(data.offsetMap=/* @__PURE__ */new Map);let path=data.offsetMap.get(width);if(path)return path;const poly=Polygon.offset(new Polygon(data.points),{offsetHalfWidth:.5*width});return data.offsetMap.set(width,poly),poly}getOffsetGeometry(line,width=.04){const data=this.getData(line);data.offsetGeometryMap||(data.offsetGeometryMap=/* @__PURE__ */new Map);let geometry=data.offsetGeometryMap.get(width);if(geometry)return geometry;let path=this.getOffset(line,width);return geometry=earcut(path.flatMap(p2=>p2.toArray())).flatMap(i=>{const p2=path[i];return[p2.x,p2.y,0]}),data.offsetGeometryMap.set(width,geometry),geometry}getIndexRangeByPoint(line,point2){const{points:points}=this.getData(line);if(points.length<2)return[0,0];let minDistSq=1/0,index2=0;for(let i=1;i<points.length;i++){const a2=points[i-1],b4=points[i],dx=b4.x-a2.x,dy=b4.y-a2.y,lenSq=dx*dx+dy*dy,t2=0===lenSq?0:Math.max(0,Math.min(1,((point2.x-a2.x)*dx+(point2.y-a2.y)*dy)/lenSq)),px=a2.x+dx*t2,py=a2.y+dy*t2,distSq=(point2.x-px)**2+(point2.y-py)**2;distSq<minDistSq&&(minDistSq=distSq,index2=i-1)}return[index2,index2+1]}getRangeByLength(line,center,width){const data=this.getData(line);data.rangeByOffsetMap||(data.rangeByOffsetMap=/* @__PURE__ */new Map);const key=`${center.hashCode(4)}-${width}`;let opt=data.rangeByOffsetMap.get(key);if(opt)return opt;function get2(center2,length,startIndex,step,halfWidth2){let w=0,currentPoint=center2,current=startIndex,endPoint=null,path2=[];for(;current>=0&¤t<length;){const point2=points[current];let dist=currentPoint.distance(point2);if(currentPoint=point2,w+dist<halfWidth2){path2.push(point2),w+=dist,current+=step;continue}const remaining=(halfWidth2-w)/dist;endPoint=point2.clone().lerp(points[current-step],1-remaining),path2.push(endPoint);break}return endPoint||(endPoint=currentPoint,path2.push(endPoint)),{start:center2,end:endPoint,path:path2,endDist:halfWidth2-w,range:[startIndex,current]}}const{points:points}=this.getData(line),[start,end]=this.getIndexRangeByPoint(line,center),halfWidth=.5*width,startInfo=get2(center,points.length,start,-1,halfWidth),endInfo=get2(center,points.length,end,1,halfWidth);let path=[...startInfo.path].reverse();path.push(...endInfo.path);const set2=/* @__PURE__ */new Set;path=path.filter(p2=>{const key2=p2.hashCode(4);return!set2.has(key2)&&(set2.add(key2),!0)});let len=0;for(let i=1;i<path.length;i++){const p0=path[i-1];len+=path[i].distance(p0)}const poly=new Polygon(path);return opt={startInfo:startInfo,endInfo:endInfo,len:len,center:poly.getPathCenter()??Point.zero(),path:poly},data.rangeByOffsetMap.set(key,opt),opt}getHoleData(line,hole){return this.getRangeByLength(line,Point.from(hole.p),hole.width)}getHoleOffset(line,hole,offsetW){const data=this.getHoleData(line,hole);data.offsetMap||(data.offsetMap=/* @__PURE__ */new Map);let poly=data.offsetMap.get(offsetW);return poly||(poly=Polygon.offset(data.path,{offsetHalfWidth:.5*offsetW}),data.offsetMap.set(offsetW,poly),poly)}getHoleOffsetGeometry(line,hole,offsetW){const path=this.getHoleOffset(line,hole,offsetW);return earcut(path.flatMap(p2=>p2.toArray())).flatMap(i=>{const p2=path[i];return[p2.x,p2.y,0]})}getPathExcludingHoles(line){const path=[...this.getPath(line)],ranges=[];let newPaths=[];for(const holeData of WallHole.getIterator(line)){const data=this.getHoleData(line,holeData),[_0,startIndex]=data.startInfo.range,[_1,endIndex]=data.endInfo.range;if(0!==data.startInfo.endDist){const p0=path[startIndex],p1=path[startIndex+1];if(p0&&p1){let point2=p0.clone().lerp(p1,1-data.startInfo.endDist/p0.distance(p1));newPaths.push([p0,point2,startIndex,startIndex+1])}}if(0!==data.endInfo.endDist){const p0=path[endIndex],p1=path[endIndex-1];if(p0&&p1){let point2=p0.clone().lerp(p1,1-data.endInfo.endDist/p0.distance(p1));newPaths.push([p0,point2,endIndex,endIndex-1])}}ranges.push([startIndex,endIndex])}if(0===ranges.length)return[path];ranges.sort((a2,b4)=>a2[0]-b4[0]);let start=0,ranges2=[];for(let i=0;i<ranges.length;i++){const range=ranges[i];start<range[0]&&ranges2.push([start,range[0]]),start=range[1]}return start<path.length-1&&ranges2.push([start,path.length-1]),ranges2.map(ranges3=>path.slice(ranges3[0],ranges3[1]+1)).concat(newPaths.map(p2=>[p2[0],p2[1]]))}}class WallHole{static mountedObjectType=[];lines;static bezierCurveLineHelper=new BezierCurveKernel;constructor(lines){this.lines=lines}static isHoleData(hole){return hole&&"p"in hole&&"x"in hole.p&&"y"in hole.p&&"width"in hole}static isHole(line){return line.userData.isWindow||line.userData.isPassageEntrance}static isDoor(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>"door"===hole.type)}static isDoubleDoor(line){if(line.userData.isPassageEntrance&&line.userData.passageEntrance?.length){return line.userData.passageEntrance.some(item=>"door"===item.type&&"number"==typeof this.getNearId(item))}return!1}static isBeam(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>"beam"===hole.type)}static isPass(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance?.some(hole=>void 0===hole.type)}static isDouble(line){return!(!line.userData.isPassageEntrance||!line.userData.passageEntrance?.length)&&line.userData.passageEntrance.some(item=>{const nearId=this.getNearId(item),id=this.getId(item);return"number"==typeof nearId&&"number"==typeof id&&id!==nearId})}static isPairing(lines){const set2=/* @__PURE__ */new Set;for(let i=0;i<lines.length;i++){const passageEntrance=lines[i].userData.passageEntrance??[];for(let i2=0;i2<passageEntrance.length;i2++){const item=passageEntrance[i2],id=this.getId(item),nearId=this.getNearId(item);if("number"==typeof item.nearId&&"number"==typeof id){if(set2.has(nearId))return!0;set2.add(id)}}}}static cancelPairing(line,line2){const map=/* @__PURE__ */new Map,lines=[line,line2];for(let i=0;i<lines.length;i++){const line32=lines[i];for(const data of this.getIterator(line32)){const id=this.getId(data),nearId=this.getNearId(data);if("number"!=typeof nearId||"number"!=typeof id)continue;const nearData=map.get(nearId);nearData?data.nearDoorId=data.nearId=nearData.nearDoorId=nearData.doorId=-1:map.set(id,data)}}}static getId(item){return item.id??item.doorId}static getNearId(item){let nearId=item.nearId??item.nearDoorId;return-1===nearId&&(nearId=void 0),nearId}static buildPairing(lineSegments){const map=new ArrayMap,originMap=/* @__PURE__ */new Map;WallHole.merge(lineSegments),lineSegments.forEach(line=>{for(const holeData of WallHole.getIterator(line)){const holeLine=WallHole.holeDataToLine(line,holeData);holeData.type=holeData.type??"passageEntrance",map.append(holeData.type,holeLine),originMap.set(holeLine,line)}});let idIndex=0;return{matchQueues:map.map(holeLines=>{const lsh=LineSegmentSpatialHash.from(holeLines),unionFindSet=new UnionFindSet(holeLines.length),lineIndexGenerator=new LineIndexGenerator(holeLines);for(const holeLine of holeLines){const rectangle=holeLine.toRectangle(.8,"butt");let list=lsh.queryRectangle(rectangle).filter(rline=>rline!==holeLine&&rline.isParallelTo(holeLine,10)&&!rline.isSameEndpoint(holeLine,1e-4)).filter(rline=>{const line=holeLine.projectLineSegment(rline);return!(line.length<1e-5)&&(line.length/holeLine.length>.1||line.length/rline.length>.1)});if(list.length){if(list.length>1){const dist=list.map(line=>({line:line,dist:line.distanceToSegment(holeLine)}));dist.sort((a2,b4)=>a2.dist-b4.dist),list=dist.map(d2=>d2.line)}unionFindSet.union(lineIndexGenerator.getIndex(holeLine),lineIndexGenerator.getIndex(list[0]))}}const matchQueue=[];return unionFindSet.getAllSets().forEach(list=>{2===list.length&&matchQueue.push(list.map(i=>lineIndexGenerator.getLine(i)))}),matchQueue.forEach(([holeLine1,holeLine2])=>{const id1=idIndex++,id2=idIndex++;holeLine1.userData.id=id1,holeLine1.userData.nearId=id2,holeLine2.userData.id=id2,holeLine2.userData.nearId=id1}),matchQueue}),originMap:originMap}}static getDoubleGroup(lines){const otherLines=[],doorMap=/* @__PURE__ */new Map,lineMap=/* @__PURE__ */new Map;lines.flatMap(line=>{if(!WallHole.isDouble(line))return otherLines.push(line),[];WallHole.forEachStorageType(line,(data,k)=>{"passageEntrance"===k&&data.forEach(v2=>{const id=WallHole.getId(v2),peLine=WallHole.holeDataToLine(line,v2);peLine.currentData.line=line,peLine.currentData.type=v2.type,peLine.currentData.ket=k,doorMap.set(id,{line:peLine,nearId:WallHole.getNearId(v2)}),lineMap.set(id,line)})})});const visited=/* @__PURE__ */new Set,results=[];for(const[id,{line:line,nearId:nearId}]of doorMap){if(visited.has(id))continue;const near=doorMap.get(nearId);if(!near)continue;const d1=line.direction(),d2=near.line.direction();d1.dot(d2)<0&&near.line.swap(),results.push([line,near.line]),visited.add(id),visited.add(nearId)}return{results:results,otherLines:otherLines}}static*getIterator(line){line.userData?.drawWindow?.forEach(item=>item.type="window"),yield*line.userData?.drawWindow??[],yield*line.userData?.passageEntrance??[]}static*getStorageDataIterator(line){yield line.userData?.drawWindow??[],yield line.userData?.passageEntrance??[]}static forEachStorageType(line,callBack){line.userData.isWindow&&(line.userData.drawWindow?.forEach(item=>item.type="window"),callBack(line.userData.drawWindow??[],"drawWindow")),line.userData.isPassageEntrance&&callBack(line.userData.passageEntrance??[],"passageEntrance")}static getMinWidth(key,type){if("drawWindow"===key)return.3;if("passageEntrance"===key){if("door"===type)return.35;if("passageEntrance"===type)return.2;if("beam"===type)return.2}return.05}static clear(target,key){if(void 0===key)return this.clear(target,"drawWindow"),void this.clear(target,"passageEntrance");const eabledKey="drawWindow"===key?"isWindow":"isPassageEntrance",key_="drawWindow"===key?"drawWindow":"passageEntrance";target.userData[eabledKey]=!1,delete target.userData[key_]}static holeDataToLine(line,hole,projClip=!0,snap=!0){const holeLine=(()=>{if(hole.full)return(new LineSegment).set(line.start,line.end);const center=PointUtils.globalPoint.copy(hole.p),direct=line.direction(),width=hole.width??0;return center.expandAsLine(direct,width).translate(.5*-width,direct)})();if(projClip&&"cubic-bezier"!==line.userData.shape?.type&&line.projectLineSegment(holeLine,holeLine),("beam"===hole.type||"passageEntrance"===hole.type)&&snap){let eps="passageEntrance"===hole.type?.02:.2;line.start.distance(holeLine.start)<eps&&holeLine.start.copy(line.start),line.end.distance(holeLine.end)<eps&&holeLine.end.copy(line.end)}return holeLine.userData=hole,holeLine.currentData.wallLine=line,holeLine.currentData.wallWidth=line.userData.wallWidth,holeLine}static miniWidthFilter(line){return Array.isArray(line)?(line.forEach(line2=>this.miniWidthFilter(line2)),this):(this.forEachStorageType(line,(data,key)=>{line.userData[key]=data.filter(w=>w.width>WallHole.getMinWidth(key,w.type)),0===line.userData[key].length&&WallHole.clear(line,key)}),this)}static filterIllegal(line,bezierCurveLineHelper=this.bezierCurveLineHelper){return Array.isArray(line)?(line.forEach(line2=>this.filterIllegal(line2,bezierCurveLineHelper)),this):(this.forEachStorageType(line,(data,key)=>{data.forEach(w=>{w.type||"drawWindow"!==key||(w.type="window"),w.uuid||(w.uuid=uuid());try{const center=Point.from(w.p);if("cubic-bezier"===line.userData.shape?.type){if(!bezierCurveLineHelper)return;const{len:len,path:path}=bezierCurveLineHelper.getHoleData(line,w);return void((0===len||!path.pointIn(center)&&len/w.width<.4)&&(w.width=0))}const windowLine=line.projectLineSegment(this.holeDataToLine(line,w));if("beam"===w.type)return w.p=windowLine.center.toJson(w.p.z),void(w.width=windowLine.length);if(windowLine.length/w.width<.4&&!windowLine.containsPoint(center))return void(w.width=0)}catch(error){}}),line.userData[key]=data.filter(w=>w.width>1e-9),0===line.userData[key].length&&WallHole.clear(line,key)}),this)}static recomputedCenter(lines,bezierCurveLineHelper=this.bezierCurveLineHelper){return lines.forEach(line=>{for(const hole of this.getIterator(line))try{if("cubic-bezier"===line.userData.shape?.type){if(bezierCurveLineHelper){const{path:path}=bezierCurveLineHelper.getHoleData(line,hole),lines2=path.toLines(!1);let minDist=1/0,index2=-1;for(let i=0;i<lines2.length;i++){const distSq=lines2[i].distanceSquaredToPoint(hole.p);minDist<distSq&&(minDist=distSq,index2=0)}if(-1!==index2){const pPoint=lines2[index2].projectPoint(hole.p,!0);pPoint&&(hole.p=pPoint.toJson(hole.p.z))}}continue}const center=line.projectPoint(hole.p);hole.p={x:center?.x??0,y:center?.y??0,z:hole.p.z}}catch(error){}}),this}static merge(line){if(Array.isArray(line))return line.forEach(line2=>this.merge(line2)),this;if("cubic-bezier"!==line.userData.shape?.type){for(const data of this.getStorageDataIterator(line)){if(0===data.length)continue;const results=data.map(hole=>{const holeLine=this.holeDataToLine(line,hole),groundClearance=hole.groundClearance??0,height=hole.height??0;return{holeLine:holeLine,startV:line.projectPointValue(holeLine.start),endV:line.projectPointValue(holeLine.end),bottom:groundClearance,top:groundClearance+height}});results.sort((a2,b4)=>a2.startV-b4.startV);const unionFindSet=new UnionFindSet(results.length);for(let i=0;i<results.length;i++){const a2=results[i];for(let j=i+1;j<results.length;j++){const b4=results[j];if(b4.startV>a2.endV)break;a2.top<b4.bottom||b4.top<a2.bottom||unionFindSet.union(i,j)}}const newData=unionFindSet.getAllSets().map(values=>{const opt={};let min=1/0,max=-1/0;for(let i=0;i<values.length;i++){const{startV:startV,endV:endV,holeLine:holeLine}=results[values[i]];Object.assign(opt,holeLine.userData),min=Math.min(min,startV,endV),max=Math.max(max,startV,endV)}const newHoleLine=new LineSegment(line.pointAt(min),line.pointAt(max));return newHoleLine.userData=opt,newHoleLine}).map(line2=>({...line2.userData,width:line2.length,p:line2.center.toJson(line2.userData.p.z)}));data.splice(0,data.length,...newData)}return this}}static addHole(target,hole,type){type||(type="window"===hole.type?"drawWindow":"passageEntrance");const eabledKey="drawWindow"===type?"isWindow":"isPassageEntrance",key="drawWindow"===type?"drawWindow":"passageEntrance";hole.uuid=hole.uuid??uuid(),target.userData[eabledKey]=!0,target.userData[key]||(target.userData[key]=[]),target.userData[key]?.push(hole)}static removeHole(target,hole){this.forEachStorageType(target,(data,key)=>{let index2=data.indexOf(hole);index2>-1&&data.splice(index2,1),0===target.userData[key]?.length&&WallHole.clear(target,key)})}static copyHole(target,source){WallHole.forEachStorageType(source,(data,key)=>{data.forEach(item=>{WallHole.addHole(target,cloneUserData(item),key)})})}static splitHole(target,source){if(Array.isArray(source)||(source=[source]),target instanceof LineSegment){this.filterIllegal(target);const iterator=this.getIterator(target);return this.splitHole([...iterator],source),void this.clear(target)}if(!Array.isArray(target))throw new Error("传入参数非孔洞数组或线段");source=source.filter(line=>line.length>1e-9);for(const hole of target){let find=!1,min=1/0,maxLine=null;for(let i=0;i<source.length;i++){const line=source[i],v2=line.projectPointValue(hole.p);if(v2>=0&&v2<=1){this.addHole(line,hole),find=!0;break}const dist=Math.abs(v2-.5);dist<min&&(min=dist,maxLine=line)}if(!find&&maxLine){let v2=maxLine.projectPointValue(hole.p);v2=Math.min(1,Math.max(0,v2));const point2=maxLine.pointAt(v2,PointUtils.globalPoint);hole.p.x=point2.x,hole.p.y=point2.y,this.addHole(maxLine,hole)}}}static splitHoleByProjectPoint(target,source){Array.isArray(source)||(source=[source]),this.filterIllegal(target),source=source.filter(line=>line.length>1e-9),this.forEachStorageType(target,(holes,key)=>{for(const hole of holes){const holeLine=this.holeDataToLine(target,hole);for(let i=0;i<source.length;i++){const line=source[i],newHoleLine=line.projectLineSegment(holeLine),minW=this.getMinWidth(key,hole.type);newHoleLine.length>minW&&this.addHole(line,{...cloneUserData(hole),p:newHoleLine.center.toJson(hole.p.z),width:newHoleLine.length})}}}),this.clear(target)}static byWindowStructure(line,holeData){const holeLine=this.holeDataToLine(line,holeData),dottedLine=holeLine.clone(!1);dottedLine.userData.isBayWindow=!0,dottedLine.userData.topClearance=(line.userData.height??0)-holeLine.userData.height-(holeData.groundClearance??0);const lines=[];if(holeData.shape){const shape=holeData.shape;for(let i=1;i<shape.path.length;i++)lines.push(new LineSegment(shape.path[i-1],shape.path[i]));(shape.fragmentAttr??[{type:"window",index:1}]).forEach(({type:type,index:index2})=>{index2>=lines.length||WallHole.addHole(lines[index2],{p:holeLine.center.toJson(),width:0,full:!0,type:type,groundClearance:holeData.groundClearance,height:holeLine.userData.height})})}else{const{direction:direction,distance:distance2}=holeLine.userData.extrusion,line2=holeLine.clone(!1);line2.translate(distance2,Point.from(direction)),lines.push(new LineSegment(holeLine.start,line2.start),new LineSegment(line2.start,line2.end),new LineSegment(line2.end,holeLine.end)),WallHole.addHole(lines[1],{p:holeLine.center.toJson(),width:0,full:!0,type:"window",groundClearance:holeData.groundClearance,height:holeLine.userData.height})}const id=uuid();return{holeLine:holeLine,structure:[dottedLine,...lines].map(line2=>(LineGroupType.set(line2,id,"bayWindow"),line2.userData.height=line2.userData.height,line2))}}}const WH=WallHole;function findDiscretePointLine(lines,grid0,lineSet,deep=!0){lineSet=lineSet??/* @__PURE__ */new Set;const is2=!!grid0,grid=grid0||PointSpatialHash.fromByLines(lines);function handle(line){if(!(line instanceof LineSegment))return;if(lineSet?.has(line))return;const startInfo=grid?.queryCircle(line.start,1e-4,!0).filter(item=>item.userData!==line),endInfo=grid?.queryCircle(line.end,1e-4,!0).filter(item=>item.userData!==line);startInfo&&endInfo&&(0===startInfo?.length||0===endInfo?.length)&&(lineSet?.add(line),grid.remove(line.start),grid.remove(line.end),deep&&(startInfo.forEach(({userData:userData})=>handle(userData)),endInfo.forEach(({userData:userData})=>handle(userData))))}for(let i=0;i<lines.length;i++){handle(lines[i])}return is2||grid.clear(),lineSet}function findDiscretePointLine2(lines,lineSet,deep=!1){lineSet=lineSet||/* @__PURE__ */new Set;const map=new MapEnhance;for(lines.forEach(line=>{lineSet.size&&lineSet.has(line)||line.points.forEach(p2=>{const id=p2.hashCode(4);map.has(id)||map.set(id,/* @__PURE__ */new Set),map.get(id)?.add(line)})});;){const linesSet=/* @__PURE__ */new Set;for(const[id,set2]of map.entries()){if(1!==set2.size)continue;const line=set2.values().next().value;lineSet.add(line),map.delete(id),linesSet.add(line)}if(linesSet.forEach(line=>{map.get(line.start.hashCode())?.delete(line),map.get(line.end.hashCode())?.delete(line)}),0===linesSet.size||!deep)break}return lineSet}function findDiscretePoint(lines){const pointMap=new MapEnhance,map=new MapEnhance;lines.forEach(line=>{line.points.forEach((p2,i)=>{const id=p2.hashCode(4);map.has(id)||map.set(id,/* @__PURE__ */new Set),map.get(id)?.add(line),line.currentData[i]=id})});for(const[id,set2]of map.entries()){if(1!==set2.size)continue;const line=set2.values().next().value;line.currentData[0]===id?pointMap.set(line.start,line):pointMap.set(line.end,line)}return pointMap}function findDiscretePoint2(lines){const pointMap=new MapEnhance,pvg=PointSpatialHash.fromByLines(lines);return lines.forEach(line=>{const qr2=Math.min(.001,.009*line.length);line.points.forEach(p2=>{0===pvg.queryCircle(p2,qr2,!0).filter(item=>item.userData!==line).length&&pointMap.set(p2,line)})}),pointMap}function buildBayWindowGroup(lines,clear=!0){const bayWindowLines=lines.filter(line=>line.userData.isBayWindow),groupedLineSet=/* @__PURE__ */new Set,removeSet=findDiscretePointLine2(lines,null,!0),lines_=lines.filter(line=>!removeSet.has(line));lines.forEach(line=>{LineGroupType.hasType(line,"bayWindow")&&(line.userData.isWindow&&(line.currentData.isBayWindowLine=!0),LineGroupType.removeByType(line,"bayWindow"))});const grid=PointSpatialHash.fromByLines(lines);return removeSet.clear(),bayWindowLines.forEach(bayWindowLine=>{let{circles:circles}=MaxiCircles.instance.miniCircle(lines_,{circleEdges:[bayWindowLine]});circles=circles.filter(group2=>group2.some(line=>{if(!line.userData.isWindow)return!1;for(const data of WallHole.getIterator(line))if(data.pair===bayWindowLine.userData.pair)return!0;return!1})),circles.length&&grid.queryPolygon(Polygon.fromByLines(circles[0]),"inside").forEach(res=>removeSet.add(res.userData));const id=uuid();if(circles.length){circles[0].forEach(line=>{clear&&LineGroupType.clear(line),LineGroupType.set(line,id,"bayWindow",!0),groupedLineSet.add(line)})}else clear&&LineGroupType.clear(bayWindowLine)}),lines=lines.filter(line=>!removeSet.has(line)),clear&&lines.forEach(line=>groupedLineSet.has(line)||LineGroupType.clear(line)),lines}let trajectory;function isDoublePeCircle(circle){return WallHole.getDoubleGroup(circle).results.length>0}function isPolyHasTrajectoryPoint(lines){if(!trajectory)return!0;const ploy=Polygon.fromByLines2(lines),box=ploy.getBox2();for(let i=0;i<trajectory.length;i++){const p2=trajectory[i];if(!(p2.x<box.minX||p2.x>box.maxX||p2.y<box.minY||p2.y>box.maxY)&&ploy.pointWithin(p2))return!1}return!0}function group(lines_,clearInternalLine=!1){PointUtils.adsorb(lines_.flatMap(line=>line.points),5e-4),lines_=lines_.filter(line=>line.length>1e-7);const{doorLines:doorLines,otherLines:otherLines,peDoubleDoors:peDoubleDoors,balconyRailingLines:balconyRailingLines}=function(lines){const doorLines=[],otherLines=[],balconyRailingLines=[],bayWindowLines=[],peDoors=[],peDoubleDoors=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(line.userData.isDoor)doorLines.push(line);else if(line.userData.isBalconyRailing)balconyRailingLines.push(line);else if(line.userData.isBayWindow||line.userData.isWindow&&LineGroupType.hasType(line,"bayWindow"))bayWindowLines.push(line);else{if(line.userData.isPassageEntrance&&line.userData.passageEntrance?.length){WallHole.isDouble(line)?peDoubleDoors.push(line):peDoors.push(line);continue}otherLines.push(line)}}return{doorLines:doorLines,balconyRailingLines:balconyRailingLines,otherLines:otherLines,bayWindowLines:bayWindowLines,peDoors:peDoors,peDoubleDoors:peDoubleDoors}}(lines_),{circlesList:circlesList}=function(lines,peDoubleDoorLines){let allLines=[...lines,...peDoubleDoorLines],notFoundLines=[],circlesList=[];for(let i=0;i<peDoubleDoorLines.length;i++){const line=peDoubleDoorLines[i];let{circles:circles}=MaxiCircles.instance.miniCircle(allLines,{circleEdges:[line]});const finalCircles=circles.filter(isDoublePeCircle);finalCircles.length?circlesList.push(...finalCircles):notFoundLines.push(line)}return{circlesList:circlesList,notFoundLines:notFoundLines}}(otherLines,peDoubleDoors),set2=findDiscretePointLine(otherLines),queryLines=otherLines.filter(line=>!set2.has(line));let{internalEdges:internalEdges,circles:circles}=MaxiCircles.instance.maxiCircles(queryLines,circles2=>circles2.filter(isPolyHasTrajectoryPoint));const{circles:finalCircles}=MaxiCircles.instance.mergeCircles([...circlesList,...circles],internalEdges);lines_.forEach(line=>LineGroupType.removeByTypes(line,["doubleWall","wall"]));const grid=new PointSpatialHash,finalCirclesSet=new Set(finalCircles.flat(2));otherLines.forEach(line=>!finalCirclesSet.has(line)&&grid.insert(line.center,line)),finalCircles.forEach(group2=>{const id2=uuid();group2.forEach(line=>LineGroupType.set(line,id2,"doubleWall"))}),clearInternalLine&&finalCircles.forEach(group2=>{grid.queryPolygon(Polygon.fromByLines(group2)).forEach(res=>internalEdges.push(res.userData))}),otherLines.forEach(line=>{finalCirclesSet.has(line)||LineGroupType.hasType(line,"bayWindow")||LineGroupType.set(line,"default","wall")});const id=uuid();doorLines.forEach(doorLine=>{LineGroupType.replace(doorLine,id,"door")||LineGroupType.set(doorLine,id,"door")});const brid=uuid();balconyRailingLines.forEach(line=>{LineGroupType.replace(line,brid,"balconyRailing")||LineGroupType.set(line,brid,"balconyRailing")});const internalEdgesSet=new Set(internalEdges);return lines_=lines_.filter(line=>!internalEdgesSet.has(line))}const buildDoubleWallGroup=Object.assign((lines_,clearInternalLine)=>LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines_,line=>LineGroupType.hasType(line,"pillar")?"pillar":WallHole.isBeam(line)?"beam":"lines")).handle("lines",lines=>(WallHole.buildPairing(lines),group(lines,clearInternalLine))).merge(),{setTrajectory(trajectory_){trajectory=trajectory_?Object.values(trajectory_).filter(p2=>!(Math.abs(p2.x)<.01&&Math.abs(p2.y)<.01)):void 0}});class BuildGroup{static get bayWindow(){return buildBayWindowGroup}static get doubleWall(){return buildDoubleWallGroup}}class DoubleWallFinder{static group(lines,parallelAxis,verticalAxis,esp=.05,gap=0){esp/=verticalAxis.length;const vls=lines.map(line=>[verticalAxis.projectPointValue(line.start),line,[parallelAxis.projectPointValue(line.start),parallelAxis.projectPointValue(line.end)].sort((a2,b4)=>a2-b4)]).sort((a2,b4)=>a2[0]-b4[0]),newLines=[];for(let i=0;i<vls.length;i++){const[ipv,iline,[istart,iend]]=vls[i];for(let j=i+1;j<vls.length;j++){const[jpv,jline,[jstart,jend]]=vls[j];if(jpv-ipv>esp)break;Math.min(iend,jend)-Math.max(istart,jstart)>-gap&&new Array([iline,jline],[jline,iline]).forEach(([line,target])=>{if(WallHole.isBeam(line))return;const holeLines=[];for(const h2 of WallHole.getIterator(target)){const holeLine=WallHole.holeDataToLine(target,h2,!0,!1);holeLine.setLength(holeLine.length-.004),holeLines.push(holeLine)}line.points.forEach(point2=>{let pv=target.projectPointValue(point2);if(pv<0||pv>1)return;const pvPoint=target.pointAt(pv);if(holeLines.some(hl=>hl.isPointOnSegment(pvPoint)))return;const newLine=deriveLine(target);newLine.start.copy(point2),newLine.end.copy(pvPoint),newLines.push(newLine)})})}}return newLines}static find(lines,obstacle=[],esp=.4){return lines=splitIntersectedLine(lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,_line=>"lines")).handle("lines",lines2=>{const parallelAxis=lines2[0],verticalAxis=parallelAxis.clone().rotate(.5*Math.PI),[group1,group2]=LineSegmentUtils.groupByParallelToAxis(lines2,lines2[0],5),newLines1=this.group(group1,parallelAxis,verticalAxis,esp),newLines2=this.group(group2,verticalAxis,parallelAxis,esp),appendLines=newLines1.concat(newLines2);return lines2=lines2.concat(appendLines)}).merge(),1e-9,{obstacle:obstacle})}static buildGroup(lineSegments){let otherLines=[];return lineSegments=lineSegments.filter(line=>!(line.userData.isDoor||WallHole.isBeam(line)||line.userData.isBalconyRailing||line.userData.isBayWindowWin||line.userData.isBayWindow)||(otherLines.push(line),!1)),lineSegments=BuildGroup.doubleWall(lineSegments,!0),lineSegments=this.find(lineSegments,[...otherLines]),lineSegments=LineSegmentUtils.deduplicate(lineSegments,{necessaryLines:otherLines}),WallHole.filterIllegal(lineSegments),lineSegments=BuildGroup.doubleWall(lineSegments,!0),[...lineSegments,...otherLines]}}const VITE_OSS_BASEURL="https://img.unrealspace3d.com/common-assets/".endsWith("/")?"https://img.unrealspace3d.com/common-assets/":"https://img.unrealspace3d.com/common-assets//",DEFAULT_WALL_WIDTH=.12,MAX_WALL_WIDTH=.3;class RangeCore{static union(list){if(0===list.length)return[];const ranges=list.map(([start,end])=>start<=end?[start,end]:[end,start]).sort((a2,b4)=>a2[0]-b4[0]),result=[ranges[0]];for(let i=1;i<ranges.length;i++){const current=ranges[i],last=result[result.length-1];current[0]<=last[1]?last[1]=Math.max(last[1],current[1]):result.push(current)}return result}static intersection(list){if(0===list.length)return[];let start=-1/0,end=1/0;for(const[a2,b4]of list)if(start=Math.max(start,Math.min(a2,b4)),end=Math.min(end,Math.max(a2,b4)),start>end)return[];return[[start,end]]}static difference(range,occupied){const[start,end]=range;if(start>=end)return[];const ranges=this.union(occupied.map(([a2,b4])=>[Math.max(start,Math.min(a2,b4)),Math.min(end,Math.max(a2,b4))]).filter(([a2,b4])=>a2<b4)),result=[];let cursor=start;for(const[a2,b4]of ranges)cursor<a2&&result.push([cursor,a2]),cursor=Math.max(cursor,b4);return cursor<end&&result.push([cursor,end]),result}}class BoundExt{static createQuery(lines,trajectoryPoints,minWidth=.4){lines=lines.flatMap(line=>{let ranges=[];for(const holeData of WallHole.getIterator(line)){if("beam"!==(holeData.type??"passageEntrance"))continue;const holeLine=WallHole.holeDataToLine(line,holeData),startV=line.projectPointValue(holeLine.start),endV=line.projectPointValue(holeLine.end);ranges.push(startV<endV?[startV,endV]:[endV,startV])}if(ranges=RangeCore.union(ranges),0===ranges.length)return[line];const clipLines=ranges.map(range=>new LineSegment(line.pointAt(range[0]),line.pointAt(range[1])));return LineSegmentUtils.clippingByLines(line,clipLines)});const lsh=LineSegmentSpatialHash.from(lines);return{query(line){const center=line.center,set2=/* @__PURE__ */new Set;for(const point2 of trajectoryPoints){if(2===set2.size)break;const lineA=new LineSegment(center,point2);if(!lsh.queryLine(lineA).filter(targetLine=>{if(targetLine===line)return!1;if(LineGroupType.hasGroup(line))return!0;if(targetLine.isParallelTo(line)&&line.distanceToSegment(targetLine)<minWidth){if(targetLine.projectLineSegment(line).length/line.length>.6)return!1}return!0}).length){const position=line.getPointSideOfLine(point2);"on"!==position&&set2.add(position)}}return set2}}}static findExtWallByTraj(lines,trajectoryPoints,minWidth=.4){lines=lines.filter(line=>!line.userData.isBayWindow);const{query:query}=this.createQuery(lines,trajectoryPoints,minWidth);return lines=lines.filter(line=>{if(LineGroupType.hasType(line,"doubleWall")||LineGroupType.hasType(line,"pillar"))return;const set2=query(line);return line.userData.expandDirect=[...set2][0],set2.size<2||void 0})}static boundExtbyTrajAndOriginalData(opt){const zList=[];let lines=opt.data.map(({start:start,end:end,...opt2})=>{const line=new LineSegment(Point.from(start),Point.from(end));return line.userData=opt2,zList.push(start.z??0,end.z??0),line});const originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length;return this.boundExtbyTraj({...opt,lines:lines}).toOriginalData(originalZAverage)}static boundExtbyTraj(opt){let{lines:lines,trajectory:trajectory2,wallWidth:wallWidth=DEFAULT_WALL_WIDTH,updateDoubleWallGroup:updateDoubleWallGroup=!1,findCallBack:findCallBack}=opt;updateDoubleWallGroup&&(lines=DoubleWallFinder.buildGroup(lines));const trajectoryPoints=Object.keys(trajectory2).map(key=>Point.from(trajectory2[key]));return lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,line=>"cubic-bezier"===line.userData.shape?.type?"cubicBezier":WallHole.isBeam(line)?"exclude":"lines")).handle("lines",lines2=>{const findLines=BoundExt.findExtWallByTraj(lines2,trajectoryPoints);findLines.forEach(line=>{line.userData.expandDirect||(line.userData.miscellaneous=!0)});let exteriorLines=findLines.filter(line=>line.userData.expandDirect).filter(line=>!line.userData.isBalconyRailing).filter(line=>!LineGroupType.hasType(line,"bayWindow"));(lines2=lines2.filter(line=>!exteriorLines.includes(line))).push(...exteriorLines);const grid=PointSpatialHash.fromByLines(lines2),quadtree=Quadtree.from(lines2),arrayMap=new ArrayMap,pointMap=/* @__PURE__ */new Map;let appendLines=[];exteriorLines.forEach(line=>{const direction="left"===line.userData.expandDirect?line.getRightDirection():line.getLeftDirection();quadtree.raycast(line.center,direction,.001,wallWidth).length>0||(line.points.forEach(point2=>{const id=point2.hashCode();arrayMap.append(id,{point:point2,line:line}),pointMap.has(id)||pointMap.set(id,point2.clone()),grid.update(point2)}),line.translate(.5*wallWidth,direction),grid.updates(line.points),delete line.userData.wallWidth)}),arrayMap.forEach((list,id)=>{if(list.length>=2){if(list[0].line.isParallelTo(list[1].line,20))return;const p1=list[0].line.getIntersection(list[1].line);p1&&(list[0].point.copy(p1),list[1].point.copy(p1))}else{if(grid.queryCircle(pointMap.get(id),1e-4).length){const newLine=new LineSegment(pointMap.get(id),list[0].point.clone()),list_=list.filter(i=>!i.line.userData.isDoor&&!i.line.userData.isWindow);if(list_.length&&(newLine.userData=cloneUserData(list_[0].line.userData)),quadtree.queryCircle(newLine.center,1e-4).length)return;newLine.userData.boundExtAppendLine=!0,newLine.userData.boundExtAppendLineLen=newLine.length,WallHole.clear(newLine),appendLines.push(newLine)}}}),appendLines=LineSegmentUtils.mergeParallelSegments(appendLines).lines,lines2.push(...appendLines.filter(line=>line.length>1e-9));const doors=(lines2=splitIntersectedLine(lines2,1e-9)).filter(line=>line.userData.isDoor),walls=lines2.filter(line=>!line.userData.isDoor);return lines2=[...LineSegmentUtils.mergeCollinearSegmentsAll(walls,mergeLineUserData),...doors],WallHole.filterIllegal(lines2),lines2=lines2.filter(line=>line.length>1e-4).filter(line=>!line.userData.isDoor||line.length>.25),findCallBack&&findCallBack([...exteriorLines,...appendLines],trajectoryPoints),lines2}).merge(),{lines:lines,toOriginalData:originalZAverage=>lineDataToOriginalData(lines,originalZAverage)}}}function getDividingLine(lines){const maxLine=lines.reduce((maxLine2,line)=>maxLine2?line.length>maxLine2.length?line:maxLine2:line),normal=maxLine.normal(),axisLine=maxLine.center.expandAsLine(normal,.1).translate(.05,normal.multiplyScalar(-1)),axisValue=axisLine.projectPointValue(maxLine.start);let min=1/0,minAxisLine=null,max=-1/0,maxAxisLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.isParallelTo(maxLine)||line===maxLine)continue;const v2=axisLine.projectPointValue(line.start);Math.abs(v2-axisValue)<1e-6||(v2<min&&(min=v2,minAxisLine=line),v2>max&&(max=v2,maxAxisLine=line))}if(minAxisLine===maxAxisLine)return;const[_,clipLine]=[[axisValue,maxLine],[min,minAxisLine],[max,maxAxisLine]].sort((a2,b4)=>a2[0]-b4[0])[1];return clipLine}function segmentationPath(lines,clipLine){const quadtree=LineSegmentSpatialHash.from(lines),queryLine2=clipLine.clone().extendAlongDirection(100),removeLines=/* @__PURE__ */new Set,fractureLines=/* @__PURE__ */new Set;lines.forEach(line=>quadtree.insert(line));const list=quadtree.queryRectangle(queryLine2.toRectangle(.001,"butt"));for(let i=0;i<list.length;i++){const line=list[i];if(line.isParallelTo(queryLine2,8)){removeLines.add(line);continue}const point2=line.getIntersection(queryLine2);if(point2){if(line.start.equal(point2)||line.end.equal(point2))continue;const newLines=LineSegmentUtils.clippingByPoints(line,[point2],clippingLineUserData);removeLines.add(line),newLines.forEach(line2=>fractureLines.add(line2))}}(lines=lines.filter(line=>!removeLines.has(line))).push(...fractureLines);const groups=LineSegmentUtils.groupByCenterPointSide(lines,queryLine2),newGroups=[];return groups.forEach(group2=>{PointUtils.adsorb(group2.flatMap(line=>line.points),.001);const points=[...findDiscretePoint2(group2=mergeChainsLine(group2)).keys()],projValues=/* @__PURE__ */new Map;points.forEach(p2=>projValues.set(p2,queryLine2.projectPointValue(p2))),points.sort((a2,b4)=>projValues.get(a2)-projValues.get(b4));for(let i=0;i<points.length;i+=2){const p1=points[i],p2=points[i+1];p1&&p2&&group2.push(new LineSegment(p1.clone(),p2.clone()))}group2=mergeChainsLine(group2),newGroups.push(group2)}),quadtree.clear(),newGroups}function clippingDoubleWall(lines){if(4===(lines=mergeChainsLine(lines=lines.map(line=>line.clone()))).length)return[lines];const queue=[lines],groups=[];let pendingLines,count=0;for(;void 0!==(pendingLines=queue.pop());){if(count++,count>2e4)throw new Error("超过最大循环次数");if(pendingLines.length<=4){groups.push(pendingLines);continue}const clipLine=getDividingLine(pendingLines);if(!clipLine){groups.push(pendingLines);continue}const result=segmentationPath(pendingLines,clipLine).flatMap(group2=>LineSegmentUtils.groupByPath(group2));1!==result.length?result.forEach(group2=>{4===(group2=mergeChainsLine(group2)).length?groups.push(group2):queue.push(group2)}):groups.push(pendingLines)}return groups}const miniCircles=new MiniCircles;function clippingInsertObjectDoubleWall(lines){if(!lines.some(line=>WallHole.isHole(line)))return clippingDoubleWall(lines);const quadtree=Quadtree.from(lines),poly=Polygon.fromByLines2(lines);let polygons=[];for(let i=0;i<lines.length;i++){const line=lines[i];if(WallHole.isHole(line)){const normal=line.normal(),center=line.center;poly.pointWithin(center.add(normal.clone().multiplyScalar(1e-6)))||normal.multiplyScalar(-1),WallHole.forEachStorageType(line,data=>data.forEach(d2=>{const wioLine=WallHole.holeDataToLine(line,d2);wioLine.setLength(wioLine.length-.004);const len=wioLine.length;let startResults=quadtree.raycast(wioLine.start,normal,1e-4,10).filter(item=>item.targetLine.isParallelTo(wioLine)),endResults=quadtree.raycast(wioLine.end,normal,1e-4,10).filter(item=>item.targetLine.isParallelTo(wioLine));if(startResults.length>1&&(startResults=startResults.filter(item=>item.targetLine.projectLineSegment(wioLine).length/len>.01)),endResults.length>1&&(endResults=endResults.filter(item=>item.targetLine.projectLineSegment(wioLine).length/len>.01)),0===startResults.length||0===endResults.length)return;const startResult=startResults[0],endResult=endResults[0];if(startResult.targetLine!==endResult.targetLine){const pl1=startResult.targetLine.projectLineSegment(wioLine),pl2=endResult.targetLine.projectLineSegment(wioLine),finalPl=pl1.length>pl2.length?pl1:pl2;return void polygons.push(new Polygon([wioLine.projectPoint(finalPl.start,!1),finalPl.start,finalPl.end,wioLine.projectPoint(finalPl.end,!1)]))}polygons.push(new Polygon([wioLine.start,startResult.intersectPoint,endResult.intersectPoint,wioLine.end]))}))}}if(!polygons.length)return[lines];polygons=Polygon.booleanOp(polygons[0],polygons.slice(1),{type:"Union",scale:1e4});const newLines=polygons.map(poly2=>poly2.toLines()).flat().flatMap(line=>{let list=quadtree.queryRect(line.toRectangle(2e-4,"butt")).map(res=>res.line).filter(l=>l.isParallelTo(line,10));if(list.length){return LineSegmentUtils.clippingByLines(line,list)??[]}return[line]});lines.push(...newLines),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),lines=mergeChainsLine(lines=splitIntersectedLine(lines=lines.map(line=>line.clone()),1e-9)).filter(line=>line.length>0),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),WallHole.filterIllegal(lines).merge(lines);const{circles:circles}=miniCircles.miniCircle(lines);return circles.flatMap(circle=>clippingDoubleWall(circle))}class WallGroupManager{[Symbol.iterator](){return this.groups[Symbol.iterator]()}groups=[];add(group2){this.groups.push(group2)}forEach(fun){for(let i=0;i<this.groups.length;i++)fun(this.groups[i],i,i==this.groups.length-1)}map(fun){const list=[];for(let i=0;i<this.groups.length;i++)list.push(fun(this.groups[i],i));return list}findGroup(fun){for(let i=0;i<this.groups.length;i++){const group2=this.groups[i];if(fun(group2))return group2}}findGroupByType(type){return this.findGroup(group2=>group2.type===type)}findGroups(fun){const list=[];for(let i=0;i<this.groups.length;i++){const group2=this.groups[i];fun(group2)&&list.push(group2)}return list}findGroupsByType(type){"string"==typeof type&&(type=[type]);const set2=new Set(type);return this.findGroups(group2=>set2.has(group2.type))}static createGroup(lines){return LineSegmentUtils.group(lines,line=>"pillar"===line.userData.type||LineGroupType.hasType(line,"pillar")?"pillar":WallHole.isBeam(line)?"beam":line.userData.isBalconyRailing?"railing":"cubic-bezier"===line.userData.shape?.type?"cubicBezier":"wall")}static fromByLines(lineSegments){const wallGroupManager=new WallGroupManager,removeLines=[];LineGroupType.getGroupsByType(lineSegments,"doubleWall").forEach(doubleWall=>{wallGroupManager.add({type:"doubleWall",lines:doubleWall}),removeLines.push(...doubleWall)});LineGroupType.getGroupsByType(lineSegments,"pillar").forEach(pillar=>{wallGroupManager.add({type:"pillar",lines:pillar}),removeLines.push(...pillar)});const bayWindowGroups=LineGroupType.getGroupsByType(lineSegments,"bayWindow");bayWindowGroups.forEach(bayWindowGroup=>{wallGroupManager.add({type:"bayWindow",lines:bayWindowGroup,data:[]})});const doors=(lineSegments=bayWindowGroups.remainingLines).filter(line=>line.userData.isDoor);wallGroupManager.add({type:"door",lines:doors}),removeLines.push(...doors);const set2=new Set(removeLines),walls=[],windowLines=[],balconyRailingLines=[];return lineSegments.filter(line=>!set2.has(line)).forEach(line=>{line.userData.isBayWindow||(line.userData.isWindow?windowLines.push(line):line.userData.isBalconyRailing?balconyRailingLines.push(line):walls.push(line))}),walls.length&&wallGroupManager.add({type:"wall",lines:walls}),windowLines.length&&wallGroupManager.add({type:"window",lines:windowLines}),balconyRailingLines.length&&wallGroupManager.add({type:"balconyRailing",lines:balconyRailingLines}),wallGroupManager}static fromByLines1_5(lineSegments){const wallGroupManager=new WallGroupManager,removeLinesSet=/* @__PURE__ */new Set,structure={wall:[],cubicBezierWall:[],pillar:[],bayWindow:[],railing:[]};LineGroupType.getGroupsByType(lineSegments,"pillar").forEach(pillar=>{pillar.forEach(line=>removeLinesSet.add(line)),structure.pillar.push(pillar)}),lineSegments.forEach(line=>{"cubic-bezier"===line.userData.shape?.type&&(removeLinesSet.add(line),structure.cubicBezierWall.push(line))}),lineSegments=lineSegments.filter(line=>!removeLinesSet.has(line));LineGroupType.getGroupsByType(lineSegments,"doubleWall").forEach(doubleWall=>{doubleWall.forEach(line=>removeLinesSet.add(line));clippingInsertObjectDoubleWall(doubleWall).forEach(group2=>{const walls=function(lines){if(lines.length<4)return lines;if(lines.length>4){const polygon2=Polygon.fromByLinePath(lines).getMinimumBoundingRectangle();polygon2&&(lines=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines=[...lines].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,newLine.currentData.doubleWall=!0,WallHole.merge(newLine).filterIllegal(newLine),[newLine]}(group2);structure.wall.push(...walls)})});return LineGroupType.getGroupsByType(lineSegments,"bayWindow").forEach(bayWindowGroup=>{bayWindowGroup.forEach(line=>removeLinesSet.add(line)),structure.bayWindow.push(bayWindowGroup)}),lineSegments.filter(line=>!removeLinesSet.has(line)).forEach(line=>{line.userData.isBalconyRailing?structure.railing.push(line):structure.wall.push(line)}),wallGroupManager.add({type:"wall",lines:structure.wall}),wallGroupManager.add({type:"cubicBezierWall",lines:structure.cubicBezierWall}),wallGroupManager.add({type:"railing",lines:structure.railing}),structure.bayWindow.forEach(lines=>wallGroupManager.add({type:"bayWindow",lines:lines})),structure.pillar.forEach(lines=>wallGroupManager.add({type:"pillar",lines:lines})),wallGroupManager}}function createPromise(){let resolve,reject;const promise2=new Promise((re2,rt)=>{resolve=re2,reject=rt});return{get resolve(){return resolve},get reject(){return reject},get promise(){return promise2}}}function precision4(value){return 1e-4*Math.round(1e4*value)}function precision4Nullable(value){return null==value?void 0:precision4(value)}function cubicBezierCurve(start,controlPointStart,controlPointEnd,end,t2){const k=1-t2,k2=k*k,t22=t2*t2;return{x:k2*k*start.x+3*k2*t2*controlPointStart.x+3*k*t22*controlPointEnd.x+t22*t2*end.x,y:k2*k*start.y+3*k2*t2*controlPointStart.y+3*k*t22*controlPointEnd.y+t22*t2*end.y}}function splitCubicBezier(p0,p1,p2,p3,t2){const p01={x:p0.x+(p1.x-p0.x)*t2,y:p0.y+(p1.y-p0.y)*t2},p12_x=p1.x+(p2.x-p1.x)*t2,p12_y=p1.y+(p2.y-p1.y)*t2,p23={x:p2.x+(p3.x-p2.x)*t2,y:p2.y+(p3.y-p2.y)*t2},p012={x:p01.x+(p12_x-p01.x)*t2,y:p01.y+(p12_y-p01.y)*t2},p123={x:p12_x+(p23.x-p12_x)*t2,y:p12_y+(p23.y-p12_y)*t2},splitPoint={x:p012.x+(p123.x-p012.x)*t2,y:p012.y+(p123.y-p012.y)*t2};return[[p0,p01,p012,splitPoint],[splitPoint,p123,p23,p3]]}const defaultWallWidth$1=DEFAULT_WALL_WIDTH;class WallHoleDrawData{static singleHoleLine(line,grid){if(WallHole.isHole(line)){const newLines=[];WallHole.merge([line]);let openDirect=null;return"expandDirect"in line.userData&&(openDirect="left"===line.userData.expandDirect?line.getRightDirection():line.getLeftDirection()),WallHole.forEachStorageType(line,(data,k)=>{const list=grid&&function(grid,line){const startList=grid.queryPoint(line.start,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),endList=grid.queryPoint(line.end,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),results=[];return 0===startList.length?results.push(0):startList.some(item=>"wall"===item)?results.push(1):results.push(2),0===endList.length?results.push(0):endList.some(item=>"wall"===item)?results.push(1):results.push(2),results}(grid,line),dwh=.5*defaultWallWidth$1;data.map(hole=>{let{height:height,groundClearance:groundClearance,uuid:uuid2,type:type}=hole;const insertObjectLine=WallHole.holeDataToLine(line,hole),hole_type=insertObjectLine.userData.type;if(insertObjectLine.userData={openDirect:openDirect,wallWidth:line.userData.wallWidth??defaultWallWidth$1,wallHeight:line.userData.height,height:height,groundClearance:groundClearance,type:"drawWindow"===k?"window":type??"passageEntrance",maxHeight:line.userData.height,extrusion:hole.extrusion,p:{...hole.p},width:hole.width,full:hole.full,shape:hole.shape},!list||"beam"===hole_type||"passageEntrance"===hole_type)return newLines.push(insertObjectLine);const startDistance=insertObjectLine.start.distance(line.start);if(startDistance<dwh&&1===list[0]){const diff=dwh-startDistance;insertObjectLine.offsetStart(diff)}const endDistance=insertObjectLine.end.distance(line.end);if(endDistance<dwh&&1===list[1]){const diff=dwh-endDistance;insertObjectLine.offsetEnd(diff)}insertObjectLine.userData.winUuid=uuid2,insertObjectLine.userData.lineUuid=line.userData.uuid,insertObjectLine.userData.type="drawWindow"===k?"window":type??"passageEntrance",newLines.push(insertObjectLine)})}),newLines.filter(line2=>line2.length>defaultWallWidth$1),newLines}return null}static doubleHoleLine(lines){if(lines.length<3)return[];const heights=(lines=[...lines].sort((a2,b4)=>b4.length-a2.length)).map(line=>line.userData.height??0),direct=lines[0].direction(),center=Polygon.fromByLines2(lines).getCenter(),newLine=new LineSegment(center.clone(),center.clone().add(direct)),pvs=lines.flatMap(line=>line.points.map(p2=>newLine.projectPointValue(p2))).sort((a2,b4)=>a2-b4),minPoint=newLine.pointAt(pvs[0]),maxPoint=newLine.pointAt(pvs[pvs.length-1]),normalLine=newLine.clone().rotate(.5*Math.PI),npvs=lines.flatMap(line=>line.points.map(p2=>normalLine.projectPointValue(p2))).sort((a2,b4)=>a2-b4),wallWidth=(npvs[npvs.length-1]-npvs[0])*normalLine.length;newLine.start.copy(minPoint),newLine.end.copy(maxPoint);let wallHeight=0;lines.forEach(line=>wallHeight=Math.max(wallHeight,line.userData.height??0)),mergeLineUserData(newLine,lines),WallHole.merge(newLine);const newLines=[];return WallHole.forEachStorageType(newLine,(data,key)=>{data.forEach(({full:full,width:width,p:p2,height:height,groundClearance:groundClearance,type:type})=>{const point2=Point.from(p2),direct2=newLine.direction();full&&(width=newLine.length);const insertObjectLine=point2.expandAsLine(direct2,width).translate(.5*-width,direct2);try{insertObjectLine.start.copy(newLine.projectPoint(insertObjectLine.start,!1)),insertObjectLine.end.copy(newLine.projectPoint(insertObjectLine.end,!1))}catch(error){}insertObjectLine.userData={wallHeight:wallHeight||void 0,wallWidth:wallWidth,height:height,groundClearance:groundClearance,type:"drawWindow"===key?"window":type??"passageEntrance",maxHeight:Math.max(...heights)},newLines.push(insertObjectLine)})}),newLines.filter(line=>line.length>defaultWallWidth$1)}static handleHoleDrawData(doubleWallGroup,wall,lines=[]){const grid=new PointSpatialHash;lines.forEach(line=>line.points.forEach(p2=>grid.insert(p2,line)));const holes=new ArrayMap,newLines=[];return(wall=wall.filter(line=>{const holeLines=this.singleHoleLine(line,grid);if(!holeLines?.length)return!0;{holeLines.forEach(line2=>holes.append(line2.userData.type,line2));const lines2=LineSegmentUtils.clippingByPoints(line,PointUtils.adsorb(holeLines.flatMap(line2=>line2.points))).filter(line2=>{const center=line2.center;return!holeLines.some(line22=>line22.isPointOnSegment(center))});newLines.push(...lines2)}})).push(...newLines),grid.clear(),doubleWallGroup=doubleWallGroup.filter(lines2=>{if(lines2.length<3)return!1;const holeLines=this.doubleHoleLine(lines2);return holeLines.forEach(line=>holes.append(line.userData.type,line)),0===holeLines.length}),Object.assign(holes,{get untreatedDoubleWallGroup(){return doubleWallGroup},get untreatedWall(){return wall},get passageEntrance(){return holes.get("passageEntrance")??[]},get window(){return holes.get("window")??[]},get door(){return holes.get("door")??[]},get beam(){return holes.get("beam")??[]}})}}function createGeometry(points,options){points=points.map(p2=>p2 instanceof Point?new THREE.Vector2(p2.x,p2.y):p2);const shape=new THREE.Shape(points);return new THREE.ExtrudeGeometry(shape,{bevelEnabled:!1,...options})}class ExtrudeMesh extends THREE.Mesh{geometry;options;constructor(points,options,material){const geometry=createGeometry(points,options);super(geometry,material),this.geometry=geometry,this.options=options}setPoints(points,options=this.options){const geometry=createGeometry(points,options);this.geometry=geometry}}class BayWindowHelper{static computedInfo(lines){let dottedLine=lines.find(line=>line.userData.isBayWindow),windowLine=lines.find(line=>line.userData.isWindow),counter=new CounterMap,side="LEFT",depth=0;if(dottedLine){for(let i=0;i<lines.length;i++){const line=lines[i];if(line===dottedLine)continue;const center=line.center,side2=dottedLine.getPointSideOfLine(center);"on"!==side2&&counter.increment(side2),depth=Math.max(depth,line.start.distance(dottedLine.projectPoint(line.start,!1)),line.end.distance(dottedLine.projectPoint(line.end,!1)))}return side="left"===counter.getMaxKey()?"LEFT":"RIGHT",{side:side,depth:depth,dottedLine:dottedLine,windowLine:windowLine}}}static getDrawData(lines){if(4===(lines=mergeChainsLine(lines.map(line=>line.clone()))).length){let bayWindowLine=null,windowLine=null,deptLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isBayWindow?bayWindowLine=line:line.userData.isWindow&&line.userData.drawWindow&&line.userData.drawWindow.length?windowLine=line:deptLine=line}if(bayWindowLine&&windowLine&&deptLine){const{width:width,height:height,groundClearance:groundClearance}=windowLine.userData.drawWindow[0],direction=Point.zero();return deptLine.isSameEndpointAsEnd(bayWindowLine)?deptLine.start.directionFrom(deptLine.end,direction):deptLine.end.directionFrom(deptLine.start,direction),{height1:bayWindowLine.userData.topClearance??0,height2:height,height3:groundClearance,depth:deptLine.length,windowWidth:width,windowHeight:height,bayWindowLine:bayWindowLine,windowLine:windowLine,deptLine:deptLine,direction:direction}}}return null}static getDrawData2(lines){lines=mergeChainsLine(lines.map(line=>line.clone()));let bayWindowLine=null,windowLine=null;for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isBayWindow?bayWindowLine=line:line.userData.isWindow&&line.userData.drawWindow&&line.userData.drawWindow.length&&(windowLine=line)}if(bayWindowLine&&windowLine){const{width:width,height:height,groundClearance:groundClearance}=windowLine.userData.drawWindow[0],direction=Point.zero();return{height1:bayWindowLine.userData.topClearance??0,height2:height,height3:groundClearance,windowWidth:width,windowHeight:height,direction:direction}}return null}static getDrawDataAll(lineSegments){const groups=LineGroupType.getGroupsByType(lineSegments,"bayWindow"),drawDataList=groups.map(this.getDrawData);return groups.map((group2,indxe)=>({group:group2,drawData:drawDataList[indxe]})).filter(item=>item.drawData)}static drawDataToModel(drawData){const pos=drawData.bayWindowLine.center,dirct=drawData.bayWindowLine.direction(),length=drawData.bayWindowLine.length,bayWindowLine=Point.zero().expandAsLine(dirct,length).translate(.5*length,dirct.multiplyScalar(-1)),winGroup=new THREE.Group,material=new THREE.MeshBasicMaterial({color:16777215});winGroup.position.set(pos.x,pos.y,0);const rectangle=bayWindowLine.toRectangle(DEFAULT_WALL_WIDTH),extrudeMesh=new ExtrudeMesh(rectangle.points,{depth:drawData.height3},material);winGroup.add(extrudeMesh);const rectangle2=bayWindowLine.clone().translate(drawData.depth,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH),extrudeMesh2=new ExtrudeMesh(rectangle2.points,{depth:drawData.height2},new THREE.MeshPhongMaterial({color:16777215,transparent:!0,opacity:.2}));extrudeMesh2.position.z=drawData.height3,winGroup.add(extrudeMesh2);const rectangle3=bayWindowLine.start.expandAsLine(drawData.direction,drawData.depth).translate(-.06,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH,"butt"),extrudeMesh3=new ExtrudeMesh(rectangle3.points,{depth:drawData.height2},material);extrudeMesh3.position.z=drawData.height3,winGroup.add(extrudeMesh3);const rectangle4=bayWindowLine.end.expandAsLine(drawData.direction,drawData.depth).translate(-.06,drawData.direction).toRectangle(DEFAULT_WALL_WIDTH,"butt"),extrudeMesh4=new ExtrudeMesh(rectangle4.points,{depth:drawData.height2},material);extrudeMesh4.position.z=drawData.height3,winGroup.add(extrudeMesh4);const extrudeMesh5=new ExtrudeMesh(rectangle.points,{depth:drawData.height1},material);extrudeMesh5.position.z=drawData.height3+drawData.height2,winGroup.add(extrudeMesh5);const rectangle6=bayWindowLine.clone().translate(.5*drawData.depth,drawData.direction).toRectangle(drawData.depth-DEFAULT_WALL_WIDTH,"butt"),extrudeMesh6=new ExtrudeMesh(rectangle6.points,{depth:.001},material);extrudeMesh6.position.z=drawData.height3,winGroup.add(extrudeMesh6);const extrudeMesh7=new ExtrudeMesh(rectangle6.points,{depth:.001},material);return extrudeMesh7.position.z=drawData.height3+drawData.height2,winGroup.add(extrudeMesh7),winGroup}}const holeTypeMap={door:"DOOR",RAILING:"RAILING",window:"WINDOW",passageEntrance:"WALL_HOLE",bay_window:"BAY_WINDOW"},placeHoldersMap={switch:"开关",socket:"插座"},WALL_HEIGHT_KEY$1=/* @__PURE__ */Symbol("height");class ThreeVJiaPipeline extends Pipeline{manager;index=0;maxHeight;lines;constructor(lines,maxHeight){super(),this.maxHeight=maxHeight,this.lines=lines,this.manager=WallGroupManager.fromByLines(lines),this.use({type:"bayWindow",handle:this.bayWindowHandle.bind(this)}),this.use({type:"doubleWall",handle:this.doubleWallHandle.bind(this)}),this.use({type:"wall",handle:this.wallHandle.bind(this)}),this.use({type:"door",handle:this.doorHandle.bind(this)}),this.use({type:"window",handle:this.wallHandle.bind(this)}),this.use({type:"balconyRailing",handle:this.balconyRailing.bind(this)}),this.use({type:"wallHole",handle:this.wallHoleHandle.bind(this)})}doubleWallHandle({data:{lines:lines},cache:cache2}){const groups=clippingInsertObjectDoubleWall(lines),{door:door,window:windowLines,passageEntrance:passageEntrance,untreatedDoubleWallGroup:untreatedDoubleWallGroup}=WallHoleDrawData.handleHoleDrawData(groups,[]),walls=untreatedDoubleWallGroup.flatMap(lines2=>{if(lines2.length<4)return lines2;if(lines2.length>4){const polygon2=Polygon.fromByLinePath(lines2).getMinimumBoundingRectangle();polygon2&&(lines2=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines2=[...lines2].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines2[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines2),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,[newLine]});this.manager.add({type:"wallHole",lines:windowLines}),this.manager.add({type:"wallHole",lines:door}),this.manager.add({type:"wallHole",lines:passageEntrance}),cache2.wallLines=[...cache2.wallLines,...walls,...windowLines,...door,...passageEntrance]}wallHandle({data:{lines:lines},cache:cache2}){const holeLines=lines.flatMap(line=>WallHoleDrawData.singleHoleLine(line)??[]);this.manager.add({type:"wallHole",lines:holeLines}),cache2.wallLines.push(...lines)}doorHandle({data:{lines:lines},cache:cache2}){const doors=lines.map(line=>{const doorLine=new LineSegment(line.start.clone(),line.end.clone());return doorLine.userData={groundClearance:line.userData.drawDoorData?.sillHeight,height:line.userData.drawDoorData?.height,type:"door",wallHeight:line.userData.drawDoorData?.height,wallWidth:void 0},doorLine});this.manager.add({type:"wallHole",lines:doors}),cache2.wallLines.push(...doors)}bayWindowHandle({data:{lines:lines},cache:cache2}){const info=BayWindowHelper.computedInfo(lines);if(info){const{dottedLine:dottedLine,windowLine:windowLine,depth:depth,side:side}=info,line=new LineSegment(dottedLine.start.clone(),dottedLine.end.clone()),win=windowLine?.userData.drawWindow&&windowLine.userData.drawWindow[0];"LEFT"===side&&line.swapValue(),line.translate(.5*-DEFAULT_WALL_WIDTH,line.normal()),line.userData={groundClearance:win?.groundClearance??0,height:win?.height,type:"bay_window",wallHeight:win?.height,wallWidth:void 0,depth:depth??.5,openSide:side},this.manager.add({type:"wallHole",lines:[line]}),line.setLength(line.length+.001),cache2.wallLines.push(line)}}balconyRailing({data:{lines:lines},cache:cache2}){const brls=lines.map(line=>{line.currentData[WALL_HEIGHT_KEY$1]=line.userData.height;const brl=new LineSegment(line.start.clone(),line.end.clone());return brl.userData={groundClearance:0,height:line.userData.height,type:"RAILING",wallWidth:void 0},brl});this.manager.add({type:"wallHole",lines:brls}),cache2.wallLines.push(...lines)}wallHoleHandle({data:{lines:lines,json:json}}){lines.forEach(line=>{if(line.length<1e-4)return;let type=holeTypeMap[line.userData.type]??"WALL_HOLE";const hole={id:this.index++,type:type,start:line.start.precision4().toJson2D(),end:line.end.precision4().toJson2D(),depth:precision4Nullable(line.userData.depth),height:precision4Nullable(line.userData?.height??2.1),sillHeight:precision4Nullable(line.userData?.groundClearance??0),groundClearance:precision4Nullable(line.userData?.groundClearance??0)};"DOOR"===type?Object.assign(hole,{openSide:"RIGHT"}):"BAY_WINDOW"===type&&Object.assign(hole,{openSide:line.userData.openSide}),json.holes.push(hole)})}transform(){const option={version:"2",name:"",communityName:"",city:"",province:"",height:this.maxHeight,walls:[],pillars:[],beams:[],holes:[],rooms:[],placeHolders:[],center:{x:0,y:0},angle:0},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),cache2.wallLines.forEach(line=>{option.walls.push({ID:this.index++,start:line.start.precision4().toJson2D(),end:line.end.precision4().toJson2D(),thickness:precision4(Math.max(line.userData.wallWidth?line.userData.wallWidth:DEFAULT_WALL_WIDTH,DEFAULT_WALL_WIDTH)),type:"LINE",isDoor:!1,loadBearingWall:!1,height:precision4(line.currentData[WALL_HEIGHT_KEY$1]??this.maxHeight)})}),option}static appendRooms(json,rooms){return Array.isArray(json.rooms)||(json.rooms=[]),rooms.map((room,i)=>{json.rooms.push({name:`房间(${i+1})`,position:room.center.clone().rotate(json.center,json.angle).toJson(),roomTypeId:17,polygon:room.ploy.map(p2=>p2.clone().rotate(json.center,json.angle).toJson2D()),id:i})}),json}static appendPlaceHolders(json,publicInfo,z){Array.isArray(json.placeHolders)||(json.placeHolders=[]);const rooms=json.rooms,roomPloys=rooms.map(room=>new Polygon(room.polygon.map(p2=>Point.from(p2))));return 0===roomPloys.length||publicInfo?.itemInfo?.forEach((item,i)=>{if(!placeHoldersMap[item.category])return;const contour=item.quadContour??item.contour;if(0===contour.length)return void console.warn(`第${i}个物品轮廓为空`);let itemPoly=new Polygon(contour.map(p2=>Point.from(p2).rotate(json.center,json.angle)));const center=itemPoly.getCenter(),index2=roomPloys.findIndex(poly=>poly.pointWithin(center));if(index2<0)return;try{let newR=itemPoly.getMinimumBoundingRectangle();newR&&(itemPoly=newR)}catch(error){console.warn(`第${i}个物品 转四边形错误`)}const direction=Point.from(item.direction).normalize().rotate(Point.zero(),json.angle);itemPoly[1].distanceSquared(itemPoly[0])<itemPoly[2].distanceSquared(itemPoly[1])&&itemPoly.reverse();const rect=itemPoly.map(p2=>p2.toJson2D());json.placeHolders.push({name:placeHoldersMap[item.category],polygon:rect,direction:direction.toJson2D(),height:item.box.max.z-item.box.min.z,sillHeight:item.box.min.z-z,roomId:rooms[index2].roomTypeId,id:i})}),json}static toThreeVJiaJson(lineSegments,angle=0,updateGroup=!0){let centerVec2=null;lineSegments=LineSegmentUndirectedGraph.rotate(lineSegments.map(line=>line.clone()),angle,(line,center,angle2)=>{centerVec2||(centerVec2={x:center.x,y:center.y}),WallHole.forEachStorageType(line,data=>{data.forEach(item=>{const point2=Point.from(item.p);point2.rotate(center,angle2),item.p=point2.toJson(item.p.z)})})});const heights=[];lineSegments.forEach(line=>{line.userData.isDoor&&heights.push(line.userData.height??0),WallHole.forEachStorageType(line,data=>{heights.push(line.userData.height??0),data.forEach(item=>{const h2=(item.height??0)+(item.groundClearance??0);heights.push(h2)})})}),0===heights.length&&heights.push(2.8);const maxHeight=precision4(Math.max(...heights));updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));const json=new ThreeVJiaPipeline(lineSegments,maxHeight).transform();return json.angle=angle,json.center=centerVec2,json}static mergeParallelLine(json){let map=new ArrayMap;return json.walls.forEach(line=>{map.append(line.thickness.toFixed(4),line)}),json.walls=map.map(list=>{if(1===list.length)return list;const lines=list.map((line,i)=>((line=LineSegment.from(line)).userData=list[i],line));return LineSegmentUtils.mergeCollinearSegmentsAll(lines,(newLine,group2)=>{group2.forEach(line=>Object.assign(newLine.userData,line.userData))}).map(line=>({...line.userData,start:line.start.toJson2D(),end:line.end.toJson2D()}))}).flat(),json}static externalDataToThreeVJia(json,height){let id=0;const cacheJson={version:"2",name:"",center:json.angleCorre.center,angle:json.angleCorre.angle,communityName:"",city:"",province:"",height:height,walls:[],pillars:[],beams:[],holes:[],rooms:[],placeHolders:[]};this.mergeParallelLine(json),json.walls.forEach(wall=>{cacheJson.walls.push({ID:id++,start:wall.start,end:wall.end,thickness:wall.thickness,type:"LINE",isDoor:!1,loadBearingWall:!1,height:height??wall.height})});const point2=Point.zero();json.holes.forEach(hole=>{const data={id:id++,type:"DOOR",start:hole.start,end:hole.end,height:hole.height??2.1,sillHeight:hole.groundClearance??0,groundClearance:hole.groundClearance??0};switch(hole.type){case"door":data.type="DOOR",data.openSide="RIGHT";break;case"window":data.type="WINDOW";break;case"passageEntrance":data.type="WALL_HOLE";break;case"byWindow":if(data.type="BAY_WINDOW",hole.shape){const line2=LineSegment.from(hole);hole.shape.path.forEach(p2=>{point2.copy(p2),data.depth=Math.max(data.depth??0,line2.distanceToPoint(point2))});const center=PointUtils.getCenter(hole.shape.path);data.openSide="left"===line2.getPointSideOfLine(center)?"LEFT":"RIGHT"}break;default:return}cacheJson.holes.push(data)}),json.railings.forEach(railing=>{cacheJson.holes.push({id:id++,type:"RAILING",start:railing.start,end:railing.end,height:railing.height,sillHeight:0,groundClearance:0}),cacheJson.walls.push({ID:id++,start:railing.start,end:railing.end,thickness:railing.thickness,type:"LINE",isDoor:!1,loadBearingWall:!1,height:height??railing.height})}),cacheJson.holes.sort((a2,_)=>"WALL_HOLE"===a2.type?1:-1),json.beams.forEach(beam=>{cacheJson.beams.push({id:id++,start:beam.start,end:beam.end,height:beam.height,thickness:beam.thickness})});const pool2=PointUtils.createPool();json.pillars.forEach(pillar=>{const ploy=new Polygon(pillar.shape.map(p2=>pool2.point.copy(p2)));try{const rect=ploy.getMinimumBoundingRectangle();if(!rect)return;const shape=rect.map(p2=>p2.toJson2D());shape.length=4,cacheJson.pillars.push({polygon:shape})}finally{pool2.freeAll()}});const line=new LineSegment;return cacheJson.walls.forEach(wall=>{line.start.copy(wall.start),line.end.copy(wall.end),line.setLength(line.length+.002),wall.start=line.start.toJson2D(),wall.end=line.end.toJson2D(),wall.thickness!==DEFAULT_WALL_WIDTH&&(wall.thickness+=.002)}),deepPrecision4(cacheJson)}}function mToMm(value){return Number((1e3*value).toFixed(0))}function mmTom(value){return Number((value/1e3).toFixed(4))}function getLineIndexByCenter(targetLines,lines){const grid=Quadtree.from(lines,(_,i)=>({index:i}));return targetLines.map(line=>{const res=grid.queryPoint(line.center);return res.length?res[0].userData.index:-1})}function originalDataToLineData(data){let lineSegments=[],verticalReferenceIndex=-1;const zList=[];data.forEach(({start:start,end:end,...opt},index2)=>{zList.push(start.z??0,end.z??0);const lineSegment=new LineSegment(Point.from(start),Point.from(end));lineSegment.userData=opt,lineSegments.push(lineSegment),opt.uuid&&(lineSegment.uuid=opt.uuid),lineSegment.userData.isWindow&&lineSegment.userData.drawWindow?.forEach(item=>{item.uuid=item.uuid??uuid()}),opt.isVerticalReferenceLine&&(verticalReferenceIndex=index2)});return{originalZAverage:zList.reduce((count,num)=>count+num,0)/zList.length,lineSegments:lineSegments,verticalReferenceIndex:verticalReferenceIndex}}function toOriginalDataItem(line,originalZAverage=0,quadtree,lines){const userData=line.userData,drawWindow=userData.drawWindow,insetionArr=quadtree?quadtree.queryLineSegment(line).filter(r2=>r2.line!==line&&!r2.userData?.isDoor).map(r2=>({index:lines?.indexOf(r2.line)})):[];return{...cloneUserData(userData),start:line.start.toJson(originalZAverage),end:line.end.toJson(originalZAverage),insetionArr:insetionArr,length:line.length,uuid:line.uuid,drawWindow:drawWindow&&drawWindow.map(w=>({...cloneUserData(w),p:{x:w.p.x,y:w.p.y,z:w.p.z}}))}}function lineDataToOriginalData(lines,originalZAverage=0,quadtree){return quadtree||(quadtree=new Quadtree(Box2.fromByLineSegment(lines)),lines.forEach(line=>quadtree?.insert({line:line,userData:void 0})),Promise.resolve().then(()=>quadtree?.clear())),lines.map(line=>toOriginalDataItem(line,originalZAverage,quadtree,lines))}function deriveLine(line){const newLine=line.clone(!0,!1);return delete newLine.userData.isBalconyRailing,delete newLine.userData.isBayWindow,delete newLine.userData.isBayWindowWin,delete newLine.userData.isDoor,delete newLine.userData.isWindow,delete newLine.userData.isVerticalReferenceLine,WallHole.clear(newLine),newLine}function splitIntersectedLine(lines,minLen=1e-9,opt){const{dedup:dedup=!0,balconyRailing:balconyRailing={filteringRatio:.2},obstacle:obstacle=[]}=opt??{},removeSet=/* @__PURE__ */new Set;let otherLines=[];return lines=lines.filter(line=>"cubic-bezier"!==line.userData.shape?.type||(otherLines.push(line),!1)),lines=(lines=LineSegmentUtils.splitIntersections(lines,{obstacle:obstacle,onSplit:(line,newLines)=>{try{if(WallHole.splitHole(line,newLines),line.userData.isBayWindow){newLines.sort((a2,b4)=>b4.length-a2.length);for(let i=1;i<newLines.length;i++)newLines[i].userData.isBayWindow=!1}if(balconyRailing&&line.userData.isBalconyRailing){const len=line.length;newLines.forEach(line2=>{line2.length/len<balconyRailing.filteringRatio&&("discard"===opt?.balconyRailing?.behavior?removeSet.add(line2):delete line2.userData.isBalconyRailing)})}}catch(error){console.error(error.message)}}})).filter(line=>line.length>=minLen&&!removeSet.has(line)&&LineSegmentUtils.legitimacy(line)),(dedup?LineSegmentUtils.deduplicate(lines,{precision:3}):lines).concat(otherLines)}function mergeChainsLine(lines,callBack,removeLines,newLines){callBack=callBack??mergeLineUserData;let otherLines=[],lines_=[];return lines.forEach(line=>{line.userData.isBalconyRailing||line.userData.isDoor||"cubic-bezier"===line.userData.shape?.type?otherLines.push(line):lines_.push(line)}),(lines=LineSegmentUndirectedGraph.breakpointMerging(lines_,callBack,removeLines,newLines)).push(...otherLines),lines}function clippingLineUserData(newLine,line2){const{drawWindow:drawWindow,passageEntrance:passageEntrance,...opt}=line2.userData;WallHole.forEachStorageType(line2,(data,key)=>{if("drawWindow"===key)return;const removeSet=/* @__PURE__ */new Set;data.forEach((item,i)=>{if("door"!==item.type)return;const point2=Point.from(item.p);newLine.projectPoint(point2)?data[i]=item:removeSet.add(i)}),newLine.userData[key]=data.filter((_,i)=>!removeSet.has(i))}),WallHole.filterIllegal([newLine]),Object.assign(newLine.userData,opt)}function mergeLineUserData(newLine,line2){if(Array.isArray(line2))return(line2=[...line2].sort((a2,b4)=>a2.length-b4.length)).forEach(l=>mergeLineUserData(newLine,l));WallHole.cancelPairing(newLine,line2),!1===line2.userData.isDoor&&delete line2.userData.isDoor,!1===line2.userData.isWindow&&delete line2.userData.isWindow,!1===line2.userData.isBayWindow&&delete line2.userData.isBayWindow,!1===line2.userData.isPassageEntrance&&delete line2.userData.isPassageEntrance,!1===newLine.userData.isPassageEntrance&&delete newLine.userData.isPassageEntrance;const{drawWindow:drawWindow,passageEntrance:passageEntrance,...opt}=line2.userData;Object.keys(opt).forEach(key=>{void 0===opt[key]&&delete opt[key]}),drawWindow&&(newLine.userData.drawWindow||(newLine.userData.drawWindow=[]),newLine.userData.drawWindow.push(...drawWindow)),passageEntrance&&(newLine.userData.passageEntrance||(newLine.userData.passageEntrance=[]),newLine.userData.passageEntrance.push(...passageEntrance)),Object.assign(newLine.userData,opt)}function getDrawingMaxHeight(lineSegments){const heights=[];lineSegments.forEach(line=>{line.userData.isDoor&&heights.push(line.userData.height??0),WallHole.forEachStorageType(line,data=>{heights.push(line.userData.height??0),data.forEach(item=>{const h2=(item.height??0)+(item.groundClearance??0);heights.push(h2)})})}),0===heights.length&&heights.push(2.8);return precision4(Math.max(...heights))}function deepPrecision4(value){return"number"==typeof value?Number(value.toFixed(4)):Array.isArray(value)?(value.forEach((item,index2)=>{value[index2]=deepPrecision4(item)}),value):(value&&"object"==typeof value&&Object.keys(value).forEach(key=>{value[key]=deepPrecision4(value[key])}),value)}function computeCubicBezierByLine(line,segmentSize=.04){if("cubic-bezier"!=line.userData.shape?.type)return[];const arr=[],count=Math.max(40,Math.ceil(line.end.distance(line.start)/segmentSize));for(let i=0;i<=count;i++){const t2=i/count,{x:x,y:y}=cubicBezierCurve(line.start,line.userData.shape.controlPointStart,line.userData.shape.controlPointEnd,line.end,t2);arr.push([x,y,t2])}return arr}const tools=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ThreeVJiaPipeline:ThreeVJiaPipeline,WallGroupManager:WallGroupManager,clippingLineUserData:clippingLineUserData,computeCubicBezierByLine:computeCubicBezierByLine,deepPrecision4:deepPrecision4,deriveLine:deriveLine,findBoundExt:async function(lines,trajectorys,originalZAverage=0){const{promise:promise2,resolve:resolve,reject:reject}=createPromise(),url=new URL("data:video/mp2t;base64,DQppbXBvcnQgeyBERUZBVUxUX1dBTExfV0lEVEggfSBmcm9tICJAL2NvbnN0YW50cyINCmltcG9ydCB7IEJvdW5kRXh0IH0gZnJvbSAiLi9Cb3VuZEV4dCINCmltcG9ydCB7IG9yaWdpbmFsRGF0YVRvTGluZURhdGEgfSBmcm9tICIuL3Rvb2xzIg0KDQpzZWxmLm9ubWVzc2FnZSA9IChlKSA9PiB7DQogICAgY29uc3QgeyBsaW5lcywgdHJhamVjdG9yeXMsIG9yaWdpbmFsWkF2ZXJhZ2UgfSA9IEpTT04ucGFyc2UoZS5kYXRhKQ0KICAgIGNvbnN0IGxpbmVTZWdtZW50cyA9IG9yaWdpbmFsRGF0YVRvTGluZURhdGEobGluZXMpLmxpbmVTZWdtZW50cw0KDQogICAgY29uc3QgZGF0YSA9IEJvdW5kRXh0LmJvdW5kRXh0YnlUcmFqKHsNCiAgICAgICAgbGluZXM6IGxpbmVTZWdtZW50cywgDQogICAgICAgIHRyYWplY3Rvcnk6IHRyYWplY3RvcnlzLA0KICAgICAgICB3YWxsV2lkdGg6IERFRkFVTFRfV0FMTF9XSURUSA0KICAgIH0pLnRvT3JpZ2luYWxEYXRhKG9yaWdpbmFsWkF2ZXJhZ2UpDQoNCiAgICBzZWxmLnBvc3RNZXNzYWdlKEpTT04uc3RyaW5naWZ5KGRhdGEpKQ0KfQ==",import.meta.url),data=lineDataToOriginalData(lines),worker=new Worker(url,{type:"module"});return worker.onerror=err=>{reject({err:err,url:url})},worker.onmessage=e=>{const data2=JSON.parse(e.data);resolve(originalDataToLineData(data2).lineSegments)},worker.postMessage(JSON.stringify({lines:data,trajectorys:trajectorys,originalZAverage:originalZAverage})),promise2},getDrawingMaxHeight:getDrawingMaxHeight,getLineIndexByCenter:getLineIndexByCenter,innerWallLine:function(lines,trajectory2){lines=lines.filter(line=>!line.userData.isBayWindow),lines=LineSegmentUtils.clone(lines),lines=BuildGroup.doubleWall(lines);let outerLines=[];if(trajectory2){const trajectoryPoints=Object.values(trajectory2).map(v2=>Point.from(v2));outerLines=BoundExt.findExtWallByTraj(lines,trajectoryPoints);const outerLinesSet=new Set(outerLines);lines=lines.filter(line=>!outerLinesSet.has(line)),outerLines=outerLines.filter(line=>line.userData.expandDirect)}else{outerLines=lines.filter(line=>line.userData.expandDirect);const outerLinesSet=new Set(outerLines);lines=lines.filter(line=>!outerLinesSet.has(line))}const manager=WallGroupManager.fromByLines(lines),pipeline=new Pipeline;pipeline.use("doubleWall",ctx=>{ctx.cache.doubleWall.push(ctx.data)}),pipeline.use(["wall","bayWindow","door","window"],ctx=>{const lines2=ctx.data.filter(line=>!LineGroupType.hasType(line,"doubleWall"));ctx.cache.lines.push(...lines2)});const option={doubleWall:[],lines:[]};manager.forEach(group2=>pipeline.run(group2.type,group2.lines,option));const lud=new LineSegmentUndirectedGraph(option.lines),temLine=new LineSegment;let singleLine=[];const wallWidths=[];lud.forEachPathLine((start,end,_line,index2,endType,indxeList)=>{temLine.start.copy(start),temLine.end.copy(end);const wallWidth=DEFAULT_WALL_WIDTH;wallWidths[index2]=wallWidth;const hw=indxeList.length?.5*Math.max(...indxeList.map(i=>wallWidths[i])):.5*wallWidth;0!==index2&&temLine.offsetStart(hw),"none"===endType&&temLine.offsetEnd(-hw),singleLine.push(...temLine.setLength(temLine.length+1e-4).toRectangle(wallWidth,"butt").toLines())});const paths=Polygon.multipleFromByLines(singleLine);if(paths.length>1){const[p1,...pn2]=paths;singleLine=Polygon.booleanOp(p1,pn2,{type:"Union",scale:1e4}).flatMap(p2=>p2.toLines())}singleLine=singleLine.filter(line=>line.length>.2),singleLine=LineSegmentUtils.deduplicate(LineSegmentUtils.splitIntersections(singleLine,{obstacle:option.doubleWall.flat()}));const polys=option.doubleWall.map(lines2=>Polygon.fromByLines2(lines2));return singleLine=singleLine.filter(line=>{const center=line.center;return!polys.find(poly=>poly.pointIn(center))}),[...singleLine,...option.doubleWall.flat(),...outerLines]},lineDataToOriginalData:lineDataToOriginalData,mToMm:mToMm,mergeChainsLine:mergeChainsLine,mergeGltf:async function(paths,binary=!0){await GltfInit();const load2=new gltf.GLTFLoader,onject3dList=await Promise.all(paths.map(path=>load2.loadAsync(path))),group2=new Group$1;return onject3dList.map(g=>group2.add(g.scene)),(new gltf.GLTFExporter).parseAsync([group2],{binary:binary})},mergeLineUserData:mergeLineUserData,mmTom:mmTom,originalDataToLineData:originalDataToLineData,splitIntersectedLine:splitIntersectedLine,toOriginalDataItem:toOriginalDataItem},Symbol.toStringTag,{value:"Module"})),units={Unitless:1,Inches:39.37007874015748,Feet:3.280839895013123,Miles:.0006213711922373339,Millimeters:1e3,Centimeters:100,Meters:1,Kilometers:.001,Microinches:39370078.74015748,Mils:39370.07874015748,Yards:1.0936132983377078,Angstroms:1e10,Nanometers:1e9,Microns:1e6,Decimeters:10,Decameters:.1,Hectometers:.01,Gigameters:1e-9,"Astronomical units":6684587122268445e-27,"Light years":10570008340246154e-32,Parsecs:3240779289666404e-32};function toDrawData(unit="Centimeters"){if(!this.needUpdate&&this._cachedDrawDataMap.has(unit))return this._cachedDrawDataMap.get(unit);this._cachedDrawDataMap.clear(),this.needUpdate=!1;const lines=this.groups.flatMap(group2=>group2.lines),s=units[unit],box=Box2.fromByLineSegment(lines).expansion(1),data={unit:unit,entitys:[],center:box.center.clone().multiplyScalar(s).toJson(),width:box.width*s,height:box.height*s,scale:s};let color="white";function drawText2(str,p2,opt){data.entitys.push({type:"text",text:str,center:{x:p2.x*s,y:p2.y*s},color:opt?.color??color,rotation:opt?.rotation??0,fontSize:.1*s})}function drawLine(p1,p2,opt){data.entitys.push({type:"line",start:{x:p1.x*s,y:p1.y*s},end:{x:p2.x*s,y:p2.y*s},color:opt?.color??color})}function drawDottedLine(p1,p2,opt){const{dash:dash=.04,gap:gap=.05}=opt??{},distance2=dash+gap;let current=0;const direction=p2.directionFrom(p1),length=p1.distance(p2);for(;current<length;){const dashEnd=Math.min(current+dash,length);drawLine(p1.clone().add(direction.clone().multiplyScalar(current)),p1.clone().add(direction.clone().multiplyScalar(dashEnd))),current+=distance2}}function drawArc(pos,radius,startAngle,endAngle,opt){data.entitys.push({type:"arc",center:{x:pos.x*s,y:pos.y*s},color:opt?.color??color,radius:radius*s,startAngle:startAngle,endAngle:endAngle})}function drawPolygonFill(path,opt){data.entitys.push({type:"polygon-fill",path:path.map(p2=>({x:p2.x*s,y:p2.y*s})),color:opt?.color??color})}return this.groups.forEach(group2=>{const set2=this._drawHandlerMap.get(group2.type);if(!set2)return;const option={group:group2,drawArc:drawArc,drawLine:drawLine,drawDottedLine:drawDottedLine,drawText:drawText2,drawPolygonFill:drawPolygonFill,setColor(c){color=c}};set2.forEach(fun=>fun.handler(option))}),this._cachedDrawDataMap.set(unit,data),data}const colors={cyan:"cyan",yellow:"yellow",white:"white",gray:"#c9c9c9",green:"green",deepgreen:"#006400",red:"red",blue:"#2c2cff",deepblue:"#0001bb",text:"#ffffff",ruler:"green",ruler_deep:"#006400"},getColor=color=>colors[color??""]??color??"#fff";class Group{type="";userData={color:"#fff"};constructor(lines=[],type="",userData={}){this.type=type,this.addLine(...lines),Object.assign(this.userData,userData)}lines=[];addLine(...arg){this.lines.push(...arg)}removeLine(...lines){if(0===lines.length)return;if(1===lines.length){const index2=this.lines.indexOf(lines[0]);return void this.lines.splice(index2,1)}const set2=new Set(lines);this.lines=this.lines.filter(line=>!set2.has(line))}clone(){const group2=new this.constructor;return group2.type=this.type,group2.lines=this.lines.map(line=>line.clone()),Object.assign(group2.userData,this.userData),group2}}class CAD{groups=[];_drawHandlerMap=new SetMap;needUpdate=!0;getAllLines(){return this.groups.flatMap(group2=>group2.lines)}addGroup(lines,type="",userData={}){const group2=new Group(lines,type,userData);return this.groups.push(group2),this.needUpdate=!0,group2}addGroups(groups,type=""){return this.needUpdate=!0,groups.map(lines=>this.addGroup(lines,type))}addGroupAndOffset(lines,option){const{offsetHalfWidth:offsetHalfWidth=.5*DEFAULT_WALL_WIDTH,joinType:joinType="jtMiter",endType:endType="etOpenButt",type:type="groupOffset",scale:scale2=1e5}=option??{};let offsetPolygons=LineSegmentUtils.groupBySharedPoints(lines).flatMap(group2=>Polygon.multipleFromByLines(group2)).map(polygon2=>Polygon.offset(polygon2,{offsetHalfWidth:offsetHalfWidth,scale:scale2,joinType:joinType,endType:endType})).filter(Boolean);if(offsetPolygons.length>1){const[first,...other]=offsetPolygons;offsetPolygons=Polygon.booleanOp(first,other,{type:"Union",scale:scale2})}return offsetPolygons.forEach(polygon2=>{let lines2=mergeChainsLine(polygon2.toLines(!0));lines2.forEach(line=>line.extendAlongDirection(.001)),lines2=splitIntersectedLine(lines2,1e-9);const set2=findDiscretePointLine2(lines2);lines2=lines2.filter(line=>!set2.has(line)),this.addGroup(lines2,type,{polygon:polygon2})}),this.needUpdate=!0,this}removeGroup(group2){const index2=this.groups.indexOf(group2);return index2>-1&&this.groups.splice(index2,1),this.needUpdate=!0,group2}filterGroups(fun){const groups=[];return this.groups=this.groups.filter(group2=>{const b4=fun(group2);return b4||groups.push(group2),b4}),groups}findGroups(fun){const groups=[];return this.groups.forEach(group2=>{fun(group2)&&groups.push(group2)}),groups}unionGroup(fun,opt){const{type:type="unionGroupAll",connectingBridge:connectingBridge=!0,threshold:threshold=.1}=opt??{},groups=[];this.groups=this.groups.filter(group2=>{const b4=fun(group2);return b4&&groups.push(group2),!b4});const polys=[],lines=groups.flatMap(group2=>(group2.userData.polygon?polys.push(group2.userData.polygon):polys.push(...Polygon.multipleFromByLines(group2.lines)),group2.lines)),quadtree=Quadtree.from(lines),temLine=new LineSegment,visited=/* @__PURE__ */new Set;if(connectingBridge)for(let i=0;i<lines.length;i++){const line=lines[i],len=line.length;temLine.copy(line);const rectangle=temLine.extendAlongDirection(.01*len).toRectangle(2*threshold,"butt"),results=quadtree.queryRect(rectangle).filter(result=>result.line!==line&&!visited.has(result.line)&&result.line.isParallelTo(line)).sort((a2,b4)=>b4.line.length-a2.line.length);if(results.length){const resultLine=results[0].line,pl1=resultLine.projectLineSegment(line),pl2=line.projectLineSegment(resultLine),pLine=pl1.length>pl2.length?pl1:pl2;polys.push(new Polygon(pLine.toRectangle(2*threshold,"butt").points).close())}visited.add(line),quadtree.remove(line)}if(0===polys.length)return;const[first,...rest]=polys;Polygon.booleanOp(first,rest??[],{type:"Union",scale:1e3}).forEach(polygon2=>{this.addGroup(polygon2.toLines(!0),type,{polygon:polygon2})}),this.needUpdate=!0}unionGroupAll(type="unionGroupAll",threshold=.01){this.unionGroup(_=>!0,{type:type,threshold:threshold})}rotate(angle){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.rotate(angle,center)})),this.needUpdate=!0}resetOrigin(){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.start.subtract(center),line.end.subtract(center)})),this.needUpdate=!0}rotateAndResetOrigin(angle){const lines=this.groups.flatMap(group2=>group2.lines),center=Box2.fromByLineSegment(lines).center;this.groups.forEach(group2=>group2.lines.forEach(line=>{line.rotate(angle,center),line.start.subtract(center),line.end.subtract(center)})),this.needUpdate=!0}addDrawHandler(handler){handler.type.forEach(type=>{this._drawHandlerMap.append(type,handler)}),this.needUpdate=!0}_cachedDrawDataMap=/* @__PURE__ */new Map;toDrawData(unit="Centimeters"){return toDrawData.call(this,unit)}async toDxfImageBlob(unit="Centimeters",type="image/jpeg",background="#000"){return async function(data,type="image/jpeg",background="#000"){const margin=0*data.scale;let canvas;if("undefined"!=typeof window)canvas=document.createElement("canvas");else{if("undefined"==typeof global)throw new Error("创建画布失败");{const{createCanvas:createCanvas}=await include("canvas");canvas=createCanvas(data.width+2*margin,data.height+2*margin)}}const colors2={cyan:"cyan",yellow:"yellow",white:"white",gray:"#c9c9c9",green:"green",deepgreen:"#006400",red:"red",blue:"#2c2cff",deepblue:"#0001bb",text:"#ffffff",ruler:"green",ruler_deep:"#006400"};canvas.width=data.width+2*margin,canvas.height=data.height+2*margin;const ctx=canvas.getContext("2d");return background&&(ctx.fillStyle=background,ctx.fillRect(0,0,canvas.width,canvas.height)),ctx.translate(-data.center.x+.5*data.width+margin,data.center.y+.5*data.height+margin),ctx.scale(1,-1),data.entitys.forEach(entity=>{switch(entity.type){case"line":ctx.strokeStyle=colors2[entity.color]??entity.color,ctx.beginPath(),ctx.moveTo(entity.start.x,entity.start.y),ctx.lineTo(entity.end.x,entity.end.y),ctx.closePath(),ctx.stroke();break;case"arc":ctx.strokeStyle=colors2[entity.color],ctx.beginPath(),ctx.arc(entity.center.x,entity.center.y,entity.radius,entity.startAngle*(Math.PI/180),entity.endAngle*(Math.PI/180)),ctx.stroke();break;case"dotted-line":ctx.beginPath(),ctx.moveTo(entity.start.x,entity.start.y),ctx.lineTo(entity.end.x,entity.end.y),ctx.setLineDash([entity.dash,entity.gap]),ctx.strokeStyle=colors2[entity.color],ctx.lineWidth=1,ctx.stroke(),ctx.setLineDash([]);break;case"text":ctx.fillStyle=colors2[entity.color]??entity.color??"#fff",ctx.font=`${entity.fontSize}px Arial`,ctx.textAlign="center",ctx.textBaseline="middle",ctx.save(),ctx.translate(entity.center.x,entity.center.y),ctx.rotate(Math.PI/180*entity.rotation),ctx.scale(1,-1),ctx.letterSpacing=.1*entity.fontSize+"px",ctx.fillText(entity.text,0,0),ctx.restore();break;case"polygon-fill":ctx.fillStyle=colors2[entity.color]??entity.color??"#fff",ctx.save(),ctx.beginPath(),entity.path.forEach((p2,i)=>{0===i?ctx.moveTo(p2.x,p2.y):ctx.lineTo(p2.x,p2.y)}),ctx.closePath(),ctx.fill(),ctx.restore()}}),"toBlob"in canvas?new Promise(resolve=>{canvas.toBlob(b4=>{resolve(b4)},type,1)}):canvas.toBuffer(type,{quality:1})}(this.toDrawData(unit),type,background)}async downloadDxfImage(filename,unit="Centimeters",type="image/jpeg"){const blob=await this.toDxfImageBlob(unit,type);if(!blob)return!1;if("undefined"!=typeof window){const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,blob)}else console.error("图片下载失败");return!0}toDxfString(unit="Millimeters"){return function(data,unit="Millimeters"){const drawing=new Drawing;drawing.setUnits(unit);const ACI={cyan:Drawing.ACI.CYAN,yellow:Drawing.ACI.YELLOW,white:Drawing.ACI.WHITE,green:Drawing.ACI.GREEN,deepgreen:83,red:Drawing.ACI.RED,gray:9,blue:Drawing.ACI.BLUE,deepblue:175,text:Drawing.ACI.WHITE,ruler:Drawing.ACI.GREEN,ruler_deep:83};Object.keys({cyan:65535,yellow:16776960,white:16777215,green:65280,deepgreen:25600,red:16711680,gray:13224393,blue:2895103,deepblue:443,text:16777215,ruler:65280,ruler_deep:25600}).forEach(key=>{drawing.addLayer(`${key}_CONTINUOUS`,ACI[key],"CONTINUOUS"),drawing.addLayer(`${key}_DASHED`,ACI[key],"DASHED"),drawing.setActiveLayer(key)});const setColor=(c,lineType="CONTINUOUS")=>{drawing.setActiveLayer(`${c}_${lineType}`)};return data.entitys.forEach(entity=>{switch(entity.type){case"line":setColor(entity.color),drawing.drawLine(entity.start.x,entity.start.y,entity.end.x,entity.end.y);break;case"arc":setColor(entity.color),drawing.drawArc(entity.center.x,entity.center.y,entity.radius,entity.startAngle,entity.endAngle);break;case"dotted-line":break;case"polygon-fill":setColor(entity.color);const faceIndex=earcut(entity.path.flatMap(p2=>[p2.x,p2.y]),null,2);for(let i=0;i<faceIndex.length;i+=3){const p1=entity.path[faceIndex[i]],p2=entity.path[faceIndex[i+1]],p3=entity.path[faceIndex[i+2]];drawing.drawFace(p1.x,p1.y,0,p2.x,p2.y,0,p3.x,p3.y,0,p1.x,p1.y,0)}break;case"text":setColor(entity.color),drawing.drawText(entity.center.x,entity.center.y,entity.fontSize,entity.rotation,entity.text,"center","middle")}}),drawing.toDxfString()}(this.toDrawData(unit),unit)}toDxfBlob(unit="Millimeters"){return new Blob([this.toDxfString(unit)])}async downloadDxf(filename,unit="Millimeters"){if("undefined"!=typeof window){const blob=this.toDxfBlob(unit),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename+".dxf",a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,this.toDxfString(unit))}}toDxfObject3D(unit="Millimeters"){return function(data){const root=new THREE.Group;return data.entitys.forEach(entity=>{switch(entity.type){case"line":{const geometry=(new THREE.BufferGeometry).setFromPoints([new THREE.Vector3(entity.start.x,entity.start.y,0),new THREE.Vector3(entity.end.x,entity.end.y,0)]);root.add(new THREE.Line(geometry,new THREE.LineBasicMaterial({color:getColor(entity.color)})));break}case"arc":{const curve=new THREE.ArcCurve(entity.center.x,entity.center.y,entity.radius,THREE.MathUtils.degToRad(entity.startAngle),THREE.MathUtils.degToRad(entity.endAngle)),geometry=(new THREE.BufferGeometry).setFromPoints(curve.getPoints(Math.max(16,Math.ceil(Math.abs(entity.endAngle-entity.startAngle)/5))).map(p2=>new THREE.Vector3(p2.x,p2.y,0)));root.add(new THREE.Line(geometry,new THREE.LineBasicMaterial({color:getColor(entity.color)})));break}case"dotted-line":{const geometry=(new THREE.BufferGeometry).setFromPoints([new THREE.Vector3(entity.start.x,entity.start.y,0),new THREE.Vector3(entity.end.x,entity.end.y,0)]),line=new THREE.Line(geometry,new THREE.LineDashedMaterial({color:getColor(entity.color),dashSize:entity.dash,gapSize:entity.gap}));line.computeLineDistances(),root.add(line);break}case"text":break;case"polygon-fill":{const shape=new THREE.Shape;entity.path.forEach((p2,i)=>0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y)),shape.closePath(),root.add(new THREE.Mesh(new THREE.ShapeGeometry(shape),new THREE.MeshBasicMaterial({color:getColor(entity.color),side:THREE.DoubleSide})));break}}}),root}(this.toDrawData(unit))}usePlugin(plugin){return plugin.install(this),this}clone(drawHandle=!0){const cad2=new this.constructor;return cad2.groups=this.groups.map(g=>g.clone()),drawHandle&&this._drawHandlerMap.forEach((v2,k)=>cad2._drawHandlerMap.set(k,v2)),cad2}clear(){this.groups.length=0,this._drawHandlerMap.clear(),this.needUpdate=!0}static obliquity(cad2){const lineSegments=cad2.groups.flatMap(g=>g.lines),vrLine=LineSegmentUtils.findDominantDirectionLine(lineSegments);return{angle:-vrLine.direction().angleBetween(new Point(0,1),"angle","360")*(Math.PI/180),referenceLine:vrLine}}}class AxisAlignCorr{static start(lines,targettLine,excludeLines){return new AxisAlignCorr(lines,targettLine,excludeLines).start()}lines;baseline;excludeLines;grid;constructor(lines,baseline,excludeLines){this.lines=lines,this.baseline=baseline,this.excludeLines=excludeLines??[],this.grid=PointSpatialHash.fromByLines(lines)}visited=/* @__PURE__ */new Set;newLines=[];start(){const excludeSet=new Set(this.excludeLines);for(let i=0;i<this.lines.length;i++){const line=this.lines[i];excludeSet.size&&excludeSet.has(line)||(this.visited.has(line)||this.correction(line))}const quadtree=Quadtree.from(this.lines);return this.newLines=this.newLines.filter(line=>0===quadtree.queryCircle(line.center,1e-4).length),[...this.lines,...this.newLines]}addVisited(lines){return lines instanceof LineSegment&&(lines=[lines]),lines.forEach(line=>this.visited.add(line)),this}queryPoint(point2){return this.grid.queryPoint(point2,!0).filter(item=>!this.visited.has(item.userData))}correction(line){const startConnectList=this.queryPoint(line.start),endConnectLines=this.queryPoint(line.end);this.rotate(line),startConnectList.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,line.start)}),endConnectLines.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,line.end)})}recursion(line,enterPoint,nextLine,nextPoint){const otherPoint=line.getAnotherPoint(enterPoint),connectList=this.queryPoint(otherPoint);this.rotate(line),this.establishConnection(enterPoint,line,nextLine,nextPoint),connectList.forEach(({userData:queryLine2,point:point2})=>{this.recursion(queryLine2,point2,line,otherPoint)})}establishConnection(point2,line,nextLine,nextPoint){if(line.isParallelTo(nextLine)){const interPoint2=nextLine.projectPoint(point2,!1),newLine=new LineSegment(point2.clone(),interPoint2?.clone()??nextPoint.clone());return void(newLine.length>1e-9&&this.newLines.push(newLine))}const interPoint=nextLine.projectPoint(point2,!1);interPoint&&(point2.copy(interPoint),nextLine.isPointOnSegment(interPoint)||nextPoint.copy(interPoint))}point=new Point;rotate(line,errAngle=45){const baseline=this.baseline;this.point.copy(line.start),line.isParallelTo(baseline,errAngle)?function(line,baseline){const currentAngle=Math.atan2(line.end.y-line.start.y,line.end.x-line.start.x);let diff=Math.atan2(baseline.end.y-baseline.start.y,baseline.end.x-baseline.start.x)-currentAngle;for(;diff>Math.PI;)diff-=2*Math.PI;for(;diff<-Math.PI;)diff+=2*Math.PI;const center=line.center;line.start.rotate(center,diff),line.end.rotate(center,diff),Math.abs(diff)>Math.PI/2&&line.swapValue()}(line,baseline):function(line,baseline){const currentAngle=Math.atan2(line.end.y-line.start.y,line.end.x-line.start.x),targetAngle=Math.atan2(baseline.end.y-baseline.start.y,baseline.end.x-baseline.start.x);let diff1=targetAngle+Math.PI/2-currentAngle,diff2=targetAngle-Math.PI/2-currentAngle;for(;diff1>Math.PI;)diff1-=2*Math.PI;for(;diff1<-Math.PI;)diff1+=2*Math.PI;for(;diff2>Math.PI;)diff2-=2*Math.PI;for(;diff2<-Math.PI;)diff2+=2*Math.PI;const diff=Math.abs(diff1)<Math.abs(diff2)?diff1:diff2,center=line.center;line.start.rotate(center,diff),line.end.rotate(center,diff),Math.abs(diff)>Math.PI/2&&line.swapValue()}(line,baseline),this.addVisited(line)}}class LineQueryer{pointVirtualGrid;lsh;constructor(lines){this.pointVirtualGrid=PointSpatialHash.fromByLines(lines),this.lsh=LineSegmentSpatialHash.from(lines)}update(lines){this.clear(),this.pointVirtualGrid=PointSpatialHash.fromByLines(lines),this.lsh=LineSegmentSpatialHash.from(lines)}clear(){this.pointVirtualGrid.clear(),this.lsh.clear()}queryNearestPoint(point2,opt){if(!point2)throw new Error("请传入查询点");const{resultIndex:resultIndex=0,radius:radius=.4,condition:condition}=opt??{},results=this.pointVirtualGrid.queryCircle(point2,radius).filter(item=>item.point!==point2).filter(item=>!condition||condition(item));return results.sort((a2,b4)=>a2.point.distance(point2)-b4.point.distance(point2)),results.length>resultIndex?{point:results[resultIndex].point,line:results[resultIndex].userData}:null}queryNearestLine(point2,opt){if(!point2)throw new Error("请传入查询点");const{resultIndex:resultIndex=0,radius:radius=.4,condition:condition}=opt??{},results=this.lsh.queryPoint(point2,radius).map(item=>{const projPoint=item.projectPoint(point2,!1);return projPoint&&(!condition||condition(item,projPoint))&&projPoint?{line:item,distance:projPoint.distance(point2)??1/0,projPoint:projPoint}:null}).filter(i=>!!i);return results.sort((a2,b4)=>a2.distance-b4.distance),results.length>resultIndex?{point:results[resultIndex].projPoint,line:results[resultIndex].line}:null}}function removeDangline(lines,maxLen=.01,consecutive=!1){const grid=PointSpatialHash.fromByLines(lines);let defaultLines=[];const doorLines=[],removeLineSet=/* @__PURE__ */new Set;function find(lines2){removeLineSet.clear();const shortLine=lines2.filter(line=>line.length<=maxLen);for(let i=0;i<shortLine.length;i++){const line=shortLine[i];line.points.some(p2=>0===grid.queryCircle(p2,1e-4).filter(item=>item.userData!==line).length)&&removeLineSet.add(line)}return removeLineSet}for(lines.forEach(line=>{line.userData.isDoor?doorLines.push(line):defaultLines.push(line)});0!=find(defaultLines).size&&(defaultLines=defaultLines.filter(line=>!removeLineSet.has(line)),removeLineSet.forEach(line=>{grid.removes(line.points)}),consecutive););return defaultLines=mergeChainsLine(defaultLines,(newLine,lines2)=>{mergeLineUserData(newLine,lines2=lines2.filter(line=>line.length>0)),newLine.userData.isBayWindow=lines2.some(line=>line.userData.isBayWindow)}),WallHole.filterIllegal(defaultLines),[...defaultLines,...doorLines]}const DELETE_SYMBOL=/* @__PURE__ */Symbol("DELETE_SYMBOL");function fitting(lines){const index2=LineSegmentUtils.maxLengthLineIndex(lines);if(-1===index2)throw Error("未找到最长线段");const maxLine=lines[index2],center=LineSegmentUtils.getLinesCenter(lines),direct=maxLine.direction(),start=center.clone().add(direct.clone().multiplyScalar(-1)),end=center.clone().add(direct.clone().multiplyScalar(1));return new LineSegment(start,end)}function layoutDesign(lines,axis,intersectPoints,opt){let blocks=lines.map((line,index2)=>{const sv=axis.projectPointValue(line.start),ev=axis.projectPointValue(line.end),range=sv<ev?[sv,ev]:[ev,sv];return{range:range,index:index2,rangeSize:range[1]-range[0]}});blocks.sort((a2,b4)=>Math.abs(a2.range[0]-b4.range[0])<1e-4?b4.rangeSize-a2.rangeSize:a2.range[0]-b4.range[0]);const newLines=[];for(let i=0;i<blocks.length;i++){const block=blocks[i],line=lines[block.index],occupationIndexList=[];let ranges=[],start=block.range[0];for(let j=i+1;j<blocks.length;j++){const nextBlock=blocks[j];if(Math.min(block.range[1],nextBlock.range[1])-Math.max(block.range[0],nextBlock.range[0])<0)break;nextBlock.range[0]>start&&ranges.push([start,nextBlock.range[0]]),start=Math.max(start,nextBlock.range[1]),occupationIndexList.push(nextBlock.index)}start<block.range[1]&&ranges.push([start,block.range[1]]),ranges=ranges.filter(range=>range[1]-range[0]>1e-4);for(let j=0;j<ranges.length;j++){const range=ranges[j],start2=axis.pointAt(range[0]),end=axis.pointAt(range[1]);if(0===j)line.set(start2,end),newLines.push(line);else{let newLine=line.clone();newLine.set(start2,end),newLines.push(newLine)}}0===ranges.length&&(line.currentData[DELETE_SYMBOL]=!0,opt.onSegmentClippedAway?.(line,occupationIndexList.map(i2=>lines[i2]).filter(line2=>!line2.currentData[DELETE_SYMBOL])))}!function(lines,axis){lines.sort((a2,b4)=>{const sa2=axis.projectPointValue(a2.start),sb=axis.projectPointValue(b4.start);if(Math.abs(sa2-sb)<1e-6){const aLen=axis.projectPointValue(a2.end)-sa2;return axis.projectPointValue(b4.end)-sb-aLen}return sa2-sb})}(newLines,axis);const psh=PointSpatialHash.from(intersectPoints);for(let i=0;i<newLines.length-1;i++){const line=newLines[i];if(0!==psh.queryPoint(line.end).length)continue;const nextLine=newLines[i+1];nextLine.start.copy(line.start),line.currentData[DELETE_SYMBOL]=!0,opt.onMergeLine?.(nextLine,line)}return lines.length=0,lines.push(...newLines),lines}class AlignToParallelSegments{static fittingAlignment(groups,verticalLines,opt={}){const grid=PointSpatialHash.fromByLines(verticalLines);for(let i=0;i<groups.length;i++){const group2=groups[i];if(group2.length<=1)continue;const axisLine=fitting(group2),intersectList=[];for(let j=0;j<group2.length;j++){group2[j].points.forEach(p2=>{const intersects2=grid.queryCircle(p2,1e-4),pv=axisLine.projectPointValue(p2);axisLine.pointAt(pv,p2),intersects2.forEach(({point:point2})=>point2.copy(p2)),intersectList.push(...intersects2)})}const intersectPoints=intersectList.filter(item=>item.userData.length>1e-5).map(item=>item.point);let oldGroup=[...group2];layoutDesign(group2,axisLine,intersectPoints,opt),opt.onLayoutDesign?.(oldGroup,DELETE_SYMBOL)}return groups.flat().filter(line=>!(line.length<1e-9)&&(!line.currentData[DELETE_SYMBOL]||(delete line.currentData[DELETE_SYMBOL],!1)))}static align(lines,opt={}){const{esp:esp=.08,gap:gap=.05}=opt,axisLine=lines[LineSegmentUtils.maxLengthLineIndex(lines)].clone().setLength(100),axisLineV=axisLine.clone().rotate(.5*Math.PI,axisLine.center);let[pllLines,verticalLines]=LineSegmentUtils.groupByParallelToAxis(lines,axisLine);const groups=LineSegmentUtils.groupByProjectedOverlap(pllLines,axisLine,axisLineV,esp,gap,opt.onGroup);pllLines=this.fittingAlignment(groups,verticalLines,opt),verticalLines=verticalLines.filter(line=>line.length>1e-6);const groups2=LineSegmentUtils.groupByProjectedOverlap(verticalLines,axisLineV,axisLine,esp,gap,opt.onGroup);return verticalLines=this.fittingAlignment(groups2,pllLines,opt),pllLines=pllLines.filter(line=>line.length>1e-6),[...pllLines,...verticalLines]}}function preprocessing(lines){return lines=function(lines,radius=.1){const pvg=PointSpatialHash.fromByLines(lines);return lines.forEach(line=>{line.points.forEach(p2=>{if(0!==pvg.queryCircle(p2,.001,!0).length)return;const list=pvg.queryCircle(p2,radius,!0).filter(item=>item.userData?.userData.isBayWindow);if(0===list.length)return;let direct1=line.getAnotherPoint(p2).directionFrom(p2);for(let i=0;i<list.length;i++){const{point:point2}=list[i],direct2=point2.directionFrom(p2);direct1.angle(direct2,{unit:"degree",range:"180"})<85||p2.copy(point2)}})}),lines}(lines=function(lines,radius=.1){const dpSet=findDiscretePoint(lines.filter(line=>!line.userData.isDoor)),pointVirtualGrid=PointSpatialHash.fromByLines(dpSet.map(v2=>v2)),lsh=LineSegmentSpatialHash.from(lines),appendLines=[],visited=/* @__PURE__ */new Set,getWeight2=(target,point2,line)=>{if(target.weight)return target.weight;const targetLine=target.userData,targetPoint=target.point,direct1=line.getAnotherPoint(point2).directionFrom(point2),direct2=targetLine.getAnotherPoint(targetPoint).directionFrom(targetPoint),direct3=targetPoint.directionFrom(point2),angle=direct1.angleBetween(direct2),angle2=direct1.angleBetween(direct3),weight=1-point2.distance(target.point)/radius+angle/Math.PI*1.2+1.2*(1-angle2/Math.PI);return target.weight=weight,weight},queryLine2=new LineSegment;for(const[point2,line]of dpSet){if(line.userData.isDoor)continue;if(visited.has(point2))continue;const list=pointVirtualGrid.queryCircle(point2,radius,!0).map(item=>Object.assign({},item)).filter(item=>{const targetLine2=item.userData;return targetLine2!==line&&(!targetLine2.isSameEndpoint(line)&&(queryLine2.set(point2,item.point),0===lsh.queryLine(queryLine2).filter(l=>l!==line&&l!==targetLine2).length))}).filter(item=>{const targetLine2=item.userData,targetPoint2=item.point,direct1=line.getAnotherPoint(point2).directionFrom(point2),direct2=targetLine2.getAnotherPoint(targetPoint2).directionFrom(targetPoint2);return direct1.angleBetween(direct2,"angle")>90}).sort((a2,b4)=>getWeight2(b4,point2,line)-getWeight2(a2,point2,line));if(0===list.length)continue;const{point:targetPoint}=list[0],targetLine=list[0].userData;visited.add(point2),visited.add(targetPoint);const projectLine1=line.projectLineSegment(targetLine),projectLine2=targetLine.projectLineSegment(line),len1=projectLine1.length,len2=projectLine2.length;let newLine=0===len1&&0===len2?new LineSegment(point2.clone(),list[0].point.clone()):new LineSegment(projectLine1.center,projectLine2.center);if(newLine.isParallelTo(line)){point2.copy(newLine.end);const otherPoint=line.getAnotherPoint(point2),step=point2.directionFrom(otherPoint).multiplyScalar(.5*newLine.length);WallHole.isBeam(line)&&new Array(...WallHole.getIterator(line)).forEach(hole=>{const p2=Point.from(hole.p);p2.add(step),hole.width+=newLine.length,hole.p=p2.toJson(hole.p.z)})}else appendLines.push(newLine);pointVirtualGrid.update(point2),lsh.update(line)}return[...lines,...appendLines]}(lines,.4),.05)}function adsorption(lines,option,otherLines=[]){const{snapThreshold:threshold=.2}=option??{},lineQueryer=new LineQueryer([...lines,...otherLines]),modifyManager=LineSegmentUtils.createModifyManager();function adsorptLine(point2,line){const direct=line.getAnotherPoint(point2).directionFrom(point2),len=line.length,result=lineQueryer.queryNearestLine(point2,{radius:threshold,condition:(target_line,projPoint)=>{if(line!==target_line&&target_line.isPerpendicularTo(line,35)){if(projPoint.distance(point2)<len)return!0;return projPoint.directionFrom(point2).angleBetween(direct)>.5*Math.PI}return!1}});if(result)return modifyManager.setPoint(line,point2,result.point.clone())}for(let i=0;i<lines.length;i++){const line=lines[i];line.points.map(point2=>{0===lineQueryer.pointVirtualGrid.queryPoint(point2,!0).length&&lineQueryer.lsh.queryPoint(point2,1e-4).length<2&&adsorptLine(point2,line)})}return modifyManager.modify(),lineQueryer.clear(),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4),lines}function breakpointMerging$1(lines){let defaultLines=[],doorLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isDoor?doorLines.push(line):defaultLines.push(line)}return defaultLines=mergeChainsLine(defaultLines),doorLines=mergeChainsLine(doorLines),[...defaultLines,...doorLines]}function alignConfig(opt){const{min_wall_width:min_wall_width=DEFAULT_WALL_WIDTH,max_wall_width:max_wall_width=MAX_WALL_WIDTH}=opt??{};return{onMergeLine:mergeLineUserData,onGroup(group2,projValues,axis){if(group2.length<=1)return;const dist=precision4((Math.max(...projValues)-Math.min(...projValues))*axis.length);dist<min_wall_width||group2.forEach(line=>{line.userData.wallWidth=Math.min(dist,max_wall_width),line.userData.type="beams"})},onLayoutDesign(lines,delKey){const holes=[];lines=lines.filter(line=>(holes.push(...WallHole.getIterator(line)),WallHole.clear(line),!line.currentData[delKey])),WallHole.splitHole(holes,lines)}}}function sparse(trajectory2,size2=.4){const idSet=/* @__PURE__ */new Set;Object.keys(trajectory2??{}).forEach(key=>{const p2=trajectory2[key],i=Math.round(p2.x/size2),j=Math.round(p2.y/size2),id=BigInt(i)<<32n|0xffffffffn&BigInt(j);idSet.has(id)?delete trajectory2[key]:idSet.add(id)})}const sortByDistance=(a2,b4,dockPoint)=>a2.point.distance(dockPoint,!0)-b4.point.distance(dockPoint,!0);function getWeight(target,dock,doorLength){if(target.weight)return target.weight;const distance2=dock.dockPoint.distance(target.point);let weight=1-Math.abs(1-distance2/doorLength);const direct1=target.point.directionFrom(dock.dockPoint),direct2=dock.dockLine.getAnotherPoint(dock.dockPoint).directionFrom(dock.dockPoint);return weight+=direct1.angleBetween(direct2)/Math.PI*1.5,target.weight=weight,weight}class DoorFind{lines;grid;quadtree;constructor(lines){lines=this.findBrotherDoor(lines),this.lines=lines;const doors=lines.filter(line=>line.userData.isDoor),noDoorLines=lines.filter(line=>!line.userData.isDoor),openDoors=doors.filter(line=>!line.userData.doorDirectConnection),closeDoors=doors.filter(line=>line.userData.doorDirectConnection);this.grid=PointSpatialHash.fromByLines(noDoorLines),this.quadtree=Quadtree.from([...noDoorLines,...closeDoors]),openDoors.forEach(l=>l.userData.doorDirectConnection=!0),closeDoors.forEach(line=>this.findCloseDoors(line)),openDoors.forEach(line=>this.findOpenDoors(line))}findBrotherDoor(lines){const grid=PointSpatialHash.fromByLines(lines),doorLines=[];findDiscretePointLine2(lines).forEach(line=>line.userData.isDoor&&doorLines.push(line));const searchedList=[];doorLines.forEach(line=>{const pointStartIsFree=grid.isFreePoint(line.start),pointEndIsFree=grid.isFreePoint(line.end);pointStartIsFree&&pointEndIsFree||(pointStartIsFree?searchedList.push({door:line,point:line.end}):searchedList.push({door:line,point:line.start}))}),searchedList.forEach(item=>{let list=grid.queryPoint(item.point,!0);list.length>1&&(list=list.filter(target=>{const otherPoint=target.userData.getAnotherPoint(target.point);return!grid.isFreePoint(otherPoint)})),item.line=list[0]?.userData,item.linePoint=list[0]?.point});const doorGrid=new PointSpatialHash,minAngle=Math.PI/180*170;searchedList.forEach((item,index2)=>item.line&&doorGrid.insert(item.point,index2));const removeLines=[];searchedList.forEach(item=>{if(!item.line||item.found)return;const dir=item.line?.getAnotherPoint(item.linePoint).directionFrom(item.linePoint),list=doorGrid.queryCircle(item.point,2.5*item.door.length).filter(result=>{const{line:line}=searchedList[result.userData];return line.isParallelTo(item.line,10)}).filter(result=>{const{line:line,linePoint:linePoint}=searchedList[result.userData],dir2=line?.getAnotherPoint(linePoint).directionFrom(linePoint);return dir.angleBetween(dir2)>minAngle}).filter(result=>{const{point:point2}=searchedList[result.userData],dir2=item.point.directionFrom(point2),dir3=item.linePoint.directionFrom(item.line.getAnotherPoint(item.linePoint));return dir2.angleBetween(dir3)>Math.PI/180*135});if(list.length){const item2=searchedList[list[0].userData];item2.found=!0,item.door.getAnotherPoint(item.point).copy(item2.point),item.door.userData.doorDirectConnection=!0,removeLines.push(item2.door)}});const set2=new Set(removeLines);return lines.filter(line=>!set2.has(line))}findCloseDoors(line){const startList=this.grid.queryCircle(line.start,.01,!0).sort((a2,b4)=>sortByDistance(a2,b4,line.start)),endList=this.grid.queryCircle(line.end,.01,!0).sort((a2,b4)=>sortByDistance(a2,b4,line.end));if(startList.length+endList.length===0)return this.findOpenDoors(line);if(startList.length&&endList.length)return line.start.copy(startList[0].point),void line.end.copy(endList[0].point);let dock=null;if(startList.length?dock={dockLine:startList[0].userData,dockPoint:startList[0].point,point:line.start,pointType:"start"}:endList.length&&(dock={dockLine:endList[0].userData,dockPoint:endList[0].point,point:line.end,pointType:"end"}),!dock)return;const point2=this.adsorpt(dock,line,20);point2&&(line.userData.doorAutomaticFind=!0,line.getAnotherPoint(dock.point).copy(point2))}findOpenDoors(line){let dock;const queryList=point22=>{let list=this.grid.queryPoint(point22,!0);if(1===list.length)return list;list=this.grid.queryCircle(point22,.6,!0),list=list.filter(item=>!item.userData?.userData.isDoor&&!item.userData?.userData.isBayWindow).filter(item=>!this.grid.queryPoint(item.point,!0).some(i=>i.userData?.isParallelTo(item.userData))).filter(item=>{const line2=item.userData,direct1=line.getAnotherPoint(point22).directionFrom(item.point),direct2=line2.getAnotherPoint(item.point).directionFrom(item.point);return direct1.angleBetween(direct2,"angle")>70});const list2=list.filter(item=>{const otherPoint=item.userData?.getAnotherPoint(item.point);return 0!==this.grid.queryPoint(otherPoint,!0).length});return list2.length&&(list=list2),list.sort((a2,b4)=>sortByDistance(a2,b4,point22)),list},startList=queryList(line.start),endList=queryList(line.end);if(startList.length+endList.length===0)return;dock=0===endList.length||0!==startList.length&&startList[0].point.distance(line.start)<endList[0].point.distance(line.end)?{dockLine:startList[0].userData,dockPoint:startList[0].point,point:line.start,pointType:"start"}:{dockLine:endList[0].userData,dockPoint:endList[0].point,point:line.end,pointType:"end"};const point2=this.adsorpt(dock,line);point2&&(line.userData.doorDirectConnection=!0,line.userData.doorAutomaticFind=!0,line.getAnotherPoint(dock.point).copy(point2))}adsorpt(dock,line,maxAngle=70){const length=line.length,targetDirect=dock.dockLine.getAnotherPoint(dock.dockPoint).directionFrom(dock.dockPoint);dock.point.copy(dock.dockPoint);const list=this.grid.queryCircle(dock.point,2*length,!0).map(item=>({...item})).filter(item=>item.userData!==dock.dockLine).filter(item=>0===this.grid.queryPoint(item.point,!0).length).filter(item=>item.point.directionFrom(dock.point).angleBetween(targetDirect,"angle")>70).filter(item=>{const line2=item.userData,d1=item.point.directionFrom(dock.point),d2=line2.getAnotherPoint(item.point).directionFrom(item.point),d3=dock.dockPoint.directionFrom(dock.dockLine.getAnotherPoint(dock.dockPoint));return d1.angleBetween(d2,"angle")<maxAngle&&d3.angleBetween(d2,"angle")<maxAngle}).filter(item=>{const queryLine2=new LineSegment(item.point.clone(),dock.point.clone());return queryLine2.offsetStart(.01).offsetEnd(.001),0===this.quadtree.queryLineSegment(queryLine2).length}).filter(item=>item.point.distance(dock.point)/length>.5).filter(item=>{const normal=item.point.leftNormal(dock.point),center=new Point((item.point.x+dock.point.x)/2,(item.point.y+dock.point.y)/2),length2=item.point.distance(dock.point),normalLine=new LineSegment(center,center.clone().add(normal.clone().multiplyScalar(length2)));normalLine.translate(.5*-length2,normal);return 0===this.quadtree.queryLineSegment(normalLine).filter(result=>result.line!==line&&result.line!==dock.dockLine).length}).sort((a2,b4)=>getWeight(b4,dock,length)-getWeight(a2,dock,length));if(list.length){const line2=list[0].userData;let point2=list[0].point;if(dock.dockLine.isPerpendicularTo(line2,25)){const p2=line2.projectPoint(dock.point,!0);p2&&(point2=p2)}return point2}return this.extendLink(dock,line)}extendLink(dock,line){const length=line.length,direct=dock.dockPoint.directionFrom(dock.dockLine.getAnotherPoint(dock.dockPoint)),queryLine2=new LineSegment(dock.dockPoint,dock.dockPoint.clone().add(direct.multiplyScalar(2*length)));let result=this.quadtree.queryLineSegment(queryLine2,!1).filter(item=>item.line!==dock.dockLine&&item.line!==line).map(item=>item.line.getIntersection(queryLine2)).filter(p2=>!!p2).filter(p2=>p2.distance(dock.dockPoint)>.2).sort((a2,b4)=>a2.distance(dock.dockPoint)-b4.distance(dock.dockPoint));if(result.length)return result[0];const normal=dock.dockLine.normal(),nNormal=normal.multiplyScalar(-1),direct2=line.getAnotherPoint(dock.point).directionFrom(dock.point);return direct2.angleBetween(normal)<direct2.angleBetween(nNormal)?queryLine2.set(dock.dockPoint,dock.dockPoint.clone().add(normal.multiplyScalar(2*length))):queryLine2.set(dock.dockPoint,dock.dockPoint.clone().add(nNormal.multiplyScalar(2*length))),result=this.quadtree.queryLineSegment(queryLine2,!1).filter(item=>{item.line!==dock.dockLine&&item.line}).map(item=>{const point2=item.line.getIntersection(queryLine2);if(point2)return point2}).filter(p2=>!!p2).filter(p2=>p2.distance(dock.dockPoint)>.2).sort((a2,b4)=>a2.distance(dock.dockPoint)-b4.distance(dock.dockPoint)),result.length?result[0]:null}getLines(){return this.lines.filter(line=>!(line.userData.isDoor&&line.length<.4))}}let loader;class LoadModel{static _cache=/* @__PURE__ */new Map;static _nameMap=/* @__PURE__ */new Map;static addNameMap(mapName,name){this._nameMap.set(mapName,name)}static loadGlb(name){if(this._nameMap.has(name)&&(name=this._nameMap.get(name)),this._cache.has(name))return this._cache.get(name);loader||(loader=new gltf.GLTFLoader);const promise2=new Promise(async resolve=>{const response=await fetch(`${VITE_OSS_BASEURL}models/${name}.glb`);if(!response.ok)return void resolve(null);const arrayBuffer=await response.arrayBuffer();resolve((await new Promise((resolve2,reject)=>{loader.parse(arrayBuffer,"",resolve2,reject)})).scene)});return this._cache.set(name,promise2),promise2}}LoadModel.addNameMap("water cooler","饮水机1"),LoadModel.addNameMap("table","桌子"),LoadModel.addNameMap("chair","椅子"),LoadModel.addNameMap("switch","开关"),LoadModel.addNameMap("cabinet","柜子"),LoadModel.addNameMap("tv","电视"),LoadModel.addNameMap("socket","插座"),LoadModel.addNameMap("refrigerator","冰箱"),LoadModel.addNameMap("kitchen hood","抽油烟机"),LoadModel.addNameMap("toilet","马桶"),LoadModel.addNameMap("sofa","沙发"),LoadModel.addNameMap("the bed","床"),LoadModel.addNameMap("door","门"),LoadModel.addNameMap("doubleDoor","双开门2"),LoadModel.addNameMap("window","窗户"),LoadModel.addNameMap("wall","单线墙"),LoadModel.addNameMap("doubleWall","双线墙"),LoadModel.addNameMap("balcony","阳台"),LoadModel.addNameMap("balconyFilm","阳台片"),LoadModel.addNameMap("balconyFilmFilm","阳台片片"),LoadModel.addNameMap("balconyFilmFilmFilm","阳台片片片");const defaultWallWidth=DEFAULT_WALL_WIDTH;function winDrawLine(line,grid){if(line.userData.isWindow&&Array.isArray(line.userData.drawWindow)){WallHole.merge([line]);const list=grid&&function(grid,line){const startList=grid.queryPoint(line.start,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),endList=grid.queryPoint(line.end,!0).map(item=>LineGroupType.hasType(item.userData,"doubleWall")?"doubleWall":"wall"),results=[];return 0===startList.length?results.push(0):startList.some(item=>"wall"===item)?results.push(1):results.push(2),0===endList.length?results.push(0):endList.some(item=>"wall"===item)?results.push(1):results.push(2),results}(grid,line),dwh=.5*defaultWallWidth;return line.userData.drawWindow.map(({full:full,width:width,p:p2,height:height,groundClearance:groundClearance,uuid:uuid2})=>{full&&(width=line.length);const point2=Point.from(p2),direct=line.direction(),winLine=point2.expandAsLine(direct,width).translate(.5*-width,direct);if(winLine.userData={wallWidth:defaultWallWidth,height:height,groundClearance:groundClearance},winLine.start.copy(line.projectPoint(winLine.start,!1)),winLine.end.copy(line.projectPoint(winLine.end,!1)),!list)return winLine;const startDistance=winLine.start.distance(line.start);if(startDistance<dwh&&1===list[0]){const diff=dwh-startDistance;winLine.offsetStart(diff)}const endDistance=winLine.end.distance(line.end);if(endDistance<dwh&&1===list[1]){const diff=dwh-endDistance;winLine.offsetEnd(diff)}return winLine.userData.winUuid=uuid2,winLine.userData.lineUuid=line.userData.uuid,winLine}).filter(line2=>line2.length>defaultWallWidth)}return null}class BayWindow{bayWindowExpansion=[];dottedLinePoints=[];singleLine;bayWindowArea;bayWindowGroup;static _instance;static get Instance(){return BayWindow._instance}constructor(){BayWindow._instance=this,this.bayWindowExpansion=[],this.dottedLinePoints=[],this.singleLine=[],this.bayWindowArea=null,this.bayWindowGroup=new THREE.Group}overhangTreatment(data,singleLine){this.singleLine=singleLine;const grid=PointSpatialHash.fromByLines(Scenario.Instance.lines);for(const i in data){this.bayWindowGroup=new THREE.Group,this.dottedLinePoints.push(data[i].dottedLine);let dashedLine=Scenario.Instance.correctionSorting([data[i].dottedLine]),lines=data[i].lines.slice(),listS=Scenario.Instance.correctionSorting(lines);const centroidPoint=this.getPolygonCentroid(listS);for(const a2 in listS)if(Number(a2)%2==0&&Number(a2)!==listS.length-1){const direction=this.pointSideOfLine(listS[a2].dian,listS[Number(a2)+1].dian,centroidPoint);listS[a2].direction=direction,listS[Number(a2)+1].direction=direction}let dataList=data[i].lines.slice();dataList.push(data[i].dottedLine),this.bayWindowArea=Polygon.fromByLines2(dataList),this.dashedLineTreatment(dashedLine,centroidPoint,data[i].data);let quanti=Scenario.Instance.correctionSorting(dataList);this.createBayWindowLayout(quanti,data[i].data);for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2,winDraw=winDrawLine(lines[Number(x)/2],grid);Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:listS[x].shared}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x,direction:listS[x].direction,shared:listS[x].shared}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:listS[x].shared};const wallHeight=listS[x].wallHeight;let Mesh=this.bayWindowExecutionOffset(a2,Number(x)/2,wallHeight,data[i].data,!0);if(!Mesh){console.log("夹角异常!");continue}if(Mesh.mesh3)if(winDraw&&winDraw.length>0){for(const x2 in winDraw)if(1===winDraw.length){this.installWindows(winDraw[x2],x2,Mesh.points3);let mesh=this.windowTreatment(winDraw[x2],Mesh.mesh3,wallHeight,Mesh.points3,a2);mesh.name=`飘窗墙_${Number(x2)/2}组`,mesh.userData.category="bayWindowWall",this.bayWindowGroup.add(mesh)}}else Mesh.mesh3.name=`飘窗墙_${Number(x)/2}组`,Mesh.mesh3.userData.category="bayWindowWall",this.bayWindowGroup.add(Mesh.mesh3)}const num=Number(i)+1;this.bayWindowGroup.name=`飘窗_${num}`,this.bayWindowGroup.userData.category="bayWindow",this.bayWindowGroup.userData.width=data[i].data.windowWidth,this.bayWindowGroup.userData.height=data[i].data.height2,this.bayWindowGroup.userData.groundHeight=data[i].data.height3,this.bayWindowGroup.userData.distanceToTheTop=data[i].data.height1;for(const w in data[i].lines)data[i].lines[w].userData.isWindow&&(this.bayWindowGroup.userData.depth=data[i].dottedLine.distanceToSegment(data[i].lines[w]));Scenario.Instance.group.add(this.bayWindowGroup)}}dashedLineTreatment(data,centroidPoint,item){let listS=data;for(const a2 in listS)if(Number(a2)%2==0&&Number(a2)!==listS.length-1){let direction;const v12=new THREE.Vector2(listS[Number(a2)+1].dian.x-listS[a2].dian.x,listS[Number(a2)+1].dian.y-listS[a2].dian.y),v2=new THREE.Vector2(centroidPoint.x-listS[a2].dian.x,centroidPoint.y-listS[a2].dian.y),crossZ=v12.x*v2.y-v12.y*v2.x;direction=Math.abs(crossZ)<1e-10?0:crossZ>0?-1:1,listS[a2].direction=direction,listS[Number(a2)+1].direction=direction}for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2;Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:!1}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x,direction:listS[x].direction,shared:!1}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x,direction:listS[x].direction,shared:!1};let Meshlist=this.bayWindowExecutionOffset(a2,Number(x)/2,item.height3,item,!1);if(!Meshlist){console.log("夹角异常1",Meshlist);continue}Scenario.Instance.group.add(Meshlist.mesh1),Scenario.Instance.group.add(Meshlist.mesh2)}}bayWindowExecutionOffset(data,index2,wallHeight,item,statuc=!1){const wallHeightc=wallHeight||Scenario.Instance.wallHeight,points=[];points.push(new THREE.Vector3(data.start.x,data.start.y,wallHeightc)),points.push(new THREE.Vector3(data.end.x,data.end.y,wallHeightc));let scale2=data.shared?.5*DEFAULT_WALL_WIDTH:DEFAULT_WALL_WIDTH;const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,scale2,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,scale2,!1);let startingPoint,finishLine;if(statuc){const dottedGrid=PointSpatialHash.fromByLines(this.singleLine),a2=new Point(data.start.x,data.start.y),b4=new Point(data.end.x,data.end.y);if(dottedGrid.queryCircle(a2,1e-4).length>0||dottedGrid.queryCircle(b4,1e-4).length>0)return startingPoint=this.xinLine(MobileX,MobileY,data.start,data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,data.direction),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint}}if(data.shared)return startingPoint=this.xinLine(MobileX,MobileY,data.start,-1*data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,-1*data.direction),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};startingPoint=this.xinLine(MobileX,MobileY,data.start,data.direction),finishLine=this.xinLine(MobileX,MobileY,data.end,data.direction);const grid=PointSpatialHash.fromByLines(Scenario.Instance.lines),isDouble=grid.queryCircle(Point.from(data.start),.001).some(item2=>LineGroupType.hasType(item2.userData,"doubleWall")||item2.userData?.userData.isDoor),isDouble1=grid.queryCircle(Point.from(data.end),.001).some(item2=>LineGroupType.hasType(item2.userData,"doubleWall")||item2.userData?.userData.isDoor);let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],0,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],1,wallHeightc);if(isDouble&&isDouble1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(isDouble&&!isDouble1){let status=!1,angle=null;for(const x in this.bayWindowExpansion)if(this.bayWindowExpansion[x].point.x===data.end.x&&this.bayWindowExpansion[x].point.y===data.end.y&&this.bayWindowExpansion[x].point.z===data.end.z){status=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z);angle=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start).dot(this.bayWindowExpansion[x].n),angle=Math.abs(angle)}if(!status){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(null!==angle&&angle<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==angle&&angle>.9){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(!isDouble&&isDouble1){let status=!1,angle=null;for(const x in this.bayWindowExpansion)if(this.bayWindowExpansion[x].point.x===data.start.x&&this.bayWindowExpansion[x].point.y===data.start.y&&this.bayWindowExpansion[x].point.z===data.start.z){status=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z);angle=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start).dot(this.bayWindowExpansion[x].n),angle=Math.abs(angle)}if(!status){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}if(null!==angle&&angle<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==angle&&angle>.9){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}if(!isDouble&&!isDouble1){let statua=!1,statub=!1,anglea=null,angleb=null;for(const x in this.bayWindowExpansion){if(this.bayWindowExpansion[x].point.x===data.start.x&&this.bayWindowExpansion[x].point.y===data.start.y&&this.bayWindowExpansion[x].point.z===data.start.z){statua=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);n.normalize();const v2=new THREE.Vector3(this.bayWindowExpansion[x].n.x,this.bayWindowExpansion[x].n.y,this.bayWindowExpansion[x].n.z);v2.normalize(),anglea=n.dot(v2),anglea=Math.abs(anglea)}if(this.bayWindowExpansion[x].point.x===data.end.x&&this.bayWindowExpansion[x].point.y===data.end.y&&this.bayWindowExpansion[x].point.z===data.end.z){statub=!0;const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);n.normalize();const v2=new THREE.Vector3(this.bayWindowExpansion[x].n.x,this.bayWindowExpansion[x].n.y,this.bayWindowExpansion[x].n.z);v2.normalize(),angleb=n.dot(v2),angleb=Math.abs(angleb)}}if(statua&&statub){if(null!==anglea&&anglea<.1&&null!==angleb&&angleb<.1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:startingPoint};if(null!==anglea&&anglea>.9&&null!==angleb&&angleb<.1){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}if(null!==anglea&&anglea<.1&&null!==angleb&&angleb>.9){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(null!==anglea&&anglea>.9&&null!==angleb&&angleb>.9){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}else if(statua&&!statub){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);if(this.bayWindowExpansion.push({point:data.end,n:n}),null!==anglea&&anglea<.1){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}}if(null!==anglea&&anglea>.9){if(this.bayWindowArea.pointWithin(Point.from(finishLine1[0]))){startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}{startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}else if(!statua&&statub){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);if(this.bayWindowExpansion.push({point:data.start,n:n}),null!==angleb&&angleb<.1){if(this.bayWindowArea.pointWithin(Point.from(startingPoint1[0]))){startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}if(null!==angleb&&angleb>.9){if(this.bayWindowArea.pointWithin(Point.from(startingPoint1[0]))){finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}{finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}else if(!statua&&!statub){let npc1=this.bayWindowArea.pointWithin(Point.from(startingPoint1[0])),npc2=this.bayWindowArea.pointWithin(Point.from(finishLine1[0]));if(npc1&&npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(npc1&&!npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint,index2,item,1),points3:winPointList}}if(!npc1&&npc2){const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}{const start=new THREE.Vector3(data.start.x,data.start.y,data.start.z),n=new THREE.Vector3(data.end.x,data.end.y,data.end.z).sub(start);this.bayWindowExpansion.push({point:data.start,n:n}),this.bayWindowExpansion.push({point:data.end,n:n}),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]);let winPointList=[];return winPointList.push(startingPoint[0]),winPointList.push(startingPoint[1]),winPointList.push(finishLine[1]),winPointList.push(finishLine[0]),{mesh1:Scenario.Instance.drawTheModel(startingPoint1,1,index2,wallHeightc),mesh2:this.createDashedLineCeilingWall(startingPoint1,index2,item,0),mesh3:this.createDashedLineCeilingWall(startingPoint1,index2,item,1),points3:winPointList}}}}}createDashedLineCeilingWall(startingPoint,index2,item,num){let startingPointZ,basePoints=[];startingPointZ=num?Scenario.Instance.height+item.height3:Scenario.Instance.height+item.height3+item.height2;for(const i in startingPoint)basePoints.push(new THREE.Vector3(startingPoint[i].x,startingPoint[i].y,startingPointZ));if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const shape=new THREE.Shape;shape.moveTo(basePoints[0].x,basePoints[0].y);for(const i in basePoints)"0"!==i&&shape.lineTo(basePoints[i].x,basePoints[i].y);shape.lineTo(basePoints[0].x,basePoints[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:0===num?item.height1:item.height2,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+basePoints[0].z);const material=new THREE.MeshStandardMaterial({color:Scenario.Instance.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);return new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall",cube}}angleToXAxisDegrees(x1,y1,x2,y2,wide,cd){const dx=x2-x1,dy=y2-y1;return cd?wide*Math.sin(Math.atan2(dy,dx)):wide*Math.cos(Math.atan2(dy,dx))}windowOpeningOffset(x,y,point2,wallHeight){let point1,point22,xOverflow=x>0?.001:-.001,YOverflow=y>0?.001:-.001;return 1===wallHeight?(point1=new THREE.Vector3(point2.x+x,point2.y-y,wallHeight),point22=new THREE.Vector3(point2.x-xOverflow,point2.y+YOverflow,wallHeight)):(point1=new THREE.Vector3(point2.x+xOverflow,point2.y-YOverflow,wallHeight),point22=new THREE.Vector3(point2.x-x,point2.y+y,wallHeight)),[point1,point22]}xinLine(x,y,point2,wallHeight){let point1,point22;return 1===wallHeight?(point1=new THREE.Vector3(point2.x+x,point2.y-y,wallHeight),point22=new THREE.Vector3(point2.x,point2.y,wallHeight)):(point1=new THREE.Vector3(point2.x,point2.y,wallHeight),point22=new THREE.Vector3(point2.x-x,point2.y+y,wallHeight)),[point1,point22]}xinLine1(x,y,pointa,pointb,num,wallHeight=2.2){let point1,point2;return 0===num?(point1=new THREE.Vector3(pointa.x-x,pointa.y-y,wallHeight),point2=new THREE.Vector3(pointb.x-x,pointb.y-y,wallHeight)):(point1=new THREE.Vector3(pointa.x+x,pointa.y+y,wallHeight),point2=new THREE.Vector3(pointb.x+x,pointb.y+y,wallHeight)),[point1,point2]}getPolygonCentroid(points){const n=points.length;let cx=0,cy=0;for(let i=0;i<n;i++)cx+=points[i].dian.x,cy+=points[i].dian.y;return{x:cx/n,y:cy/n,z:points[0].dian.z}}pointSideOfLine(p1,p2,p3){const v12=new THREE.Vector2(p2.x-p1.x,p2.y-p1.y),v2=new THREE.Vector2(p3.x-p1.x,p3.y-p1.y),crossZ=v12.x*v2.y-v12.y*v2.x;return Math.abs(crossZ)<1e-10?0:crossZ>0?1:-1}windowTreatment(dblWin,mesh,wallHeight,startingPoint,data){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_WIDTH+.001,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_WIDTH+.001,!1);let startingPoints=this.windowOpeningOffset(MobileX,MobileY,data.start,data.direction),finishLine=this.windowOpeningOffset(MobileX,MobileY,data.end,data.direction);return startingPoints.push(finishLine[1]),startingPoints.push(finishLine[0]),Scenario.Instance.winHoleOpening(startingPoints,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}installWindows(data,index2,startingPoint){const point4=new THREE.Vector3(startingPoint[0].x,startingPoint[0].y,data.start.z),point3=new THREE.Vector3(startingPoint[2].x,startingPoint[2].y,data.start.z),center=new THREE.Vector3;center.addVectors(point4,point3).multiplyScalar(.5);const point1=new THREE.Vector3(data.start.x,data.start.y,startingPoint[0].z),point2=new THREE.Vector3(data.end.x,data.end.y,startingPoint[0].z),dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:Scenario.Instance.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??Scenario.Instance.WindowGroundHeight)+Scenario.Instance.height;let menModel=Scenario.Instance.windowModely.clone();if(data.center&&distance2){const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set((distance2+.12)/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(center.x,center.y,groundClearance),Scenario.Instance.windowForm=Scenario.Instance.windowForm+1,menModel.name=`窗体_${Scenario.Instance.windowForm}`,menModel.userData.category="windowForm",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.bayWindowGroup.add(menModel)}}createBayWindowLayout(listS,objData){let distance2,sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i=0;i<listS.length-1;i++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));const seen=/* @__PURE__ */new Set,uniqueCoords=objectiveList.filter(coord=>{const key=JSON.stringify(coord.dian);return!seen.has(key)&&(seen.add(key),!0)});objectiveList=uniqueCoords;const shape=new Shape;shape.moveTo(objectiveList[0].dian.x,objectiveList[0].dian.y);for(let i=1;i<objectiveList.length;i++)shape.lineTo(objectiveList[i].dian.x,objectiveList[i].dian.y);shape.lineTo(objectiveList[0].dian.x,objectiveList[0].dian.y);const geometry=new THREE.ShapeGeometry(shape),material=new THREE.MeshStandardMaterial({color:Scenario.Instance.color,side:THREE.DoubleSide}),mesh=new THREE.Mesh(geometry,material);let mesh2=mesh.clone(),height1=Scenario.Instance.height+objData.height3,height2=Scenario.Instance.height+objData.height3+objData.height2;mesh.position.z=height1,mesh2.position.z=height2,this.bayWindowGroup.add(mesh),this.bayWindowGroup.add(mesh2)}}const DEFAULT_WALL_HALF_WIDTH=.5*DEFAULT_WALL_WIDTH;class Scenario{camera;scene;renderer;controls;axesHelper;group;closedArray;lines;singleLines;doorGroup;texture;numdu;color;doorModely;doubleDoorModely;windowModely;balconyModely;doorHeight;doorGroundHeight;WindowHeight;WindowGroundHeight;CabinetModel;tableModel;chairModel;switchModel;socketModel;waterCoolerModel;height;expandedList;wallHeight;box;singleLineWallValue;liangNum;zhuNum;poortNum;doorNum;windowNum;windowForm;static _instance;static get Instance(){return Scenario._instance}constructor(scene,camera,renderer,controls){Scenario._instance=this,this.camera=camera,this.scene=scene,this.renderer=renderer,this.controls=controls,this.axesHelper=new THREE.AxesHelper(20),this.liangNum=0,this.zhuNum=0,this.poortNum=0,this.doorNum=0,this.windowNum=0,this.windowForm=0,this.scene.add(this.axesHelper),this.group=null,this.closedArray=[],this.lines=[],this.singleLines=[],this.doorGroup=new Group$1,this.doorGroup.name="",this.texture=null,this.numdu=1,this.color=16777215,this.doorModely=null,this.doubleDoorModely=null,this.windowModely=null,this.balconyModely=null,this.CabinetModel=null,this.tableModel=null,this.chairModel=null,this.switchModel=null,this.socketModel=null,this.waterCoolerModel=null,this.doorHeight=2.1,this.doorGroundHeight=0,this.WindowHeight=.8,this.WindowGroundHeight=.7,this.height=0,this.expandedList=[],this.wallHeight=2.8,this.box=null,this.singleLineWallValue=null}async drawGraphics(lines,z,trajectoryJson){lines.forEach(line=>{for(const hole of WallHole.getIterator(line))if(!hole.groundClearance&&0!==hole.groundClearance)switch(hole.type){case"door":hole.groundClearance=this.doorGroundHeight;break;case"window":hole.groundClearance=this.WindowGroundHeight;break;default:hole.groundClearance=0}});const doorLines=lines.filter(line=>line.userData.isDoor);if((lines=BuildGroup.doubleWall(lines.filter(line=>!line.userData.isDoor))).push(...doorLines),await this.modelLoader(),await this.windowModelLoader(),await this.balconyModelLoader(),this.height=z,this.lines=lines,this.group){this.scene.remove(this.group);const meshes=[];this.scene.traverse(function(object){object.isMesh&&meshes.push(object)}),meshes.forEach(mesh=>{mesh.geometry&&mesh.geometry.dispose(),mesh.material&&(Array.isArray(mesh.material)?mesh.material.forEach(material=>{material.map&&material.map.dispose(),material.dispose()}):(mesh.material.map&&mesh.material.map.dispose(),mesh.material.dispose())),mesh.parent?.remove(mesh)})}return this.group=new Group$1,this.liangNum=0,this.zhuNum=0,this.poortNum=0,this.doorNum=0,this.windowNum=0,this.windowForm=0,this.expandedList=[],BayWindow.Instance||new BayWindow,BayWindow.Instance.bayWindowExpansion=[],BayWindow.Instance.dottedLinePoints=[],this.splitProcessData(lines,this.texture),this.scene.add(this.group),this.group}loadJSONFile(callback){const input=document.createElement("input");input.type="file",input.accept=".json",input.onchange=function(event){const file=event.target.files[0];if(!file)return;const reader=new FileReader;reader.onload=function(e){const jsonData=JSON.parse(e.target.result);callback(jsonData)},reader.onerror=function(){console.error("文件读取失败"),alert("文件读取失败")},reader.readAsText(file)},input.click()}splitProcessData(lines,texture){this.closedArray=lines.filter(item=>LineGroupType.hasType(item,"doubleWall"));let pillar=LineGroupType.getGroupsByType(lines,"pillar");for(const m in pillar)this.processTheColumnData(pillar[m]);let groups=LineGroupType.getGroupsByType(this.closedArray,"doubleWall"),bayWindow=lines.filter(item=>LineGroupType.hasType(item,"bayWindow"));const set2=new Set([...this.closedArray,...pillar].flat(2));let singleLineWall=lines.filter(line=>!set2.has(line)&&!line.userData.isDoor&&!line.userData.isBayWindow&&"bayWindow"!==line.userData.groupType),menList=lines.filter(line=>line.userData.isDoor),bayWinGroups=LineGroupType.getGroupsByType(bayWindow,"bayWindow"),bayWinList=[];bayWinGroups.forEach(lines2=>{const data=BayWindowHelper.getDrawData2(lines2);if(data){let dottedLine=null;for(const i in lines2)lines2[i].userData.isBayWindow&&(dottedLine=lines2[i],lines2.splice(Number(i),1));bayWinList.push({lines:lines2,data:data,dottedLine:dottedLine})}else for(const i in lines2)singleLineWall.push(lines2[i])}),BayWindow.Instance?.overhangTreatment(bayWinList,singleLineWall),this.TheHandlingOfTheDoor(menList),this.singleLineWallValue=PointSpatialHash.fromByLines(singleLineWall),this.overallTreatmentOfSingleLineWalls(singleLineWall);for(const g in groups){const a2=clippingInsertObjectDoubleWall(groups[g]);for(const i in a2){let wallHeight=0;for(const v2 in a2[i])a2[i][v2].userData.height>wallHeight&&(wallHeight=a2[i][v2].userData.height);20===wallHeight&&(wallHeight=this.wallHeight);let distance2,bitem=a2[i].slice(),listS=this.correctionSorting(bitem),sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i2=0;i2<listS.length-1;i2++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));let c=objectiveList.map(pos=>(pos.dian.x=parseFloat(pos.dian.x.toFixed(6)),pos.dian.y=parseFloat(pos.dian.y.toFixed(6)),pos)),d2=[];for(const i2 in c)d2.push(new THREE.Vector3(c[i2].dian.x,c[i2].dian.y,c[i2].dian.z));const seen=/* @__PURE__ */new Set,E=d2.filter(coord=>{const key=JSON.stringify(coord);return!seen.has(key)&&(seen.add(key),!0)});let Mesh;if(Mesh=this.drawTheModel(E,0,Number(i),wallHeight,a2[i]),Mesh){Mesh.material.envMap=texture,Mesh.material.needsUpdate=!0;const doubleLinesWindow=WallHoleDrawData.doubleHoleLine(a2[i]);if(doubleLinesWindow&&0!=doubleLinesWindow.length){let houMesh=null;for(const x in doubleLinesWindow)if(1===doubleLinesWindow.length){const edges=new THREE.EdgesGeometry(this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]);let mesh=this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight);this.group.add(mesh)}else if(houMesh)if(Number(x)===doubleLinesWindow.length-1){const edges=new THREE.EdgesGeometry(this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]);let mesh=this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight);this.group.add(mesh)}else"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type&&this.singleLineWallMountedDoor(doubleLinesWindow[x],E),"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]),houMesh=this.windowTreatment(doubleLinesWindow[x],houMesh,wallHeight);else"window"===doubleLinesWindow[x].userData.type?this.installWindows(doubleLinesWindow[x],E):"door"===doubleLinesWindow[x].userData.type?this.singleLineWallMountedDoor(doubleLinesWindow[x],E):"beam"===doubleLinesWindow[x].userData.type||"passageEntrance"===doubleLinesWindow[x].userData.type&&this.addThePassModel(doubleLinesWindow[x]),houMesh=this.windowTreatment(doubleLinesWindow[x],Mesh,wallHeight)}else this.group.add(Mesh)}}}}drawTheModel(data,num,index2,wallHeight,originalData){let colorValue=!1,liangOriginalData=null;if(originalData&&0===num){const doubleLinesWindow=WallHoleDrawData.doubleHoleLine(originalData);if(doubleLinesWindow&&0!=doubleLinesWindow.length)for(const x in doubleLinesWindow)"beam"===doubleLinesWindow[x].userData.type&&(colorValue=!0,liangOriginalData=doubleLinesWindow[x])}if(originalData&&1===num)for(const x in originalData)"beam"===originalData[x].userData.type&&(colorValue=!0,liangOriginalData=originalData[x]);let basePoints=[];for(const i in data)basePoints.push(new THREE.Vector3(data[i].x,data[i].y,this.height?this.height:0));if(4===basePoints.length){if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const geometry=this.createParallelepipedFromBase(basePoints,wallHeight),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);if(new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),colorValue&&liangOriginalData){const point1=new THREE.Vector3(liangOriginalData.start.x,liangOriginalData.start.y,0),point2=new THREE.Vector3(liangOriginalData.end.x,liangOriginalData.end.y,0);this.liangNum=this.liangNum+1,cube.name=`梁_${this.liangNum}`,cube.userData.category="beam";const distance2=point1.distanceTo(point2),height=liangOriginalData.userData.wallHeight-liangOriginalData.userData.height,wallWidth=liangOriginalData.userData.wallWidth?liangOriginalData.userData.wallWidth:.18,groundClearance=liangOriginalData.userData.height;cube.userData.width=distance2,cube.userData.depth=wallWidth,cube.userData.height=height,cube.userData.groundHeight=groundClearance}else 0===num?(cube.name=`双线墙_${index2}`,cube.userData.category="doubleWall"):1===num?(cube.name=`单线墙_${index2}`,cube.userData.category="wall"):(cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall");return cube}}{const geometry=this.createParallelepipedFromBase(basePoints,wallHeight),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return new THREE.EdgesGeometry(geometry),0===num?(cube.name=`双线墙_${index2}`,cube.userData.category="doubleWall"):1===num?(cube.name=`单线墙_${index2}`,cube.userData.category="wall"):(cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall"),cube}}executionOffset(data,index2,wallHeight,winDraw,line){let wallWidth;line.userData.tags?.includes("hole-independent")&&(wallWidth=.5*line.userData.wallWidth);const wallHeightc=wallHeight||this.wallHeight,points=[];points.push(new THREE.Vector3(data.start.x,data.start.y,wallHeightc)),points.push(new THREE.Vector3(data.end.x,data.end.y,wallHeightc)),(new THREE.BufferGeometry).setFromPoints(points),new THREE.LineBasicMaterial({color:65280});const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,wallWidth??DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,wallWidth??DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);const grid=PointSpatialHash.fromByLines(this.lines),isDouble=grid.queryCircle(Point.from(data.start),.001).some(item=>LineGroupType.hasType(item.userData,"doubleWall")||item.userData?.userData.isDoor),isDouble1=grid.queryCircle(Point.from(data.end),.001).some(item=>LineGroupType.hasType(item.userData,"doubleWall")||item.userData?.userData.isDoor);let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],0,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],1,wallHeightc);if(isDouble&&isDouble1)return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw);if(isDouble&&!isDouble1){let status=!1;for(const x in this.expandedList)this.expandedList[x].x===data.end.x&&this.expandedList[x].y===data.end.y&&this.expandedList[x].z===data.end.z&&(status=!0);if(status)return finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw);{const npcEnd=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcEnd).length?(this.expandedList.push(data.end),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.end),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw))}}if(!isDouble&&isDouble1){let status=!1;for(const x in this.expandedList)this.expandedList[x].x===data.start.x&&this.expandedList[x].y===data.start.y&&this.expandedList[x].z===data.start.z&&(status=!0);if(status)return startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw);{const npcStart=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcStart).length?(this.expandedList.push(data.start),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}}if(!isDouble&&!isDouble1){let statua=!1,statub=!1;for(const x in this.expandedList)this.expandedList[x].x===data.start.x&&this.expandedList[x].y===data.start.y&&this.expandedList[x].z===data.start.z&&(statua=!0),this.expandedList[x].x===data.end.x&&this.expandedList[x].y===data.end.y&&this.expandedList[x].z===data.end.z&&(statub=!0);if(statua&&statub)return startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw);if(statua&&!statub){const npcEnd=new Point(data.end.x,data.end.y);return 1===this.singleLineWallValue.queryPoint(npcEnd).length?(this.expandedList.push(data.end),startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.end),startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}if(!statua&&statub){const npcStart=new Point(data.start.x,data.start.y);return 1===this.singleLineWallValue.queryPoint(npcStart).length?(this.expandedList.push(data.start),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}if(!statua&&!statub){const npcStart=new Point(data.start.x,data.start.y),npcEnd=new Point(data.end.x,data.end.y);let npc1=1===this.singleLineWallValue.queryPoint(npcStart).length,npc2=1===this.singleLineWallValue.queryPoint(npcEnd).length;return npc1&&npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):!npc1&&npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw)):npc1&&!npc2?(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.drawTheModel(startingPoint,1,index2,wallHeightc,winDraw)):(this.expandedList.push(data.start),this.expandedList.push(data.end),startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.drawTheModel(startingPoint1,1,index2,wallHeightc,winDraw))}}}windowTreatment(dblWin,mesh,wallHeight){const doorList=dblWin;let start,end;mesh.userData.start&&mesh.userData.end?(start=mesh.userData.start,end=mesh.userData.end):(start=doorList.start,end=doorList.end);const MobileX=this.angleToXAxisDegrees(start.x,start.y,end.x,end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!0),MobileY=this.angleToXAxisDegrees(start.x,start.y,end.x,end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!1);let startingPoint=this.xinLine(MobileX,MobileY,start,wallHeight),finishLine=this.xinLine(MobileX,MobileY,end,wallHeight),x=MobileX>0?.003:-.003,y=MobileY>0?.003:-.003,startingPoint1=this.xinLine1(y,x,startingPoint[0],startingPoint[1],0,wallHeight),finishLine1=this.xinLine1(y,x,finishLine[0],finishLine[1],1,wallHeight);return startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.winHoleOpening(startingPoint1,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}windowTreatment1(dblWin,mesh,wallHeight){const doorList=dblWin,MobileX=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!0),MobileY=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,doorList.userData.wallWidth?doorList.userData.wallWidth+.001:.5,!1);let startingPoint=BayWindow.Instance.xinLine(MobileX,MobileY,doorList.start,wallHeight),finishLine=BayWindow.Instance.xinLine(MobileX,MobileY,doorList.end,wallHeight);return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.winHoleOpening(startingPoint,mesh,dblWin.userData.groundClearance,dblWin.userData.height)}TheHandlingOfTheDoor1(data){const wallHeightc=data.userData.height?data.userData.height:this.wallHeight,doorList=data,MobileX=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,DEFAULT_WALL_HALF_WIDTH+.01,!0),MobileY=this.angleToXAxisDegrees(doorList.start.x,doorList.start.y,doorList.end.x,doorList.end.y,DEFAULT_WALL_HALF_WIDTH+.01,!1);let startingPoint=this.xinLine(MobileX,MobileY,doorList.start,doorList.userData.height?doorList.userData.height:this.wallHeight),finishLine=this.xinLine(MobileX,MobileY,doorList.end,doorList.userData.height?doorList.userData.height:this.wallHeight);const quadtree=Quadtree.from(this.lines),doorPoint=doorList.start,doorPoint1=doorList.end;let statua=!1,statub=!1;if(statua=quadtree.queryPoint(doorPoint).some(item=>item.line.isPerpendicularTo(doorList,20)&&!LineGroupType.hasType(item.line,"doubleWall")),statub=quadtree.queryPoint(doorPoint1).some(item=>item.line.isPerpendicularTo(doorList,20)&&!LineGroupType.hasType(item.line,"doubleWall")),statua&&!statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc);return startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),startingPoint1}if(!statua&&statub){let finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);return startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),startingPoint}if(statua&&statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);return startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),startingPoint1}return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),startingPoint}TheHandlingOfTheDoor(data){const doorList=data;for(const i in doorList){const wallHeightc=data[i].userData.height?data[i].userData.height:this.wallHeight,point1=new THREE.Vector3(doorList[i].start.x,doorList[i].start.y,0),point2=new THREE.Vector3(doorList[i].end.x,doorList[i].end.y,0),point3=new THREE.Vector3(doorList[i].center.x,doorList[i].center.y,0),dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),MobileX=this.angleToXAxisDegrees(doorList[i].start.x,doorList[i].start.y,doorList[i].end.x,doorList[i].end.y,DEFAULT_WALL_HALF_WIDTH+.01,!0),MobileY=this.angleToXAxisDegrees(doorList[i].start.x,doorList[i].start.y,doorList[i].end.x,doorList[i].end.y,DEFAULT_WALL_HALF_WIDTH+.01,!1);let startingPoint=this.xinLine(MobileX,MobileY,doorList[i].start,doorList[i].userData.height?doorList[i].userData.height:this.wallHeight),finishLine=this.xinLine(MobileX,MobileY,doorList[i].end,doorList[i].userData.height?doorList[i].userData.height:this.wallHeight);const quadtree=Quadtree.from(this.lines),doorPoint=doorList[i].start,doorPoint1=doorList[i].end;let statua=!1,statub=!1;if(statua=quadtree.queryPoint(doorPoint).some(item=>item.line.isPerpendicularTo(doorList[i],20)&&!LineGroupType.hasType(item.line,"doubleWall")),statub=quadtree.queryPoint(doorPoint1).some(item=>item.line.isPerpendicularTo(doorList[i],20)&&!LineGroupType.hasType(item.line,"doubleWall")),statua&&!statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc);startingPoint1.push(finishLine[1]),startingPoint1.push(finishLine[0]),this.doorHoleOpening(wallHeightc,startingPoint1,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData?.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_HALF_WIDTH,this.doorCenterOffset(.03,doorList[i].end,point3),angleRad,i,doorList[i])}else if(!statua&&statub){let finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);startingPoint.push(finishLine1[1]),startingPoint.push(finishLine1[0]),this.doorHoleOpening(wallHeightc,startingPoint,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_HALF_WIDTH,this.doorCenterOffset(.03,doorList[i].start,point3),angleRad,i,doorList[i])}else if(statua&&statub){let startingPoint1=this.xinLine1(MobileY,MobileX,startingPoint[0],startingPoint[1],1,wallHeightc),finishLine1=this.xinLine1(MobileY,MobileX,finishLine[0],finishLine[1],0,wallHeightc);startingPoint1.push(finishLine1[1]),startingPoint1.push(finishLine1[0]),this.doorHoleOpening(wallHeightc,startingPoint1,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2-DEFAULT_WALL_WIDTH,point3,angleRad,i,doorList[i])}else startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.doorHoleOpening(wallHeightc,startingPoint,this.TheHandlingOfTheDoor1(doorList[i]),doorList[i].userData.drawDoorData?.groundClearance,doorList[i].userData.drawDoorData?.height,distance2,point3,angleRad,i,doorList[i])}}doorCenterOffset(distanceFromB,point2,pointc){point2=new THREE.Vector3(point2.x,point2.y,0);const direction=(new THREE.Vector3).subVectors(pointc,point2).normalize();return(new THREE.Vector3).copy(pointc).addScaledVector(direction.negate(),distanceFromB)}installWindows(data,lineCy){const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??this.WindowGroundHeight)+this.height;let menModel=this.windowModely.clone();if(data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,groundClearance),this.windowNum=this.windowNum+1,menModel.name=`窗_${this.windowNum}`,menModel.userData.category="window",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.group.add(menModel)}}dataPresentationEffect(data){}singleLineWallMountedDoor(data,lineCy){const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18,groundClearance=(data.userData.groundClearance??this.doorGroundHeight)+this.height;let menModel;if(menModel=distance2>=1.5?this.doubleDoorModely.clone():this.doorModely.clone(),data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,groundClearance),this.doorNum=this.doorNum+1,menModel.name=`门_${this.doorNum}`,menModel.userData.category="door",menModel.userData.winUuid=data.userData.winUuid,menModel.userData.lineUuid=data.userData.lineUuid,menModel.userData.width=distance2,menModel.userData.depth=wallWidth,menModel.userData.height=height,menModel.userData.groundHeight=groundClearance,this.group.add(menModel)}}installBalconys(data,index2){let balconyGroup=new Group$1;balconyGroup.name=`阳台${index2}`,balconyGroup.userData.category="balcony",balconyGroup.userData.height=data.userData.height,balconyGroup.userData.width=data.length,balconyGroup.userData.depth=0,balconyGroup.userData.groundHeight=0;const point1=new THREE.Vector3(data.start.x,data.start.y,0),point2=new THREE.Vector3(data.end.x,data.end.y,0);new THREE.Vector3(data.center.x,data.center.y,0);const dx=point2.x-point1.x,dy=point2.y-point1.y,angleRad=Math.atan2(dy,dx),distance2=point1.distanceTo(point2),height=data.userData.height?data.userData.height:this.WindowHeight,wallWidth=data.userData.wallWidth?data.userData.wallWidth:.18;data.userData.groundClearance??this.WindowGroundHeight,this.height;let menModel=this.balconyModely.clone();if(distance2<1.2){if(data.center&&distance2){menModel.position.set(data.center.x,data.center.y,0);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,height/size2.y,wallWidth/size2.z),menModel.position.set(data.center.x,data.center.y,this.height),menModel.name=`阳台_${index2}`,menModel.userData.category="balcony_",balconyGroup.add(menModel),this.group.add(balconyGroup)}}else{let splitLineInto7Points=function(startPoint,endPoint){const points2=[],startVec=new THREE.Vector3(startPoint.x,startPoint.y,startPoint.z),endVec=new THREE.Vector3(endPoint.x,endPoint.y,endPoint.z);for(let i=0;i<=npc;i++){const fraction=i/npc,point3=new THREE.Vector3;point3.lerpVectors(startVec,endVec,fraction),points2.push(point3)}return points2},npc=0;npc=distance2/.8,npc=Math.round(npc);const points=splitLineInto7Points(point1,point2);for(let o=0;o<points.length-1;o++){const spacing=points[o].distanceTo(points[o+1]),center=new THREE.Vector3;center.lerpVectors(points[o],points[o+1],.5);let balconyModel=this.balconyModely.clone();const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),balconyModel.rotation.x=Math.PI/2,balconyModel.rotation.y=angleRad,balconyModel.scale.set(spacing/size2.x,height/size2.y,wallWidth/size2.z),balconyModel.position.set(center.x,center.y,this.height),balconyModel.name=`阳台_${index2}`,balconyModel.userData.category="balcony_",balconyGroup.add(balconyModel)}this.group.add(balconyGroup)}}installCabinet(){let cabinetModel=this.CabinetModel.clone();cabinetModel.position.set(5,5,0);const box32=new THREE.Box3;box32.setFromObject(cabinetModel);let size2=new THREE.Vector3;box32.getSize(size2),cabinetModel.rotation.x=Math.PI/2,cabinetModel.scale.set(.7/size2.x,.7/size2.y,.3/size2.z),this.group.add(cabinetModel)}installTable(){let tableModel=this.tableModel.clone();tableModel.position.set(5,4,0);const box32=new THREE.Box3;box32.setFromObject(tableModel);let size2=new THREE.Vector3;box32.getSize(size2),tableModel.rotation.x=Math.PI/2,tableModel.scale.set(.7/size2.x,.75/size2.y,1.3/size2.z),this.group.add(tableModel)}installchair(){let tableModel=this.tableModel.clone();tableModel.position.set(5,4,0);const box32=new THREE.Box3;box32.setFromObject(tableModel);let size2=new THREE.Vector3;box32.getSize(size2),tableModel.rotation.x=Math.PI/2,tableModel.scale.set(.7/size2.x,.75/size2.y,1.3/size2.z),this.group.add(tableModel)}winHoleOpening(data,mesh,winGroundHeight,Height){winGroundHeight=(winGroundHeight??this.WindowGroundHeight)+this.height;const basePoints=[new THREE.Vector3(data[0].x,data[0].y,winGroundHeight),new THREE.Vector3(data[1].x,data[1].y,winGroundHeight),new THREE.Vector3(data[2].x,data[2].y,winGroundHeight),new THREE.Vector3(data[3].x,data[3].y,winGroundHeight)],geometry=this.createParallelepipedFromBase(basePoints,Height??this.WindowHeight);new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide});const brush1=new Brush(mesh.geometry);brush1.updateMatrixWorld();const brush2=new Brush(geometry);brush2.updateMatrixWorld();const result=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION);return result.material=mesh.material,"beam"!==mesh.userData.category&&"passageEntrance"!==mesh.userData.category||(result.name=mesh.name,result.userData=mesh.userData),result}doorHoleOpening(wallHeight,data,data1,groundHeight,Height,distance2,center,angleRad,index2,doorList){groundHeight=(groundHeight??this.doorGroundHeight)+this.height;const basePoints=[new THREE.Vector3(data[0].x,data[0].y,groundHeight),new THREE.Vector3(data[1].x,data[1].y,groundHeight),new THREE.Vector3(data[2].x,data[2].y,groundHeight),new THREE.Vector3(data[3].x,data[3].y,groundHeight)],basePoints1=[new THREE.Vector3(data1[0].x,data1[0].y,groundHeight),new THREE.Vector3(data1[1].x,data1[1].y,groundHeight),new THREE.Vector3(data1[2].x,data1[2].y,groundHeight),new THREE.Vector3(data1[3].x,data1[3].y,groundHeight)],basePoints2=[new THREE.Vector3(data[0].x,data1[0].y,groundHeight),new THREE.Vector3(data[1].x,data1[1].y,groundHeight),new THREE.Vector3(data[2].x,data1[2].y,groundHeight),new THREE.Vector3(data[3].x,data1[3].y,groundHeight)],geometry=this.createParallelepipedFromBase(basePoints,wallHeight),geometry1=this.createParallelepipedFromBase(basePoints1,Height||this.doorHeight),geometry2=this.createParallelepipedFromBase(basePoints2,Height||this.doorHeight),brush1=new Brush(geometry);brush1.updateMatrixWorld();const brush2=new Brush(geometry1);brush2.updateMatrixWorld();const result=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),material1=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide});result.material=material1,new THREE.Mesh(geometry2,material);const edges=new THREE.EdgesGeometry(result.geometry);let menModel;if(new THREE.EdgesGeometry(geometry2),new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),menModel=distance2>=1.5?this.doubleDoorModely.clone():this.doorModely.clone(),center&&distance2){menModel.position.set(center.x,center.y,groundHeight);const box32=new THREE.Box3;box32.setFromObject(menModel);let size2=new THREE.Vector3;box32.getSize(size2),menModel.rotation.x=Math.PI/2,menModel.rotation.y=angleRad,menModel.scale.set(distance2/size2.x,(Height||this.doorHeight)/size2.y,DEFAULT_WALL_WIDTH/size2.z),menModel.name=`门_${index2}`,menModel.userData.category="door",menModel.userData.uuid=doorList?.uuid,menModel.userData.width=distance2,menModel.userData.height=Height||this.doorHeight,menModel.userData.groundHeight=groundHeight,this.group.add(menModel)}result.name=`额墙_${index2}`,result.userData.category="partitionWall",this.group.add(result)}angleToXAxisDegrees(x1,y1,x2,y2,wide,cd){const dx=x2-x1,dy=y2-y1;return cd?wide*Math.sin(Math.atan2(dy,dx)):wide*Math.cos(Math.atan2(dy,dx))}xinLine(x,y,point2,wallHeight){let xOverflow=x>0?.001:-.001,YOverflow=y>0?.001:-.001;return[new THREE.Vector3(point2.x+x-xOverflow,point2.y-y-YOverflow,wallHeight),new THREE.Vector3(point2.x-x-xOverflow,point2.y+y-YOverflow,wallHeight)]}expandRectangleAlongLongSide(p1,p2,p3,p4,expandAmount=.01){const edge12=(new THREE.Vector3).copy(p2).sub(p1),edge23=(new THREE.Vector3).copy(p3).sub(p2),edge34=(new THREE.Vector3).copy(p4).sub(p3),edge41=(new THREE.Vector3).copy(p1).sub(p4),len12=edge12.length(),len23=edge23.length(),len34=edge34.length(),len41=edge41.length();let longEdgeDirection,longEdgeStart1,longEdgeEnd1,longEdgeStart2,longEdgeEnd2;len12>=len23&&len12>=len34&&len12>=len41?(longEdgeDirection=edge12.clone().normalize(),edge23.clone().normalize(),longEdgeStart1=p1,longEdgeEnd1=p2,longEdgeStart2=p4,longEdgeEnd2=p3):len23>=len12&&len23>=len34&&len23>=len41?(longEdgeDirection=edge23.clone().normalize(),edge34.clone().normalize(),longEdgeStart1=p2,longEdgeEnd1=p3,longEdgeStart2=p1,longEdgeEnd2=p4):len34>=len12&&len34>=len23&&len34>=len41?(longEdgeDirection=edge34.clone().normalize(),edge41.clone().normalize(),longEdgeStart1=p3,longEdgeEnd1=p4,longEdgeStart2=p2,longEdgeEnd2=p1):(longEdgeDirection=edge41.clone().normalize(),edge12.clone().normalize(),longEdgeStart1=p4,longEdgeEnd1=p1,longEdgeStart2=p3,longEdgeEnd2=p2);return[longEdgeStart1.clone().add(longEdgeDirection.clone().multiplyScalar(-expandAmount)),longEdgeEnd1.clone().add(longEdgeDirection.clone().multiplyScalar(expandAmount)),longEdgeEnd2.clone().add(longEdgeDirection.clone().multiplyScalar(expandAmount)),longEdgeStart2.clone().add(longEdgeDirection.clone().multiplyScalar(-expandAmount))]}expandRectangleSimple(p1,p2,p3,p4,expandAmount=.01){const edge12=(new THREE.Vector3).copy(p2).sub(p1),edge14=(new THREE.Vector3).copy(p4).sub(p1),len12=edge12.length(),len14=edge14.length();let longEdgeDir,shortEdgeDir,halfLong,halfShort;len12>=len14?(longEdgeDir=edge12.clone().normalize(),shortEdgeDir=edge14.clone().normalize(),halfLong=len12/2,halfShort=len14/2):(longEdgeDir=edge14.clone().normalize(),shortEdgeDir=edge12.clone().normalize(),halfLong=len14/2,halfShort=len12/2);const center=(new THREE.Vector3).copy(p1).add(p2).add(p3).add(p4).multiplyScalar(.25),newHalfLong=halfLong+expandAmount,newHalfShort=halfShort+expandAmount;return[center.clone().addScaledVector(longEdgeDir,-newHalfLong).addScaledVector(shortEdgeDir,-newHalfShort),center.clone().addScaledVector(longEdgeDir,newHalfLong).addScaledVector(shortEdgeDir,-newHalfShort),center.clone().addScaledVector(longEdgeDir,newHalfLong).addScaledVector(shortEdgeDir,newHalfShort),center.clone().addScaledVector(longEdgeDir,-newHalfLong).addScaledVector(shortEdgeDir,newHalfShort)]}xinLine1(x,y,pointa,pointb,num,wallHeight){let point1,point2;return 0===num?(point1=new THREE.Vector3(pointa.x-x,pointa.y-y,wallHeight),point2=new THREE.Vector3(pointb.x-x,pointb.y-y,wallHeight)):(point1=new THREE.Vector3(pointa.x+x,pointa.y+y,wallHeight),point2=new THREE.Vector3(pointb.x+x,pointb.y+y,wallHeight)),[point1,point2]}createParallelepipedFromBase(points,height){const shape=new THREE.Shape;shape.moveTo(points[0].x,points[0].y);for(const i in points)"0"!==i&&shape.lineTo(points[i].x,points[i].y);shape.lineTo(points[0].x,points[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:height,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+points[0].z);return geometry}correctionSorting(bitem){let listS=[];for(const i in bitem){const abc=2===LineGroupType.getIdsByType(bitem[i],"bayWindow").length;if(0===listS.length){const b4=new THREE.Vector3(bitem[i].start.x,bitem[i].start.y,bitem[i].start.z),c=new THREE.Vector3(bitem[i].end.x,bitem[i].end.y,bitem[i].end.z);listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})}else{const b4=new THREE.Vector3(bitem[i].start.x,bitem[i].start.y,bitem[i].start.z),c=new THREE.Vector3(bitem[i].end.x,bitem[i].end.y,bitem[i].end.z),distanceAB=listS[listS.length-1].dian.distanceTo(b4),distanceAC=listS[listS.length-1].dian.distanceTo(c);distanceAB<distanceAC?(listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})):distanceAC<distanceAB?(listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc})):(listS.push({dian:b4,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}),listS.push({dian:c,zhong:i,wallHeight:bitem[i].userData.height?bitem[i].userData.height:this.wallHeight,shared:abc}))}}return listS}balconyTreatment(bayWinList){for(const i in bayWinList){let lines=bayWinList[i].lines;for(const o in lines)if(lines[o].userData.isBayWindow){let Mesh=this.overhangWallOffset(lines[o],i,bayWinList[i].data.height3);this.group.add(Mesh);let Mesh1=this.dashedLineCeilingTreatment(lines[o],i,bayWinList[i].data);this.group.add(Mesh1)}}}overhangWallOffset(data,index2,height){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);return startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]),this.drawTheModel(startingPoint,1,index2,height)}dashedLineCeilingTreatment(data,index2,item){const MobileX=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!0),MobileY=this.angleToXAxisDegrees(data.start.x,data.start.y,data.end.x,data.end.y,DEFAULT_WALL_HALF_WIDTH,!1);let startingPoint=this.xinLine(MobileX,MobileY,data.start,0),finishLine=this.xinLine(MobileX,MobileY,data.end,1);startingPoint.push(finishLine[1]),startingPoint.push(finishLine[0]);let basePoints=[];const startingPointZ=this.height+item.height3+item.height2;for(const i in startingPoint)basePoints.push(new THREE.Vector3(startingPoint[i].x,startingPoint[i].y,startingPointZ));if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const shape=new THREE.Shape;shape.moveTo(basePoints[0].x,basePoints[0].y);for(const i in basePoints)"0"!==i&&shape.lineTo(basePoints[i].x,basePoints[i].y);shape.lineTo(basePoints[0].x,basePoints[0].y);const geometry=new THREE.ExtrudeGeometry(shape,{depth:item.height1,bevelEnabled:!1}),position=geometry.getAttribute("position");for(let i=0;i<position.count;i++)position.setZ(i,position.getZ(i)+basePoints[0].z);const material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material),edges=new THREE.EdgesGeometry(geometry);return new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),cube.name=`飘窗墙_${index2}组`,cube.userData.category="bayWindowWall",cube}}overallTreatmentOfSingleLineWalls(data){let balconyLins=[];for(let i=data.length-1;i>=0;i--)data[i].userData.isBalconyRailing&&(balconyLins.push(data[i]),data.splice(i,1));for(const o in balconyLins)this.installBalconys(balconyLins[o],o);const grid=PointSpatialHash.fromByLines(this.lines);let listS=this.correctionSorting(data);for(const i in listS)Number(i)%2==0&&Number(i)!==listS.length-1&&this.singleLines.push({start:listS[i].dian,end:listS[Number(i)+1].dian,index:i});for(const x in listS)if(Number(x)%2==0&&Number(x)!==listS.length-1){let point1,point2,distance2,a2,winDraw=WallHoleDrawData.singleHoleLine(data[Number(x)/2],grid);this.dataPresentationEffect(winDraw),Number(x)<listS.length-2?(point1=new THREE.Vector3(listS[Number(x)+1].dian.x,listS[Number(x)+1].dian.y,listS[Number(x)+1].dian.z),point2=new THREE.Vector3(listS[Number(x)+2].dian.x,listS[Number(x)+2].dian.y,listS[Number(x)+2].dian.z)):(point1=new THREE.Vector3(0,0,0),point2=new THREE.Vector3(0,0,0)),distance2=point1.distanceTo(point2),"0"===x&&(a2={start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x}),a2=distance2<.01?{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!1,index:x}:{start:listS[x].dian,end:listS[Number(x)+1].dian,isTheFirst:!0,index:x};const wallHeight=listS[x].wallHeight;let Mesh,status=!1;for(const y in winDraw)"beam"===winDraw[Number(y)].userData.type&&(status=!0,Mesh=this.generateBeamModel(data[Number(x)/2]));if(status){Mesh&&this.group.add(Mesh);continue}Mesh=this.executionOffset(a2,Number(x)/2,wallHeight,winDraw,data[Number(x)/2]);for(const y in winDraw)"beam"===winDraw[Number(y)].userData.type&&(Mesh.userData.start=a2.start,Mesh.userData.end=a2.end);if(Mesh)if(winDraw&&winDraw.length>0){let houMesh=null;for(const s in winDraw)if(1===winDraw.length){const edges=new THREE.EdgesGeometry(this.windowTreatment(winDraw[s],Mesh,wallHeight).geometry);new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0})),"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]);let mesh=this.windowTreatment(winDraw[s],Mesh,wallHeight);this.group.add(mesh)}else if(houMesh)if(Number(s)===winDraw.length-1){const edges=new THREE.EdgesGeometry(this.windowTreatment(winDraw[s],houMesh,wallHeight).geometry);"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:0}));let mesh=this.windowTreatment(winDraw[s],houMesh,wallHeight);this.group.add(mesh)}else"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"beam"===winDraw[s].userData.type?console.log("梁"):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),houMesh=this.windowTreatment(winDraw[s],houMesh,wallHeight);else"window"===winDraw[s].userData.type?this.installWindows(winDraw[s],data[Number(x)/2]):"door"===winDraw[s].userData.type?this.singleLineWallMountedDoor(winDraw[s],data[Number(x)/2]):"beam"===winDraw[s].userData.type?console.log("梁"):"passageEntrance"===winDraw[s].userData.type&&this.addThePassModel(winDraw[s]),houMesh=this.windowTreatment(winDraw[s],Mesh,wallHeight)}else this.group.add(Mesh)}}generateBeamModel(line){let basePoints,expansionPoints,cube;if(line.userData.expansionWidth||line.userData.expansionDirction){const directionX=line.userData.expansionDirction.x*line.userData.expansionWidth,directionY=line.userData.expansionDirction.y*line.userData.expansionWidth;let pointStart=new THREE.Vector3(line.start.x,line.start.y,this.height?this.height:0),pointEnd=new THREE.Vector3(line.end.x,line.end.y,this.height?this.height:0),startExpansion=new THREE.Vector3(pointStart.x+directionX,pointStart.y+directionY,this.height?this.height:0);basePoints=[pointStart,pointEnd,new THREE.Vector3(pointEnd.x+directionX,pointEnd.y+directionY,this.height?this.height:0),startExpansion];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material2=new THREE.MeshStandardMaterial({color:5214420,side:THREE.DoubleSide}),beamList=WallHoleDrawData.singleHoleLine(line);cube=new THREE.Mesh(geometry,material2);for(const w in beamList)cube=this.pierceTheBeam(cube,beamList[Number(w)],line,1)}else{let wallWidth;wallWidth=line.userData.wallWidth?line.userData.wallWidth/2:.06;const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wallWidth,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wallWidth,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0);basePoints=[startingPoint[0],startingPoint[1],finishLine[1],finishLine[0]];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material2=new THREE.MeshStandardMaterial({color:5214420,side:THREE.DoubleSide}),beamList=WallHoleDrawData.singleHoleLine(line);cube=new THREE.Mesh(geometry,material2);for(const w in beamList)cube=this.pierceTheBeam(cube,beamList[Number(w)],wallWidth,0)}const material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),beamLint=WallHoleDrawData.singleHoleLine(line),point1=new THREE.Vector3(basePoints[0].x,basePoints[0].y,basePoints[0].z+beamLint[0].userData.height-.001),point2=new THREE.Vector3(basePoints[1].x,basePoints[1].y,basePoints[1].z+beamLint[0].userData.height-.001),point3=new THREE.Vector3(basePoints[2].x,basePoints[2].y,basePoints[2].z+beamLint[0].userData.height-.001),point4=new THREE.Vector3(basePoints[3].x,basePoints[3].y,basePoints[3].z+beamLint[0].userData.height-.001);expansionPoints=this.expandRectangleSimple(point1,point2,point3,point4,.001);const bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height-beamLint[0].userData.height+.002),brush1=new Brush(cube.geometry);brush1.updateMatrixWorld();const brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();const wallCube=(new Evaluator).evaluate(brush1,brush2,SUBTRACTION);wallCube.material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),this.group.add(wallCube);const result=new THREE.Mesh(bodyGeometry,material);return this.liangNum=this.liangNum+1,result.name=`梁_${this.liangNum}`,result.userData.category="beam",result.userData.width=line.length,result.userData.depth=line.userData.expansionWidth??line.userData.wallWidth??DEFAULT_WALL_WIDTH,result.userData.height=line.userData.height-(line.userData.passageEntrance[0].groundClearance+line.userData.passageEntrance[0].height),result.userData.groundHeight=line.userData.passageEntrance[0].groundClearance+line.userData.passageEntrance[0].height,result}pierceTheBeam(model,line,wall,num){if(num){const brush1=new Brush(model.geometry),directionX=wall.userData.expansionDirction.x*wall.userData.expansionWidth,directionY=wall.userData.expansionDirction.y*wall.userData.expansionWidth;let pointStart=new THREE.Vector3(line.start.x,line.start.y,this.height?this.height:0),pointEnd=new THREE.Vector3(line.end.x,line.end.y,this.height?this.height:0),startExpansion=new THREE.Vector3(pointStart.x+directionX,pointStart.y+directionY,this.height?this.height:0),endExpansion=new THREE.Vector3(pointEnd.x+directionX,pointEnd.y+directionY,this.height?this.height:0);const expansionPoints=this.expandRectangleSimple(pointStart,pointEnd,endExpansion,startExpansion,.01),bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height),brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();return(new Evaluator).evaluate(brush1,brush2,SUBTRACTION)}{const brush1=new Brush(model.geometry);brush1.updateMatrixWorld();const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wall,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,wall,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0);const expansionPoints=this.expandRectangleSimple(startingPoint[0],startingPoint[1],finishLine[1],finishLine[0],.01),bodyGeometry=this.createParallelepipedFromBase(expansionPoints,line.userData.height),brush2=new Brush(bodyGeometry);brush2.updateMatrixWorld();return(new Evaluator).evaluate(brush1,brush2,SUBTRACTION)}}generateColumnModel(data,lines,Height){let basePoints=[];for(const i in data)basePoints.push(new THREE.Vector3(data[i].x,data[i].y,this.height?this.height:0));let longerSide=0,shortSide=100;for(const w in lines)lines[w].length>longerSide&&(longerSide=lines[w].length),lines[w].length<shortSide&&(shortSide=lines[w].length);if(4===basePoints.length){if(basePoints[0].distanceTo(basePoints[3])<.005)return null;{const geometry=this.createParallelepipedFromBase(basePoints,Height),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return this.zhuNum=this.zhuNum+1,cube.name=`柱_${this.zhuNum}`,cube.userData.category="pillar",cube.userData.width=longerSide,cube.userData.depth=shortSide,cube.userData.height=Height,cube.userData.groundHeight=0,cube}}{const geometry=this.createParallelepipedFromBase(basePoints,Height),material=new THREE.MeshStandardMaterial({color:this.color,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);return this.zhuNum=this.zhuNum+1,cube.name=`柱_${this.zhuNum}`,cube.userData.category="pillar",cube.userData.width=longerSide,cube.userData.depth=shortSide,cube.userData.height=Height,cube.userData.groundHeight=0,cube}}processTheColumnData(lines){let pillarHeight=0;for(const w in lines)lines[w].userData.height>pillarHeight&&(pillarHeight=lines[w].userData.height);let distance2,bitem=lines.slice(),listS=this.correctionSorting(bitem),sliceList=listS.slice(1),distance1={num:100,index:""},distance3={data:null,index:""},objectiveList=[];objectiveList.push(listS[0]);for(let i=0;i<listS.length-1;i++)for(const x in sliceList)distance2=objectiveList[objectiveList.length-1].dian.distanceTo(sliceList[x].dian),distance2<distance1.num&&(distance1.num=distance2,distance1.index=x),objectiveList[objectiveList.length-1].zhong===sliceList[x].zhong&&(distance3.data=sliceList[x],distance3.index=x),x===""+(sliceList.length-1)&&(distance3.data?(objectiveList.push(distance3.data),distance1.num=100,sliceList.splice(distance3.index,1),distance3.data=null,distance3.index=""):(objectiveList.push(sliceList[distance1.index]),distance1.num=100,sliceList.splice(distance1.index,1)));let c=objectiveList.map(pos=>(pos.dian.x=parseFloat(pos.dian.x.toFixed(6)),pos.dian.y=parseFloat(pos.dian.y.toFixed(6)),pos)),d2=[];for(const i in c)d2.push(new THREE.Vector3(c[i].dian.x,c[i].dian.y,c[i].dian.z));const seen=/* @__PURE__ */new Set,E=d2.filter(coord=>{const key=JSON.stringify(coord);return!seen.has(key)&&(seen.add(key),!0)});let mesh=this.generateColumnModel(E,lines,pillarHeight);this.group.add(mesh)}addThePassModel(line){const MobileX=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,.5*line.userData.wallWidth,!0),MobileY=this.angleToXAxisDegrees(line.start.x,line.start.y,line.end.x,line.end.y,.5*line.userData.wallWidth,!1);let startingPoint=this.xinLine(MobileX,MobileY,line.start,this.height?this.height:0),finishLine=this.xinLine(MobileX,MobileY,line.end,this.height?this.height:0),basePoints=[startingPoint[0],startingPoint[1],finishLine[1],finishLine[0]];const geometry=this.createParallelepipedFromBase(basePoints,line.userData.height),material=new THREE.MeshStandardMaterial({color:5214420,transparent:!0,opacity:0,side:THREE.DoubleSide}),cube=new THREE.Mesh(geometry,material);"passageEntrance"===line.userData.type&&(this.poortNum=this.poortNum+1,cube.name=`垭口_${this.poortNum}`,cube.userData.category="passageEntrance",cube.userData.height=line.userData.height,cube.userData.width=line.length,cube.userData.depth=line.userData.wallWidth,cube.userData.groundHeight=0),this.group.add(cube)}createAPlane(lines,menList){let precision=lines.map(pos=>(pos.start.x=parseFloat(pos.start.x.toFixed(3)),pos.start.y=parseFloat(pos.start.y.toFixed(3)),pos.end.x=parseFloat(pos.end.x.toFixed(3)),pos.end.y=parseFloat(pos.end.y.toFixed(3)),pos)),points=[],head=null,theTail=null;for(const x in precision)"0"===x?(head=precision[x].start,theTail=precision[x].end,points.push([precision[x].start.x,precision[x].start.y]),points.push([precision[x].end.x,precision[x].end.y])):precision[x].start.x===head.x&&precision[x].start.y===head.y?(points.push([precision[x].end.x,precision[x].end.y]),theTail=precision[x].end):precision[x].end.x===head.x&&precision[x].end.y===head.y?(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start):precision[x].start.x===theTail.x&&precision[x].start.y===theTail.y?(points.push([precision[x].end.x,precision[x].end.y]),head=theTail,theTail=precision[x].end):precision[x].end.x===theTail.x&&precision[x].end.y===theTail.y?(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start):(points.push([precision[x].start.x,precision[x].start.y]),head=precision[x].start,points.push([precision[x].end.x,precision[x].end.y]),theTail=precision[x].end)}async modelLoader(){this.doorModely=await LoadModel.loadGlb("door"),this.doubleDoorModely=await LoadModel.loadGlb("doubleDoor")}async windowModelLoader(){this.windowModely=await LoadModel.loadGlb("window")}async balconyModelLoader(){this.balconyModely=await LoadModel.loadGlb("balconyFilmFilmFilm")}damian(){const planeGeometry=new THREE.BufferGeometry,vertices=new Float32Array([-20,-20,0,20,-20,0,20,20,0,-20,20,0]);planeGeometry.setAttribute("position",new THREE.BufferAttribute(vertices,3));const planeMaterial=new THREE.MeshBasicMaterial({color:15066597,side:THREE.DoubleSide}),indices=new Uint16Array([0,1,2,2,3,0]);planeGeometry.setIndex(new THREE.BufferAttribute(indices,1));const plane=new THREE.Mesh(planeGeometry,planeMaterial);this.group.add(plane)}drawStaircase=pcdPointsArr=>{console.log(pcdPointsArr);const pointCloudGroup=new THREE.Group,material=new THREE.MeshStandardMaterial({color:16737792,side:THREE.DoubleSide});for(let i=0;i<pcdPointsArr.length;i++){const points=[];for(let j=0;j<pcdPointsArr[i].path.length;j++)points.push(new THREE.Vector3(pcdPointsArr[i].path[j][0],pcdPointsArr[i].path[j][1],0));if(0==points.length)continue;let bottom1=new THREE.Vector3(pcdPointsArr[i].stairBottomPt1.x,pcdPointsArr[i].stairBottomPt1.y,pcdPointsArr[i].stairBottomPt1.z),bottom2=new THREE.Vector3(pcdPointsArr[i].stairBottomPt2.x,pcdPointsArr[i].stairBottomPt2.y,pcdPointsArr[i].stairBottomPt2.z);for(let x=0;x<pcdPointsArr[i].stairStepNum;x++){let rectArray=[bottom1,bottom2];rectArray.push(bottom2.clone().addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth)),rectArray.push(bottom1.clone().addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth));let boxGeometry=this.createBoxGeometryFromRectPoints(rectArray,pcdPointsArr[i].stairStepHeight);const mesh=new THREE.Mesh(boxGeometry,material);pointCloudGroup.add(mesh),bottom1=bottom1.addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth),bottom1=bottom1.addScaledVector(new THREE.Vector3(0,0,1),pcdPointsArr[i].stairStepHeight),bottom2=bottom2.addScaledVector(pcdPointsArr[i].vecStepWidth,pcdPointsArr[i].stairStepWidth),bottom2=bottom2.addScaledVector(new THREE.Vector3(0,0,1),pcdPointsArr[i].stairStepHeight)}if(0!=pcdPointsArr[i].rectPt1.x&&0!=pcdPointsArr[i].rectPt1.y){let rectArray=[pcdPointsArr[i].stairBottomPt1,pcdPointsArr[i].stairBottomPt2,pcdPointsArr[i].rectPt2,pcdPointsArr[i].rectPt1],boxGeometry=this.createBoxGeometryFromRectPoints(rectArray,pcdPointsArr[i].stairStepHeight);const mesh=new THREE.Mesh(boxGeometry,material);pointCloudGroup.add(mesh)}}return pointCloudGroup};createBoxGeometryFromRectPoints=(rectPoints,height)=>{const p0=rectPoints[0],p1=rectPoints[1],p2=rectPoints[2],p3=rectPoints[3],xDir=(new THREE.Vector3).subVectors(p1,p0),yDir=(new THREE.Vector3).subVectors(p3,p0),width=xDir.length(),depth=yDir.length();xDir.normalize(),yDir.normalize();const zDir=new THREE.Vector3(0,0,1),boxCenter=(new THREE.Vector3).add(p0).add(p1).add(p2).add(p3).multiplyScalar(.25).clone().addScaledVector(zDir,height/2),geometry=new THREE.BoxGeometry(width,depth,height),matrix2=new THREE.Matrix4;return matrix2.makeBasis(xDir,yDir,zDir),matrix2.setPosition(boxCenter),geometry.applyMatrix4(matrix2),geometry.computeVertexNormals(),geometry}}function Rr(t2,e,n=0,r2=t2.length-1,i=Mu){for(;r2>n;){if(r2-n>600){const f=r2-n+1,l=e-n+1,a2=Math.log(f),c=.5*Math.exp(2*a2/3),D2=.5*Math.sqrt(a2*c*(f-c)/f)*(l-f/2<0?-1:1);Rr(t2,e,Math.max(n,Math.floor(e-l*c/f+D2)),Math.min(r2,Math.floor(e+(f-l)*c/f+D2)),i)}const u2=t2[e];let o=n,s=r2;for(Xe(t2,n,e),i(t2[r2],u2)>0&&Xe(t2,n,r2);o<s;){for(Xe(t2,o,s),o++,s--;i(t2[o],u2)<0;)o++;for(;i(t2[s],u2)>0;)s--}0===i(t2[n],u2)?Xe(t2,n,s):(s++,Xe(t2,s,r2)),s<=e&&(n=s+1),e<=s&&(r2=s-1)}}function Xe(t2,e,n){const r2=t2[e];t2[e]=t2[n],t2[n]=r2}function Mu(t2,e){return t2<e?-1:t2>e?1:0}class Kn{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const r2=[];if(!tn(e,n))return r2;const i=this.toBBox,u2=[];for(;n;){for(let o=0;o<n.children.length;o++){const s=n.children[o],f=n.leaf?i(s):s;tn(e,f)&&(n.leaf?r2.push(s):xn(e,f)?this._all(s,r2):u2.push(s))}n=u2.pop()}return r2}collides(e){let n=this.data;if(!tn(e,n))return!1;const r2=[];for(;n;){for(let i=0;i<n.children.length;i++){const u2=n.children[i],o=n.leaf?this.toBBox(u2):u2;if(tn(e,o)){if(n.leaf||xn(e,o))return!0;r2.push(u2)}}n=r2.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let r2=0;r2<e.length;r2++)this.insert(e[r2]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const r2=this.data;this.data=n,n=r2}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=xe([]),this}remove(e,n){if(!e)return this;let r2=this.data;const i=this.toBBox(e),u2=[],o=[];let s,f,l;for(;r2||u2.length;){if(r2||(r2=u2.pop(),f=u2[u2.length-1],s=o.pop(),l=!0),r2.leaf){const a2=Nu(e,r2.children,n);if(-1!==a2)return r2.children.splice(a2,1),u2.push(r2),this._condense(u2),this}l||r2.leaf||!xn(r2,i)?f?(s++,r2=f.children[s],l=!1):r2=null:(u2.push(r2),o.push(s),s=0,f=r2,r2=r2.children[0])}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const r2=[];for(;e;)e.leaf?n.push(...e.children):r2.push(...e.children),e=r2.pop();return n}_build(e,n,r2,i){const u2=r2-n+1;let s,o=this._maxEntries;if(u2<=o)return s=xe(e.slice(n,r2+1)),Ae(s,this.toBBox),s;i||(i=Math.ceil(Math.log(u2)/Math.log(o)),o=Math.ceil(u2/Math.pow(o,i-1))),s=xe([]),s.leaf=!1,s.height=i;const f=Math.ceil(u2/o),l=f*Math.ceil(Math.sqrt(o));jn(e,n,r2,l,this.compareMinX);for(let a2=n;a2<=r2;a2+=l){const c=Math.min(a2+l-1,r2);jn(e,a2,c,f,this.compareMinY);for(let D2=a2;D2<=c;D2+=f){const w=Math.min(D2+f-1,c);s.children.push(this._build(e,D2,w,i-1))}}return Ae(s,this.toBBox),s}_chooseSubtree(e,n,r2,i){for(;i.push(n),!n.leaf&&i.length-1!==r2;){let s,u2=1/0,o=1/0;for(let f=0;f<n.children.length;f++){const l=n.children[f],a2=Nn(l),c=Tu(e,l)-a2;c<o?(o=c,u2=a2<u2?a2:u2,s=l):c===o&&a2<u2&&(u2=a2,s=l)}n=s||n.children[0]}return n}_insert(e,n,r2){const i=r2?e:this.toBBox(e),u2=[],o=this._chooseSubtree(i,this.data,n,u2);for(o.children.push(e),Ze(o,i);n>=0&&u2[n].children.length>this._maxEntries;)this._split(u2,n),n--;this._adjustParentBBoxes(i,u2,n)}_split(e,n){const r2=e[n],i=r2.children.length,u2=this._minEntries;this._chooseSplitAxis(r2,u2,i);const o=this._chooseSplitIndex(r2,u2,i),s=xe(r2.children.splice(o,r2.children.length-o));s.height=r2.height,s.leaf=r2.leaf,Ae(r2,this.toBBox),Ae(s,this.toBBox),n?e[n-1].children.push(s):this._splitRoot(r2,s)}_splitRoot(e,n){this.data=xe([e,n]),this.data.height=e.height+1,this.data.leaf=!1,Ae(this.data,this.toBBox)}_chooseSplitIndex(e,n,r2){let i,u2=1/0,o=1/0;for(let s=n;s<=r2-n;s++){const f=Le(e,0,s,this.toBBox),l=Le(e,s,r2,this.toBBox),a2=bu(f,l),c=Nn(f)+Nn(l);a2<u2?(u2=a2,i=s,o=c<o?c:o):a2===u2&&c<o&&(o=c,i=s)}return i||r2-n}_chooseSplitAxis(e,n,r2){const i=e.leaf?this.compareMinX:xu,u2=e.leaf?this.compareMinY:Su;this._allDistMargin(e,n,r2,i)<this._allDistMargin(e,n,r2,u2)&&e.children.sort(i)}_allDistMargin(e,n,r2,i){e.children.sort(i);const u2=this.toBBox,o=Le(e,0,n,u2),s=Le(e,r2-n,r2,u2);let f=je(o)+je(s);for(let l=n;l<r2-n;l++){const a2=e.children[l];Ze(o,e.leaf?u2(a2):a2),f+=je(o)}for(let l=r2-n-1;l>=n;l--){const a2=e.children[l];Ze(s,e.leaf?u2(a2):a2),f+=je(s)}return f}_adjustParentBBoxes(e,n,r2){for(let i=r2;i>=0;i--)Ze(n[i],e)}_condense(e){for(let r2,n=e.length-1;n>=0;n--)0===e[n].children.length?n>0?(r2=e[n-1].children,r2.splice(r2.indexOf(e[n]),1)):this.clear():Ae(e[n],this.toBBox)}}function Nu(t2,e,n){if(!n)return e.indexOf(t2);for(let r2=0;r2<e.length;r2++)if(n(t2,e[r2]))return r2;return-1}function Ae(t2,e){Le(t2,0,t2.children.length,e,t2)}function Le(t2,e,n,r2,i){i||(i=xe(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let u2=e;u2<n;u2++){const o=t2.children[u2];Ze(i,t2.leaf?r2(o):o)}return i}function Ze(t2,e){return t2.minX=Math.min(t2.minX,e.minX),t2.minY=Math.min(t2.minY,e.minY),t2.maxX=Math.max(t2.maxX,e.maxX),t2.maxY=Math.max(t2.maxY,e.maxY),t2}function xu(t2,e){return t2.minX-e.minX}function Su(t2,e){return t2.minY-e.minY}function Nn(t2){return(t2.maxX-t2.minX)*(t2.maxY-t2.minY)}function je(t2){return t2.maxX-t2.minX+(t2.maxY-t2.minY)}function Tu(t2,e){return(Math.max(e.maxX,t2.maxX)-Math.min(e.minX,t2.minX))*(Math.max(e.maxY,t2.maxY)-Math.min(e.minY,t2.minY))}function bu(t2,e){const n=Math.max(t2.minX,e.minX),r2=Math.max(t2.minY,e.minY),i=Math.min(t2.maxX,e.maxX),u2=Math.min(t2.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,u2-r2)}function xn(t2,e){return t2.minX<=e.minX&&t2.minY<=e.minY&&e.maxX<=t2.maxX&&e.maxY<=t2.maxY}function tn(t2,e){return e.minX<=t2.maxX&&e.minY<=t2.maxY&&e.maxX>=t2.minX&&e.maxY>=t2.minY}function xe(t2){return{children:t2,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function jn(t2,e,n,r2,i){const u2=[e,n];for(;u2.length;){if((n=u2.pop())-(e=u2.pop())<=r2)continue;const o=e+Math.ceil((n-e)/r2/2)*r2;Rr(t2,o,e,n,i),u2.push(e,o,o,n)}}class Iu{constructor(e=[],n=(r2,i)=>r2<i?-1:r2>i?1:0){if(this.data=e,this.length=this.data.length,this.compare=n,this.length>0)for(let r2=(this.length>>1)-1;r2>=0;r2--)this._down(r2)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],n=this.data.pop();return--this.length>0&&(this.data[0]=n,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:n,compare:r2}=this,i=n[e];for(;e>0;){const u2=e-1>>1,o=n[u2];if(r2(i,o)>=0)break;n[e]=o,e=u2}n[e]=i}_down(e){const{data:n,compare:r2}=this,i=this.length>>1,u2=n[e];for(;e<i;){let o=1+(e<<1);const s=o+1;if(s<this.length&&r2(n[s],n[o])<0&&(o=s),r2(n[o],u2)>=0)break;n[e]=n[o],e=o}n[e]=u2}}function qr(t2){return t2&&t2.__esModule&&Object.prototype.hasOwnProperty.call(t2,"default")?t2.default:t2}var Sn,tr,Tn,er,nr,$e={exports:{}};const qu=/* @__PURE__ */qr(function(){if(nr)return $e.exports;nr=1;var t2=(tr||(tr=1,Sn=function(e,n,r2,i){var u2=e[0],o=e[1],s=!1;void 0===r2&&(r2=0),void 0===i&&(i=n.length);for(var f=(i-r2)/2,l=0,a2=f-1;l<f;a2=l++){var c=n[r2+2*l+0],D2=n[r2+2*l+1],w=n[r2+2*a2+0],M=n[r2+2*a2+1];D2>o!=M>o&&u2<(w-c)*(o-D2)/(M-D2)+c&&(s=!s)}return s}),Sn),e=(er||(er=1,Tn=function(e,n,r2,i){var u2=e[0],o=e[1],s=!1;void 0===r2&&(r2=0),void 0===i&&(i=n.length);for(var f=i-r2,l=0,a2=f-1;l<f;a2=l++){var c=n[l+r2][0],D2=n[l+r2][1],w=n[a2+r2][0],M=n[a2+r2][1];D2>o!=M>o&&u2<(w-c)*(o-D2)/(M-D2)+c&&(s=!s)}return s}),Tn);return $e.exports=function(r2,i,u2,o){return i.length>0&&Array.isArray(i[0])?e(r2,i,u2,o):t2(r2,i,u2,o)},$e.exports.nested=e,$e.exports.flat=t2,$e.exports}()),ae=11102230246251565e-32,bt=134217729,Yu=(3+8*ae)*ae;function bn(t2,e,n,r2,i){let u2,o,s,f,l=e[0],a2=r2[0],c=0,D2=0;a2>l==a2>-l?(u2=l,l=e[++c]):(u2=a2,a2=r2[++D2]);let w=0;if(c<t2&&D2<n)for(a2>l==a2>-l?(o=l+u2,s=u2-(o-l),l=e[++c]):(o=a2+u2,s=u2-(o-a2),a2=r2[++D2]),u2=o,0!==s&&(i[w++]=s);c<t2&&D2<n;)a2>l==a2>-l?(o=u2+l,f=o-u2,s=u2-(o-f)+(l-f),l=e[++c]):(o=u2+a2,f=o-u2,s=u2-(o-f)+(a2-f),a2=r2[++D2]),u2=o,0!==s&&(i[w++]=s);for(;c<t2;)o=u2+l,f=o-u2,s=u2-(o-f)+(l-f),l=e[++c],u2=o,0!==s&&(i[w++]=s);for(;D2<n;)o=u2+a2,f=o-u2,s=u2-(o-f)+(a2-f),a2=r2[++D2],u2=o,0!==s&&(i[w++]=s);return(0!==u2||0===w)&&(i[w++]=u2),w}function Ge(t2){return new Float64Array(t2)}const Xu=(3+16*ae)*ae,$u=(2+12*ae)*ae,Lu=(9+64*ae)*ae*ae,Ce=Ge(4),rr=Ge(8),ir=Ge(12),ur=Ge(16),qt=Ge(4);function Wu(t2,e,n,r2,i,u2){const o=(e-u2)*(n-i),s=(t2-i)*(r2-u2),f=o-s,l=Math.abs(o+s);return Math.abs(f)>=Xu*l?f:-function(t2,e,n,r2,i,u2,o){let s,f,l,a2,c,D2,w,M,h2,g,p2,E,F,A,d2,m,C,y;const B2=t2-i,x=n-i,T=e-u2,q=r2-u2;A=B2*q,D2=bt*B2,w=D2-(D2-B2),M=B2-w,D2=bt*q,h2=D2-(D2-q),g=q-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=T*x,D2=bt*T,w=D2-(D2-T),M=T-w,D2=bt*x,h2=D2-(D2-x),g=x-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,Ce[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,Ce[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,Ce[2]=E-(y-c)+(p2-c),Ce[3]=y;let Z=function(t2,e){let n=e[0];for(let r2=1;r2<t2;r2++)n+=e[r2];return n}(4,Ce),W=$u*o;if(Z>=W||-Z>=W||(c=t2-B2,s=t2-(B2+c)+(c-i),c=n-x,l=n-(x+c)+(c-i),c=e-T,f=e-(T+c)+(c-u2),c=r2-q,a2=r2-(q+c)+(c-u2),0===s&&0===f&&0===l&&0===a2)||(W=Lu*o+Yu*Math.abs(Z),Z+=B2*a2+q*s-(T*l+x*f),Z>=W||-Z>=W))return Z;A=s*q,D2=bt*s,w=D2-(D2-s),M=s-w,D2=bt*q,h2=D2-(D2-q),g=q-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=f*x,D2=bt*f,w=D2-(D2-f),M=f-w,D2=bt*x,h2=D2-(D2-x),g=x-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const L=bn(4,Ce,4,qt,rr);A=B2*a2,D2=bt*B2,w=D2-(D2-B2),M=B2-w,D2=bt*a2,h2=D2-(D2-a2),g=a2-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=T*l,D2=bt*T,w=D2-(D2-T),M=T-w,D2=bt*l,h2=D2-(D2-l),g=l-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const z=bn(L,rr,4,qt,ir);A=s*a2,D2=bt*s,w=D2-(D2-s),M=s-w,D2=bt*a2,h2=D2-(D2-a2),g=a2-h2,d2=M*g-(A-w*h2-M*h2-w*g),m=f*l,D2=bt*f,w=D2-(D2-f),M=f-w,D2=bt*l,h2=D2-(D2-l),g=l-h2,C=M*g-(m-w*h2-M*h2-w*g),p2=d2-C,c=d2-p2,qt[0]=d2-(p2+c)+(c-C),E=A+p2,c=E-A,F=A-(E-c)+(p2-c),p2=F-m,c=F-p2,qt[1]=F-(p2+c)+(c-m),y=E+p2,c=y-E,qt[2]=E-(y-c)+(p2-c),qt[3]=y;const J=bn(z,ir,4,qt,ur);return ur[J-1]}(t2,e,n,r2,i,u2,l)}function Vu(t2,e,n){e=Math.max(0,void 0===e?2:e),n=n||0;const r2=function(t2){let e=t2[0],n=t2[0],r2=t2[0],i=t2[0];for(let s=0;s<t2.length;s++){const f=t2[s];f[0]<e[0]&&(e=f),f[0]>r2[0]&&(r2=f),f[1]<n[1]&&(n=f),f[1]>i[1]&&(i=f)}const u2=[e,n,r2,i],o=u2.slice();for(let s=0;s<t2.length;s++)qu(t2[s],u2)||o.push(t2[s]);return function(t2){t2.sort(Ku);const e=[];for(let r2=0;r2<t2.length;r2++){for(;e.length>=2&&Se(e[e.length-2],e[e.length-1],t2[r2])<=0;)e.pop();e.push(t2[r2])}const n=[];for(let r2=t2.length-1;r2>=0;r2--){for(;n.length>=2&&Se(n[n.length-2],n[n.length-1],t2[r2])<=0;)n.pop();n.push(t2[r2])}return n.pop(),e.pop(),e.concat(n)}(o)}(t2),i=new Kn(16);i.toBBox=function(D2){return{minX:D2[0],minY:D2[1],maxX:D2[0],maxY:D2[1]}},i.compareMinX=function(D2,w){return D2[0]-w[0]},i.compareMinY=function(D2,w){return D2[1]-w[1]},i.load(t2);const u2=[];let o;for(let D2=0;D2<r2.length;D2++){const w=r2[D2];i.remove(w),o=ar(w,o),u2.push(o)}const s=new Kn(16);for(let D2=0;D2<u2.length;D2++)s.insert(In(u2[D2]));const f=e*e,l=n*n;for(;u2.length;){const D2=u2.shift(),w=D2.p,M=D2.next.p,h2=On(w,M);if(h2<l)continue;const g=h2/f,p2=Hu(i,D2.prev.p,w,M,D2.next.next.p,g,s);p2&&Math.min(On(p2,w),On(p2,M))<=g&&(u2.push(D2),u2.push(ar(p2,D2)),i.remove(p2),s.remove(D2),s.insert(In(D2)),s.insert(In(D2.next)))}let a2=o;const c=[];do{c.push(a2.p),a2=a2.next}while(a2!==o);return c.push(a2.p),c}function Hu(t2,e,n,r2,i,u2,o){const s=new Iu([],Ju);let f=t2.data;for(;f;){for(let l=0;l<f.children.length;l++){const a2=f.children[l],c=f.leaf?Pn(a2,n,r2):ku(n,r2,a2);c>u2||s.push({node:a2,dist:c})}for(;s.length&&!s.peek().node.children;){const l=s.pop(),a2=l.node,c=Pn(a2,e,n),D2=Pn(a2,r2,i);if(l.dist<c&&l.dist<D2&&sr(n,a2,o)&&sr(r2,a2,o))return a2}f=s.pop(),f&&(f=f.node)}return null}function Ju(t2,e){return t2.dist-e.dist}function ku(t2,e,n){if(or(t2,n)||or(e,n))return 0;const r2=en(t2[0],t2[1],e[0],e[1],n.minX,n.minY,n.maxX,n.minY);if(0===r2)return 0;const i=en(t2[0],t2[1],e[0],e[1],n.minX,n.minY,n.minX,n.maxY);if(0===i)return 0;const u2=en(t2[0],t2[1],e[0],e[1],n.maxX,n.minY,n.maxX,n.maxY);if(0===u2)return 0;const o=en(t2[0],t2[1],e[0],e[1],n.minX,n.maxY,n.maxX,n.maxY);return 0===o?0:Math.min(r2,i,u2,o)}function or(t2,e){return t2[0]>=e.minX&&t2[0]<=e.maxX&&t2[1]>=e.minY&&t2[1]<=e.maxY}function sr(t2,e,n){const r2=Math.min(t2[0],e[0]),i=Math.min(t2[1],e[1]),u2=Math.max(t2[0],e[0]),o=Math.max(t2[1],e[1]),s=n.search({minX:r2,minY:i,maxX:u2,maxY:o});for(let f=0;f<s.length;f++)if(Gu(s[f].p,s[f].next.p,t2,e))return!1;return!0}function Se(t2,e,n){return Wu(t2[0],t2[1],e[0],e[1],n[0],n[1])}function Gu(t2,e,n,r2){return t2!==r2&&e!==n&&Se(t2,e,n)>0!=Se(t2,e,r2)>0&&Se(n,r2,t2)>0!=Se(n,r2,e)>0}function In(t2){const e=t2.p,n=t2.next.p;return t2.minX=Math.min(e[0],n[0]),t2.minY=Math.min(e[1],n[1]),t2.maxX=Math.max(e[0],n[0]),t2.maxY=Math.max(e[1],n[1]),t2}function ar(t2,e){const n={p:t2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return e?(n.next=e.next,n.prev=e,e.next.prev=n,e.next=n):(n.prev=n,n.next=n),n}function On(t2,e){const n=t2[0]-e[0],r2=t2[1]-e[1];return n*n+r2*r2}function Pn(t2,e,n){let r2=e[0],i=e[1],u2=n[0]-r2,o=n[1]-i;if(0!==u2||0!==o){const s=((t2[0]-r2)*u2+(t2[1]-i)*o)/(u2*u2+o*o);s>1?(r2=n[0],i=n[1]):s>0&&(r2+=u2*s,i+=o*s)}return u2=t2[0]-r2,o=t2[1]-i,u2*u2+o*o}function en(t2,e,n,r2,i,u2,o,s){const f=n-t2,l=r2-e,a2=o-i,c=s-u2,D2=t2-i,w=e-u2,M=f*f+l*l,h2=f*a2+l*c,g=a2*a2+c*c,p2=f*D2+l*w,E=a2*D2+c*w,F=M*g-h2*h2;let A,d2,m=F,C=F;0===F?(A=0,m=1,d2=E,C=g):(A=h2*E-g*p2,d2=M*E-h2*p2,A<0?(A=0,d2=E,C=g):A>m&&(A=m,d2=E+h2,C=g)),d2<0?(d2=0,-p2<0?A=0:-p2>M?A=m:(A=-p2,m=M)):d2>C&&(d2=C,-p2+h2<0?A=0:-p2+h2>M?A=m:(A=-p2+h2,m=M));const y=0===A?0:A/m,B2=0===d2?0:d2/C,W=(1-B2)*i+B2*o-((1-y)*t2+y*n),L=(1-B2)*u2+B2*s-((1-y)*e+y*r2);return W*W+L*L}function Ku(t2,e){return t2[0]===e[0]?t2[1]-e[1]:t2[0]-e[0]}function fn(){return fn=Object.assign?Object.assign.bind():function(t2){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r2 in n)({}).hasOwnProperty.call(n,r2)&&(t2[r2]=n[r2])}return t2},fn.apply(null,arguments)}var Yr={relTol:1e-12,absTol:1e-15,matrix:"Matrix",number:"number",numberFallback:"number",precision:64,predictable:!1,randomSeed:null};function to(t2,e){if(cn(t2,e))return t2[e];throw"function"==typeof t2[e]&&function(t2,e){return!(null==t2||"function"!=typeof t2[e]||kt(t2,e)&&Object.getPrototypeOf&&e in Object.getPrototypeOf(t2))&&(!!kt(uo,e)||!(e in Object.prototype||e in Function.prototype))}(t2,e)?new Error('Cannot access method "'+e+'" as a property'):new Error('No access to property "'+e+'"')}function cn(t2,e){return!(!function(t2){return"object"==typeof t2&&t2&&t2.constructor===Object}(t2)&&!Array.isArray(t2))&&(!!kt(io,e)||!(e in Object.prototype||e in Function.prototype))}var io={length:!0,name:!0},uo={toString:!0,valueOf:!0,toLocaleString:!0};class oo{constructor(e){this.wrappedObject=e,this[Symbol.iterator]=this.entries}keys(){return Object.keys(this.wrappedObject).filter(e=>this.has(e)).values()}get(e){return to(this.wrappedObject,e)}set(e,n){return function(t2,e,n){if(cn(t2,e))return t2[e]=n,n;throw new Error('No access to property "'+e+'"')}(this.wrappedObject,e,n),this}has(e){return cn(this.wrappedObject,e)&&e in this.wrappedObject}entries(){return t2=this.keys(),e=e=>[e,this.get(e)],{next:()=>{var n=t2.next();return n.done?n:{value:e(n.value),done:!1}}};var t2,e}forEach(e){for(var n of this.keys())e(this.get(n),n,this)}delete(e){cn(this.wrappedObject,e)&&delete this.wrappedObject[e]}clear(){for(var e of this.keys())this.delete(e)}get size(){return Object.keys(this.wrappedObject).length}}function lt(t2){return"number"==typeof t2}function Nt(t2){return!(!t2||"object"!=typeof t2||"function"!=typeof t2.constructor)&&(!0===t2.isBigNumber&&"object"==typeof t2.constructor.prototype&&!0===t2.constructor.prototype.isBigNumber||"function"==typeof t2.constructor.isDecimal&&!0===t2.constructor.isDecimal(t2))}function Ur(t2){return"bigint"==typeof t2}function gn(t2){return t2&&"object"==typeof t2&&!0===Object.getPrototypeOf(t2).isComplex||!1}function vn(t2){return t2&&"object"==typeof t2&&!0===Object.getPrototypeOf(t2).isFraction||!1}function Fn(t2){return t2&&!0===t2.constructor.prototype.isUnit||!1}function jt(t2){return"string"==typeof t2}var At=Array.isArray;function Mt(t2){return t2&&!0===t2.constructor.prototype.isMatrix||!1}function He(t2){return Array.isArray(t2)||Mt(t2)}function Xr(t2){return t2&&t2.isDenseMatrix&&!0===t2.constructor.prototype.isMatrix||!1}function $r(t2){return t2&&t2.isSparseMatrix&&!0===t2.constructor.prototype.isMatrix||!1}function Lr(t2){return t2&&!0===t2.constructor.prototype.isRange||!1}function wn(t2){return t2&&!0===t2.constructor.prototype.isIndex||!1}function Zr(t2){return"boolean"==typeof t2}function Wr(t2){return t2&&!0===t2.constructor.prototype.isResultSet||!1}function Vr(t2){return t2&&!0===t2.constructor.prototype.isHelp||!1}function Hr(t2){return"function"==typeof t2}function Jr(t2){return t2 instanceof Date}function kr(t2){return t2 instanceof RegExp}function qe(t2){return!(!t2||"object"!=typeof t2||t2.constructor!==Object||gn(t2)||vn(t2))}function Ie(t2){return!!t2&&(t2 instanceof Map||t2 instanceof oo||"function"==typeof t2.set&&"function"==typeof t2.get&&"function"==typeof t2.keys&&"function"==typeof t2.has)}function ao(t2){return Ie(t2)&&Ie(t2.a)&&Ie(t2.b)}function fo(t2){return Ie(t2)&&qe(t2.wrappedObject)}function Gr(t2){return null===t2}function Qr(t2){return void 0===t2}function Kr(t2){return t2&&!0===t2.isAccessorNode&&!0===t2.constructor.prototype.isNode||!1}function jr(t2){return t2&&!0===t2.isArrayNode&&!0===t2.constructor.prototype.isNode||!1}function ti(t2){return t2&&!0===t2.isAssignmentNode&&!0===t2.constructor.prototype.isNode||!1}function ei(t2){return t2&&!0===t2.isBlockNode&&!0===t2.constructor.prototype.isNode||!1}function ni(t2){return t2&&!0===t2.isConditionalNode&&!0===t2.constructor.prototype.isNode||!1}function ri(t2){return t2&&!0===t2.isConstantNode&&!0===t2.constructor.prototype.isNode||!1}function ii(t2){return t2&&!0===t2.isFunctionAssignmentNode&&!0===t2.constructor.prototype.isNode||!1}function ui(t2){return t2&&!0===t2.isFunctionNode&&!0===t2.constructor.prototype.isNode||!1}function oi(t2){return t2&&!0===t2.isIndexNode&&!0===t2.constructor.prototype.isNode||!1}function si(t2){return t2&&!0===t2.isNode&&!0===t2.constructor.prototype.isNode||!1}function ai(t2){return t2&&!0===t2.isObjectNode&&!0===t2.constructor.prototype.isNode||!1}function fi(t2){return t2&&!0===t2.isOperatorNode&&!0===t2.constructor.prototype.isNode||!1}function ci(t2){return t2&&!0===t2.isParenthesisNode&&!0===t2.constructor.prototype.isNode||!1}function li(t2){return t2&&!0===t2.isRangeNode&&!0===t2.constructor.prototype.isNode||!1}function hi(t2){return t2&&!0===t2.isRelationalNode&&!0===t2.constructor.prototype.isNode||!1}function Di(t2){return t2&&!0===t2.isSymbolNode&&!0===t2.constructor.prototype.isNode||!1}function pi(t2){return t2&&!0===t2.constructor.prototype.isChain||!1}function me(t2){var e=typeof t2;return"object"===e?null===t2?"null":Nt(t2)?"BigNumber":t2.constructor&&t2.constructor.name?t2.constructor.name:"Object":e}function Dt(t2){var e=typeof t2;if("number"===e||"bigint"===e||"string"===e||"boolean"===e||null==t2)return t2;if("function"==typeof t2.clone)return t2.clone();if(Array.isArray(t2))return t2.map(function(n){return Dt(n)});if(t2 instanceof Date)return new Date(t2.valueOf());if(Nt(t2))return t2;if(qe(t2))return function(t2,e){var n={};for(var r2 in t2)kt(t2,r2)&&(n[r2]=e(t2[r2]));return n}(t2,Dt);if("function"===e)return t2;throw new TypeError("Cannot clone: unknown type of value (value: ".concat(t2,")"))}function di(t2,e){if(Array.isArray(e))throw new TypeError("Arrays are not supported by deepExtend");for(var n in e)if(kt(e,n)&&!(n in Object.prototype)&&!(n in Function.prototype))if(e[n]&&e[n].constructor===Object)void 0===t2[n]&&(t2[n]={}),t2[n]&&t2[n].constructor===Object?di(t2[n],e[n]):t2[n]=e[n];else{if(Array.isArray(e[n]))throw new TypeError("Arrays are not supported by deepExtend");t2[n]=e[n]}return t2}function Pe(t2,e){var n,r2,i;if(Array.isArray(t2)){if(!Array.isArray(e)||t2.length!==e.length)return!1;for(r2=0,i=t2.length;r2<i;r2++)if(!Pe(t2[r2],e[r2]))return!1;return!0}if("function"==typeof t2)return t2===e;if(t2 instanceof Object){if(Array.isArray(e)||!(e instanceof Object))return!1;for(n in t2)if(!(n in e)||!Pe(t2[n],e[n]))return!1;for(n in e)if(!(n in t2))return!1;return!0}return t2===e}function lo(t2){var e={};return mi(t2,e),e}function mi(t2,e){for(var n in t2)if(kt(t2,n)){var r2=t2[n];"object"==typeof r2&&null!==r2?mi(r2,e):e[n]=r2}}function ye(t2,e,n){var i,r2=!0;Object.defineProperty(t2,e,{get:function(){return r2&&(i=n(),r2=!1),i},set:function(o){i=o,r2=!1},configurable:!0,enumerable:!0})}function kt(t2,e){return t2&&Object.hasOwnProperty.call(t2,e)}var fr=["Matrix","Array"],cr=["number","BigNumber","Fraction"];function po(t2,e){function n(r2){if(r2){if(void 0!==r2.epsilon){console.warn('Warning: The configuration option "epsilon" is deprecated. Use "relTol" and "absTol" instead.');var i=Dt(r2);return i.relTol=r2.epsilon,i.absTol=.001*r2.epsilon,delete i.epsilon,n(i)}var u2=Dt(t2);lr(r2,"matrix",fr),lr(r2,"number",cr),di(t2,r2);var o=Dt(t2),s=Dt(r2);return e("config",o,u2,s),o}return Dt(t2)}return n.MATRIX_OPTIONS=fr,n.NUMBER_OPTIONS=cr,Object.keys(Yr).forEach(r2=>{Object.defineProperty(n,r2,{get:()=>t2[r2],enumerable:!0,configurable:!0})}),n}function lr(t2,e,n){void 0!==t2[e]&&!n.includes(t2[e])&&console.warn('Warning: Unknown value "'+t2[e]+'" for configuration option "'+e+'". Available options: '+n.map(r2=>JSON.stringify(r2)).join(", ")+".")}function hr(){return!0}function Vt(){return!1}function Be(){}const Dr="Argument is not a typed-function.";const Je=function gi(){function t2(v2){return"object"==typeof v2&&null!==v2&&v2.constructor===Object}const e=[{name:"number",test:function(v2){return"number"==typeof v2}},{name:"string",test:function(v2){return"string"==typeof v2}},{name:"boolean",test:function(v2){return"boolean"==typeof v2}},{name:"Function",test:function(v2){return"function"==typeof v2}},{name:"Array",test:Array.isArray},{name:"Date",test:function(v2){return v2 instanceof Date}},{name:"RegExp",test:function(v2){return v2 instanceof RegExp}},{name:"Object",test:t2},{name:"null",test:function(v2){return null===v2}},{name:"undefined",test:function(v2){return void 0===v2}}],n={name:"any",test:hr,isAny:!0};let r2,i,u2=0,o={createCount:0};function s(v2){const _=r2.get(v2);if(_)return _;let N='Unknown type "'+v2+'"';const b4=v2.toLowerCase();let P;for(P of i)if(P.toLowerCase()===b4){N+='. Did you mean "'+P+'" ?';break}throw new TypeError(N)}function f(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"any";const N=_?s(_).index:i.length,b4=[];for(let I=0;I<v2.length;++I){if(!v2[I]||"string"!=typeof v2[I].name||"function"!=typeof v2[I].test)throw new TypeError("Object with properties {name: string, test: function} expected");const X=v2[I].name;if(r2.has(X))throw new TypeError('Duplicate type name "'+X+'"');b4.push(X),r2.set(X,{name:X,test:v2[I].test,isAny:v2[I].isAny,index:N+I,conversionsTo:[]})}const P=i.slice(N);i=i.slice(0,N).concat(b4).concat(P);for(let I=N+b4.length;I<i.length;++I)r2.get(i[I]).index=I}function l(){r2=/* @__PURE__ */new Map,i=[],u2=0,f([n],!1)}function c(v2){const _=i.filter(N=>{const b4=r2.get(N);return!b4.isAny&&b4.test(v2)});return _.length?_:["any"]}function D2(v2){return v2&&"function"==typeof v2&&"_typedFunctionData"in v2}function w(v2,_,N){if(!D2(v2))throw new TypeError(Dr);const b4=N&&N.exact,I=A(Array.isArray(_)?_.join(","):_),X=g(I);if(!b4||X in v2.signatures){const ut=v2._typedFunctionData.signatureMap.get(X);if(ut)return ut}const Y=I.length;let $,R2;if(b4){let ut;for(ut in $=[],v2.signatures)$.push(v2._typedFunctionData.signatureMap.get(ut))}else $=v2._typedFunctionData.signatures;for(let ut=0;ut<Y;++ut){const ct=I[ut],Et=[];let Yt;for(Yt of $){const Rt=y(Yt.params,ut);if(Rt&&(!ct.restParam||Rt.restParam)){if(!Rt.hasAny){const Gt=F(Rt);if(ct.types.some(Qt=>!Gt.has(Qt.name)))continue}Et.push(Yt)}}if($=Et,0===$.length)break}for(R2 of $)if(R2.params.length<=Y)return R2;throw new TypeError("Signature not found (signature: "+(v2.name||"unnamed")+"("+g(I,", ")+"))")}function g(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:",";return v2.map(N=>N.name).join(_)}function p2(v2){const _=0===v2.indexOf("..."),b4=(_?v2.length>3?v2.slice(3):"any":v2).split("|").map(Y=>s(Y.trim()));let P=!1,I=_?"...":"";return{types:b4.map(function(Y){return P=Y.isAny||P,I+=Y.name+"|",{name:Y.name,typeIndex:Y.index,test:Y.test,isAny:Y.isAny,conversion:null,conversionIndex:-1}}),name:I.slice(0,-1),hasAny:P,hasConversion:!1,restParam:_}}function E(v2){const N=function(v2){if(0===v2.length)return[];const _=v2.map(s);v2.length>1&&_.sort((P,I)=>P.index-I.index);let N=_[0].conversionsTo;if(1===v2.length)return N;N=N.concat([]);const b4=new Set(v2);for(let P=1;P<_.length;++P){let I;for(I of _[P].conversionsTo)b4.has(I.from)||(N.push(I),b4.add(I.from))}return N}(v2.types.map(X=>X.name));let b4=v2.hasAny,P=v2.name;const I=N.map(function(X){const Y=s(X.from);return b4=Y.isAny||b4,P+="|"+X.from,{name:X.from,typeIndex:Y.index,test:Y.test,isAny:Y.isAny,conversion:X,conversionIndex:X.index}});return{types:v2.types.concat(I),name:P,hasAny:b4,hasConversion:I.length>0,restParam:v2.restParam}}function F(v2){return v2.typeSet||(v2.typeSet=/* @__PURE__ */new Set,v2.types.forEach(_=>v2.typeSet.add(_.name))),v2.typeSet}function A(v2){const _=[];if("string"!=typeof v2)throw new TypeError("Signatures must be strings");const N=v2.trim();if(""===N)return _;const b4=N.split(",");for(let P=0;P<b4.length;++P){const I=p2(b4[P].trim());if(I.restParam&&P!==b4.length-1)throw new SyntaxError('Unexpected rest parameter "'+b4[P]+'": only allowed for the last parameter');if(0===I.types.length)return null;_.push(I)}return _}function d2(v2){const _=st(v2);return!!_&&_.restParam}function m(v2){if(!v2||0===v2.types.length)return hr;if(1===v2.types.length)return s(v2.types[0].name).test;if(2===v2.types.length){const _=s(v2.types[0].name).test,N=s(v2.types[1].name).test;return function(P){return _(P)||N(P)}}{const _=v2.types.map(function(N){return s(N.name).test});return function(b4){for(let P=0;P<_.length;P++)if(_[P](b4))return!0;return!1}}}function C(v2){let _,N,b4;if(d2(v2)){_=zt(v2).map(m);const P=_.length,I=m(st(v2)),X=function(Y){for(let $=P;$<Y.length;$++)if(!I(Y[$]))return!1;return!0};return function($){for(let R2=0;R2<_.length;R2++)if(!_[R2]($[R2]))return!1;return X($)&&$.length>=P+1}}return 0===v2.length?function(I){return 0===I.length}:1===v2.length?(N=m(v2[0]),function(I){return N(I[0])&&1===I.length}):2===v2.length?(N=m(v2[0]),b4=m(v2[1]),function(I){return N(I[0])&&b4(I[1])&&2===I.length}):(_=v2.map(m),function(I){for(let X=0;X<_.length;X++)if(!_[X](I[X]))return!1;return I.length===_.length})}function y(v2,_){return _<v2.length?v2[_]:d2(v2)?st(v2):null}function B2(v2,_){const N=y(v2,_);return N?F(N):/* @__PURE__ */new Set}function x(v2){return null===v2.conversion||void 0===v2.conversion}function T(v2,_){const N=/* @__PURE__ */new Set;return v2.forEach(b4=>{const P=B2(b4.params,_);let I;for(I of P)N.add(I)}),N.has("any")?["any"]:Array.from(N)}function q(v2,_,N){let b4,P;const I=v2||"unnamed";let Y,X=N;for(Y=0;Y<_.length;Y++){const ct=[];if(X.forEach(Et=>{const Rt=m(y(Et.params,Y));(Y<Et.params.length||d2(Et.params))&&Rt(_[Y])&&ct.push(Et)}),0===ct.length){if(P=T(X,Y),P.length>0){const Et=c(_[Y]);return b4=new TypeError("Unexpected type of argument in function "+I+" (expected: "+P.join(" or ")+", actual: "+Et.join(" | ")+", index: "+Y+")"),b4.data={category:"wrongType",fn:I,index:Y,actual:Et,expected:P},b4}}else X=ct}const $=X.map(function(ct){return d2(ct.params)?1/0:ct.params.length});if(_.length<Math.min.apply(null,$))return P=T(X,Y),b4=new TypeError("Too few arguments in function "+I+" (expected: "+P.join(" or ")+", index: "+_.length+")"),b4.data={category:"tooFewArgs",fn:I,index:_.length,expected:P},b4;const R2=Math.max.apply(null,$);if(_.length>R2)return b4=new TypeError("Too many arguments in function "+I+" (expected: "+R2+", actual: "+_.length+")"),b4.data={category:"tooManyArgs",fn:I,index:_.length,expectedLength:R2},b4;const ut=[];for(let ct=0;ct<_.length;++ct)ut.push(c(_[ct]).join("|"));return b4=new TypeError('Arguments of type "'+ut.join(", ")+'" do not match any of the defined signatures of function '+I+"."),b4.data={category:"mismatch",actual:ut},b4}function Z(v2){let _=i.length+1;for(let N=0;N<v2.types.length;N++)x(v2.types[N])&&(_=Math.min(_,v2.types[N].typeIndex));return _}function W(v2){let _=u2+1;for(let N=0;N<v2.types.length;N++)x(v2.types[N])||(_=Math.min(_,v2.types[N].conversionIndex));return _}function L(v2,_){if(v2.hasAny){if(!_.hasAny)return 1}else if(_.hasAny)return-1;if(v2.restParam){if(!_.restParam)return 1}else if(_.restParam)return-1;if(v2.hasConversion){if(!_.hasConversion)return 1}else if(_.hasConversion)return-1;const N=Z(v2)-Z(_);if(N<0)return-1;if(N>0)return 1;const b4=W(v2)-W(_);return b4<0?-1:b4>0?1:0}function z(v2,_){const N=v2.params,b4=_.params,P=st(N),I=st(b4),X=d2(N),Y=d2(b4);if(X&&P.hasAny){if(!Y||!I.hasAny)return 1}else if(Y&&I.hasAny)return-1;let ut,$=0,R2=0;for(ut of N)ut.hasAny&&++$,ut.hasConversion&&++R2;let ct=0,Et=0;for(ut of b4)ut.hasAny&&++ct,ut.hasConversion&&++Et;if($!==ct)return $-ct;if(X&&P.hasConversion){if(!Y||!I.hasConversion)return 1}else if(Y&&I.hasConversion)return-1;if(R2!==Et)return R2-Et;if(X){if(!Y)return 1}else if(Y)return-1;const Yt=(N.length-b4.length)*(X?-1:1);if(0!==Yt)return Yt;const Rt=[];let Qt,Gt=0;for(let Ee=0;Ee<N.length;++Ee){const Qe=L(N[Ee],b4[Ee]);Rt.push(Qe),Gt+=Qe}if(0!==Gt)return Gt;for(Qt of Rt)if(0!==Qt)return Qt;return 0}function k(v2,_){let N=_;if(v2.some(P=>P.hasConversion)){const P=d2(v2),I=v2.map(G);N=function(){const Y=[],$=P?arguments.length-1:arguments.length;for(let R2=0;R2<$;R2++)Y[R2]=I[R2](arguments[R2]);return P&&(Y[$]=arguments[$].map(I[$])),_.apply(this,Y)}}let b4=N;if(d2(v2)){const P=v2.length-1;b4=function(){return N.apply(this,it(arguments,0,P).concat([it(arguments,P)]))}}return b4}function G(v2){let _,N,b4,P;const I=[],X=[];switch(v2.types.forEach(function(Y){Y.conversion&&(I.push(s(Y.conversion.from).test),X.push(Y.conversion.convert))}),X.length){case 0:return function($){return $};case 1:return _=I[0],b4=X[0],function($){return _($)?b4($):$};case 2:return _=I[0],N=I[1],b4=X[0],P=X[1],function($){return _($)?b4($):N($)?P($):$};default:return function($){for(let R2=0;R2<X.length;R2++)if(I[R2]($))return X[R2]($);return $}}}function j(v2){return function _(N,b4,P){if(b4<N.length){const I=N[b4];let X=[];if(I.restParam){const Y=I.types.filter(x);Y.length<I.types.length&&X.push({types:Y,name:"..."+Y.map($=>$.name).join("|"),hasAny:Y.some($=>$.isAny),hasConversion:!1,restParam:!0}),X.push(I)}else X=I.types.map(function(Y){return{types:[Y],name:Y.name,hasAny:Y.isAny,hasConversion:Y.conversion,restParam:!1}});return function(v2,_){return Array.prototype.concat.apply([],v2.map(_))}(X,function(Y){return _(N,b4+1,P.concat([Y]))})}return[P]}(v2,0,[])}function rt(v2,_){const N=Math.max(v2.length,_.length);for(let Y=0;Y<N;Y++){const $=B2(v2,Y),R2=B2(_,Y);let ct,ut=!1;for(ct of R2)if($.has(ct)){ut=!0;break}if(!ut)return!1}const b4=v2.length,P=_.length,I=d2(v2),X=d2(_);return I?X?b4===P:P>=b4:X?b4>=P:b4===P}function ot(v2,_,N){const b4=[];let P;for(P of v2){let I=N[P];if("number"!=typeof I)throw new TypeError('No definition for referenced signature "'+P+'"');if(I=_[I],"function"!=typeof I)return!1;b4.push(I)}return b4}function wt(v2,_,N){const b4=function(v2){return v2.map(_=>ue(_)?Wt(_.referToSelf.callback):ie(_)?yt(_.referTo.references,_.referTo.callback):_)}(v2),P=new Array(b4.length).fill(!1);let I=!0;for(;I;){I=!1;let X=!0;for(let Y=0;Y<b4.length;++Y){if(P[Y])continue;const $=b4[Y];if(ue($))b4[Y]=$.referToSelf.callback(N),b4[Y].referToSelf=$.referToSelf,P[Y]=!0,X=!1;else if(ie($)){const R2=ot($.referTo.references,b4,_);R2?(b4[Y]=$.referTo.callback.apply(this,R2),b4[Y].referTo=$.referTo,P[Y]=!0,X=!1):I=!0}}if(X&&I)throw new SyntaxError("Circular reference detected in resolving typed.referTo")}return b4}function mt(v2,_){if(o.createCount++,0===Object.keys(_).length)throw new SyntaxError("No signatures provided");o.warnAgainstDeprecatedThis&&function(v2){const _=/\bthis(\(|\.signatures\b)/;Object.keys(v2).forEach(N=>{const b4=v2[N];if(_.test(b4.toString()))throw new SyntaxError("Using `this` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead.")})}(_);const N=[],b4=[],P={},I=[];let X;for(X in _){if(!Object.prototype.hasOwnProperty.call(_,X))continue;const nt=A(X);if(!nt)continue;N.forEach(function(Ue){if(rt(Ue,nt))throw new TypeError('Conflicting signatures "'+g(Ue)+'" and "'+g(nt)+'".')}),N.push(nt);const Ut=b4.length;b4.push(_[X]);const Bu=nt.map(E);let Ke;for(Ke of j(Bu)){const Ue=g(Ke);I.push({params:Ke,name:Ue,fn:Ut}),Ke.every(_u=>!_u.hasConversion)&&(P[Ue]=Ut)}}I.sort(z);const Y=wt(b4,P,Ye);let $;for($ in P)Object.prototype.hasOwnProperty.call(P,$)&&(P[$]=Y[P[$]]);const R2=[],ut=/* @__PURE__ */new Map;for($ of I)ut.has($.name)||($.fn=Y[$.fn],R2.push($),ut.set($.name,$));const ct=R2[0]&&R2[0].params.length<=2&&!d2(R2[0].params),Et=R2[1]&&R2[1].params.length<=2&&!d2(R2[1].params),Yt=R2[2]&&R2[2].params.length<=2&&!d2(R2[2].params),Rt=R2[3]&&R2[3].params.length<=2&&!d2(R2[3].params),Gt=R2[4]&&R2[4].params.length<=2&&!d2(R2[4].params),Qt=R2[5]&&R2[5].params.length<=2&&!d2(R2[5].params),Ee=ct&&Et&&Yt&&Rt&&Gt&&Qt;for(let nt=0;nt<R2.length;++nt)R2[nt].test=C(R2[nt].params);const Qe=ct?m(R2[0].params[0]):Vt,Qi=Et?m(R2[1].params[0]):Vt,Ki=Yt?m(R2[2].params[0]):Vt,ji=Rt?m(R2[3].params[0]):Vt,tu=Gt?m(R2[4].params[0]):Vt,eu=Qt?m(R2[5].params[0]):Vt,nu=ct?m(R2[0].params[1]):Vt,ru=Et?m(R2[1].params[1]):Vt,iu=Yt?m(R2[2].params[1]):Vt,uu=Rt?m(R2[3].params[1]):Vt,ou=Gt?m(R2[4].params[1]):Vt,su=Qt?m(R2[5].params[1]):Vt;for(let nt=0;nt<R2.length;++nt)R2[nt].implementation=k(R2[nt].params,R2[nt].fn);const au=ct?R2[0].implementation:Be,fu=Et?R2[1].implementation:Be,cu=Yt?R2[2].implementation:Be,lu=Rt?R2[3].implementation:Be,hu=Gt?R2[4].implementation:Be,Du=Qt?R2[5].implementation:Be,pu=ct?R2[0].params.length:-1,du=Et?R2[1].params.length:-1,mu=Yt?R2[2].params.length:-1,gu=Rt?R2[3].params.length:-1,vu=Gt?R2[4].params.length:-1,Fu=Qt?R2[5].params.length:-1,wu=Ee?6:0,Eu=R2.length,Au=R2.map(nt=>nt.test),Cu=R2.map(nt=>nt.implementation),yu=function(){for(let Ut=wu;Ut<Eu;Ut++)if(Au[Ut](arguments))return Cu[Ut].apply(this,arguments);return o.onMismatch(v2,arguments,R2)};function Ye(nt,Ut){return arguments.length===pu&&Qe(nt)&&nu(Ut)?au.apply(this,arguments):arguments.length===du&&Qi(nt)&&ru(Ut)?fu.apply(this,arguments):arguments.length===mu&&Ki(nt)&&iu(Ut)?cu.apply(this,arguments):arguments.length===gu&&ji(nt)&&uu(Ut)?lu.apply(this,arguments):arguments.length===vu&&tu(nt)&&ou(Ut)?hu.apply(this,arguments):arguments.length===Fu&&eu(nt)&&su(Ut)?Du.apply(this,arguments):yu.apply(this,arguments)}try{Object.defineProperty(Ye,"name",{value:v2})}catch{}return Ye.signatures=P,Ye._typedFunctionData={signatures:R2,signatureMap:ut},Ye}function ht(v2,_,N){throw q(v2,_,N)}function zt(v2){return it(v2,0,v2.length-1)}function st(v2){return v2[v2.length-1]}function it(v2,_,N){return Array.prototype.slice.call(v2,_,N)}function yt(v2,_){return{referTo:{references:v2,callback:_}}}function Wt(v2){if("function"!=typeof v2)throw new TypeError("Callback function expected as first argument");return{referToSelf:{callback:v2}}}function ie(v2){return v2&&"object"==typeof v2.referTo&&Array.isArray(v2.referTo.references)&&"function"==typeof v2.referTo.callback}function ue(v2){return v2&&"object"==typeof v2.referToSelf&&"function"==typeof v2.referToSelf.callback}function Fe(v2,_){if(!v2)return _;if(_&&_!==v2){const N=new Error("Function names do not match (expected: "+v2+", actual: "+_+")");throw N.data={actual:_,expected:v2},N}return v2}function we(v2){let _;for(const N in v2)Object.prototype.hasOwnProperty.call(v2,N)&&(D2(v2[N])||"string"==typeof v2[N].signature)&&(_=Fe(_,v2[N].name));return _}function Mn(v2,_){let N;for(N in _)if(Object.prototype.hasOwnProperty.call(_,N)){if(N in v2&&_[N]!==v2[N]){const b4=new Error('Signature "'+N+'" is defined twice');throw b4.data={signature:N,sourceFunction:_[N],destFunction:v2[N]},b4}v2[N]=_[N]}}l(),f(e);const Gi=o;function Qn(v2){if(!v2||"string"!=typeof v2.from||"string"!=typeof v2.to||"function"!=typeof v2.convert)throw new TypeError("Object with properties {from: string, to: string, convert: function} expected");if(v2.to===v2.from)throw new SyntaxError('Illegal to define conversion from "'+v2.from+'" to itself.')}return o=function(v2){const _="string"==typeof v2;let b4=_?v2:"";const P={};for(let I=_?1:0;I<arguments.length;++I){const X=arguments[I];let $,Y={};if("function"==typeof X?($=X.name,"string"==typeof X.signature?Y[X.signature]=X:D2(X)&&(Y=X.signatures)):t2(X)&&(Y=X,_||($=we(X))),0===Object.keys(Y).length){const R2=new TypeError("Argument to 'typed' at index "+I+" is not a (typed) function, nor an object with signatures as keys and functions as values.");throw R2.data={index:I,argument:X},R2}_||(b4=Fe(b4,$)),Mn(P,Y)}return mt(b4||"",P)},o.create=gi,o.createCount=Gi.createCount,o.onMismatch=ht,o.throwMismatchError=ht,o.createError=q,o.clear=l,o.clearConversions=function(){let v2;for(v2 of i)r2.get(v2).conversionsTo=[];u2=0},o.addTypes=f,o._findType=s,o.referTo=function(){const v2=zt(arguments).map(N=>g(A(N))),_=st(arguments);if("function"!=typeof _)throw new TypeError("Callback function expected as last argument");return yt(v2,_)},o.referToSelf=Wt,o.convert=function(v2,_){const N=s(_);if(N.test(v2))return v2;const b4=N.conversionsTo;if(0===b4.length)throw new Error("There are no conversions to "+_+" defined.");for(let P=0;P<b4.length;P++)if(s(b4[P].from).test(v2))return b4[P].convert(v2);throw new Error("Cannot convert "+v2+" to "+_)},o.findSignature=w,o.find=function(v2,_,N){return w(v2,_,N).implementation},o.isTypedFunction=D2,o.warnAgainstDeprecatedThis=!0,o.addType=function(v2,_){let N="any";!1!==_&&r2.has("Object")&&(N="Object"),o.addTypes([v2],N)},o.addConversion=function(v2){let _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{override:!1};Qn(v2);const N=s(v2.to),b4=N.conversionsTo.find(P=>P.from===v2.from);if(b4){if(!_||!_.override)throw new Error('There is already a conversion from "'+v2.from+'" to "'+N.name+'"');o.removeConversion({from:b4.from,to:v2.to,convert:b4.convert})}N.conversionsTo.push({from:v2.from,convert:v2.convert,index:u2++})},o.addConversions=function(v2,_){v2.forEach(N=>o.addConversion(N,_))},o.removeConversion=function(v2){Qn(v2);const _=s(v2.to),N=function(v2,_){for(let N=0;N<v2.length;N++)if(_(v2[N]))return v2[N]}(_.conversionsTo,P=>P.from===v2.from);if(!N)throw new Error("Attempt to remove nonexistent conversion from "+v2.from+" to "+v2.to);if(N.convert!==v2.convert)throw new Error("Conversion to remove does not match existing conversion");const b4=_.conversionsTo.indexOf(N);_.conversionsTo.splice(b4,1)},o.resolve=function(v2,_){if(!D2(v2))throw new TypeError(Dr);const N=v2._typedFunctionData.signatures;for(let b4=0;b4<N.length;++b4)if(N[b4].test(_))return N[b4];return null},o}();function Ft(t2,e,n,r2){function i(u2){var o=function(t2,e){for(var n={},r2=0;r2<e.length;r2++){var i=e[r2],u2=t2[i];void 0!==u2&&(n[i]=u2)}return n}(u2,e.map(vi));return function(t2,e,n){var r2=e.filter(u2=>!function(t2){return t2&&"?"===t2[0]}(u2)).every(u2=>void 0!==n[u2]);if(!r2){var i=e.filter(u2=>void 0===n[u2]);throw new Error('Cannot create function "'.concat(t2,'", ')+"some dependencies are missing: ".concat(i.map(u2=>'"'.concat(u2,'"')).join(", "),"."))}}(t2,e,u2),n(o)}return i.isFactory=!0,i.fn=t2,i.dependencies=e.slice().sort(),r2&&(i.meta=r2),i}function We(t2){return"function"==typeof t2&&"string"==typeof t2.fn&&Array.isArray(t2.dependencies)}function vi(t2){return t2&&"?"===t2[0]?t2.slice(1):t2}function St(t2){return"boolean"==typeof t2||!!isFinite(t2)&&t2===Math.round(t2)}function zn(t2,e,n){var i={2:"0b",8:"0o",16:"0x"}[e],u2="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!St(n))throw new Error("size must be an integer");if(t2>2**(n-1)-1||t2<-(2**(n-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!St(t2))throw new Error("Value must be an integer");t2<0&&(t2+=2**n),u2="i".concat(n)}var o="";return t2<0&&(t2=-t2,o="-"),"".concat(o).concat(i).concat(t2.toString(e)).concat(u2)}function Un(t2,e){if("function"==typeof e)return e(t2);if(t2===1/0)return"Infinity";if(t2===-1/0)return"-Infinity";if(isNaN(t2))return"NaN";var{notation:n,precision:r2,wordSize:i}=Fi(e);switch(n){case"fixed":return function(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2="number"==typeof e?An(n,n.exponent+1+e):n,i=r2.coefficients,u2=r2.exponent+1,o=u2+(e||0);return i.length<o&&(i=i.concat(Oe(o-i.length))),u2<0&&(i=Oe(1-u2).concat(i),u2=1),u2<i.length&&i.splice(u2,0,0===u2?"0.":"."),r2.sign+i.join("")}(t2,r2);case"exponential":return wi(t2,r2);case"engineering":return function(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2=An(n,e),i=r2.exponent,u2=r2.coefficients,o=i%3==0?i:i<0?i-3-i%3:i-i%3;if(lt(e))for(;e>u2.length||i-o+1>u2.length;)u2.push(0);else for(var s=Math.abs(i-o)-(u2.length-1),f=0;f<s;f++)u2.push(0);for(var l=Math.abs(i-o),a2=1;l>0;)a2++,l--;var c=u2.slice(a2).join(""),D2=lt(e)&&c.length||c.match(/[1-9]/)?"."+c:"",w=u2.slice(0,a2).join("")+D2+"e"+(i>=0?"+":"")+o.toString();return r2.sign+w}(t2,r2);case"bin":return zn(t2,2,i);case"oct":return zn(t2,8,i);case"hex":return zn(t2,16,i);case"auto":return function(t2,e,n){if(isNaN(t2)||!isFinite(t2))return String(t2);var r2=dr(n?.lowerExp,-3),i=dr(n?.upperExp,5),u2=En(t2),o=e?An(u2,e):u2;if(o.exponent<r2||o.exponent>=i)return wi(t2,e);var s=o.coefficients,f=o.exponent;s.length<e&&(s=s.concat(Oe(e-s.length))),s=s.concat(Oe(f-s.length+1+(s.length<e?e-s.length:0))),s=Oe(-f).concat(s);var l=f>0?f:0;return l<s.length-1&&s.splice(l+1,0,"."),o.sign+s.join("")}(t2,r2,e).replace(/((\.\d*?)(0+))($|e)/,function(){var u2=arguments[2],o=arguments[4];return"."!==u2?u2+o:o});default:throw new Error('Unknown notation "'+n+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function Fi(t2){var n,r2,e="auto";if(void 0!==t2)if(lt(t2))n=t2;else if(Nt(t2))n=t2.toNumber();else{if(!qe(t2))throw new Error("Unsupported type of options, number, BigNumber, or object expected");void 0!==t2.precision&&(n=pr(t2.precision,()=>{throw new Error('Option "precision" must be a number or BigNumber')})),void 0!==t2.wordSize&&(r2=pr(t2.wordSize,()=>{throw new Error('Option "wordSize" must be a number or BigNumber')})),t2.notation&&(e=t2.notation)}return{notation:e,precision:n,wordSize:r2}}function En(t2){var e=String(t2).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);if(!e)throw new SyntaxError("Invalid number "+t2);var n=e[1],r2=e[2],i=parseFloat(e[4]||"0"),u2=r2.indexOf(".");i+=-1!==u2?u2-1:r2.length-1;var o=r2.replace(".","").replace(/^0*/,function(s){return i-=s.length,""}).replace(/0*$/,"").split("").map(function(s){return parseInt(s)});return 0===o.length&&(o.push(0),i++),{sign:n,coefficients:o,exponent:i}}function wi(t2,e){if(isNaN(t2)||!isFinite(t2))return String(t2);var n=En(t2),r2=e?An(n,e):n,i=r2.coefficients,u2=r2.exponent;i.length<e&&(i=i.concat(Oe(e-i.length)));var o=i.shift();return r2.sign+o+(i.length>0?"."+i.join(""):"")+"e"+(u2>=0?"+":"")+u2}function An(t2,e){for(var n={sign:t2.sign,coefficients:t2.coefficients,exponent:t2.exponent},r2=n.coefficients;e<=0;)r2.unshift(0),n.exponent++,e++;if(r2.length>e&&r2.splice(e,r2.length-e)[0]>=5){var u2=e-1;for(r2[u2]++;10===r2[u2];)r2.pop(),0===u2&&(r2.unshift(0),n.exponent++,u2++),r2[--u2]++}return n}function Oe(t2){for(var e=[],n=0;n<t2;n++)e.push(0);return e}function ln(t2,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e-8,r2=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n<=0)throw new Error("Relative tolerance must be greater than 0");if(r2<0)throw new Error("Absolute tolerance must be at least 0");return!isNaN(t2)&&!isNaN(e)&&(isFinite(t2)&&isFinite(e)?t2===e||Math.abs(t2-e)<=Math.max(n*Math.max(Math.abs(t2),Math.abs(e)),r2):t2===e)}function pr(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():void e()}function dr(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():e}var Ei=function(){return Ei=Je.create,Je},Co=/* @__PURE__ */Ft("typed",["?BigNumber","?Complex","?DenseMatrix","?Fraction"],function(e){var{BigNumber:n,Complex:r2,DenseMatrix:i,Fraction:u2}=e,o=Ei();return o.clear(),o.addTypes([{name:"number",test:lt},{name:"Complex",test:gn},{name:"BigNumber",test:Nt},{name:"bigint",test:Ur},{name:"Fraction",test:vn},{name:"Unit",test:Fn},{name:"identifier",test:s=>jt&&/^(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC4\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDDC0-\uDDF3\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDD4A-\uDD65\uDD6F-\uDD85\uDE80-\uDEA9\uDEB0\uDEB1\uDEC2-\uDEC4\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61\uDF80-\uDF89\uDF8B\uDF8E\uDF90-\uDFB5\uDFB7\uDFD1\uDFD3]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8\uDFC0-\uDFE0]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD80E\uD80F\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46\uDC60-\uDFFF]|\uD810[\uDC00-\uDFFA]|\uD811[\uDC00-\uDE46]|\uD818[\uDD00-\uDD1D]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDD40-\uDD6C\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDDD0-\uDDED\uDDF0\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])*$/.test(s)},{name:"string",test:jt},{name:"Chain",test:pi},{name:"Array",test:At},{name:"Matrix",test:Mt},{name:"DenseMatrix",test:Xr},{name:"SparseMatrix",test:$r},{name:"Range",test:Lr},{name:"Index",test:wn},{name:"boolean",test:Zr},{name:"ResultSet",test:Wr},{name:"Help",test:Vr},{name:"function",test:Hr},{name:"Date",test:Jr},{name:"RegExp",test:kr},{name:"null",test:Gr},{name:"undefined",test:Qr},{name:"AccessorNode",test:Kr},{name:"ArrayNode",test:jr},{name:"AssignmentNode",test:ti},{name:"BlockNode",test:ei},{name:"ConditionalNode",test:ni},{name:"ConstantNode",test:ri},{name:"FunctionNode",test:ui},{name:"FunctionAssignmentNode",test:ii},{name:"IndexNode",test:oi},{name:"Node",test:si},{name:"ObjectNode",test:ai},{name:"OperatorNode",test:fi},{name:"ParenthesisNode",test:ci},{name:"RangeNode",test:li},{name:"RelationalNode",test:hi},{name:"SymbolNode",test:Di},{name:"Map",test:Ie},{name:"Object",test:qe}]),o.addConversions([{from:"number",to:"BigNumber",convert:function(f){if(n||nn(f),f.toExponential().replace(/e.*$/,"").replace(/^0\.?0*|\./,"").length>15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+f+"). Use function bignumber(x) to convert to BigNumber.");return new n(f)}},{from:"number",to:"Complex",convert:function(f){return r2||rn(f),new r2(f,0)}},{from:"BigNumber",to:"Complex",convert:function(f){return r2||rn(f),new r2(f.toNumber(),0)}},{from:"bigint",to:"number",convert:function(f){if(f>Number.MAX_SAFE_INTEGER)throw new TypeError("Cannot implicitly convert bigint to number: value exceeds the max safe integer value (value: "+f+")");return Number(f)}},{from:"bigint",to:"BigNumber",convert:function(f){return n||nn(f),new n(f.toString())}},{from:"bigint",to:"Fraction",convert:function(f){return u2||un(f),new u2(f)}},{from:"Fraction",to:"BigNumber",convert:function(f){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(f){return r2||rn(f),new r2(f.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(f){u2||un(f);var l=new u2(f);if(l.valueOf()!==f)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+f+"). Use function fraction(x) to convert to Fraction.");return l}},{from:"string",to:"number",convert:function(f){var l=Number(f);if(isNaN(l))throw new Error('Cannot convert "'+f+'" to a number');return l}},{from:"string",to:"BigNumber",convert:function(f){n||nn(f);try{return new n(f)}catch{throw new Error('Cannot convert "'+f+'" to BigNumber')}}},{from:"string",to:"bigint",convert:function(f){try{return BigInt(f)}catch{throw new Error('Cannot convert "'+f+'" to BigInt')}}},{from:"string",to:"Fraction",convert:function(f){u2||un(f);try{return new u2(f)}catch{throw new Error('Cannot convert "'+f+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(f){r2||rn(f);try{return new r2(f)}catch{throw new Error('Cannot convert "'+f+'" to Complex')}}},{from:"boolean",to:"number",convert:function(f){return+f}},{from:"boolean",to:"BigNumber",convert:function(f){return n||nn(f),new n(+f)}},{from:"boolean",to:"bigint",convert:function(f){return BigInt(+f)}},{from:"boolean",to:"Fraction",convert:function(f){return u2||un(f),new u2(+f)}},{from:"boolean",to:"string",convert:function(f){return String(f)}},{from:"Array",to:"Matrix",convert:function(f){return i||function(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}(),new i(f)}},{from:"Matrix",to:"Array",convert:function(f){return f.valueOf()}}]),o.onMismatch=(s,f,l)=>{var a2=o.createError(s,f,l);if(["wrongType","mismatch"].includes(a2.data.category)&&1===f.length&&He(f[0])&&l.some(D2=>!D2.params.includes(","))){var c=new TypeError("Function '".concat(s,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(s,")'."));throw c.data=a2.data,c}throw a2},o.onMismatch=(s,f,l)=>{var a2=o.createError(s,f,l);if(["wrongType","mismatch"].includes(a2.data.category)&&1===f.length&&He(f[0])&&l.some(D2=>!D2.params.includes(","))){var c=new TypeError("Function '".concat(s,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(s,")'."));throw c.data=a2.data,c}throw a2},o});function nn(t2){throw new Error("Cannot convert value ".concat(t2," into a BigNumber: no class 'BigNumber' provided"))}function rn(t2){throw new Error("Cannot convert value ".concat(t2," into a Complex number: no class 'Complex' provided"))}function un(t2){throw new Error("Cannot convert value ".concat(t2," into a Fraction, no class 'Fraction' provided."))}var Ai,se,Te=9e15,De=1e9,Xn="0123456789abcdef",hn="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Dn="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",$n={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Te,maxE:Te,crypto:!1},K=!0,Cn="[DecimalError] ",he=Cn+"Invalid argument: ",Ci=Cn+"Precision limit exceeded",yi=Cn+"crypto unavailable",Bi="[object Decimal]",Pt=Math.floor,Ct=Math.pow,Bo=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,_o=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Mo=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,_i=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,te=1e7,xo=hn.length-1,Ln=Dn.length-1,O={toStringTag:Bi};function Tt(t2){var e,n,r2,i=t2.length-1,u2="",o=t2[0];if(i>0){for(u2+=o,e=1;e<i;e++)(n=7-(r2=t2[e]+"").length)&&(u2+=ce(n)),u2+=r2;(n=7-(r2=(o=t2[e])+"").length)&&(u2+=ce(n))}else if(0===o)return"0";for(;o%10==0;)o/=10;return u2+o}function $t(t2,e,n){if(t2!==~~t2||t2<e||t2>n)throw Error(he+t2)}function ke(t2,e,n,r2){var i,u2,o,s;for(u2=t2[0];u2>=10;u2/=10)--e;return--e<0?(e+=7,i=0):(i=Math.ceil((e+1)/7),e%=7),u2=Ct(10,7-e),s=t2[i]%u2|0,null==r2?e<3?(0==e?s=s/100|0:1==e&&(s=s/10|0),o=n<4&&99999==s||n>3&&49999==s||5e4==s||0==s):o=(n<4&&s+1==u2||n>3&&s+1==u2/2)&&(t2[i+1]/u2/100|0)==Ct(10,e-2)-1||(s==u2/2||0==s)&&!(t2[i+1]/u2/100|0):e<4?(0==e?s=s/1e3|0:1==e?s=s/100|0:2==e&&(s=s/10|0),o=(r2||n<4)&&9999==s||!r2&&n>3&&4999==s):o=((r2||n<4)&&s+1==u2||!r2&&n>3&&s+1==u2/2)&&(t2[i+1]/u2/1e3|0)==Ct(10,e-3)-1,o}function sn(t2,e,n){for(var r2,u2,i=[0],o=0,s=t2.length;o<s;){for(u2=i.length;u2--;)i[u2]*=e;for(i[0]+=Xn.indexOf(t2.charAt(o++)),r2=0;r2<i.length;r2++)i[r2]>n-1&&(void 0===i[r2+1]&&(i[r2+1]=0),i[r2+1]+=i[r2]/n|0,i[r2]%=n)}return i.reverse()}O.absoluteValue=O.abs=function(){var t2=new this.constructor(this);return t2.s<0&&(t2.s=1),H(t2)},O.ceil=function(){return H(new this.constructor(this),this.e+1,2)},O.clampedTo=O.clamp=function(t2,e){var i=this.constructor;if(t2=new i(t2),e=new i(e),!t2.s||!e.s)return new i(NaN);if(t2.gt(e))throw Error(he+e);return this.cmp(t2)<0?t2:this.cmp(e)>0?e:new i(this)},O.comparedTo=O.cmp=function(t2){var e,n,r2,i,u2=this,o=u2.d,s=(t2=new u2.constructor(t2)).d,f=u2.s,l=t2.s;if(!o||!s)return f&&l?f!==l?f:o===s?0:!o^f<0?1:-1:NaN;if(!o[0]||!s[0])return o[0]?f:s[0]?-l:0;if(f!==l)return f;if(u2.e!==t2.e)return u2.e>t2.e^f<0?1:-1;for(e=0,n=(r2=o.length)<(i=s.length)?r2:i;e<n;++e)if(o[e]!==s[e])return o[e]>s[e]^f<0?1:-1;return r2===i?0:r2>i^f<0?1:-1},O.cosine=O.cos=function(){var t2,e,n=this,r2=n.constructor;return n.d?n.d[0]?(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(n.e,n.sd())+7,r2.rounding=1,n=function(t2,e){var n,r2,i;if(e.isZero())return e;r2=e.d.length,r2<32?(n=Math.ceil(r2/3),i=(1/Bn(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),t2.precision+=n,e=ze(t2,1,e.times(i),new t2(1));for(var u2=n;u2--;){var o=e.times(e);e=o.times(o).minus(o).times(8).plus(1)}return t2.precision-=n,e}(r2,Ti(r2,n)),r2.precision=t2,r2.rounding=e,H(2==se||3==se?n.neg():n,t2,e,!0)):new r2(1):new r2(NaN)},O.cubeRoot=O.cbrt=function(){var t2,e,n,r2,i,u2,o,s,f,l,a2=this,c=a2.constructor;if(!a2.isFinite()||a2.isZero())return new c(a2);for(K=!1,(u2=a2.s*Ct(a2.s*a2,1/3))&&Math.abs(u2)!=1/0?r2=new c(u2.toString()):(n=Tt(a2.d),(u2=((t2=a2.e)-n.length+1)%3)&&(n+=1==u2||-2==u2?"0":"00"),u2=Ct(n,1/3),t2=Pt((t2+1)/3)-(t2%3==(t2<0?-1:2)),u2==1/0?n="5e"+t2:n=(n=u2.toExponential()).slice(0,n.indexOf("e")+1)+t2,(r2=new c(n)).s=a2.s),o=(t2=c.precision)+3;;)if(l=(f=(s=r2).times(s).times(s)).plus(a2),r2=ft(l.plus(a2).times(s),l.plus(f),o+2,1),Tt(s.d).slice(0,o)===(n=Tt(r2.d)).slice(0,o)){if("9999"!=(n=n.slice(o-3,o+1))&&(i||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(H(r2,t2+1,1),e=!r2.times(r2).times(r2).eq(a2));break}if(!i&&(H(s,t2+1,0),s.times(s).times(s).eq(a2))){r2=s;break}o+=4,i=1}return K=!0,H(r2,t2,c.rounding,e)},O.decimalPlaces=O.dp=function(){var t2,e=this.d,n=NaN;if(e){if(n=7*((t2=e.length-1)-Pt(this.e/7)),t2=e[t2])for(;t2%10==0;t2/=10)n--;n<0&&(n=0)}return n},O.dividedBy=O.div=function(t2){return ft(this,new this.constructor(t2))},O.dividedToIntegerBy=O.divToInt=function(t2){var n=this.constructor;return H(ft(this,new n(t2),0,1,1),n.precision,n.rounding)},O.equals=O.eq=function(t2){return 0===this.cmp(t2)},O.floor=function(){return H(new this.constructor(this),this.e+1,3)},O.greaterThan=O.gt=function(t2){return this.cmp(t2)>0},O.greaterThanOrEqualTo=O.gte=function(t2){var e=this.cmp(t2);return 1==e||0===e},O.hyperbolicCosine=O.cosh=function(){var t2,e,n,r2,i,u2=this,o=u2.constructor,s=new o(1);if(!u2.isFinite())return new o(u2.s?1/0:NaN);if(u2.isZero())return s;n=o.precision,r2=o.rounding,o.precision=n+Math.max(u2.e,u2.sd())+4,o.rounding=1,(i=u2.d.length)<32?e=(1/Bn(4,t2=Math.ceil(i/3))).toString():(t2=16,e="2.3283064365386962890625e-10"),u2=ze(o,1,u2.times(e),new o(1),!0);for(var f,l=t2,a2=new o(8);l--;)f=u2.times(u2),u2=s.minus(f.times(a2.minus(f.times(a2))));return H(u2,o.precision=n,o.rounding=r2,!0)},O.hyperbolicSine=O.sinh=function(){var t2,e,n,r2,i=this,u2=i.constructor;if(!i.isFinite()||i.isZero())return new u2(i);if(e=u2.precision,n=u2.rounding,u2.precision=e+Math.max(i.e,i.sd())+4,u2.rounding=1,(r2=i.d.length)<3)i=ze(u2,2,i,i,!0);else{t2=(t2=1.4*Math.sqrt(r2))>16?16:0|t2,i=ze(u2,2,i=i.times(1/Bn(5,t2)),i,!0);for(var o,s=new u2(5),f=new u2(16),l=new u2(20);t2--;)o=i.times(i),i=i.times(s.plus(o.times(f.times(o).plus(l))))}return u2.precision=e,u2.rounding=n,H(i,e,n,!0)},O.hyperbolicTangent=O.tanh=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+7,r2.rounding=1,ft(n.sinh(),n.cosh(),r2.precision=t2,r2.rounding=e)):new r2(n.s)},O.inverseCosine=O.acos=function(){var t2=this,e=t2.constructor,n=t2.abs().cmp(1),r2=e.precision,i=e.rounding;return-1!==n?0===n?t2.isNeg()?ee(e,r2,i):new e(0):new e(NaN):t2.isZero()?ee(e,r2+4,i).times(.5):(e.precision=r2+6,e.rounding=1,t2=new e(1).minus(t2).div(t2.plus(1)).sqrt().atan(),e.precision=r2,e.rounding=i,t2.times(2))},O.inverseHyperbolicCosine=O.acosh=function(){var t2,e,n=this,r2=n.constructor;return n.lte(1)?new r2(n.eq(1)?0:NaN):n.isFinite()?(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(Math.abs(n.e),n.sd())+4,r2.rounding=1,K=!1,n=n.times(n).minus(1).sqrt().plus(n),K=!0,r2.precision=t2,r2.rounding=e,n.ln()):new r2(n)},O.inverseHyperbolicSine=O.asinh=function(){var t2,e,n=this,r2=n.constructor;return!n.isFinite()||n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+2*Math.max(Math.abs(n.e),n.sd())+6,r2.rounding=1,K=!1,n=n.times(n).plus(1).sqrt().plus(n),K=!0,r2.precision=t2,r2.rounding=e,n.ln())},O.inverseHyperbolicTangent=O.atanh=function(){var t2,e,n,r2,i=this,u2=i.constructor;return i.isFinite()?i.e>=0?new u2(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(t2=u2.precision,e=u2.rounding,r2=i.sd(),Math.max(r2,t2)<2*-i.e-1?H(new u2(i),t2,e,!0):(u2.precision=n=r2-i.e,i=ft(i.plus(1),new u2(1).minus(i),n+t2,1),u2.precision=t2+4,u2.rounding=1,i=i.ln(),u2.precision=t2,u2.rounding=e,i.times(.5))):new u2(NaN)},O.inverseSine=O.asin=function(){var t2,e,n,r2,i=this,u2=i.constructor;return i.isZero()?new u2(i):(e=i.abs().cmp(1),n=u2.precision,r2=u2.rounding,-1!==e?0===e?((t2=ee(u2,n+4,r2).times(.5)).s=i.s,t2):new u2(NaN):(u2.precision=n+6,u2.rounding=1,i=i.div(new u2(1).minus(i.times(i)).sqrt().plus(1)).atan(),u2.precision=n,u2.rounding=r2,i.times(2)))},O.inverseTangent=O.atan=function(){var t2,e,n,r2,i,u2,o,s,f,l=this,a2=l.constructor,c=a2.precision,D2=a2.rounding;if(l.isFinite()){if(l.isZero())return new a2(l);if(l.abs().eq(1)&&c+4<=Ln)return(o=ee(a2,c+4,D2).times(.25)).s=l.s,o}else{if(!l.s)return new a2(NaN);if(c+4<=Ln)return(o=ee(a2,c+4,D2).times(.5)).s=l.s,o}for(a2.precision=s=c+10,a2.rounding=1,t2=n=Math.min(28,s/7+2|0);t2;--t2)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(K=!1,e=Math.ceil(s/7),r2=1,f=l.times(l),o=new a2(l),i=l;-1!==t2;)if(i=i.times(f),u2=o.minus(i.div(r2+=2)),i=i.times(f),void 0!==(o=u2.plus(i.div(r2+=2))).d[e])for(t2=e;o.d[t2]===u2.d[t2]&&t2--;);return n&&(o=o.times(2<<n-1)),K=!0,H(o,a2.precision=c,a2.rounding=D2,!0)},O.isFinite=function(){return!!this.d},O.isInteger=O.isInt=function(){return!!this.d&&Pt(this.e/7)>this.d.length-2},O.isNaN=function(){return!this.s},O.isNegative=O.isNeg=function(){return this.s<0},O.isPositive=O.isPos=function(){return this.s>0},O.isZero=function(){return!!this.d&&0===this.d[0]},O.lessThan=O.lt=function(t2){return this.cmp(t2)<0},O.lessThanOrEqualTo=O.lte=function(t2){return this.cmp(t2)<1},O.logarithm=O.log=function(t2){var e,n,r2,i,u2,o,s,f,l=this,a2=l.constructor,c=a2.precision,D2=a2.rounding;if(null==t2)t2=new a2(10),e=!0;else{if(n=(t2=new a2(t2)).d,t2.s<0||!n||!n[0]||t2.eq(1))return new a2(NaN);e=t2.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new a2(n&&!n[0]?-1/0:1!=l.s?NaN:n?0:1/0);if(e)if(n.length>1)u2=!0;else{for(i=n[0];i%10==0;)i/=10;u2=1!==i}if(K=!1,o=le(l,s=c+5),r2=e?pn(a2,s+10):le(t2,s),ke((f=ft(o,r2,s,1)).d,i=c,D2))do{if(o=le(l,s+=10),r2=e?pn(a2,s+10):le(t2,s),f=ft(o,r2,s,1),!u2){+Tt(f.d).slice(i+1,i+15)+1==1e14&&(f=H(f,c+1,0));break}}while(ke(f.d,i+=10,D2));return K=!0,H(f,c,D2)},O.minus=O.sub=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c,D2,w=this,M=w.constructor;if(t2=new M(t2),!w.d||!t2.d)return w.s&&t2.s?w.d?t2.s=-t2.s:t2=new M(t2.d||w.s!==t2.s?w:NaN):t2=new M(NaN),t2;if(w.s!=t2.s)return t2.s=-t2.s,w.plus(t2);if(l=w.d,D2=t2.d,s=M.precision,f=M.rounding,!l[0]||!D2[0]){if(D2[0])t2.s=-t2.s;else{if(!l[0])return new M(3===f?-0:0);t2=new M(w)}return K?H(t2,s,f):t2}if(n=Pt(t2.e/7),a2=Pt(w.e/7),l=l.slice(),u2=a2-n){for((c=u2<0)?(e=l,u2=-u2,o=D2.length):(e=D2,n=a2,o=l.length),u2>(r2=Math.max(Math.ceil(s/7),o)+2)&&(u2=r2,e.length=1),e.reverse(),r2=u2;r2--;)e.push(0);e.reverse()}else{for((c=(r2=l.length)<(o=D2.length))&&(o=r2),r2=0;r2<o;r2++)if(l[r2]!=D2[r2]){c=l[r2]<D2[r2];break}u2=0}for(c&&(e=l,l=D2,D2=e,t2.s=-t2.s),o=l.length,r2=D2.length-o;r2>0;--r2)l[o++]=0;for(r2=D2.length;r2>u2;){if(l[--r2]<D2[r2]){for(i=r2;i&&0===l[--i];)l[i]=te-1;--l[i],l[r2]+=te}l[r2]-=D2[r2]}for(;0===l[--o];)l.pop();for(;0===l[0];l.shift())--n;return l[0]?(t2.d=l,t2.e=yn(l,n),K?H(t2,s,f):t2):new M(3===f?-0:0)},O.modulo=O.mod=function(t2){var e,n=this,r2=n.constructor;return t2=new r2(t2),!n.d||!t2.s||t2.d&&!t2.d[0]?new r2(NaN):!t2.d||n.d&&!n.d[0]?H(new r2(n),r2.precision,r2.rounding):(K=!1,9==r2.modulo?(e=ft(n,t2.abs(),0,3,1)).s*=t2.s:e=ft(n,t2,0,r2.modulo,1),e=e.times(t2),K=!0,n.minus(e))},O.naturalExponential=O.exp=function(){return Zn(this)},O.naturalLogarithm=O.ln=function(){return le(this)},O.negated=O.neg=function(){var t2=new this.constructor(this);return t2.s=-t2.s,H(t2)},O.plus=O.add=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c=this,D2=c.constructor;if(t2=new D2(t2),!c.d||!t2.d)return c.s&&t2.s?c.d||(t2=new D2(t2.d||c.s===t2.s?c:NaN)):t2=new D2(NaN),t2;if(c.s!=t2.s)return t2.s=-t2.s,c.minus(t2);if(l=c.d,a2=t2.d,s=D2.precision,f=D2.rounding,!l[0]||!a2[0])return a2[0]||(t2=new D2(c)),K?H(t2,s,f):t2;if(u2=Pt(c.e/7),r2=Pt(t2.e/7),l=l.slice(),i=u2-r2){for(i<0?(n=l,i=-i,o=a2.length):(n=a2,r2=u2,o=l.length),i>(o=(u2=Math.ceil(s/7))>o?u2+1:o+1)&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for((o=l.length)-(i=a2.length)<0&&(i=o,n=a2,a2=l,l=n),e=0;i;)e=(l[--i]=l[i]+a2[i]+e)/te|0,l[i]%=te;for(e&&(l.unshift(e),++r2),o=l.length;0==l[--o];)l.pop();return t2.d=l,t2.e=yn(l,r2),K?H(t2,s,f):t2},O.precision=O.sd=function(t2){var e,n=this;if(void 0!==t2&&t2!==!!t2&&1!==t2&&0!==t2)throw Error(he+t2);return n.d?(e=Mi(n.d),t2&&n.e+1>e&&(e=n.e+1)):e=NaN,e},O.round=function(){var e=this.constructor;return H(new e(this),this.e+1,e.rounding)},O.sine=O.sin=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+Math.max(n.e,n.sd())+7,r2.rounding=1,n=function(t2,e){var n,r2=e.d.length;if(r2<3)return e.isZero()?e:ze(t2,2,e,e);n=1.4*Math.sqrt(r2),n=n>16?16:0|n,e=e.times(1/Bn(5,n)),e=ze(t2,2,e,e);for(var i,u2=new t2(5),o=new t2(16),s=new t2(20);n--;)i=e.times(e),e=e.times(u2.plus(i.times(o.times(i).minus(s))));return e}(r2,Ti(r2,n)),r2.precision=t2,r2.rounding=e,H(se>2?n.neg():n,t2,e,!0)):new r2(NaN)},O.squareRoot=O.sqrt=function(){var t2,e,n,r2,i,u2,o=this,s=o.d,f=o.e,l=o.s,a2=o.constructor;if(1!==l||!s||!s[0])return new a2(!l||l<0&&(!s||s[0])?NaN:s?o:1/0);for(K=!1,0==(l=Math.sqrt(+o))||l==1/0?(((e=Tt(s)).length+f)%2==0&&(e+="0"),l=Math.sqrt(e),f=Pt((f+1)/2)-(f<0||f%2),l==1/0?e="5e"+f:e=(e=l.toExponential()).slice(0,e.indexOf("e")+1)+f,r2=new a2(e)):r2=new a2(l.toString()),n=(f=a2.precision)+3;;)if(r2=(u2=r2).plus(ft(o,u2,n+2,1)).times(.5),Tt(u2.d).slice(0,n)===(e=Tt(r2.d)).slice(0,n)){if("9999"!=(e=e.slice(n-3,n+1))&&(i||"4999"!=e)){(!+e||!+e.slice(1)&&"5"==e.charAt(0))&&(H(r2,f+1,1),t2=!r2.times(r2).eq(o));break}if(!i&&(H(u2,f+1,0),u2.times(u2).eq(o))){r2=u2;break}n+=4,i=1}return K=!0,H(r2,f,a2.rounding,t2)},O.tangent=O.tan=function(){var t2,e,n=this,r2=n.constructor;return n.isFinite()?n.isZero()?new r2(n):(t2=r2.precision,e=r2.rounding,r2.precision=t2+10,r2.rounding=1,(n=n.sin()).s=1,n=ft(n,new r2(1).minus(n.times(n)).sqrt(),t2+10,0),r2.precision=t2,r2.rounding=e,H(2==se||4==se?n.neg():n,t2,e,!0)):new r2(NaN)},O.times=O.mul=function(t2){var e,n,r2,i,u2,o,s,f,l,c=this.constructor,D2=this.d,w=(t2=new c(t2)).d;if(t2.s*=this.s,!(D2&&D2[0]&&w&&w[0]))return new c(!t2.s||D2&&!D2[0]&&!w||w&&!w[0]&&!D2?NaN:D2&&w?0*t2.s:t2.s/0);for(n=Pt(this.e/7)+Pt(t2.e/7),(f=D2.length)<(l=w.length)&&(u2=D2,D2=w,w=u2,o=f,f=l,l=o),u2=[],r2=o=f+l;r2--;)u2.push(0);for(r2=l;--r2>=0;){for(e=0,i=f+r2;i>r2;)s=u2[i]+w[r2]*D2[i-r2-1]+e,u2[i--]=s%te|0,e=s/te|0;u2[i]=(u2[i]+e)%te|0}for(;!u2[--o];)u2.pop();return e?++n:u2.shift(),t2.d=u2,t2.e=yn(u2,n),K?H(t2,c.precision,c.rounding):t2},O.toBinary=function(t2,e){return Vn(this,2,t2,e)},O.toDecimalPlaces=O.toDP=function(t2,e){var n=this,r2=n.constructor;return n=new r2(n),void 0===t2?n:($t(t2,0,De),void 0===e?e=r2.rounding:$t(e,0,8),H(n,t2+n.e+1,e))},O.toExponential=function(t2,e){var n,r2=this,i=r2.constructor;return void 0===t2?n=ne(r2,!0):($t(t2,0,De),void 0===e?e=i.rounding:$t(e,0,8),n=ne(r2=H(new i(r2),t2+1,e),!0,t2+1)),r2.isNeg()&&!r2.isZero()?"-"+n:n},O.toFixed=function(t2,e){var n,r2,i=this,u2=i.constructor;return void 0===t2?n=ne(i):($t(t2,0,De),void 0===e?e=u2.rounding:$t(e,0,8),n=ne(r2=H(new u2(i),t2+i.e+1,e),!1,t2+r2.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n},O.toFraction=function(t2){var e,n,r2,i,u2,o,s,f,l,a2,c,D2,w=this,M=w.d,h2=w.constructor;if(!M)return new h2(w);if(l=n=new h2(1),r2=f=new h2(0),o=(u2=(e=new h2(r2)).e=Mi(M)-w.e-1)%7,e.d[0]=Ct(10,o<0?7+o:o),null==t2)t2=u2>0?e:l;else{if(!(s=new h2(t2)).isInt()||s.lt(l))throw Error(he+s);t2=s.gt(e)?u2>0?e:l:s}for(K=!1,s=new h2(Tt(M)),a2=h2.precision,h2.precision=u2=7*M.length*2;c=ft(s,e,0,1,1),1!=(i=n.plus(c.times(r2))).cmp(t2);)n=r2,r2=i,i=l,l=f.plus(c.times(i)),f=i,i=e,e=s.minus(c.times(i)),s=i;return i=ft(t2.minus(n),r2,0,1,1),f=f.plus(i.times(l)),n=n.plus(i.times(r2)),f.s=l.s=w.s,D2=ft(l,r2,u2,1).minus(w).abs().cmp(ft(f,n,u2,1).minus(w).abs())<1?[l,r2]:[f,n],h2.precision=a2,K=!0,D2},O.toHexadecimal=O.toHex=function(t2,e){return Vn(this,16,t2,e)},O.toNearest=function(t2,e){var n=this,r2=n.constructor;if(n=new r2(n),null==t2){if(!n.d)return n;t2=new r2(1),e=r2.rounding}else{if(t2=new r2(t2),void 0===e?e=r2.rounding:$t(e,0,8),!n.d)return t2.s?n:t2;if(!t2.d)return t2.s&&(t2.s=n.s),t2}return t2.d[0]?(K=!1,n=ft(n,t2,0,e,1).times(t2),K=!0,H(n)):(t2.s=n.s,n=t2),n},O.toNumber=function(){return+this},O.toOctal=function(t2,e){return Vn(this,8,t2,e)},O.toPower=O.pow=function(t2){var e,n,r2,i,u2,o,s=this,f=s.constructor,l=+(t2=new f(t2));if(!(s.d&&t2.d&&s.d[0]&&t2.d[0]))return new f(Ct(+s,l));if((s=new f(s)).eq(1))return s;if(r2=f.precision,u2=f.rounding,t2.eq(1))return H(s,r2,u2);if((e=Pt(t2.e/7))>=t2.d.length-1&&(n=l<0?-l:l)<=9007199254740991)return i=Ni(f,s,n,r2),t2.s<0?new f(1).div(i):H(i,r2,u2);if((o=s.s)<0){if(e<t2.d.length-1)return new f(NaN);if(!(1&t2.d[e])&&(o=1),0==s.e&&1==s.d[0]&&1==s.d.length)return s.s=o,s}return(e=0!=(n=Ct(+s,l))&&isFinite(n)?new f(n+"").e:Pt(l*(Math.log("0."+Tt(s.d))/Math.LN10+s.e+1)))>f.maxE+1||e<f.minE-1?new f(e>0?o/0:0):(K=!1,f.rounding=s.s=1,n=Math.min(12,(e+"").length),(i=Zn(t2.times(le(s,r2+n)),r2)).d&&(ke((i=H(i,r2+5,1)).d,r2,u2)&&(e=r2+10,+Tt((i=H(Zn(t2.times(le(s,e+n)),e),e+5,1)).d).slice(r2+1,r2+15)+1==1e14&&(i=H(i,r2+1,0)))),i.s=o,K=!0,f.rounding=u2,H(i,r2,u2))},O.toPrecision=function(t2,e){var n,r2=this,i=r2.constructor;return void 0===t2?n=ne(r2,r2.e<=i.toExpNeg||r2.e>=i.toExpPos):($t(t2,1,De),void 0===e?e=i.rounding:$t(e,0,8),n=ne(r2=H(new i(r2),t2,e),t2<=r2.e||r2.e<=i.toExpNeg,t2)),r2.isNeg()&&!r2.isZero()?"-"+n:n},O.toSignificantDigits=O.toSD=function(t2,e){var r2=this.constructor;return void 0===t2?(t2=r2.precision,e=r2.rounding):($t(t2,1,De),void 0===e?e=r2.rounding:$t(e,0,8)),H(new r2(this),t2,e)},O.toString=function(){var t2=this,e=t2.constructor,n=ne(t2,t2.e<=e.toExpNeg||t2.e>=e.toExpPos);return t2.isNeg()&&!t2.isZero()?"-"+n:n},O.truncated=O.trunc=function(){return H(new this.constructor(this),this.e+1,1)},O.valueOf=O.toJSON=function(){var t2=this,e=t2.constructor,n=ne(t2,t2.e<=e.toExpNeg||t2.e>=e.toExpPos);return t2.isNeg()?"-"+n:n};var ft=/* @__PURE__ */function(){function t2(r2,i,u2){var o,s=0,f=r2.length;for(r2=r2.slice();f--;)o=r2[f]*i+s,r2[f]=o%u2|0,s=o/u2|0;return s&&r2.unshift(s),r2}function e(r2,i,u2,o){var s,f;if(u2!=o)f=u2>o?1:-1;else for(s=f=0;s<u2;s++)if(r2[s]!=i[s]){f=r2[s]>i[s]?1:-1;break}return f}function n(r2,i,u2,o){for(var s=0;u2--;)r2[u2]-=s,s=r2[u2]<i[u2]?1:0,r2[u2]=s*o+r2[u2]-i[u2];for(;!r2[0]&&r2.length>1;)r2.shift()}return function(r2,i,u2,o,s,f){var l,a2,c,D2,w,M,h2,g,p2,E,F,A,d2,m,C,y,B2,x,T,q,Z=r2.constructor,W=r2.s==i.s?1:-1,L=r2.d,z=i.d;if(!(L&&L[0]&&z&&z[0]))return new Z(r2.s&&i.s&&(L?!z||L[0]!=z[0]:z)?L&&0==L[0]||!z?0*W:W/0:NaN);for(f?(w=1,a2=r2.e-i.e):(f=te,w=7,a2=Pt(r2.e/w)-Pt(i.e/w)),T=z.length,B2=L.length,E=(p2=new Z(W)).d=[],c=0;z[c]==(L[c]||0);c++);if(z[c]>(L[c]||0)&&a2--,null==u2?(m=u2=Z.precision,o=Z.rounding):m=s?u2+(r2.e-i.e)+1:u2,m<0)E.push(1),M=!0;else{if(m=m/w+2|0,c=0,1==T){for(D2=0,z=z[0],m++;(c<B2||D2)&&m--;c++)C=D2*f+(L[c]||0),E[c]=C/z|0,D2=C%z|0;M=D2||c<B2}else{for((D2=f/(z[0]+1)|0)>1&&(z=t2(z,D2,f),L=t2(L,D2,f),T=z.length,B2=L.length),y=T,A=(F=L.slice(0,T)).length;A<T;)F[A++]=0;(q=z.slice()).unshift(0),x=z[0],z[1]>=f/2&&++x;do{D2=0,(l=e(z,F,T,A))<0?(d2=F[0],T!=A&&(d2=d2*f+(F[1]||0)),(D2=d2/x|0)>1?(D2>=f&&(D2=f-1),1==(l=e(h2=t2(z,D2,f),F,g=h2.length,A=F.length))&&(D2--,n(h2,T<g?q:z,g,f))):(0==D2&&(l=D2=1),h2=z.slice()),(g=h2.length)<A&&h2.unshift(0),n(F,h2,A,f),-1==l&&((l=e(z,F,T,A=F.length))<1&&(D2++,n(F,T<A?q:z,A,f))),A=F.length):0===l&&(D2++,F=[0]),E[c++]=D2,l&&F[0]?F[A++]=L[y]||0:(F=[L[y]],A=1)}while((y++<B2||void 0!==F[0])&&m--);M=void 0!==F[0]}E[0]||E.shift()}if(1==w)p2.e=a2,Ai=M;else{for(c=1,D2=E[0];D2>=10;D2/=10)c++;p2.e=c+a2*w-1,H(p2,s?u2+p2.e+1:u2,o,M)}return p2}}();function H(t2,e,n,r2){var i,u2,o,s,f,l,a2,c,D2,w=t2.constructor;t:if(null!=e){if(!(c=t2.d))return t2;for(i=1,s=c[0];s>=10;s/=10)i++;if((u2=e-i)<0)u2+=7,o=e,f=(a2=c[D2=0])/Ct(10,i-o-1)%10|0;else if((D2=Math.ceil((u2+1)/7))>=(s=c.length)){if(!r2)break t;for(;s++<=D2;)c.push(0);a2=f=0,i=1,o=(u2%=7)-7+1}else{for(a2=s=c[D2],i=1;s>=10;s/=10)i++;f=(o=(u2%=7)-7+i)<0?0:a2/Ct(10,i-o-1)%10|0}if(r2=r2||e<0||void 0!==c[D2+1]||(o<0?a2:a2%Ct(10,i-o-1)),l=n<4?(f||r2)&&(0==n||n==(t2.s<0?3:2)):f>5||5==f&&(4==n||r2||6==n&&(u2>0?o>0?a2/Ct(10,i-o):0:c[D2-1])%10&1||n==(t2.s<0?8:7)),e<1||!c[0])return c.length=0,l?(e-=t2.e+1,c[0]=Ct(10,(7-e%7)%7),t2.e=-e||0):c[0]=t2.e=0,t2;if(0==u2?(c.length=D2,s=1,D2--):(c.length=D2+1,s=Ct(10,7-u2),c[D2]=o>0?(a2/Ct(10,i-o)%Ct(10,o)|0)*s:0),l)for(;;){if(0==D2){for(u2=1,o=c[0];o>=10;o/=10)u2++;for(o=c[0]+=s,s=1;o>=10;o/=10)s++;u2!=s&&(t2.e++,c[0]==te&&(c[0]=1));break}if(c[D2]+=s,c[D2]!=te)break;c[D2--]=0,s=1}for(u2=c.length;0===c[--u2];)c.pop()}return K&&(t2.e>w.maxE?(t2.d=null,t2.e=NaN):t2.e<w.minE&&(t2.e=0,t2.d=[0])),t2}function ne(t2,e,n){if(!t2.isFinite())return Si(t2);var r2,i=t2.e,u2=Tt(t2.d),o=u2.length;return e?(n&&(r2=n-o)>0?u2=u2.charAt(0)+"."+u2.slice(1)+ce(r2):o>1&&(u2=u2.charAt(0)+"."+u2.slice(1)),u2=u2+(t2.e<0?"e":"e+")+t2.e):i<0?(u2="0."+ce(-i-1)+u2,n&&(r2=n-o)>0&&(u2+=ce(r2))):i>=o?(u2+=ce(i+1-o),n&&(r2=n-i-1)>0&&(u2=u2+"."+ce(r2))):((r2=i+1)<o&&(u2=u2.slice(0,r2)+"."+u2.slice(r2)),n&&(r2=n-o)>0&&(i+1===o&&(u2+="."),u2+=ce(r2))),u2}function yn(t2,e){var n=t2[0];for(e*=7;n>=10;n/=10)e++;return e}function pn(t2,e,n){if(e>xo)throw K=!0,n&&(t2.precision=n),Error(Ci);return H(new t2(hn),e,1,!0)}function ee(t2,e,n){if(e>Ln)throw Error(Ci);return H(new t2(Dn),e,n,!0)}function Mi(t2){var e=t2.length-1,n=7*e+1;if(e=t2[e]){for(;e%10==0;e/=10)n--;for(e=t2[0];e>=10;e/=10)n++}return n}function ce(t2){for(var e="";t2--;)e+="0";return e}function Ni(t2,e,n,r2){var i,u2=new t2(1),o=Math.ceil(r2/7+4);for(K=!1;;){if(n%2&&(gr((u2=u2.times(e)).d,o)&&(i=!0)),0===(n=Pt(n/2))){n=u2.d.length-1,i&&0===u2.d[n]&&++u2.d[n];break}gr((e=e.times(e)).d,o)}return K=!0,u2}function mr(t2){return 1&t2.d[t2.d.length-1]}function xi(t2,e,n){for(var r2,i,u2=new t2(e[0]),o=0;++o<e.length;){if(!(i=new t2(e[o])).s){u2=i;break}((r2=u2.cmp(i))===n||0===r2&&u2.s===n)&&(u2=i)}return u2}function Zn(t2,e){var n,r2,i,u2,o,s,f,l=0,a2=0,c=0,D2=t2.constructor,w=D2.rounding,M=D2.precision;if(!t2.d||!t2.d[0]||t2.e>17)return new D2(t2.d?t2.d[0]?t2.s<0?0:1/0:1:t2.s?t2.s<0?0:t2:NaN);for(null==e?(K=!1,f=M):f=e,s=new D2(.03125);t2.e>-2;)t2=t2.times(s),c+=5;for(f+=r2=Math.log(Ct(2,c))/Math.LN10*2+5|0,n=u2=o=new D2(1),D2.precision=f;;){if(u2=H(u2.times(t2),f,1),n=n.times(++a2),Tt((s=o.plus(ft(u2,n,f,1))).d).slice(0,f)===Tt(o.d).slice(0,f)){for(i=c;i--;)o=H(o.times(o),f,1);if(null!=e)return D2.precision=M,o;if(!(l<3&&ke(o.d,f-r2,w,l)))return H(o,D2.precision=M,w,K=!0);D2.precision=f+=10,n=u2=s=new D2(1),a2=0,l++}o=s}}function le(t2,e){var n,r2,i,u2,o,s,f,l,a2,c,D2,w=1,h2=t2,g=h2.d,p2=h2.constructor,E=p2.rounding,F=p2.precision;if(h2.s<0||!g||!g[0]||!h2.e&&1==g[0]&&1==g.length)return new p2(g&&!g[0]?-1/0:1!=h2.s?NaN:g?0:h2);if(null==e?(K=!1,a2=F):a2=e,p2.precision=a2+=10,r2=(n=Tt(g)).charAt(0),!(Math.abs(u2=h2.e)<15e14))return l=pn(p2,a2+2,F).times(u2+""),h2=le(new p2(r2+"."+n.slice(1)),a2-10).plus(l),p2.precision=F,null==e?H(h2,F,E,K=!0):h2;for(;r2<7&&1!=r2||1==r2&&n.charAt(1)>3;)r2=(n=Tt((h2=h2.times(t2)).d)).charAt(0),w++;for(u2=h2.e,r2>1?(h2=new p2("0."+n),u2++):h2=new p2(r2+"."+n.slice(1)),c=h2,f=o=h2=ft(h2.minus(1),h2.plus(1),a2,1),D2=H(h2.times(h2),a2,1),i=3;;){if(o=H(o.times(D2),a2,1),Tt((l=f.plus(ft(o,new p2(i),a2,1))).d).slice(0,a2)===Tt(f.d).slice(0,a2)){if(f=f.times(2),0!==u2&&(f=f.plus(pn(p2,a2+2,F).times(u2+""))),f=ft(f,new p2(w),a2,1),null!=e)return p2.precision=F,f;if(!ke(f.d,a2-10,E,s))return H(f,p2.precision=F,E,K=!0);p2.precision=a2+=10,l=o=h2=ft(c.minus(1),c.plus(1),a2,1),D2=H(h2.times(h2),a2,1),i=s=1}f=l,i+=2}}function Si(t2){return String(t2.s*t2.s/0)}function an(t2,e){var n,r2,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r2=e.search(/e/i))>0?(n<0&&(n=r2),n+=+e.slice(r2+1),e=e.substring(0,r2)):n<0&&(n=e.length),r2=0;48===e.charCodeAt(r2);r2++);for(i=e.length;48===e.charCodeAt(i-1);--i);if(e=e.slice(r2,i)){if(i-=r2,t2.e=n=n-r2-1,t2.d=[],r2=(n+1)%7,n<0&&(r2+=7),r2<i){for(r2&&t2.d.push(+e.slice(0,r2)),i-=7;r2<i;)t2.d.push(+e.slice(r2,r2+=7));r2=7-(e=e.slice(r2)).length}else r2-=i;for(;r2--;)e+="0";t2.d.push(+e),K&&(t2.e>t2.constructor.maxE?(t2.d=null,t2.e=NaN):t2.e<t2.constructor.minE&&(t2.e=0,t2.d=[0]))}else t2.e=0,t2.d=[0];return t2}function ze(t2,e,n,r2,i){var u2,o,s,f,l=t2.precision,a2=Math.ceil(l/7);for(K=!1,f=n.times(n),s=new t2(r2);;){if(o=ft(s.times(f),new t2(e++*e++),l,1),s=i?r2.plus(o):r2.minus(o),r2=ft(o.times(f),new t2(e++*e++),l,1),void 0!==(o=s.plus(r2)).d[a2]){for(u2=a2;o.d[u2]===s.d[u2]&&u2--;);if(-1==u2)break}u2=s,s=r2,r2=o,o=u2}return K=!0,o.d.length=a2+1,o}function Bn(t2,e){for(var n=t2;--e;)n*=t2;return n}function Ti(t2,e){var n,r2=e.s<0,i=ee(t2,t2.precision,1),u2=i.times(.5);if((e=e.abs()).lte(u2))return se=r2?4:1,e;if((n=e.divToInt(i)).isZero())se=r2?3:2;else{if((e=e.minus(n.times(i))).lte(u2))return se=mr(n)?r2?2:3:r2?4:1,e;se=mr(n)?r2?1:4:r2?3:2}return e.minus(i).abs()}function Vn(t2,e,n,r2){var i,u2,o,s,f,l,a2,c,D2,w=t2.constructor,M=void 0!==n;if(M?($t(n,1,De),void 0===r2?r2=w.rounding:$t(r2,0,8)):(n=w.precision,r2=w.rounding),t2.isFinite()){for(M?(i=2,16==e?n=4*n-3:8==e&&(n=3*n-2)):i=e,(o=(a2=ne(t2)).indexOf("."))>=0&&(a2=a2.replace(".",""),(D2=new w(1)).e=a2.length-o,D2.d=sn(ne(D2),10,i),D2.e=D2.d.length),u2=f=(c=sn(a2,10,i)).length;0==c[--f];)c.pop();if(c[0]){if(o<0?u2--:((t2=new w(t2)).d=c,t2.e=u2,c=(t2=ft(t2,D2,n,r2,0,i)).d,u2=t2.e,l=Ai),o=c[n],s=i/2,l=l||void 0!==c[n+1],l=r2<4?(void 0!==o||l)&&(0===r2||r2===(t2.s<0?3:2)):o>s||o===s&&(4===r2||l||6===r2&&1&c[n-1]||r2===(t2.s<0?8:7)),c.length=n,l)for(;++c[--n]>i-1;)c[n]=0,n||(++u2,c.unshift(1));for(f=c.length;!c[f-1];--f);for(o=0,a2="";o<f;o++)a2+=Xn.charAt(c[o]);if(M){if(f>1)if(16==e||8==e){for(o=16==e?4:3,--f;f%o;f++)a2+="0";for(f=(c=sn(a2,i,e)).length;!c[f-1];--f);for(o=1,a2="1.";o<f;o++)a2+=Xn.charAt(c[o])}else a2=a2.charAt(0)+"."+a2.slice(1);a2=a2+(u2<0?"p":"p+")+u2}else if(u2<0){for(;++u2;)a2="0"+a2;a2="0."+a2}else if(++u2>f)for(u2-=f;u2--;)a2+="0";else u2<f&&(a2=a2.slice(0,u2)+"."+a2.slice(u2))}else a2=M?"0p+0":"0";a2=(16==e?"0x":2==e?"0b":8==e?"0o":"")+a2}else a2=Si(t2);return t2.s<0?"-"+a2:a2}function gr(t2,e){if(t2.length>e)return t2.length=e,!0}function Io(t2){return new this(t2).abs()}function Oo(t2){return new this(t2).acos()}function Po(t2){return new this(t2).acosh()}function zo(t2,e){return new this(t2).plus(e)}function Ro(t2){return new this(t2).asin()}function qo(t2){return new this(t2).asinh()}function Yo(t2){return new this(t2).atan()}function Uo(t2){return new this(t2).atanh()}function Xo(t2,e){t2=new this(t2),e=new this(e);var n,r2=this.precision,i=this.rounding,u2=r2+4;return t2.s&&e.s?t2.d||e.d?!e.d||t2.isZero()?(n=e.s<0?ee(this,r2,i):new this(0)).s=t2.s:!t2.d||e.isZero()?(n=ee(this,u2,1).times(.5)).s=t2.s:e.s<0?(this.precision=u2,this.rounding=1,n=this.atan(ft(t2,e,u2,1)),e=ee(this,u2,1),this.precision=r2,this.rounding=i,n=t2.s<0?n.minus(e):n.plus(e)):n=this.atan(ft(t2,e,u2,1)):(n=ee(this,u2,1).times(e.s>0?.25:.75)).s=t2.s:n=new this(NaN),n}function $o(t2){return new this(t2).cbrt()}function Lo(t2){return H(t2=new this(t2),t2.e+1,2)}function Zo(t2,e,n){return new this(t2).clamp(e,n)}function Wo(t2){if(!t2||"object"!=typeof t2)throw Error(Cn+"Object expected");var e,n,r2,i=!0===t2.defaults,u2=["precision",1,De,"rounding",0,8,"toExpNeg",-Te,0,"toExpPos",0,Te,"maxE",0,Te,"minE",-Te,0,"modulo",0,9];for(e=0;e<u2.length;e+=3)if(n=u2[e],i&&(this[n]=$n[n]),void 0!==(r2=t2[n])){if(!(Pt(r2)===r2&&r2>=u2[e+1]&&r2<=u2[e+2]))throw Error(he+n+": "+r2);this[n]=r2}if(n="crypto",i&&(this[n]=$n[n]),void 0!==(r2=t2[n])){if(!0!==r2&&!1!==r2&&0!==r2&&1!==r2)throw Error(he+n+": "+r2);if(r2){if(!(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes)))throw Error(yi);this[n]=!0}else this[n]=!1}return this}function Vo(t2){return new this(t2).cos()}function Ho(t2){return new this(t2).cosh()}function Jo(t2,e){return new this(t2).div(e)}function ko(t2){return new this(t2).exp()}function Go(t2){return H(t2=new this(t2),t2.e+1,3)}function Qo(){var t2,e,n=new this(0);for(K=!1,t2=0;t2<arguments.length;)if((e=new this(arguments[t2++])).d)n.d&&(n=n.plus(e.times(e)));else{if(e.s)return K=!0,new this(1/0);n=e}return K=!0,n.sqrt()}function vr(t2){return t2 instanceof Re||t2&&t2.toStringTag===Bi||!1}function Ko(t2){return new this(t2).ln()}function jo(t2,e){return new this(t2).log(e)}function ts(t2){return new this(t2).log(2)}function es(t2){return new this(t2).log(10)}function ns(){return xi(this,arguments,-1)}function rs(){return xi(this,arguments,1)}function is(t2,e){return new this(t2).mod(e)}function us(t2,e){return new this(t2).mul(e)}function os(t2,e){return new this(t2).pow(e)}function ss(t2){var e,n,r2,i,u2=0,o=new this(1),s=[];if(void 0===t2?t2=this.precision:$t(t2,1,De),r2=Math.ceil(t2/7),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r2));u2<r2;)(i=e[u2])>=429e7?e[u2]=crypto.getRandomValues(new Uint32Array(1))[0]:s[u2++]=i%1e7;else{if(!crypto.randomBytes)throw Error(yi);for(e=crypto.randomBytes(r2*=4);u2<r2;)(i=e[u2]+(e[u2+1]<<8)+(e[u2+2]<<16)+((127&e[u2+3])<<24))>=214e7?crypto.randomBytes(4).copy(e,u2):(s.push(i%1e7),u2+=4);u2=r2/4}else for(;u2<r2;)s[u2++]=1e7*Math.random()|0;for(t2%=7,(r2=s[--u2])&&t2&&(i=Ct(10,7-t2),s[u2]=(r2/i|0)*i);0===s[u2];u2--)s.pop();if(u2<0)n=0,s=[0];else{for(n=-1;0===s[0];n-=7)s.shift();for(r2=1,i=s[0];i>=10;i/=10)r2++;r2<7&&(n-=7-r2)}return o.e=n,o.d=s,o}function as(t2){return H(t2=new this(t2),t2.e+1,this.rounding)}function fs(t2){return(t2=new this(t2)).d?t2.d[0]?t2.s:0*t2.s:t2.s||NaN}function cs(t2){return new this(t2).sin()}function ls(t2){return new this(t2).sinh()}function hs(t2){return new this(t2).sqrt()}function Ds(t2,e){return new this(t2).sub(e)}function ps(){var t2=0,e=arguments,n=new this(e[t2]);for(K=!1;n.s&&++t2<e.length;)n=n.plus(e[t2]);return K=!0,H(n,this.precision,this.rounding)}function ds(t2){return new this(t2).tan()}function ms(t2){return new this(t2).tanh()}function gs(t2){return H(t2=new this(t2),t2.e+1,1)}O[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")]=O.toString,O[Symbol.toStringTag]="Decimal";var Re=O.constructor=function bi(t2){var e,n,r2;function i(u2){var o,s,f,l=this;if(!(l instanceof i))return new i(u2);if(l.constructor=i,vr(u2))return l.s=u2.s,void(K?!u2.d||u2.e>i.maxE?(l.e=NaN,l.d=null):u2.e<i.minE?(l.e=0,l.d=[0]):(l.e=u2.e,l.d=u2.d.slice()):(l.e=u2.e,l.d=u2.d?u2.d.slice():u2.d));if("number"===(f=typeof u2)){if(0===u2)return l.s=1/u2<0?-1:1,l.e=0,void(l.d=[0]);if(u2<0?(u2=-u2,l.s=-1):l.s=1,u2===~~u2&&u2<1e7){for(o=0,s=u2;s>=10;s/=10)o++;return void(K?o>i.maxE?(l.e=NaN,l.d=null):o<i.minE?(l.e=0,l.d=[0]):(l.e=o,l.d=[u2]):(l.e=o,l.d=[u2]))}return 0*u2!=0?(u2||(l.s=NaN),l.e=NaN,void(l.d=null)):an(l,u2.toString())}if("string"===f)return 45===(s=u2.charCodeAt(0))?(u2=u2.slice(1),l.s=-1):(43===s&&(u2=u2.slice(1)),l.s=1),_i.test(u2)?an(l,u2):function(t2,e){var n,r2,i,u2,o,s,f,l,a2;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),_i.test(e))return an(t2,e)}else if("Infinity"===e||"NaN"===e)return+e||(t2.s=NaN),t2.e=NaN,t2.d=null,t2;if(_o.test(e))n=16,e=e.toLowerCase();else if(Bo.test(e))n=2;else{if(!Mo.test(e))throw Error(he+e);n=8}for((u2=e.search(/p/i))>0?(f=+e.slice(u2+1),e=e.substring(2,u2)):e=e.slice(2),o=(u2=e.indexOf("."))>=0,r2=t2.constructor,o&&(u2=(s=(e=e.replace(".","")).length)-u2,i=Ni(r2,new r2(n),u2,2*u2)),u2=a2=(l=sn(e,n,te)).length-1;0===l[u2];--u2)l.pop();return u2<0?new r2(0*t2.s):(t2.e=yn(l,a2),t2.d=l,K=!1,o&&(t2=ft(t2,i,4*s)),f&&(t2=t2.times(Math.abs(f)<54?Ct(2,f):Re.pow(2,f))),K=!0,t2)}(l,u2);if("bigint"===f)return u2<0?(u2=-u2,l.s=-1):l.s=1,an(l,u2.toString());throw Error(he+u2)}if(i.prototype=O,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Wo,i.clone=bi,i.isDecimal=vr,i.abs=Io,i.acos=Oo,i.acosh=Po,i.add=zo,i.asin=Ro,i.asinh=qo,i.atan=Yo,i.atanh=Uo,i.atan2=Xo,i.cbrt=$o,i.ceil=Lo,i.clamp=Zo,i.cos=Vo,i.cosh=Ho,i.div=Jo,i.exp=ko,i.floor=Go,i.hypot=Qo,i.ln=Ko,i.log=jo,i.log10=es,i.log2=ts,i.max=ns,i.min=rs,i.mod=is,i.mul=us,i.pow=os,i.random=ss,i.round=as,i.sign=fs,i.sin=cs,i.sinh=ls,i.sqrt=hs,i.sub=Ds,i.sum=ps,i.tan=ds,i.tanh=ms,i.trunc=gs,void 0===t2&&(t2={}),t2&&!0!==t2.defaults)for(r2=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r2.length;)t2.hasOwnProperty(n=r2[e++])||(t2[n]=this[n]);return i.config(t2),i}($n);hn=new Re(hn),Dn=new Re(Dn);var ws=/* @__PURE__ */Ft("BigNumber",["?on","config"],t2=>{var{on:e,config:n}=t2,r2=Re.clone({precision:n.precision,modulo:Re.EUCLID});return r2.prototype=Object.create(r2.prototype),r2.prototype.type="BigNumber",r2.prototype.isBigNumber=!0,r2.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},r2.fromJSON=function(i){return new r2(i.value)},e&&e("config",function(i,u2){i.precision!==u2.precision&&r2.config({precision:i.precision})}),r2},{isClass:!0});const It=Math.cosh||function(t2){return Math.abs(t2)<1e-9?1-t2:.5*(Math.exp(t2)+Math.exp(-t2))},Ht=Math.sinh||function(t2){return Math.abs(t2)<1e-9?t2:.5*(Math.exp(t2)-Math.exp(-t2))},Rn=function(t2,e){return(t2=Math.abs(t2))<(e=Math.abs(e))&&([t2,e]=[e,t2]),t2<1e8?Math.sqrt(t2*t2+e*e):(e/=t2,t2*Math.sqrt(1+e*e))},_e=function(){throw SyntaxError("Invalid Param")};function qn(t2,e){const n=Math.abs(t2),r2=Math.abs(e);return 0===t2?Math.log(r2):0===e?Math.log(n):n<3e3&&r2<3e3?.5*Math.log(t2*t2+e*e):(t2*=.5,e*=.5,.5*Math.log(t2*t2+e*e)+Math.LN2)}const As={re:0,im:0},pe=function(t2,e){const n=As;if(null==t2)n.re=n.im=0;else if(void 0!==e)n.re=t2,n.im=e;else switch(typeof t2){case"object":if("im"in t2&&"re"in t2)n.re=t2.re,n.im=t2.im;else if("abs"in t2&&"arg"in t2){if(!isFinite(t2.abs)&&isFinite(t2.arg))return S.INFINITY;n.re=t2.abs*Math.cos(t2.arg),n.im=t2.abs*Math.sin(t2.arg)}else if("r"in t2&&"phi"in t2){if(!isFinite(t2.r)&&isFinite(t2.phi))return S.INFINITY;n.re=t2.r*Math.cos(t2.phi),n.im=t2.r*Math.sin(t2.phi)}else 2===t2.length?(n.re=t2[0],n.im=t2[1]):_e();break;case"string":n.im=n.re=0;const r2=t2.replace(/_/g,"").match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g);let i=1,u2=0;null===r2&&_e();for(let o=0;o<r2.length;o++){const s=r2[o];" "===s||"\t"===s||"\n"===s||("+"===s?i++:"-"===s?u2++:"i"===s||"I"===s?(i+u2===0&&_e()," "===r2[o+1]||isNaN(r2[o+1])?n.im+=parseFloat((u2%2?"-":"")+"1"):(n.im+=parseFloat((u2%2?"-":"")+r2[o+1]),o++),i=u2=0):((i+u2===0||isNaN(s))&&_e(),"i"===r2[o+1]||"I"===r2[o+1]?(n.im+=parseFloat((u2%2?"-":"")+s),o++):n.re+=parseFloat((u2%2?"-":"")+s),i=u2=0))}i+u2>0&&_e();break;case"number":n.im=0,n.re=t2;break;default:_e()}return isNaN(n.re)||isNaN(n.im),n};function S(t2,e){if(!(this instanceof S))return new S(t2,e);const n=pe(t2,e);this.re=n.re,this.im=n.im}S.prototype={re:0,im:0,sign:function(){const t2=Rn(this.re,this.im);return new S(this.re/t2,this.im/t2)},add:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r2||i?r2&&i?S.NAN:S.INFINITY:new S(this.re+n.re,this.im+n.im)},sub:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im));return r2||i?r2&&i?S.NAN:S.INFINITY:new S(this.re-n.re,this.im-n.im)},mul:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),u2=0===this.re&&0===this.im,o=0===n.re&&0===n.im;return r2&&o||i&&u2?S.NAN:r2||i?S.INFINITY:0===n.im&&0===this.im?new S(this.re*n.re,0):new S(this.re*n.re-this.im*n.im,this.re*n.im+this.im*n.re)},div:function(t2,e){const n=pe(t2,e),r2=this.isInfinite(),i=!(isFinite(n.re)&&isFinite(n.im)),u2=0===this.re&&0===this.im,o=0===n.re&&0===n.im;if(u2&&o||r2&&i)return S.NAN;if(o||r2)return S.INFINITY;if(u2||i)return S.ZERO;if(0===n.im)return new S(this.re/n.re,this.im/n.re);if(Math.abs(n.re)<Math.abs(n.im)){const s=n.re/n.im,f=n.re*s+n.im;return new S((this.re*s+this.im)/f,(this.im*s-this.re)/f)}{const s=n.im/n.re,f=n.im*s+n.re;return new S((this.re+this.im*s)/f,(this.im-this.re*s)/f)}},pow:function(t2,e){const n=pe(t2,e),r2=0===this.re&&0===this.im;if(0===n.re&&0===n.im)return S.ONE;if(0===n.im){if(0===this.im&&this.re>0)return new S(Math.pow(this.re,n.re),0);if(0===this.re)switch((n.re%4+4)%4){case 0:return new S(Math.pow(this.im,n.re),0);case 1:return new S(0,Math.pow(this.im,n.re));case 2:return new S(-Math.pow(this.im,n.re),0);case 3:return new S(0,-Math.pow(this.im,n.re))}}if(r2&&n.re>0)return S.ZERO;const u2=Math.atan2(this.im,this.re),o=qn(this.re,this.im);let s=Math.exp(n.re*o-n.im*u2),f=n.im*o+n.re*u2;return new S(s*Math.cos(f),s*Math.sin(f))},sqrt:function(){const t2=this.re,e=this.im;if(0===e)return t2>=0?new S(Math.sqrt(t2),0):new S(0,Math.sqrt(-t2));const n=Rn(t2,e);let r2=Math.sqrt(.5*(n+Math.abs(t2))),i=Math.abs(e)/(2*r2);return t2>=0?new S(r2,e<0?-i:i):new S(i,e<0?-r2:r2)},exp:function(){const t2=Math.exp(this.re);return 0===this.im?new S(t2,0):new S(t2*Math.cos(this.im),t2*Math.sin(this.im))},expm1:function(){const t2=this.re,e=this.im;return new S(Math.expm1(t2)*Math.cos(e)+function(t2){const e=Math.PI/4;if(-e>t2||t2>e)return Math.cos(t2)-1;const n=t2*t2;return n*(n*(n*(n*(n*(n*(n*(n/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5)}(e),Math.exp(t2)*Math.sin(e))},log:function(){const t2=this.re,e=this.im;return 0===e&&t2>0?new S(Math.log(t2),0):new S(qn(t2,e),Math.atan2(e,t2))},abs:function(){return Rn(this.re,this.im)},arg:function(){return Math.atan2(this.im,this.re)},sin:function(){const t2=this.re,e=this.im;return new S(Math.sin(t2)*It(e),Math.cos(t2)*Ht(e))},cos:function(){const t2=this.re,e=this.im;return new S(Math.cos(t2)*It(e),-Math.sin(t2)*Ht(e))},tan:function(){const t2=2*this.re,e=2*this.im,n=Math.cos(t2)+It(e);return new S(Math.sin(t2)/n,Ht(e)/n)},cot:function(){const t2=2*this.re,e=2*this.im,n=Math.cos(t2)-It(e);return new S(-Math.sin(t2)/n,Ht(e)/n)},sec:function(){const t2=this.re,e=this.im,n=.5*It(2*e)+.5*Math.cos(2*t2);return new S(Math.cos(t2)*It(e)/n,Math.sin(t2)*Ht(e)/n)},csc:function(){const t2=this.re,e=this.im,n=.5*It(2*e)-.5*Math.cos(2*t2);return new S(Math.sin(t2)*It(e)/n,-Math.cos(t2)*Ht(e)/n)},asin:function(){const t2=this.re,e=this.im,n=new S(e*e-t2*t2+1,-2*t2*e).sqrt(),r2=new S(n.re-e,n.im+t2).log();return new S(r2.im,-r2.re)},acos:function(){const t2=this.re,e=this.im,n=new S(e*e-t2*t2+1,-2*t2*e).sqrt(),r2=new S(n.re-e,n.im+t2).log();return new S(Math.PI/2-r2.im,r2.re)},atan:function(){const t2=this.re,e=this.im;if(0===t2){if(1===e)return new S(0,1/0);if(-1===e)return new S(0,-1/0)}const n=t2*t2+(1-e)*(1-e),r2=new S((1-e*e-t2*t2)/n,-2*t2/n).log();return new S(-.5*r2.im,.5*r2.re)},acot:function(){const t2=this.re,e=this.im;if(0===e)return new S(Math.atan2(1,t2),0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).atan():new S(0!==t2?t2/0:0,0!==e?-e/0:0).atan()},asec:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(0,1/0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).acos():new S(0!==t2?t2/0:0,0!==e?-e/0:0).acos()},acsc:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(Math.PI/2,1/0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).asin():new S(0!==t2?t2/0:0,0!==e?-e/0:0).asin()},sinh:function(){const t2=this.re,e=this.im;return new S(Ht(t2)*Math.cos(e),It(t2)*Math.sin(e))},cosh:function(){const t2=this.re,e=this.im;return new S(It(t2)*Math.cos(e),Ht(t2)*Math.sin(e))},tanh:function(){const t2=2*this.re,e=2*this.im,n=It(t2)+Math.cos(e);return new S(Ht(t2)/n,Math.sin(e)/n)},coth:function(){const t2=2*this.re,e=2*this.im,n=It(t2)-Math.cos(e);return new S(Ht(t2)/n,-Math.sin(e)/n)},csch:function(){const t2=this.re,e=this.im,n=Math.cos(2*e)-It(2*t2);return new S(-2*Ht(t2)*Math.cos(e)/n,2*It(t2)*Math.sin(e)/n)},sech:function(){const t2=this.re,e=this.im,n=Math.cos(2*e)+It(2*t2);return new S(2*It(t2)*Math.cos(e)/n,-2*Ht(t2)*Math.sin(e)/n)},asinh:function(){let t2=this.im;this.im=-this.re,this.re=t2;const e=this.asin();return this.re=-this.im,this.im=t2,t2=e.re,e.re=-e.im,e.im=t2,e},acosh:function(){const t2=this.acos();if(t2.im<=0){const e=t2.re;t2.re=-t2.im,t2.im=e}else{const e=t2.im;t2.im=-t2.re,t2.re=e}return t2},atanh:function(){const t2=this.re,e=this.im,n=t2>1&&0===e,r2=1-t2,i=1+t2,u2=r2*r2+e*e,o=0!==u2?new S((i*r2-e*e)/u2,(e*r2+i*e)/u2):new S(-1!==t2?t2/0:0,0!==e?e/0:0),s=o.re;return o.re=qn(o.re,o.im)/2,o.im=Math.atan2(o.im,s)/2,n&&(o.im=-o.im),o},acoth:function(){const t2=this.re,e=this.im;if(0===t2&&0===e)return new S(0,Math.PI/2);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).atanh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).atanh()},acsch:function(){const t2=this.re,e=this.im;if(0===e)return new S(0!==t2?Math.log(t2+Math.sqrt(t2*t2+1)):1/0,0);const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).asinh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).asinh()},asech:function(){const t2=this.re,e=this.im;if(this.isZero())return S.INFINITY;const n=t2*t2+e*e;return 0!==n?new S(t2/n,-e/n).acosh():new S(0!==t2?t2/0:0,0!==e?-e/0:0).acosh()},inverse:function(){if(this.isZero())return S.INFINITY;if(this.isInfinite())return S.ZERO;const t2=this.re,e=this.im,n=t2*t2+e*e;return new S(t2/n,-e/n)},conjugate:function(){return new S(this.re,-this.im)},neg:function(){return new S(-this.re,-this.im)},ceil:function(t2){return t2=Math.pow(10,t2||0),new S(Math.ceil(this.re*t2)/t2,Math.ceil(this.im*t2)/t2)},floor:function(t2){return t2=Math.pow(10,t2||0),new S(Math.floor(this.re*t2)/t2,Math.floor(this.im*t2)/t2)},round:function(t2){return t2=Math.pow(10,t2||0),new S(Math.round(this.re*t2)/t2,Math.round(this.im*t2)/t2)},equals:function(t2,e){const n=pe(t2,e);return Math.abs(n.re-this.re)<=S.EPSILON&&Math.abs(n.im-this.im)<=S.EPSILON},clone:function(){return new S(this.re,this.im)},toString:function(){let t2=this.re,e=this.im,n="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(t2)<S.EPSILON&&(t2=0),Math.abs(e)<S.EPSILON&&(e=0),0===e?n+t2:(0!==t2?(n+=t2,n+=" ",e<0?(e=-e,n+="-"):n+="+",n+=" "):e<0&&(e=-e,n+="-"),1!==e&&(n+=e),n+"i"))},toVector:function(){return[this.re,this.im]},valueOf:function(){return 0===this.im?this.re:null},isNaN:function(){return isNaN(this.re)||isNaN(this.im)},isZero:function(){return 0===this.im&&0===this.re},isFinite:function(){return isFinite(this.re)&&isFinite(this.im)},isInfinite:function(){return!this.isFinite()}},S.ZERO=new S(0,0),S.ONE=new S(1,0),S.I=new S(0,1),S.PI=new S(Math.PI,0),S.E=new S(Math.E,0),S.INFINITY=new S(1/0,1/0),S.NAN=new S(NaN,NaN),S.EPSILON=1e-15;var Bs=/* @__PURE__ */Ft("Complex",[],()=>(Object.defineProperty(S,"name",{value:"Complex"}),S.prototype.constructor=S,S.prototype.type="Complex",S.prototype.isComplex=!0,S.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},S.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},S.prototype.format=function(t2){var n=this.im,r2=this.re,i=Un(this.re,t2),u2=Un(this.im,t2),o=lt(t2)?t2:t2?t2.precision:null;if(null!==o){var s=Math.pow(10,-o);Math.abs(r2/n)<s&&(r2=0),Math.abs(n/r2)<s&&(n=0)}return 0===n?i:0===r2?1===n?"i":-1===n?"-i":u2+"i":n<0?-1===n?i+" - i":i+" - "+u2.substring(1)+"i":1===n?i+" + i":i+" + "+u2+"i"},S.fromPolar=function(t2){switch(arguments.length){case 1:var e=arguments[0];if("object"==typeof e)return S(e);throw new TypeError("Input has to be an object with r and phi keys.");case 2:var n=arguments[0],r2=arguments[1];if(lt(n)){if(Fn(r2)&&r2.hasBase("ANGLE")&&(r2=r2.toNumber("rad")),lt(r2))return new S({r:n,phi:r2});throw new TypeError("Phi is not a number nor an angle unit.")}throw new TypeError("Radius r is not a number.");default:throw new SyntaxError("Wrong number of arguments in function fromPolar")}},S.prototype.valueOf=S.prototype.toString,S.fromJSON=function(t2){return new S(t2)},S.compare=function(t2,e){return t2.re>e.re?1:t2.re<e.re?-1:t2.im>e.im?1:t2.im<e.im?-1:0},S),{isClass:!0});typeof BigInt>"u"&&(BigInt=function(t2){if(isNaN(t2))throw new Error("");return t2});const V=BigInt(0),tt=BigInt(1),_t=BigInt(2),Ve=BigInt(3),be=BigInt(5),Xt=BigInt(10);BigInt(Number.MAX_SAFE_INTEGER);const U={s:tt,n:V,d:tt};function oe(t2,e){try{t2=BigInt(t2)}catch{throw fe()}return t2*e}function Kt(t2){return"bigint"==typeof t2?t2:Math.floor(t2)}function dt(t2,e){if(e===V)throw Hn();const n=Object.create(Jt.prototype);n.s=t2<V?-tt:tt;const r2=de(t2=t2<V?-t2:t2,e);return n.n=t2/r2,n.d=e/r2,n}const Ms=[_t*_t,_t,_t*_t,_t,_t*_t,_t*Ve,_t,_t*Ve];function Me(t2){const e=/* @__PURE__ */Object.create(null);if(t2<=tt)return e[t2]=tt,e;const n=r2=>{e[r2]=(e[r2]||V)+tt};for(;t2%_t===V;)n(_t),t2/=_t;for(;t2%Ve===V;)n(Ve),t2/=Ve;for(;t2%be===V;)n(be),t2/=be;for(let r2=0,i=_t+be;i*i<=t2;){for(;t2%i===V;)n(i),t2/=i;i+=Ms[r2],r2=r2+1&7}return t2>tt&&n(t2),e}const Bt=function(t2,e){let n=V,r2=tt,i=tt;if(null!=t2)if(void 0!==e){if("bigint"==typeof t2)n=t2;else{if(isNaN(t2))throw fe();if(t2%1!=0)throw Fr();n=BigInt(t2)}if("bigint"==typeof e)r2=e;else{if(isNaN(e))throw fe();if(e%1!=0)throw Fr();r2=BigInt(e)}i=n*r2}else if("object"==typeof t2){if("d"in t2&&"n"in t2)n=BigInt(t2.n),r2=BigInt(t2.d),"s"in t2&&(n*=BigInt(t2.s));else if(0 in t2)n=BigInt(t2[0]),1 in t2&&(r2=BigInt(t2[1]));else{if("bigint"!=typeof t2)throw fe();n=t2}i=n*r2}else if("number"==typeof t2){if(isNaN(t2))throw fe();if(t2<0&&(i=-tt,t2=-t2),t2%1==0)n=BigInt(t2);else{let u2=1,o=0,s=1,f=1,l=1,a2=1e7;for(t2>=1&&(u2=10**Math.floor(1+Math.log10(t2)),t2/=u2);s<=a2&&l<=a2;){let c=(o+f)/(s+l);if(t2===c){s+l<=a2?(n=o+f,r2=s+l):l>s?(n=f,r2=l):(n=o,r2=s);break}t2>c?(o+=f,s+=l):(f+=o,l+=s),s>a2?(n=f,r2=l):(n=o,r2=s)}n=BigInt(n)*BigInt(u2),r2=BigInt(r2)}}else if("string"==typeof t2){let u2=0,o=V,s=V,f=V,l=tt,a2=tt,c=t2.replace(/_/g,"").match(/\d+|./g);if(null===c)throw fe();if("-"===c[u2]?(i=-tt,u2++):"+"===c[u2]&&u2++,c.length===u2+1?s=oe(c[u2++],i):"."===c[u2+1]||"."===c[u2]?("."!==c[u2]&&(o=oe(c[u2++],i)),u2++,(u2+1===c.length||"("===c[u2+1]&&")"===c[u2+3]||"'"===c[u2+1]&&"'"===c[u2+3])&&(s=oe(c[u2],i),l=Xt**BigInt(c[u2].length),u2++),("("===c[u2]&&")"===c[u2+2]||"'"===c[u2]&&"'"===c[u2+2])&&(f=oe(c[u2+1],i),a2=Xt**BigInt(c[u2+1].length)-tt,u2+=3)):"/"===c[u2+1]||":"===c[u2+1]?(s=oe(c[u2],i),l=oe(c[u2+2],tt),u2+=3):"/"===c[u2+3]&&" "===c[u2+1]&&(o=oe(c[u2],i),s=oe(c[u2+2],i),l=oe(c[u2+4],tt),u2+=5),!(c.length<=u2))throw fe();r2=l*a2,i=n=f+r2*o+a2*s}else{if("bigint"!=typeof t2)throw fe();n=t2,i=t2,r2=tt}if(r2===V)throw Hn();U.s=i<V?-tt:tt,U.n=n<V?-n:n,U.d=r2<V?-r2:r2};function Ss(t2,e,n){let r2=tt,i=function(t2,e,n){let r2=tt;for(;e>V;t2=t2*t2%n,e>>=tt)e&tt&&(r2=r2*t2%n);return r2}(Xt,n,e);for(let u2=0;u2<300;u2++){if(r2===i)return BigInt(u2);r2=r2*Xt%e,i=i*Xt%e}return 0}function de(t2,e){if(!t2)return e;if(!e)return t2;for(;;){if(!(t2%=e))return e;if(!(e%=t2))return t2}}function Jt(t2,e){if(Bt(t2,e),!(this instanceof Jt))return dt(U.s*U.n,U.d);t2=de(U.d,U.n),this.s=U.s,this.n=U.n/t2,this.d=U.d/t2}const Hn=function(){return new Error("Division by Zero")},fe=function(){return new Error("Invalid argument")},Fr=function(){return new Error("Parameters must be integer")};Jt.prototype={s:tt,n:V,d:tt,abs:function(){return dt(this.n,this.d)},neg:function(){return dt(-this.s*this.n,this.d)},add:function(t2,e){return Bt(t2,e),dt(this.s*this.n*U.d+U.s*this.d*U.n,this.d*U.d)},sub:function(t2,e){return Bt(t2,e),dt(this.s*this.n*U.d-U.s*this.d*U.n,this.d*U.d)},mul:function(t2,e){return Bt(t2,e),dt(this.s*U.s*this.n*U.n,this.d*U.d)},div:function(t2,e){return Bt(t2,e),dt(this.s*U.s*this.n*U.d,this.d*U.n)},clone:function(){return dt(this.s*this.n,this.d)},mod:function(t2,e){if(void 0===t2)return dt(this.s*this.n%this.d,tt);if(Bt(t2,e),V===U.n*this.d)throw Hn();return dt(this.s*(U.d*this.n)%(U.n*this.d),U.d*this.d)},gcd:function(t2,e){return Bt(t2,e),dt(de(U.n,this.n)*de(U.d,this.d),U.d*this.d)},lcm:function(t2,e){return Bt(t2,e),U.n===V&&this.n===V?dt(V,tt):dt(U.n*this.n,de(U.n,this.n)*de(U.d,this.d))},inverse:function(){return dt(this.s*this.d,this.n)},pow:function(t2,e){if(Bt(t2,e),U.d===tt)return U.s<V?dt((this.s*this.d)**U.n,this.n**U.n):dt((this.s*this.n)**U.n,this.d**U.n);if(this.s<V)return null;let n=Me(this.n),r2=Me(this.d),i=tt,u2=tt;for(let o in n)if("1"!==o){if("0"===o){i=V;break}if(n[o]*=U.n,n[o]%U.d!==V)return null;n[o]/=U.d,i*=BigInt(o)**n[o]}for(let o in r2)if("1"!==o){if(r2[o]*=U.n,r2[o]%U.d!==V)return null;r2[o]/=U.d,u2*=BigInt(o)**r2[o]}return U.s<V?dt(u2,i):dt(i,u2)},log:function(t2,e){if(Bt(t2,e),this.s<=V||U.s<=V)return null;const n=/* @__PURE__ */Object.create(null),r2=Me(U.n),i=Me(U.d),u2=Me(this.n),o=Me(this.d);for(const l in i)r2[l]=(r2[l]||V)-i[l];for(const l in o)u2[l]=(u2[l]||V)-o[l];for(const l in r2)"1"!==l&&(n[l]=!0);for(const l in u2)"1"!==l&&(n[l]=!0);let s=null,f=null;for(const l in n){const a2=r2[l]||V,c=u2[l]||V;if(a2===V){if(c!==V)return null;continue}let D2=c,w=a2;const M=de(D2,w);if(D2/=M,w/=M,null===s&&null===f)s=D2,f=w;else if(D2*f!==s*w)return null}return null!==s&&null!==f?dt(s,f):null},equals:function(t2,e){return Bt(t2,e),this.s*this.n*U.d===U.s*U.n*this.d},lt:function(t2,e){return Bt(t2,e),this.s*this.n*U.d<U.s*U.n*this.d},lte:function(t2,e){return Bt(t2,e),this.s*this.n*U.d<=U.s*U.n*this.d},gt:function(t2,e){return Bt(t2,e),this.s*this.n*U.d>U.s*U.n*this.d},gte:function(t2,e){return Bt(t2,e),this.s*this.n*U.d>=U.s*U.n*this.d},compare:function(t2,e){Bt(t2,e);let n=this.s*this.n*U.d-U.s*U.n*this.d;return(V<n)-(n<V)},ceil:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)+(t2*this.n%this.d>V&&this.s>=V?tt:V),t2)},floor:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)-(t2*this.n%this.d>V&&this.s<V?tt:V),t2)},round:function(t2){return t2=Xt**BigInt(t2||0),dt(Kt(this.s*t2*this.n/this.d)+this.s*((this.s>=V?tt:V)+_t*(t2*this.n%this.d)>this.d?tt:V),t2)},roundTo:function(t2,e){Bt(t2,e);const n=this.n*U.d,r2=this.d*U.n,i=n%r2;let u2=Kt(n/r2);return i+i>=r2&&u2++,dt(this.s*u2*U.n,U.d)},divisible:function(t2,e){return Bt(t2,e),U.n!==V&&this.n*U.d%(U.n*this.d)===V},valueOf:function(){return Number(this.s*this.n)/Number(this.d)},toString:function(t2=15){let e=this.n,n=this.d,r2=function(t2,e){for(;e%_t===V;e/=_t);for(;e%be===V;e/=be);if(e===tt)return V;let n=Xt%e,r2=1;for(;n!==tt;r2++)if(n=n*Xt%e,r2>2e3)return V;return BigInt(r2)}(0,n),i=Ss(0,n,r2),u2=this.s<V?"-":"";if(u2+=Kt(e/n),e%=n,e*=Xt,e&&(u2+="."),r2){for(let o=i;o--;)u2+=Kt(e/n),e%=n,e*=Xt;u2+="(";for(let o=r2;o--;)u2+=Kt(e/n),e%=n,e*=Xt;u2+=")"}else for(let o=t2;e&&o--;)u2+=Kt(e/n),e%=n,e*=Xt;return u2},toFraction:function(t2=!1){let e=this.n,n=this.d,r2=this.s<V?"-":"";if(n===tt)r2+=e;else{const i=Kt(e/n);t2&&i>V&&(r2+=i,r2+=" ",e%=n),r2+=e,r2+="/",r2+=n}return r2},toLatex:function(t2=!1){let e=this.n,n=this.d,r2=this.s<V?"-":"";if(n===tt)r2+=e;else{const i=Kt(e/n);t2&&i>V&&(r2+=i,e%=n),r2+="\\frac{",r2+=e,r2+="}{",r2+=n,r2+="}"}return r2},toContinued:function(){let t2=this.n,e=this.d;const n=[];for(;e;){n.push(Kt(t2/e));const r2=t2%e;t2=e,e=r2}return n},simplify:function(t2=.001){const e=BigInt(Math.ceil(1/t2)),n=this.abs(),r2=n.toContinued();for(let i=1;i<r2.length;i++){let u2=dt(r2[i-1],tt);for(let s=i-2;s>=0;s--)u2=u2.inverse().add(r2[s]);let o=u2.sub(n);if(o.n*e<o.d)return u2.mul(this.s)}return this}};var Is=/* @__PURE__ */Ft("Fraction",[],()=>(Object.defineProperty(Jt,"name",{value:"Fraction"}),Jt.prototype.constructor=Jt,Jt.prototype.type="Fraction",Jt.prototype.isFraction=!0,Jt.prototype.toJSON=function(){return{mathjs:"Fraction",n:String(this.s*this.n),d:String(this.d)}},Jt.fromJSON=function(t2){return new Jt(t2)},Jt),{isClass:!0}),zs=/* @__PURE__ */Ft("Matrix",[],()=>{function t2(){if(!(this instanceof t2))throw new SyntaxError("Constructor must be called with the new operator")}return t2.prototype.type="Matrix",t2.prototype.isMatrix=!0,t2.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},t2.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},t2.prototype.create=function(e,n){throw new Error("Cannot invoke create on a Matrix interface")},t2.prototype.subset=function(e,n,r2){throw new Error("Cannot invoke subset on a Matrix interface")},t2.prototype.get=function(e){throw new Error("Cannot invoke get on a Matrix interface")},t2.prototype.set=function(e,n,r2){throw new Error("Cannot invoke set on a Matrix interface")},t2.prototype.resize=function(e,n){throw new Error("Cannot invoke resize on a Matrix interface")},t2.prototype.reshape=function(e,n){throw new Error("Cannot invoke reshape on a Matrix interface")},t2.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},t2.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},t2.prototype.map=function(e,n){throw new Error("Cannot invoke map on a Matrix interface")},t2.prototype.forEach=function(e){throw new Error("Cannot invoke forEach on a Matrix interface")},t2.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},t2.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},t2.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},t2.prototype.format=function(e){throw new Error("Cannot invoke format on a Matrix interface")},t2.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},t2},{isClass:!0});function Yn(t2,e,n){var i=new(0,t2.constructor)(2),u2="";if(n){if(n<1)throw new Error("size must be in greater than 0");if(!St(n))throw new Error("size must be an integer");if(t2.greaterThan(i.pow(n-1).sub(1))||t2.lessThan(i.pow(n-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(n-1,", 2^").concat(n-1,"-1]"));if(!t2.isInteger())throw new Error("Value must be an integer");t2.lessThan(0)&&(t2=t2.add(i.pow(n))),u2="i".concat(n)}switch(e){case 2:return"".concat(t2.toBinary()).concat(u2);case 8:return"".concat(t2.toOctal()).concat(u2);case 16:return"".concat(t2.toHexadecimal()).concat(u2);default:throw new Error("Base ".concat(e," not supported "))}}function Rs(t2,e){if("function"==typeof e)return e(t2);if(!t2.isFinite())return t2.isNaN()?"NaN":t2.gt(0)?"Infinity":"-Infinity";var{notation:n,precision:r2,wordSize:i}=Fi(e);switch(n){case"fixed":return function(t2,e){return t2.toFixed(e)}(t2,r2);case"exponential":return wr(t2,r2);case"engineering":return function(t2,e){var n=t2.e,r2=n%3==0?n:n<0?n-3-n%3:n-n%3,i=t2.mul(Math.pow(10,-r2)),u2=i.toPrecision(e);if(u2.includes("e")){u2=new(0,t2.constructor)(u2).toFixed()}return u2+"e"+(n>=0?"+":"")+r2.toString()}(t2,r2);case"bin":return Yn(t2,2,i);case"oct":return Yn(t2,8,i);case"hex":return Yn(t2,16,i);case"auto":var u2=Er(e?.lowerExp,-3),o=Er(e?.upperExp,5);if(t2.isZero())return"0";var f=t2.toSignificantDigits(r2),l=f.e;return(l>=u2&&l<o?f.toFixed():wr(t2,r2)).replace(/((\.\d*?)(0+))($|e)/,function(){var a2=arguments[2],c=arguments[4];return"."!==a2?a2+c:c});default:throw new Error('Unknown notation "'+n+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function wr(t2,e){return void 0!==e?t2.toExponential(e-1):t2.toExponential()}function Er(t2,e){return lt(t2)?t2:Nt(t2)?t2.toNumber():e}function Ot(t2,e){var n=function(t2,e){if("number"==typeof t2)return Un(t2,e);if(Nt(t2))return Rs(t2,e);if(function(t2){return t2&&"object"==typeof t2&&"bigint"==typeof t2.s&&"bigint"==typeof t2.n&&"bigint"==typeof t2.d||!1}(t2))return e&&"decimal"===e.fraction?t2.toString():"".concat(t2.s*t2.n,"/").concat(t2.d);if(Array.isArray(t2))return Ii(t2,e);if(jt(t2))return Ar(t2);if("function"==typeof t2)return t2.syntax?String(t2.syntax):"function";if(t2&&"object"==typeof t2){return"function"==typeof t2.format?t2.format(e):t2&&t2.toString(e)!=={}.toString()?t2.toString(e):"{"+Object.keys(t2).map(r2=>Ar(r2)+": "+Ot(t2[r2],e)).join(", ")+"}"}return String(t2)}(t2,e);return e&&"object"==typeof e&&"truncate"in e&&n.length>e.truncate?n.substring(0,e.truncate-3)+"...":n}function Ar(t2){for(var e=String(t2),n="",r2=0;r2<e.length;){var i=e.charAt(r2);n+=i in Cr?Cr[i]:i,r2++}return'"'+n+'"'}var Cr={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function Ii(t2,e){if(Array.isArray(t2)){for(var n="[",r2=t2.length,i=0;i<r2;i++)0!==i&&(n+=", "),n+=Ii(t2[i],e);return n+="]"}return Ot(t2,e)}function pt(t2,e,n){if(!(this instanceof pt))throw new SyntaxError("Constructor must be called with the new operator");this.actual=t2,this.expected=e,this.relation=n,this.message="Dimension mismatch ("+(Array.isArray(t2)?"["+t2.join(", ")+"]":t2)+" "+(this.relation||"!=")+" "+(Array.isArray(e)?"["+e.join(", ")+"]":e)+")",this.stack=(new Error).stack}function ge(t2,e,n){if(!(this instanceof ge))throw new SyntaxError("Constructor must be called with the new operator");this.index=t2,arguments.length<3?(this.min=0,this.max=e):(this.min=e,this.max=n),void 0!==this.min&&this.index<this.min?this.message="Index out of range ("+this.index+" < "+this.min+")":void 0!==this.max&&this.index>=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=(new Error).stack}function Lt(t2){for(var e=[];Array.isArray(t2);)e.push(t2.length),t2=t2[0];return e}function Oi(t2,e,n){var r2,i=t2.length;if(i!==e[n])throw new pt(i,e[n]);if(n<e.length-1){var u2=n+1;for(r2=0;r2<i;r2++){var o=t2[r2];if(!Array.isArray(o))throw new pt(e.length-1,e.length,"<");Oi(t2[r2],e,u2)}}else for(r2=0;r2<i;r2++)if(Array.isArray(t2[r2]))throw new pt(e.length+1,e.length,">")}function yr(t2,e){if(0===e.length){if(Array.isArray(t2))throw new pt(t2.length,0)}else Oi(t2,e,0)}function gt(t2,e){if(void 0!==t2){if(!lt(t2)||!St(t2))throw new TypeError("Index must be an integer (value: "+t2+")");if(t2<0||"number"==typeof e&&t2>=e)throw new ge(t2,e)}}function Br(t2,e,n){if(!Array.isArray(e))throw new TypeError("Array expected");if(0===e.length)throw new Error("Resizing to scalar is not supported");return e.forEach(function(i){if(!lt(i)||!St(i)||i<0)throw new TypeError("Invalid size, must contain positive integers (size: "+Ot(e)+")")}),(lt(t2)||Nt(t2))&&(t2=[t2]),Wn(t2,e,0,void 0!==n?n:0),t2}function Wn(t2,e,n,r2){var i,u2,o=t2.length,s=e[n],f=Math.min(o,s);if(t2.length=s,n<e.length-1){var l=n+1;for(i=0;i<f;i++)u2=t2[i],Array.isArray(u2)||(u2=[u2],t2[i]=u2),Wn(u2,e,l,r2);for(i=f;i<s;i++)u2=[],t2[i]=u2,Wn(u2,e,l,r2)}else{for(i=0;i<f;i++)for(;Array.isArray(t2[i]);)t2[i]=t2[i][0];for(i=f;i<s;i++)t2[i]=r2}}function Pi(t2,e){var n=function(t2){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Array.isArray(t2))return t2;if("boolean"!=typeof e)throw new TypeError("Boolean expected for second argument of flatten");var n=[];return e?i(t2):r2(t2),n;function r2(u2){for(var o=0;o<u2.length;o++){var s=u2[o];Array.isArray(s)?r2(s):n.push(s)}}function i(u2){if(Array.isArray(u2[0]))for(var o=0;o<u2.length;o++)i(u2[o]);else for(var s=0;s<u2.length;s++)n.push(u2[s])}}(t2,!0),r2=n.length;if(!Array.isArray(t2)||!Array.isArray(e))throw new TypeError("Array expected");if(0===e.length)throw new pt(0,r2,"!=");var i=zi(e=Jn(e,r2));if(r2!==i)throw new pt(i,r2,"!=");try{return function(t2,e){for(var r2,n=t2,i=e.length-1;i>0;i--){var u2=e[i];r2=[];for(var o=n.length/u2,s=0;s<o;s++)r2.push(n.slice(s*u2,(s+1)*u2));n=r2}return n}(n,e)}catch(u2){throw u2 instanceof pt?new pt(i,r2,"!="):u2}}function Jn(t2,e){var n=zi(t2),r2=t2.slice(),u2=t2.indexOf(-1);if(t2.indexOf(-1,u2+1)>=0)throw new Error("More than one wildcard in sizes");if(u2>=0){if(!(e%n===0))throw new Error("Could not replace wildcard, since "+e+" is no multiple of "+-n);r2[u2]=-e/n}return r2}function zi(t2){return t2.reduce((e,n)=>e*n,1)}function Ri(t2,e,n,r2){var i=r2||Lt(t2);if(n)for(var u2=0;u2<n;u2++)t2=[t2],i.unshift(1);for(t2=qi(t2,e,0);i.length<e;)i.push(1);return t2}function qi(t2,e,n){var r2,i;if(Array.isArray(t2)){var u2=n+1;for(r2=0,i=t2.length;r2<i;r2++)t2[r2]=qi(t2[r2],e,u2)}else for(var o=n;o<e;o++)t2=[t2];return t2}function kn(t2,e){for(var n,r2=0,i=0;i<t2.length;i++){var u2=t2[i],o=Array.isArray(u2);if(0===i&&o&&(r2=u2.length),o&&u2.length!==r2)return;var s=o?kn(u2,e):e(u2);if(void 0===n)n=s;else if(n!==s)return"mixed"}return n}function Yi(t2,e,n,r2){if(r2<n){if(t2.length!==e.length)throw new pt(t2.length,e.length);for(var i=[],u2=0;u2<t2.length;u2++)i[u2]=Yi(t2[u2],e[u2],n,r2+1);return i}return t2.concat(e)}function Zs(){var t2=Array.prototype.slice.call(arguments,0,-1),e=Array.prototype.slice.call(arguments,-1);if(1===t2.length)return t2[0];if(t2.length>1)return t2.slice(1).reduce(function(n,r2){return Yi(n,r2,e,0)},t2[0]);throw new Error("Wrong number of arguments in function concat")}function Ui(t2,e){for(var n=e.length,r2=t2.length,i=0;i<r2;i++){var u2=n-r2+i;if(t2[i]<e[u2]&&t2[i]>1||t2[i]>e[u2])throw new Error("shape mismatch: mismatch is found in arg with shape (".concat(t2,") not possible to broadcast dimension ").concat(r2," with size ").concat(t2[i]," to size ").concat(e[u2]))}}function _r(t2,e){var n=Lt(t2);if(Pe(n,e))return t2;Ui(n,e);var r2=function(){for(var t2=arguments.length,e=new Array(t2),n=0;n<t2;n++)e[n]=arguments[n];for(var r2=e.map(D2=>D2.length),i=Math.max(...r2),u2=new Array(i).fill(null),o=0;o<e.length;o++)for(var s=e[o],f=r2[o],l=0;l<f;l++){var a2=i-f+l;s[l]>u2[a2]&&(u2[a2]=s[l])}for(var c=0;c<e.length;c++)Ui(e[c],u2);return u2}(n,e),i=r2.length,u2=[...Array(i-n.length).fill(1),...n],o=function(t2){return fn([],t2)}(t2);n.length<i&&(n=Lt(o=Pi(o,u2)));for(var s=0;s<i;s++)n[s]<r2[s]&&(n=Lt(o=Vs(o,r2[s],s)));return o}function Vs(t2,e,n){return Zs(...Array(e).fill(t2),n)}function Xi(t2,e){if(!Array.isArray(t2))throw new Error("Array expected");var n=Lt(t2);if(e.length!==n.length)throw new pt(e.length,n.length);for(var r2=0;r2<e.length;r2++)gt(e[r2],n[r2]);return e.reduce((i,u2)=>i[u2],t2)}function dn(t2,e,n){var r2=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(Je.isTypedFunction(t2)){var i,s;if(r2)i=1;else{var u2=(e.isMatrix?e.size():Lt(e)).map(()=>0),o=e.isMatrix?e.get(u2):Xi(e,u2);i=function(t2,e,n,r2){for(var i=[e,n,r2],u2=3;u2>0;u2--){var o=i.slice(0,u2);if(null!==Je.resolve(t2,o))return u2}}(t2,o,u2,e)}if(e.isMatrix&&"mixed"!==e.dataType&&void 0!==e.dataType){var f=function(t2,e){var n=[];if(Object.entries(t2.signatures).forEach(r2=>{var[i,u2]=r2;i.split(",").length===e&&n.push(u2)}),1===n.length)return n[0]}(t2,i);s=void 0!==f?f:t2}else s=t2;return i>=1&&i<=3?{isUnary:1===i,fn:function(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return Mr(s,c.slice(0,i),n,t2.name)}}:{isUnary:!1,fn:function(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return Mr(s,c,n,t2.name)}}}return void 0===r2?{isUnary:Gs(t2),fn:t2}:{isUnary:r2,fn:t2}}function Gs(t2){if(1!==t2.length)return!1;var e=t2.toString();if(/arguments/.test(e))return!1;var n=e.match(/\(.*?\)/);return!/\.\.\./.test(n)}function Mr(t2,e,n,r2){try{return t2(...e)}catch(i){!function(t2,e,n,r2){var i;if(t2 instanceof TypeError&&"wrongType"===(null===(i=t2.data)||void 0===i?void 0:i.category)){var u2=[];throw u2.push("value: ".concat(me(e[0]))),e.length>=2&&u2.push("index: ".concat(me(e[1]))),e.length>=3&&u2.push("array: ".concat(me(e[2]))),new TypeError("Function ".concat(n," cannot apply callback arguments ")+"".concat(r2,"(").concat(u2.join(", "),") at index ").concat(JSON.stringify(e[1])))}throw new TypeError("Function ".concat(n," cannot apply callback arguments ")+"to function ".concat(r2,": ").concat(t2.message))}(i,e,n,r2)}}pt.prototype=new RangeError,pt.prototype.constructor=RangeError,pt.prototype.name="DimensionError",pt.prototype.isDimensionError=!0,ge.prototype=new RangeError,ge.prototype.constructor=RangeError,ge.prototype.name="IndexError",ge.prototype.isIndexError=!0;var ea=/* @__PURE__ */Ft("DenseMatrix",["Matrix"],t2=>{var{Matrix:e}=t2;function n(a2,c){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(c&&!jt(c))throw new Error("Invalid datatype: "+c);if(Mt(a2))"DenseMatrix"===a2.type?(this._data=Dt(a2._data),this._size=Dt(a2._size),this._datatype=c||a2._datatype):(this._data=a2.toArray(),this._size=a2.size(),this._datatype=c||a2._datatype);else if(a2&&At(a2.data)&&At(a2.size))this._data=a2.data,this._size=a2.size,yr(this._data,this._size),this._datatype=c||a2.datatype;else if(At(a2))this._data=l(a2),this._size=Lt(this._data),yr(this._data,this._size),this._datatype=c;else{if(a2)throw new TypeError("Unsupported type of data ("+me(a2)+")");this._data=[],this._size=[0],this._datatype=c}}function s(a2,c,D2){if(0===c.length){for(var w=a2._data;At(w);)w=w[0];return w}return a2._size=c.slice(0),a2._data=Br(a2._data,a2._size,D2),a2}function f(a2,c,D2){for(var w=a2._size.slice(0),M=!1;w.length<c.length;)w.push(0),M=!0;for(var h2=0,g=c.length;h2<g;h2++)c[h2]>w[h2]&&(w[h2]=c[h2],M=!0);M&&s(a2,w,D2)}function l(a2){return Mt(a2)?l(a2.valueOf()):At(a2)?a2.map(l):a2}return n.prototype=new e,n.prototype.createDenseMatrix=function(a2,c){return new n(a2,c)},Object.defineProperty(n,"name",{value:"DenseMatrix"}),n.prototype.constructor=n,n.prototype.type="DenseMatrix",n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return kn(this._data,me)},n.prototype.storage=function(){return"dense"},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(a2,c){return new n(a2,c)},n.prototype.subset=function(a2,c,D2){switch(arguments.length){case 1:return function(a2,c){if(!wn(c))throw new TypeError("Invalid index");var D2=c.isScalar();if(D2)return a2.get(c.min());var w=c.size();if(w.length!==a2._size.length)throw new pt(w.length,a2._size.length);for(var M=c.min(),h2=c.max(),g=0,p2=a2._size.length;g<p2;g++)gt(M[g],a2._size[g]),gt(h2[g],a2._size[g]);var E=new n([]),F=function(a2,c){var D2=c.size().length-1,w=Array(D2);return{data:M(a2),size:w};function M(h2){var g=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,p2=c.dimension(g);return w[g]=p2.size()[0],g<D2?p2.map(E=>(gt(E,h2.length),M(h2[E],g+1))).valueOf():p2.map(E=>(gt(E,h2.length),h2[E])).valueOf()}}(a2._data,c);return E._size=F.size,E._datatype=a2._datatype,E._data=F.data,E}(this,a2);case 2:case 3:return function(a2,c,D2,w){if(!c||!0!==c.isIndex)throw new TypeError("Invalid index");var g,M=c.size(),h2=c.isScalar();if(Mt(D2)?(g=D2.size(),D2=D2.valueOf()):g=Lt(D2),h2){if(0!==g.length)throw new TypeError("Scalar expected");a2.set(c.min(),D2,w)}else{if(!Pe(g,M))try{g=Lt(D2=0===g.length?_r([D2],M):_r(D2,M))}catch{}if(M.length<a2._size.length)throw new pt(M.length,a2._size.length,"<");if(g.length<M.length){for(var p2=0,E=0;1===M[p2]&&1===g[p2];)p2++;for(;1===M[p2];)E++,p2++;D2=Ri(D2,M.length,E,g)}if(!Pe(M,g))throw new pt(M,g,">");f(a2,c.max().map(function(A){return A+1}),w),function(a2,c,D2){var w=c.size().length-1;function M(h2,g){var p2=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,E=c.dimension(p2);p2<w?E.forEach((F,A)=>{gt(F,h2.length),M(h2[F],g[A[0]],p2+1)}):E.forEach((F,A)=>{gt(F,h2.length),h2[F]=g[A[0]]})}M(a2,D2)}(a2._data,c,D2)}return a2}(this,a2,c,D2);default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.get=function(a2){return Xi(this._data,a2)},n.prototype.set=function(a2,c,D2){if(!At(a2))throw new TypeError("Array expected");if(a2.length<this._size.length)throw new pt(a2.length,this._size.length,"<");var w,M,h2;f(this,a2.map(function(E){return E+1}),D2);var p2=this._data;for(w=0,M=a2.length-1;w<M;w++)gt(h2=a2[w],p2.length),p2=p2[h2];return gt(h2=a2[a2.length-1],p2.length),p2[h2]=c,this},n.prototype.resize=function(a2,c,D2){if(!He(a2))throw new TypeError("Array or Matrix expected");var w=a2.valueOf().map(h2=>Array.isArray(h2)&&1===h2.length?h2[0]:h2);return s(D2?this.clone():this,w,c)},n.prototype.reshape=function(a2,c){var D2=c?this.clone():this;D2._data=Pi(D2._data,a2);var w=D2._size.reduce((M,h2)=>M*h2);return D2._size=Jn(a2,w),D2},n.prototype.clone=function(){return new n({data:Dt(this._data),size:Dt(this._size),datatype:this._datatype})},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(a2){var c=arguments.length>2&&void 0!==arguments[2]&&arguments[2],D2=this,w=D2._size.length-1;if(w<0)return D2.clone();var M=dn(a2,D2,"map",c),h2=M.fn,g=D2.create(void 0,D2._datatype);if(g._size=D2._size,c||M.isUnary)return g._data=function m(C){var y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,B2=Array(C.length);if(y<w)for(var x=0;x<C.length;x++)B2[x]=m(C[x],y+1);else for(var T=0;T<C.length;T++)B2[T]=h2(C[T]);return B2}(D2._data),g;if(0===w){for(var p2=D2.valueOf(),E=Array(p2.length),F=0;F<p2.length;F++)E[F]=h2(p2[F],[F],D2);return g._data=E,g}var A=[];return g._data=function d2(C){var y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,B2=Array(C.length);if(y<w)for(var x=0;x<C.length;x++)A[y]=x,B2[x]=d2(C[x],y+1);else for(var T=0;T<C.length;T++)A[y]=T,B2[T]=h2(C[T],A.slice(),D2);return B2}(D2._data),g},n.prototype.forEach=function(a2){var c=arguments.length>2&&void 0!==arguments[2]&&arguments[2],D2=this,w=D2._size.length-1;if(!(w<0)){var M=dn(a2,D2,"map",c),h2=M.fn;if(c||M.isUnary)(function F(A){var d2=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(d2<w)for(var m=0;m<A.length;m++)F(A[m],d2+1);else for(var C=0;C<A.length;C++)h2(A[C])})(D2._data);else if(0!==w){var p2=[];!function E(A){var d2=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(d2<w)for(var m=0;m<A.length;m++)p2[d2]=m,E(A[m],d2+1);else for(var C=0;C<A.length;C++)p2[d2]=C,h2(A[C],p2.slice(),D2)}(D2._data)}else for(var g=0;g<D2._data.length;g++)h2(D2._data[g],[g],D2)}},n.prototype[Symbol.iterator]=function*(){var a2=this._size.length-1;if(!(a2<0)){if(0===a2){for(var c=0;c<this._data.length;c++)yield{value:this._data[c],index:[c]};return}var D2=[],w=function*(h2,g){if(g<a2)for(var p2=0;p2<h2.length;p2++)D2[g]=p2,yield*w(h2[p2],g+1);else for(var E=0;E<h2.length;E++)D2[g]=E,yield{value:h2[E],index:D2.slice()}};yield*w(this._data,0)}},n.prototype.rows=function(){var a2=[];if(2!==this.size().length)throw new TypeError("Rows can only be returned for a 2D matrix.");var D2=this._data;for(var w of D2)a2.push(new n([w],this._datatype));return a2},n.prototype.columns=function(){var a2=this,c=[],D2=this.size();if(2!==D2.length)throw new TypeError("Rows can only be returned for a 2D matrix.");for(var w=this._data,M=function(p2){var E=w.map(F=>[F[p2]]);c.push(new n(E,a2._datatype))},h2=0;h2<D2[1];h2++)M(h2);return c},n.prototype.toArray=function(){return Dt(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(a2){return Ot(this._data,a2)},n.prototype.toString=function(){return Ot(this._data)},n.prototype.toJSON=function(){return{mathjs:"DenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(a2){if(a2){if(Nt(a2)&&(a2=a2.toNumber()),!lt(a2)||!St(a2))throw new TypeError("The parameter k must be an integer number")}else a2=0;for(var c=a2>0?a2:0,D2=a2<0?-a2:0,w=this._size[0],M=this._size[1],h2=Math.min(w-D2,M-c),g=[],p2=0;p2<h2;p2++)g[p2]=this._data[p2+D2][p2+c];return new n({data:g,size:[h2],datatype:this._datatype})},n.diagonal=function(a2,c,D2,w){if(!At(a2))throw new TypeError("Array expected, size parameter");if(2!==a2.length)throw new Error("Only two dimensions matrix are supported");if(a2=a2.map(function(C){if(Nt(C)&&(C=C.toNumber()),!lt(C)||!St(C)||C<1)throw new Error("Size values must be positive integers");return C}),D2){if(Nt(D2)&&(D2=D2.toNumber()),!lt(D2)||!St(D2))throw new TypeError("The parameter k must be an integer number")}else D2=0;var F,M=D2>0?D2:0,h2=D2<0?-D2:0,g=a2[0],p2=a2[1],E=Math.min(g-h2,p2-M);if(At(c)){if(c.length!==E)throw new Error("Invalid value array length");F=function(y){return c[y]}}else if(Mt(c)){var A=c.size();if(1!==A.length||A[0]!==E)throw new Error("Invalid matrix length");F=function(y){return c.get([y])}}else F=function(){return c};w||(w=Nt(F(0))?F(0).mul(0):0);var d2=[];if(a2.length>0){d2=Br(d2,a2,w);for(var m=0;m<E;m++)d2[m+h2][m+M]=F(m)}return new n({data:d2,size:[g,p2]})},n.fromJSON=function(a2){return new n(a2)},n.prototype.swapRows=function(a2,c){if(!(lt(a2)&&St(a2)&<(c)&&St(c)))throw new Error("Row index must be positive integers");if(2!==this._size.length)throw new Error("Only two dimensional matrix is supported");return gt(a2,this._size[0]),gt(c,this._size[0]),n._swapRows(a2,c,this._data),this},n._swapRows=function(a2,c,D2){var w=D2[a2];D2[a2]=D2[c],D2[c]=w},n},{isClass:!0});function na(t2,e,n){return Mt(t2)?t2.map(r2=>e(r2),!1,!0):function(t2,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(0===t2.length)return[];if(n)return function u2(o){if(Array.isArray(o)){for(var s=o.length,f=Array(s),l=0;l<s;l++)f[l]=u2(o[l]);return f}return e(o)}(t2);var r2=[];return function i(o,s){if(Array.isArray(o)){for(var f=o.length,l=Array(f),a2=0;a2<f;a2++)r2[s]=a2,l[a2]=i(o[a2],s+1);return l}return e(o,r2.slice(0,s),t2)}(t2,0)}(t2,e,!0)}var $i="number, number";function Li(t2,e){return t2+e}function Zi(t2,e){return t2*e}Li.signature=$i,Zi.signature=$i;var ua=/* @__PURE__ */Ft("compareUnits",["typed"],t2=>{var{typed:e}=t2;return{"Unit, Unit":e.referToSelf(n=>(r2,i)=>{if(!r2.equalBase(i))throw new Error("Cannot compare units with different base");return e.find(n,[r2.valueType(),i.valueType()])(r2.value,i.value)})}}),mn="equalScalar",sa=/* @__PURE__ */Ft(mn,["typed","config"],t2=>{var{typed:e,config:n}=t2,r2=ua({typed:e});return e(mn,{"boolean, boolean":function(u2,o){return u2===o},"number, number":function(u2,o){return ln(u2,o,n.relTol,n.absTol)},"BigNumber, BigNumber":function(u2,o){return u2.eq(o)||function(t2,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e-9,r2=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n<=0)throw new Error("Relative tolerance must be greater than 0");if(r2<0)throw new Error("Absolute tolerance must be at least 0");return!t2.isNaN()&&!e.isNaN()&&(t2.isFinite()&&e.isFinite()?!!t2.eq(e)||t2.minus(e).abs().lte(t2.constructor.max(t2.constructor.max(t2.abs(),e.abs()).mul(n),r2)):t2.eq(e))}(u2,o,n.relTol,n.absTol)},"bigint, bigint":function(u2,o){return u2===o},"Fraction, Fraction":function(u2,o){return u2.equals(o)},"Complex, Complex":function(u2,o){return function(t2,e,n,r2){return ln(t2.re,e.re,n,r2)&&ln(t2.im,e.im,n,r2)}(u2,o,n.relTol,n.absTol)}},r2)});Ft(mn,["typed","config"],t2=>{var{typed:e,config:n}=t2;return e(mn,{"number, number":function(i,u2){return ln(i,u2,n.relTol,n.absTol)}})});var ca=/* @__PURE__ */Ft("SparseMatrix",["typed","equalScalar","Matrix"],t2=>{var{typed:e,equalScalar:n,Matrix:r2}=t2;function i(h2,g){if(!(this instanceof i))throw new SyntaxError("Constructor must be called with the new operator");if(g&&!jt(g))throw new Error("Invalid datatype: "+g);if(Mt(h2))!function(h2,g,p2){"SparseMatrix"===g.type?(h2._values=g._values?Dt(g._values):void 0,h2._index=Dt(g._index),h2._ptr=Dt(g._ptr),h2._size=Dt(g._size),h2._datatype=p2||g._datatype):o(h2,g.valueOf(),p2||g._datatype)}(this,h2,g);else if(h2&&At(h2.index)&&At(h2.ptr)&&At(h2.size))this._values=h2.values,this._index=h2.index,this._ptr=h2.ptr,this._size=h2.size,this._datatype=g||h2.datatype;else if(At(h2))o(this,h2,g);else{if(h2)throw new TypeError("Unsupported type of data ("+me(h2)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=g}}function o(h2,g,p2){h2._values=[],h2._index=[],h2._ptr=[],h2._datatype=p2;var E=g.length,F=0,A=n,d2=0;if(jt(p2)&&(A=e.find(n,[p2,p2])||n,d2=e.convert(0,p2)),E>0){var m=0;do{h2._ptr.push(h2._index.length);for(var C=0;C<E;C++){var y=g[C];if(At(y)){if(0===m&&F<y.length&&(F=y.length),m<y.length){var B2=y[m];A(B2,d2)||(h2._values.push(B2),h2._index.push(C))}}else 0===m&&F<1&&(F=1),A(y,d2)||(h2._values.push(y),h2._index.push(C))}m++}while(m<F)}h2._ptr.push(h2._index.length),h2._size=[E,F]}function l(h2,g,p2,E){if(p2-g===0)return p2;for(var F=g;F<p2;F++)if(E[F]===h2)return F;return g}function c(h2,g,p2,E,F,A,d2){F.splice(h2,0,E),A.splice(h2,0,g);for(var m=p2+1;m<d2.length;m++)d2[m]++}function D2(h2,g,p2,E){var F=E||0,A=n,d2=0;jt(h2._datatype)&&(A=e.find(n,[h2._datatype,h2._datatype])||n,d2=e.convert(0,h2._datatype),F=e.convert(F,h2._datatype));var B2,x,T,m=!A(F,d2),C=h2._size[0],y=h2._size[1];if(p2>y){for(x=y;x<p2;x++)if(h2._ptr[x]=h2._values.length,m)for(B2=0;B2<C;B2++)h2._values.push(F),h2._index.push(B2);h2._ptr[p2]=h2._values.length}else p2<y&&(h2._ptr.splice(p2+1,y-p2),h2._values.splice(h2._ptr[p2],h2._values.length),h2._index.splice(h2._ptr[p2],h2._index.length));if(y=p2,g>C){if(m){var q=0;for(x=0;x<y;x++){h2._ptr[x]=h2._ptr[x]+q,T=h2._ptr[x+1]+q;var Z=0;for(B2=C;B2<g;B2++,Z++)h2._values.splice(T+Z,0,F),h2._index.splice(T+Z,0,B2),q++}h2._ptr[y]=h2._values.length}}else if(g<C){var W=0;for(x=0;x<y;x++){h2._ptr[x]=h2._ptr[x]-W;var L=h2._ptr[x],z=h2._ptr[x+1]-W;for(T=L;T<z;T++)(B2=h2._index[T])>g-1&&(h2._values.splice(T,1),h2._index.splice(T,1),W++)}h2._ptr[x]=h2._values.length}return h2._size[0]=g,h2._size[1]=p2,h2}function M(h2,g,p2,E,F){var C,y,A=E[0],d2=E[1],m=[];for(C=0;C<A;C++)for(m[C]=[],y=0;y<d2;y++)m[C][y]=0;for(y=0;y<d2;y++)for(var B2=p2[y],x=p2[y+1],T=B2;T<x;T++)m[C=g[T]][y]=h2?F?Dt(h2[T]):h2[T]:1;return m}return i.prototype=new r2,i.prototype.createSparseMatrix=function(h2,g){return new i(h2,g)},Object.defineProperty(i,"name",{value:"SparseMatrix"}),i.prototype.constructor=i,i.prototype.type="SparseMatrix",i.prototype.isSparseMatrix=!0,i.prototype.getDataType=function(){return kn(this._values,me)},i.prototype.storage=function(){return"sparse"},i.prototype.datatype=function(){return this._datatype},i.prototype.create=function(h2,g){return new i(h2,g)},i.prototype.density=function(){var h2=this._size[0],g=this._size[1];return 0!==h2&&0!==g?this._index.length/(h2*g):0},i.prototype.subset=function(h2,g,p2){if(!this._values)throw new Error("Cannot invoke subset on a Pattern only matrix");switch(arguments.length){case 1:return function(h2,g){if(!wn(g))throw new TypeError("Invalid index");var p2=g.isScalar();if(p2)return h2.get(g.min());var E=g.size();if(E.length!==h2._size.length)throw new pt(E.length,h2._size.length);var F,A,d2,m,C=g.min(),y=g.max();for(F=0,A=h2._size.length;F<A;F++)gt(C[F],h2._size[F]),gt(y[F],h2._size[F]);var B2=h2._values,x=h2._index,T=h2._ptr,q=g.dimension(0),Z=g.dimension(1),W=[],L=[];q.forEach(function(G,j){L[G]=j[0],W[G]=!0});var z=B2?[]:void 0,J=[],k=[];return Z.forEach(function(G){for(k.push(J.length),d2=T[G],m=T[G+1];d2<m;d2++)F=x[d2],!0===W[F]&&(J.push(L[F]),z&&z.push(B2[d2]))}),k.push(J.length),new i({values:z,index:J,ptr:k,size:E,datatype:h2._datatype})}(this,h2);case 2:case 3:return function(h2,g,p2,E){if(!g||!0!==g.isIndex)throw new TypeError("Invalid index");var d2,F=g.size(),A=g.isScalar();if(Mt(p2)?(d2=p2.size(),p2=p2.toArray()):d2=Lt(p2),A){if(0!==d2.length)throw new TypeError("Scalar expected");h2.set(g.min(),p2,E)}else{if(1!==F.length&&2!==F.length)throw new pt(F.length,h2._size.length,"<");if(d2.length<F.length){for(var m=0,C=0;1===F[m]&&1===d2[m];)m++;for(;1===F[m];)C++,m++;p2=Ri(p2,F.length,C,d2)}if(!Pe(F,d2))throw new pt(F,d2,">");if(1===F.length){g.dimension(0).forEach(function(T,q){gt(T),h2.set([T,0],p2[q[0]],E)})}else{var B2=g.dimension(0),x=g.dimension(1);B2.forEach(function(T,q){gt(T),x.forEach(function(Z,W){gt(Z),h2.set([T,Z],p2[q[0]][W[0]],E)})})}}return h2}(this,h2,g,p2);default:throw new SyntaxError("Wrong number of arguments")}},i.prototype.get=function(h2){if(!At(h2))throw new TypeError("Array expected");if(h2.length!==this._size.length)throw new pt(h2.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var g=h2[0],p2=h2[1];gt(g,this._size[0]),gt(p2,this._size[1]);var E=l(g,this._ptr[p2],this._ptr[p2+1],this._index);return E<this._ptr[p2+1]&&this._index[E]===g?this._values[E]:0},i.prototype.set=function(h2,g,p2){if(!At(h2))throw new TypeError("Array expected");if(h2.length!==this._size.length)throw new pt(h2.length,this._size.length);if(!this._values)throw new Error("Cannot invoke set on a Pattern only matrix");var E=h2[0],F=h2[1],A=this._size[0],d2=this._size[1],m=n,C=0;jt(this._datatype)&&(m=e.find(n,[this._datatype,this._datatype])||n,C=e.convert(0,this._datatype)),(E>A-1||F>d2-1)&&(D2(this,Math.max(E+1,A),Math.max(F+1,d2),p2),A=this._size[0],d2=this._size[1]),gt(E,A),gt(F,d2);var y=l(E,this._ptr[F],this._ptr[F+1],this._index);return y<this._ptr[F+1]&&this._index[y]===E?m(g,C)?function(h2,g,p2,E,F){p2.splice(h2,1),E.splice(h2,1);for(var A=g+1;A<F.length;A++)F[A]--}(y,F,this._values,this._index,this._ptr):this._values[y]=g:m(g,C)||c(y,E,F,g,this._values,this._index,this._ptr),this},i.prototype.resize=function(h2,g,p2){if(!He(h2))throw new TypeError("Array or Matrix expected");var E=h2.valueOf().map(A=>Array.isArray(A)&&1===A.length?A[0]:A);if(2!==E.length)throw new Error("Only two dimensions matrix are supported");return E.forEach(function(A){if(!lt(A)||!St(A)||A<0)throw new TypeError("Invalid size, must contain positive integers (size: "+Ot(E)+")")}),D2(p2?this.clone():this,E[0],E[1],g)},i.prototype.reshape=function(h2,g){if(!At(h2))throw new TypeError("Array expected");if(2!==h2.length)throw new Error("Sparse matrices can only be reshaped in two dimensions");h2.forEach(function(G){if(!lt(G)||!St(G)||G<=-2||0===G)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+Ot(h2)+")")});var p2=this._size[0]*this._size[1];if(p2!==(h2=Jn(h2,p2))[0]*h2[1])throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var F=g?this.clone():this;if(this._size[0]===h2[0]&&this._size[1]===h2[1])return F;for(var A=[],d2=0;d2<F._ptr.length;d2++)for(var m=0;m<F._ptr[d2+1]-F._ptr[d2];m++)A.push(d2);for(var C=F._values.slice(),y=F._index.slice(),B2=0;B2<F._index.length;B2++){var x=y[B2],T=A[B2],q=x*F._size[1]+T;A[B2]=q%h2[1],y[B2]=Math.floor(q/h2[1])}F._values.length=0,F._index.length=0,F._ptr.length=h2[1]+1,F._size=h2.slice();for(var Z=0;Z<F._ptr.length;Z++)F._ptr[Z]=0;for(var W=0;W<C.length;W++){var L=y[W],z=A[W],J=C[W];c(l(L,F._ptr[z],F._ptr[z+1],F._index),L,z,J,F._values,F._index,F._ptr)}return F},i.prototype.clone=function(){return new i({values:this._values?Dt(this._values):void 0,index:Dt(this._index),ptr:Dt(this._ptr),size:Dt(this._size),datatype:this._datatype})},i.prototype.size=function(){return this._size.slice(0)},i.prototype.map=function(h2,g){if(!this._values)throw new Error("Cannot invoke map on a Pattern only matrix");var p2=this,E=this._size[0],F=this._size[1],A=dn(h2,p2,"map");return function(h2,g,p2,E,F,A,d2){var m=[],C=[],y=[],B2=n,x=0;jt(h2._datatype)&&(B2=e.find(n,[h2._datatype,h2._datatype])||n,x=e.convert(0,h2._datatype));for(var T=function(ot,wt,vt){var mt=A(ot,wt,vt);B2(mt,x)||(m.push(mt),C.push(wt))},q=E;q<=F;q++){y.push(m.length);var Z=h2._ptr[q],W=h2._ptr[q+1];if(d2)for(var L=Z;L<W;L++){var z=h2._index[L];z>=g&&z<=p2&&T(h2._values[L],z-g,q-E)}else{for(var J={},k=Z;k<W;k++){J[h2._index[k]]=h2._values[k]}for(var j=g;j<=p2;j++){T(j in J?J[j]:0,j-g,q-E)}}}return y.push(m.length),new i({values:m,index:C,ptr:y,size:[p2-g+1,F-E+1]})}(this,0,E-1,0,F-1,function(C,y,B2){return A.fn(C,[y,B2],p2)},g)},i.prototype.forEach=function(h2,g){if(!this._values)throw new Error("Cannot invoke forEach on a Pattern only matrix");for(var E=this._size[0],F=this._size[1],A=dn(h2,this,"forEach"),d2=0;d2<F;d2++){var m=this._ptr[d2],C=this._ptr[d2+1];if(g)for(var y=m;y<C;y++){var B2=this._index[y];A.fn(this._values[y],[B2,d2],this)}else{for(var x={},T=m;T<C;T++){x[this._index[T]]=this._values[T]}for(var Z=0;Z<E;Z++){var W=Z in x?x[Z]:0;A.fn(W,[Z,d2],this)}}}},i.prototype[Symbol.iterator]=function*(){if(!this._values)throw new Error("Cannot iterate a Pattern only matrix");for(var h2=this._size[1],g=0;g<h2;g++)for(var p2=this._ptr[g],E=this._ptr[g+1],F=p2;F<E;F++){var A=this._index[F];yield{value:this._values[F],index:[A,g]}}},i.prototype.toArray=function(){return M(this._values,this._index,this._ptr,this._size,!0)},i.prototype.valueOf=function(){return M(this._values,this._index,this._ptr,this._size,!1)},i.prototype.format=function(h2){for(var g=this._size[0],p2=this._size[1],E=this.density(),F="Sparse Matrix ["+Ot(g,h2)+" x "+Ot(p2,h2)+"] density: "+Ot(E,h2)+"\n",A=0;A<p2;A++)for(var d2=this._ptr[A],m=this._ptr[A+1],C=d2;C<m;C++){F+="\n ("+Ot(this._index[C],h2)+", "+Ot(A,h2)+") ==> "+(this._values?Ot(this._values[C],h2):"X")}return F},i.prototype.toString=function(){return Ot(this.toArray())},i.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},i.prototype.diagonal=function(h2){if(h2){if(Nt(h2)&&(h2=h2.toNumber()),!lt(h2)||!St(h2))throw new TypeError("The parameter k must be an integer number")}else h2=0;var g=h2>0?h2:0,p2=h2<0?-h2:0,E=this._size[0],F=this._size[1],A=Math.min(E-p2,F-g),d2=[],m=[],C=[];C[0]=0;for(var y=g;y<F&&d2.length<A;y++)for(var B2=this._ptr[y],x=this._ptr[y+1],T=B2;T<x;T++){var q=this._index[T];if(q===y-g+p2){d2.push(this._values[T]),m[d2.length-1]=q-p2;break}}return C.push(d2.length),new i({values:d2,index:m,ptr:C,size:[A,1]})},i.fromJSON=function(h2){return new i(h2)},i.diagonal=function(h2,g,p2,E,F){if(!At(h2))throw new TypeError("Array expected, size parameter");if(2!==h2.length)throw new Error("Only two dimensions matrix are supported");if(h2=h2.map(function(G){if(Nt(G)&&(G=G.toNumber()),!lt(G)||!St(G)||G<1)throw new Error("Size values must be positive integers");return G}),p2){if(Nt(p2)&&(p2=p2.toNumber()),!lt(p2)||!St(p2))throw new TypeError("The parameter k must be an integer number")}else p2=0;var A=n,d2=0;jt(F)&&(A=e.find(n,[F,F])||n,d2=e.convert(0,F));var T,m=p2>0?p2:0,C=p2<0?-p2:0,y=h2[0],B2=h2[1],x=Math.min(y-C,B2-m);if(At(g)){if(g.length!==x)throw new Error("Invalid value array length");T=function(j){return g[j]}}else if(Mt(g)){var q=g.size();if(1!==q.length||q[0]!==x)throw new Error("Invalid matrix length");T=function(j){return g.get([j])}}else T=function(){return g};for(var Z=[],W=[],L=[],z=0;z<B2;z++){L.push(Z.length);var J=z-m;if(J>=0&&J<x){var k=T(J);A(k,d2)||(W.push(J+C),Z.push(k))}}return L.push(Z.length),new i({values:Z,index:W,ptr:L,size:[y,B2]})},i.prototype.swapRows=function(h2,g){if(!(lt(h2)&&St(h2)&<(g)&&St(g)))throw new Error("Row index must be positive integers");if(2!==this._size.length)throw new Error("Only two dimensional matrix is supported");return gt(h2,this._size[0]),gt(g,this._size[0]),i._swapRows(h2,g,this._size[1],this._values,this._index,this._ptr),this},i._forEachRow=function(h2,g,p2,E,F){for(var A=E[h2],d2=E[h2+1],m=A;m<d2;m++)F(p2[m],g[m])},i._swapRows=function(h2,g,p2,E,F,A){for(var d2=0;d2<p2;d2++){var m=A[d2],C=A[d2+1],y=l(h2,m,C,F),B2=l(g,m,C,F);if(y<C&&B2<C&&F[y]===h2&&F[B2]===g){if(E){var x=E[y];E[y]=E[B2],E[B2]=x}}else if(y<C&&F[y]===h2&&(B2>=C||F[B2]!==g)){var T=E?E[y]:void 0;F.splice(B2,0,g),E&&E.splice(B2,0,T),F.splice(B2<=y?y+1:y,1),E&&E.splice(B2<=y?y+1:y,1)}else if(B2<C&&F[B2]===g&&(y>=C||F[y]!==h2)){var q=E?E[B2]:void 0;F.splice(y,0,h2),E&&E.splice(y,0,q),F.splice(y<=B2?B2+1:B2,1),E&&E.splice(y<=B2?B2+1:B2,1)}}},i},{isClass:!0}),ha=/* @__PURE__ */Ft("matrix",["typed","Matrix","DenseMatrix","SparseMatrix"],t2=>{var{typed:e,Matrix:n,DenseMatrix:r2,SparseMatrix:i}=t2;return e("matrix",{"":function(){return u2([])},string:function(s){return u2([],s)},"string, string":function(s,f){return u2([],s,f)},Array:function(s){return u2(s)},Matrix:function(s){return u2(s,s.storage())},"Array | Matrix, string":u2,"Array | Matrix, string, string":u2});function u2(o,s,f){if("dense"===s||"default"===s||void 0===s)return new r2(o,f);if("sparse"===s)return new i(o,f);throw new TypeError("Unknown matrix type "+JSON.stringify(s)+".")}}),xr="addScalar",pa=/* @__PURE__ */Ft(xr,["typed"],t2=>{var{typed:e}=t2;return e(xr,{"number, number":Li,"Complex, Complex":function(r2,i){return r2.add(i)},"BigNumber, BigNumber":function(r2,i){return r2.plus(i)},"bigint, bigint":function(r2,i){return r2+i},"Fraction, Fraction":function(r2,i){return r2.add(i)},"Unit, Unit":e.referToSelf(n=>(r2,i)=>{if(null===r2.value||void 0===r2.value)throw new Error("Parameter x contains a unit with undefined value");if(null===i.value||void 0===i.value)throw new Error("Parameter y contains a unit with undefined value");if(!r2.equalBase(i))throw new Error("Units do not match");var u2=r2.clone();return u2.value=e.find(n,[u2.valueType(),i.valueType()])(u2.value,i.value),u2.fixPrefix=!1,u2})})}),ga=/* @__PURE__ */Ft("matAlgo11xS0s",["typed","equalScalar"],t2=>{var{typed:e,equalScalar:n}=t2;return function(i,u2,o,s){var f=i._values,l=i._index,a2=i._ptr,c=i._size,D2=i._datatype;if(!f)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h2,w=c[0],M=c[1],g=n,p2=0,E=o;"string"==typeof D2&&(h2=D2,g=e.find(n,[h2,h2]),p2=e.convert(0,h2),u2=e.convert(u2,h2),E=e.find(o,[h2,h2]));for(var F=[],A=[],d2=[],m=0;m<M;m++){d2[m]=A.length;for(var C=a2[m],y=a2[m+1],B2=C;B2<y;B2++){var x=l[B2],T=s?E(u2,f[B2]):E(f[B2],u2);g(T,p2)||(A.push(x),F.push(T))}}return d2[M]=A.length,i.createSparseMatrix({values:F,index:A,ptr:d2,size:[w,M],datatype:h2})}}),wa=/* @__PURE__ */Ft("matAlgo14xDs",["typed"],t2=>{var{typed:e}=t2;return function(i,u2,o,s){var c,f=i._data,l=i._size,a2=i._datatype,D2=o;"string"==typeof a2&&(c=a2,u2=e.convert(u2,c),D2=e.find(o,[c,c]));var w=l.length>0?n(D2,0,l,l[0],f,u2,s):[];return i.createDenseMatrix({data:w,size:Dt(l),datatype:c})};function n(r2,i,u2,o,s,f,l){var a2=[];if(i===u2.length-1)for(var c=0;c<o;c++)a2[c]=l?r2(f,s[c]):r2(s[c],f);else for(var D2=0;D2<o;D2++)a2[D2]=n(r2,i+1,u2,u2[i+1],s[D2],f,l);return a2}});function ve(t2,e,n,r2){if(!(this instanceof ve))throw new SyntaxError("Constructor must be called with the new operator");this.fn=t2,this.count=e,this.min=n,this.max=r2,this.message="Wrong number of arguments in function "+t2+" ("+e+" provided, "+n+(null!=r2?"-"+r2:"")+" expected)",this.stack=(new Error).stack}ve.prototype=new Error,ve.prototype.constructor=Error,ve.prototype.name="ArgumentsError",ve.prototype.isArgumentsError=!0;var Ca=/* @__PURE__ */Ft("multiplyScalar",["typed"],t2=>{var{typed:e}=t2;return e("multiplyScalar",{"number, number":Zi,"Complex, Complex":function(r2,i){return r2.mul(i)},"BigNumber, BigNumber":function(r2,i){return r2.times(i)},"bigint, bigint":function(r2,i){return r2*i},"Fraction, Fraction":function(r2,i){return r2.mul(i)},"number | Fraction | BigNumber | Complex, Unit":(n,r2)=>r2.multiply(n),"Unit, number | Fraction | BigNumber | Complex | Unit":(n,r2)=>n.multiply(r2)})}),Sr="multiply",Ba=/* @__PURE__ */Ft(Sr,["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],t2=>{var{typed:e,matrix:n,addScalar:r2,multiplyScalar:i,equalScalar:u2,dot:o}=t2,s=ga({typed:e,equalScalar:u2}),f=wa({typed:e});function l(d2,m){switch(d2.length){case 1:switch(m.length){case 1:if(d2[0]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(d2[0]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+d2[0]+") must match Matrix rows ("+m[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+m.length+" dimensions)")}break;case 2:switch(m.length){case 1:if(d2[1]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+d2[1]+") must match Vector length ("+m[0]+")");break;case 2:if(d2[1]!==m[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+d2[1]+") must match Matrix B rows ("+m[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+m.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+d2.length+" dimensions)")}}function c(d2,m){if("dense"!==m.storage())throw new Error("Support for SparseMatrix not implemented");return function(d2,m){var L,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._size,q=m._datatype||m.getDataType(),Z=y[0],W=T[1],z=r2,J=i;B2&&q&&B2===q&&"string"==typeof B2&&"mixed"!==B2&&(L=B2,z=e.find(r2,[L,L]),J=e.find(i,[L,L]));for(var k=[],G=0;G<W;G++){for(var j=J(C[0],x[0][G]),rt=1;rt<Z;rt++)j=z(j,J(C[rt],x[rt][G]));k[G]=j}return d2.createDenseMatrix({data:k,size:[W],datatype:B2===d2._datatype&&q===m._datatype?L:void 0})}(d2,m)}var w=e("_multiplyMatrixVector",{"DenseMatrix, any":function(d2,m){var W,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._datatype||m.getDataType(),q=y[0],Z=y[1],L=r2,z=i;B2&&T&&B2===T&&"string"==typeof B2&&"mixed"!==B2&&(W=B2,L=e.find(r2,[W,W]),z=e.find(i,[W,W]));for(var J=[],k=0;k<q;k++){for(var G=C[k],j=z(G[0],x[0]),rt=1;rt<Z;rt++)j=L(j,z(G[rt],x[rt]));J[k]=j}return d2.createDenseMatrix({data:J,size:[q],datatype:B2===d2._datatype&&T===m._datatype?W:void 0})},"SparseMatrix, any":function(d2,m){var C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType();if(!C)throw new Error("Cannot multiply Pattern only Matrix times Dense Matrix");var k,T=m._data,q=m._datatype||m.getDataType(),Z=d2._size[0],W=m._size[0],L=[],z=[],J=[],G=r2,j=i,rt=u2,et=0;x&&q&&x===q&&"string"==typeof x&&"mixed"!==x&&(k=x,G=e.find(r2,[k,k]),j=e.find(i,[k,k]),rt=e.find(u2,[k,k]),et=e.convert(0,k));var ot=[],wt=[];J[0]=0;for(var vt=0;vt<W;vt++){var mt=T[vt];if(!rt(mt,et))for(var ht=B2[vt],zt=B2[vt+1],st=ht;st<zt;st++){var it=y[st];wt[it]?ot[it]=G(ot[it],j(mt,C[st])):(wt[it]=!0,z.push(it),ot[it]=j(mt,C[st]))}}for(var Zt=z.length,xt=0;xt<Zt;xt++){var at=z[xt];L[xt]=ot[at]}return J[1]=z.length,d2.createSparseMatrix({values:L,index:z,ptr:J,size:[Z,1],datatype:x===d2._datatype&&q===m._datatype?k:void 0})}}),M=e("_multiplyMatrixMatrix",{"DenseMatrix, DenseMatrix":function(d2,m){var z,C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._data,T=m._size,q=m._datatype||m.getDataType(),Z=y[0],W=y[1],L=T[1],J=r2,k=i;B2&&q&&B2===q&&"string"==typeof B2&&"mixed"!==B2&&"mixed"!==B2&&(z=B2,J=e.find(r2,[z,z]),k=e.find(i,[z,z]));for(var G=[],j=0;j<Z;j++){var rt=C[j];G[j]=[];for(var et=0;et<L;et++){for(var ot=k(rt[0],x[0][et]),wt=1;wt<W;wt++)ot=J(ot,k(rt[wt],x[wt][et]));G[j][et]=ot}}return d2.createDenseMatrix({data:G,size:[Z,L],datatype:B2===d2._datatype&&q===m._datatype?z:void 0})},"DenseMatrix, SparseMatrix":function(d2,m){var C=d2._data,y=d2._size,B2=d2._datatype||d2.getDataType(),x=m._values,T=m._index,q=m._ptr,Z=m._size,W=m._datatype||void 0===m._data?m._datatype:m.getDataType();if(!x)throw new Error("Cannot multiply Dense Matrix times Pattern only Matrix");var J,L=y[0],z=Z[1],k=r2,G=i,j=u2,rt=0;B2&&W&&B2===W&&"string"==typeof B2&&"mixed"!==B2&&(J=B2,k=e.find(r2,[J,J]),G=e.find(i,[J,J]),j=e.find(u2,[J,J]),rt=e.convert(0,J));for(var et=[],ot=[],wt=[],vt=m.createSparseMatrix({values:et,index:ot,ptr:wt,size:[L,z],datatype:B2===d2._datatype&&W===m._datatype?J:void 0}),mt=0;mt<z;mt++){wt[mt]=ot.length;var ht=q[mt],zt=q[mt+1];if(zt>ht)for(var st=0,it=0;it<L;it++){for(var Zt=it+1,xt=void 0,at=ht;at<zt;at++){var yt=T[at];st!==Zt?(xt=G(C[it][yt],x[at]),st=Zt):xt=k(xt,G(C[it][yt],x[at]))}st===Zt&&!j(xt,rt)&&(ot.push(it),et.push(xt))}}return wt[z]=ot.length,vt},"SparseMatrix, DenseMatrix":function(d2,m){var C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType();if(!C)throw new Error("Cannot multiply Pattern only Matrix times Dense Matrix");var z,T=m._data,q=m._datatype||m.getDataType(),Z=d2._size[0],W=m._size[0],L=m._size[1],J=r2,k=i,G=u2,j=0;x&&q&&x===q&&"string"==typeof x&&"mixed"!==x&&(z=x,J=e.find(r2,[z,z]),k=e.find(i,[z,z]),G=e.find(u2,[z,z]),j=e.convert(0,z));for(var rt=[],et=[],ot=[],wt=d2.createSparseMatrix({values:rt,index:et,ptr:ot,size:[Z,L],datatype:x===d2._datatype&&q===m._datatype?z:void 0}),vt=[],mt=[],ht=0;ht<L;ht++){ot[ht]=et.length;for(var zt=ht+1,st=0;st<W;st++){var it=T[st][ht];if(!G(it,j))for(var Zt=B2[st],xt=B2[st+1],at=Zt;at<xt;at++){var yt=y[at];mt[yt]!==zt?(mt[yt]=zt,et.push(yt),vt[yt]=k(it,C[at])):vt[yt]=J(vt[yt],k(it,C[at]))}}for(var Wt=ot[ht],ie=et.length,ue=Wt;ue<ie;ue++){var Fe=et[ue];rt[ue]=vt[Fe]}}return ot[L]=et.length,wt},"SparseMatrix, SparseMatrix":function(d2,m){var k,C=d2._values,y=d2._index,B2=d2._ptr,x=d2._datatype||void 0===d2._data?d2._datatype:d2.getDataType(),T=m._values,q=m._index,Z=m._ptr,W=m._datatype||void 0===m._data?m._datatype:m.getDataType(),L=d2._size[0],z=m._size[1],J=C&&T,G=r2,j=i;x&&W&&x===W&&"string"==typeof x&&"mixed"!==x&&(k=x,G=e.find(r2,[k,k]),j=e.find(i,[k,k]));for(var ht,zt,st,it,Zt,xt,at,yt,rt=J?[]:void 0,et=[],ot=[],wt=d2.createSparseMatrix({values:rt,index:et,ptr:ot,size:[L,z],datatype:x===d2._datatype&&W===m._datatype?k:void 0}),vt=J?[]:void 0,mt=[],Wt=0;Wt<z;Wt++){ot[Wt]=et.length;var ie=Wt+1;for(Zt=Z[Wt],xt=Z[Wt+1],it=Zt;it<xt;it++)if(yt=q[it],J)for(zt=B2[yt],st=B2[yt+1],ht=zt;ht<st;ht++)mt[at=y[ht]]!==ie?(mt[at]=ie,et.push(at),vt[at]=j(T[it],C[ht])):vt[at]=G(vt[at],j(T[it],C[ht]));else for(zt=B2[yt],st=B2[yt+1],ht=zt;ht<st;ht++)mt[at=y[ht]]!==ie&&(mt[at]=ie,et.push(at));if(J)for(var ue=ot[Wt],Fe=et.length,we=ue;we<Fe;we++){var Mn=et[we];rt[we]=vt[Mn]}}return ot[z]=et.length,wt}});return e(Sr,i,{"Array, Array":e.referTo("Matrix, Matrix",d2=>(m,C)=>{l(Lt(m),Lt(C));var y=d2(n(m),n(C));return Mt(y)?y.valueOf():y}),"Matrix, Matrix":function(m,C){var y=m.size(),B2=C.size();return l(y,B2),1===y.length?1===B2.length?function(d2,m,C){if(0===C)throw new Error("Cannot multiply two empty vectors");return o(d2,m)}(m,C,y[0]):c(m,C):1===B2.length?w(m,C):M(m,C)},"Matrix, Array":e.referTo("Matrix,Matrix",d2=>(m,C)=>d2(m,n(C))),"Array, Matrix":e.referToSelf(d2=>(m,C)=>d2(n(m,C.storage()),C)),"SparseMatrix, any":function(m,C){return s(m,C,i,!1)},"DenseMatrix, any":function(m,C){return f(m,C,i,!1)},"any, SparseMatrix":function(m,C){return s(C,m,i,!0)},"any, DenseMatrix":function(m,C){return f(C,m,i,!0)},"Array, any":function(m,C){return f(n(m),C,i,!1).valueOf()},"any, Array":function(m,C){return f(n(C),m,i,!0).valueOf()},"any, any":i,"any, any, ...any":e.referToSelf(d2=>(m,C,y)=>{for(var B2=d2(m,C),x=0;x<y.length;x++)B2=d2(B2,y[x]);return B2})})}),Ma=/* @__PURE__ */Ft("conj",["typed"],t2=>{var{typed:e}=t2;return e("conj",{"number | BigNumber | Fraction":n=>n,Complex:n=>n.conjugate(),Unit:e.referToSelf(n=>r2=>new r2.constructor(n(r2.toNumeric()),r2.formatUnits())),"Array | Matrix":e.referToSelf(n=>r2=>na(r2,n))})});var Pr,Sa=/* @__PURE__ */Ft("size",["typed","config","?matrix"],t2=>{var{typed:e,config:n,matrix:r2}=t2;return e("size",{Matrix:function(u2){return u2.create(u2.size(),"number")},Array:Lt,string:function(u2){return"Array"===n.matrix?[u2.length]:r2([u2.length],"dense","number")},"number | Complex | BigNumber | Unit | boolean | null":function(u2){return"Array"===n.matrix?[]:r2?r2([],"dense","number"):function(){throw new Error('No "matrix" implementation available')}()}})}),Ir="transpose",ba=/* @__PURE__ */Ft(Ir,["typed","matrix"],t2=>{var{typed:e,matrix:n}=t2;return e(Ir,{Array:o=>r2(n(o)).valueOf(),Matrix:r2,any:Dt});function r2(o){var f,s=o.size();switch(s.length){case 1:f=o.clone();break;case 2:var l=s[0],a2=s[1];if(0===a2)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+Ot(s)+")");switch(o.storage()){case"dense":f=function(o,s,f){for(var c,l=o._data,a2=[],D2=0;D2<f;D2++){c=a2[D2]=[];for(var w=0;w<s;w++)c[w]=Dt(l[w][D2])}return o.createDenseMatrix({data:a2,size:[f,s],datatype:o._datatype})}(o,l,a2);break;case"sparse":f=function(o,s,f){for(var l=o._values,a2=o._index,c=o._ptr,D2=l?[]:void 0,w=[],M=[],h2=[],g=0;g<s;g++)h2[g]=0;var p2,E,F;for(p2=0,E=a2.length;p2<E;p2++)h2[a2[p2]]++;for(var A=0,d2=0;d2<s;d2++)M.push(A),A+=h2[d2],h2[d2]=M[d2];for(M.push(A),F=0;F<f;F++)for(var m=c[F],C=c[F+1],y=m;y<C;y++){var B2=h2[a2[y]]++;w[B2]=F,l&&(D2[B2]=Dt(l[y]))}return o.createSparseMatrix({values:D2,index:w,ptr:M,size:[f,s],datatype:o._datatype})}(o,l,a2)}break;default:throw new RangeError("Matrix must be a vector or two dimensional (size: "+Ot(s)+")")}return f}}),Gn={createMatrixClass:zs},Wi={MatrixDependencies:Gn,createDenseMatrixClass:ea},re={BigNumberDependencies:{createBigNumberClass:ws},ComplexDependencies:{createComplexClass:Bs},DenseMatrixDependencies:Wi,FractionDependencies:{createFractionClass:Is},createTyped:Co},Vi={typedDependencies:re,createEqualScalar:sa},Hi={typedDependencies:re,createAddScalar:pa},_n={DenseMatrixDependencies:Wi,MatrixDependencies:Gn,SparseMatrixDependencies:{MatrixDependencies:Gn,equalScalarDependencies:Vi,typedDependencies:re,createSparseMatrixClass:ca},typedDependencies:re,createMatrix:ha},Ji={typedDependencies:re,createMultiplyScalar:Ca},$a={addScalarDependencies:Hi,dotDependencies:{addScalarDependencies:Hi,conjDependencies:{typedDependencies:re,createConj:Ma},multiplyScalarDependencies:Ji,sizeDependencies:{matrixDependencies:_n,typedDependencies:re,createSize:Sa},typedDependencies:re,createDot:/* @__PURE__ */Ft("dot",["typed","addScalar","multiplyScalar","conj","size"],t2=>{var{typed:e,addScalar:n,multiplyScalar:r2,conj:i,size:u2}=t2;return e("dot",{"Array | DenseMatrix, Array | DenseMatrix":function(a2,c){var D2=o(a2,c),w=Mt(a2)?a2._data:a2,M=Mt(a2)?a2._datatype||a2.getDataType():void 0,h2=Mt(c)?c._data:c,g=Mt(c)?c._datatype||c.getDataType():void 0,p2=2===l(a2).length,E=2===l(c).length,F=n,A=r2;if(M&&g&&M===g&&"string"==typeof M&&"mixed"!==M){var d2=M;F=e.find(n,[d2,d2]),A=e.find(r2,[d2,d2])}if(!p2&&!E){for(var m=A(i(w[0]),h2[0]),C=1;C<D2;C++)m=F(m,A(i(w[C]),h2[C]));return m}if(!p2&&E){for(var y=A(i(w[0]),h2[0][0]),B2=1;B2<D2;B2++)y=F(y,A(i(w[B2]),h2[B2][0]));return y}if(p2&&!E){for(var x=A(i(w[0][0]),h2[0]),T=1;T<D2;T++)x=F(x,A(i(w[T][0]),h2[T]));return x}if(p2&&E){for(var q=A(i(w[0][0]),h2[0][0]),Z=1;Z<D2;Z++)q=F(q,A(i(w[Z][0]),h2[Z][0]));return q}},"SparseMatrix, SparseMatrix":function(a2,c){o(a2,c);for(var D2=a2._index,w=a2._values,M=c._index,h2=c._values,g=0,p2=n,E=r2,F=0,A=0;F<D2.length&&A<M.length;){var d2=D2[F],m=M[A];d2<m?F++:d2>m?A++:d2===m&&(g=p2(g,E(w[F],h2[A])),F++,A++)}return g}});function o(a2,c){var M,h2,D2=l(a2),w=l(c);if(1===D2.length)M=D2[0];else{if(2!==D2.length||1!==D2[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+D2.join(", ")+")");M=D2[0]}if(1===w.length)h2=w[0];else{if(2!==w.length||1!==w[1])throw new RangeError("Expected a column vector, instead got a matrix of size ("+w.join(", ")+")");h2=w[0]}if(M!==h2)throw new RangeError("Vectors must have equal length ("+M+" != "+h2+")");if(0===M)throw new RangeError("Cannot calculate the dot product of empty vectors");return M}function l(a2){return Mt(a2)?a2.size():u2(a2)}})},equalScalarDependencies:Vi,matrixDependencies:_n,multiplyScalarDependencies:Ji,typedDependencies:re,createMultiply:Ba},La={matrixDependencies:_n,typedDependencies:re,createTranspose:ba},on={exports:{}};const Va=/* @__PURE__ */qr(function(){if(Pr)return on.exports;function t2(){}return Pr=1,t2.prototype={on:function(e,n,r2){var i=this.e||(this.e={});return(i[e]||(i[e]=[])).push({fn:n,ctx:r2}),this},once:function(e,n,r2){var i=this;function u2(){i.off(e,u2),n.apply(r2,arguments)}return u2._=n,this.on(e,u2,r2)},emit:function(e){for(var n=[].slice.call(arguments,1),r2=((this.e||(this.e={}))[e]||[]).slice(),i=0,u2=r2.length;i<u2;i++)r2[i].fn.apply(r2[i].ctx,n);return this},off:function(e,n){var r2=this.e||(this.e={}),i=r2[e],u2=[];if(i&&n)for(var o=0,s=i.length;o<s;o++)i[o].fn!==n&&i[o].fn._!==n&&u2.push(i[o]);return u2.length?r2[e]=u2:delete r2[e],this}},on.exports=t2,on.exports.TinyEmitter=t2,on.exports}());function Ja(t2,e,n,r2){function u2(p2,E,F){var A;if(F.wrap&&"function"==typeof E&&(E=function(p2){var E=function(){for(var A=[],d2=0,m=arguments.length;d2<m;d2++){var C=arguments[d2];A[d2]=C&&C.valueOf()}return p2.apply(n,A)};return p2.transform&&(E.transform=p2.transform),E}(E)),function(p2){return"function"==typeof p2&&"string"==typeof p2.signature}(E)&&(E=t2(p2,{[E.signature]:E})),t2.isTypedFunction(n[p2])&&t2.isTypedFunction(E))return E=F.override?t2(p2,E.signatures):t2(n[p2],E),n[p2]=E,delete r2[p2],o(p2,E),void n.emit("import",p2,function(){return E});var d2=void 0!==n[p2],m=null===(A=n.Unit)||void 0===A?void 0:A.isValuelessUnit(p2);if(!d2&&!m||F.override)return n[p2]=E,delete r2[p2],o(p2,E),void n.emit("import",p2,function(){return E});if(!F.silent)throw new Error('Cannot import "'+p2+'": already exists')}function o(p2,E){E&&"function"==typeof E.transform?(n.expression.transform[p2]=E.transform,w(p2)&&(n.expression.mathWithTransform[p2]=E.transform)):(delete n.expression.transform[p2],w(p2)&&(n.expression.mathWithTransform[p2]=E))}function s(p2){delete n.expression.transform[p2],w(p2)?n.expression.mathWithTransform[p2]=n[p2]:delete n.expression.mathWithTransform[p2]}function l(p2,E){var F,A,d2=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p2.fn;if(d2.includes("."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(d2));var m=h2(p2)?n.expression.transform:n,C=d2 in n.expression.transform,y=kt(m,d2)?m[d2]:void 0,B2=function(){var W={};p2.dependencies.map(vi).forEach(z=>{if(z.includes("."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(z));"math"===z?W.math=n:"mathWithTransform"===z?W.mathWithTransform=n.expression.mathWithTransform:"classes"===z?W.classes=n:W[z]=n[z]});var L=/* @__PURE__ */p2(W);if(L&&"function"==typeof L.transform)throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with export const path = "expression.transform"');if(void 0===y||E.override)return L;if(t2.isTypedFunction(y)&&t2.isTypedFunction(L))return t2(y,L);if(E.silent)return y;throw new Error('Cannot import "'+d2+'": already exists')},x=null!==(F=null===(A=p2.meta)||void 0===A?void 0:A.formerly)&&void 0!==F?F:"",T=h2(p2)||function(p2){return!(p2.fn.includes(".")||kt(g,p2.fn)||p2.meta&&p2.meta.isClass)}(p2),q=n.expression.mathWithTransform;p2.meta&&!1===p2.meta.lazy?(m[d2]=B2(),x&&(m[x]=m[d2]),y&&C?(s(d2),x&&s(x)):T&&(ye(q,d2,()=>m[d2]),x&&ye(q,x,()=>m[d2]))):(ye(m,d2,B2),x&&ye(m,x,B2),y&&C?(s(d2),x&&s(x)):T&&(ye(q,d2,()=>m[d2]),x&&ye(q,x,()=>m[d2]))),r2[d2]=p2,n.emit("import",d2,B2)}function a2(p2){return"function"==typeof p2||"number"==typeof p2||"string"==typeof p2||"boolean"==typeof p2||null===p2||Fn(p2)||gn(p2)||Nt(p2)||vn(p2)||Mt(p2)||Array.isArray(p2)}function w(p2){return!kt(g,p2)}function h2(p2){return void 0!==p2&&void 0!==p2.meta&&!0===p2.meta.isTransformFunction||!1}var g={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return function(p2,E){var F=arguments.length;if(1!==F&&2!==F)throw new ve("import",F,1,2);E||(E={});var d2={};for(var m in function A(y,B2,x){if(Array.isArray(B2))B2.forEach(Z=>A(y,Z));else if(qe(B2)||function(p2){return"object"==typeof p2&&"Module"===p2[Symbol.toStringTag]}(B2))for(var T in B2)kt(B2,T)&&A(y,B2[T],T);else if(We(B2)||void 0!==x){var q=We(B2)?h2(B2)?B2.fn+".transform":B2.fn:x;if(kt(y,q)&&y[q]!==B2&&!E.silent)throw new Error('Cannot import "'+q+'" twice');y[q]=B2}else if(!E.silent)throw new TypeError("Factory, Object, or Array expected")}(d2,p2),d2)if(kt(d2,m)){var C=d2[m];if(We(C))l(C,E);else if(a2(C))u2(m,C,E);else if(!E.silent)throw new TypeError("Factory, Object, or Array expected")}}}const{matrix:zr,transpose:ka,multiply:Ne}=function ki(t2,e){var n=fn({},Yr,e);if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r2=function(t2){var e=new Va;return t2.on=e.on.bind(e),t2.off=e.off.bind(e),t2.once=e.once.bind(e),t2.emit=e.emit.bind(e),t2}({isNumber:lt,isComplex:gn,isBigNumber:Nt,isBigInt:Ur,isFraction:vn,isUnit:Fn,isString:jt,isArray:At,isMatrix:Mt,isCollection:He,isDenseMatrix:Xr,isSparseMatrix:$r,isRange:Lr,isIndex:wn,isBoolean:Zr,isResultSet:Wr,isHelp:Vr,isFunction:Hr,isDate:Jr,isRegExp:kr,isObject:qe,isMap:Ie,isPartitionedMap:ao,isObjectWrappingMap:fo,isNull:Gr,isUndefined:Qr,isAccessorNode:Kr,isArrayNode:jr,isAssignmentNode:ti,isBlockNode:ei,isConditionalNode:ni,isConstantNode:ri,isFunctionAssignmentNode:ii,isFunctionNode:ui,isIndexNode:oi,isNode:si,isObjectNode:ai,isOperatorNode:fi,isParenthesisNode:ci,isRangeNode:li,isRelationalNode:hi,isSymbolNode:Di,isChain:pi});r2.config=po(n,r2.emit),r2.expression={transform:{},mathWithTransform:{config:r2.config}};var s={};function f(){for(var a2=arguments.length,c=new Array(a2),D2=0;D2<a2;D2++)c[D2]=arguments[D2];return r2.typed.apply(r2.typed,c)}f.isTypedFunction=Je.isTypedFunction;var l=Ja(f,0,r2,s);return r2.import=l,r2.on("config",()=>{Object.values(s).forEach(a2=>{a2&&a2.meta&&a2.meta.recreateOnConfigChange&&l(a2,{override:!0})})}),r2.create=ki.bind(null,t2),r2.factory=Ft,r2.import(Object.values(lo(t2))),r2.ArgumentsError=ve,r2.DimensionError=pt,r2.IndexError=ge,r2}({matrixDependencies:_n,multiplyDependencies:$a,transposeDependencies:La}),Qa=t2=>{const e=Vu(t2,1/0),n=(t2=>{const e=[];for(let r2=0;r2<t2.length-1;r2++)e.push([t2[r2+1][0]-t2[r2][0],t2[r2+1][1]-t2[r2][1]]);return[...new Set(e.map(r2=>Math.abs(Math.atan2(r2[1],r2[0])%(Math.PI/2))))].map(r2=>[[Math.cos(r2),Math.cos(r2-Math.PI/2)],[Math.cos(r2+Math.PI/2),Math.cos(r2)]])})(e),r2=n.map(p2=>{const E=zr(p2),F=ka(zr(e));return Ne(E,F).toArray()}),i=r2.map(p2=>{const E=p2;return[Math.min(...E[0]),Math.min(...E[1])]}),u2=r2.map(p2=>{const E=p2;return[Math.max(...E[0]),Math.max(...E[1])]}),o=i.map(p2=>p2[0]),s=i.map(p2=>p2[1]),f=u2.map(p2=>p2[0]),l=u2.map(p2=>p2[1]),c=o.map((p2,E)=>(f[E]-o[E])*(l[E]-s[E])).reduce((p2,E,F,A)=>E<A[p2]?F:p2,0),[D2,w]=[f[c],l[c]],[M,h2]=[o[c],s[c]],g=n[c];return[Ne([D2,h2],g),Ne([M,h2],g),Ne([M,w],g),Ne([D2,w],g),Ne([D2,h2],g)]};function quickselect(arr,k,left=0,right=arr.length-1,compare=defaultCompare){for(;right>left;){if(right-left>600){const n=right-left+1,m=k-left+1,z=Math.log(n),s=.5*Math.exp(2*z/3),sd=.5*Math.sqrt(z*s*(n-s)/n)*(m-n/2<0?-1:1);quickselect(arr,k,Math.max(left,Math.floor(k-m*s/n+sd)),Math.min(right,Math.floor(k+(n-m)*s/n+sd)),compare)}const t2=arr[k];let i=left,j=right;for(swap(arr,left,k),compare(arr[right],t2)>0&&swap(arr,left,right);i<j;){for(swap(arr,i,j),i++,j--;compare(arr[i],t2)<0;)i++;for(;compare(arr[j],t2)>0;)j--}0===compare(arr[left],t2)?swap(arr,left,j):(j++,swap(arr,j,right)),j<=k&&(left=j+1),k<=j&&(right=j-1)}}function swap(arr,i,j){const tmp=arr[i];arr[i]=arr[j],arr[j]=tmp}function defaultCompare(a2,b4){return a2<b4?-1:a2>b4?1:0}class RBush{constructor(maxEntries=9){this._maxEntries=Math.max(4,maxEntries),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(bbox2){let node=this.data;const result=[];if(!intersects$1(bbox2,node))return result;const toBBox=this.toBBox,nodesToSearch=[];for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],childBBox=node.leaf?toBBox(child):child;intersects$1(bbox2,childBBox)&&(node.leaf?result.push(child):contains(bbox2,childBBox)?this._all(child,result):nodesToSearch.push(child))}node=nodesToSearch.pop()}return result}collides(bbox2){let node=this.data;if(!intersects$1(bbox2,node))return!1;const nodesToSearch=[];for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],childBBox=node.leaf?this.toBBox(child):child;if(intersects$1(bbox2,childBBox)){if(node.leaf||contains(bbox2,childBBox))return!0;nodesToSearch.push(child)}}node=nodesToSearch.pop()}return!1}load(data){if(!data||!data.length)return this;if(data.length<this._minEntries){for(let i=0;i<data.length;i++)this.insert(data[i]);return this}let node=this._build(data.slice(),0,data.length-1,0);if(this.data.children.length)if(this.data.height===node.height)this._splitRoot(this.data,node);else{if(this.data.height<node.height){const tmpNode=this.data;this.data=node,node=tmpNode}this._insert(node,this.data.height-node.height-1,!0)}else this.data=node;return this}insert(item){return item&&this._insert(item,this.data.height-1),this}clear(){return this.data=createNode([]),this}remove(item,equalsFn){if(!item)return this;let node=this.data;const bbox2=this.toBBox(item),path=[],indexes=[];let i,parent,goingUp;for(;node||path.length;){if(node||(node=path.pop(),parent=path[path.length-1],i=indexes.pop(),goingUp=!0),node.leaf){const index2=findItem(item,node.children,equalsFn);if(-1!==index2)return node.children.splice(index2,1),path.push(node),this._condense(path),this}goingUp||node.leaf||!contains(node,bbox2)?parent?(i++,node=parent.children[i],goingUp=!1):node=null:(path.push(node),indexes.push(i),i=0,parent=node,node=node.children[0])}return this}toBBox(item){return item}compareMinX(a2,b4){return a2.minX-b4.minX}compareMinY(a2,b4){return a2.minY-b4.minY}toJSON(){return this.data}fromJSON(data){return this.data=data,this}_all(node,result){const nodesToSearch=[];for(;node;)node.leaf?result.push(...node.children):nodesToSearch.push(...node.children),node=nodesToSearch.pop();return result}_build(items,left,right,height){const N=right-left+1;let node,M=this._maxEntries;if(N<=M)return node=createNode(items.slice(left,right+1)),calcBBox(node,this.toBBox),node;height||(height=Math.ceil(Math.log(N)/Math.log(M)),M=Math.ceil(N/Math.pow(M,height-1))),node=createNode([]),node.leaf=!1,node.height=height;const N2=Math.ceil(N/M),N1=N2*Math.ceil(Math.sqrt(M));multiSelect(items,left,right,N1,this.compareMinX);for(let i=left;i<=right;i+=N1){const right2=Math.min(i+N1-1,right);multiSelect(items,i,right2,N2,this.compareMinY);for(let j=i;j<=right2;j+=N2){const right3=Math.min(j+N2-1,right2);node.children.push(this._build(items,j,right3,height-1))}}return calcBBox(node,this.toBBox),node}_chooseSubtree(bbox2,node,level,path){for(;path.push(node),!node.leaf&&path.length-1!==level;){let targetNode,minArea=1/0,minEnlargement=1/0;for(let i=0;i<node.children.length;i++){const child=node.children[i],area2=bboxArea(child),enlargement=enlargedArea(bbox2,child)-area2;enlargement<minEnlargement?(minEnlargement=enlargement,minArea=area2<minArea?area2:minArea,targetNode=child):enlargement===minEnlargement&&area2<minArea&&(minArea=area2,targetNode=child)}node=targetNode||node.children[0]}return node}_insert(item,level,isNode){const bbox2=isNode?item:this.toBBox(item),insertPath=[],node=this._chooseSubtree(bbox2,this.data,level,insertPath);for(node.children.push(item),extend(node,bbox2);level>=0&&insertPath[level].children.length>this._maxEntries;)this._split(insertPath,level),level--;this._adjustParentBBoxes(bbox2,insertPath,level)}_split(insertPath,level){const node=insertPath[level],M=node.children.length,m=this._minEntries;this._chooseSplitAxis(node,m,M);const splitIndex=this._chooseSplitIndex(node,m,M),newNode=createNode(node.children.splice(splitIndex,node.children.length-splitIndex));newNode.height=node.height,newNode.leaf=node.leaf,calcBBox(node,this.toBBox),calcBBox(newNode,this.toBBox),level?insertPath[level-1].children.push(newNode):this._splitRoot(node,newNode)}_splitRoot(node,newNode){this.data=createNode([node,newNode]),this.data.height=node.height+1,this.data.leaf=!1,calcBBox(this.data,this.toBBox)}_chooseSplitIndex(node,m,M){let index2,minOverlap=1/0,minArea=1/0;for(let i=m;i<=M-m;i++){const bbox1=distBBox(node,0,i,this.toBBox),bbox2=distBBox(node,i,M,this.toBBox),overlap=intersectionArea(bbox1,bbox2),area2=bboxArea(bbox1)+bboxArea(bbox2);overlap<minOverlap?(minOverlap=overlap,index2=i,minArea=area2<minArea?area2:minArea):overlap===minOverlap&&area2<minArea&&(minArea=area2,index2=i)}return index2||M-m}_chooseSplitAxis(node,m,M){const compareMinX=node.leaf?this.compareMinX:compareNodeMinX,compareMinY=node.leaf?this.compareMinY:compareNodeMinY;this._allDistMargin(node,m,M,compareMinX)<this._allDistMargin(node,m,M,compareMinY)&&node.children.sort(compareMinX)}_allDistMargin(node,m,M,compare){node.children.sort(compare);const toBBox=this.toBBox,leftBBox=distBBox(node,0,m,toBBox),rightBBox=distBBox(node,M-m,M,toBBox);let margin=bboxMargin(leftBBox)+bboxMargin(rightBBox);for(let i=m;i<M-m;i++){const child=node.children[i];extend(leftBBox,node.leaf?toBBox(child):child),margin+=bboxMargin(leftBBox)}for(let i=M-m-1;i>=m;i--){const child=node.children[i];extend(rightBBox,node.leaf?toBBox(child):child),margin+=bboxMargin(rightBBox)}return margin}_adjustParentBBoxes(bbox2,path,level){for(let i=level;i>=0;i--)extend(path[i],bbox2)}_condense(path){for(let siblings,i=path.length-1;i>=0;i--)0===path[i].children.length?i>0?(siblings=path[i-1].children,siblings.splice(siblings.indexOf(path[i]),1)):this.clear():calcBBox(path[i],this.toBBox)}}function findItem(item,items,equalsFn){if(!equalsFn)return items.indexOf(item);for(let i=0;i<items.length;i++)if(equalsFn(item,items[i]))return i;return-1}function calcBBox(node,toBBox){distBBox(node,0,node.children.length,toBBox,node)}function distBBox(node,k,p2,toBBox,destNode){destNode||(destNode=createNode(null)),destNode.minX=1/0,destNode.minY=1/0,destNode.maxX=-1/0,destNode.maxY=-1/0;for(let i=k;i<p2;i++){const child=node.children[i];extend(destNode,node.leaf?toBBox(child):child)}return destNode}function extend(a2,b4){return a2.minX=Math.min(a2.minX,b4.minX),a2.minY=Math.min(a2.minY,b4.minY),a2.maxX=Math.max(a2.maxX,b4.maxX),a2.maxY=Math.max(a2.maxY,b4.maxY),a2}function compareNodeMinX(a2,b4){return a2.minX-b4.minX}function compareNodeMinY(a2,b4){return a2.minY-b4.minY}function bboxArea(a2){return(a2.maxX-a2.minX)*(a2.maxY-a2.minY)}function bboxMargin(a2){return a2.maxX-a2.minX+(a2.maxY-a2.minY)}function enlargedArea(a2,b4){return(Math.max(b4.maxX,a2.maxX)-Math.min(b4.minX,a2.minX))*(Math.max(b4.maxY,a2.maxY)-Math.min(b4.minY,a2.minY))}function intersectionArea(a2,b4){const minX=Math.max(a2.minX,b4.minX),minY=Math.max(a2.minY,b4.minY),maxX=Math.min(a2.maxX,b4.maxX),maxY=Math.min(a2.maxY,b4.maxY);return Math.max(0,maxX-minX)*Math.max(0,maxY-minY)}function contains(a2,b4){return a2.minX<=b4.minX&&a2.minY<=b4.minY&&b4.maxX<=a2.maxX&&b4.maxY<=a2.maxY}function intersects$1(a2,b4){return b4.minX<=a2.maxX&&b4.minY<=a2.maxY&&b4.maxX>=a2.minX&&b4.maxY>=a2.minY}function createNode(children){return{children:children,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function multiSelect(arr,left,right,n,compare){const stack=[left,right];for(;stack.length;){if((right=stack.pop())-(left=stack.pop())<=n)continue;const mid=left+Math.ceil((right-left)/n/2)*n;quickselect(arr,mid,left,right,compare),stack.push(left,mid,mid,right)}}class TinyQueue2{constructor(data=[],compare=(a2,b4)=>a2<b4?-1:a2>b4?1:0){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos<halfLength;){let bestChild=1+(pos<<1);const right=bestChild+1;if(right<this.length&&compare(data[right],data[bestChild])<0&&(bestChild=right),compare(data[bestChild],item)>=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const pointInPolygon=/* @__PURE__ */getDefaultExportFromCjs(requirePointInPolygon());function sum(elen,e,flen,f,h2){let Q2,Qnew,hh,bvirt,enow=e[0],fnow=f[0],eindex=0,findex=0;fnow>enow==fnow>-enow?(Q2=enow,enow=e[++eindex]):(Q2=fnow,fnow=f[++findex]);let hindex=0;if(eindex<elen&&findex<flen)for(fnow>enow==fnow>-enow?(Qnew=enow+Q2,hh=Q2-(Qnew-enow),enow=e[++eindex]):(Qnew=fnow+Q2,hh=Q2-(Qnew-fnow),fnow=f[++findex]),Q2=Qnew,0!==hh&&(h2[hindex++]=hh);eindex<elen&&findex<flen;)fnow>enow==fnow>-enow?(Qnew=Q2+enow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(enow-bvirt),enow=e[++eindex]):(Qnew=Q2+fnow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(fnow-bvirt),fnow=f[++findex]),Q2=Qnew,0!==hh&&(h2[hindex++]=hh);for(;eindex<elen;)Qnew=Q2+enow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(enow-bvirt),enow=e[++eindex],Q2=Qnew,0!==hh&&(h2[hindex++]=hh);for(;findex<flen;)Qnew=Q2+fnow,bvirt=Qnew-Q2,hh=Q2-(Qnew-bvirt)+(fnow-bvirt),fnow=f[++findex],Q2=Qnew,0!==hh&&(h2[hindex++]=hh);return 0===Q2&&0!==hindex||(h2[hindex++]=Q2),hindex}function vec(n){return new Float64Array(n)}const B=vec(4),C1=vec(8),C2=vec(12),D=vec(16),u=vec(4);function orient2d(ax,ay,bx,by,cx,cy){const detleft=(ay-cy)*(bx-cx),detright=(ax-cx)*(by-cy),det=detleft-detright,detsum=Math.abs(detleft+detright);return Math.abs(det)>=33306690738754716e-32*detsum?det:-function(ax,ay,bx,by,cx,cy,detsum){let acxtail,acytail,bcxtail,bcytail,bvirt,c,ahi,alo,bhi,blo,_i2,_j,_0,s1,s0,t1,t0,u3;const acx=ax-cx,bcx=bx-cx,acy=ay-cy,bcy=by-cy;s1=acx*bcy,c=134217729*acx,ahi=c-(c-acx),alo=acx-ahi,c=134217729*bcy,bhi=c-(c-bcy),blo=bcy-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acy*bcx,c=134217729*acy,ahi=c-(c-acy),alo=acy-ahi,c=134217729*bcx,bhi=c-(c-bcx),blo=bcx-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,B[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,B[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,B[2]=_j-(u3-bvirt)+(_i2-bvirt),B[3]=u3;let det=function(elen,e){let Q2=e[0];for(let i=1;i<elen;i++)Q2+=e[i];return Q2}(4,B),errbound=22204460492503146e-32*detsum;if(det>=errbound||-det>=errbound)return det;if(bvirt=ax-acx,acxtail=ax-(acx+bvirt)+(bvirt-cx),bvirt=bx-bcx,bcxtail=bx-(bcx+bvirt)+(bvirt-cx),bvirt=ay-acy,acytail=ay-(acy+bvirt)+(bvirt-cy),bvirt=by-bcy,bcytail=by-(bcy+bvirt)+(bvirt-cy),0===acxtail&&0===acytail&&0===bcxtail&&0===bcytail)return det;if(errbound=11093356479670487e-47*detsum+33306690738754706e-32*Math.abs(det),det+=acx*bcytail+bcy*acxtail-(acy*bcxtail+bcx*acytail),det>=errbound||-det>=errbound)return det;s1=acxtail*bcy,c=134217729*acxtail,ahi=c-(c-acxtail),alo=acxtail-ahi,c=134217729*bcy,bhi=c-(c-bcy),blo=bcy-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acytail*bcx,c=134217729*acytail,ahi=c-(c-acytail),alo=acytail-ahi,c=134217729*bcx,bhi=c-(c-bcx),blo=bcx-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const C1len=sum(4,B,4,u,C1);s1=acx*bcytail,c=134217729*acx,ahi=c-(c-acx),alo=acx-ahi,c=134217729*bcytail,bhi=c-(c-bcytail),blo=bcytail-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acy*bcxtail,c=134217729*acy,ahi=c-(c-acy),alo=acy-ahi,c=134217729*bcxtail,bhi=c-(c-bcxtail),blo=bcxtail-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const C2len=sum(C1len,C1,4,u,C2);s1=acxtail*bcytail,c=134217729*acxtail,ahi=c-(c-acxtail),alo=acxtail-ahi,c=134217729*bcytail,bhi=c-(c-bcytail),blo=bcytail-bhi,s0=alo*blo-(s1-ahi*bhi-alo*bhi-ahi*blo),t1=acytail*bcxtail,c=134217729*acytail,ahi=c-(c-acytail),alo=acytail-ahi,c=134217729*bcxtail,bhi=c-(c-bcxtail),blo=bcxtail-bhi,t0=alo*blo-(t1-ahi*bhi-alo*bhi-ahi*blo),_i2=s0-t0,bvirt=s0-_i2,u[0]=s0-(_i2+bvirt)+(bvirt-t0),_j=s1+_i2,bvirt=_j-s1,_0=s1-(_j-bvirt)+(_i2-bvirt),_i2=_0-t1,bvirt=_0-_i2,u[1]=_0-(_i2+bvirt)+(bvirt-t1),u3=_j+_i2,bvirt=u3-_j,u[2]=_j-(u3-bvirt)+(_i2-bvirt),u[3]=u3;const Dlen=sum(C2len,C2,4,u,D);return D[Dlen-1]}(ax,ay,bx,by,cx,cy,detsum)}function concaveman(points,concavity,lengthThreshold){concavity=Math.max(0,void 0===concavity?2:concavity),lengthThreshold=lengthThreshold||0;const hull=function(points){let left=points[0],top=points[0],right=points[0],bottom=points[0];for(let i=0;i<points.length;i++){const p2=points[i];p2[0]<left[0]&&(left=p2),p2[0]>right[0]&&(right=p2),p2[1]<top[1]&&(top=p2),p2[1]>bottom[1]&&(bottom=p2)}const cull2=[left,top,right,bottom],filtered=cull2.slice();for(let i=0;i<points.length;i++)pointInPolygon(points[i],cull2)||filtered.push(points[i]);return function(points){points.sort(compareByX);const lower=[];for(let i=0;i<points.length;i++){for(;lower.length>=2&&cross(lower[lower.length-2],lower[lower.length-1],points[i])<=0;)lower.pop();lower.push(points[i])}const upper=[];for(let ii2=points.length-1;ii2>=0;ii2--){for(;upper.length>=2&&cross(upper[upper.length-2],upper[upper.length-1],points[ii2])<=0;)upper.pop();upper.push(points[ii2])}return upper.pop(),lower.pop(),lower.concat(upper)}(filtered)}(points),tree=new RBush(16);tree.toBBox=function(a2){return{minX:a2[0],minY:a2[1],maxX:a2[0],maxY:a2[1]}},tree.compareMinX=function(a2,b4){return a2[0]-b4[0]},tree.compareMinY=function(a2,b4){return a2[1]-b4[1]},tree.load(points);const queue=[];let last;for(let i=0;i<hull.length;i++){const p2=hull[i];tree.remove(p2),last=insertNode(p2,last),queue.push(last)}const segTree=new RBush(16);for(let i=0;i<queue.length;i++)segTree.insert(updateBBox(queue[i]));const sqConcavity=concavity*concavity,sqLenThreshold=lengthThreshold*lengthThreshold;for(;queue.length;){const node2=queue.shift(),a2=node2.p,b4=node2.next.p,sqLen=getSqDist(a2,b4);if(sqLen<sqLenThreshold)continue;const maxSqLen=sqLen/sqConcavity,p2=findCandidate(tree,node2.prev.p,a2,b4,node2.next.next.p,maxSqLen,segTree);p2&&Math.min(getSqDist(p2,a2),getSqDist(p2,b4))<=maxSqLen&&(queue.push(node2),queue.push(insertNode(p2,node2)),tree.remove(p2),segTree.remove(node2),segTree.insert(updateBBox(node2)),segTree.insert(updateBBox(node2.next)))}let node=last;const concave=[];do{concave.push(node.p),node=node.next}while(node!==last);return concave.push(node.p),concave}function findCandidate(tree,a2,b4,c,d2,maxDist,segTree){const queue=new TinyQueue2([],compareDist);let node=tree.data;for(;node;){for(let i=0;i<node.children.length;i++){const child=node.children[i],dist=node.leaf?sqSegDist(child,b4,c):sqSegBoxDist(b4,c,child);dist>maxDist||queue.push({node:child,dist:dist})}for(;queue.length&&!queue.peek().node.children;){const item=queue.pop(),p2=item.node,d0=sqSegDist(p2,a2,b4),d1=sqSegDist(p2,c,d2);if(item.dist<d0&&item.dist<d1&&noIntersections(b4,p2,segTree)&&noIntersections(c,p2,segTree))return p2}node=queue.pop(),node&&(node=node.node)}return null}function compareDist(a2,b4){return a2.dist-b4.dist}function sqSegBoxDist(a2,b4,bbox2){if(inside(a2,bbox2)||inside(b4,bbox2))return 0;const d1=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.maxX,bbox2.minY);if(0===d1)return 0;const d2=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.minY,bbox2.minX,bbox2.maxY);if(0===d2)return 0;const d3=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.maxX,bbox2.minY,bbox2.maxX,bbox2.maxY);if(0===d3)return 0;const d4=sqSegSegDist(a2[0],a2[1],b4[0],b4[1],bbox2.minX,bbox2.maxY,bbox2.maxX,bbox2.maxY);return 0===d4?0:Math.min(d1,d2,d3,d4)}function inside(a2,bbox2){return a2[0]>=bbox2.minX&&a2[0]<=bbox2.maxX&&a2[1]>=bbox2.minY&&a2[1]<=bbox2.maxY}function noIntersections(a2,b4,segTree){const minX=Math.min(a2[0],b4[0]),minY=Math.min(a2[1],b4[1]),maxX=Math.max(a2[0],b4[0]),maxY=Math.max(a2[1],b4[1]),edges=segTree.search({minX:minX,minY:minY,maxX:maxX,maxY:maxY});for(let i=0;i<edges.length;i++)if(intersects(edges[i].p,edges[i].next.p,a2,b4))return!1;return!0}function cross(p1,p2,p3){return orient2d(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1])}function intersects(p1,q1,p2,q2){return p1!==q2&&q1!==p2&&cross(p1,q1,p2)>0!=cross(p1,q1,q2)>0&&cross(p2,q2,p1)>0!=cross(p2,q2,q1)>0}function updateBBox(node){const p1=node.p,p2=node.next.p;return node.minX=Math.min(p1[0],p2[0]),node.minY=Math.min(p1[1],p2[1]),node.maxX=Math.max(p1[0],p2[0]),node.maxY=Math.max(p1[1],p2[1]),node}function insertNode(p2,prev){const node={p:p2,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return prev?(node.next=prev.next,node.prev=prev,prev.next.prev=node,prev.next=node):(node.prev=node,node.next=node),node}function getSqDist(p1,p2){const dx=p1[0]-p2[0],dy=p1[1]-p2[1];return dx*dx+dy*dy}function sqSegDist(p2,p1,p22){let x=p1[0],y=p1[1],dx=p22[0]-x,dy=p22[1]-y;if(0!==dx||0!==dy){const t2=((p2[0]-x)*dx+(p2[1]-y)*dy)/(dx*dx+dy*dy);t2>1?(x=p22[0],y=p22[1]):t2>0&&(x+=dx*t2,y+=dy*t2)}return dx=p2[0]-x,dy=p2[1]-y,dx*dx+dy*dy}function sqSegSegDist(x0,y0,x1,y1,x2,y2,x3,y3){const ux=x1-x0,uy=y1-y0,vx=x3-x2,vy=y3-y2,wx=x0-x2,wy=y0-y2,a2=ux*ux+uy*uy,b4=ux*vx+uy*vy,c=vx*vx+vy*vy,d2=ux*wx+uy*wy,e=vx*wx+vy*wy,D2=a2*c-b4*b4;let sN,tN,sD=D2,tD=D2;0===D2?(sN=0,sD=1,tN=e,tD=c):(sN=b4*e-c*d2,tN=a2*e-b4*d2,sN<0?(sN=0,tN=e,tD=c):sN>sD&&(sN=sD,tN=e+b4,tD=c)),tN<0?(tN=0,-d2<0?sN=0:-d2>a2?sN=sD:(sN=-d2,sD=a2)):tN>tD&&(tN=tD,-d2+b4<0?sN=0:-d2+b4>a2?sN=sD:(sN=-d2+b4,sD=a2));const sc=0===sN?0:sN/sD,tc=0===tN?0:tN/tD,dx=(1-tc)*x2+tc*x3-((1-sc)*x0+sc*x1),dy=(1-tc)*y2+tc*y3-((1-sc)*y0+sc*y1);return dx*dx+dy*dy}function compareByX(a2,b4){return a2[0]===b4[0]?a2[1]-b4[1]:a2[0]-b4[0]}function findRooms(lines,trajectory2,option){const{clone:clone2=!0,split:split=!0}=option??{};clone2&&(lines=lines.map(line=>line.clone())),split&&(lines=splitIntersectedLine(lines,0));const rooms=[],pool2=PointUtils.createPool(),psh=trajectory2?PointSpatialHash.from(Object.values(trajectory2).map(p2=>pool2.point.set(p2.x,p2.y))):void 0,maxiCircles=new MaxiCircles,center=pool2.point;return LineSegmentUtils.groupByPath(lines).forEach(group2=>{const removeSet=findDiscretePointLine2(group2,null,!0);lines=group2.filter(line=>!removeSet.has(line)&&!line.userData.isBayWindow);const circles=maxiCircles.miniCircle(lines).circles.filter(function(psh){return lines=>{const doubleLines=lines.filter(line=>WH.isDouble(line));if(WH.isPairing(doubleLines))return!1;const ply=Polygon.fromByLinePath(lines);return!psh||psh.queryPolygon(ply,"inside").length>0}}(psh));circles.map(p2=>Polygon.fromByLinePath(p2)).forEach((ploy,i)=>{const xList=[],yList=[];ploy.forEach(p2=>{xList.push(p2.x),yList.push(p2.y)});const minX=Math.min(...xList),maxX=Math.max(...xList),minY=Math.min(...yList),maxY=Math.max(...yList);center.set(.5*(maxX-minX)+minX,.5*(maxY-minY)+minY),rooms.push({lines:circles[i],ploy:ploy,center:center,uuid:uuid()})})}),pool2.freeAll(),rooms}function mergeAttributes(attributes){let TypedArray,itemSize,normalized,gpuType=-1,arrayLength=0;for(let i=0;i<attributes.length;++i){const attribute=attributes[i];if(void 0===TypedArray&&(TypedArray=attribute.array.constructor),TypedArray!==attribute.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(void 0===itemSize&&(itemSize=attribute.itemSize),itemSize!==attribute.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(void 0===normalized&&(normalized=attribute.normalized),normalized!==attribute.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(-1===gpuType&&(gpuType=attribute.gpuType),gpuType!==attribute.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;arrayLength+=attribute.count*itemSize}const array=new TypedArray(arrayLength),result=new BufferAttribute(array,itemSize,normalized);let offset=0;for(let i=0;i<attributes.length;++i){const attribute=attributes[i];if(attribute.isInterleavedBufferAttribute){const tupleOffset=offset/itemSize;for(let j=0,l=attribute.count;j<l;j++)for(let c=0;c<itemSize;c++){const value=attribute.getComponent(j,c);result.setComponent(j+tupleOffset,c,value)}}else array.set(attribute.array,offset);offset+=attribute.count*itemSize}return void 0!==gpuType&&(result.gpuType=gpuType),result}function toTrianglesDrawMode(geometry,drawMode){if(drawMode===TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),geometry;if(drawMode===TriangleFanDrawMode||drawMode===TriangleStripDrawMode){let index2=geometry.getIndex();if(null===index2){const indices=[],position=geometry.getAttribute("position");if(void 0===position)return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),geometry;for(let i=0;i<position.count;i++)indices.push(i);geometry.setIndex(indices),index2=geometry.getIndex()}const numberOfTriangles=index2.count-2,newIndices=[];if(drawMode===TriangleFanDrawMode)for(let i=1;i<=numberOfTriangles;i++)newIndices.push(index2.getX(0)),newIndices.push(index2.getX(i)),newIndices.push(index2.getX(i+1));else for(let i=0;i<numberOfTriangles;i++)i%2==0?(newIndices.push(index2.getX(i)),newIndices.push(index2.getX(i+1)),newIndices.push(index2.getX(i+2))):(newIndices.push(index2.getX(i+2)),newIndices.push(index2.getX(i+1)),newIndices.push(index2.getX(i)));newIndices.length/3!==numberOfTriangles&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const newGeometry=geometry.clone();return newGeometry.setIndex(newIndices),newGeometry.clearGroups(),newGeometry}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",drawMode),geometry}let globalScenario;const box3=new THREE.Box3,polygon=new Polygon;class SceneAutoGenerat{lines;itemList;z;scene=new THREE.Group;trajectory;angle=0;constructor(lines,itemList,z,trajectory2){this.lines=lines,this.itemList=itemList,this.z=z,this.trajectory=trajectory2,globalScenario=globalScenario??Scenario.Instance??new Scenario(new THREE.Scene,{},{},{});const vrLine=LineSegmentUtils.findDominantDirectionLine(lines);this.angle=-vrLine.direction().angleBetween(new Point(0,1),"angle","360")*(Math.PI/180)}async init(){await this.buildWall(),globalScenario.scene.add(this.scene),globalScenario.scene.traverse(child=>{child.updateWorldMatrix(!1,!1)})}createGeometryByLines(lines){const shape=new THREE.Shape;Polygon.fromByLinePath(lines,polygon),polygon.forEach((p2,i)=>0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y)),shape.closePath();return new THREE.ShapeGeometry(shape)}findRoom(lines){const queryLines=lines.filter(line=>line.userData.isDoor||line.userData.isPassageEntrance),{circles:circles}=MaxiCircles.instance.miniCircle(lines,{circleEdges:queryLines,side:Side.IN});return circles.map(circle=>[Polygon.fromByLinePath(circle),uuid()])}findByWindow(lines){return LineGroupType.getGroupsByType(lines,"bayWindow").map(lines2=>Polygon.fromByLines2(lines2))}findOutline(lines,type){if("closed-loop"===type){const set2=findDiscretePointLine(lines);lines=lines.filter(line=>!set2.has(line));const{circles:circles}=MaxiCircles.instance.miniCircle(lines,{side:Side.OUT});return circles.map(circle=>Polygon.fromByLinePath(circle))}const counterMap=new CounterMap;findDiscretePoint(this.lines).forEach(l=>counterMap.increment(l));const ls2=counterMap.getByCount(2);let removeSet=new Set(ls2);const points=this.lines.filter(line=>!removeSet.has(line)).filter(line=>!line.userData.isBayWindow&&!line.userData.miscellaneous).flatMap(line=>[...line.points,...LineSegmentUtils.sampleSegmentBydistance(line,.01)]);if(0===points.length)return[];const hull=concaveman(points.map(p2=>p2.toArray()),2);return[new Polygon(Point.fromByList(hull))]}buildPlane(lines,type,roomList){lines=splitIntersectedLine(lines.map(line=>line.clone()),0),PointUtils.adsorb(lines.flatMap(line=>line.points),1e-4);let rooms=roomList.length>0?roomList.map(i=>[i.ploy.clone(),i.uuid]):this.findRoom(lines),byWindows=this.findByWindow(lines),outCircles=this.findOutline(lines,type);rooms.forEach(([room])=>room.close());const group2=new THREE.Group,geometries=[];if(rooms.forEach(([polygon2,uuid2],j)=>{const geometry=this.createGeometryByLines(polygon2.toLines());geometries.push(geometry);const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_${j}`,mesh.userData.category="plane",mesh.userData.planeType="room",mesh.userData.uuid=uuid2,mesh.userData.area=polygon2.area(),mesh.userData.room=!0,group2.add(mesh)}),byWindows.forEach((polygon2,j)=>{const geometry=this.createGeometryByLines(polygon2.toLines());geometries.push(geometry);const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_飘窗_${j}`,mesh.userData.category="plane",mesh.userData.planeType="byWindow",mesh.userData.uuid=uuid(),mesh.userData.area=polygon2.area(),mesh.userData.room=!0,group2.add(mesh)}),outCircles.length){let brush1;if(geometries.length){const merged=function(geometries,useGroups=!1){const isIndexed=null!==geometries[0].index,attributesUsed=new Set(Object.keys(geometries[0].attributes)),morphAttributesUsed=new Set(Object.keys(geometries[0].morphAttributes)),attributes={},morphAttributes={},morphTargetsRelative=geometries[0].morphTargetsRelative,mergedGeometry=new BufferGeometry;let offset=0;for(let i=0;i<geometries.length;++i){const geometry=geometries[i];let attributesCount=0;if(isIndexed!==(null!==geometry.index))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const name in geometry.attributes){if(!attributesUsed.has(name))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+'. All geometries must have compatible attributes; make sure "'+name+'" attribute exists among all geometries, or in none of them.'),null;void 0===attributes[name]&&(attributes[name]=[]),attributes[name].push(geometry.attributes[name]),attributesCount++}if(attributesCount!==attributesUsed.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". Make sure all geometries have the same number of attributes."),null;if(morphTargetsRelative!==geometry.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const name in geometry.morphAttributes){if(!morphAttributesUsed.has(name))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". .morphAttributes must be consistent throughout all geometries."),null;void 0===morphAttributes[name]&&(morphAttributes[name]=[]),morphAttributes[name].push(geometry.morphAttributes[name])}if(useGroups){let count;if(isIndexed)count=geometry.index.count;else{if(void 0===geometry.attributes.position)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+i+". The geometry must have either an index or a position attribute"),null;count=geometry.attributes.position.count}mergedGeometry.addGroup(offset,count,i),offset+=count}}if(isIndexed){let indexOffset=0;const mergedIndex=[];for(let i=0;i<geometries.length;++i){const index2=geometries[i].index;for(let j=0;j<index2.count;++j)mergedIndex.push(index2.getX(j)+indexOffset);indexOffset+=geometries[i].attributes.position.count}mergedGeometry.setIndex(mergedIndex)}for(const name in attributes){const mergedAttribute=mergeAttributes(attributes[name]);if(!mergedAttribute)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+name+" attribute."),null;mergedGeometry.setAttribute(name,mergedAttribute)}for(const name in morphAttributes){const numMorphTargets=morphAttributes[name][0].length;if(0===numMorphTargets)break;mergedGeometry.morphAttributes=mergedGeometry.morphAttributes||{},mergedGeometry.morphAttributes[name]=[];for(let i=0;i<numMorphTargets;++i){const morphAttributesToMerge=[];for(let j=0;j<morphAttributes[name].length;++j)morphAttributesToMerge.push(morphAttributes[name][j][i]);const mergedMorphAttribute=mergeAttributes(morphAttributesToMerge);if(!mergedMorphAttribute)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+name+" morphAttribute."),null;mergedGeometry.morphAttributes[name].push(mergedMorphAttribute)}}return mergedGeometry}(geometries);brush1=new Brush(merged),brush1.updateMatrixWorld()}const evaluator=new Evaluator;outCircles.forEach((poly,j)=>{let geometry=this.createGeometryByLines(poly.toLines());if(brush1){const brush2=new Brush(geometry);brush2.updateMatrixWorld();geometry=evaluator.evaluate(brush2,brush1,SUBTRACTION).geometry}const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:11184810,side:THREE.DoubleSide}));mesh.position.z=this.z,mesh.name=`平面_out_${j}`,mesh.userData.category="plane",mesh.userData.planeType="outline",mesh.userData.uuid=uuid(),mesh.userData.area=poly.area(),group2.add(mesh)})}this.scene.add(group2)}wallGroup=null;async buildWall(){this.wallGroup=await globalScenario.drawGraphics(this.lines,this.z,this.trajectory),this.scene.add(this.wallGroup)}async getModel(item){let model=await LoadModel.loadGlb(item.category);if(!model)return;model=model.clone(!0),model.rotateX(.5*Math.PI),model.traverse(mesh=>{if(mesh instanceof THREE.Mesh){const material=mesh.material;mesh.material.map=null,material.vertexColors=!1,material.color=new THREE.Color(16777215)}});const contour=Point.fromByList(item.contour??[]),rectangle=new Polygon(Qa(contour.map(p2=>[p2.x,p2.y])).map(p2=>Point.from(p2)));rectangle.pop();const z=item.box.min.z,max=rectangle.getMaxLengthInfo(),min=rectangle.getMinLengthInfo(),center=rectangle.getCenter(),direction=max.start.y<max.end.y?max.start.directionFrom(max.end):max.end.directionFrom(max.start),height=Math.abs(item.box.max.z-z),group2=new THREE.Group;group2.position.set(center.x,center.y,z),group2.add(model),this.scene.add(group2);const box32=new THREE.Box3;box32.setFromObject(group2);const size2=box32.getSize(new THREE.Vector3),maxKey=size2.x>size2.y?"x":"y",mimKey=size2.x<size2.y?"x":"y",maxS=max.length/size2[maxKey],minS=min.length/size2[mimKey],scale2=height/size2.z;group2.scale[maxKey]*=maxS,group2.scale[mimKey]*=minS,group2.scale.z*=scale2,box32.setFromObject(group2),box32.getSize(size2);const point1=new Point,point2=new Point;size2.x>size2.y?(point1.set(box32.min.x,box32.min.y),point2.set(box32.max.x,box32.min.y)):(point1.set(box32.min.x,box32.min.y),point2.set(box32.min.x,box32.max.y));const direction2=point1.y<point2.y?point1.directionFrom(point2):point2.directionFrom(point1);group2.rotateZ(direction2.angleBetween2(direction)),this.scene.add(SceneAutoGenerat.itemParse(item).box)}static itemParse(item){const contourData=item.quadContour??item.contour;if(!Array.isArray(contourData)||!contourData.length)return null;const contour=Point.fromByList(contourData??[]),rectangle=new Polygon(Qa(contour.map(p2=>[p2.x,p2.y])).map(p2=>Point.from(p2)));rectangle.pop();const z=item.box.min.z,height=Math.abs(item.box.max.z-z),max=rectangle.getMaxLengthInfo(),min=rectangle.getMinLengthInfo(),direction=max.start.y<max.end.y?max.start.directionFrom(max.end):max.end.directionFrom(max.start),shape=new THREE.Shape;rectangle.forEach((p2,i)=>{0===i?shape.moveTo(p2.x,p2.y):shape.lineTo(p2.x,p2.y),i===rectangle.length-1&&shape.lineTo(rectangle[0].x,rectangle[0].y)});const geometry=new THREE.ExtrudeGeometry(shape,{depth:height,bevelEnabled:!1}),edges=new THREE.EdgesGeometry(geometry),lineSegments=new THREE.LineSegments(edges,new THREE.LineBasicMaterial({color:16776960}));lineSegments.position.z=z,box3.setFromObject(lineSegments);const center=box3.getCenter(new THREE.Vector3),maxLine=new LineSegment(max.start,max.end),minLine=new LineSegment(min.start,min.end),zStart=(new THREE.Vector3).copy(rectangle[0].toJson(z)),zEnd=zStart.clone();return zEnd.z+=height,{geometry:geometry,box:lineSegments,center:center,category:item.category,angle:direction.angleBetween(new Point(0,1),"angle","360")*(Math.PI/180)+.5*Math.PI,info:[{center:(new THREE.Vector3).copy(maxLine.center.toJson(z)),start:(new THREE.Vector3).copy(maxLine.start.toJson(z)),end:(new THREE.Vector3).copy(maxLine.start.toJson(z)),length:maxLine.length},{center:(new THREE.Vector3).copy(minLine.center.toJson(z)),start:(new THREE.Vector3).copy(minLine.start.toJson(z)),end:(new THREE.Vector3).copy(minLine.start.toJson(z)),length:minLine.length},{center:zStart.clone().add(zEnd).multiplyScalar(.5),start:zStart,end:zEnd,length:height}]}}}function proj(line,baseline,verticalLine){const startProj=baseline.projectPointValue(line.start),endProj=baseline.projectPointValue(line.end);return{pos:verticalLine.projectPointValue(line.start),startProj:Math.min(startProj,endProj),endProj:Math.max(startProj,endProj)}}function insertRangeIndex(track,range){if(0===track.length)return 0;let left=0,right=track.length;for(;left<right;){const mid=left+right>>1;track[mid][0]<range[0]?left=mid+1:right=mid}const i=left,prev=track[i-1],next=track[i];return prev&&range[0]<prev[1]||next&&range[1]>next[0]?-1:i}function getSize(ranges){let min=1/0,max=-1/0;return ranges.forEach(ranges2=>{ranges2.forEach(range=>{min=Math.min(min,range[0],range[1]),max=Math.max(max,range[0],range[1])})}),{min:min,max:max,length:max-min}}class DimensionLine{static build(lines,opt){if(0===lines.length)return[];const{maxTracks:maxTracks=3,besideLines:besideLines=[],occupancy:occupancy=[],minLen:minLen=.04,besideLinesPosFunc:besideLinesPosFunc,besideLineOffset:besideLineOffset=.2}=opt??{},geometryCenter=LineSegmentUtils.getLinesCenter(lines),dimensionAxis=LineSegmentUtils.findDominantDirectionLine(lines).clone().setLength(4),axisOffset=geometryCenter.subtract(dimensionAxis.center);dimensionAxis.translate(1,axisOffset);const normalAxis=dimensionAxis.clone().rotate(.5*-Math.PI),negativeParallelRanges=[],positiveParallelRanges=[],negativeNormalRanges=[],positiveNormalRanges=[];lines.forEach((line,index2)=>{if(dimensionAxis.isParallelTo(line)){const{pos:pos,startProj:startProj,endProj:endProj}=proj(line,dimensionAxis,normalAxis);pos<=.5?negativeParallelRanges.push([startProj,endProj,index2]):positiveParallelRanges.push([startProj,endProj,index2])}else{const{pos:pos,startProj:startProj,endProj:endProj}=proj(line,normalAxis,dimensionAxis);pos<=.5?negativeNormalRanges.push([startProj,endProj,index2]):positiveNormalRanges.push([startProj,endProj,index2])}});const besideRanges=besideLines.reduce((ranges,line,index2)=>{if(dimensionAxis.isParallelTo(line)){const{startProj:startProj,endProj:endProj}=proj(line,dimensionAxis,normalAxis);ranges[0].push([startProj,endProj,index2])}else{const{startProj:startProj,endProj:endProj}=proj(line,normalAxis,dimensionAxis);ranges[1].push([startProj,endProj,index2])}return ranges},[[],[]]),occupancyRange=occupancy.reduce((ranges,line,index2)=>{if(dimensionAxis.isParallelTo(line)){const{startProj:startProj,endProj:endProj}=proj(line,dimensionAxis,normalAxis);ranges[0].push([startProj,endProj,index2])}else{const{startProj:startProj,endProj:endProj}=proj(line,normalAxis,dimensionAxis);ranges[1].push([startProj,endProj,index2])}return ranges},[[],[]]),dimensionSize=getSize([negativeParallelRanges,positiveParallelRanges,besideRanges[0],occupancyRange[0]]),normalSize=getSize([negativeNormalRanges,positiveNormalRanges,besideRanges[1],occupancyRange[1]]);function handle(ranges,dimensionAxis2,normalAxis2,dimensionSize2,normalSize2,direction=1){if(0===ranges.length)return[];const normalDirection=normalAxis2.direction(),{tracks:tracks,untreated:untreated}=function(ranges,maxTracks=3,minLen=1e-6){(ranges=ranges.map(d2=>d2.map(v2=>Number(v2.toFixed(3))))).sort((a2,b4)=>a2[0]-b4[0]),ranges=ranges.filter((range,i)=>{if(0===i)return!0;const prev=ranges[i-1];return!(Math.abs(range[0]-prev[0])<=1e-4&&Math.abs(range[1]-prev[1])<=1e-4)});const map=/* @__PURE__ */new Map;for(let i=0;i<ranges.length;i++){const range=ranges[i];for(let j=0;j<2;j++){const value=range[j],item=map.get(value);item?(0===item.mode&&1==j||1===item.mode&&0==j)&&(item.mode=2):map.set(value,{value:value,mode:j})}}let list=Array.from(map.values());list=list.filter((value,i)=>{if(0===i||i===list.length-1)return!0;switch(value.mode){case 0:return 1===list[i-1].mode;case 1:return 0===list[i+1].mode;case 2:return!0}return!1}).sort((a2,b4)=>a2.value-b4.value).filter((item,i,arr)=>0===i||i===arr.length-1||item.value-arr[i-1].value>minLen);const mainTrackRanges=[];for(let i=1;i<list.length;i++)mainTrackRanges.push([list[i-1].value,list[i].value,0]);const mainMap=/* @__PURE__ */new Map;list.forEach((item,i)=>mainMap.set(item.value,i));let others=[];ranges=ranges.filter(range=>{const startIndex=mainMap.get(range[0]),endIndex=mainMap.get(range[1]);return void 0!==startIndex&&void 0!==endIndex?1!==endIndex-startIndex:(others.push(range),!1)}),others.sort((a2,b4)=>-(a2[1]-a2[0])-(b4[1]-b4[0]));const tracks=[],trackSet=/* @__PURE__ */new Set;for(let i=0;i<maxTracks-1;i++){trackSet.clear();let currValue=-1/0;ranges.forEach((range,i2)=>{if(!(range[0]<currValue)){for(let j=i2+1;j<ranges.length;j++)if(ranges[j][1]<=range[1])return;trackSet.add(i2),currValue=range[1]}});const track=Array.from(trackSet.values()).map(i2=>ranges[i2]);tracks.push(track),ranges=ranges.filter((_,i2)=>!trackSet.has(i2)),others=others.filter(range=>{const index2=insertRangeIndex(track,range);return-1==index2||(track.splice(index2,0,range),!1)})}return others.push(...ranges),{tracks:[mainTrackRanges,...tracks],untreated:others}}(ranges,maxTracks,minLen/dimensionAxis2.length),height=(-1===direction?.5-normalSize2.min:normalSize2.max-.5)*normalAxis2.length;return untreated.forEach(d2=>besideLines.push(lines[d2[2]])),tracks.push([[dimensionSize2.min,dimensionSize2.max,0]]),tracks.filter(t2=>t2.length).map((track2,i)=>{let dimensionOffset=direction*(.2*i+height+1.4),dimensionLine=new LineSegment(dimensionAxis2.pointAt(dimensionSize2.min),dimensionAxis2.pointAt(dimensionSize2.max));dimensionLine.translate(dimensionOffset,normalDirection);const result={track:{start:dimensionLine.start.toJson2D(),end:dimensionLine.end.toJson2D()},fragments:[]};return track2.forEach(([start,end,index2])=>{const points=[dimensionAxis2.pointAt(start),dimensionAxis2.pointAt(end)].map(point2=>(point2.x+=normalDirection.x*dimensionOffset,point2.y+=normalDirection.y*dimensionOffset,point2)),length=points[1].distance(points[0]);result.fragments.push({start:points[0].toJson2D(),end:points[1].toJson2D(),length:length,index:index2})}),result})}const results=[handle(negativeParallelRanges,dimensionAxis,normalAxis,dimensionSize,normalSize,-1),handle(positiveParallelRanges,dimensionAxis,normalAxis,dimensionSize,normalSize,1),handle(negativeNormalRanges,normalAxis,dimensionAxis,normalSize,dimensionSize,-1),handle(positiveNormalRanges,normalAxis,dimensionAxis,normalSize,dimensionSize,1)],track={track:{start:{x:0,y:0},end:{x:0,y:0}},fragments:[]};results.push([track]);const drawSegmentRuler=(line,point2)=>{const direct=point2.directionFrom(line.center),ruler=line.clone().translate(besideLineOffset,direct);track.fragments.push({start:ruler.start.toJson2D(),end:ruler.end.toJson2D(),length:ruler.length,index:0})},lsh=LineSegmentSpatialHash.from([.../* @__PURE__ */new Set([...besideLines,...lines])]),queryLine2=new LineSegment;for(const line of besideLines){let pos=null;if(besideLinesPosFunc&&(pos=besideLinesPosFunc(line,lsh)),"discard"!==pos){if(!pos){const step=line.normal().multiplyScalar(2*besideLineOffset),center=line.center;queryLine2.start.copy(center),queryLine2.end.copy(center).add(step);const result=[];let results2=lsh.queryLine(queryLine2).filter(l=>l!==line);if(0===results2.length&&result.push(queryLine2.center.clone()),queryLine2.end.copy(center).add(step.multiplyScalar(-1)),results2=lsh.queryLine(queryLine2).filter(l=>l!==line),0===results2.length&&result.push(queryLine2.center.clone()),2===result.length){const countList=result.map(p2=>{const projpoint=line.projectPoint(p2,!1),dist=p2.distance(projpoint),ql=line.clone().translate(dist,p2.directionFrom(projpoint));return ql.setLength(ql.length+.001),lsh.queryLine(ql).length}),[c1,c22]=countList;if(c1+c22===0)pos=result[0];else{if(c1===c22)continue;pos=c1<c22?result[0]:result[1]}}else pos=result[0]}pos&&drawSegmentRuler(line,pos)}}return results}}function getHoleLine(line){const holeLines=WallHoleDrawData.singleHoleLine(line)??[];return holeLines.forEach(holeLine=>{holeLine.userData.wallWidth=line.userData.wallWidth??holeLine.userData.wallWidth}),{lines:LineSegmentUtils.clippingByLines(line,holeLines,clippingLineUserData),holeLines:holeLines}}const SIDE_KEY=/* @__PURE__ */Symbol("SIDE_KEY");class DxfDataPlugin extends Pipeline{manager;lines=[];wallWidthLine=[];wallLengthLine=[];holeLine=[];occupancyLines=[];bezierCurveKernel=new BezierCurveKernel;constructor(lines){super(),lines=lines.filter(line=>!(line.userData.boundExtAppendLine&&Math.abs(line.length-(line.userData.boundExtAppendLineLen??0))<1e-6)),this.use({type:"bayWindow",handle:this.bayWindow.bind(this)}),this.use({type:"wall",handle:this.wall.bind(this)}),this.use({type:"cubicBezierWall",handle:this.cubicBezierWall.bind(this)}),this.use({type:"railing",handle:this.railing.bind(this)}),this.use({type:"pillar",handle:this.pillar.bind(this)}),this.use({type:"hole",handle:this.hole.bind(this)}),this.use({type:"cubicBezierHole",handle:this.cubicBezierHole.bind(this)}),this.lines=lines,this.manager=WallGroupManager.fromByLines1_5(lines)}bayWindow({data:{lines:lines},cache:{cad:cad2}}){const center=LineSegmentUtils.getLinesCenter(lines);lines=lines.filter(line=>line.userData.isBayWindow?(cad2.addGroup([line],"bayWindow"),!1):!LineGroupType.hasType(line,"doubleWall"));const psh=PointSpatialHash.fromByLines(lines),visited=/* @__PURE__ */new Set,relationshipTable=[];lines.forEach(line=>line.points.forEach(point2=>{if(visited.has(point2))return;const result=psh.queryPoint(point2,!0).filter(r2=>r2.userData?.isPerpendicularTo(line,35));result.length&&(relationshipTable.push({l1:line,p1:point2,l2:result[0].userData,p2:result[0].point}),visited.add(point2).add(result[0].point))})),lines.forEach(line=>{const projPoint=line.projectPoint(center,!1);if(projPoint){const direction=projPoint.directionFrom(center);line.translate(.5*DEFAULT_WALL_WIDTH,direction)}}),relationshipTable.forEach(({l1:l1,p1:p1,l2:l2,p2:p2})=>{const point2=l1.getIntersection(l2);point2&&(p1.copy(point2),p2.copy(point2))}),lines.forEach(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);cad2.addGroup(lines2,"wall",{bayWindow:!0}),this.manager.add({type:"hole",lines:holeLines})})}wall({data:{lines:lines},cache:{cad:cad2}}){let{doubleWall:doubleWall=[],wall:wall=[]}=LineSegmentUtils.group(lines,line=>line.currentData.doubleWall?"doubleWall":"wall");const holes=[];doubleWall=doubleWall.flatMap(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);return holes.push(...holeLines),lines2}),doubleWall.flatMap(line=>{const lines2=line.toRectangle(line.userData.wallWidth,"butt").toLines();cad2.addGroup(lines2,"doubleWall")}),wall=wall.flatMap(line=>{const{lines:lines2,holeLines:holeLines}=getHoleLine(line);return holes.push(...holeLines),lines2}),cad2.addGroup(wall,"wall"),this.manager.add({type:"hole",lines:holes})}cubicBezierWall({data:{lines:lines},cache:{cad:cad2}}){lines?.forEach(line=>{const lines2=this.bezierCurveKernel.getPathExcludingHoles(line).flatMap(path=>{const lines3=[];for(let i=1;i<path.length;i++){const newLine=new LineSegment(path[i-1],path[i]);newLine.userData=line.userData,lines3.push(newLine)}return lines3}),holeLines=[...WallHole.getIterator(line)].map(holeData=>WallHole.holeDataToLine(line,holeData));this.manager.add({type:"cubicBezierHole",lines:holeLines}),cad2.addGroup(lines2,"cubicBezierWall")})}railing({cache:{cad:cad2},data:{lines:lines}}){cad2.addGroupAndOffset(lines,{offsetHalfWidth:.025,type:"balconyRailing"}),cad2.addGroup(lines.flatMap(line=>{const dirct=line.normal(),moveDirct=line.direction(),length=line.length,newLine=line.start.expandAsLine(dirct,.05).translate(.025,dirct.multiplyScalar(-1)),distance2=length/4,count2=Math.floor(length/distance2),lines2=[];for(let i=1;i<=count2;i++)lines2.push(newLine.clone().translate(i*distance2,moveDirct));return lines2}),"balconyRailing")}pillar(ctx){try{ctx.cache.cad.addGroups([ctx.data.lines],"pillar");let poly=Polygon.fromByLines2(ctx.data.lines).getMinimumBoundingRectangle();if(poly){const line1=new LineSegment(poly[0],poly[1]),line2=new LineSegment(poly[1],poly[2]);this.wallWidthLine.push(line1,line2)}}catch(error){this.manager.add({type:"wall",lines:ctx.data.lines})}}hole({cache:{cad:cad2},data:{lines:lines}}){lines.forEach(line=>{switch(line.userData.type){case"beam":cad2.addGroup([line],"beam");break;case"door":cad2.addGroup([line],"door");break;case"window":cad2.addGroup([line],"window");break;case"byWindow":const{structure:structure}=WallHole.byWindowStructure(line,line.userData);this.manager.add({type:"bayWindow",lines:structure});break;default:cad2.addGroup([line],"passageEntrance")}})}cubicBezierHole({cache:{cad:cad2},data:{lines:lines}}){lines.forEach(line=>{const wallLine=line.currentData.wallLine,holeData=line.userData,wallWidth=line.currentData.wallWidth??DEFAULT_WALL_WIDTH;switch(line.userData.type??"passageEntrance"){case"window":{const data=this.bezierCurveKernel.getHoleData(wallLine,holeData),path=this.bezierCurveKernel.getHoleOffset(wallLine,holeData,wallWidth);cad2.addGroup([...data.path.toLines(!1),...path.toLines()],"cubicBezierWindow");break}case"passageEntrance":{const path=this.bezierCurveKernel.getHoleOffset(wallLine,holeData,wallWidth);cad2.addGroup(path.toLines(),"cubicBezierPassageEntrance");break}}})}dimensionLine(cad2){const besideLines=[...this.holeLine,...this.wallWidthLine].filter(line=>line.length>.1),lines=[...this.wallLengthLine],data=DimensionLine.build(lines,{maxTracks:3,besideLines:besideLines,occupancy:this.occupancyLines}),leaderLine=data.pop();data.forEach(list=>list.forEach(track=>{let trackLine=LineSegment.from(track.track);const fragmentLines=track.fragments.map(fragment=>LineSegment.from(fragment));let trackLines=LineSegmentUtils.clippingByLines(trackLine,fragmentLines);trackLines&&cad2.addGroup(trackLines,"dimensionLine"),cad2.addGroup(fragmentLines,"dimensionFragmentLine")})),leaderLine?.forEach(track=>{const fragmentLines=track.fragments.map(fragment=>LineSegment.from(fragment));cad2.addGroup(fragmentLines,"leaderLine")})}computeDimension(cad2,walls,holes=[],otherLines=[]){cad2=cad2.clone();const groups=LineSegmentUtils.group(walls,line=>line.userData.wallWidth??DEFAULT_WALL_WIDTH);Object.keys(groups).forEach(key=>{const lines=groups[key];LineSegmentUtils.groupByLeafPath(lines).forEach(lines2=>{cad2.addGroupAndOffset([...lines2],{type:"wall",offsetHalfWidth:.5*Number(key)})})}),cad2.unionGroup(g=>"wall"===g.type||"doubleWall"===g.type,{type:"wall",connectingBridge:!1});let walls2=cad2.filterGroups(g=>"wall"!==g.type).flatMap(item=>item.lines);const{widthLines:widthLines,lengthLines:lengthLines}=function(lines){const psh=PointSpatialHash.fromByLines(lines),hasLongerPerpendicularSegment=(point2,line)=>{const list=psh.queryPoint(point2,!0).filter(target=>target.userData.length>line.length).filter(target=>target.userData.isPerpendicularTo(line,25)),side=list.map(l=>line.getPointSideOfLine(l.userData.center));return{is:list.length>0,side:new Set(side)}},widthLines=[],lengthLines=lines.filter(line=>{const sideList=[];for(const point2 of line.points){const{is:is2,side:side}=hasLongerPerpendicularSegment(point2,line);if(sideList.push(side),!is2)return!0}return widthLines.push(line),line.currentData[SIDE_KEY]=new Set(sideList.flatMap(set2=>[...set2.values()].filter(v2=>"on"!==v2))),!1});return{widthLines:widthLines,lengthLines:lengthLines}}(walls2);this.wallWidthLine.push(...widthLines),this.wallLengthLine.push(...lengthLines),this.occupancyLines=otherLines,this.holeLine.push(...LineSegmentUtils.clone(holes))}finally(cad2){const walls=cad2.filterGroups(g=>"wall"!=g.type).flatMap(g=>g.lines),cubicBezierWalls=cad2.filterGroups(g=>"cubicBezierWall"!=g.type).flatMap(g=>g.lines),holes=cad2.findGroups(g=>["beam","door","window","passageEntrance"].includes(g.type)).flatMap(g=>g.lines),modifier=PointUtils.createDeferredModifier();!function(lines,avoidanceTargets,modifier){const lsh=LineSegmentSpatialHash.from(avoidanceTargets);lines.forEach(line=>{line.points.forEach(point2=>{if(lsh.queryPoint(point2).filter(result=>result!==line&&result.isPerpendicularTo(line,35)).length){const step=line.getAnotherPoint(point2).directionFrom(point2).multiplyScalar(.5*DEFAULT_WALL_WIDTH);modifier.add(point2,[step.x,step.y])}})})}(holes,walls,modifier),function(lines,avoidanceTargets,modifier){const psh=PointSpatialHash.fromByLines([...lines,...avoidanceTargets]),avoidanceTargetsSet=new Set(avoidanceTargets);lines.forEach(line=>{line.points.forEach(point2=>{let relation=0;if(psh.queryCircle(point2,1e-4).filter(result=>result.userData!==line).forEach(result=>{const target=result.userData;avoidanceTargetsSet.has(target)?target.isPerpendicularTo(line,25)&&(relation|=1):target.isParallelTo(line,45)&&(relation|=2)}),!(2&~relation))return;if(1&~relation)return;const otherPoint=line.getAnotherPoint(point2),step=point2.directionFrom(otherPoint).multiplyScalar(.5*DEFAULT_WALL_WIDTH);modifier.add(point2,[step.x,step.y])})})}(walls,holes,modifier),modifier.apply(),this.computeDimension(cad2,walls,holes,cubicBezierWalls),walls.push(...cubicBezierWalls);const groups=LineSegmentUtils.group(walls,line=>line.userData.wallWidth??DEFAULT_WALL_WIDTH);Object.keys(groups).forEach(key=>{const lines=groups[key];LineSegmentUtils.groupByLeafPath(lines).forEach(lines2=>{cad2.addGroupAndOffset([...lines2],{type:"wall",offsetHalfWidth:.5*Number(key)})})}),cad2.unionGroup(g=>"wall"===g.type||"doubleWall"===g.type,{type:"wall",connectingBridge:!1})}install(cad2){const config={cad:cad2};this.manager.forEach(group2=>{const option={lines:group2.lines};this.run(group2.type,option,config),group2.lines=option.lines}),this.finally(cad2),this.dimensionLine(cad2)}}class DxfDrawPlugin{dimension=!1;constructor(dimension=!1){this.dimension=dimension}getArcAngleRange(center,p1,p2){const x1=p1.x-center.x,y1=p1.y-center.y,x2=p2.x-center.x,y2=p2.y-center.y;let r1,r2,angle1=Math.atan2(y1,x1),angle2=Math.atan2(y2,x2);angle1=angle1<0?angle1+2*Math.PI:angle1,angle2=angle2<0?angle2+2*Math.PI:angle2;return Math.abs(angle2-angle1)<=Math.PI?(r1=Math.min(angle1,angle2),r2=Math.max(angle1,angle2)):(r1=Math.max(angle1,angle2),r2=Math.min(angle1,angle2)+2*Math.PI),[r1/(Math.PI/180),r2/(Math.PI/180)]}install(cad2){cad2.addDrawHandler({type:["wall"],handler({group:group2,drawLine:drawLine,setColor:setColor}){setColor("white"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["pillar"],handler({drawLine:drawLine,setColor:setColor,group:group2}){setColor("white"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["door"],handler:({group:group2,drawArc:drawArc,drawLine:drawLine,setColor:setColor})=>{group2.lines.forEach(lineSegment=>{const line=lineSegment.clone(),doorThickness=.2*DEFAULT_WALL_WIDTH,list=[];if(setColor("yellow"),line.length<1.5){line.extendAlongDirection(.5*-doorThickness);const normal=lineSegment.normal();lineSegment.userData.openDirect&&normal.angle(lineSegment.userData.openDirect,{unit:"degree",range:"180"})>90&&normal.multiplyScalar(-1);let door=new LineSegment(line.start.clone(),line.start.clone().add(normal.clone().multiplyScalar(line.length)));const box=door.clone().translate(-.5*line.length,door.normal()).toRectangle(line.length,"butt");for(let j=0;j<list.length;j++)if(list[j].intersectRectangle(box)){door=new LineSegment(line.start.clone(),line.start.clone().add(normal.clone().multiplyScalar(-line.length)));break}door.extendAlongDirection(.5*-doorThickness).toRectangle(.2*DEFAULT_WALL_WIDTH,"butt").path2D((p1,p2)=>drawLine(p1,p2));const a2=line.length,b4=door.length,r2=(a2**2+b4**2)/(2*b4),center=door.end.clone().add(door.direction().multiplyScalar(-r2)),[startAngle,endAngle]=this.getArcAngleRange(center,line.end,door.end);drawArc(center,r2,Math.min(startAngle,endAngle),Math.max(startAngle,endAngle)),list.push(box)}else line.clone().extendAlongDirection(.5*-DEFAULT_WALL_WIDTH).toRectangle(DEFAULT_WALL_WIDTH).path2D((p1,p2)=>drawLine(p1,p2)),line.clone().translate(.5*doorThickness,line.normal()).translate(.5*doorThickness,line.direction()).extendAlongDirection(.45*-line.length,"end").translate(.5*doorThickness).toRectangle(doorThickness).path2D((p1,p2)=>drawLine(p1,p2)),line.clone().translate(.5*-doorThickness,line.normal()).translate(.5*-doorThickness,line.direction()).extendAlongDirection(.45*-line.length,"start").translate(.5*-doorThickness).toRectangle(doorThickness).path2D((p1,p2)=>drawLine(p1,p2))})}}),cad2.addDrawHandler({type:["window"],handler:({group:group2,drawLine:drawLine,setColor:setColor})=>{setColor("cyan"),group2.lines.forEach(line=>{drawLine(line.start,line.end),line.toRectangle(line?.userData?.wallWidth??DEFAULT_WALL_WIDTH,"butt").path2D((p1,p2)=>drawLine(p1,p2))})}}),cad2.addDrawHandler({type:["cubicBezierWindow"],handler:({group:group2,drawLine:drawLine,setColor:setColor})=>{setColor("cyan"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["bayWindow"],handler({drawDottedLine:drawDottedLine,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("cyan"),line=line.clone().extendAlongDirection(.5*-DEFAULT_WALL_WIDTH),drawDottedLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["balconyRailing"],handler({group:group2,setColor:setColor,drawLine:drawLine}){group2.lines.forEach(line=>{setColor("green"),drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["passageEntrance"],handler({group:group2,setColor:setColor,drawDottedLine:drawDottedLine}){group2.lines.forEach(line=>{setColor("white");const direction=line.normal(),width=line?.userData?.wallWidth??DEFAULT_WALL_WIDTH,line1=line.clone().translate(.5*width,direction),line2=line.clone().translate(.5*-width,direction);drawDottedLine(line1.start,line1.end),drawDottedLine(line2.start,line2.end),drawDottedLine(line1.start,line2.start),drawDottedLine(line1.end,line2.end)})}}),cad2.addDrawHandler({type:["cubicBezierPassageEntrance"],handler:({group:group2,drawDottedLine:drawDottedLine,setColor:setColor})=>{setColor("white"),group2.lines.forEach(line=>{drawDottedLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["beam"],handler({drawDottedLine:drawDottedLine,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("red");const width=line?.userData?.wallWidth??DEFAULT_WALL_WIDTH;if(width!=DEFAULT_WALL_WIDTH){const direction=line.normal(),line1=line.clone().translate(.5*width,direction),line2=line.clone().translate(.5*-width,direction);drawDottedLine(line1.start,line1.end),drawDottedLine(line2.start,line2.end),drawDottedLine(line1.start,line2.start),drawDottedLine(line1.end,line2.end)}else drawDottedLine(line.start,line.end)})}}),!0!==this.dimension&&"out"!==this.dimension||(cad2.addDrawHandler({type:["dimensionLine"],handler({drawLine:drawLine,setColor:setColor,group:group2}){setColor("ruler_deep"),group2.lines.forEach(line=>{drawLine(line.start,line.end)})}}),cad2.addDrawHandler({type:["dimensionFragmentLine"],handler({drawLine:drawLine,drawText:drawText2,setColor:setColor,group:group2}){group2.lines.forEach(line=>{setColor("ruler_deep"),drawLine(line.start,line.end);const dirct=line.direction(),l1=line.clone().rotate(.5*Math.PI);l1.setLength(.1);const l2=l1.clone();if(setColor("ruler"),l1.translate(.5*line.length,dirct),drawLine(l1.start,l1.end),l1.rotate(Math.PI/180*-35),drawLine(l1.start,l1.end),l2.translate(.5*-line.length,dirct),drawLine(l2.start,l2.end),l2.rotate(Math.PI/180*-35),drawLine(l2.start,l2.end),line.length>.12){setColor("text");const dirct2=line.direction();(line.start.x>line.end.x||line.start.x===line.end.x&&line.start.y>line.end.y)&&dirct2.multiplyScalar(-1);let angle=Math.atan2(dirct2.y,dirct2.x);angle/=Math.PI/180,drawText2((1e3*line.length).toFixed(0),line.center,{rotation:angle,fontSize:.01})}})}})),!0!==this.dimension&&"in"!==this.dimension||cad2.addDrawHandler({type:["leaderLine"],handler({drawLine:drawLine,drawText:drawText2,setColor:setColor,group:group2}){group2.lines.forEach(line=>{if(line.length<.12)return;setColor("ruler_deep"),drawLine(line.start,line.end);const dirct=line.direction(),l1=line.clone().rotate(.5*Math.PI);l1.setLength(.08);const l2=l1.clone();setColor("ruler"),l1.translate(.5*line.length,dirct),drawLine(l1.start,l1.end),l2.translate(.5*-line.length,dirct),drawLine(l2.start,l2.end);{setColor("text");const dirct2=line.direction();(line.start.x>line.end.x||line.start.x===line.end.x&&line.start.y>line.end.y)&&dirct2.multiplyScalar(-1);let angle=Math.atan2(dirct2.y,dirct2.x);angle/=Math.PI/180,drawText2((1e3*line.length).toFixed(0),line.center,{rotation:angle,fontSize:.001})}})}})}}const cad={CAD:CAD,DxfDataPlugin:DxfDataPlugin,DxfDrawPlugin:DxfDrawPlugin};function doubleWallAlignmentFun(lines){const singleWall=lines.filter(line=>!LineGroupType.hasType(line,"doubleWall")&&!line.userData.isDoor),doorLines=lines.filter(line=>line.userData.isDoor),lshSingle=LineSegmentSpatialHash.from(singleWall.filter(line=>!line.userData.isDoor)),allGrid=PointSpatialHash.fromByLines(lines),doubleWalls=LineGroupType.getGroupsByType(lines,"doubleWall"),lshDouble=LineSegmentSpatialHash.from(doubleWalls.flat());return(lines=splitIntersectedLine(lines=[singleWall,doubleWalls.flatMap(doubleWall=>{const poly=Polygon.fromByLines2(doubleWall);Polygon.ensureCCW(poly),poly.toLines().forEach(line=>{const list=lshDouble.queryPoint(line.center,1e-6);list.length&&(list[0].start.copy(line.start),list[0].end.copy(line.end),list[0].points.forEach(p2=>allGrid.update(p2)))});const wallWidthMap=/* @__PURE__ */new Map,expLines=doubleWall.filter(line=>{if(line.length<.001)return!1;for(let i=0;i<line.points.length;i++){const point2=line.points[i];let list=lshSingle.queryPoint(point2);if(1===list.length&&(list=lshSingle.queryPoint(point2).filter(item=>item.isParallelTo(line)),1===list.length))return wallWidthMap.set(line,list[0].userData.wallWidth??DEFAULT_WALL_WIDTH),!0}return!1});return[expLines.flatMap(line=>{const normal=line.normal(),id=LineGroupType.getIdByType(line,"doubleWall"),offset=.5*(wallWidthMap.get(line)??DEFAULT_WALL_WIDTH);let step=normal.multiplyScalar(-offset);const newLines2=[],old_line=line.clone();return line.points.forEach(p2=>{const newPoint=p2.clone().add(step);let newLine=((point2,newPoint,line)=>{let list=allGrid.queryPoint(point2,!0),direct=newPoint.directionFrom(point2),isParallel2=!1;if(list=list.filter(item=>!item.userData.isParallelTo(line,25)||(isParallel2=!0,!1)),list.forEach(item=>{const direct2=item.userData.getAnotherPoint(item.point).directionFrom(item.point);direct.angle(direct2,{unit:"degree",range:"180"})>145&&isParallel2||(item.point.copy(newPoint),allGrid.update(item.point))}),isParallel2){let newLine=(new LineSegment).set(point2,newPoint);return allGrid.insert(newLine.start,newLine).insert(newLine.end,newLine),point2.copy(newPoint),newLine}point2.copy(newPoint)})(p2,newPoint,old_line);newLine&&newLines2.push(newLine)}),allGrid.update(line.start),allGrid.update(line.end),newLines2.forEach(newLine=>{LineGroupType.set(newLine,id,"doubleWall")}),newLines2}),doubleWall].flat(10)})].flat(10))).push(...doorLines),WallHole.filterIllegal(lines),lines.filter(line=>line.length>1e-4)}const point=new Point;class HeightQuery{static query(line,rootTopContourInfo){const inLinePoints=[],len=line.length,newLine=line.clone(),center=line.center;newLine.offsetStart(.2*len),newLine.offsetEnd(.2*len),inLinePoints.push([center.x,center.y],[newLine.start.x,newLine.start.y],[newLine.end.x,newLine.end.y]);const contoursData=this.whichContourContainsPoint(inLinePoints,rootTopContourInfo);contoursData.sort((a2,b4)=>b4.averagePz-a2.averagePz);return contoursData[0]?.averagePz??2.8}static whichContourContainsPoint(points,rootTopContourInfo){const contoursData=[],{contours:contours,maxContourIndex:maxContourIndex,quadtree:quadtree}=rootTopContourInfo;return points.filter(p2=>{point.set(p2[0],p2[1]);for(let i=0;i<contours.length;i++){const{contour:contour,polygon:polygon2}=contours[i];contour.length&&i!==maxContourIndex&&(polygon2?.pointIn(point)&&contoursData.push({i:i,averagePz:contours[i].averagePz}))}}),contoursData.length||points.filter(p2=>{point.set(p2[0],p2[1]),new Array(...new Set(quadtree?.queryCircle(point,.6).map(item=>item.line.currentData.contourIndex))).forEach(index2=>{index2!==maxContourIndex&&contoursData.push({i:index2,averagePz:contours[index2].averagePz})})}),contoursData}}const builtinFun={init:function(lines,option){const group2=WallGroupManager.createGroup(lines);return lines=LineSegmentUtils.GroupBuilder(group2).handleAll(lines2=>{const map=new ArrayMap;lines2.forEach(line=>{const width=line.userData.wallWidth??DEFAULT_WALL_WIDTH;map.append(width,line)});const newLines=[];return map.forEach(lines3=>{newLines.push(...function(lines){let defaultLines=[],doorLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];line.userData.isDoor?doorLines.push(line):defaultLines.push(line)}return defaultLines=mergeChainsLine(defaultLines),doorLines=mergeChainsLine(doorLines),[...defaultLines,...doorLines]}(lines3))}),newLines}).handle("wall",lines2=>(lines2=splitIntersectedLine(lines2,1e-9,{balconyRailing:{behavior:"discard",filteringRatio:.2}}),WallHole.filterIllegal(lines2).merge(lines2),lines2)).merge(),option.trajectory&&(sparse(option.trajectory,.2),sparse(option.trajectory,.5),function(lines,trajectory2){const holeLines=[];for(let i=0;i<lines.length;i++){const line=lines[i];for(const hole of WallHole.getIterator(line))if("door"===hole.type||"passageEntrance"===hole.type){const holeLine=WallHole.holeDataToLine(line,hole);holeLines.push(holeLine)}}const lsh=LineSegmentSpatialHash.from(holeLines),p2=new Point;Object.keys(trajectory2).forEach(k=>{Point.from(trajectory2[k],p2);const dircts=lsh.queryPoint(p2,.3).map(line=>{const pp=line.projectPoint(p2);if(pp)return pp.directionFrom(p2)}).filter(p22=>!!p22);for(let i=0;i<dircts.length;i++){const dirct1=dircts[i];for(let j=0;j<dircts.length;j++){const dirct2=dircts[j];if(dirct1.dot(dirct2)<0)return void delete trajectory2[k]}}})}(lines,option.trajectory)),BuildGroup.doubleWall.setTrajectory(option.trajectory),lines.forEach(line=>{for(const hole of WallHole.getIterator(line))hole.uuid||(hole.uuid=uuid())}),lines},DoorToHole:function(lines,option){return lines.forEach(line=>{line.userData.isDoor&&(delete line.userData.isDoor,line.userData.isPassageEntrance=!0,line.userData.passageEntrance=[{p:line.center.toJson(option?.originalZ),width:line.length,full:!1,groundClearance:line.userData.drawDoorData?.groundClearance,type:"door",height:line.userData.drawDoorData?.height??Math.min(2,.8*(line.userData?.height??line.length))}])}),lines},AxisAlignCorr:function(lines,option,verticalReferenceLine){if(!(verticalReferenceLine=verticalReferenceLine??LineSegmentUtils.findDominantDirectionLine(lines)))return console.error("未找到一条垂直纠正基准轴线, 未做垂直纠正处理"),lines;const t2=performance.now();return lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle(["wall","railing"],lines2=>function(lines,targettLine,option){return lines=preprocessing(lines),lines=splitIntersectedLine(lines=AxisAlignCorr.start(lines,targettLine),1e-9),WallHole.miniWidthFilter(lines).filterIllegal(lines).merge(lines),lines=removeDangline(lines=splitIntersectedLine(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",lines2=>(lines2=AlignToParallelSegments.align(lines2,{...alignConfig(),gap:option?.alignGroupGap,esp:option?.alignGroupEsp}),WallHole.merge(lines2),adsorption(lines2,option))).handle("railing",lines2=>AlignToParallelSegments.align(lines2)).merge(),1e-9),.1,!1),WallHole.miniWidthFilter(lines),lines=removeDangline(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",newLines=>{newLines=BuildGroup.bayWindow(newLines,!1);const{wallGroup:wallGroup=!0}=option??{};return wallGroup&&(newLines=breakpointMerging$1(newLines=DoubleWallFinder.buildGroup(newLines)),newLines=BuildGroup.bayWindow(newLines,!1)),newLines}).merge(),.15,!0),WallHole.merge(lines).miniWidthFilter(lines),lines.filter(line=>line.length>1e-9)}(lines2,verticalReferenceLine,option)).handle("pillar",(lines2,group2)=>function(lines,group2,option){return LineGroupType.getGroupsByType(lines,"pillar").flatMap(lines2=>{if(4===(lines2=breakpointMerging$1(lines2)).length){const verticalReferenceLine=LineSegmentUtils.findDominantDirectionLine(lines2);lines2=adsorption(lines2=AxisAlignCorr.start(lines2,verticalReferenceLine),option,group2.wall)}const id=uuid();return lines2.forEach(line=>LineGroupType.set(line,id,"pillar")),lines2})}(lines2,group2,option)).handle("beam",(lines2,group2)=>function(lines,verticalReferenceLine,group2,option){return lines=AxisAlignCorr.start(lines,verticalReferenceLine),lines=adsorption(lines=AlignToParallelSegments.align(lines,{...alignConfig({max_wall_width:.8}),onMergeLine:(target,source)=>{const maxHeight=Math.max(target.userData.height??0,source.userData.height??0);mergeLineUserData(target,source),maxHeight&&(target.userData.height=maxHeight),target.userData.tags=target.userData.tags??[],target.userData.tags.push("merge")},esp:.8}),option,group2.wall),WallHole.merge(lines),lines}(lines2,verticalReferenceLine,group2,option)).merge(),console.log("垂直纠正耗时:",performance.now()-t2),lines},DoorFind:lines=>new DoorFind(lines).getLines(),BoundExt:function(lines,{trajectory:trajectory2,onBoundExt:onBoundExt}){if(!trajectory2)return console.error("没有传入轨迹文件"),lines;let t2=performance.now();return lines=BoundExt.boundExtbyTraj({lines:lines,trajectory:trajectory2,wallWidth:DEFAULT_WALL_WIDTH,findCallBack:onBoundExt}).lines,console.log(`外墙外扩总消耗时间: ${(performance.now()-t2).toFixed(2)} ms 处理线段数量:`,lines.length),lines},DoubleWallAlignment:function(lines){return LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",doubleWallAlignmentFun).merge()},WallHeightHandle:function(lineSegments,option){if(option?.publicInfo?.rootTopContourInfo){const polygons=option.publicInfo.rootTopContourInfo.contours.map(item=>(item.polygon||Object.defineProperty(item,"polygon",{value:new Polygon(Point.fromByList(item.contour))}),item.polygon));if(!option.publicInfo.rootTopContourInfo.quadtree){const lines=polygons.flatMap((polygon2,index2)=>{const lines2=polygon2?.toLines()??[];return lines2.forEach(line=>line.currentData.contourIndex=index2),lines2}),quadtree=Quadtree.from(lines);Object.defineProperty(option.publicInfo.rootTopContourInfo,"quadtree",{value:quadtree})}}const psh=PointSpatialHash.fromByLines(lineSegments);return lineSegments.forEach(line=>{if(!("height"in line.userData)){if(!line.userData.rooftopPz&&option?.publicInfo?.rootTopContourInfo){const list=psh.queryPoints(line.points,!0).map(item=>item.userData?.userData.rooftopPz??0);list.length?line.userData.rooftopPz=Math.max(...list):line.userData.rooftopPz=HeightQuery.query(line,option.publicInfo.rootTopContourInfo)}"rooftopPz"in line.userData&&(line.userData.height=Math.abs(line.userData.rooftopPz-(option.originalZ??0)))}}),lineSegments},DoorSpaceHandle:function(lineSegments){const noDoorLines=lineSegments.filter(line=>!line.userData.isDoor),quadtree=Quadtree.from(noDoorLines),pvg=PointSpatialHash.fromByLines(noDoorLines),doors=lineSegments.filter(line=>{if(!line.userData.isDoor)return!1;let startCount=pvg.queryPoint(line.start,!0).length,endCount=pvg.queryPoint(line.end,!0).length;return 0===startCount&&(startCount=quadtree.queryPoint(line.start).length),0===endCount&&(endCount=quadtree.queryPoint(line.end).length),0===startCount&&0===endCount||startCount>0&&endCount>0}),removeLines=[],appendLines=[];doors.forEach(doorLine=>{const length=doorLine.length,rectangle=doorLine.clone().extendAlongDirection(-.1,"all").toRectangle(.8,"butt"),results=quadtree.queryRect(rectangle).map(item=>{const projectLine=item.line.projectLineSegment(doorLine);return{...item,projectLine:projectLine,plLength:projectLine.length}}).filter(opt=>opt.projectLine.length/length>.7);results.sort((a2,b4)=>b4.plLength-a2.plLength),results.forEach(({line:line,projectLine:projectLine},i)=>{0===i&&doorLine.copy(projectLine);const lines=LineSegmentUtils.clippingByLine(line,projectLine);lines&&(removeLines.push(line),appendLines.push(...lines))})});const removeLinesSet=new Set(removeLines);return(lineSegments=lineSegments.filter(line=>!removeLinesSet.has(line))).push(...appendLines),lineSegments},RemoveShortDoubleWall:function(lineSegments){const doubleWalls=LineGroupType.getGroupsByType(lineSegments,"doubleWall"),freePointLines=[...findDiscretePointLine2(lineSegments)].filter(line=>line.length<.3),grid=PointSpatialHash.fromByLines(doubleWalls.flat(4)),lines=freePointLines.filter(line=>grid.queryPoint(line.start).length>0||grid.queryPoint(line.end).length>0),removeSet=new Set(lines);return lineSegments.filter(line=>!removeSet.has(line))},BeamSupportLine:function(lines,{}){const lsh=Quadtree.from(lines.filter(line=>!line.userData.isBalconyRailing));return lines.forEach(line=>{if(!line.userData.wallWidth&&WallHole.isBeam(line)){const findLine=line.clone();findLine.setLength(findLine.length-.002);let rectangle=findLine.toRectangle(2,"butt");const center=findLine.center,beamNearWallVec=function(line){const iterator=WallHole.getIterator(line);for(const hole of iterator)if("beamNearWallVec"in hole)return Point.from(hole.beamNearWallVec)}(line),list=lsh.queryRect(rectangle).filter(target=>{if(target.line===line)return!1;if(!target.line.isParallelTo(findLine,10))return!1;if(beamNearWallVec){if(target.line.center.directionFrom(center).dot(beamNearWallVec)<0)return!1}return!0}).map(item=>item.line).sort((a2,b4)=>a2.distanceToPoint(center)-b4.distanceToPoint(center));if(list.length){const point2=list[0].projectPoint(center,!1);line.userData.expansionWidth=Math.max(point2.distance(center),DEFAULT_WALL_WIDTH),line.userData.expansionDirction=point2.directionFrom(center).toJson2D()}}}),lines},RemoveRoomSundries:function(lines,{trajectory:trajectory2}){return trajectory2&&(lines=LineSegmentUtils.GroupBuilder(WallGroupManager.createGroup(lines)).handle("wall",lines2=>{const rooms=findRooms(lines2,trajectory2,{clone:!1,split:!1}),counterMap=new CounterMap;findDiscretePoint(lines2).forEach(l=>counterMap.increment(l));const ls2=counterMap.getByCount(2);ls2.push(...lines2.filter(line=>line.userData.isBalconyRailing));let removeLines=[...new Set(ls2)].filter(line=>{const center=line.center;return!!rooms.find(room=>room.ploy.pointWithin(center)&&!room.lines.find(l=>l==line))});const set2=new Set(removeLines);return lines2=lines2.filter(line=>!set2.has(line))}).merge()),lines},BaywindowToHole:function(lines,_){const{walls:walls=[],bayWindows:bayWindows=[]}=LineSegmentUtils.group(lines,line=>LineGroupType.hasType(line,"bayWindow")?"bayWindows":"walls"),appends=[];return LineGroupType.getGroupsByType(bayWindows,"bayWindow").forEach(bayWindows2=>{bayWindows2=mergeChainsLine(bayWindows2=splitIntersectedLine(bayWindows2,0),mergeLineUserData),bayWindows2=MaxiCircles.instance.maxiCircles(bayWindows2).circles.sort((a2,b4)=>b4.length-a2.length)[0];let{walls:walls2=[],path:path=[]}=LineSegmentUtils.group(bayWindows2,line=>line.userData.isBayWindow?"walls":"path");if(!walls2.length)return appends.push(...bayWindows2);if(path.length<3)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);const windowIndex=path.findIndex(line=>line.userData.isWindow),wall=walls2[0];if(-1===windowIndex)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);const windowLine=path[windowIndex],windowHole=windowLine.userData.drawWindow?.[0];if(!windowHole)return walls2.forEach(line=>delete line.userData.isBayWindow),void appends.push(...bayWindows2);if(delete wall.userData.isBayWindow,LineGroupType.clear(wall),path.length<=4){let h2=0,dirct=Point.zero();return path.flatMap(line=>line.points.forEach(p2=>{const dist=wall.distanceToPoint(p2);if(dist>h2){h2=dist;const proP=wall.projectPoint(p2,!1);p2.directionFrom(proP,dirct)}})),WallHole.addHole(wall,{p:wall.center.toJson(),width:wall.length,full:!1,type:"byWindow",groundClearance:windowHole.groundClearance,height:windowHole.height,extrusion:{direction:dirct.toJson(),distance:h2}}),void appends.push(wall)}const ploy=Polygon.fromByLines2(path),center=windowLine.center;let index2=0;for(let i=0;i<ploy.length-1;i++){const point1=ploy[i],point2=ploy[i+1],center2=point1.clone().add(point2).multiplyScalar(.5);if(center.distanceSquared(center2)<1e-4){index2=i;break}}WallHole.addHole(wall,{p:wall.center.toJson(),width:wall.length,full:!1,type:"byWindow",groundClearance:windowHole.groundClearance,height:windowHole.height,shape:{path:ploy.map(p2=>p2.toJson2D()),fragmentAttr:[{type:"window",index:index2}]}}),appends.push(wall)}),[...walls,...appends]},SplitCollinearWallsAndBeams:function(lineSegments,_){return(lineSegments=lineSegments.flatMap(lineSegment=>{let ranges=[],holeDatas=[...WallHole.getIterator(lineSegment)];for(const holeData of holeDatas)if("beam"===holeData.type){const holeLine=WallHole.holeDataToLine(lineSegment,holeData),startV=lineSegment.projectPointValue(holeLine.start),endV=lineSegment.projectPointValue(holeLine.end);ranges.push(startV<endV?[startV,endV]:[endV,startV])}if(0===ranges.length)return[lineSegment];ranges=RangeCore.union(ranges);const points=ranges.flatMap(range=>range.map(t2=>lineSegment.pointAt(t2))),lines=LineSegmentUtils.clippingByPoints(lineSegment,points,line=>{WallHole.clear(line)});return WallHole.splitHoleByProjectPoint(lineSegment,lines),holeDatas.forEach(holeData=>holeData.full=!0),lines})).forEach(lineSegment=>{for(const holeData of WallHole.getIterator(lineSegment))"beam"===holeData.type&&(holeData.full=!0)}),lineSegments}};class LinePipeline extends Pipeline{static get builtin(){return builtinFun}fronts=[];nofront=!0;constructor(){super()}add(handle,index2){if("number"==typeof index2){const list=this.map.get("LINE");if(list)return index2=Math.max(0,Math.min(index2,list.length)),list.splice(index2,0,{type:"LINE",handle:ctx=>{ctx.data=handle(ctx.data,ctx.cache)}}),this}return this.use({type:"LINE",handle:ctx=>{ctx.data=handle(ctx.data,ctx.cache)}}),this}clear(){return super.clear(),this.nofront=!0,this}execute(data,option){return this.nofront&&(this.fronts.forEach(fun=>this.add(fun,0)),this.nofront=!1),super.run("LINE",data,option)}}class Dxf extends Component{static name="Dxf";originalData=[];data=[];box=new Box2(0,0,0,0);cadQueue=/* @__PURE__ */new Map;angle=0;lineSegments=[];verticalReferenceLine;originalZAverage=0;linePipeline=new LinePipeline;get lines(){return this.lineSegments}constructor(){super(),this.linePipeline.fronts.push(LinePipeline.builtin.init,LinePipeline.builtin.WallHeightHandle,LinePipeline.builtin.SplitCollinearWallsAndBeams,LinePipeline.builtin.DoorToHole,LinePipeline.builtin.BaywindowToHole)}getLineSegments(clone2=!1){let lines=this.lineSegments;return clone2&&(lines=lines.map(line=>line.clone(!0,!0))),lines}preprocessing(data,options){let{lineSegments:lineSegments,originalZAverage:originalZAverage}=originalDataToLineData(data);return this.originalZAverage=originalZAverage,options.originalZ=options.originalZ??originalZAverage,lineSegments=this.linePipeline.execute(lineSegments,options),this.verticalReferenceLine=LineSegmentUtils.findDominantDirectionLine(lineSegments),this.verticalReferenceLine.userData.isVerticalReferenceLine=!0,{lineSegments:lineSegments,data:data}}options={};rooms=[];async set(data,options={}){if("string"==typeof data){if("undefined"!=typeof global){const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(data),json=JSON.parse(buffer.toString("utf-8"));return this.set(json,options)}throw new Error("非node环境不允许使用路径")}if(0===data.length)return;if(this.cadQueue.clear(),this.options=options,0===data.length)this.lineSegments=[],this.originalData=data;else{const res=this.preprocessing(data,options);data=res.data,this.lineSegments=res.lineSegments,this.originalData=data}const zList=[];data.forEach(({start:start,end:end})=>zList.push(start.z??0,end.z??0)),this.originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length,this.box=Box2.fromByLineSegment(this.lineSegments),this.rooms=findRooms(this.lineSegments,options.trajectory),this.dispatchEvent({type:"dataChange",originalData:this.originalData,data:this.data,options:options}),this.dispatchEvent({type:"setDta",originalData:this.originalData,data:this.data,options:options});let lines=this.getLineSegments(!0);const doors=lines.filter(line=>line.userData.isDoor);lines=lines.filter(line=>!line.userData.isDoor),lines=BuildGroup.doubleWall(lines),lines.push(...doors);const{cad:cad2}=this.generateCad(lines);this.dispatchEvent({type:"cadChange",cad:cad2,options:options}),this.dispatchEvent({type:"lineOffset",cad:cad2,options:options})}async setTrajectory(trajectory2,clear=!1){this.options.trajectory=trajectory2,await this.set(lineDataToOriginalData(this.getLineSegments(),this.originalZAverage),this.options),clear&&(this.options.trajectory=void 0)}generateCad(lines){const cad2=(new CAD).usePlugin(new DxfDataPlugin(lines)).usePlugin(new DxfDrawPlugin),dimensionCad=cad2.clone(!1).usePlugin(new DxfDrawPlugin(!0));this.cadQueue.set("cad",cad2),this.cadQueue.set("dimCad",dimensionCad);const degCorrCad=cad2.clone(),{angle:angle}=CAD.obliquity(degCorrCad);degCorrCad.rotateAndResetOrigin(angle),this.angle=angle;const dimensionCorrCad=degCorrCad.clone(!1).usePlugin(new DxfDrawPlugin(!0));return this.cadQueue.set("degCorrCad",degCorrCad),this.cadQueue.set("degCorrDimCad",dimensionCorrCad),{cad:cad2,dimensionCad:dimensionCad,degCorrCad:degCorrCad,dimensionCorrCad:dimensionCorrCad}}getCAD(cadName){return this.cadQueue.get(cadName)}toOriginalData(quadtree){return lineDataToOriginalData(this.getLineSegments(!0),this.originalZAverage,quadtree)}async downloadOriginalData(filename){const data=lineDataToOriginalData(this.getLineSegments(),this.originalZAverage),content=JSON.stringify(data);if("undefined"!=typeof window){const blob=new Blob([content],{type:"application/json"}),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,content)}}toDrawData(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDrawData(unit)}toDxfString(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfString(unit)}toDxfBlob(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfBlob(unit)}toDxfObject3D(cadName,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfObject3D(unit)}async downloadDxf(cadName,filename,unit="Millimeters"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.downloadDxf(filename,unit)}async toDxfImageBlob(cadName,unit="Centimeters",type="image/jpeg",background="#000"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return cad2.toDxfImageBlob(unit,type,background)}async downloadDxfImage(cadName,filename,unit="Centimeters",type="image/jpeg"){const cad2=this.cadQueue.get(cadName);if(!cad2)throw new Error("获取的cad图纸:"+cadName+", 不存在");return!cad2.downloadDxfImage(filename,unit,type)}}class BoundExtDxf extends Dxf{static name="BoundExtDxf";angle=0;constructor(){super(),this.linePipeline.fronts.length=0}onAddFromParent(parent){parent.Dxf.addEventListener("cadChange",e=>{e.options.trajectory&&this.linePipeline.add(LinePipeline.builtin.BoundExt),this.linePipeline.add(LinePipeline.builtin.DoubleWallAlignment);const lines=parent.Dxf.getLineSegments(!0);this.set(lineDataToOriginalData(lines,parent.Dxf.originalZAverage),{trajectory:e.options.trajectory,publicInfo:e.options.publicInfo,onBoundExt:e.options.onBoundExt}),this.linePipeline.clear()})}set(data,options={}){if(0===data.length)return;if(this.cadQueue.clear(),0===data.length)this.lineSegments=[],this.originalData=data;else{const res=this.preprocessing(data,options);data=res.data,this.lineSegments=res.lineSegments,this.originalData=data,this.lineSegments=LinePipeline.builtin.WallHeightHandle(this.lineSegments,options)}this.options=options;const zList=[];data.forEach(({start:start,end:end})=>zList.push(start.z??0,end.z??0)),this.lineSegments=function(lineSegments){let appendLines=[];const newHoleLines=[],clipLineMap=new ArrayMap,removeHoleMap=new ArrayMap,{matchQueues:matchQueues,originMap:originMap}=WallHole.buildPairing(lineSegments);matchQueues.forEach(matchQueue=>matchQueue.forEach(([holeLine1,holeLine2])=>{const line1=originMap.get(holeLine1),line2=originMap.get(holeLine2),newLine=LineSegmentUtils.mergeLinesByMaxlength(holeLine1,holeLine2);holeLine1.projectLineSegment(newLine,newLine),holeLine2.projectLineSegment(newLine,newLine);const clipLine1=line1.projectLineSegment(newLine),clipLine2=line2.projectLineSegment(newLine),appendLine1=new LineSegment(clipLine1.start,clipLine2.start),appendLine2=new LineSegment(clipLine1.end,clipLine2.end),newHoleLine=line1.clone().set(appendLine1.center,appendLine2.center);newHoleLine.userData.wallWidth=Math.max(appendLine1.length,appendLine2.length),newHoleLine.userData.tags=["hole-independent"],WallHole.clear(newHoleLine),WallHole.addHole(newHoleLine,holeLine1.userData),WallHole.addHole(newHoleLine,holeLine2.userData),WallHole.merge(newHoleLine),appendLines.push(appendLine1,appendLine2),newHoleLines.push(newHoleLine),clipLineMap.append(line1,clipLine1).append(line2,clipLine2),removeHoleMap.append(line1,holeLine1.userData).append(line2,holeLine2.userData)})),(lineSegments=lineSegments.flatMap(lineSegment=>{const clipLines=clipLineMap.get(lineSegment);if(clipLines){const newLines=LineSegmentUtils.clippingByLines(lineSegment,clipLines,clippingLineUserData);return newLines.forEach(line=>WallHole.clear(line)),WallHole.splitHoleByProjectPoint(lineSegment,newLines),WallHole.merge(newLines),newLines}return[lineSegment]})).push(...newHoleLines);let lsh=LineSegmentSpatialHash.from(lineSegments);return appendLines=appendLines.filter(line=>line.points.every(point2=>lsh.queryPoint(point2,1e-4).filter(res=>!res.userData.tags?.includes("hole-independent")).length>0)),appendLines=LineSegmentUtils.deduplicate(appendLines,{necessaryLines:lineSegments}),lineSegments.push(...appendLines),lineSegments}(LineSegmentUtils.clone(this.lineSegments)),this.originalZAverage=zList.reduce((count,num)=>count+num,0)/zList.length,this.box=Box2.fromByLineSegment(this.lineSegments),this.dispatchEvent({type:"dataChange",originalData:this.originalData,data:this.data});let lines=this.getLineSegments(!0);lines=BuildGroup.doubleWall(lines);const{cad:cad2}=this.generateCad(lines);this.dispatchEvent({type:"cadChange",cad:cad2})}}class ExternalDataPipeline extends Pipeline{manager;index=0;lines;constructor(lines){super(),this.lines=lines,this.manager=WallGroupManager.fromByLines1_5(lines),this.use({type:"bayWindow",handle:this.bayWindow.bind(this)}),this.use({type:"wall",handle:this.wall.bind(this)}),this.use({type:"railing",handle:this.railing.bind(this)}),this.use({type:"pillar",handle:this.pillar.bind(this)}),this.use({type:"beam",handle:this.beam.bind(this)}),this.use({type:"holeBayWindow",handle:this.holeBayWindow.bind(this)})}wall({data:{lines:lines,json:json}}){lines.map(line=>{if(WallHole.isBeam(line))return void this.manager.add({type:"beam",lines:[line]});const holeDatas=[...WallHole.getIterator(line)];for(let i=0;i<holeDatas.length;i++)if("byWindow"===holeDatas[i].type&&!holeDatas[i].shape)return void this.manager.add({type:"holeBayWindow",lines:[line]});const id=uuid(),thickness=line.userData.wallWidth??DEFAULT_WALL_WIDTH,index2=json.walls.length;json.walls.push({id:id,start:line.start.toJson2D(),end:line.end.toJson2D(),thickness:thickness,height:line.userData.height??2.8}),holeDatas.forEach(holeData=>{const holeLine=WallHole.holeDataToLine(line,holeData);json.holes.push({id:uuid(),wallId:id,wallIndex:index2,type:holeLine.userData.type,start:holeLine.start.toJson2D(),end:holeLine.end.toJson2D(),height:holeLine.userData.height,thickness:thickness,shape:holeData.shape&&cloneUserData(holeData.shape),groundClearance:holeData.groundClearance})})})}beam({data:{lines:lines,json:json}}){lines.forEach(line=>{const beamLines=[];for(const holeData of WallHole.getIterator(line))if("beam"===holeData.type){const beamLine=WallHole.holeDataToLine(line,holeData);let{groundClearance:groundClearance=0,height:height=0}=holeData;groundClearance+=height,json.beams.push({id:uuid(),start:beamLine.start.toJson2D(),end:beamLine.end.toJson2D(),height:(line.userData.height??2.8)-groundClearance,groundClearance:groundClearance,thickness:line.userData.wallWidth??DEFAULT_WALL_WIDTH}),beamLines.push(beamLine),WallHole.removeHole(line,holeData)}const newLines=LineSegmentUtils.clippingByLines(line,beamLines,clippingLineUserData);newLines.length&&this.manager.add({type:"wall",lines:newLines})})}holeBayWindow({data:{lines:lines}}){lines.forEach(line=>{const holeBayWindowLines=[];for(const holeData of WallHole.getIterator(line))if("byWindow"===holeData.type){const holeLine=WallHole.holeDataToLine(line,holeData),{structure:structure}=WallHole.byWindowStructure(holeLine,holeData);this.manager.add({type:"bayWindow",lines:structure}),holeBayWindowLines.push(holeLine),WallHole.removeHole(line,holeData)}const newLines=LineSegmentUtils.clippingByLines(line,holeBayWindowLines,clippingLineUserData);newLines.length&&this.manager.add({type:"wall",lines:newLines})})}bayWindow({data:{lines:lines}}){let{bwlines:bwlines,path:path=[]}=LineSegmentUtils.group(lines,line=>line.userData.isBayWindow?"bwlines":"path");if(bwlines?.length){const line=bwlines[0].clone();line.userData.isBayWindow=!1;const lug=new LineSegmentUndirectedGraph(path);let startIndex=lug.getIndex(line.start);const visited=/* @__PURE__ */new Set([startIndex]);for(;null!=startIndex;){const set2=lug.getNeighbors(startIndex);if(!set2)return;if(0===set2.size)break;startIndex=[...set2.values()].filter(v2=>!visited.has(v2))[0],void 0!==startIndex&&visited.add(startIndex)}const values=[...visited],points=values.map(v2=>lug.getPoint(v2)),fragmentAttr=[];for(let i=1;i<values.length;i++){const v2=values[i],preV=values[i-1],line2=lug.getLine(v2,preV);line2&&line2.userData.isWindow&&fragmentAttr.push({type:"window",index:i-1})}const windowLine=path.filter(line2=>line2.userData.isWindow);let groundClearance=0,height=0;if(windowLine.length)for(const holes of WallHole.getStorageDataIterator(windowLine[0]))for(let i=0;i<holes.length;i++){const hole=holes[i];if("window"===hole.type){groundClearance=hole.groundClearance??0,height=hole.height??0;break}}WallHole.addHole(line,{p:line.start.toJson(),width:line.length,full:!0,groundClearance:groundClearance,height:height,type:"byWindow",shape:{path:points.map(point2=>point2.toJson()),fragmentAttr:fragmentAttr}}),this.manager.add({type:"wall",lines:[line]})}}railing({data:{lines:lines,json:json}}){lines.forEach(line=>{json.railings.push({id:uuid(),start:line.start.toJson2D(),end:line.end.toJson2D(),thickness:line.userData.wallWidth??DEFAULT_WALL_WIDTH,height:line.userData.height??2.8})})}pillar({data:{lines:lines,json:json}}){const poly=Polygon.fromByLines2(lines),height=lines.reduce((h2,l)=>Math.max(h2,l.userData.height??0),0);json.pillars.push({id:uuid(),height:height,shape:poly.map(p2=>p2.toJson2D())})}transform(){const option={version:"1.0",walls:[],pillars:[],beams:[],holes:[],railings:[],rooms:[],angleCorre:{center:{x:0,y:0},angle:0}},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),option}static appendRooms(json,rooms,z){return Array.isArray(json.rooms)||(json.rooms=[]),rooms.map(room=>{json.rooms.push({position:room.center.clone().toJson(z),shape:room.ploy.map(p2=>p2.clone().toJson2D()),id:room.uuid})}),json}static rotate(json){const{center:center,angle:angle}=json.angleCorre;if(!angle)return json;const cos=Math.cos(angle),sin=Math.sin(angle),rotatePoint=point2=>{const x=point2.x-center.x,y=point2.y-center.y;point2.x=center.x+x*cos-y*sin,point2.y=center.y+x*sin+y*cos};return json.walls.forEach(wall=>{rotatePoint(wall.start),rotatePoint(wall.end)}),json.pillars.forEach(pillar=>{pillar.shape.forEach(rotatePoint)}),json.beams.forEach(beam=>{rotatePoint(beam.start),rotatePoint(beam.end)}),json.holes.forEach(hole=>{rotatePoint(hole.start),rotatePoint(hole.end),hole.shape?.path.forEach(rotatePoint)}),json.railings.forEach(railing=>{rotatePoint(railing.start),rotatePoint(railing.end)}),json.rooms.forEach(room=>{rotatePoint(room.position),room.shape.forEach(rotatePoint)}),json}static toJson(lineSegments,angle=0,updateGroup=!0){let centerVec2=Box2.fromByLineSegment(lineSegments).center.toJson2D();updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));const json=new ExternalDataPipeline(lineSegments).transform();return json.angleCorre.angle=angle,json.angleCorre.center=centerVec2,json}}class ThreeVJia extends Component{static name="ThreeVJia";lineSegments=[];neededUpdate=!0;trajectory;onAddFromParent(){const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf");angleCorrectionDxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0,this.trajectory=angleCorrectionDxf.options.trajectory})}cacheJson;updateData(){if(!this.neededUpdate)return;const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf"),dxf=this.parent?.findComponentByName("Dxf"),rooms=dxf.rooms,lines=angleCorrectionDxf.getLineSegments();this.cacheJson=ThreeVJiaPipeline.externalDataToThreeVJia(ExternalDataPipeline.rotate(ExternalDataPipeline.toJson(lines,angleCorrectionDxf.angle)),getDrawingMaxHeight(lines)),ThreeVJiaPipeline.appendRooms(this.cacheJson,rooms),this.neededUpdate=!1}toJson(name="测试",communityName=""){return this.neededUpdate&&this.updateData(),this.cacheJson.name=name,this.cacheJson.communityName=communityName,this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class Variable extends Component{static name="Variable";originalLineVisible=!0;dxfVisible=!0;whiteModelVisible=!0;isLook=!1;currentWheel=0;pointerMove={x:0,y:0};currentKeyUp="";currentKeyDown="";currentMouseUp="";currentMouseDown="";focus=!1;set(key,value){if(key in this){const oldValue=this[key];this[key]=value,this.dispatchEvent({type:key,value:value,oldValue:oldValue})}}get(key){if(key in this)return this[key]}}const WALL_HEIGHT_KEY=/* @__PURE__ */Symbol("height");class RunJianPipeline extends Pipeline{manager;index=0;z;floor;lines;constructor(lines,z,floor){super(),this.z=z,this.floor=floor,this.lines=lines,this.manager=WallGroupManager.fromByLines(lines),this.use({type:"bayWindow",handle:this.bayWindowHandle.bind(this)}),this.use({type:"doubleWall",handle:this.doubleWallHandle.bind(this)}),this.use({type:"pillar",handle:this.pillarHandle.bind(this)}),this.use({type:"wall",handle:this.wallHandle.bind(this)}),this.use({type:"door",handle:this.doorHandle.bind(this)}),this.use({type:"window",handle:this.wallHandle.bind(this)}),this.use({type:"balconyRailing",handle:this.balconyRailing.bind(this)}),this.use({type:"wallHole",handle:this.wallHoleHandle.bind(this)})}doubleWallHandle({data:{lines:lines},cache:cache2}){const groups=clippingInsertObjectDoubleWall(lines),{door:door,window:windowLines,passageEntrance:passageEntrance,untreatedDoubleWallGroup:untreatedDoubleWallGroup}=WallHoleDrawData.handleHoleDrawData(groups,[]),walls=untreatedDoubleWallGroup.flatMap(lines2=>{if(lines2.length<4)return lines2;if(lines2.length>4){const polygon2=Polygon.fromByLinePath(lines2).getMinimumBoundingRectangle();polygon2&&(lines2=polygon2.toLines())}let newLine=null,wallWidth=0;const line1=(lines2=[...lines2].sort((a2,b4)=>a2.length-b4.length))[0],line2=lines2[1];return newLine=new LineSegment(line1.center.clone(),line2.center.clone()),wallWidth=line1.length,mergeLineUserData(newLine,lines2),newLine.setLength(newLine.length+.002),newLine.userData.wallWidth=wallWidth+.001,[newLine]});this.manager.add({type:"wallHole",lines:windowLines}),this.manager.add({type:"wallHole",lines:door}),this.manager.add({type:"wallHole",lines:passageEntrance}),cache2.wallLines=[...cache2.wallLines,...walls,...windowLines,...door,...passageEntrance]}pillarHandle({data:{lines:lines,json:json}}){try{const rect=Polygon.fromByLines2(lines).getMinimumBoundingRectangle();if(!rect)return;const heights=lines.map(line=>"number"==typeof line.userData.height?line.userData.height:"number"==typeof line.userData.rooftopPz?line.userData.rooftopPz-this.z:0),center=rect.getCenter(),dist1=rect[1].distance(rect[0]),dist2=rect[2].distance(rect[1]),width=Math.min(dist1,dist2),height=Math.max(...heights);json.components.push({index:json.components.length,id:json.components.length,name:"柱",floor:this.floor,length:Math.max(dist1,dist2),width:width,height:height,x:center.x,y:center.y,z:this.z+.5*height})}catch(error){this.manager.add({type:"wall",lines:lines})}}wallHandle({data:{lines:lines},cache:cache2}){const alignConfig2={esp:.3,onMergeLine:mergeLineUserData,onGroup(group2,projValues,axis){if(group2.length<=1)return;const dist=precision4((Math.max(...projValues)-Math.min(...projValues))*axis.length);dist<DEFAULT_WALL_WIDTH||group2.forEach(line=>{line.userData.wallWidth=Math.min(dist,MAX_WALL_WIDTH)})},onLayoutDesign(lines2,delKey){const holes=[];lines2=lines2.filter(line=>(holes.push(...WallHole.getIterator(line)),WallHole.clear(line),!line.currentData[delKey])),WallHole.splitHole(holes,lines2)}},holeLines=(lines=LineSegmentUtils.GroupBuilder(LineSegmentUtils.group(lines,line=>WallHole.isBeam(line)?"beam":"line")).handle("beam",beamLines=>beamLines=AlignToParallelSegments.align(beamLines,alignConfig2)).merge()).flatMap(line=>WallHoleDrawData.singleHoleLine(line)??[]);this.manager.add({type:"wallHole",lines:holeLines}),cache2.wallLines.push(...lines.filter(line=>!WallHole.isBeam(line)))}doorHandle({data:{lines:lines},cache:cache2}){const doors=lines.map(line=>{const doorLine=new LineSegment(line.start.clone(),line.end.clone());return doorLine.userData={groundClearance:line.userData.drawDoorData?.sillHeight,height:line.userData.drawDoorData?.height,type:"door",wallHeight:line.userData.drawDoorData?.height,wallWidth:void 0},doorLine});this.manager.add({type:"wallHole",lines:doors}),cache2.wallLines.push(...doors)}bayWindowHandle({data:{lines:lines},cache:cache2}){const info=BayWindowHelper.computedInfo(lines);if(info){const{dottedLine:dottedLine,windowLine:windowLine,depth:depth,side:side}=info,line=new LineSegment(dottedLine.start.clone(),dottedLine.end.clone()),win=windowLine?.userData.drawWindow&&windowLine.userData.drawWindow[0];"LEFT"===side&&line.swapValue(),line.translate(.5*-DEFAULT_WALL_WIDTH,line.normal()),line.userData={groundClearance:win?.groundClearance??0,height:win?.height,type:"bay_window",wallHeight:win?.height,wallWidth:void 0,depth:depth??.5,openSide:side},this.manager.add({type:"wallHole",lines:[line]}),line.setLength(line.length+.001),cache2.wallLines.push(line)}}balconyRailing({data:{lines:lines},cache:cache2}){const brls=lines.map(line=>{line.currentData[WALL_HEIGHT_KEY]=line.userData.height;const brl=new LineSegment(line.start.clone(),line.end.clone());return brl.userData={groundClearance:0,height:line.userData.height,type:"RAILING",wallWidth:void 0},brl});this.manager.add({type:"wallHole",lines:brls}),cache2.wallLines.push(...lines)}wallHoleHandle({data:{lines:lines,json:json}}){lines.forEach(line=>{if(line.length<1e-4)return;if("beam"!==line.userData.type)return;const center=line.center,startZ=precision4Nullable(line.userData?.height??2.1),height=line.userData.maxHeight-startZ,width=line.userData.wallWidth??DEFAULT_WALL_WIDTH;json.components.push({index:json.components.length,id:json.components.length,name:"梁",floor:this.floor,length:line.length,width:width,height:height,x:center.x,y:center.y,z:this.z+startZ+.5*height})})}transform(){const option={version:"1.0",components:[],title:"1F",rooms:[],floor:this.floor},cache2={wallLines:[]};return this.manager.forEach(group2=>this.run(group2.type,{lines:group2.lines,json:option},cache2)),cache2.wallLines.forEach(line=>{const center=line.center,height=precision4(line.userData.height??0),width=precision4(Math.max(line.userData.wallWidth?line.userData.wallWidth:DEFAULT_WALL_WIDTH,DEFAULT_WALL_WIDTH));option.components.push({index:option.components.length,id:option.components.length,name:"墙",floor:this.floor,length:line.length,width:width,height:height,x:center.x,y:center.y,z:this.z+.5*height})}),option}static toJson(lineSegments,opt){const{z:z=0,floor:floor=1,angle:angle=0,updateGroup:updateGroup=!1}=opt??{};let centerVec2=null;lineSegments=LineSegmentUndirectedGraph.rotate(lineSegments.map(line=>line.clone()),angle,(line,center,angle2)=>{centerVec2||(centerVec2={x:center.x,y:center.y}),WallHole.forEachStorageType(line,data=>{data.forEach(item=>{const point2=Point.from(item.p);point2.rotate(center,angle2),item.p=point2.toJson(item.p.z)})})}),updateGroup&&(lineSegments=BuildGroup.doubleWall(lineSegments));return new RunJianPipeline(lineSegments,z,floor).transform()}}class RunJian extends Component{static name="RunJian";lineSegments=[];neededUpdate=!0;trajectory;onAddFromParent(){const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf");angleCorrectionDxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0,this.trajectory=angleCorrectionDxf.options.trajectory})}cacheJson;updateData(){if(!this.neededUpdate)return;const angleCorrectionDxf=this.parent?.findComponentByName("BoundExtDxf"),dxf=this.parent?.findComponentByName("Dxf");this.cacheJson=RunJianPipeline.toJson(angleCorrectionDxf.getLineSegments(),{angle:angleCorrectionDxf.angle,floor:1});dxf.rooms.forEach(room=>{this.cacheJson?.rooms.push({...room.center.toJson(dxf.originalZAverage),area:room.ploy.area()})}),this.neededUpdate=!1}toJson(floor=1){return this.neededUpdate&&this.updateData(),this.cacheJson.floor=floor,this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class ExternalData extends Component{static name="ExternalData";lineSegments=[];neededUpdate=!0;onAddFromParent(){const dxf=this.parent?.findComponentByName("Dxf");dxf.addEventListener("cadChange",async()=>{this.neededUpdate=!0})}cacheJson;updateData(){if(!this.neededUpdate)return;const dxf=this.parent?.findComponentByName("Dxf"),lines=dxf.getLineSegments(!0),rooms=dxf.rooms;this.cacheJson=ExternalDataPipeline.toJson(lines,dxf.angle),ExternalDataPipeline.appendRooms(this.cacheJson,rooms,dxf.originalZAverage),this.neededUpdate=!1}toJson(){return this.neededUpdate&&this.updateData(),this.cacheJson}async download(filename="download.json"){if("undefined"!=typeof window){const blob=new Blob([JSON.stringify(this.toJson())]),a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){(await include("fs",!1)).writeFileSync(filename,JSON.stringify(this.toJson()))}}}class DxfSystem extends ComponentContainer{Dxf;Variable;BoundExtDxf;environment;static finalInstance;constructor(){super(),this.environment="undefined"!=typeof window?"browser":"undefined"!=typeof global?"node":"unknown",this.Dxf=new Dxf,this.BoundExtDxf=new BoundExtDxf,this.Variable=new Variable,this.addComponent(this.Variable),this.addComponent(this.Dxf),this.addComponent(this.BoundExtDxf),this.addComponent(new ThreeVJia),this.addComponent(new RunJian),this.addComponent(new ExternalData),DxfSystem.finalInstance=this}usePlugin(plugin){return"function"==typeof plugin&&plugin.call(this,this),this}destroy(){this.components.concat().forEach(com=>{com.destroy()}),this.components.concat().forEach(com=>{this.removeComponent(com)})}}const components={ThreeVJia:ThreeVJia,Variable:Variable,Dxf:Dxf,BoundExtDxf:BoundExtDxf},index$2=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BoundExt:BoundExt,DoubleWallFinder:DoubleWallFinder,DxfSystem:DxfSystem,LineGroupType:LineGroupType,SceneAutoGenerat:SceneAutoGenerat,ThreeVJiaPipeline:ThreeVJiaPipeline,cad:cad,clippingDoubleWall:clippingDoubleWall,clippingInsertObjectDoubleWall:clippingInsertObjectDoubleWall,components:components,findDiscretePoint:findDiscretePoint,findDiscretePoint2:findDiscretePoint2,findDiscretePointLine:findDiscretePointLine,findDiscretePointLine2:findDiscretePointLine2,tools:tools},Symbol.toStringTag,{value:"Module"}));function drawText$1(text,point2,style,offset=.001){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer"),editor=dxfSystem.findComponentByName("EditorView");if(renderer){const obj3d=renderer.createText(text,point2,style,editor?.container2);return obj3d.position.z=offset,obj3d}}}const exporter=new OBJExporter;let glbExporter;class WhiteModel extends Component{static name="WhiteModel";Dxf=null;Variable=null;whiteModelGroup=new THREE.Group;groundBuildMode="none";itemList=[];promise;setItemList(itemList){Array.isArray(itemList)?this.itemList=itemList:"itemInfo"in itemList&&(this.itemList=itemList.itemInfo)}onAddFromParent(parent){this.Dxf=parent.findComponentByName("Dxf"),this.Variable=parent.findComponentByName("Variable"),this.Dxf?.addEventListener("cadChange",({options:options})=>{this.setItemList(options?.publicInfo??[]),this.promise=this.updateModel()})}regenerateModel(){this.promise=this.updateModel()}rotateAroundPoint(object,point2,angle,axis=new THREE.Vector3(0,0,1)){object.position.sub(point2),object.position.applyAxisAngle(axis,angle),object.position.add(point2),object.rotateOnWorldAxis(axis,angle)}center=Point.zero();angle=0;async updateModel(){const dxfSystem=this.parent;this.Variable?.set("whiteModelVisible",!1);let lines=dxfSystem.BoundExtDxf.getLineSegments(!0);lines=lines.flatMap(line=>{const holes=Array.from(WallHole.getIterator(line)).filter(hole=>"byWindow"===hole.type);return[...LineSegmentUtils.clippingByLines(line,holes.map(hole=>WallHole.holeDataToLine(line,hole)),clippingLineUserData),...holes.flatMap(hole=>WallHole.byWindowStructure(line,hole).structure)]});const sceneAutoGenerat=new SceneAutoGenerat(lines,this.itemList,dxfSystem.Dxf.originalZAverage,dxfSystem.Dxf.options.trajectory);await sceneAutoGenerat.init(),"none"!==this.groundBuildMode&&sceneAutoGenerat.buildPlane(dxfSystem.Dxf.getLineSegments(),this.groundBuildMode,dxfSystem.Dxf.rooms);let group2=sceneAutoGenerat.scene;if(group2){this.whiteModelGroup.clear(),group2=group2.clone(!0);const center=dxfSystem.BoundExtDxf.box.center;this.center.copy(center),group2.position.sub(new THREE.Vector3(center.x,center.y,0));const container=new THREE.Group;container.add(group2),container.rotation.z=dxfSystem.BoundExtDxf.angle,container.position.z=this.Dxf?.originalZAverage??0,container.userData.correction=!0,container.userData.angle=dxfSystem.BoundExtDxf.angle,this.angle=dxfSystem.BoundExtDxf.angle,this.whiteModelGroup.add(container)}return this.dispatchEvent({type:"updateModel",whiteModelGroup:this.whiteModelGroup}),this.whiteModelGroup}toOBJ(){return new Promise(async resolve=>{await this.promise;const group2=this.whiteModelGroup.clone(!0),center=this.center,angle=this.angle,cos=Math.cos(angle),sin=Math.sin(angle),vertex=new THREE.Vector3;group2.traverse(obj=>{if(!(obj instanceof THREE.Mesh))return;obj.geometry=obj.geometry.clone();const geometry=obj.geometry,position=geometry.attributes.position;if(!position)return;obj.updateMatrixWorld(!0);const matrixWorld=obj.matrixWorld,inverseMatrix=matrixWorld.clone().invert();for(let i=0;i<position.count;i++){vertex.fromBufferAttribute(position,i),vertex.applyMatrix4(matrixWorld);const x=vertex.x-center.x,y=vertex.y-center.y;vertex.x=center.x+x*cos-y*sin,vertex.y=center.y+x*sin+y*cos,vertex.applyMatrix4(inverseMatrix),position.setXYZ(i,vertex.x,vertex.y,vertex.z)}position.needsUpdate=!0,geometry.computeBoundingBox(),geometry.computeBoundingSphere()}),resolve(exporter.parse(group2))})}toGltf(binary=!0){return glbExporter||(glbExporter=new gltf.GLTFExporter),new Promise(async resolve=>{await this.promise,glbExporter.parse(this.whiteModelGroup.children,gltf2=>{resolve(gltf2)},()=>{resolve(void 0)},{binary:binary})})}async toOBJBlob(){const buffer=await this.toOBJ();if(buffer)return new Blob([buffer],{type:"application/octet-stream"})}async toGltfBlob(binary=!0){const buffer=await this.toGltf(binary);if(buffer)return binary?new Blob([buffer],{type:"application/octet-stream"}):new Blob([JSON.stringify(buffer)],{type:"application/json"})}async downloadOBJ(filename){if("undefined"!=typeof window){const blob=await this.toOBJBlob();if(!blob)return;const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){const buffer=await this.toOBJ();if(buffer){(await include("fs",!1)).writeFileSync(filename,buffer)}}}async downloadGltf(filename,binary=!0){if("undefined"!=typeof window){const blob=await this.toGltfBlob(binary);if(!blob)return;const a2=document.createElement("a");a2.href=URL.createObjectURL(blob),a2.download=filename,a2.click()}else if("undefined"!=typeof global){const buffer=await this.toGltf(binary);if(buffer){(await include("fs",!1)).writeFileSync(filename,binary?Buffer.from(buffer):JSON.stringify(buffer))}}}}class DxfLineModel extends Component{static name="DxfLineModel";dxfLineModel=new THREE.LineSegments;dxfModelGroup=new THREE.Group;onAddFromParent(parent){const dxf=parent.findComponentByName("BoundExtDxf");this.dxfModelGroup.add(this.dxfLineModel),dxf?.addEventListener("cadChange",()=>this.updateMode())}updateMode(){const dxf=this.parent?.findComponentByName("BoundExtDxf");this.dxfLineModel.clear();const cad2=dxf.cadQueue.get("cad"),dxfArray=new Float32Array(cad2.groups.flatMap(group2=>"wall"!==group2.type?[]:group2.lines.flatMap(line=>line.points.flatMap(p2=>[p2.x,p2.y,0]))));this.dxfLineModel.geometry=(new THREE.BufferGeometry).setAttribute("position",new THREE.BufferAttribute(dxfArray,3,!0)),this.dxfModelGroup.position.z=dxf.originalZAverage,this.dispatchEvent({type:"modelUpdate",model:this.dxfModelGroup})}}const index$1=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,DxfLineModel:DxfLineModel,WhiteModel:WhiteModel},Symbol.toStringTag,{value:"Module"}));function Model3dPlugin_(dxfSystem,option={}){const{whiteModel:whiteModel=!0,dxfLineModel:dxfLineModel=!0}=option;dxfLineModel&&dxfSystem.addComponent(new DxfLineModel),whiteModel&&dxfSystem.addComponent(new WhiteModel)}const ModelDataPlugin=Object.assign(Model3dPlugin_,{create:(option={})=>dxfSystem=>Model3dPlugin_(dxfSystem,option)}),index=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ModelDataPlugin:ModelDataPlugin,components:index$1},Symbol.toStringTag,{value:"Module"})),inBrowser="undefined"!=typeof window;let mark,measure;if("production"!==process.env.NODE_ENV){const perf2=inBrowser&&window.performance;perf2&&perf2.mark&&perf2.measure&&perf2.clearMarks&&perf2.clearMeasures&&(mark=tag=>{perf2.mark(tag)},measure=(name,startTag,endTag)=>{perf2.measure(name,startTag,endTag),perf2.clearMarks(startTag),perf2.clearMarks(endTag)})}const RE_ARGS=/\{([0-9a-zA-Z]+)\}/g;function format$1(message,...args){return 1===args.length&&isObject(args[0])&&(args=args[0]),args&&args.hasOwnProperty||(args={}),message.replace(RE_ARGS,(match,identifier)=>args.hasOwnProperty(identifier)?args[identifier]:"")}const makeSymbol=(name,shareable=!1)=>shareable?Symbol.for(name):Symbol(name),friendlyJSONstringify=json=>JSON.stringify(json).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029").replace(/\u0027/g,"\\u0027"),isNumber=val=>"number"==typeof val&&isFinite(val);function toDevtoolsGroupId(type,key){return isString(key)||isNumber(key)?`${type}:${key}`:type}const isDate=val=>"[object Date]"===toTypeString(val),isRegExp=val=>"[object RegExp]"===toTypeString(val),isEmptyObject=val=>isPlainObject(val)&&0===Object.keys(val).length,assign=Object.assign,_create=Object.create,create=(obj=null)=>_create(obj);let _globalThis;const getGlobalThis=()=>_globalThis||(_globalThis="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:create()),hasOwnProperty=Object.prototype.hasOwnProperty;function hasOwn(obj,key){return hasOwnProperty.call(obj,key)}const isArray=Array.isArray,isFunction=val=>"function"==typeof val,isString=val=>"string"==typeof val,isBoolean=val=>"boolean"==typeof val,isObject=val=>null!==val&&"object"==typeof val,objectToString=Object.prototype.toString,toTypeString=value=>objectToString.call(value),isPlainObject=val=>"[object Object]"===toTypeString(val);function join(items,separator=""){return items.reduce((str,item,index2)=>0===index2?str+item:str+separator+item,"")}function warn(msg,err){"undefined"!=typeof console&&(console.warn("[intlify] "+msg),err&&console.warn(err.stack))}const hasWarned={};function warnOnce(msg){hasWarned[msg]||(hasWarned[msg]=!0,warn(msg))}function escapeHtml(rawText){return rawText.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/").replace(/=/g,"=")}const javascriptSchemePattern=/^javascript:/i,urlAttributePattern=/^(?:href|src|action|formaction)$/i,numericCharacterReferencePattern=/&#(?:x([0-9a-f]+)|(\d+));?/gi,namedWhitespaceCharacterReferencePattern=/&(?:Tab|NewLine);/g,colonCharacterReferencePattern=/:?/gi,controlOrWhitespacePattern=/[\u0000-\u0020\u007f-\u009f]/g,eventHandlerPattern=/(?:^|[\s"'<>/])on\w+\s*=\s*["']?[^"'>]+["']?/i,eventHandlerAttributePattern=/(^|[\s"'<>/])on(\w+\s*=)/gi,unquotedUrlAttributePattern=/(^|[\s"'<>/])((?:href|src|action|formaction)\s*=\s*)([^\s"'=<>`]+)/gi;function decodeNumericCharacterReference(match,hex,decimal){const digits=hex||decimal;if(!digits)return match;const codePoint=Number.parseInt(digits,hex?16:10);return codePoint<=127?String.fromCharCode(codePoint):match}function hasJavascriptScheme(value){const normalized=value.replace(numericCharacterReferencePattern,decodeNumericCharacterReference).replace(namedWhitespaceCharacterReferencePattern,"").replace(colonCharacterReferencePattern,":").replace(controlOrWhitespacePattern,"");return javascriptSchemePattern.test(normalized)}function sanitizeAttributeValue(attrName,value){if(urlAttributePattern.test(attrName)&&hasJavascriptScheme(value))return"about:blank";const sanitizedValue="style"===attrName.toLowerCase()?function(value){const urlPattern=/url\s*\(/gi;let match,sanitized="",cursor=0;for(;null!==(match=urlPattern.exec(value));){const urlStart=match.index,openParenIndex=urlPattern.lastIndex-1;let index2=openParenIndex+1,depth=1,quote=null;for(;index2<value.length;index2++){const char=value[index2];if(quote)char===quote&&(quote=null);else if('"'===char||"'"===char)quote=char;else if("("===char)depth++;else if(")"===char&&(depth--,0===depth))break}if(0!==depth)break;const rawUrlValue=value.slice(openParenIndex+1,index2).trim(),unquotedUrlValue=rawUrlValue.startsWith('"')&&rawUrlValue.endsWith('"')||rawUrlValue.startsWith("'")&&rawUrlValue.endsWith("'")?rawUrlValue.slice(1,-1).trim():rawUrlValue;sanitized+=value.slice(cursor,urlStart),sanitized+=hasJavascriptScheme(unquotedUrlValue)?"url(about:blank)":value.slice(urlStart,index2+1),cursor=index2+1}return sanitized+value.slice(cursor)}(value):value;return function(value){return value.replace(/&(?![a-z0-9#]{2,6};)/gi,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}(sanitizedValue)}function createEmitter(){const events=/* @__PURE__ */new Map;return{events:events,on(event,handler){const handlers=events.get(event);handlers&&handlers.push(handler)||events.set(event,[handler])},off(event,handler){const handlers=events.get(event);handlers&&handlers.splice(handlers.indexOf(handler)>>>0,1)},emit(event,payload){(events.get(event)||[]).slice().map(handler=>handler(payload)),(events.get("*")||[]).slice().map(handler=>handler(event,payload))}}}const isNotObjectOrIsArray=val=>!isObject(val)||isArray(val);function deepCopy(src,des){if(isNotObjectOrIsArray(src)||isNotObjectOrIsArray(des))throw new Error("Invalid value");const stack=[{src:src,des:des}];for(;stack.length;){const{src:src2,des:des2}=stack.pop();Object.keys(src2).forEach(key=>{if("__proto__"===key)return;const value=src2[key];if(isArray(value)){const copied=[];copied.length=value.length,des2[key]=copied,stack.push({src:value,des:copied})}else isObject(value)?(isObject(des2[key])&&!isArray(des2[key])||(des2[key]=create()),stack.push({src:value,des:des2[key]})):des2[key]=value})}}function createLocation(start,end,source){return{start:start,end:end}}const CompileErrorCodes_EXPECTED_TOKEN=1,CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER=2,CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER=3,CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE=4,CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE=5,CompileErrorCodes_UNBALANCED_CLOSING_BRACE=6,CompileErrorCodes_UNTERMINATED_CLOSING_BRACE=7,CompileErrorCodes_EMPTY_PLACEHOLDER=8,CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER=9,CompileErrorCodes_INVALID_LINKED_FORMAT=10,CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL=11,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER=12,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY=13,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS=14,CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE=15,CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE=16,errorMessages$2={[CompileErrorCodes_EXPECTED_TOKEN]:"Expected token: '{0}'",[CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER]:"Invalid token in placeholder: '{0}'",[CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]:"Unterminated single quote in placeholder",[CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE]:"Unknown escape sequence: \\{0}",[CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE]:"Invalid unicode escape sequence: {0}",[CompileErrorCodes_UNBALANCED_CLOSING_BRACE]:"Unbalanced closing brace",[CompileErrorCodes_UNTERMINATED_CLOSING_BRACE]:"Unterminated closing brace",[CompileErrorCodes_EMPTY_PLACEHOLDER]:"Empty placeholder",[CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER]:"Not allowed nest placeholder",[CompileErrorCodes_INVALID_LINKED_FORMAT]:"Invalid linked format",[CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL]:"Plural must have messages",[CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER]:"Unexpected empty linked modifier",[CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY]:"Unexpected empty linked key",[CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS]:"Unexpected lexical analysis in token: '{0}'",[CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE]:"unhandled codegen node type: '{0}'",[CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE]:"unhandled mimifier node type: '{0}'"};function createCompileError(code,loc,options={}){const{domain:domain,messages:messages2,args:args}=options,msg="production"!==process.env.NODE_ENV?format$1((messages2||errorMessages$2)[code]||"",...args||[]):code,error=new SyntaxError(String(msg));return error.code=code,loc&&(error.location=loc),error.domain=domain,error}function defaultOnError(error){throw error}const RE_HTML_TAG=/<\/?[\w\s="/.':;#-\/]+>/,CHAR_LS=String.fromCharCode(8232),CHAR_PS=String.fromCharCode(8233);function createScanner(str){const _buf=str;let _index=0,_line=1,_column=1,_peekOffset=0;const isCRLF=index3=>"\r"===_buf[index3]&&"\n"===_buf[index3+1],isPS=index3=>_buf[index3]===CHAR_PS,isLS=index3=>_buf[index3]===CHAR_LS,isLineEnd=index3=>isCRLF(index3)||(index3=>"\n"===_buf[index3])(index3)||isPS(index3)||isLS(index3),charAt=offset=>isCRLF(offset)||isPS(offset)||isLS(offset)?"\n":_buf[offset];function next(){return _peekOffset=0,isLineEnd(_index)&&(_line++,_column=0),isCRLF(_index)&&_index++,_index++,_column++,_buf[_index]}return{index:()=>_index,line:()=>_line,column:()=>_column,peekOffset:()=>_peekOffset,charAt:charAt,currentChar:()=>charAt(_index),currentPeek:()=>charAt(_index+_peekOffset),next:next,peek:function(){return isCRLF(_index+_peekOffset)&&_peekOffset++,_peekOffset++,_buf[_index+_peekOffset]},reset:function(){_index=0,_line=1,_column=1,_peekOffset=0},resetPeek:function(offset=0){_peekOffset=offset},skipToPeek:function(){const target=_index+_peekOffset;for(;target!==_index;)next();_peekOffset=0}}}const EOF=void 0;function createTokenizer(source,options={}){const location=!1!==options.location,_scnr=createScanner(source),currentOffset=()=>_scnr.index(),currentPosition=()=>{return line=_scnr.line(),column=_scnr.column(),offset=_scnr.index(),{line:line,column:column,offset:offset};var line,column,offset},_initLoc=currentPosition(),_initOffset=currentOffset(),_context={currentType:13,offset:_initOffset,startLoc:_initLoc,endLoc:_initLoc,lastType:13,lastOffset:_initOffset,lastStartLoc:_initLoc,lastEndLoc:_initLoc,braceNest:0,inLinked:!1,text:""},context=()=>_context,{onError:onError}=options;function emitError(code,pos,offset,...args){const ctx=context();if(pos.column+=offset,pos.offset+=offset,onError){const err=createCompileError(code,location?createLocation(ctx.startLoc,pos):null,{domain:"tokenizer",args:args});onError(err)}}function getToken(context2,type,value){context2.endLoc=currentPosition(),context2.currentType=type;const token={type:type};return location&&(token.loc=createLocation(context2.startLoc,context2.endLoc)),null!=value&&(token.value=value),token}const getEndToken=context2=>getToken(context2,13);function eat(scnr,ch){return scnr.currentChar()===ch?(scnr.next(),ch):(emitError(CompileErrorCodes_EXPECTED_TOKEN,currentPosition(),0,ch),"")}function peekSpaces(scnr){let buf="";for(;" "===scnr.currentPeek()||"\n"===scnr.currentPeek();)buf+=scnr.currentPeek(),scnr.peek();return buf}function skipSpaces(scnr){const buf=peekSpaces(scnr);return scnr.skipToPeek(),buf}function isIdentifierStart(ch){if(ch===EOF)return!1;const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||95===cc}function isListIdentifierStart(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret=function(ch){if(ch===EOF)return!1;const cc=ch.charCodeAt(0);return cc>=48&&cc<=57}("-"===scnr.currentPeek()?scnr.peek():scnr.currentPeek());return scnr.resetPeek(),ret}function isPluralStart(scnr){peekSpaces(scnr);const ret="|"===scnr.currentPeek();return scnr.resetPeek(),ret}function isTextStart(scnr,reset=!0){const fn2=(hasSpace=!1,prev="")=>{const ch=scnr.currentPeek();return"{"===ch?hasSpace:"@"!==ch&&ch?"|"===ch?!(" "===prev||"\n"===prev):" "===ch?(scnr.peek(),fn2(!0," ")):"\n"!==ch||(scnr.peek(),fn2(!0,"\n")):hasSpace},ret=fn2();return reset&&scnr.resetPeek(),ret}function takeChar(scnr,fn2){const ch=scnr.currentChar();return ch===EOF?EOF:fn2(ch)?(scnr.next(),ch):null}function isIdentifier(ch){const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||95===cc||36===cc}function takeIdentifierChar(scnr){return takeChar(scnr,isIdentifier)}function isNamedIdentifier(ch){const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||95===cc||36===cc||45===cc}function takeNamedIdentifierChar(scnr){return takeChar(scnr,isNamedIdentifier)}function isDigit(ch){const cc=ch.charCodeAt(0);return cc>=48&&cc<=57}function takeDigit(scnr){return takeChar(scnr,isDigit)}function isHexDigit(ch){const cc=ch.charCodeAt(0);return cc>=48&&cc<=57||cc>=65&&cc<=70||cc>=97&&cc<=102}function takeHexDigit(scnr){return takeChar(scnr,isHexDigit)}function getDigits(scnr){let ch="",num="";for(;ch=takeDigit(scnr);)num+=ch;return num}function isLiteral2(ch){return"'"!==ch&&"\n"!==ch}function readEscapeSequence(scnr){const ch=scnr.currentChar();switch(ch){case"\\":case"'":return scnr.next(),`\\${ch}`;case"u":return readUnicodeEscapeSequence(scnr,ch,4);case"U":return readUnicodeEscapeSequence(scnr,ch,6);default:return emitError(CompileErrorCodes_UNKNOWN_ESCAPE_SEQUENCE,currentPosition(),0,ch),""}}function readUnicodeEscapeSequence(scnr,unicode,digits){eat(scnr,unicode);let sequence="";for(let i=0;i<digits;i++){const ch=takeHexDigit(scnr);if(!ch){emitError(CompileErrorCodes_INVALID_UNICODE_ESCAPE_SEQUENCE,currentPosition(),0,`\\${unicode}${sequence}${scnr.currentChar()}`);break}sequence+=ch}return`\\${unicode}${sequence}`}function isInvalidIdentifier(ch){return"{"!==ch&&"}"!==ch&&" "!==ch&&"\n"!==ch}function readInvalidIdentifier(scnr){skipSpaces(scnr);let ch="",identifiers="";for(;ch=takeChar(scnr,isInvalidIdentifier);)identifiers+=ch;return identifiers}function readPlural(scnr){skipSpaces(scnr);const plural=eat(scnr,"|");return skipSpaces(scnr),plural}function readTokenInPlaceholder(scnr,context2){let token=null;switch(scnr.currentChar()){case"{":return context2.braceNest>=1&&emitError(CompileErrorCodes_NOT_ALLOW_NEST_PLACEHOLDER,currentPosition(),0),scnr.next(),token=getToken(context2,2,"{"),skipSpaces(scnr),context2.braceNest++,token;case"}":return context2.braceNest>0&&2===context2.currentType&&emitError(CompileErrorCodes_EMPTY_PLACEHOLDER,currentPosition(),0),scnr.next(),token=getToken(context2,3,"}"),context2.braceNest--,context2.braceNest>0&&skipSpaces(scnr),context2.inLinked&&0===context2.braceNest&&(context2.inLinked=!1),token;case"@":return context2.braceNest>0&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),token=readTokenInLinked(scnr,context2)||getEndToken(context2),context2.braceNest=0,token;default:{let validNamedIdentifier=!0,validListIdentifier=!0,validLiteral=!0;if(isPluralStart(scnr))return context2.braceNest>0&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token;if(context2.braceNest>0&&(4===context2.currentType||5===context2.currentType||6===context2.currentType))return emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),context2.braceNest=0,readToken(scnr,context2);if(validNamedIdentifier=function(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret=isIdentifierStart(scnr.currentPeek());return scnr.resetPeek(),ret}(scnr,context2))return token=getToken(context2,4,function(scnr){skipSpaces(scnr);let ch="",name="";for(;ch=takeNamedIdentifierChar(scnr);)name+=ch;const currentChar=scnr.currentChar();if(currentChar&&"}"!==currentChar&¤tChar!==EOF&&" "!==currentChar&&"\n"!==currentChar&&" "!==currentChar){const invalidPart=readInvalidIdentifier(scnr);return emitError(CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER,currentPosition(),0,name+invalidPart),name+invalidPart}return scnr.currentChar()===EOF&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),name}(scnr)),skipSpaces(scnr),token;if(validListIdentifier=isListIdentifierStart(scnr,context2))return token=getToken(context2,5,function(scnr){skipSpaces(scnr);let value="";return"-"===scnr.currentChar()?(scnr.next(),value+=`-${getDigits(scnr)}`):value+=getDigits(scnr),scnr.currentChar()===EOF&&emitError(CompileErrorCodes_UNTERMINATED_CLOSING_BRACE,currentPosition(),0),value}(scnr)),skipSpaces(scnr),token;if(validLiteral=function(scnr,context2){const{currentType:currentType}=context2;if(2!==currentType)return!1;peekSpaces(scnr);const ret="'"===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2))return token=getToken(context2,6,function(scnr){skipSpaces(scnr),eat(scnr,"'");let ch="",literal="";for(;ch=takeChar(scnr,isLiteral2);)literal+="\\"===ch?readEscapeSequence(scnr):ch;const current=scnr.currentChar();return"\n"===current||current===EOF?(emitError(CompileErrorCodes_UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER,currentPosition(),0),"\n"===current&&(scnr.next(),eat(scnr,"'")),literal):(eat(scnr,"'"),literal)}(scnr)),skipSpaces(scnr),token;if(!validNamedIdentifier&&!validListIdentifier&&!validLiteral)return token=getToken(context2,12,readInvalidIdentifier(scnr)),emitError(CompileErrorCodes_INVALID_TOKEN_IN_PLACEHOLDER,currentPosition(),0,token.value),skipSpaces(scnr),token;break}}return token}function readTokenInLinked(scnr,context2){const{currentType:currentType}=context2;let token=null;const ch=scnr.currentChar();switch(7!==currentType&&8!==currentType&&11!==currentType&&9!==currentType||"\n"!==ch&&" "!==ch||emitError(CompileErrorCodes_INVALID_LINKED_FORMAT,currentPosition(),0),ch){case"@":return scnr.next(),token=getToken(context2,7,"@"),context2.inLinked=!0,token;case".":return skipSpaces(scnr),scnr.next(),getToken(context2,8,".");case":":return skipSpaces(scnr),scnr.next(),getToken(context2,9,":");default:return isPluralStart(scnr)?(token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token):function(scnr,context2){const{currentType:currentType}=context2;if(7!==currentType)return!1;peekSpaces(scnr);const ret="."===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2)||function(scnr,context2){const{currentType:currentType}=context2;if(7!==currentType&&11!==currentType)return!1;peekSpaces(scnr);const ret=":"===scnr.currentPeek();return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),readTokenInLinked(scnr,context2)):function(scnr,context2){const{currentType:currentType}=context2;if(8!==currentType)return!1;peekSpaces(scnr);const ret=isIdentifierStart(scnr.currentPeek());return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),getToken(context2,11,function(scnr){let ch="",name="";for(;ch=takeIdentifierChar(scnr);)name+=ch;return name}(scnr))):function(scnr,context2){const{currentType:currentType}=context2;if(9!==currentType)return!1;const fn2=()=>{const ch=scnr.currentPeek();return"{"===ch?isIdentifierStart(scnr.peek()):!("@"===ch||"|"===ch||":"===ch||"."===ch||" "===ch||!ch)&&("\n"===ch?(scnr.peek(),fn2()):isTextStart(scnr,!1))},ret=fn2();return scnr.resetPeek(),ret}(scnr,context2)?(skipSpaces(scnr),"{"===ch?readTokenInPlaceholder(scnr,context2)||token:getToken(context2,10,function(scnr){const fn2=buf=>{const ch=scnr.currentChar();return"{"!==ch&&"@"!==ch&&"|"!==ch&&"("!==ch&&")"!==ch&&ch?" "===ch?buf:(buf+=ch,scnr.next(),fn2(buf)):buf};return fn2("")}(scnr))):(7===currentType&&emitError(CompileErrorCodes_INVALID_LINKED_FORMAT,currentPosition(),0),context2.braceNest=0,context2.inLinked=!1,readToken(scnr,context2))}}function readToken(scnr,context2){let token={type:13};if(context2.braceNest>0)return readTokenInPlaceholder(scnr,context2)||getEndToken(context2);if(context2.inLinked)return readTokenInLinked(scnr,context2)||getEndToken(context2);switch(scnr.currentChar()){case"{":return readTokenInPlaceholder(scnr,context2)||getEndToken(context2);case"}":return emitError(CompileErrorCodes_UNBALANCED_CLOSING_BRACE,currentPosition(),0),scnr.next(),getToken(context2,3,"}");case"@":return readTokenInLinked(scnr,context2)||getEndToken(context2);default:if(isPluralStart(scnr))return token=getToken(context2,1,readPlural(scnr)),context2.braceNest=0,context2.inLinked=!1,token;if(isTextStart(scnr))return getToken(context2,0,function(scnr){let buf="";for(;;){const ch=scnr.currentChar();if("\\"===ch){const nextCh=scnr.peek();"{"===nextCh||"}"===nextCh||"@"===nextCh||"|"===nextCh||"\\"===nextCh?(buf+=ch+nextCh,scnr.next(),scnr.next()):(scnr.resetPeek(),buf+=ch,scnr.next())}else{if("{"===ch||"}"===ch||"@"===ch||"|"===ch||!ch)break;if(" "===ch||"\n"===ch)if(isTextStart(scnr))buf+=ch,scnr.next();else{if(isPluralStart(scnr))break;buf+=ch,scnr.next()}else buf+=ch,scnr.next()}}return buf}(scnr))}return token}return{nextToken:function(){const{currentType:currentType,offset:offset,startLoc:startLoc,endLoc:endLoc}=_context;return _context.lastType=currentType,_context.lastOffset=offset,_context.lastStartLoc=startLoc,_context.lastEndLoc=endLoc,_context.offset=currentOffset(),_context.startLoc=currentPosition(),_scnr.currentChar()===EOF?getToken(_context,13):readToken(_scnr,_context)},currentOffset:currentOffset,currentPosition:currentPosition,context:context}}const KNOWN_ESCAPES=/(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g,TEXT_ESCAPES=/\\([\\@{}|])/g;function fromTextEscapeSequence(_match,char){return char}function fromEscapeSequence(match,codePoint4,codePoint6){switch(match){case"\\\\":return"\\";case"\\'":return"'";default:{const codePoint=parseInt(codePoint4||codePoint6,16);return codePoint<=55295||codePoint>=57344?String.fromCodePoint(codePoint):"�"}}}function createParser(options={}){const location=!1!==options.location,{onError:onError}=options;function emitError(tokenzer,code,start,offset,...args){const end=tokenzer.currentPosition();if(end.offset+=offset,end.column+=offset,onError){const err=createCompileError(code,location?createLocation(start,end):null,{domain:"parser",args:args});onError(err)}}function startNode(type,offset,loc){const node={type:type};return location&&(node.start=offset,node.end=offset,node.loc={start:loc,end:loc}),node}function endNode(node,offset,pos,type){location&&(node.end=offset,node.loc&&(node.loc.end=pos))}function parseText(tokenizer,value){const context=tokenizer.context(),node=startNode(3,context.offset,context.startLoc);return node.value=value.replace(TEXT_ESCAPES,fromTextEscapeSequence),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseList(tokenizer,index2){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(5,offset,loc);return node.index=parseInt(index2,10),tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseNamed(tokenizer,key){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(4,offset,loc);return node.key=key,tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseLiteral(tokenizer,value){const context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(9,offset,loc);return node.value=value.replace(KNOWN_ESCAPES,fromEscapeSequence),tokenizer.nextToken(),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}function parseLinked(tokenizer){const context=tokenizer.context(),linkedNode=startNode(6,context.offset,context.startLoc);let token=tokenizer.nextToken();if(8===token.type){const parsed=function(tokenizer){const token=tokenizer.nextToken(),context=tokenizer.context(),{lastOffset:offset,lastStartLoc:loc}=context,node=startNode(8,offset,loc);return 11!==token.type?(emitError(tokenizer,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_MODIFIER,context.lastStartLoc,0),node.value="",endNode(node,offset,loc),{nextConsumeToken:token,node:node}):(null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.value=token.value||"",endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),{node:node})}(tokenizer);linkedNode.modifier=parsed.node,token=parsed.nextConsumeToken||tokenizer.nextToken()}switch(9!==token.type&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),token=tokenizer.nextToken(),2===token.type&&(token=tokenizer.nextToken()),token.type){case 10:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=function(tokenizer,value){const context=tokenizer.context(),node=startNode(7,context.offset,context.startLoc);return node.value=value,endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}(tokenizer,token.value||"");break;case 4:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseNamed(tokenizer,token.value||"");break;case 5:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseList(tokenizer,token.value||"");break;case 6:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),linkedNode.key=parseLiteral(tokenizer,token.value||"");break;default:{emitError(tokenizer,CompileErrorCodes_UNEXPECTED_EMPTY_LINKED_KEY,context.lastStartLoc,0);const nextContext=tokenizer.context(),emptyLinkedKeyNode=startNode(7,nextContext.offset,nextContext.startLoc);return emptyLinkedKeyNode.value="",endNode(emptyLinkedKeyNode,nextContext.offset,nextContext.startLoc),linkedNode.key=emptyLinkedKeyNode,endNode(linkedNode,nextContext.offset,nextContext.startLoc),{nextConsumeToken:token,node:linkedNode}}}return endNode(linkedNode,tokenizer.currentOffset(),tokenizer.currentPosition()),{node:linkedNode}}function parseMessage(tokenizer){const context=tokenizer.context(),node=startNode(2,1===context.currentType?tokenizer.currentOffset():context.offset,1===context.currentType?context.endLoc:context.startLoc);node.items=[];let nextToken=null;do{const token=nextToken||tokenizer.nextToken();switch(nextToken=null,token.type){case 0:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseText(tokenizer,token.value||""));break;case 5:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseList(tokenizer,token.value||""));break;case 4:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseNamed(tokenizer,token.value||""));break;case 6:null==token.value&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,getTokenCaption(token)),node.items.push(parseLiteral(tokenizer,token.value||""));break;case 7:{const parsed=parseLinked(tokenizer);node.items.push(parsed.node),nextToken=parsed.nextConsumeToken||null;break}}}while(13!==context.currentType&&1!==context.currentType);return endNode(node,1===context.currentType?context.lastOffset:tokenizer.currentOffset(),1===context.currentType?context.lastEndLoc:tokenizer.currentPosition()),node}function parseResource(tokenizer){const context=tokenizer.context(),{offset:offset,startLoc:startLoc}=context,msgNode=parseMessage(tokenizer);return 13===context.currentType?msgNode:function(tokenizer,offset,loc,msgNode){const context=tokenizer.context();let hasEmptyMessage=0===msgNode.items.length;const node=startNode(1,offset,loc);node.cases=[],node.cases.push(msgNode);do{const msg=parseMessage(tokenizer);hasEmptyMessage||(hasEmptyMessage=0===msg.items.length),node.cases.push(msg)}while(13!==context.currentType);return hasEmptyMessage&&emitError(tokenizer,CompileErrorCodes_MUST_HAVE_MESSAGES_IN_PLURAL,loc,0),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}(tokenizer,offset,startLoc,msgNode)}return{parse:function(source){const tokenizer=createTokenizer(source,assign({},options)),context=tokenizer.context(),node=startNode(0,context.offset,context.startLoc);return location&&node.loc&&(node.loc.source=source),node.body=parseResource(tokenizer),options.onCacheKey&&(node.cacheKey=options.onCacheKey(source)),13!==context.currentType&&emitError(tokenizer,CompileErrorCodes_UNEXPECTED_LEXICAL_ANALYSIS,context.lastStartLoc,0,source[context.offset]||""),endNode(node,tokenizer.currentOffset(),tokenizer.currentPosition()),node}}}function getTokenCaption(token){if(13===token.type)return"EOF";const name=(token.value||"").replace(/\r?\n/gu,"\\n");return name.length>10?name.slice(0,9)+"…":name}function traverseNodes(nodes,transformer){for(let i=0;i<nodes.length;i++)traverseNode(nodes[i],transformer)}function traverseNode(node,transformer){switch(node.type){case 1:traverseNodes(node.cases,transformer),transformer.helper("plural");break;case 2:traverseNodes(node.items,transformer);break;case 6:traverseNode(node.key,transformer),transformer.helper("linked"),transformer.helper("type");break;case 5:transformer.helper("interpolate"),transformer.helper("list");break;case 4:transformer.helper("interpolate"),transformer.helper("named")}}function transform(ast,options={}){const transformer=function(ast){const _context={ast:ast,helpers:/* @__PURE__ */new Set};return{context:()=>_context,helper:name=>(_context.helpers.add(name),name)}}(ast);transformer.helper("normalize"),ast.body&&traverseNode(ast.body,transformer);const context=transformer.context();ast.helpers=Array.from(context.helpers)}function optimizeMessageNode(message){if(1===message.items.length){const item=message.items[0];3!==item.type&&9!==item.type||(message.static=item.value,delete item.value)}else{const values=[];for(let i=0;i<message.items.length;i++){const item=message.items[i];if(3!==item.type&&9!==item.type)break;if(null==item.value)break;values.push(item.value)}if(values.length===message.items.length){message.static=join(values);for(let i=0;i<message.items.length;i++){const item=message.items[i];3!==item.type&&9!==item.type||delete item.value}}}}function minify(node){switch(node.t=node.type,node.type){case 0:{const resource=node;minify(resource.body),resource.b=resource.body,delete resource.body;break}case 1:{const plural=node,cases=plural.cases;for(let i=0;i<cases.length;i++)minify(cases[i]);plural.c=cases,delete plural.cases;break}case 2:{const message=node,items=message.items;for(let i=0;i<items.length;i++)minify(items[i]);message.i=items,delete message.items,message.static&&(message.s=message.static,delete message.static);break}case 3:case 9:case 8:case 7:{const valueNode=node;valueNode.value&&(valueNode.v=valueNode.value,delete valueNode.value);break}case 6:{const linked=node;minify(linked.key),linked.k=linked.key,delete linked.key,linked.modifier&&(minify(linked.modifier),linked.m=linked.modifier,delete linked.modifier);break}case 5:{const list=node;list.i=list.index,delete list.index;break}case 4:{const named=node;named.k=named.key,delete named.key;break}default:if("production"!==process.env.NODE_ENV)throw createCompileError(CompileErrorCodes_UNHANDLED_MINIFIER_NODE_TYPE,null,{domain:"minifier",args:[node.type]})}delete node.type}function generateNode(generator,node){const{helper:helper}=generator;switch(node.type){case 0:!function(generator,node){node.body?generateNode(generator,node.body):generator.push("null")}(generator,node);break;case 1:!function(generator,node){const{helper:helper,needIndent:needIndent}=generator;if(node.cases.length>1){generator.push(`${helper("plural")}([`),generator.indent(needIndent());const length=node.cases.length;for(let i=0;i<length&&(generateNode(generator,node.cases[i]),i!==length-1);i++)generator.push(", ");generator.deindent(needIndent()),generator.push("])")}}(generator,node);break;case 2:!function(generator,node){const{helper:helper,needIndent:needIndent}=generator;generator.push(`${helper("normalize")}([`),generator.indent(needIndent());const length=node.items.length;for(let i=0;i<length&&(generateNode(generator,node.items[i]),i!==length-1);i++)generator.push(", ");generator.deindent(needIndent()),generator.push("])")}(generator,node);break;case 6:!function(generator,node){const{helper:helper}=generator;generator.push(`${helper("linked")}(`),generateNode(generator,node.key),node.modifier?(generator.push(", "),generateNode(generator,node.modifier),generator.push(", _type")):generator.push(", undefined, _type"),generator.push(")")}(generator,node);break;case 8:case 7:case 9:case 3:generator.push(JSON.stringify(node.value),node);break;case 5:generator.push(`${helper("interpolate")}(${helper("list")}(${node.index}))`,node);break;case 4:generator.push(`${helper("interpolate")}(${helper("named")}(${JSON.stringify(node.key)}))`,node);break;default:if("production"!==process.env.NODE_ENV)throw createCompileError(CompileErrorCodes_UNHANDLED_CODEGEN_NODE_TYPE,null,{domain:"parser",args:[node.type]})}}function baseCompile$1(source,options={}){const assignedOptions=assign({},options),jit=!!assignedOptions.jit,enalbeMinify=!!assignedOptions.minify,enambeOptimize=null==assignedOptions.optimize||assignedOptions.optimize,ast=createParser(assignedOptions).parse(source);return jit?(enambeOptimize&&function(ast){const body=ast.body;2===body.type?optimizeMessageNode(body):body.cases.forEach(c=>optimizeMessageNode(c))}(ast),enalbeMinify&&minify(ast),{ast:ast,code:""}):(transform(ast,assignedOptions),((ast,options={})=>{const mode=isString(options.mode)?options.mode:"normal",filename=isString(options.filename)?options.filename:"message.intl";options.sourceMap;const breakLineCode=null!=options.breakLineCode?options.breakLineCode:"arrow"===mode?";":"\n",needIndent=options.needIndent?options.needIndent:"arrow"!==mode,helpers=ast.helpers||[],generator=function(ast,options){const{filename:filename,breakLineCode:breakLineCode,needIndent:_needIndent}=options,location=!1!==options.location,_context={filename:filename,code:"",column:1,line:1,offset:0,map:void 0,breakLineCode:breakLineCode,needIndent:_needIndent,indentLevel:0};function push(code,node){_context.code+=code}function _newline(n,withBreakLine=!0){const _breakLineCode=withBreakLine?breakLineCode:"";push(_needIndent?_breakLineCode+" ".repeat(n):_breakLineCode)}return location&&ast.loc&&(_context.source=ast.loc.source),{context:()=>_context,push:push,indent:function(withNewLine=!0){const level=++_context.indentLevel;withNewLine&&_newline(level)},deindent:function(withNewLine=!0){const level=--_context.indentLevel;withNewLine&&_newline(level)},newline:function(){_newline(_context.indentLevel)},helper:key=>`_${key}`,needIndent:()=>_context.needIndent}}(ast,{filename:filename,breakLineCode:breakLineCode,needIndent:needIndent});generator.push("normal"===mode?"function __msg__ (ctx) {":"(ctx) => {"),generator.indent(needIndent),helpers.length>0&&(generator.push(`const { ${join(helpers.map(s=>`${s}: _${s}`),", ")} } = ctx`),generator.newline()),generator.push("return "),generateNode(generator,ast),generator.deindent(needIndent),generator.push("}"),delete ast.helpers;const{code:code,map:map}=generator.context();return{ast:ast,code:code,map:map?map.toJSON():void 0}})(ast,assignedOptions))}function isMessageAST(val){return isObject(val)&&0===resolveType(val)&&(hasOwn(val,"b")||hasOwn(val,"body"))}const PROPS_BODY=["b","body"];const PROPS_CASES=["c","cases"];const PROPS_STATIC=["s","static"];const PROPS_ITEMS=["i","items"];const PROPS_TYPE=["t","type"];function resolveType(node){return resolveProps(node,PROPS_TYPE)}const PROPS_VALUE=["v","value"];function resolveValue$1(node,type){const resolved=resolveProps(node,PROPS_VALUE);if(null!=resolved)return resolved;throw createUnhandleNodeError(type)}const PROPS_MODIFIER=["m","modifier"];const PROPS_KEY=["k","key"];function resolveProps(node,props,defaultValue){for(let i=0;i<props.length;i++){const prop=props[i];if(hasOwn(node,prop)&&null!=node[prop])return node[prop]}return defaultValue}const AST_NODE_PROPS_KEYS=[...PROPS_BODY,...PROPS_CASES,...PROPS_STATIC,...PROPS_ITEMS,...PROPS_KEY,...PROPS_MODIFIER,...PROPS_VALUE,...PROPS_TYPE];function createUnhandleNodeError(type){return new Error(`unhandled node type: ${type}`)}function format(ast){return ctx=>function(ctx,ast){const body=(node=ast,resolveProps(node,PROPS_BODY));var node;if(null==body)throw createUnhandleNodeError(0);if(1===resolveType(body)){const cases=function(node){return resolveProps(node,PROPS_CASES,[])}(body);return ctx.plural(cases.reduce((messages2,c)=>[...messages2,formatMessageParts(ctx,c)],[]))}return formatMessageParts(ctx,body)}(ctx,ast)}function formatMessageParts(ctx,node){const static_=function(node){return resolveProps(node,PROPS_STATIC)}(node);if(null!=static_)return"text"===ctx.type?static_:ctx.normalize([static_]);{const messages2=function(node){return resolveProps(node,PROPS_ITEMS,[])}(node).reduce((acm,c)=>[...acm,formatMessagePart(ctx,c)],[]);return ctx.normalize(messages2)}}function formatMessagePart(ctx,node){const type=resolveType(node);switch(type){case 3:case 9:case 7:case 8:return resolveValue$1(node,type);case 4:{const named=node;if(hasOwn(named,"k")&&named.k)return ctx.interpolate(ctx.named(named.k));if(hasOwn(named,"key")&&named.key)return ctx.interpolate(ctx.named(named.key));throw createUnhandleNodeError(type)}case 5:{const list=node;if(hasOwn(list,"i")&&isNumber(list.i))return ctx.interpolate(ctx.list(list.i));if(hasOwn(list,"index")&&isNumber(list.index))return ctx.interpolate(ctx.list(list.index));throw createUnhandleNodeError(type)}case 6:{const linked=node,modifier=function(node){return resolveProps(node,PROPS_MODIFIER)}(linked),key=function(node){const resolved=resolveProps(node,PROPS_KEY);if(resolved)return resolved;throw createUnhandleNodeError(6)}(linked);return ctx.linked(formatMessagePart(ctx,key),modifier?formatMessagePart(ctx,modifier):void 0,ctx.type)}default:throw new Error(`unhandled node on format message part: ${type}`)}}function checkHtmlMessage(source,warnHtmlMessage){warnHtmlMessage&&(source=>RE_HTML_TAG.test(source))(source)&&warn(format$1("Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.",{source:source}))}const defaultOnCacheKey=message=>message;let compileCache=create();let devtools=null;const translateDevTools=/* @__PURE__ */createDevToolsHook("function:translate");function createDevToolsHook(hook){return payloads=>devtools&&devtools.emit(hook,payloads)}const CoreErrorCodes_INVALID_ARGUMENT=17,CoreErrorCodes_INVALID_DATE_ARGUMENT=18,CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT=19,CoreErrorCodes_NOT_SUPPORT_NON_STRING_MESSAGE=20,CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE=21,CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION=22,CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE=23;function createCoreError(code){return createCompileError(code,null,"production"!==process.env.NODE_ENV?{messages:errorMessages$1}:void 0)}const errorMessages$1={[CoreErrorCodes_INVALID_ARGUMENT]:"Invalid arguments",[CoreErrorCodes_INVALID_DATE_ARGUMENT]:"The date provided is an invalid Date object.Make sure your Date represents a valid date.",[CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT]:"The argument provided is not a valid ISO date string",[CoreErrorCodes_NOT_SUPPORT_NON_STRING_MESSAGE]:"Not support non-string message",[CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE]:"cannot support promise value",[CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]:"cannot support async function",[CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE]:"cannot support locale type"};function getLocale(context,options){return null!=options.locale?resolveLocale(options.locale):resolveLocale(context.locale)}let _resolveLocale;function resolveLocale(locale2){if(isString(locale2))return locale2;if(isFunction(locale2)){if(locale2.resolvedOnce&&null!=_resolveLocale)return _resolveLocale;if("Function"===locale2.constructor.name){const resolve=locale2();if(isObject(val=resolve)&&isFunction(val.then)&&isFunction(val.catch))throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_PROMISE_VALUE);return _resolveLocale=resolve}throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_ASYNC_FUNCTION)}throw createCoreError(CoreErrorCodes_NOT_SUPPORT_LOCALE_TYPE);var val}function fallbackWithSimple(ctx,fallback,start){return[.../* @__PURE__ */new Set([start,...isArray(fallback)?fallback:isObject(fallback)?Object.keys(fallback).filter(locale2=>"default"!==locale2):isString(fallback)?[fallback]:[start]])]}function fallbackWithLocaleChain(ctx,fallback,start){const startLocale=isString(start)?start:DEFAULT_LOCALE,context=ctx;context.__localeChainCache||(context.__localeChainCache=/* @__PURE__ */new Map);const fallbackKey=friendlyJSONstringify(fallback);let chains=context.__localeChainCache.get(startLocale);chains||(chains=/* @__PURE__ */new Map,context.__localeChainCache.set(startLocale,chains));const cached=chains.get(fallbackKey);if(cached)return cached;const chain=[];let block=[start];for(;isArray(block);)block=appendBlockToChain(chain,block,fallback);const defaults=isArray(fallback)||!isPlainObject(fallback)?fallback:fallback.default?fallback.default:null;return block=isString(defaults)?[defaults]:defaults,isArray(block)&&appendBlockToChain(chain,block,!1),chains.set(fallbackKey,chain),chain}function appendBlockToChain(chain,block,blocks){let follow=!0;for(let i=0;i<block.length&&isBoolean(follow);i++){const locale2=block[i];isString(locale2)&&(follow=appendLocaleToChain(chain,block[i],blocks))}return follow}function appendLocaleToChain(chain,locale2,blocks){let follow;const tokens=locale2.split("-");do{follow=appendItemToChain(chain,tokens.join("-"),blocks),tokens.splice(-1,1)}while(tokens.length&&!0===follow);return follow}function appendItemToChain(chain,target,blocks){let follow=!1;if(!chain.includes(target)&&(follow=!0,target)){follow="!"!==target[target.length-1];const locale2=target.replace(/!/g,"");chain.push(locale2),(isArray(blocks)||isPlainObject(blocks))&&blocks[locale2]&&(follow=blocks[locale2])}return follow}const pathStateMachine=[];pathStateMachine[0]={w:[0],i:[3,0],"[":[4],o:[7]},pathStateMachine[1]={w:[1],".":[2],"[":[4],o:[7]},pathStateMachine[2]={w:[2],i:[3,0],0:[3,0]},pathStateMachine[3]={i:[3,0],0:[3,0],w:[1,1],".":[2,1],"[":[4,1],o:[7,1]},pathStateMachine[4]={"'":[5,0],'"':[6,0],"[":[4,2],"]":[1,3],o:8,l:[4,0]},pathStateMachine[5]={"'":[4,0],o:8,l:[5,0]},pathStateMachine[6]={'"':[4,0],o:8,l:[6,0]};const literalValueRE=/^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;function getPathCharType(ch){if(null==ch)return"o";switch(ch.charCodeAt(0)){case 91:case 93:case 46:case 34:case 39:return ch;case 95:case 36:case 45:return"i";case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"w"}return"i"}function formatSubPath(path){const trimmed=path.trim();return("0"!==path.charAt(0)||!isNaN(parseInt(path)))&&(exp=trimmed,literalValueRE.test(exp)?function(str){const a2=str.charCodeAt(0);return a2!==str.charCodeAt(str.length-1)||34!==a2&&39!==a2?str:str.slice(1,-1)}(trimmed):"*"+trimmed);var exp}const cache=/* @__PURE__ */new Map;function resolveWithKeyValue(obj,path){return isObject(obj)?obj[path]:null}const CoreWarnCodes_NOT_FOUND_KEY=1,CoreWarnCodes_FALLBACK_TO_TRANSLATE=2,CoreWarnCodes_CANNOT_FORMAT_NUMBER=3,CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT=4,CoreWarnCodes_CANNOT_FORMAT_DATE=5,CoreWarnCodes_FALLBACK_TO_DATE_FORMAT=6,CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER=7,CoreWarnCodes_INVALID_NUMBER_ARGUMENT=8,CoreWarnCodes_INVALID_DATE_ARGUMENT=9,warnMessages$1={[CoreWarnCodes_NOT_FOUND_KEY]:"Not found '{key}' key in '{locale}' locale messages.",[CoreWarnCodes_FALLBACK_TO_TRANSLATE]:"Fall back to translate '{key}' key with '{target}' locale.",[CoreWarnCodes_CANNOT_FORMAT_NUMBER]:"Cannot format a number value due to not supported Intl.NumberFormat.",[CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT]:"Fall back to number format '{key}' key with '{target}' locale.",[CoreWarnCodes_CANNOT_FORMAT_DATE]:"Cannot format a date value due to not supported Intl.DateTimeFormat.",[CoreWarnCodes_FALLBACK_TO_DATE_FORMAT]:"Fall back to datetime format '{key}' key with '{target}' locale.",[CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]:"This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.",[CoreWarnCodes_INVALID_NUMBER_ARGUMENT]:"Invalid argument for number formatting: expected a number but received '{value}'.",[CoreWarnCodes_INVALID_DATE_ARGUMENT]:"Invalid argument for datetime formatting: expected a Date, number, or ISO string but received '{value}'."};function getWarnMessage$1(code,...args){return format$1(warnMessages$1[code],...args)}const DEFAULT_LOCALE="en-US",capitalize=str=>`${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;let _compiler,_resolver,_fallbacker;let _additionalMeta=null;const getAdditionalMeta=()=>_additionalMeta;let _fallbackContext=null;const setFallbackContext=context=>{_fallbackContext=context};let _cid=0;function createCoreContext(options={}){const onWarn=isFunction(options.onWarn)?options.onWarn:warn,version=isString(options.version)?options.version:"11.4.10",locale2=isString(options.locale)||isFunction(options.locale)?options.locale:DEFAULT_LOCALE,_locale=isFunction(locale2)?DEFAULT_LOCALE:locale2,fallbackLocale=isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||isString(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:_locale,messages2=isPlainObject(options.messages)?options.messages:createResources(_locale),datetimeFormats=isPlainObject(options.datetimeFormats)?options.datetimeFormats:createResources(_locale),numberFormats=isPlainObject(options.numberFormats)?options.numberFormats:createResources(_locale),modifiers=assign(create(),options.modifiers,{upper:(val,type)=>"text"===type&&isString(val)?val.toUpperCase():"vnode"===type&&isObject(val)&&"__v_isVNode"in val?val.children.toUpperCase():val,lower:(val,type)=>"text"===type&&isString(val)?val.toLowerCase():"vnode"===type&&isObject(val)&&"__v_isVNode"in val?val.children.toLowerCase():val,capitalize:(val,type)=>"text"===type&&isString(val)?capitalize(val):"vnode"===type&&isObject(val)&&"__v_isVNode"in val?capitalize(val.children):val}),pluralRules=options.pluralRules||create(),missing=isFunction(options.missing)?options.missing:null,missingWarn=!isBoolean(options.missingWarn)&&!isRegExp(options.missingWarn)||options.missingWarn,fallbackWarn=!isBoolean(options.fallbackWarn)&&!isRegExp(options.fallbackWarn)||options.fallbackWarn,fallbackFormat=!!options.fallbackFormat,unresolving=!!options.unresolving,postTranslation=isFunction(options.postTranslation)?options.postTranslation:null,processor=isPlainObject(options.processor)?options.processor:null,warnHtmlMessage=!isBoolean(options.warnHtmlMessage)||options.warnHtmlMessage,escapeParameter=!!options.escapeParameter,messageCompiler=isFunction(options.messageCompiler)?options.messageCompiler:_compiler;"production"!==process.env.NODE_ENV&&isFunction(options.messageCompiler)&&warnOnce(getWarnMessage$1(CoreWarnCodes_EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));const messageResolver=isFunction(options.messageResolver)?options.messageResolver:_resolver||resolveWithKeyValue,localeFallbacker=isFunction(options.localeFallbacker)?options.localeFallbacker:_fallbacker||fallbackWithSimple,fallbackContext=isObject(options.fallbackContext)?options.fallbackContext:void 0,internalOptions=options,__datetimeFormatters=isObject(internalOptions.__datetimeFormatters)?internalOptions.__datetimeFormatters:/* @__PURE__ */new Map,__numberFormatters=isObject(internalOptions.__numberFormatters)?internalOptions.__numberFormatters:/* @__PURE__ */new Map,__meta=isObject(internalOptions.__meta)?internalOptions.__meta:{};_cid++;const context={version:version,cid:_cid,locale:locale2,fallbackLocale:fallbackLocale,messages:messages2,modifiers:modifiers,pluralRules:pluralRules,missing:missing,missingWarn:missingWarn,fallbackWarn:fallbackWarn,fallbackFormat:fallbackFormat,unresolving:unresolving,postTranslation:postTranslation,processor:processor,warnHtmlMessage:warnHtmlMessage,escapeParameter:escapeParameter,messageCompiler:messageCompiler,messageResolver:messageResolver,localeFallbacker:localeFallbacker,fallbackContext:fallbackContext,onWarn:onWarn,__meta:__meta};return context.datetimeFormats=datetimeFormats,context.numberFormats=numberFormats,context.__datetimeFormatters=__datetimeFormatters,context.__numberFormatters=__numberFormatters,"production"!==process.env.NODE_ENV&&(context.__v_emitter=null!=internalOptions.__v_emitter?internalOptions.__v_emitter:void 0),("production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__)&&function(i18n2,version,meta){devtools&&devtools.emit("i18n:init",{timestamp:Date.now(),i18n:i18n2,version:version,meta:meta})}(context,version,__meta),context}const createResources=locale2=>({[locale2]:create()});function isTranslateFallbackWarn(fallback,key){return fallback instanceof RegExp?fallback.test(key):fallback}function isTranslateMissingWarn(missing,key){return missing instanceof RegExp?missing.test(key):missing}function handleMissing(context,key,locale2,missingWarn,type){const{missing:missing,onWarn:onWarn}=context;if("production"!==process.env.NODE_ENV){const emitter=context.__v_emitter;emitter&&emitter.emit("missing",{locale:locale2,key:key,type:type,groupId:toDevtoolsGroupId(type,key)})}if(null!==missing){const ret=missing(context,locale2,key,type);return isString(ret)?ret:key}return"production"!==process.env.NODE_ENV&&isTranslateMissingWarn(missingWarn,key)&&onWarn(getWarnMessage$1(CoreWarnCodes_NOT_FOUND_KEY,{key:key,locale:locale2})),key}function updateFallbackLocale(ctx,locale2,fallback){ctx.__localeChainCache=/* @__PURE__ */new Map,ctx.localeFallbacker(ctx,fallback,locale2)}function isAlmostSameLocale(locale2,compareLocale){return locale2!==compareLocale&&locale2.split("-")[0]===compareLocale.split("-")[0]}function isImplicitFallback(targetLocale,locales){const index2=locales.indexOf(targetLocale);if(-1===index2)return!1;for(let i=index2+1;i<locales.length;i++)if(isAlmostSameLocale(targetLocale,locales[i]))return!0;return!1}function resolveFormatLocale(context,key,locale2,formats,missingWarn,fallbackWarn,type){const{fallbackLocale:fallbackLocale,localeFallbacker:localeFallbacker,onWarn:onWarn}=context,locales=localeFallbacker(context,fallbackLocale,locale2);let from=locale2;for(let i=0;i<locales.length;i++){const targetLocale=locales[i];if("production"!==process.env.NODE_ENV&&locale2!==targetLocale&&isTranslateFallbackWarn(fallbackWarn,key)&&onWarn(getWarnMessage$1("datetime format"===type?CoreWarnCodes_FALLBACK_TO_DATE_FORMAT:CoreWarnCodes_FALLBACK_TO_NUMBER_FORMAT,{key:key,target:targetLocale})),"production"!==process.env.NODE_ENV&&locale2!==targetLocale){const emitter=context.__v_emitter;emitter&&emitter.emit("fallback",{type:type,key:key,from:from,to:targetLocale,groupId:toDevtoolsGroupId(type,key)})}const format2=(formats[targetLocale]||{})[key];if(isPlainObject(format2)&&isString(targetLocale))return targetLocale;handleMissing(context,key,targetLocale,missingWarn,type),from=targetLocale}return null}function getFormatterCacheKey(locale2,key,overrides){let id=`${locale2}__${key}`;return isPlainObject(overrides)&&!isEmptyObject(overrides)&&(id=`${id}__${JSON.stringify(overrides)}`),id}function clearFormatCache(formatters,locale2,format2){for(const key in format2){const prefix=`${locale2}__${key}`;for(const id of formatters.keys())(id===prefix||id.startsWith(`${prefix}__`))&&formatters.delete(id)}}function parseFormatArgs(args,options,initialOverrides,optionsKeys){const[,arg2,arg3,arg4]=args;let overrides=initialOverrides;return isString(arg2)?options.key=arg2:isPlainObject(arg2)&&Object.keys(arg2).forEach(key=>{optionsKeys.includes(key)?overrides[key]=arg2[key]:options[key]=arg2[key]}),isString(arg3)?options.locale=arg3:isPlainObject(arg3)&&(overrides=arg3),isPlainObject(arg4)&&(overrides=arg4),overrides}const intlDefined="undefined"!=typeof Intl,Availabilities_dateTimeFormat=intlDefined&&void 0!==Intl.DateTimeFormat,Availabilities_numberFormat=intlDefined&&void 0!==Intl.NumberFormat;function datetime(context,...args){const{datetimeFormats:datetimeFormats,unresolving:unresolving,onWarn:onWarn}=context,{__datetimeFormatters:__datetimeFormatters}=context;if("production"!==process.env.NODE_ENV&&!Availabilities_dateTimeFormat)return onWarn(getWarnMessage$1(CoreWarnCodes_CANNOT_FORMAT_DATE)),"";if(!isString(args[0])&&!isDate(args[0])&&!isNumber(args[0]))return"production"!==process.env.NODE_ENV&&onWarn(getWarnMessage$1(CoreWarnCodes_INVALID_DATE_ARGUMENT,{value:String(args[0])})),"";const[key,value,options,overrides]=parseDateTimeArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,part=!!options.part,locale2=getLocale(context,options);if(!isString(key)||""===key){const formatter2=new Intl.DateTimeFormat(locale2.replace(/!/g,""),overrides);return part?formatter2.formatToParts(value):formatter2.format(value)}const targetLocale=resolveFormatLocale(context,key,locale2,datetimeFormats,missingWarn,fallbackWarn,"datetime format");if(!isString(targetLocale))return unresolving?-1:key;const format2=datetimeFormats[targetLocale][key],id=getFormatterCacheKey(targetLocale,key,overrides);let formatter=__datetimeFormatters.get(id);return formatter||(formatter=new Intl.DateTimeFormat(targetLocale,assign({},format2,overrides)),__datetimeFormatters.set(id,formatter)),part?formatter.formatToParts(value):formatter.format(value)}const DATETIME_FORMAT_OPTIONS_KEYS=["localeMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName","formatMatcher","hour12","timeZone","dateStyle","timeStyle","calendar","dayPeriod","numberingSystem","hourCycle","fractionalSecondDigits"];function parseDateTimeArgs(...args){const[arg1]=args,options=create(),initialOverrides=create();let value;if(isString(arg1)){const matches=arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);if(!matches)throw createCoreError(CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT);const dateTime=matches[3]?matches[3].trim().startsWith("T")?`${matches[1].trim()}${matches[3].trim()}`:`${matches[1].trim()}T${matches[3].trim()}`:matches[1].trim();value=new Date(dateTime);try{value.toISOString()}catch{throw createCoreError(CoreErrorCodes_INVALID_ISO_DATE_ARGUMENT)}}else if(isDate(arg1)){if(isNaN(arg1.getTime()))throw createCoreError(CoreErrorCodes_INVALID_DATE_ARGUMENT);value=arg1}else{if(!isNumber(arg1))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);value=arg1}const overrides=parseFormatArgs(args,options,initialOverrides,DATETIME_FORMAT_OPTIONS_KEYS);return[options.key||"",value,options,overrides]}function clearDateTimeFormat(ctx,locale2,format2){clearFormatCache(ctx.__datetimeFormatters,locale2,format2)}function number(context,...args){const{numberFormats:numberFormats,unresolving:unresolving,onWarn:onWarn}=context,{__numberFormatters:__numberFormatters}=context;if("production"!==process.env.NODE_ENV&&!Availabilities_numberFormat)return onWarn(getWarnMessage$1(CoreWarnCodes_CANNOT_FORMAT_NUMBER)),"";if(!isNumber(args[0]))return"production"!==process.env.NODE_ENV&&onWarn(getWarnMessage$1(CoreWarnCodes_INVALID_NUMBER_ARGUMENT,{value:String(args[0])})),"";const[key,value,options,overrides]=parseNumberArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,part=!!options.part,locale2=getLocale(context,options);if(!isString(key)||""===key){const formatter2=new Intl.NumberFormat(locale2.replace(/!/g,""),overrides);return part?formatter2.formatToParts(value):formatter2.format(value)}const targetLocale=resolveFormatLocale(context,key,locale2,numberFormats,missingWarn,fallbackWarn,"number format");if(!isString(targetLocale))return unresolving?-1:key;const format2=numberFormats[targetLocale][key],id=getFormatterCacheKey(targetLocale,key,overrides);let formatter=__numberFormatters.get(id);return formatter||(formatter=new Intl.NumberFormat(targetLocale,assign({},format2,overrides)),__numberFormatters.set(id,formatter)),part?formatter.formatToParts(value):formatter.format(value)}const NUMBER_FORMAT_OPTIONS_KEYS=["localeMatcher","style","currency","currencyDisplay","currencySign","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits","compactDisplay","notation","signDisplay","unit","unitDisplay","roundingMode","roundingPriority","roundingIncrement","trailingZeroDisplay"];function parseNumberArgs(...args){const[arg1]=args,options=create(),initialOverrides=create();if(!isNumber(arg1))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);const value=arg1,overrides=parseFormatArgs(args,options,initialOverrides,NUMBER_FORMAT_OPTIONS_KEYS);return[options.key||"",value,options,overrides]}function clearNumberFormat(ctx,locale2,format2){clearFormatCache(ctx.__numberFormatters,locale2,format2)}const DEFAULT_MODIFIER=str=>str,DEFAULT_MESSAGE=ctx=>"",DEFAULT_NORMALIZE=values=>0===values.length?"":join(values),DEFAULT_INTERPOLATE=val=>null==val?"":isArray(val)||isPlainObject(val)&&val.toString===objectToString?JSON.stringify(val,null,2):String(val);function pluralDefault(choice,choicesLength){return choice=Math.abs(choice),2===choicesLength?1===choice?0:1:Math.min(choice,2)}function createMessageContext(options={}){const locale2=options.locale,pluralIndex=function(options){const index2=isNumber(options.pluralIndex)?options.pluralIndex:-1;return isNumber(options.named?.count)?options.named.count:isNumber(options.named?.n)?options.named.n:index2}(options),pluralRule=isString(locale2)&&isFunction(options.pluralRules?.[locale2])?options.pluralRules[locale2]:pluralDefault,orgPluralRule=pluralRule===pluralDefault?void 0:pluralDefault,_list=options.list||[],_named=options.named||create();isNumber(options.pluralIndex)&&(_named.count||=options.pluralIndex,_named.n||=options.pluralIndex);function message(key,useLinked){const msg=isFunction(options.messages)?options.messages(key,!!useLinked):!!isObject(options.messages)&&options.messages[key];return msg||(options.parent?options.parent.message(key):DEFAULT_MESSAGE)}const normalize=isFunction(options.processor?.normalize)?options.processor.normalize:DEFAULT_NORMALIZE,interpolate=isFunction(options.processor?.interpolate)?options.processor.interpolate:DEFAULT_INTERPOLATE,ctx={list:index2=>_list[index2],named:key=>_named[key],plural:messages2=>messages2[pluralRule(pluralIndex,messages2.length,orgPluralRule)],linked:(key,...args)=>{const[arg1,arg2]=args;let type2="text",modifier="";1===args.length?isObject(arg1)?(modifier=arg1.modifier||modifier,type2=arg1.type||type2):isString(arg1)&&(modifier=arg1||modifier):2===args.length&&(isString(arg1)&&(modifier=arg1||modifier),isString(arg2)&&(type2=arg2||type2));const ret=message(key,!0)(ctx),resolved=""===ret||void 0===ret?key:ret,msg="vnode"===type2&&isArray(resolved)&&modifier?resolved[0]:resolved;return modifier?(name=modifier,options.modifiers?options.modifiers[name]:DEFAULT_MODIFIER)(msg,type2):msg;var name},message:message,type:isString(options.processor?.type)?options.processor.type:"text",interpolate:interpolate,normalize:normalize,values:assign(create(),_list,_named)};return ctx}const NOOP_MESSAGE_FUNCTION=()=>"",isMessageFunction=val=>isFunction(val);function translate(context,...args){const{fallbackFormat:fallbackFormat,postTranslation:postTranslation,unresolving:unresolving,messageCompiler:messageCompiler,fallbackLocale:fallbackLocale,messages:messages2}=context,[key,options]=parseTranslateArgs(...args),missingWarn=isBoolean(options.missingWarn)?options.missingWarn:context.missingWarn,fallbackWarn=isBoolean(options.fallbackWarn)?options.fallbackWarn:context.fallbackWarn,escapeParameter=isBoolean(options.escapeParameter)?options.escapeParameter:context.escapeParameter,resolvedMessage=!!options.resolvedMessage,defaultMsgOrKey=isString(options.default)||isBoolean(options.default)?isBoolean(options.default)?messageCompiler?key:()=>key:options.default:fallbackFormat?messageCompiler?key:()=>key:null,enableDefaultMsg=fallbackFormat||null!=defaultMsgOrKey&&(isString(defaultMsgOrKey)||isFunction(defaultMsgOrKey)),locale2=getLocale(context,options);escapeParameter&&function(options){isArray(options.list)?options.list=options.list.map(item=>isString(item)?escapeHtml(item):item):isObject(options.named)&&Object.keys(options.named).forEach(key=>{isString(options.named[key])&&(options.named[key]=escapeHtml(options.named[key]))})}(options);let[formatScope,targetLocale,message]=resolvedMessage?[key,locale2,messages2[locale2]||create()]:resolveMessageFormat(context,key,locale2,fallbackLocale,fallbackWarn,missingWarn),format2=formatScope,cacheBaseKey=key;if(resolvedMessage||isString(format2)||isMessageAST(format2)||isMessageFunction(format2)||enableDefaultMsg&&(format2=defaultMsgOrKey,cacheBaseKey=format2),!(resolvedMessage||(isString(format2)||isMessageAST(format2)||isMessageFunction(format2))&&isString(targetLocale)))return unresolving?-1:key;if("production"!==process.env.NODE_ENV&&isString(format2)&&null==context.messageCompiler)return warn(`The message format compilation is not supported in this build. Because message compiler isn't included. You need to pre-compilation all message format. So translate function return '${key}'.`),key;let occurred=!1;const msg=isMessageFunction(format2)?format2:compileMessageFormat(context,key,targetLocale,format2,cacheBaseKey,()=>{occurred=!0});if(occurred)return format2;const ctxOptions=function(context,locale2,message,options){const{modifiers:modifiers,pluralRules:pluralRules,messageResolver:resolveValue2,fallbackLocale:fallbackLocale,fallbackWarn:fallbackWarn,missingWarn:missingWarn,fallbackContext:fallbackContext}=context,resolveMessage=(key,useLinked)=>{let val=resolveValue2(message,key);if(null==val&&(fallbackContext||useLinked)){const[format2,,message2]=resolveMessageFormat(fallbackContext||context,key,locale2,fallbackLocale,fallbackWarn,missingWarn);val=format2??resolveValue2(message2,key)}if(isString(val)||isMessageAST(val)){let occurred=!1;const msg=compileMessageFormat(context,key,locale2,val,key,()=>{occurred=!0});return occurred?NOOP_MESSAGE_FUNCTION:msg}return isMessageFunction(val)?val:NOOP_MESSAGE_FUNCTION},ctxOptions={locale:locale2,modifiers:modifiers,pluralRules:pluralRules,messages:resolveMessage};context.processor&&(ctxOptions.processor=context.processor);options.list&&(ctxOptions.list=options.list);options.named&&(ctxOptions.named=options.named);isNumber(options.plural)&&(ctxOptions.pluralIndex=options.plural);return ctxOptions}(context,targetLocale,message,options),messaged=function(context,msg,msgCtx){const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;let startTag,endTag,start=null;"production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-evaluation-start",endTag="intlify-message-evaluation-end",mark&&mark(startTag));const messaged=msg(msgCtx);if("production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&emitter.emit("message-evaluation",{type:"message-evaluation",value:messaged,time:end-start,groupId:toDevtoolsGroupId("translate",msg.key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message evaluation",startTag,endTag))}return messaged}(context,msg,createMessageContext(ctxOptions));let ret=postTranslation?postTranslation(messaged,key):messaged;var html;if(escapeParameter&&isString(ret)&&(html=(html=(html=ret).replace(/([\w:-]+)\s*=\s*"([^"]*)"/g,(_,attrName,attrValue)=>`${attrName}="${sanitizeAttributeValue(attrName,attrValue)}"`)).replace(/([\w:-]+)\s*=\s*'([^']*)'/g,(_,attrName,attrValue)=>`${attrName}='${sanitizeAttributeValue(attrName,attrValue)}'`),eventHandlerPattern.test(html)&&("production"!==process.env.NODE_ENV&&warn("Potentially dangerous event handlers detected in translation. Consider removing onclick, onerror, etc. from your translation messages."),html=html.replace(eventHandlerAttributePattern,"$1on$2")),ret=html.replace(unquotedUrlAttributePattern,(match,boundary,prefix,attrValue)=>hasJavascriptScheme(attrValue)?`${boundary}${prefix}about:blank`:match)),"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__){const payloads={timestamp:Date.now(),key:isString(key)?key:isMessageFunction(format2)?format2.key:"",locale:targetLocale||(isMessageFunction(format2)?format2.locale:""),format:isString(format2)?format2:isMessageFunction(format2)?format2.source:"",message:ret};payloads.meta=assign({},context.__meta,/* @__PURE__ */getAdditionalMeta()||{}),translateDevTools(payloads)}return ret}function resolveMessageFormat(context,key,locale2,fallbackLocale,fallbackWarn,missingWarn){const{messages:messages2,onWarn:onWarn,messageResolver:resolveValue2,localeFallbacker:localeFallbacker}=context,locales=localeFallbacker(context,fallbackLocale,locale2);let targetLocale,message=create(),format2=null,from=locale2,to2=null;const type="translate";for(let i=0;i<locales.length;i++){targetLocale=to2=locales[i],"production"!==process.env.NODE_ENV&&locale2!==targetLocale&&!isAlmostSameLocale(locale2,targetLocale)&&isTranslateFallbackWarn(fallbackWarn,key)&&onWarn(getWarnMessage$1(CoreWarnCodes_FALLBACK_TO_TRANSLATE,{key:key,target:targetLocale}));const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;"production"!==process.env.NODE_ENV&&locale2!==targetLocale&&emitter&&emitter.emit("fallback",{type:type,key:key,from:from,to:to2,groupId:toDevtoolsGroupId(type,key)}),message=messages2[targetLocale]||create();let startTag,endTag,start=null;if("production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-resolve-start",endTag="intlify-message-resolve-end",mark&&mark(startTag)),null===(format2=resolveValue2(message,key))&&(format2=message[key]),"production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&format2&&emitter.emit("message-resolve",{type:"message-resolve",key:key,message:format2,time:end-start,groupId:toDevtoolsGroupId(type,key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message resolve",startTag,endTag))}if(isString(format2)||isMessageAST(format2)||isMessageFunction(format2))break;if(!isImplicitFallback(targetLocale,locales)){const missingRet=handleMissing(context,key,targetLocale,missingWarn,type);missingRet!==key&&(format2=missingRet)}from=to2}return[format2,targetLocale,message]}function compileMessageFormat(context,key,targetLocale,format2,cacheBaseKey,onError){const{messageCompiler:messageCompiler,warnHtmlMessage:warnHtmlMessage}=context;if(isMessageFunction(format2)){const msg2=format2;return msg2.locale=msg2.locale||targetLocale,msg2.key=msg2.key||key,msg2}if(null==messageCompiler){const msg2=()=>format2;return msg2.locale=targetLocale,msg2.key=key,msg2}const emitter="production"!==process.env.NODE_ENV?context.__v_emitter:void 0;let startTag,endTag,start=null;"production"!==process.env.NODE_ENV&&inBrowser&&emitter&&(start=window.performance.now(),startTag="intlify-message-compilation-start",endTag="intlify-message-compilation-end",mark&&mark(startTag));const msg=messageCompiler(format2,function(context,locale2,key,source,warnHtmlMessage,onError){return{locale:locale2,key:key,warnHtmlMessage:warnHtmlMessage,onError:err=>{if(onError&&onError(err),"production"!==process.env.NODE_ENV){const _source=function(source){if(isString(source))return source;if(source.loc&&source.loc.source)return source.loc.source}(source),codeFrame=err.location&&_source&&function(source,start=0,end=source.length){const lines=source.split(/\r?\n/);let count=0;const res=[];for(let i=0;i<lines.length;i++)if(count+=lines[i].length+1,count>=start){for(let j=i-2;j<=i+2||end>count;j++){if(j<0||j>=lines.length)continue;const line=j+1;res.push(`${line}${" ".repeat(3-String(line).length)}| ${lines[j]}`);const lineLength=lines[j].length;if(j===i){const pad=start-(count-lineLength)+1,length=Math.max(1,end>count?lineLength-pad:end-start);res.push(" | "+" ".repeat(pad)+"^".repeat(length))}else if(j>i){if(end>count){const length=Math.max(Math.min(end-count,lineLength),1);res.push(" | "+"^".repeat(length))}count+=lineLength+1}}break}return res.join("\n")}(_source,err.location.start.offset,err.location.end.offset),emitter=context.__v_emitter;emitter&&_source&&emitter.emit("compile-error",{message:_source,error:err.message,start:err.location&&err.location.start.offset,end:err.location&&err.location.end.offset,groupId:toDevtoolsGroupId("translate",key)});const message=`Message compilation error: ${err.message}`;throw new SyntaxError(codeFrame?`${message}\n${codeFrame}`:message)}throw err},onCacheKey:source2=>((locale2,key,source)=>friendlyJSONstringify({l:locale2,k:key,s:source}))(locale2,key,source2)}}(context,targetLocale,cacheBaseKey,format2,warnHtmlMessage,onError));if("production"!==process.env.NODE_ENV&&inBrowser&&emitter){const end=window.performance.now();emitter&&start&&emitter.emit("message-compilation",{type:"message-compilation",message:format2,time:end-start,groupId:toDevtoolsGroupId("translate",key)}),startTag&&endTag&&mark&&measure&&(mark(endTag),measure("intlify message compilation",startTag,endTag))}return msg.locale=targetLocale,msg.key=key,msg.source=format2,msg}function parseTranslateArgs(...args){const[arg1,arg2,arg3]=args,options=create();if(!(isString(arg1)||isNumber(arg1)||isMessageFunction(arg1)||isMessageAST(arg1)))throw createCoreError(CoreErrorCodes_INVALID_ARGUMENT);const key=isNumber(arg1)?String(arg1):(isMessageFunction(arg1),arg1);return isNumber(arg2)?options.plural=arg2:isString(arg2)?options.default=arg2:isPlainObject(arg2)&&!isEmptyObject(arg2)?options.named=arg2:isArray(arg2)&&(options.list=arg2),isNumber(arg3)?options.plural=arg3:isString(arg3)?options.default=arg3:isPlainObject(arg3)&&assign(options,arg3),[key,options]}function getTarget(){return"undefined"!=typeof navigator&&"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:{}}"boolean"!=typeof __INTLIFY_PROD_DEVTOOLS__&&(getGlobalThis().__INTLIFY_PROD_DEVTOOLS__=!1),"boolean"!=typeof __INTLIFY_DROP_MESSAGE_COMPILER__&&(getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__=!1);const isProxyAvailable="function"==typeof Proxy;let supported,perf;function now(){return void 0!==supported||("undefined"!=typeof window&&window.performance?(supported=!0,perf=window.performance):"undefined"!=typeof globalThis&&(null===(_a2=globalThis.perf_hooks)||void 0===_a2?void 0:_a2.performance)?(supported=!0,perf=globalThis.perf_hooks.performance):supported=!1),supported?perf.now():Date.now();var _a2}class ApiProxy{constructor(plugin,hook){this.target=null,this.targetQueue=[],this.onQueue=[],this.plugin=plugin,this.hook=hook;const defaultSettings={};if(plugin.settings)for(const id in plugin.settings){const item=plugin.settings[id];defaultSettings[id]=item.defaultValue}const localSettingsSaveId=`__vue-devtools-plugin-settings__${plugin.id}`;let currentSettings=Object.assign({},defaultSettings);try{const raw=localStorage.getItem(localSettingsSaveId),data=JSON.parse(raw);Object.assign(currentSettings,data)}catch(e){}this.fallbacks={getSettings:()=>currentSettings,setSettings(value){try{localStorage.setItem(localSettingsSaveId,JSON.stringify(value))}catch(e){}currentSettings=value},now:()=>now()},hook&&hook.on("plugin:settings:set",(pluginId,value)=>{pluginId===this.plugin.id&&this.fallbacks.setSettings(value)}),this.proxiedOn=new Proxy({},{get:(_target,prop)=>this.target?this.target.on[prop]:(...args)=>{this.onQueue.push({method:prop,args:args})}}),this.proxiedTarget=new Proxy({},{get:(_target,prop)=>this.target?this.target[prop]:"on"===prop?this.proxiedOn:Object.keys(this.fallbacks).includes(prop)?(...args)=>(this.targetQueue.push({method:prop,args:args,resolve:()=>{}}),this.fallbacks[prop](...args)):(...args)=>new Promise(resolve=>{this.targetQueue.push({method:prop,args:args,resolve:resolve})})})}async setRealTarget(target){this.target=target;for(const item of this.onQueue)this.target.on[item.method](...item.args);for(const item of this.targetQueue)item.resolve(await this.target[item.method](...item.args))}}function setupDevtoolsPlugin(pluginDescriptor,setupFn){const descriptor=pluginDescriptor,target=getTarget(),hook=getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__,enableProxy=isProxyAvailable&&descriptor.enableEarlyProxy;if(!hook||!target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__&&enableProxy){const proxy=enableProxy?new ApiProxy(descriptor,hook):null;(target.__VUE_DEVTOOLS_PLUGINS__=target.__VUE_DEVTOOLS_PLUGINS__||[]).push({pluginDescriptor:descriptor,setupFn:setupFn,proxy:proxy}),proxy&&setupFn(proxy.proxiedTarget)}else hook.emit("devtools-plugin:setup",pluginDescriptor,setupFn)}const I18nErrorCodes_UNEXPECTED_RETURN_TYPE=24,I18nErrorCodes_INVALID_ARGUMENT=25,I18nErrorCodes_MUST_BE_CALL_SETUP_TOP=26,I18nErrorCodes_NOT_INSTALLED=27,I18nErrorCodes_REQUIRED_VALUE=28,I18nErrorCodes_INVALID_VALUE=29,I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN=30,I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE=31,I18nErrorCodes_UNEXPECTED_ERROR=32,I18nErrorCodes_NOT_COMPATIBLE_LEGACY_VUE_I18N=33,I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY=34;function createI18nError(code,...args){return createCompileError(code,null,"production"!==process.env.NODE_ENV?{messages:errorMessages,args:args}:void 0)}const errorMessages={[I18nErrorCodes_UNEXPECTED_RETURN_TYPE]:"Unexpected return type in composer",[I18nErrorCodes_INVALID_ARGUMENT]:"Invalid argument",[I18nErrorCodes_MUST_BE_CALL_SETUP_TOP]:"Must be called at the top of a `setup` function",[I18nErrorCodes_NOT_INSTALLED]:"Need to install with `app.use` function",[I18nErrorCodes_UNEXPECTED_ERROR]:"Unexpected error",[I18nErrorCodes_REQUIRED_VALUE]:"Required in value: {0}",[I18nErrorCodes_INVALID_VALUE]:"Invalid value",[I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]:"Cannot setup vue-devtools plugin",[I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE]:"Need to install with `provide` function",[I18nErrorCodes_NOT_COMPATIBLE_LEGACY_VUE_I18N]:"Not compatible legacy VueI18n.",[I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY]:"Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly"},TranslateVNodeSymbol=/* @__PURE__ */makeSymbol("__translateVNode"),DatetimePartsSymbol=/* @__PURE__ */makeSymbol("__datetimeParts"),NumberPartsSymbol=/* @__PURE__ */makeSymbol("__numberParts"),EnableEmitter=/* @__PURE__ */makeSymbol("__enableEmitter"),DisableEmitter=/* @__PURE__ */makeSymbol("__disableEmitter"),SetPluralRulesSymbol=makeSymbol("__setPluralRules"),InejctWithOptionSymbol=/* @__PURE__ */makeSymbol("__injectWithOption"),DisposeSymbol=/* @__PURE__ */makeSymbol("__dispose"),I18nWarnCodes={FALLBACK_TO_ROOT:10,NOT_FOUND_PARENT_SCOPE:11,IGNORE_OBJ_FLATTEN:12,DEPRECATE_LEGACY_MODE:13,DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE:14,DUPLICATE_USE_I18N_CALLING:15},warnMessages={[I18nWarnCodes.FALLBACK_TO_ROOT]:"Fall back to {type} '{key}' with root locale.",[I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]:"Not found parent scope. use the global scope.",[I18nWarnCodes.IGNORE_OBJ_FLATTEN]:"Ignore object flatten: '{key}' key has an string value",[I18nWarnCodes.DEPRECATE_LEGACY_MODE]:"Legacy API mode has been deprecated in v11. Use Composition API mode instead.\nAbout how to use the Composition API mode, see https://vue-i18n.intlify.dev/guide/advanced/composition.html",[I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE]:"'v-t' has been deprecated in v11. Use translate APIs ('t' or '$t') instead.",[I18nWarnCodes.DUPLICATE_USE_I18N_CALLING]:"Duplicate `useI18n` calling by local scope. Please don't call it on local scope, due to it does not work properly in component."};function getWarnMessage(code,...args){return format$1(warnMessages[code],...args)}let mirroredCurrentInstance=null;{const setters=getGlobalThis().__VUE_INSTANCE_SETTERS__;isArray(setters)&&setters.push(instance=>{mirroredCurrentInstance=instance})}function handleFlatJson(obj){if(!isObject(obj))return obj;if(isMessageAST(obj))return obj;for(const key in obj)if(hasOwn(obj,key))if(key.includes(".")){const subKeys=key.split("."),lastIndex=subKeys.length-1;let currentObj=obj,hasStringValue=!1;for(let i=0;i<lastIndex;i++){if("__proto__"===subKeys[i])throw new Error(`unsafe key: ${subKeys[i]}`);if(subKeys[i]in currentObj||(currentObj[subKeys[i]]=create()),!isObject(currentObj[subKeys[i]])){"production"!==process.env.NODE_ENV&&warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN,{key:subKeys[i]})),hasStringValue=!0;break}currentObj=currentObj[subKeys[i]]}if(hasStringValue||(isMessageAST(currentObj)?AST_NODE_PROPS_KEYS.includes(subKeys[lastIndex])||delete obj[key]:(currentObj[subKeys[lastIndex]]=obj[key],delete obj[key])),!isMessageAST(currentObj)){const target=currentObj[subKeys[lastIndex]];isObject(target)&&handleFlatJson(target)}}else isObject(obj[key])&&handleFlatJson(obj[key]);return obj}function getLocaleMessages(locale2,options){const{messages:messages2,__i18n:__i18n,messageResolver:messageResolver,flatJson:flatJson}=options,ret=isPlainObject(messages2)?messages2:isArray(__i18n)?create():{[locale2]:create()};if(isArray(__i18n)&&__i18n.forEach(custom=>{if("locale"in custom&&"resource"in custom){const{locale:locale22,resource:resource}=custom;locale22?(ret[locale22]=ret[locale22]||create(),deepCopy(resource,ret[locale22])):deepCopy(resource,ret)}else isString(custom)&&deepCopy(JSON.parse(custom),ret)}),null==messageResolver&&flatJson)for(const key in ret)hasOwn(ret,key)&&handleFlatJson(ret[key]);return ret}function getComponentOptions(instance){return instance.type}function adjustI18nResources(gl,options,componentOptions){let messages2=isObject(options.messages)?options.messages:create();"__i18nGlobal"in componentOptions&&(messages2=getLocaleMessages(gl.locale.value,{messages:messages2,__i18n:componentOptions.__i18nGlobal}));const locales=Object.keys(messages2);if(locales.length&&locales.forEach(locale2=>{gl.mergeLocaleMessage(locale2,messages2[locale2])}),isObject(options.datetimeFormats)){const locales2=Object.keys(options.datetimeFormats);locales2.length&&locales2.forEach(locale2=>{gl.mergeDateTimeFormat(locale2,options.datetimeFormats[locale2])})}if(isObject(options.numberFormats)){const locales2=Object.keys(options.numberFormats);locales2.length&&locales2.forEach(locale2=>{gl.mergeNumberFormat(locale2,options.numberFormats[locale2])})}}function createTextNode(key){return createVNode(Text,null,key,0)}function getCurrentInstance(){return mirroredCurrentInstance??getCurrentInstance$1()}const NOOP_RETURN_ARRAY=()=>[],NOOP_RETURN_FALSE=()=>!1;let composerID=0;function defineCoreMissingHandler(missing){return(ctx,locale2,key,type)=>missing(locale2,key,getCurrentInstance()||void 0,type)}function createComposer(options={}){const{__root:__root,__injectWithOption:__injectWithOption}=options,_isGlobal=void 0===__root,flatJson=options.flatJson,_ref=inBrowser?ref:shallowRef;let _inheritLocale=!isBoolean(options.inheritLocale)||options.inheritLocale;const _locale=_ref(__root&&_inheritLocale?__root.locale.value:isString(options.locale)?options.locale:DEFAULT_LOCALE),_fallbackLocale=_ref(__root&&_inheritLocale?__root.fallbackLocale.value:isString(options.fallbackLocale)||isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:_locale.value),_messages=_ref(getLocaleMessages(_locale.value,options)),_datetimeFormats=_ref(isPlainObject(options.datetimeFormats)?options.datetimeFormats:{[_locale.value]:{}}),_numberFormats=_ref(isPlainObject(options.numberFormats)?options.numberFormats:{[_locale.value]:{}});let _missingWarn=__root?__root.missingWarn:!isBoolean(options.missingWarn)&&!isRegExp(options.missingWarn)||options.missingWarn,_fallbackWarn=__root?__root.fallbackWarn:!isBoolean(options.fallbackWarn)&&!isRegExp(options.fallbackWarn)||options.fallbackWarn,_fallbackRoot=__root?__root.fallbackRoot:!isBoolean(options.fallbackRoot)||options.fallbackRoot,_fallbackFormat=!!options.fallbackFormat,_missing=isFunction(options.missing)?options.missing:null,_runtimeMissing=isFunction(options.missing)?defineCoreMissingHandler(options.missing):null,_postTranslation=isFunction(options.postTranslation)?options.postTranslation:null,_warnHtmlMessage=__root?__root.warnHtmlMessage:!isBoolean(options.warnHtmlMessage)||options.warnHtmlMessage,_escapeParameter=!!options.escapeParameter;const _modifiers=__root?__root.modifiers:isPlainObject(options.modifiers)?options.modifiers:{};let _context,_pluralRules=options.pluralRules||__root&&__root.pluralRules;_context=(()=>{_isGlobal&&setFallbackContext(null);const ctxOptions={version:"11.4.10",locale:_locale.value,fallbackLocale:_fallbackLocale.value,messages:_messages.value,modifiers:_modifiers,pluralRules:_pluralRules,missing:null===_runtimeMissing?void 0:_runtimeMissing,missingWarn:_missingWarn,fallbackWarn:_fallbackWarn,fallbackFormat:_fallbackFormat,unresolving:!0,postTranslation:null===_postTranslation?void 0:_postTranslation,warnHtmlMessage:_warnHtmlMessage,escapeParameter:_escapeParameter,messageResolver:options.messageResolver,messageCompiler:options.messageCompiler,__meta:{framework:"vue"}};ctxOptions.datetimeFormats=_datetimeFormats.value,ctxOptions.numberFormats=_numberFormats.value,ctxOptions.__datetimeFormatters=isPlainObject(_context)?_context.__datetimeFormatters:void 0,ctxOptions.__numberFormatters=isPlainObject(_context)?_context.__numberFormatters:void 0,"production"!==process.env.NODE_ENV&&(ctxOptions.__v_emitter=isPlainObject(_context)?_context.__v_emitter:void 0);const ctx=createCoreContext(ctxOptions);return _isGlobal&&setFallbackContext(ctx),ctx})(),updateFallbackLocale(_context,_locale.value,_fallbackLocale.value);const locale2=computed({get:()=>_locale.value,set:val=>{_context.locale=val,_locale.value=val}}),fallbackLocale=computed({get:()=>_fallbackLocale.value,set:val=>{_context.fallbackLocale=val,_fallbackLocale.value=val,updateFallbackLocale(_context,_locale.value,val)}}),messages2=computed(()=>_messages.value),datetimeFormats=/* @__PURE__ */computed(()=>_datetimeFormats.value),numberFormats=/* @__PURE__ */computed(()=>_numberFormats.value);const wrapWithDeps=(fn2,argumentParser,warnType,fallbackSuccess,fallbackFail,successCondition)=>{let ret;_locale.value,_fallbackLocale.value,_messages.value,_datetimeFormats.value,_numberFormats.value;try{"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__,_isGlobal||(_context.fallbackContext=__root?_fallbackContext:void 0),ret=fn2(_context)}finally{"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__,_isGlobal||(_context.fallbackContext=void 0)}if("translate exists"!==warnType&&isNumber(ret)&&-1===ret||"translate exists"===warnType&&!ret){const[key,arg2]=argumentParser();if("production"!==process.env.NODE_ENV&&__root&&isString(key)&&(arg=arg2,"translate"!==warnType||!arg.resolvedMessage)&&(_fallbackRoot&&(isTranslateFallbackWarn(_fallbackWarn,key)||isTranslateMissingWarn(_missingWarn,key))&&warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT,{key:key,type:warnType})),"production"!==process.env.NODE_ENV)){const{__v_emitter:emitter}=_context;emitter&&_fallbackRoot&&emitter.emit("fallback",{type:warnType,key:key,to:"global",groupId:toDevtoolsGroupId(warnType,key)})}return __root&&_fallbackRoot?fallbackSuccess(__root):fallbackFail(key)}if(successCondition(ret))return ret;throw createI18nError(I18nErrorCodes_UNEXPECTED_RETURN_TYPE);var arg};function t2(...args){return wrapWithDeps(context=>Reflect.apply(translate,null,[context,...args]),()=>parseTranslateArgs(...args),"translate",root=>Reflect.apply(root.t,root,[...args]),key=>key,val=>isString(val))}const processor={normalize:function(values){return values.map(val=>isString(val)||isNumber(val)||isBoolean(val)?createTextNode(String(val)):val)},interpolate:val=>val,type:"vnode"};function getLocaleMessage(locale22){return _messages.value[locale22]||{}}composerID++,__root&&inBrowser&&(watch(__root.locale,val=>{_inheritLocale&&(_locale.value=val,_context.locale=val,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))}),watch(__root.fallbackLocale,val=>{_inheritLocale&&(_fallbackLocale.value=val,_context.fallbackLocale=val,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))}));const composer={id:composerID,locale:locale2,fallbackLocale:fallbackLocale,get inheritLocale(){return _inheritLocale},set inheritLocale(val){_inheritLocale=val,val&&__root&&(_locale.value=__root.locale.value,_fallbackLocale.value=__root.fallbackLocale.value,updateFallbackLocale(_context,_locale.value,_fallbackLocale.value))},get availableLocales(){return Object.keys(_messages.value).sort()},messages:messages2,get modifiers(){return _modifiers},get pluralRules(){return _pluralRules||{}},get isGlobal(){return _isGlobal},get missingWarn(){return _missingWarn},set missingWarn(val){_missingWarn=val,_context.missingWarn=_missingWarn},get fallbackWarn(){return _fallbackWarn},set fallbackWarn(val){_fallbackWarn=val,_context.fallbackWarn=_fallbackWarn},get fallbackRoot(){return _fallbackRoot},set fallbackRoot(val){_fallbackRoot=val},get fallbackFormat(){return _fallbackFormat},set fallbackFormat(val){_fallbackFormat=val,_context.fallbackFormat=_fallbackFormat},get warnHtmlMessage(){return _warnHtmlMessage},set warnHtmlMessage(val){_warnHtmlMessage=val,_context.warnHtmlMessage=val},get escapeParameter(){return _escapeParameter},set escapeParameter(val){_escapeParameter=val,_context.escapeParameter=val},t:t2,getLocaleMessage:getLocaleMessage,setLocaleMessage:function(locale22,message){if(flatJson){const _message={[locale22]:message};for(const key in _message)hasOwn(_message,key)&&handleFlatJson(_message[key]);message=_message[locale22]}_messages.value[locale22]=message,_context.messages=_messages.value},mergeLocaleMessage:function(locale22,message){_messages.value[locale22]=_messages.value[locale22]||{};const _message={[locale22]:message};if(flatJson)for(const key in _message)hasOwn(_message,key)&&handleFlatJson(_message[key]);deepCopy(message=_message[locale22],_messages.value[locale22]),_context.messages=_messages.value},getPostTranslationHandler:function(){return isFunction(_postTranslation)?_postTranslation:null},setPostTranslationHandler:function(handler){_postTranslation=handler,_context.postTranslation=handler},getMissingHandler:function(){return _missing},setMissingHandler:function(handler){null!==handler&&(_runtimeMissing=defineCoreMissingHandler(handler)),_missing=handler,_context.missing=_runtimeMissing},[SetPluralRulesSymbol]:function(rules){_pluralRules=rules,_context.pluralRules=_pluralRules}};return composer.datetimeFormats=datetimeFormats,composer.numberFormats=numberFormats,composer.rt=function(...args){const[arg1,arg2,arg3]=args;if(arg3&&!isObject(arg3))throw createI18nError(I18nErrorCodes_INVALID_ARGUMENT);return t2(arg1,arg2,assign({resolvedMessage:!0},arg3||{}))},composer.te=function(key,locale22){return wrapWithDeps(()=>{if(!key)return!1;const targetLocale=isString(locale22)?locale22:_locale.value,locales=isString(locale22)?[targetLocale]:fallbackWithLocaleChain(_context,_fallbackLocale.value,targetLocale);for(let i=0;i<locales.length;i++){const message=getLocaleMessage(locales[i]);let resolved=_context.messageResolver(message,key);if(null===resolved&&(resolved=message[key]),isMessageAST(resolved)||isMessageFunction(resolved)||isString(resolved))return!0}return!1},()=>[key],"translate exists",root=>Reflect.apply(root.te,root,[key,locale22]),NOOP_RETURN_FALSE,val=>isBoolean(val))},composer.tm=function(key){const messages22=function(key){let messages22=null;const locales=fallbackWithLocaleChain(_context,_fallbackLocale.value,_locale.value);for(let i=0;i<locales.length;i++){const targetLocaleMessages=_messages.value[locales[i]]||{},messageValue=_context.messageResolver(targetLocaleMessages,key);if(null!=messageValue){messages22=messageValue;break}}return messages22}(key);return null!=messages22?messages22:__root&&__root.tm(key)||{}},composer.d=function(...args){return wrapWithDeps(context=>Reflect.apply(datetime,null,[context,...args]),()=>parseDateTimeArgs(...args),"datetime format",root=>Reflect.apply(root.d,root,[...args]),()=>"",val=>isString(val)||isArray(val))},composer.n=function(...args){return wrapWithDeps(context=>Reflect.apply(number,null,[context,...args]),()=>parseNumberArgs(...args),"number format",root=>Reflect.apply(root.n,root,[...args]),()=>"",val=>isString(val)||isArray(val))},composer.getDateTimeFormat=function(locale22){return _datetimeFormats.value[locale22]||{}},composer.setDateTimeFormat=function(locale22,format2){_datetimeFormats.value[locale22]=format2,_context.datetimeFormats=_datetimeFormats.value,clearDateTimeFormat(_context,locale22,format2)},composer.mergeDateTimeFormat=function(locale22,format2){_datetimeFormats.value[locale22]=assign(_datetimeFormats.value[locale22]||{},format2),_context.datetimeFormats=_datetimeFormats.value,clearDateTimeFormat(_context,locale22,format2)},composer.getNumberFormat=function(locale22){return _numberFormats.value[locale22]||{}},composer.setNumberFormat=function(locale22,format2){_numberFormats.value[locale22]=format2,_context.numberFormats=_numberFormats.value,clearNumberFormat(_context,locale22,format2)},composer.mergeNumberFormat=function(locale22,format2){_numberFormats.value[locale22]=assign(_numberFormats.value[locale22]||{},format2),_context.numberFormats=_numberFormats.value,clearNumberFormat(_context,locale22,format2)},composer[InejctWithOptionSymbol]=__injectWithOption,composer[TranslateVNodeSymbol]=function(...args){return wrapWithDeps(context=>{let ret;const _context2=context;try{_context2.processor=processor,ret=Reflect.apply(translate,null,[_context2,...args])}finally{_context2.processor=null}return ret},()=>parseTranslateArgs(...args),"translate",root=>root[TranslateVNodeSymbol](...args),key=>[createTextNode(key)],val=>isArray(val))},composer[DatetimePartsSymbol]=function(...args){return wrapWithDeps(context=>Reflect.apply(datetime,null,[context,...args]),()=>parseDateTimeArgs(...args),"datetime format",root=>root[DatetimePartsSymbol](...args),NOOP_RETURN_ARRAY,val=>isString(val)||isArray(val))},composer[NumberPartsSymbol]=function(...args){return wrapWithDeps(context=>Reflect.apply(number,null,[context,...args]),()=>parseNumberArgs(...args),"number format",root=>root[NumberPartsSymbol](...args),NOOP_RETURN_ARRAY,val=>isString(val)||isArray(val))},"production"!==process.env.NODE_ENV&&(composer[EnableEmitter]=emitter=>{_context.__v_emitter=emitter},composer[DisableEmitter]=()=>{_context.__v_emitter=void 0}),composer}const VueDevToolsLabels_vue_devtools_plugin_vue_i18n="Vue I18n DevTools",VueDevToolsLabels_vue_i18n_resource_inspector="Vue I18n DevTools",VueDevToolsLabels_vue_i18n_timeline="Vue I18n",VueDevToolsPlaceholders_vue_i18n_resource_inspector="Search for scopes ...",VueDevToolsTimelineColors_vue_i18n_timeline=16764185;let devtoolsApi;async function enableDevTools(app,i18n2){return new Promise((resolve,reject)=>{try{setupDevtoolsPlugin({id:"vue-devtools-plugin-vue-i18n",label:VueDevToolsLabels_vue_devtools_plugin_vue_i18n,packageName:"vue-i18n",homepage:"https://vue-i18n.intlify.dev",logo:"https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png",componentStateTypes:["vue-i18n: composer properties"],app:app},api=>{devtoolsApi=api,api.on.visitComponentTree(({componentInstance:componentInstance,treeNode:treeNode})=>{!function(instance,treeNode,i18n2){const global2="composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;if(instance&&instance.__VUE_I18N__&&instance.__VUE_I18N__!==global2){const tag={label:`i18n (${getI18nScopeLable(instance)} Scope)`,textColor:0,backgroundColor:16764185};treeNode.tags.push(tag)}}(componentInstance,treeNode,i18n2)}),api.on.inspectComponent(({componentInstance:componentInstance,instanceData:instanceData})=>{componentInstance.__VUE_I18N__&&instanceData&&("legacy"===i18n2.mode?componentInstance.__VUE_I18N__!==i18n2.global.__composer&&inspectComposer(instanceData,componentInstance.__VUE_I18N__):inspectComposer(instanceData,componentInstance.__VUE_I18N__))}),api.addInspector({id:"vue-i18n-resource-inspector",label:VueDevToolsLabels_vue_i18n_resource_inspector,icon:"language",treeFilterPlaceholder:VueDevToolsPlaceholders_vue_i18n_resource_inspector}),api.on.getInspectorTree(payload=>{payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId&&function(payload,i18n2){payload.rootNodes.push({id:"global",label:"Global Scope"});const global2="composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;for(const[keyInstance,instance]of i18n2.__instances){const composer="composition"===i18n2.mode?instance:instance.__composer;global2!==composer&&payload.rootNodes.push({id:composer.id.toString(),label:`${getI18nScopeLable(keyInstance)} Scope`})}}(payload,i18n2)});const roots=/* @__PURE__ */new Map;api.on.getInspectorState(async payload=>{if(payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId)if(api.unhighlightElement(),function(payload,i18n2){const composer=getComposer$2(payload.nodeId,i18n2);composer&&(payload.state=function(composer){const state={},localeType="Locale related info",localeStates=[{type:localeType,key:"locale",editable:!0,value:composer.locale.value},{type:localeType,key:"fallbackLocale",editable:!0,value:composer.fallbackLocale.value},{type:localeType,key:"availableLocales",editable:!1,value:composer.availableLocales},{type:localeType,key:"inheritLocale",editable:!0,value:composer.inheritLocale}];state[localeType]=localeStates;const localeMessagesType="Locale messages info",localeMessagesStates=[{type:localeMessagesType,key:"messages",editable:!1,value:getLocaleMessageValue(composer.messages.value)}];state[localeMessagesType]=localeMessagesStates;{const datetimeFormatsType="Datetime formats info",datetimeFormatsStates=[{type:datetimeFormatsType,key:"datetimeFormats",editable:!1,value:composer.datetimeFormats.value}];state[datetimeFormatsType]=datetimeFormatsStates;const numberFormatsType="Datetime formats info",numberFormatsStates=[{type:numberFormatsType,key:"numberFormats",editable:!1,value:composer.numberFormats.value}];state[numberFormatsType]=numberFormatsStates}return state}(composer))}(payload,i18n2),"global"===payload.nodeId){if(!roots.has(payload.app)){const[root]=await api.getComponentInstances(payload.app);roots.set(payload.app,root)}api.highlightElement(roots.get(payload.app))}else{const instance=function(nodeId,i18n2){let instance=null;if("global"!==nodeId)for(const[component,composer]of i18n2.__instances.entries())if(composer.id.toString()===nodeId){instance=component;break}return instance}(payload.nodeId,i18n2);instance&&api.highlightElement(instance)}}),api.on.editInspectorState(payload=>{payload.app===app&&"vue-i18n-resource-inspector"===payload.inspectorId&&function(payload,i18n2){const composer=getComposer$2(payload.nodeId,i18n2);if(composer){const[field]=payload.path;"locale"===field&&isString(payload.state.value)?composer.locale.value=payload.state.value:"fallbackLocale"===field&&(isString(payload.state.value)||isArray(payload.state.value)||isObject(payload.state.value))?composer.fallbackLocale.value=payload.state.value:"inheritLocale"===field&&isBoolean(payload.state.value)&&(composer.inheritLocale=payload.state.value)}}(payload,i18n2)}),api.addTimelineLayer({id:"vue-i18n-timeline",label:VueDevToolsLabels_vue_i18n_timeline,color:VueDevToolsTimelineColors_vue_i18n_timeline}),resolve(!0)})}catch(e){console.error(e),reject(!1)}})}function getI18nScopeLable(instance){return instance.type.name||instance.type.displayName||instance.type.__file||"Anonymous"}function inspectComposer(instanceData,composer){const type="vue-i18n: composer properties";instanceData.state.push({type:type,key:"locale",editable:!0,value:composer.locale.value}),instanceData.state.push({type:type,key:"availableLocales",editable:!1,value:composer.availableLocales}),instanceData.state.push({type:type,key:"fallbackLocale",editable:!0,value:composer.fallbackLocale.value}),instanceData.state.push({type:type,key:"inheritLocale",editable:!0,value:composer.inheritLocale}),instanceData.state.push({type:type,key:"messages",editable:!1,value:getLocaleMessageValue(composer.messages.value)}),instanceData.state.push({type:type,key:"datetimeFormats",editable:!1,value:composer.datetimeFormats.value}),instanceData.state.push({type:type,key:"numberFormats",editable:!1,value:composer.numberFormats.value})}function getLocaleMessageValue(messages2){const value={};return Object.keys(messages2).forEach(key=>{const v2=messages2[key];var func;isFunction(v2)&&"source"in v2?value[key]={_custom:{type:"function",display:"<span>ƒ</span> "+((func=v2).source?`("${escape(func.source)}")`:"(?)")}}:isMessageAST(v2)&&v2.loc&&v2.loc.source?value[key]=v2.loc.source:isObject(v2)?value[key]=getLocaleMessageValue(v2):value[key]=v2}),value}const ESC={"<":"<",">":">",'"':""","&":"&"};function escape(s){return s.replace(/[<>"&]/g,escapeChar)}function escapeChar(a2){return ESC[a2]||a2}function getComposer$2(nodeId,i18n2){if("global"===nodeId)return"composition"===i18n2.mode?i18n2.global:i18n2.global.__composer;{const instance=Array.from(i18n2.__instances.values()).find(item=>item.id.toString()===nodeId);return instance?"composition"===i18n2.mode?instance:instance.__composer:null}}function addTimelineEvent(event,payload){if(devtoolsApi){let groupId;payload&&"groupId"in payload&&(groupId=payload.groupId,delete payload.groupId),devtoolsApi.addTimelineEvent({layerId:"vue-i18n-timeline",event:{title:event,groupId:groupId,time:Date.now(),meta:{},data:payload||{},logType:"compile-error"===event?"error":"fallback"===event||"missing"===event?"warning":"default"}})}}function createVueI18n(options={}){const composer=createComposer(function(options){const locale2=isString(options.locale)?options.locale:DEFAULT_LOCALE,fallbackLocale=isString(options.fallbackLocale)||isArray(options.fallbackLocale)||isPlainObject(options.fallbackLocale)||!1===options.fallbackLocale?options.fallbackLocale:locale2,missing=isFunction(options.missing)?options.missing:void 0,missingWarn=!isBoolean(options.silentTranslationWarn)&&!isRegExp(options.silentTranslationWarn)||!options.silentTranslationWarn,fallbackWarn=!isBoolean(options.silentFallbackWarn)&&!isRegExp(options.silentFallbackWarn)||!options.silentFallbackWarn,fallbackRoot=!isBoolean(options.fallbackRoot)||options.fallbackRoot,fallbackFormat=!!options.formatFallbackMessages,modifiers=isPlainObject(options.modifiers)?options.modifiers:{},pluralizationRules=options.pluralizationRules,postTranslation=isFunction(options.postTranslation)?options.postTranslation:void 0,warnHtmlMessage=!isString(options.warnHtmlInMessage)||"off"!==options.warnHtmlInMessage,escapeParameter=!!options.escapeParameterHtml,inheritLocale=!isBoolean(options.sync)||options.sync;let messages2=options.messages;if(isPlainObject(options.sharedMessages)){const sharedMessages=options.sharedMessages;messages2=Object.keys(sharedMessages).reduce((messages22,locale22)=>{const message=messages22[locale22]||(messages22[locale22]={});return assign(message,sharedMessages[locale22]),messages22},messages2||{})}const{__i18n:__i18n,__root:__root,__injectWithOption:__injectWithOption}=options,datetimeFormats=options.datetimeFormats,numberFormats=options.numberFormats;return{locale:locale2,fallbackLocale:fallbackLocale,messages:messages2,flatJson:options.flatJson,datetimeFormats:datetimeFormats,numberFormats:numberFormats,missing:missing,missingWarn:missingWarn,fallbackWarn:fallbackWarn,fallbackRoot:fallbackRoot,fallbackFormat:fallbackFormat,modifiers:modifiers,pluralRules:pluralizationRules,postTranslation:postTranslation,warnHtmlMessage:warnHtmlMessage,escapeParameter:escapeParameter,messageResolver:options.messageResolver,inheritLocale:inheritLocale,__i18n:__i18n,__root:__root,__injectWithOption:__injectWithOption}}(options)),{__extender:__extender}=options,vueI18n={id:composer.id,get locale(){return composer.locale.value},set locale(val){composer.locale.value=val},get fallbackLocale(){return composer.fallbackLocale.value},set fallbackLocale(val){composer.fallbackLocale.value=val},get messages(){return composer.messages.value},get datetimeFormats(){return composer.datetimeFormats.value},get numberFormats(){return composer.numberFormats.value},get availableLocales(){return composer.availableLocales},get missing(){return composer.getMissingHandler()},set missing(handler){composer.setMissingHandler(handler)},get silentTranslationWarn(){return isBoolean(composer.missingWarn)?!composer.missingWarn:composer.missingWarn},set silentTranslationWarn(val){composer.missingWarn=isBoolean(val)?!val:val},get silentFallbackWarn(){return isBoolean(composer.fallbackWarn)?!composer.fallbackWarn:composer.fallbackWarn},set silentFallbackWarn(val){composer.fallbackWarn=isBoolean(val)?!val:val},get modifiers(){return composer.modifiers},get formatFallbackMessages(){return composer.fallbackFormat},set formatFallbackMessages(val){composer.fallbackFormat=val},get postTranslation(){return composer.getPostTranslationHandler()},set postTranslation(handler){composer.setPostTranslationHandler(handler)},get sync(){return composer.inheritLocale},set sync(val){composer.inheritLocale=val},get warnHtmlInMessage(){return composer.warnHtmlMessage?"warn":"off"},set warnHtmlInMessage(val){composer.warnHtmlMessage="off"!==val},get escapeParameterHtml(){return composer.escapeParameter},set escapeParameterHtml(val){composer.escapeParameter=val},get pluralizationRules(){return composer.pluralRules||{}},__composer:composer,t:(...args)=>Reflect.apply(composer.t,composer,[...args]),rt:(...args)=>Reflect.apply(composer.rt,composer,[...args]),te:(key,locale2)=>composer.te(key,locale2),tm:key=>composer.tm(key),getLocaleMessage:locale2=>composer.getLocaleMessage(locale2),setLocaleMessage(locale2,message){composer.setLocaleMessage(locale2,message)},mergeLocaleMessage(locale2,message){composer.mergeLocaleMessage(locale2,message)},d:(...args)=>Reflect.apply(composer.d,composer,[...args]),getDateTimeFormat:locale2=>composer.getDateTimeFormat(locale2),setDateTimeFormat(locale2,format2){composer.setDateTimeFormat(locale2,format2)},mergeDateTimeFormat(locale2,format2){composer.mergeDateTimeFormat(locale2,format2)},n:(...args)=>Reflect.apply(composer.n,composer,[...args]),getNumberFormat:locale2=>composer.getNumberFormat(locale2),setNumberFormat(locale2,format2){composer.setNumberFormat(locale2,format2)},mergeNumberFormat(locale2,format2){composer.mergeNumberFormat(locale2,format2)}};return vueI18n.__extender=__extender,"production"!==process.env.NODE_ENV&&(vueI18n.__enableEmitter=emitter=>{const __composer=composer;__composer[EnableEmitter]&&__composer[EnableEmitter](emitter)},vueI18n.__disableEmitter=()=>{const __composer=composer;__composer[DisableEmitter]&&__composer[DisableEmitter]()}),vueI18n}function mergeToGlobal(g,options){g.locale=options.locale||g.locale,g.fallbackLocale=options.fallbackLocale||g.fallbackLocale,g.missing=options.missing||g.missing,g.silentTranslationWarn=options.silentTranslationWarn||g.silentFallbackWarn,g.silentFallbackWarn=options.silentFallbackWarn||g.silentFallbackWarn,g.formatFallbackMessages=options.formatFallbackMessages||g.formatFallbackMessages,g.postTranslation=options.postTranslation||g.postTranslation,g.warnHtmlInMessage=options.warnHtmlInMessage||g.warnHtmlInMessage,g.escapeParameterHtml=options.escapeParameterHtml||g.escapeParameterHtml,g.sync=options.sync||g.sync,g.__composer[SetPluralRulesSymbol](options.pluralizationRules||g.pluralizationRules);const messages2=getLocaleMessages(g.locale,{messages:options.messages,__i18n:options.__i18n});return Object.keys(messages2).forEach(locale2=>g.mergeLocaleMessage(locale2,messages2[locale2])),options.datetimeFormats&&Object.keys(options.datetimeFormats).forEach(locale2=>g.mergeDateTimeFormat(locale2,options.datetimeFormats[locale2])),options.numberFormats&&Object.keys(options.numberFormats).forEach(locale2=>g.mergeNumberFormat(locale2,options.numberFormats[locale2])),g}const baseFormatProps={tag:{type:[String,Object]},locale:{type:String},scope:{type:String,validator:val=>"parent"===val||"global"===val,default:"parent"},i18n:{type:Object}};function getFragmentableTag(){return Fragment}const Translation=/* @__PURE__ */defineComponent({name:"i18n-t",props:assign({keypath:{type:String,required:!0},plural:{type:[Number,String],validator:val=>isNumber(val)||!isNaN(val)}},baseFormatProps),setup(props,context){const{slots:slots,attrs:attrs}=context,i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return()=>{const renderChildren=()=>{const keys=Object.keys(slots).filter(key=>"_"!==key[0]),options=create();props.locale&&(options.locale=props.locale),void 0!==props.plural&&(options.plural=isString(props.plural)?+props.plural:props.plural);const arg=function({slots:slots},keys){if(1===keys.length&&"default"===keys[0])return(slots.default?slots.default():[]).reduce((slot,current)=>[...slot,...current.type===Fragment?current.children:[current]],[]);return keys.reduce((arg,key)=>{const slot=slots[key];return slot&&(arg[key]=slot()),arg},create())}(context,keys);return i18n2[TranslateVNodeSymbol](props.keypath,arg,options)},assignedAttrs=assign(create(),attrs),tag=isString(props.tag)||isObject(props.tag)?props.tag:getFragmentableTag();return isObject(tag)?h(tag,assignedAttrs,{default:renderChildren}):h(tag,assignedAttrs,renderChildren())}}});function renderFormatter(props,context,slotKeys,partFormatter){const{slots:slots,attrs:attrs}=context;return()=>{const renderChildren=()=>{const options={part:!0};let overrides=create();props.locale&&(options.locale=props.locale),isString(props.format)?options.key=props.format:isObject(props.format)&&(isString(props.format.key)&&(options.key=props.format.key),overrides=Object.keys(props.format).reduce((options2,prop)=>slotKeys.includes(prop)?assign(create(),options2,{[prop]:props.format[prop]}):options2,create()));const parts=partFormatter(props.value,options,overrides);let children=[options.key];return isArray(parts)?children=parts.map((part,index2)=>{const slot=slots[part.type],node=slot?slot({[part.type]:part.value,index:index2,parts:parts}):[part.value];var target;return isArray(target=node)&&!isString(target[0])&&(node[0].key=`${part.type}-${index2}`),node}):isString(parts)&&(children=[parts]),children},assignedAttrs=assign(create(),attrs),tag=isString(props.tag)||isObject(props.tag)?props.tag:getFragmentableTag();return isObject(tag)?h(tag,assignedAttrs,{default:renderChildren}):h(tag,assignedAttrs,renderChildren())}}const NumberFormat=/* @__PURE__ */defineComponent({name:"i18n-n",props:assign({value:{type:Number,required:!0},format:{type:[String,Object]}},baseFormatProps),setup(props,context){const i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return renderFormatter(props,context,NUMBER_FORMAT_OPTIONS_KEYS,(...args)=>i18n2[NumberPartsSymbol](...args))}});function parseValue(value){if(isString(value))return{path:value};if(isPlainObject(value)){if(!("path"in value))throw createI18nError(I18nErrorCodes_REQUIRED_VALUE,"path");return value}throw createI18nError(I18nErrorCodes_INVALID_VALUE)}function makeParams(value){const{path:path,locale:locale2,args:args,choice:choice,plural:plural}=value,options={},named=args||{};return isString(locale2)&&(options.locale=locale2),isNumber(choice)&&(options.plural=choice),isNumber(plural)&&(options.plural=plural),[path,named,options]}function apply(app,i18n2,...options){const pluginOptions=isPlainObject(options[0])?options[0]:{};(!isBoolean(pluginOptions.globalInstall)||pluginOptions.globalInstall)&&([Translation.name,"I18nT"].forEach(name=>app.component(name,Translation)),[NumberFormat.name,"I18nN"].forEach(name=>app.component(name,NumberFormat)),[DatetimeFormat.name,"I18nD"].forEach(name=>app.component(name,DatetimeFormat))),app.directive("t",function(i18n2){const _process=binding=>{"production"!==process.env.NODE_ENV&&warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_TRANSLATE_CUSTOME_DIRECTIVE));const{instance:instance,value:value}=binding;if(!instance||!instance.$)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const composer=function(i18n2,instance){const i18nInternal=i18n2;if("composition"===i18n2.mode)return i18nInternal.__getInstance(instance)||i18n2.global;{const vueI18n=i18nInternal.__getInstance(instance);return null!=vueI18n?vueI18n.__composer:i18n2.global.__composer}}(i18n2,instance.$),parsedValue=parseValue(value);return[Reflect.apply(composer.t,composer,[...makeParams(parsedValue)]),composer]};return{created:(el,binding)=>{const[textContent,composer]=_process(binding);inBrowser&&(el.__i18nWatcher=watch(composer.locale,()=>{binding.instance&&binding.instance.$forceUpdate()})),el.__composer=composer,el.textContent=textContent},unmounted:el=>{inBrowser&&el.__i18nWatcher&&(el.__i18nWatcher(),el.__i18nWatcher=void 0,delete el.__i18nWatcher),el.__composer&&(el.__composer=void 0,delete el.__composer)},beforeUpdate:(el,{value:value})=>{if(el.__composer){const composer=el.__composer,parsedValue=parseValue(value);el.textContent=Reflect.apply(composer.t,composer,[...makeParams(parsedValue)])}},getSSRProps:binding=>{const[textContent]=_process(binding);return{textContent:textContent}}}}(i18n2))}const I18nInjectionKey=/* @__PURE__ */makeSymbol("global-vue-i18n");function useI18n(options={}){const instance=getCurrentInstance();if(null==instance)throw createI18nError(I18nErrorCodes_MUST_BE_CALL_SETUP_TOP);if(!instance.isCE&&null!=instance.appContext.app&&!instance.appContext.app.__VUE_I18N_SYMBOL__)throw createI18nError(I18nErrorCodes_NOT_INSTALLED);const i18n2=function(instance){const i18n2=inject(instance.isCE?I18nInjectionKey:instance.appContext.app.__VUE_I18N_SYMBOL__);if(!i18n2)throw createI18nError(instance.isCE?I18nErrorCodes_NOT_INSTALLED_WITH_PROVIDE:I18nErrorCodes_UNEXPECTED_ERROR);return i18n2}(instance),gl=function(i18n2){return"composition"===i18n2.mode?i18n2.global:i18n2.global.__composer}(i18n2),componentOptions=getComponentOptions(instance),scope=function(options,componentOptions){return isEmptyObject(options)?"__i18n"in componentOptions?"local":"global":options.useScope?options.useScope:"local"}(options,componentOptions);if("global"===scope)return adjustI18nResources(gl,options,componentOptions),gl;if("parent"===scope){let composer2=getComposer(i18n2,instance,options.__useComponent);return null==composer2&&("production"!==process.env.NODE_ENV&&warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE)),composer2=gl),composer2}if("isolated"===scope){if("composition"!==i18n2.mode)throw createI18nError(I18nErrorCodes_NOT_AVAILABLE_COMPOSITION_IN_LEGACY);const i18nInternalIso=i18n2,composerOptions=assign({},options),parentComposer=getComposer(i18n2,instance);composerOptions.__root=parentComposer||gl;const composer2=createComposer(composerOptions);i18nInternalIso.__composerExtend&&(composer2[DisposeSymbol]=i18nInternalIso.__composerExtend(composer2));let emitter=null;if("production"!==process.env.NODE_ENV){emitter=createEmitter();const _composer=composer2;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter),emitter.on("*",addTimelineEvent)}return getCurrentScope()&&onScopeDispose(()=>{if("production"!==process.env.NODE_ENV){emitter&&emitter.off("*",addTimelineEvent);const _composer=composer2;_composer[DisableEmitter]&&_composer[DisableEmitter]()}const dispose=composer2[DisposeSymbol];dispose&&(dispose(),delete composer2[DisposeSymbol])}),composer2}const i18nInternal=i18n2;let composer=i18nInternal.__getInstance(instance);if(null==composer){const composerOptions=assign({},options);"__i18n"in componentOptions&&(composerOptions.__i18n=componentOptions.__i18n),gl&&(composerOptions.__root=gl),composer=createComposer(composerOptions),i18nInternal.__composerExtend&&(composer[DisposeSymbol]=i18nInternal.__composerExtend(composer)),function(i18n2,target,composer){let emitter=null;onMounted(()=>{if("production"!==process.env.NODE_ENV){target.__VUE_I18N__=composer,emitter=createEmitter();const _composer=composer;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter),emitter.on("*",addTimelineEvent)}},target),onUnmounted(()=>{const _composer=composer;"production"!==process.env.NODE_ENV&&(emitter&&emitter.off("*",addTimelineEvent),_composer[DisableEmitter]&&_composer[DisableEmitter](),delete target.__VUE_I18N__),i18n2.__deleteInstance(target);const dispose=_composer[DisposeSymbol];dispose&&(dispose(),delete _composer[DisposeSymbol])},target)}(i18nInternal,instance,composer),i18nInternal.__setInstance(instance,composer)}else"production"!==process.env.NODE_ENV&&"local"===scope&&warn(getWarnMessage(I18nWarnCodes.DUPLICATE_USE_I18N_CALLING));return composer}function getComposer(i18n2,target,useComponent=!1){let composer=null;const root=target.root;let current=function(target,useComponent=!1){if(null==target)return null;return useComponent&&target.vnode.ctx||target.parent}(target,useComponent);for(;null!=current;){const i18nInternal=i18n2;if("composition"===i18n2.mode)composer=i18nInternal.__getInstance(current);else if(__VUE_I18N_LEGACY_API__){const vueI18n=i18nInternal.__getInstance(current);null!=vueI18n&&(composer=vueI18n.__composer,useComponent&&composer&&!composer[InejctWithOptionSymbol]&&(composer=null))}if(null!=composer)break;if(root===current)break;current=current.parent}return composer}const globalExportProps=["locale","fallbackLocale","availableLocales"],globalExportMethods=["t","rt","d","n","tm","te"];const DatetimeFormat=/* @__PURE__ */defineComponent({name:"i18n-d",props:assign({value:{type:[Number,Date],required:!0},format:{type:[String,Object]}},baseFormatProps),setup(props,context){const i18n2=props.i18n||useI18n({useScope:props.scope,__useComponent:!0});return renderFormatter(props,context,DATETIME_FORMAT_OPTIONS_KEYS,(...args)=>i18n2[DatetimePartsSymbol](...args))}});var hook;if("boolean"!=typeof __VUE_I18N_FULL_INSTALL__&&(getGlobalThis().__VUE_I18N_FULL_INSTALL__=!0),"boolean"!=typeof __VUE_I18N_LEGACY_API__&&(getGlobalThis().__VUE_I18N_LEGACY_API__=!0),"boolean"!=typeof __INTLIFY_DROP_MESSAGE_COMPILER__&&(getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__=!1),"boolean"!=typeof __INTLIFY_PROD_DEVTOOLS__&&(getGlobalThis().__INTLIFY_PROD_DEVTOOLS__=!1),_compiler=function(message,context){if(!__INTLIFY_DROP_MESSAGE_COMPILER__&&isString(message)){const warnHtmlMessage=!isBoolean(context.warnHtmlMessage)||context.warnHtmlMessage;"production"!==process.env.NODE_ENV&&checkHtmlMessage(message,warnHtmlMessage);const cacheKey=(context.onCacheKey||defaultOnCacheKey)(message),cached=compileCache[cacheKey];if(cached)return cached;const{ast:ast,detectError:detectError}=function(message,options={}){let detectError=!1;const onError=options.onError||defaultOnError;return options.onError=err=>{detectError=!0,onError(err)},{...baseCompile$1(message,options),detectError:detectError}}(message,{...context,location:"production"!==process.env.NODE_ENV,jit:!0}),msg=format(ast);return detectError?msg:compileCache[cacheKey]=msg}{if("production"!==process.env.NODE_ENV&&!isMessageAST(message))return warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`),()=>message;const cacheKey=message.cacheKey;if(cacheKey){const cached=compileCache[cacheKey];return cached||(compileCache[cacheKey]=format(message))}return format(message)}},_resolver=function(obj,path){if(!isObject(obj))return null;let hit=cache.get(path);if(hit||(hit=function(path){const keys=[];let c,key,newChar,type,transition,action,typeMap,index2=-1,mode=0,subPathDepth=0;const actions=[];function maybeUnescapeQuote(){const nextChar=path[index2+1];if(5===mode&&"'"===nextChar||6===mode&&'"'===nextChar)return index2++,newChar="\\"+nextChar,actions[0](),!0}for(actions[0]=()=>{void 0===key?key=newChar:key+=newChar},actions[1]=()=>{void 0!==key&&(keys.push(key),key=void 0)},actions[2]=()=>{actions[0](),subPathDepth++},actions[3]=()=>{if(subPathDepth>0)subPathDepth--,mode=4,actions[0]();else{if(subPathDepth=0,void 0===key)return!1;if(key=formatSubPath(key),!1===key)return!1;actions[1]()}};null!==mode;)if(index2++,c=path[index2],"\\"!==c||!maybeUnescapeQuote()){if(type=getPathCharType(c),typeMap=pathStateMachine[mode],transition=typeMap[type]||typeMap.l||8,8===transition)return;if(mode=transition[0],void 0!==transition[1]&&(action=actions[transition[1]],action&&(newChar=c,!1===action())))return;if(7===mode)return keys}}(path),hit&&cache.set(path,hit)),!hit)return null;const len=hit.length;let last=obj,i=0;for(;i<len;){const key=hit[i];if(AST_NODE_PROPS_KEYS.includes(key)&&isMessageAST(last))return null;if(!isObject(last))return null;if(!hasOwn(last,key))return null;const val=last[key];if(void 0===val)return null;if(isFunction(last))return null;last=val,i++}return last},_fallbacker=fallbackWithLocaleChain,"production"!==process.env.NODE_ENV||__INTLIFY_PROD_DEVTOOLS__){const target=getGlobalThis();target.__INTLIFY__=!0,hook=target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__,devtools=hook}process.env.NODE_ENV;const modules=/* @__PURE__ */Object.assign({"./locales/en.ts":{"帮助":"Help","线吸附":"LineSnap","点吸附":"PointSnap","取消命令":"Cancel Command","确认命令":"Confirm Command","其他功能":"Other Functions","默认":"Default","绘制线段":"Line","绘制门线":"Door","绘制普通窗":"Window","绘制飘窗":"Bay Window","绘制垭口":"Wall Opening","绘制房梁":"Beam","绘制柱子":"Column","绘制栏杆":"Railing","修改模式":"Edit Mode","裁剪线段":"Trim Line","手动测距":"Manual Measurement","射线测距":"Ray Measurement","操作回滚":"Undo","撤销操作回滚":"Redo","合并":"Merge","两点连接":"Connect Two Points","两线连接":"Connect Two Lines","垂直纠正":"Correct Vertical Alignment","连续垂直纠正":"Continuous Vertical Alignment","角度显示":"Show Angle","全选":"Select All","删除":"Delete","属性面板":"Properties Panel","更多":"More","预览白膜":"Preview White Model","预览CAD":"Preview CAD","预览":"Preview","请选择线段":"Please select a line segment","删除成功":"Deleted Successfully","进入命令失败":"Failed to Enter Command","绘制完成":"Drawing Complete","绘制飘窗不合法提示":"Bay window width cannot be 0","长度":"Length","高度":"Height","离地高":"Height Above Floor","鼠标滚轮":"Mouse Wheel","绘制孔洞提示":"Please select a line segment as the wall for the opening, %s to modify the default opening length, %s to quickly increase the length, %s to quickly decrease the length, %s to cancel the command","修改绘制的长度":"Modify Drawing Length","修改绘制的宽度":"Modify Drawing Width","修改绘制的离地高":"Modify Height Above Floor","请输入长度":"Please enter the length","请输入高度":"Please enter the height","请输入离地高":"Please enter the height above floor","绘制线段提示":"Click two points to draw a line segment. Multiple line segments can be drawn continuously, %s to lock the direction, %s to cancel the command","绘制线段方向锁定漫游引导提示":"When drawing, the direction of the previous line is automatically detected, allowing the new line to extend only in the same direction (parallel) or at a right angle (perpendicular).","方向锁定":"Direction Lock (%s)","方向锁定无快捷键":"Direction Lock","绘制线段不合法提示":"At least %s line segments are required","手动测距提示":"Please select two points, %s to cancel the command","合并线段进入不合法提示":"Line merge not executed. Please select at least two line segments","已合并":"Merged","合并失败提示":"Merge failed. No shared point was found","选择线段小于2提醒":"Please select 2 line segments","两条线段夹角大于135度提醒":"The angle between the two line segments must be less than 135°","连接成功":"Connected Successfully","未选择1条线段提醒":"Please select one line segment","选择两条有端点相交的线段提醒":"Please select two line segments that intersect at their endpoints","修改线段提示":"Please select the line segment to modify, %s to cancel the command","跟随移动":"Follow Movement","重置位置":"Reset Position","确认":"Confirm","返回":"Back","加载中":"Loading","操作提示":"Instructions","跳过":"Skip","下一步":"Next","完成":"Finish","控制面板":"Control Panel","宽度":"Width","飘窗宽度":"Bay Window Width","修改":"Modify","门":"Door","窗户":"Window","梁":"Beam","飘窗":"Bay Window","垭口":"Wall Opening","栏杆":"Railing","墙线":"Wall Line","柱子":"Column","数值小于提醒":"Value cannot be less than %s mm","数值大于提醒":"Value cannot be greater than %s mm","取消命令漫游引导":"Clear the current drawing and return to the default state","确认命令漫游引导":"Confirm the current drawing, then continue drawing or return to the default state","提示漫游引导":"Tips about the drawing process and commonly used keyboard shortcuts","清空":"Clear","取消":"Cancel","设置最大值":"Set Maximum","设置最小值":"Set Minimum","射线测距提示":"Please select a point on the line segment as the ray origin, %s to cancel the command","转化为墙壁":"Convert to Wall","已撤回":"Withdrawn","已回退":"Reverted","转化成功":"Conversion Successful","选择需要转化的柱子提示":"Please select the columns to convert","请选择相同类型的结构":"Please select the same type of structure","请选择需要合并的结构":"Please select the structures to merge","柱子结构不支持合并":"Column structure does not support merging","请选择需要合并的结构, 且选择数量大于1":"Please select the structures to merge, and select more than 1","选择的孔洞类型数量不能大于1种":"The number of selected hole types cannot exceed 1.","复制":"Copy","粘贴":"Paste","已复制":"Copied","粘贴失败":"Paste failed","裁断":"Cut","裁断失败":"Cutting failed","成功":"Success","应用":"Apply","矩形":"Rectangle","非标准":"Non-standard","自定义":"Custom","转移":"Transfer","引用":"Quote","确定":"OK","请选择":"Please select","请选择需要粘贴的属性":"Select the property to paste","高":"High","长":"Long","请选择需要引用的属性":"Please select the attributes to reference","转化失败":"Conversion failed","逆转方向":"Reverse direction","绘制曲线":"Draw curve","绘制墙线":"Draw wall lines","绘制曲线墙":"Draw curved wall","该功能正在加急开发中":"This feature is under urgent development"},"./locales/zh-CN.ts":{"帮助":"帮助","线吸附":"线吸附","点吸附":"点吸附","取消命令":"取消命令","确认命令":"确认命令","其他功能":"其他功能","默认":"默认","绘制线段":"绘制线段","绘制门线":"绘制门线","绘制普通窗":"绘制普通窗","绘制飘窗":"绘制飘窗","绘制垭口":"绘制垭口","绘制房梁":"绘制房梁","绘制柱子":"绘制柱子","绘制栏杆":"绘制栏杆","修改模式":"修改模式","裁剪线段":"裁剪线段","手动测距":"手动测距","射线测距":"射线测距","操作回滚":"操作回滚","撤销操作回滚":"撤销操作回滚","合并":"合并","两点连接":"两点连接","两线连接":"两线连接","垂直纠正":"垂直纠正","连续垂直纠正":"连续垂直纠正","角度显示":"角度显示","全选":"全选","删除":"删除","属性面板":"属性面板","更多":"更多","预览白膜":"预览白膜","预览CAD":"预览CAD","预览":"预览","请选择线段":"请选择线段","删除成功":"删除成功","进入命令失败":"进入命令失败","绘制完成":"绘制完成","绘制飘窗不合法提示":"飘窗宽度不能为0","长度":"长度","高度":"高度","离地高":"离地高","鼠标滚轮":"鼠标滚轮","绘制孔洞提示":"请选择一条线段作为空洞依附墙体, %s 修改孔洞默认长度, %s 快速修改长度, %s 快速增加长度, %s 快速减少长度, %s 取消命令","修改绘制的长度":"修改绘制的长度","修改绘制的宽度":"修改绘制的宽度","修改绘制的离地高":"修改绘制的离地高","请输入长度":"请输入长度","请输入高度":"请输入高度","请输入离地高":"请输入离地高","绘制线段提示":"两个点绘制一条线段,可连续绘制多条线段, %s 键锁定方向, %s 取消命令","绘制线段方向锁定漫游引导提示":"绘制时,会自动捕捉上一条线的走势,让新线只能沿着它的同向(平行)或直角(垂直)延伸。","方向锁定":"方向锁定( %s )","方向锁定无快捷键":"方向锁定","绘制线段不合法提示":"需要绘制的线段不得低于%s条","手动测距提示":"请选择两个点, %s 取消命令","合并线段进入不合法提示":"未执行线段合并,请选择至少两条线段","已合并":"已合并","合并失败提示":"合并失败,未找到共用点","选择线段小于2提醒":"请选择2条线段","两条线段夹角大于135度提醒":"两条线段角度需要小于135度","连接成功":"连接成功","未选择1条线段提醒":"请选择一条线段","选择两条有端点相交的线段提醒":"请选择两条具有端点相交的线段","修改线段提示":"请选择需要修改的线段, %s 取消命令","跟随移动":"跟随移动","重置位置":"重置位置","确认":"确认","返回":"返回","加载中":"加载中","操作提示":"操作提示","跳过":"跳过","下一步":"下一步","完成":"完成","控制面板":"控制面板","宽度":"宽度","飘窗宽度":"飘窗宽度","修改":"修改","门":"门","窗户":"窗户","梁":"梁","飘窗":"飘窗","垭口":"垭口","栏杆":"栏杆","墙线":"墙线","柱子":"柱子","数值小于提醒":"数值不能小于%smm","数值大于提醒":"数值不能大于%smm","取消命令漫游引导":"清空当前的绘制内容,并退回到默认状态","确认命令漫游引导":"确认完成当前的绘制内容,继续新的绘制或者退回默认状态","提示漫游引导":"绘制过程中的一些注意事项和常用的键盘快捷键提示","清空":"清空","取消":"取消","设置最大值":"设置最大值","设置最小值":"设置最小值","射线测距提示":"请选择线段上的一个点作为发射点, %s 取消命令","转化为墙壁":"转化为墙壁","已撤回":"已撤回","已回退":"已回退","转化成功":"转化成功","选择需要转化的柱子提示":"请选择需要转化的柱子","请选择相同类型的结构":"请选择相同类型的结构","请选择需要合并的结构":"请选择需要合并的结构","柱子结构不支持合并":"柱子结构不支持合并","请选择需要合并的结构, 且选择数量大于1":"请选择需要合并的结构 且选择数量大于1","选择的孔洞类型数量不能大于1种":"选择的孔洞类型数量不能大于1种","复制":"复制","粘贴":"粘贴","已复制":"已复制","粘贴失败":"粘贴失败","裁断":"裁断","裁断失败":"裁断失败","成功":"成功","应用":"应用","矩形":"矩形","非标准":"非标准","自定义":"自定义","转移":"转移","引用":"引用","确定":"确定","请选择":"请选择","请选择需要粘贴的属性":"请选择需要粘贴的属性","高":"高","长":"长","请选择需要引用的属性":"请选择需要引用的属性","转化失败":"转化失败","逆转方向":"逆转方向","绘制曲线":"绘制曲线","绘制墙线":"绘制墙线","绘制曲线墙":"绘制曲线墙","该功能正在加急开发中":"该功能正在加急开发中"},"./locales/zh-TW.ts":{"帮助":"幫助","线吸附":"線吸附","点吸附":"點吸附","取消命令":"取消命令","确认命令":"確認命令","其他功能":"其他功能","默认":"預設","绘制线段":"繪製線段","绘制门线":"繪製門線","绘制普通窗":"繪製普通窗","绘制飘窗":"繪製飄窗","绘制垭口":"繪製埡口","绘制房梁":"繪製房樑","绘制柱子":"繪製柱子","绘制栏杆":"繪製欄杆","修改模式":"修改模式","裁剪线段":"裁剪線段","手动测距":"手動測距","射线测距":"射線測距","操作回滚":"操作回滾","撤销操作回滚":"撤銷操作回滾","合并":"合併","两点连接":"兩點連接","两线连接":"兩線連接","垂直纠正":"垂直糾正","连续垂直纠正":"連續垂直糾正","角度显示":"角度顯示","全选":"全選","删除":"刪除","属性面板":"屬性面板","更多":"更多","预览白膜":"預覽白膜","预览CAD":"預覽CAD","预览":"預覽","请选择线段":"請選擇線段","删除成功":"刪除成功","进入命令失败":"進入命令失敗","绘制完成":"繪製完成","绘制飘窗不合法提示":"飄窗寬度不能為0","长度":"長度","高度":"高度","离地高":"離地高","鼠标滚轮":"滑鼠滾輪","绘制孔洞提示":"請選擇一條線段作為空洞依附牆體, %s 修改孔洞預設長度, %s 快速修改長度, %s 快速增加長度, %s 快速減少長度, %s 取消命令","修改绘制的长度":"修改繪製的長度","修改绘制的宽度":"修改繪製的寬度","修改绘制的离地高":"修改繪製的離地高","请输入长度":"請輸入長度","请输入高度":"請輸入高度","请输入离地高":"請輸入離地高","绘制线段提示":"兩個點繪製一條線段,可連續繪製多條線段, %s 鍵鎖定方向, %s 取消命令","绘制线段方向锁定漫游引导提示":"繪製時,會自動捕捉上一條線的走勢,讓新線只能沿著它的同向(平行)或直角(垂直)延伸。","方向锁定":"方向鎖定( %s )","方向锁定无快捷键":"方向鎖定","绘制线段不合法提示":"需要繪製的線段不得低於%s條","手动测距提示":"請選擇兩個點, %s 取消命令","合并线段进入不合法提示":"未執行線段合併,請選擇至少兩條線段","已合并":"已合併","合并失败提示":"合併失敗,未找到共用點","选择线段小于2提醒":"請選擇2條線段","两条线段夹角大于135度提醒":"兩條線段角度需要小於135度","连接成功":"連接成功","未选择1条线段提醒":"請選擇一條線段","选择两条有端点相交的线段提醒":"請選擇兩條具有端點相交的線段","修改线段提示":"請選擇需要修改的線段, %s 取消命令","跟随移动":"跟隨移動","重置位置":"重置位置","确认":"確認","返回":"返回","加载中":"載入中","操作提示":"操作提示","跳过":"跳過","下一步":"下一步","完成":"完成","控制面板":"控制面板","宽度":"寬度","飘窗宽度":"飄窗寬度","修改":"修改","门":"門","窗户":"窗戶","梁":"樑","飘窗":"飄窗","垭口":"埡口","栏杆":"欄杆","墙线":"牆線","柱子":"柱子","数值小于提醒":"數值不能小於%smm","数值大于提醒":"數值不能大於%smm","取消命令漫游引导":"清空當前的繪製內容,並退回到預設狀態","确认命令漫游引导":"確認完成當前的繪製內容,繼續新的繪製或者退回預設狀態","提示漫游引导":"繪製過程中的一些注意事項和常用的鍵盤快捷鍵提示","清空":"清空","取消":"取消","设置最大值":"設定最大值","设置最小值":"設定最小值","射线测距提示":"請選擇線段上的一個點作為射線起點,%s 取消命令","转化为墙壁":"轉化為牆壁","已撤回":"已撤回","已回退":"已回退","转化成功":"轉化成功","选择需要转化的柱子提示":"請選擇需要轉化的柱子","请选择相同类型的结构":"請選擇相同類型的結構","请选择需要合并的结构":"請選擇需要合併的結構","柱子结构不支持合并":"柱結構不支援合併","请选择需要合并的结构, 且选择数量大于1":"請選擇需要合併的結構,且選擇數量需大於1","选择的孔洞类型数量不能大于1种":"選擇的孔洞類型數量不能大於1種","复制":"複製","粘贴":"貼上","已复制":"已複製","粘贴失败":"貼上失敗","裁断":"裁切","裁断失败":"裁切失敗","成功":"成功","应用":"應用","矩形":"矩形","非标准":"非標準","自定义":"自訂","转移":"轉移","引用":"引用","确定":"確定","请选择":"請選擇","请选择需要粘贴的属性":"請選擇需要貼上的屬性","高":"高","长":"長","请选择需要引用的属性":"請選擇需要引用的屬性","转化失败":"轉換失敗","逆转方向":"反轉方向","绘制曲线":"繪製曲線","绘制墙线":"繪製牆線","绘制曲线墙":"繪製曲線牆","该功能正在加急开发中":"該功能正在加急開發中"}}),messages={};for(const[path,message]of Object.entries(modules)){const locale2=path.match(/\.\/locales\/(.+)\.ts$/)?.[1];locale2&&(messages[locale2]=message)}const i18n=function(options={}){const __legacyMode=__VUE_I18N_LEGACY_API__&&isBoolean(options.legacy)?options.legacy:__VUE_I18N_LEGACY_API__;"production"!==process.env.NODE_ENV&&__legacyMode&&warnOnce(getWarnMessage(I18nWarnCodes.DEPRECATE_LEGACY_MODE));const __globalInjection=!isBoolean(options.globalInjection)||options.globalInjection,__instances=/* @__PURE__ */new Map,[globalScope,__global]=function(options,legacyMode){const scope=effectScope(),obj=__VUE_I18N_LEGACY_API__&&legacyMode?scope.run(()=>createVueI18n(options)):scope.run(()=>createComposer(options));if(null==obj)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);return[scope,obj]}(options,__legacyMode),symbol=/* @__PURE__ */makeSymbol("production"!==process.env.NODE_ENV?"vue-i18n":""),i18n2={get mode(){return __VUE_I18N_LEGACY_API__&&__legacyMode?"legacy":"composition"},async install(app,...options2){if("production"!==process.env.NODE_ENV&&(app.__VUE_I18N__=i18n2),app.__VUE_I18N_SYMBOL__=symbol,app.provide(app.__VUE_I18N_SYMBOL__,i18n2),isPlainObject(options2[0])){const opts=options2[0];i18n2.__composerExtend=opts.__composerExtend,i18n2.__vueI18nExtend=opts.__vueI18nExtend}let globalReleaseHandler=null;!__legacyMode&&__globalInjection&&(globalReleaseHandler=function(app,composer){const i18n2=/* @__PURE__ */Object.create(null);globalExportProps.forEach(prop=>{const desc=Object.getOwnPropertyDescriptor(composer,prop);if(!desc)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const wrap=isRef(desc.value)?{get:()=>desc.value.value,set(val){desc.value.value=val}}:{get:()=>desc.get&&desc.get()};Object.defineProperty(i18n2,prop,wrap)}),app.config.globalProperties.$i18n=i18n2,globalExportMethods.forEach(method=>{const desc=Object.getOwnPropertyDescriptor(composer,method);if(!desc||!desc.value)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);Object.defineProperty(app.config.globalProperties,`$${method}`,desc)});const dispose=()=>{delete app.config.globalProperties.$i18n,globalExportMethods.forEach(method=>{delete app.config.globalProperties[`$${method}`]})};return dispose}(app,i18n2.global)),__VUE_I18N_FULL_INSTALL__&&apply(app,i18n2,...options2),__VUE_I18N_LEGACY_API__&&__legacyMode&&app.mixin(function(vuei18n,composer,i18n2){return{beforeCreate(){const instance=getCurrentInstance();if(!instance)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const options=this.$options;if(options.i18n){const optionsI18n=options.i18n;if(options.__i18n&&(optionsI18n.__i18n=options.__i18n),optionsI18n.__root=composer,this===this.$root)this.$i18n=mergeToGlobal(vuei18n,optionsI18n);else{optionsI18n.__injectWithOption=!0,optionsI18n.__extender=i18n2.__vueI18nExtend,this.$i18n=createVueI18n(optionsI18n);const _vueI18n=this.$i18n;_vueI18n.__extender&&(_vueI18n.__disposer=_vueI18n.__extender(this.$i18n))}}else if(options.__i18n)if(this===this.$root)this.$i18n=mergeToGlobal(vuei18n,options);else{this.$i18n=createVueI18n({__i18n:options.__i18n,__injectWithOption:!0,__extender:i18n2.__vueI18nExtend,__root:composer});const _vueI18n=this.$i18n;_vueI18n.__extender&&(_vueI18n.__disposer=_vueI18n.__extender(this.$i18n))}else this.$i18n=vuei18n;options.__i18nGlobal&&adjustI18nResources(composer,options,options),this.$t=(...args)=>this.$i18n.t(...args),this.$rt=(...args)=>this.$i18n.rt(...args),this.$te=(key,locale2)=>this.$i18n.te(key,locale2),this.$d=(...args)=>this.$i18n.d(...args),this.$n=(...args)=>this.$i18n.n(...args),this.$tm=key=>this.$i18n.tm(key),i18n2.__setInstance(instance,this.$i18n)},mounted(){if("production"!==process.env.NODE_ENV&&this.$i18n){const instance=getCurrentInstance();if(!instance)return;const _vueI18n=this.$i18n;instance.__VUE_I18N__=_vueI18n.__composer;const emitter=this.__v_emitter=createEmitter();_vueI18n.__enableEmitter&&_vueI18n.__enableEmitter(emitter),emitter.on("*",addTimelineEvent)}},unmounted(){const instance=getCurrentInstance();if(!instance)throw createI18nError(I18nErrorCodes_UNEXPECTED_ERROR);const _vueI18n=this.$i18n;"production"!==process.env.NODE_ENV&&instance.__VUE_I18N__&&(this.__v_emitter&&(this.__v_emitter.off("*",addTimelineEvent),delete this.__v_emitter),_vueI18n&&(_vueI18n.__disableEmitter&&_vueI18n.__disableEmitter(),delete instance.__VUE_I18N__)),_vueI18n&&(delete this.$t,delete this.$rt,delete this.$te,delete this.$d,delete this.$n,delete this.$tm,_vueI18n?.__disposer&&(_vueI18n.__disposer(),delete _vueI18n.__disposer,delete _vueI18n.__extender),i18n2.__deleteInstance(instance),delete this.$i18n)}}}(__global,__global.__composer,i18n2));const unmountApp=app.unmount;if(app.unmount=()=>{globalReleaseHandler&&globalReleaseHandler(),i18n2.dispose(),unmountApp()},"production"!==process.env.NODE_ENV){if(!(await enableDevTools(app,i18n2)))throw createI18nError(I18nErrorCodes_CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);const emitter=createEmitter();if(__legacyMode){const _vueI18n=__global;_vueI18n.__enableEmitter&&_vueI18n.__enableEmitter(emitter)}else{const _composer=__global;_composer[EnableEmitter]&&_composer[EnableEmitter](emitter)}emitter.on("*",addTimelineEvent)}},get global(){return __global},dispose(){globalScope.stop()},__instances:__instances,__getInstance:function(component){return __instances.get(component)||null},__setInstance:function(component,instance){__instances.set(component,instance)},__deleteInstance:function(component){__instances.delete(component)}};return i18n2}({legacy:!1,locale:"zh-CN",fallbackLocale:"zh-CN",messages:messages}),t=(key,...formats)=>{let str=i18n.global.t(key);if(formats.length){let index2=0;str=str.replace(/%s/g,()=>index2<formats.length?formats[index2++]+"":"%s")}return str},locale=computed({set(v2){i18n.global.locale.value=v2},get:()=>i18n.global.locale.value});let gloabalDxfSystem=null;class Log{static preTime=performance.now();static firstTime=performance.now();static clear(){this.preTime=performance.now(),this.firstTime=this.preTime}static timeConsuming(msg=""){const t2=performance.now(),diff=t2-this.preTime;return console.log(msg+" %c time "+parseFloat(diff.toFixed(6))+"ms","color: green;"),this.preTime=t2,diff}static totalTime(msg=""){const t2=performance.now(),diff=t2-this.firstTime;return console.log(msg+" %c totalTime "+parseFloat(diff.toFixed(6))+"ms","color: green;"),this.preTime=t2,diff}}async function createEditor(opt){const{dom:dom,camera:camera,orbitControls:orbitControls=!1,viewPermission:viewPermission,bgTransparent:bgTransparent=!1,language:language}=opt??{},mp=await Promise.resolve().then(()=>index),rp=await import("./index2.js"),editor2=await import("./index3.js");language&&(locale.value=language);const dxfSystem=(new DxfSystem).usePlugin(mp.ModelDataPlugin.create({whiteModel:!0})).usePlugin(rp.RenderPlugin.create({modelData:!1,orbitControls:orbitControls,camera:camera,bgTransparent:bgTransparent})).usePlugin(editor2.EditorPlugin.create({viewPermission:viewPermission})),domContainer=dxfSystem.findComponentByType(rp.components.DomContainer);return domContainer&&dom.appendChild(domContainer.container),gloabalDxfSystem=dxfSystem,{dxfSystem:dxfSystem,getFileAll:()=>getFileAll("closed-loop",dxfSystem)}}async function getModels(originData,trajectory2,itemList){"itemInfo"in itemList&&(itemList=itemList.itemInfo),Array.isArray(itemList)||(itemList=[]);const{lineSegments:lineSegments,originalZAverage:originalZAverage}=originalDataToLineData(originData),lines=BoundExt.boundExtbyTraj({lines:lineSegments,trajectory:trajectory2,updateDoubleWallGroup:!0,wallWidth:DEFAULT_WALL_WIDTH}).lines,sceneAutoGenerat=new SceneAutoGenerat(lines,itemList,originalZAverage,trajectory2);await sceneAutoGenerat.init();const model=sceneAutoGenerat.scene,whiteModel=new WhiteModel;whiteModel.whiteModelGroup.add(model);return{glb:new File([await whiteModel.toGltfBlob(!0)||""],"model.glb",{type:"application/octet-stream"}),gltf:new File([await whiteModel.toGltfBlob(!1)||""],"model.gltf",{type:"application/json"})}}"undefined"!=typeof window&&(window.drawLines=function drawLines(lines,parameters,offset=.001){if(Array.isArray(lines)&&lines[0]instanceof Point){const _lines=lines;lines=[..._lines].map((p2,i)=>{const nextP=_lines[(i+1)%_lines.length];return new LineSegment(p2,nextP)})}if(lines instanceof LineSegment)return drawLines([lines],parameters,offset);const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");if(renderer){if(0===lines.length)return;const obj3d=renderer.createLineSegments(lines,0,parameters,renderer?.container2);return obj3d.position.z=offset,obj3d}}},window.drawPoint=function(point2,parameters,offset=.001){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");if(renderer){const obj3d=renderer.createCircle(point2,parameters,renderer?.container2);return obj3d.position.z=offset,obj3d}}},window.drawText=drawText$1,window.enableRotate=function(b4=!0){const dxfSystem=DxfSystem.finalInstance;if(dxfSystem){const renderer=dxfSystem.findComponentByName("Renderer");renderer&&(renderer.orbitControls.enableRotate=b4)}},window.randomColor=()=>Math.floor(16777215*Math.random()),window.Log=Log,window.TEST=!1),"undefined"!=typeof globalThis&&(globalThis.Log=Log,globalThis.TEST=!1);var DrawingFeature=/* @__PURE__ */(DrawingFeature2=>(DrawingFeature2[DrawingFeature2.RotationCorr=1]="RotationCorr",DrawingFeature2[DrawingFeature2.Dimension=2]="Dimension",DrawingFeature2[DrawingFeature2.BoundExt=4]="BoundExt",DrawingFeature2))(DrawingFeature||{});async function buildJson(opt,dxfSystem=new DxfSystem){const mp=await Promise.resolve().then(()=>index);let{json:json,trajectory:trajectory2,axisAlignCorrOption:axisAlignCorrOption,download:download,itemInfo:itemInfo,doorFind:doorFind=!0,groundBuildMode:groundBuildMode="closed-loop"}=opt;dxfSystem.usePlugin(mp.ModelDataPlugin);const whiteModel=dxfSystem.findComponentByType(mp.components.WhiteModel),threeVJia=dxfSystem.findComponentByName("ThreeVJia"),runJian=dxfSystem.findComponentByName("RunJian"),externalData=dxfSystem.findComponentByName("ExternalData");if(whiteModel.groundBuildMode=groundBuildMode,itemInfo&&"string"==typeof itemInfo){if("undefined"==typeof global)throw new Error("非node环境不允许使用路径");{const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(itemInfo);itemInfo=JSON.parse(buffer.toString("utf-8"))}}if(doorFind&&dxfSystem.Dxf.linePipeline.add(LinePipeline.builtin.DoorFind),!1!==opt.axisAlignCorr&&dxfSystem.Dxf.linePipeline.add(LinePipeline.builtin.AxisAlignCorr).add(LinePipeline.builtin.RemoveShortDoubleWall).add(LinePipeline.builtin.BeamSupportLine).add(LinePipeline.builtin.RemoveRoomSundries),trajectory2&&"string"==typeof trajectory2){if("undefined"==typeof global)throw new Error("非node环境不允许使用路径");{const packageName="fs",{default:fs2}=await import(packageName),buffer=fs2.readFileSync(trajectory2);trajectory2=JSON.parse(buffer.toString("utf-8"))}}await dxfSystem.Dxf.set(json,{wallGroup:!0,...axisAlignCorrOption,publicInfo:itemInfo,trajectory:trajectory2}),download?.json&&await dxfSystem.Dxf.downloadOriginalData(download.json),download?.gltf&&await(whiteModel?.downloadGltf(download.gltf,!1)),download?.glb&&await(whiteModel?.downloadGltf(download.glb)),download?.obj&&await(whiteModel?.downloadOBJ(download.obj));for await(const{files:files,features:features}of opt.download?.cad??[]){let dxfCom=dxfSystem.Dxf;4&features&&(dxfCom=dxfSystem.BoundExtDxf);const list=["cad"];2&features&&list.push("dim"),1&features&&list.push("deg_corr");const mode=toCamelCase(list.reverse().join("_"));for await(const{path:path,type:type}of files)"dxf"===type?await dxfCom.downloadDxf(mode,path):"image"===type&&await dxfCom.downloadDxfImage(mode,path)}return{dxfSystem:dxfSystem,threeVJia:threeVJia,whiteModel:whiteModel,runJian:runJian,externalData:externalData}}async function getFileAll(groundBuildMode="closed-loop",dxfSystem=gloabalDxfSystem){const whiteModel=dxfSystem.findComponentByName("WhiteModel");whiteModel.groundBuildMode=groundBuildMode,whiteModel.regenerateModel();const dxf=new File([dxfSystem.BoundExtDxf.toDxfBlob("dimCad")??""],"dxf.dxf",{type:"application/dxf"}),correctionDxf=new File([dxfSystem.BoundExtDxf.toDxfBlob("degCorrCad")??""],"dxf.dxf",{type:"application/dxf"}),jpg=new File([await dxfSystem.BoundExtDxf.toDxfImageBlob("degCorrDimCad")],"img.jpg",{type:"image/jpeg"}),obj=new File([await whiteModel.toOBJBlob()],"model.obj",{type:"application/octet-stream"}),glb=new File([await whiteModel.toGltfBlob(!0)],"model.glb",{type:"application/octet-stream"}),gltf2=new File([await whiteModel.toGltfBlob(!1)],"model.gltf",{type:"application/json"}),originalData=lineDataToOriginalData(dxfSystem.Dxf.getLineSegments(),dxfSystem.Dxf.originalZAverage);return{dxf:dxf,obj:obj,glb:glb,gltf:gltf2,json:new File([JSON.stringify(originalData)],"json.json",{type:"application/json"}),jpg:jpg,correctionDxf:correctionDxf,dwg:new File([await dxfToDwgByBlob(dxf)],"dwg.dwg",{type:"application/dwg"}),correctionDwg:new File([await dxfToDwgByBlob(correctionDxf)],"dwg.dwg",{type:"application/dwg"})}}function getGlobalDxfSystem(){return gloabalDxfSystem}async function openGlobalDxfSystemPreview(opt){const preview=gloabalDxfSystem?.findComponentByName("Preview"),editorView=gloabalDxfSystem?.findComponentByName("EditorView");preview&&editorView&&(preview.addEventListener("exitPreview",()=>{opt?.callBackFun?.()},{once:!0}),await preview.preview(opt.perspectiveCamera))}async function exitGlobalDxfSystemPreview(){const preview=gloabalDxfSystem?.findComponentByName("Preview");preview&&preview.cancel()}function hasCircle(lineData,startIndex,direction){let lines=originalDataToLineData(lineData).lineSegments;const center=lines[startIndex].center;let findlines=splitIntersectedLine(lines.map(line2=>line2.clone()),1e-9),removeSet=findDiscretePointLine(findlines);findlines=findlines.filter(line2=>!removeSet.has(line2));const list=findlines.filter(line2=>line2.userData.isBayWindow&&line2.isPointOnSegment(center));if(0===list.length)return null;const miniCircles2=new MiniCircles,line=list[0],testPoint=line.center.add(Point.from(direction).multiplyScalar(1e-4));let circle=miniCircles2.miniCircle(findlines,{circleEdges:[line]}).circles.filter(circle2=>Polygon.fromByLines2(circle2).pointWithin(testPoint))[0];if(circle){let indices=lazy(()=>getLineIndexByCenter(circle,findlines).filter(i=>i>-1)),originalDataIndices=lazy(()=>getLineIndexByCenter(circle,lines).filter(i=>i>-1));return{get originalIndices(){return originalDataIndices.value},get indices(){return indices.value},circle:circle,originalLines:lines,lines:findlines}}return null}export{getModels as $,ArrayMap as A,BezierCurveKernel as B,Component as C,DEFAULT_WALL_WIDTH as D,WhiteModel as E,lazy as F,EventDispatcher as G,HeightQuery as H,SelectLocalFile as I,CommandManager as J,DrawingFeature as K,LineSegmentSpatialHash as L,MiniCircles as M,index as N,buildJson as O,PointSpatialHash as P,Quadtree as Q,Rectangle as R,SetMap as S,ThreeVJia as T,createEditor as U,Variable as V,WallGroupManager as W,index$2 as X,exitGlobalDxfSystemPreview as Y,getFileAll as Z,getGlobalDxfSystem as _,Box2 as a,hasCircle as a0,locale as a1,openGlobalDxfSystemPreview as a2,index$3 as a3,LineSegment as b,Point as c,cloneUserData as d,Pipeline as e,WallHole as f,getDefaultExportFromCjs as g,LineSegmentUtils as h,Polygon as i,earcut as j,createPromise as k,mmTom as l,mToMm as m,WH as n,Lines as o,PointUtils as p,LineDashed as q,cubicBezierCurve as r,LineGroupType as s,t,splitCubicBezier as u,uuid as v,clippingLineUserData as w,LinePipeline as x,drawText$1 as y,toTrianglesDrawMode as z};
|