@equinor/esv-intersection 3.0.0-beta.6 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -16
- package/dist/components/axis.d.ts +47 -47
- package/dist/components/index.d.ts +1 -1
- package/dist/constants.d.ts +11 -11
- package/dist/control/ExtendedCurveInterpolator.d.ts +58 -58
- package/dist/control/IntersectionReferenceSystem.d.ts +96 -96
- package/dist/control/LayerManager.d.ts +76 -76
- package/dist/control/MainController.d.ts +154 -154
- package/dist/control/ZoomPanHandler.d.ts +158 -158
- package/dist/control/index.d.ts +5 -5
- package/dist/control/interfaces.d.ts +37 -37
- package/dist/control/overlay.d.ts +20 -20
- package/dist/datautils/colortable.d.ts +1 -1
- package/dist/datautils/findsample.d.ts +2 -2
- package/dist/datautils/index.d.ts +6 -6
- package/dist/datautils/interfaces.d.ts +63 -63
- package/dist/datautils/picks.d.ts +74 -74
- package/dist/datautils/schematicShapeGenerator.d.ts +59 -61
- package/dist/datautils/seismicimage.d.ts +45 -45
- package/dist/datautils/surfacedata.d.ts +10 -10
- package/dist/datautils/trajectory.d.ts +14 -14
- package/dist/index.cjs +15 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.mjs +7944 -0
- package/dist/index.mjs.map +1 -0
- package/dist/index.umd.js +15 -1
- package/dist/index.umd.js.map +1 -0
- package/dist/interfaces.d.ts +86 -86
- package/dist/layers/CalloutCanvasLayer.d.ts +60 -60
- package/dist/layers/CustomDisplayObjects/ComplexRope.d.ts +22 -22
- package/dist/layers/CustomDisplayObjects/ComplexRopeGeometry.d.ts +27 -27
- package/dist/layers/CustomDisplayObjects/FixedWidthSimpleRope.d.ts +20 -20
- package/dist/layers/CustomDisplayObjects/FixedWidthSimpleRopeGeometry.d.ts +26 -26
- package/dist/layers/CustomDisplayObjects/UniformTextureStretchRope.d.ts +17 -17
- package/dist/layers/CustomDisplayObjects/UniformTextureStretchRopeGeometry.d.ts +24 -24
- package/dist/layers/GeomodelCanvasLayer.d.ts +28 -28
- package/dist/layers/GeomodelLabelsLayer.d.ts +49 -49
- package/dist/layers/GeomodelLayerV2.d.ts +12 -12
- package/dist/layers/GridLayer.d.ts +29 -29
- package/dist/layers/ImageCanvasLayer.d.ts +20 -20
- package/dist/layers/ReferenceLineLayer.d.ts +29 -29
- package/dist/layers/SchematicLayer.d.ts +113 -114
- package/dist/layers/SeismicCanvasLayer.d.ts +18 -18
- package/dist/layers/WellborePathLayer.d.ts +17 -17
- package/dist/layers/base/CanvasLayer.d.ts +19 -19
- package/dist/layers/base/HTMLLayer.d.ts +13 -13
- package/dist/layers/base/Layer.d.ts +69 -69
- package/dist/layers/base/PixiLayer.d.ts +32 -32
- package/dist/layers/base/SVGLayer.d.ts +13 -13
- package/dist/layers/base/index.d.ts +5 -5
- package/dist/layers/index.d.ts +16 -16
- package/dist/layers/schematicInterfaces.d.ts +208 -208
- package/dist/tubing1.svg +3 -0
- package/dist/tubing2.svg +6 -0
- package/dist/tubing3.svg +12 -0
- package/dist/utils/arc-length.d.ts +23 -23
- package/dist/utils/binary-search.d.ts +8 -8
- package/dist/utils/color.d.ts +5 -5
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/root-finder.d.ts +34 -34
- package/dist/utils/text.d.ts +14 -14
- package/dist/utils/vectorUtils.d.ts +15 -15
- package/dist/vendor/pixi-dashed-line/index.d.ts +57 -0
- package/package.json +30 -55
- package/src/datautils/schematicShapeGenerator.ts +2 -8
- package/src/layers/SchematicLayer.ts +12 -37
- package/src/layers/base/PixiLayer.ts +4 -4
- package/src/vendor/pixi-dashed-line/index.ts +394 -0
- package/dist/datautils/camelcase.d.ts +0 -5
- package/dist/index.esm.js +0 -1
- package/dist/index.js +0 -1
- package/src/datautils/camelcase.ts +0 -28
package/dist/index.esm.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{axisRight,axisBottom}from"d3-axis";import{scaleLinear,scaleOrdinal}from"d3-scale";import Vector2 from"@equinor/videx-vector2";import{clamp,radians,seqI}from"@equinor/videx-math";import{CurveInterpolator,normalize}from"curve-interpolator";import{select,pointer}from"d3-selection";import{zoom,zoomIdentity}from"d3-zoom";import{Renderer,RENDERER_TYPE,autoDetectRenderer,Container,Graphics,Point,Texture,WRAP_MODES,Rectangle,groupD8,MeshGeometry,Mesh,MeshMaterial,SimpleRope}from"pixi.js";import{color}from"d3-color";import{quantize,interpolateRgb}from"d3-interpolate";import{max,sum}from"d3-array";import{DashLine}from"pixi-dashed-line";import{curveCardinal,curveBundle,curveCatmullRom,line,curveStepBefore,curveStepAfter,curveStep,curveNatural,curveMonotoneY,curveMonotoneX,curveBasisClosed,curveBasis,curveLinear}from"d3-shape";var Axis=function(){function Axis(mainGroup,showLabels,labelXDesc,labelYDesc,unitOfMeasure,options){void 0===showLabels&&(showLabels=!0);var _this=this;this._showLabels=!0,this._offsetX=0,this._offsetY=0,this._flipX=!1,this._flipY=!1,this.visible=!0,this.createOrGet=function(name){var mainGroup=_this.mainGroup,res=mainGroup.select("g.".concat(name));return res.empty()&&(res=mainGroup.append("g").attr("class",name)),res},this.mainGroup=mainGroup,this._showLabels=showLabels,this._labelXDesc=labelXDesc,this._labelYDesc=labelYDesc,this._unitOfMeasure=unitOfMeasure,options&&options.offsetX&&(this._offsetX=options.offsetX),options&&options.offsetX&&(this._offsetY=options.offsetY),options&&options.visible&&(this.visible=options.visible),this.mainGroup.style("pointer-events","none"),this._scaleX=scaleLinear().domain([0,1]).range([0,1]),this._scaleY=scaleLinear().domain([0,1]).range([0,1])}return Axis.prototype.renderLabelx=function(){var labelXDesc=this._labelXDesc,unitOfMeasure=this._unitOfMeasure,_showLabels=this._showLabels,width=this._scaleX.range()[1],gx=this.renderGx(),labelx=gx.select("text.axis-labelx");return _showLabels?labelx.empty()&&(labelx=gx.append("text").attr("class","axis-labelx").attr("fill","rgba(0,0,0,0.3)").style("text-anchor","middle").style("font-weight","800").style("font-size","10px").text("".concat(labelXDesc," (").concat(unitOfMeasure,")"))):labelx.remove(),labelx.attr("transform","translate(".concat(width/2,",-4)")),labelx},Axis.prototype.renderLabely=function(){var labelYDesc=this._labelYDesc,unitOfMeasure=this._unitOfMeasure,_showLabels=this._showLabels,height=this._scaleY.range()[1],gy=this.renderGy(),labely=gy.select("text.axis-labely");return _showLabels?(labely.empty()&&(labely=gy.append("text").attr("class","axis-labely").attr("fill","rgba(0,0,0,0.3)").style("text-anchor","middle").style("font-weight","800").style("font-size","10px").text("".concat(labelYDesc," (").concat(unitOfMeasure,")"))),labely.attr("transform","translate(-10,".concat(height/2,")rotate(90)"))):labely.remove(),labely},Axis.prototype.renderGy=function(){var _scaleX=this._scaleX,_scaleY=this._scaleY,yAxis=axisRight(_scaleY),width=_scaleX.range()[1],gy=this.createOrGet("y-axis");return gy.call(yAxis),gy.attr("transform","translate(".concat(width,",0)")),gy},Axis.prototype.renderGx=function(){var _scaleX=this._scaleX,_scaleY=this._scaleY,xAxis=axisBottom(_scaleX),height=_scaleY.range()[1],gx=this.createOrGet("x-axis");return gx.attr("transform","translate(0 ".concat(height,")")),gx.call(xAxis),gx},Axis.prototype.render=function(){this.renderLabelx(),this.renderLabely()},Axis.prototype.onResize=function(event){this.mainGroup.attr("height","".concat(event.height,"px")).attr("width","".concat(event.width,"px"))},Axis.prototype.onRescale=function(event){var _scaleX=this._scaleX,_scaleY=this._scaleY,offsetX=this.offsetX,offsetY=this.offsetY,xScale=event.xScale,yScale=event.yScale,xBounds=xScale.domain(),yBounds=yScale.domain(),xRange=xScale.range(),yRange=yScale.range();_scaleX.domain([xBounds[0]-offsetX,xBounds[1]-offsetX]).range(xRange),_scaleY.domain([yBounds[0]-offsetY,yBounds[1]-offsetY]).range(yRange),this.flipX(this._flipX),this.flipY(this._flipY),this.visible&&this.render()},Axis.prototype.show=function(){return this.visible=!0,this.mainGroup.attr("visibility","visible"),this.render(),this},Axis.prototype.hide=function(){return this.visible=!1,this.mainGroup.attr("visibility","hidden"),this},Axis.prototype.flipX=function(flipX){this._flipX=flipX;var domain=this._scaleX.domain(),flip=flipX?-1:1;return this._scaleX.domain([flip*domain[0],flip*domain[1]]),this},Axis.prototype.flipY=function(flipY){this._flipY=flipY;var domain=this._scaleY.domain(),flip=flipY?-1:1;return this._scaleY.domain([flip*domain[0],flip*domain[1]]),this},Axis.prototype.showLabels=function(){return this._showLabels=!0,this.render(),this},Axis.prototype.hideLabels=function(){return this._showLabels=!1,this.render(),this},Axis.prototype.setLabelX=function(label){return this._labelXDesc=label,this},Axis.prototype.setLabelY=function(label){return this._labelYDesc=label,this},Axis.prototype.setUnitOfMeasure=function(uom){return this._unitOfMeasure=uom,this},Axis.prototype.setLabels=function(labelX,labelY,unitOfMeasure){return this._labelXDesc=labelX,this._labelYDesc=labelY,this._unitOfMeasure=unitOfMeasure,this},Object.defineProperty(Axis.prototype,"offsetX",{get:function(){return this._offsetX},set:function(offset){this._offsetX=offset},enumerable:!1,configurable:!0}),Object.defineProperty(Axis.prototype,"offsetY",{get:function(){return this._offsetY},set:function(offset){this._offsetY=offset},enumerable:!1,configurable:!0}),Object.defineProperty(Axis.prototype,"scaleX",{get:function(){return this._scaleX.copy()},enumerable:!1,configurable:!0}),Object.defineProperty(Axis.prototype,"scaleY",{get:function(){return this._scaleY.copy()},enumerable:!1,configurable:!0}),Axis}(),extendStatics=function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)Object.prototype.hasOwnProperty.call(b,p)&&(d[p]=b[p])},extendStatics(d,b)};function __extends(d,b){if("function"!=typeof b&&null!==b)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function __(){this.constructor=d}extendStatics(d,b),d.prototype=null===b?Object.create(b):(__.prototype=b.prototype,new __)}var __assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__assign.apply(this,arguments)};function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))}function __generator(thisArg,body){var f,y,t,g,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return g={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=_.trys,(t=t.length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}function __spreadArray(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))}var RootFinder=function(){function RootFinder(){}return RootFinder.newton=function(func,precision,maxIterations,start,minLimit,maxLimit){void 0===precision&&(precision=.01),void 0===maxIterations&&(maxIterations=1e3),void 0===start&&(start=.5),void 0===minLimit&&(minLimit=0),void 0===maxLimit&&(maxLimit=1);for(var h=1e-4,t=start,i=0;i<maxIterations;i++){var v=func(t);if(Math.abs(v)<precision)return clamp(t,minLimit,maxLimit);t-=v/((func(t+h)-v)/h)}return null},RootFinder.bisect=function(func,precision,maxIterations,start,minLimit,maxLimit){void 0===precision&&(precision=.01),void 0===maxIterations&&(maxIterations=1e3),void 0===start&&(start=.5),void 0===minLimit&&(minLimit=0),void 0===maxLimit&&(maxLimit=1);var v,i,tl=minLimit,th=maxLimit,t=start;for(i=0;i<maxIterations;i++){if(v=func(t),Math.abs(v)<precision)return t;v<0?th=t:tl=t,t=(th+tl)/2}return t},RootFinder.findRoot=function(func,precision,maxIterations,start,minLimit,maxLimit){void 0===precision&&(precision=.01),void 0===maxIterations&&(maxIterations=1e3),void 0===start&&(start=.5),void 0===minLimit&&(minLimit=0),void 0===maxLimit&&(maxLimit=1);var t=RootFinder.newton(func,precision,maxIterations,start);return null==t&&(t=RootFinder.bisect(func,precision,maxIterations,start,minLimit,maxLimit)),t},RootFinder}(),ArcLength=function(){function ArcLength(){}return ArcLength.bisect=function(func,minLimit,maxLimit,tolerance,minDepth,maxDepth){void 0===minLimit&&(minLimit=0),void 0===maxLimit&&(maxLimit=1),void 0===tolerance&&(tolerance=.005),void 0===minDepth&&(minDepth=4),void 0===maxDepth&&(maxDepth=10);var calcRec=function(a,b,aVal,bVal,span,tolerance,depth){void 0===depth&&(depth=0);var mid=(a+b)/2,midVal=func(mid),spanA=Vector2.distance(aVal,midVal),spanB=Vector2.distance(midVal,bVal),length=spanA+spanB;if(depth>=minDepth&&Math.abs(length-span)<tolerance||depth>=maxDepth)return length;var tol=tolerance/2,d=depth+1;return calcRec(a,mid,aVal,midVal,spanA,tol,d)+calcRec(mid,b,midVal,bVal,spanB,tol,d)},aVal=func(minLimit),bVal=func(maxLimit),span=Vector2.distance(aVal,bVal);return calcRec(minLimit,maxLimit,aVal,bVal,span,tolerance)},ArcLength.trapezoid=function(func,minLimit,maxLimit,segments){void 0===minLimit&&(minLimit=0),void 0===maxLimit&&(maxLimit=1),void 0===segments&&(segments=1e3);for(var length=0,lastPos=func(minLimit),step=(maxLimit-minLimit)/(segments-1),i=1;i<segments;i++){var pos=func(minLimit+i*step);length+=Vector2.distance(lastPos,pos),lastPos=pos}return length},ArcLength}(),BinarySearch=function(){function BinarySearch(){}return BinarySearch.search=function(values,searchValue){for(var il=0,ih=values.length-1,i=Math.floor(il+ih/2);i>il&&i<ih;){var v=values[i],v1=values[i+1];if(v<=searchValue&&v1>=searchValue)return i;searchValue<v?ih=i:il=i,i=Math.floor(il+ih/2)}return i},BinarySearch}(),ExtendedCurveInterpolator=function(_super){function ExtendedCurveInterpolator(points,options){var _this=_super.call(this,points,options)||this;return _this.arcLengthLookup=[],_this.findTForArcLength=_this.findTForArcLength.bind(_this),_this.findTByRootForArcLength=_this.findTByRootForArcLength.bind(_this),_this.findApproxTForArcLength=_this.findApproxTForArcLength.bind(_this),_this.findTQuickForArcLength=_this.findTQuickForArcLength.bind(_this),_this.generateArcLengthLookup=_this.generateArcLengthLookup.bind(_this),_this.getArcLength=_this.getArcLength.bind(_this),_this.getQuickArcLength=_this.getQuickArcLength.bind(_this),_this.getPointAtArcLength=_this.getPointAtArcLength.bind(_this),_this.getPointAt=_this.getPointAt.bind(_this),_this}return __extends(ExtendedCurveInterpolator,_super),ExtendedCurveInterpolator.prototype.findTForArcLength=function(arcLength,options){return(null==options?void 0:options.approxT)?this.findApproxTForArcLength(arcLength,null==options?void 0:options.normalizedLength):(null==options?void 0:options.quickT)?this.findTQuickForArcLength(arcLength):this.findTByRootForArcLength(arcLength)},ExtendedCurveInterpolator.prototype.findTByRootForArcLength=function(arcLength,tolerance,iterations){var _this=this;return void 0===tolerance&&(tolerance=.01),void 0===iterations&&(iterations=100),arcLength<=0?0:arcLength>=this.length?1:RootFinder.findRoot((function(x){return arcLength-_this.getQuickArcLength(0,x)}),tolerance,iterations,arcLength/this.length)},ExtendedCurveInterpolator.prototype.findApproxTForArcLength=function(arcLength,normalizedLength){return arcLength/(normalizedLength||this.length)},ExtendedCurveInterpolator.prototype.findTQuickForArcLength=function(arcLength){0===this.arcLengthLookup.length&&this.generateArcLengthLookup();var index=BinarySearch.search(this.arcLengthLookup,arcLength),v1=this.arcLengthLookup[index];return(index+(arcLength-v1)/(this.arcLengthLookup[index+1]-v1))/this.arcLengthLookup.length},ExtendedCurveInterpolator.prototype.generateArcLengthLookup=function(segments){void 0===segments&&(segments=1e3);for(var lastPos=this.getPointAt(0),length=0,i=0;i<segments;i++){var pos=this.getPointAt(i/(segments-1));length+=Vector2.distance(lastPos,pos),this.arcLengthLookup.push(length),lastPos=pos}},ExtendedCurveInterpolator.prototype.getArcLength=function(from,to){var _this=this;if(void 0===from&&(from=0),void 0===to&&(to=1),0===from&&1===to)return this.length;return ArcLength.bisect((function(t){return _this.getPointAt(t)}),from,to,.002)},ExtendedCurveInterpolator.prototype.getQuickArcLength=function(from,to){void 0===from&&(from=0),void 0===to&&(to=1);var fromLength=0,toLength=this.length;if(0===this.arcLengthLookup.length&&this.generateArcLengthLookup(),0!==from){var fromIndex=Math.floor(from*this.arcLengthLookup.length),fromLl=this.arcLengthLookup[fromIndex],fromLh=this.arcLengthLookup[fromIndex+1];fromLength=fromLl+from*this.arcLengthLookup.length%this.arcLengthLookup.length*(fromLh-fromLl)}if(1!==to){var toIndex=Math.floor(to*this.arcLengthLookup.length),toLl=this.arcLengthLookup[toIndex],toLh=this.arcLengthLookup[toIndex+1];toLength=toLl+from*this.arcLengthLookup.length%this.arcLengthLookup.length*(toLh-toLl)}return toLength-fromLength},ExtendedCurveInterpolator.prototype.getPointAtArcLength=function(arcLength,options){var t=this.findTForArcLength(arcLength,options);return this.getPointAt(t)},ExtendedCurveInterpolator.prototype.getPointAt=function(t){var tl=clamp(t,0,1);return _super.prototype.getPointAt.call(this,tl)},ExtendedCurveInterpolator}(CurveInterpolator),defaultOptions$2={approxT:!0},IntersectionReferenceSystem=function(){function IntersectionReferenceSystem(path,options){if(this.path=[],this.projectedPath=[],this._offset=0,path.length<1)throw new Error("Missing coordinates");if(path[0]&&3!==path[0].length)throw new Error("Coordinates should be in 3d");this.setPath(path,options),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.getPosition=this.getPosition.bind(this),this.getProjectedLength=this.getProjectedLength.bind(this),this.getTrajectory=this.getTrajectory.bind(this)}return IntersectionReferenceSystem.prototype.setPath=function(path,options){void 0===options&&(options={}),this.options=__assign(__assign({},defaultOptions$2),options);var _a=this.options,arcDivisions=_a.arcDivisions,tension=_a.tension,calculateDisplacementFromBottom=_a.calculateDisplacementFromBottom;this.path=path,this.projectedPath=IntersectionReferenceSystem.toDisplacement(path);var displacement=this.projectedPath[this.projectedPath.length-1][0];this.displacement=displacement,this.interpolators={curve:options.curveInterpolator||new ExtendedCurveInterpolator(path),trajectory:options.trajectoryInterpolator||new ExtendedCurveInterpolator(path.map((function(d){return[d[0],d[1]]})),{tension:tension||.75,arcDivisions:arcDivisions||5e3}),curtain:options.curtainInterpolator||new ExtendedCurveInterpolator(this.projectedPath,{tension:tension||.75,arcDivisions:arcDivisions||5e3})};var trajVector=this.getTrajectoryVector(),negativeTrajVector=trajVector.map((function(d){return-1*d}));calculateDisplacementFromBottom?(this.endVector=negativeTrajVector,this.startVector=trajVector):(this.endVector=trajVector,this.startVector=negativeTrajVector),this._curtainPathCache=void 0},IntersectionReferenceSystem.prototype.project=function(length){var curtain=this.interpolators.curtain,calculateDisplacementFromBottom=this.options.calculateDisplacementFromBottom,cl=clamp(calculateDisplacementFromBottom?this.length-(length-this._offset):length-this._offset,0,this.length);return curtain.getPointAtArcLength(cl,this.options)},IntersectionReferenceSystem.prototype.curtainTangent=function(length){var curtain=this.interpolators.curtain,l=length-this._offset,t=curtain.findTForArcLength(l,this.options);return t&&curtain.getTangentAt(t)},IntersectionReferenceSystem.prototype.getCurtainPath=function(startMd,endMd,includeStartEnd){if(void 0===includeStartEnd&&(includeStartEnd=!1),!this._curtainPathCache){for(var points=[],prevAngle=2*Math.PI,i=this._offset;i<=this.length+this._offset;i+=.1){var point=this.project(i),angle=Math.atan2(point[1],point[0]);Math.abs(angle-prevAngle)>5e-4&&(points.push({point:point,md:i}),prevAngle=angle)}this._curtainPathCache=points}if(includeStartEnd){var startPoint={point:this.project(startMd),md:startMd},pointsBetween=this._curtainPathCache.filter((function(p){return p.md>startMd&&p.md<endMd})),endPoint={point:this.project(endMd),md:endMd};return __spreadArray(__spreadArray([startPoint],pointsBetween,!0),[endPoint],!1)}return this._curtainPathCache.filter((function(p){return p.md>=startMd&&p.md<=endMd}))},IntersectionReferenceSystem.prototype.unproject=function(displacement){var _a=this.options,normalizedLength=_a.normalizedLength,displacementFromStart=_a.calculateDisplacementFromBottom?this.displacement-displacement:displacement,length=normalizedLength||this.length;if(displacementFromStart<0)return displacementFromStart;if(displacementFromStart>this.displacement)return length+(displacementFromStart-this.displacement);var ls=this.interpolators.curtain.lookupPositions(displacementFromStart,0,1);return ls&&ls.length?ls[0]*length+this._offset:null},IntersectionReferenceSystem.prototype.getProjectedLength=function(length){var curtain=this.interpolators.curtain,l=this.project(length)[0]/curtain.maxX;return Number.isFinite(l)?clamp(l,0,1):0},IntersectionReferenceSystem.prototype.getPosition=function(length){var trajectory=this.interpolators.trajectory,t=this.getProjectedLength(length);return trajectory.getPointAt(t)},IntersectionReferenceSystem.prototype.getTrajectory=function(steps,from,to){void 0===from&&(from=0),void 0===to&&(to=1);var p0,p3,extensionStart=from<0?-from:0,extensionEnd=to>1?to-1:0,refStart=this.interpolators.trajectory.getPointAt(0),refEnd=this.interpolators.trajectory.getPointAt(1),offset=0,t0=Math.max(0,from),t1=Math.min(1,to),p1=this.interpolators.trajectory.getPointAt(t0),p2=this.interpolators.trajectory.getPointAt(t1);extensionStart?(p0=[refStart[0]+this.startVector[0]*extensionStart*this.displacement,refStart[1]+this.startVector[1]*extensionStart*this.displacement],offset=-Vector2.distance(p0,refStart)):from>0&&(offset=Vector2.distance(p1,refStart)),extensionEnd&&(p3=[refEnd[0]+this.endVector[0]*extensionEnd*this.displacement,refEnd[1]+this.endVector[1]*extensionEnd*this.displacement]);var points=[],tl=to-from,preSteps=Math.floor(extensionStart/tl*steps),curveSteps=Math.ceil((t1-t0)/tl*steps),postSteps=steps-curveSteps-preSteps;if(p0){points.push(p0);for(var i=1;i<preSteps;i++){var f=i/preSteps*extensionStart*this.displacement;points.push([p0[0]-this.startVector[0]*f,p0[1]-this.startVector[1]*f])}}var curvePoints=this.interpolators.trajectory.getPoints(curveSteps-1,null,t0,t1);if(points.push.apply(points,curvePoints),p3){for(i=1;i<postSteps-1;i++){f=i/postSteps*extensionEnd*this.displacement;points.push([p2[0]+this.endVector[0]*f,p2[1]+this.endVector[1]*f])}points.push(p3)}return{points:points,offset:offset}},IntersectionReferenceSystem.prototype.getExtendedTrajectory=function(numPoints,startExtensionLength,endExtensionLength){if(void 0===startExtensionLength&&(startExtensionLength=1e3),void 0===endExtensionLength&&(endExtensionLength=1e3),!isFinite(startExtensionLength)||startExtensionLength<0)throw new Error("Invalid parameter, getExtendedTrajectory() must be called with a valid and positive startExtensionLength parameter");if(!isFinite(endExtensionLength)||endExtensionLength<0)throw new Error("Invalid parameter, getExtendedTrajectory() must be called with a valid and positive endExtensionLength parameter");for(var totalLength=this.displacement+startExtensionLength+endExtensionLength,startExtensionNumPoints=Math.floor(startExtensionLength/totalLength*numPoints),curveSteps=Math.max(Math.ceil(this.displacement/totalLength*numPoints),1),endExtensionNumPoints=numPoints-curveSteps-startExtensionNumPoints,points=[],refStart=new Vector2(this.interpolators.trajectory.getPointAt(0)),startVec=new Vector2(this.startVector),startExtensionStepLength=startExtensionLength/startExtensionNumPoints,i=startExtensionNumPoints;i>0;i--){var f=i*startExtensionStepLength,point=refStart.add(startVec.scale(f));points.push(point.toArray())}var curveStepPoints=this.interpolators.trajectory.getPoints(curveSteps,null,0,1);points.push.apply(points,curveStepPoints);var refEnd=new Vector2(this.interpolators.trajectory.getPointAt(1)),endVec=new Vector2(this.endVector),endExtensionStepLength=endExtensionLength/(endExtensionNumPoints-1);for(i=1;i<endExtensionNumPoints;i++){f=i*endExtensionStepLength,point=refEnd.add(endVec.scale(f));points.push(point.toArray())}return{points:points,offset:-startExtensionLength}},IntersectionReferenceSystem.prototype.getTrajectoryVector=function(){var _a=this.options,trajectoryAngle=_a.trajectoryAngle,calculateDisplacementFromBottom=_a.calculateDisplacementFromBottom;if(isFinite(trajectoryAngle)){var angleInRad=radians(trajectoryAngle);return new Vector2(Math.cos(angleInRad),Math.sin(angleInRad)).toArray()}return IntersectionReferenceSystem.getDirectionVector(this.interpolators.trajectory,calculateDisplacementFromBottom?.001:.999,calculateDisplacementFromBottom?0:1)},IntersectionReferenceSystem.toDisplacement=function(points,offset){void 0===offset&&(offset=0);var p0=points[0],l=0;return points.map((function(p1){var dx=p1[0]-p0[0],dy=p1[1]-p0[1];return l+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2)),p0=p1,[offset>0?offset-l:l,p1[2]||0]}))},IntersectionReferenceSystem.getDirectionVector=function(interpolator,from,to){var p1=interpolator.getPointAt(to),p2=interpolator.getPointAt(from);return normalize([p1[0]-p2[0],p1[1]-p2[1]])},Object.defineProperty(IntersectionReferenceSystem.prototype,"length",{get:function(){return this.interpolators.curve.length},enumerable:!1,configurable:!0}),Object.defineProperty(IntersectionReferenceSystem.prototype,"offset",{get:function(){return this._offset},set:function(offset){this._curtainPathCache=void 0,this._offset=offset},enumerable:!1,configurable:!0}),IntersectionReferenceSystem}(),ZoomPanHandler=function(){function ZoomPanHandler(elm,onRescale,options){void 0===options&&(options={maxZoomLevel:256,minZoomLevel:.1}),this.zoom=null,this.elm=null,this.container=null,this.onRescale=null,this.options=null,this.xBounds=[0,1],this.yBounds=[0,1],this.translateBoundsX=[0,1],this.translateBoundsY=[0,1],this.scaleX=null,this.scaleY=null,this._zFactor=1,this.container=select(elm),this.options=options,this.onRescale=onRescale,this.onZoom=this.onZoom.bind(this),this.calculateTransform=this.calculateTransform.bind(this),this.applyTransform=this.applyTransform.bind(this),this.recalculateZoomTransform=this.recalculateZoomTransform.bind(this),this.rescale=this.rescale.bind(this),this.adjustToSize=this.adjustToSize.bind(this),this.setViewport=this.setViewport.bind(this),this.currentStateAsEvent=this.currentStateAsEvent.bind(this),this.updateTranslateExtent=this.updateTranslateExtent.bind(this),this.scaleX=scaleLinear().domain(this.xBounds).range([0,1]),this.scaleY=scaleLinear().domain(this.yBounds).range([0,1]),this.init()}return Object.defineProperty(ZoomPanHandler.prototype,"width",{get:function(){return this.scaleX.range()[1]},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"height",{get:function(){return this.scaleY.range()[1]},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"xSpan",{get:function(){var xBounds=this.xBounds;return Math.abs(xBounds[1]-xBounds[0])},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"ySpan",{get:function(){var yBounds=this.yBounds;return Math.abs(yBounds[1]-yBounds[0])},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"viewportRatio",{get:function(){return this.width/(this.height||1)},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"xRatio",{get:function(){var domain=this.scaleX.domain();return Math.abs(this.width/(domain[1]-domain[0]))},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"yRatio",{get:function(){var domain=this.scaleY.domain();return Math.abs(this.height/(domain[1]-domain[0]))},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"zFactor",{get:function(){return this._zFactor},set:function(factor){this._zFactor=factor,this.recalculateZoomTransform()},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"isXInverted",{get:function(){return this.xBounds[1]<this.xBounds[0]},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"isYInverted",{get:function(){return this.yBounds[1]<this.yBounds[0]},enumerable:!1,configurable:!0}),Object.defineProperty(ZoomPanHandler.prototype,"enableTranslateExtent",{get:function(){return this._enableTranslateExtent},set:function(enabled){this._enableTranslateExtent=enabled,this.updateTranslateExtent()},enumerable:!1,configurable:!0}),ZoomPanHandler.prototype.updateTranslateExtent=function(){var _a=this,width=_a.width,xSpan=_a.xSpan,zFactor=_a.zFactor,enableTranslateExtent=_a.enableTranslateExtent,translateBoundsX=_a.translateBoundsX,translateBoundsY=_a.translateBoundsY,x1=-1/0,y1=-1/0,x2=1/0,y2=1/0;if(enableTranslateExtent){var ppu=width/xSpan;x1=translateBoundsX[0]*ppu,x2=translateBoundsX[1]*ppu,y1=translateBoundsY[0]*ppu*zFactor,y2=translateBoundsY[1]*ppu*zFactor}this.zoom.translateExtent([[x1,y1],[x2,y2]])},ZoomPanHandler.prototype.currentStateAsEvent=function(){var _a=this,scaleX=_a.scaleX,scaleY=_a.scaleY,xBounds=_a.xBounds,yBounds=_a.yBounds,zFactor=_a.zFactor,viewportRatio=_a.viewportRatio,currentTransform=_a.currentTransform,xRatio=_a.xRatio,yRatio=_a.yRatio,width=_a.width,height=_a.height;return{xScale:scaleX.copy(),yScale:scaleY.copy(),xBounds:xBounds,yBounds:yBounds,zFactor:zFactor,viewportRatio:viewportRatio,xRatio:xRatio,yRatio:yRatio,width:width,height:height,transform:Object.assign({},currentTransform)}},ZoomPanHandler.prototype.rescale=function(){var currentStateAsEvent=this.currentStateAsEvent;this.onRescale(currentStateAsEvent())},ZoomPanHandler.prototype.init=function(){this.zoom=zoom().scaleExtent([this.options.minZoomLevel,this.options.maxZoomLevel]).on("zoom",this.onZoom),this.container.call(this.zoom)},ZoomPanHandler.prototype.onZoom=function(event){var transform=event.transform;transform&&(this.applyTransform(transform),this.rescale())},ZoomPanHandler.prototype.applyTransform=function(transform){var _a=this,width=_a.width,scaleX=_a.scaleX,scaleY=_a.scaleY,xSpan=_a.xSpan,xBounds=_a.xBounds,yBounds=_a.yBounds,zFactor=_a.zFactor,ratio=this.viewportRatio,isXInverted=this.isXInverted,isYInverted=this.isYInverted,unitsPerPixels=xSpan/(width*transform.k),newXSpan=xSpan/transform.k,newYSpan=newXSpan/zFactor/ratio,shiftx=unitsPerPixels*transform.x,shifty=unitsPerPixels/zFactor*transform.y,dx0=xBounds[0]-(isXInverted?-shiftx:shiftx),dy0=yBounds[0]-(isYInverted?-shifty:shifty);scaleX.domain([dx0,dx0+(isXInverted?-newXSpan:newXSpan)]),scaleY.domain([dy0,dy0+(isYInverted?-newYSpan:newYSpan)]),this.currentTransform=transform},ZoomPanHandler.prototype.setViewport=function(cx,cy,displ,duration){var _a=this,zoom=_a.zoom,container=_a.container,calculateTransform=_a.calculateTransform,scaleX=_a.scaleX,scaleY=_a.scaleY,isXInverted=_a.isXInverted;if(isNaN(cx)||isNaN(displ)){var xd=scaleX.domain(),dspan=xd[1]-xd[0];isNaN(cx)&&(cx=xd[0]+dspan/2||0),isNaN(displ)&&(displ=Math.abs(dspan)||1)}if(isNaN(cy)){var yd=scaleY.domain();cy=yd[0]+(yd[1]-yd[0])/2||0}var xdispl=isXInverted?-displ:displ,dx0=cx-xdispl/2,t=calculateTransform(dx0,dx0+xdispl,cy);Number.isFinite(duration)&&duration>0?zoom.transform(container.transition().duration(duration),t):zoom.transform(container,t)},ZoomPanHandler.prototype.setBounds=function(xBounds,yBounds){this.xBounds=xBounds,this.yBounds=yBounds,this.recalculateZoomTransform()},ZoomPanHandler.prototype.setTranslateBounds=function(xBounds,yBounds){this.translateBoundsX=xBounds,this.translateBoundsY=yBounds,this.updateTranslateExtent()},ZoomPanHandler.prototype.adjustToSize=function(width,height,force){void 0===force&&(force=!1);var _a=this,oldWidth=_a.width,oldHeight=_a.height,scaleX=_a.scaleX,scaleY=_a.scaleY,recalculateZoomTransform=_a.recalculateZoomTransform,w=0,h=0;if(void 0===width||"boolean"==typeof width){var _b=this.container.node().getBoundingClientRect();w=_b.width,h=_b.height}else w=width,h=height;var newWidth=Math.max(1,w),newHeight=Math.max(1,h);(force||oldWidth!==newWidth||oldHeight!==newHeight)&&(scaleX.range([0,newWidth]),scaleY.range([0,newHeight]),recalculateZoomTransform(),this.onRescale(this.currentStateAsEvent()))},ZoomPanHandler.prototype.calculateTransform=function(dx0,dx1,dy){var _a=this,scaleX=_a.scaleX,xSpan=_a.xSpan,xBounds=_a.xBounds,yBounds=_a.yBounds,zFactor=_a.zFactor,ratio=_a.viewportRatio,isXInverted=_a.isXInverted,isYInverted=_a.isYInverted,_b=scaleX.range(),rx1=_b[0],rx2=_b[1],displ=Math.abs(dx1-dx0),k=xSpan/displ,unitsPerPixels=displ/(rx2-rx1),dy0=dy-(isYInverted?-displ:displ)/zFactor/ratio/2,tx=(xBounds[0]-dx0)/(isXInverted?-unitsPerPixels:unitsPerPixels),ty=(yBounds[0]-dy0)/((isYInverted?-unitsPerPixels:unitsPerPixels)/zFactor);return zoomIdentity.translate(tx,ty).scale(k)},ZoomPanHandler.prototype.recalculateZoomTransform=function(){var _a=this,scaleX=_a.scaleX,scaleY=_a.scaleY,container=_a.container,calculateTransform=_a.calculateTransform,updateTranslateExtent=_a.updateTranslateExtent,_b=scaleX.domain(),dx0=_b[0],dx1=_b[1],_c=scaleY.domain(),dy0=_c[0],transform=calculateTransform(dx0,dx1,dy0+(_c[1]-dy0)/2);updateTranslateExtent(),this.zoom.transform(container,transform)},ZoomPanHandler.prototype.setZoomLevelBoundary=function(zoomlevels){return this.zoom.scaleExtent(zoomlevels),this},ZoomPanHandler.prototype.setMaxZoomLevel=function(zoomlevel){var zoomLevels=this.zoom.scaleExtent();return this.zoom.scaleExtent([zoomLevels[0],zoomlevel]),this},ZoomPanHandler.prototype.setMinZoomLevel=function(zoomlevel){var zoomLevels=this.zoom.scaleExtent();return this.zoom.scaleExtent([zoomlevel,zoomLevels[1]]),this},ZoomPanHandler}(),defaultOptions$1={order:1,layerOpacity:1,interactive:!1},Layer=function(){function Layer(id,options){this._referenceSystem=null,this._interactive=!1,this._id=id||"layer-".concat(Math.floor(1e3*Math.random()));var opts=options||defaultOptions$1;this._order=opts.order||1,this._options=__assign({},opts),this.loading=!1,this._element=null,this._opacity=opts.layerOpacity||1,this._visible=!0,this._interactive=opts.interactive||!1,options&&options.data&&this.setData(options.data),this._referenceSystem=options&&options.referenceSystem,this.onMount=this.onMount.bind(this),this.onUnmount=this.onUnmount.bind(this),this.onUpdate=this.onUpdate.bind(this),this.onRescale=this.onRescale.bind(this),this.onResize=this.onResize.bind(this),this.onOrderChanged=this.onOrderChanged.bind(this),this.onOpacityChanged=this.onOpacityChanged.bind(this),this.setVisibility=this.setVisibility.bind(this)}return Object.defineProperty(Layer.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"element",{get:function(){return this._element},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"options",{get:function(){return this._options},set:function(options){this._options=options},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"isLoading",{get:function(){return this.loading},set:function(loading){this.loading=loading},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"opacity",{get:function(){return this._opacity},set:function(opacity){this._opacity=opacity,this.onOpacityChanged(opacity)},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"order",{get:function(){return this._order},set:function(order){this._order=order,this.onOrderChanged(order)},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"interactive",{get:function(){return this._interactive},set:function(shouldBeInteractive){this._interactive=shouldBeInteractive,this.onInteractivityChanged(shouldBeInteractive)},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"referenceSystem",{get:function(){return this._referenceSystem},set:function(referenceSystem){this._referenceSystem=referenceSystem},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"data",{get:function(){return this.getData()},set:function(data){this.setData(data)},enumerable:!1,configurable:!0}),Object.defineProperty(Layer.prototype,"isVisible",{get:function(){return this._visible},enumerable:!1,configurable:!0}),Layer.prototype.getData=function(){return this._data},Layer.prototype.setData=function(data){this._data=data,this.element&&this.onUpdate({data:data})},Layer.prototype.clearData=function(includeReferenceSystem){void 0===includeReferenceSystem&&(includeReferenceSystem=!0),this._data=null,includeReferenceSystem&&(this.referenceSystem=null),this.onUpdate({})},Layer.prototype.setVisibility=function(visible,_layerId){this._visible=visible},Layer.prototype.onMount=function(event){this._element=event.elm,this._options.onMount&&this._options.onMount(event,this)},Layer.prototype.onUnmount=function(event){this._options.onUnmount&&this._options.onUnmount(event,this)},Layer.prototype.onResize=function(event){this._options.onResize&&this._options.onResize(event,this)},Layer.prototype.onUpdate=function(event){event.data&&(this._data=event.data),this._options.onUpdate&&this._options.onUpdate(event,this)},Layer.prototype.onRescale=function(event){this.optionsRescale(event)},Layer.prototype.optionsRescale=function(event){this._options.onRescale&&this._options.onRescale(event,this)},Layer.prototype.getInternalLayerIds=function(){return[]},Layer}(),CanvasLayer=function(_super){function CanvasLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(CanvasLayer,_super),CanvasLayer.prototype.onOpacityChanged=function(_opacity){this.canvas&&this.updateStyle()},CanvasLayer.prototype.onOrderChanged=function(_order){this.canvas&&this.updateStyle()},CanvasLayer.prototype.onInteractivityChanged=function(_interactive){this.canvas&&this.updateStyle()},CanvasLayer.prototype.setVisibility=function(visible){_super.prototype.setVisibility.call(this,visible),this.canvas&&this.updateStyle(visible)},CanvasLayer.prototype.updateStyle=function(visible){var visibility=visible||this.isVisible?"visible":"hidden",interactive=this.interactive?"auto":"none";this.canvas.setAttribute("style","position:absolute;pointer-events:".concat(interactive,";z-index:").concat(this.order,";opacity:").concat(this.opacity,";visibility:").concat(visibility))},CanvasLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event);var canvas,elm=event.elm,width=event.width||parseInt(elm.getAttribute("width"),10)||200,height=event.height||parseInt(elm.getAttribute("height"),10)||300;this.elm=elm,this.canvas||(canvas=document.createElement("canvas"),this.canvas=canvas,event.elm.appendChild(canvas)),this.canvas.setAttribute("id","".concat(this.id)),this.canvas.setAttribute("width","".concat(width,"px")),this.canvas.setAttribute("height","".concat(height,"px")),this.canvas.setAttribute("class","canvas-layer"),this.updateStyle(),this.ctx=this.canvas.getContext("2d")},CanvasLayer.prototype.onUnmount=function(){_super.prototype.onUnmount.call(this),this.canvas.remove(),this.canvas=null},CanvasLayer.prototype.onResize=function(event){var ctx=this.ctx,width=event.width,height=event.height;ctx.canvas.setAttribute("width","".concat(width,"px")),ctx.canvas.setAttribute("height","".concat(height,"px"))},CanvasLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event)},CanvasLayer.prototype.resetTransform=function(){this.ctx.resetTransform()},CanvasLayer.prototype.setTransform=function(event){this.resetTransform();var flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.ctx.translate(event.xScale(0),event.yScale(0)),this.ctx.scale(event.xRatio*(flippedX?-1:1),event.yRatio*(flippedY?-1:1))},CanvasLayer.prototype.clearCanvas=function(){var ctx=this.ctx,canvas=this.canvas;ctx.save(),ctx.resetTransform(),ctx.clearRect(0,0,canvas.width,canvas.height),ctx.restore()},CanvasLayer}(Layer),HTMLLayer=function(_super){function HTMLLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(HTMLLayer,_super),HTMLLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event);var elm=event.elm,width=event.width||parseInt(elm.getAttribute("width"),10)||200,height=event.height||parseInt(elm.getAttribute("height"),10)||300;this.elm||(this.elm=select(elm).append("div"),this.elm.attr("id","".concat(this.id)),this.elm.attr("class","html-layer"));var interactive=this.interactive?"auto":"none";this.elm.style("position","absolute").style("height","".concat(height,"px")).style("width","".concat(width,"px")).style("opacity",this.opacity).style("overflow","hidden").style("pointer-events",interactive).style("z-index",this.order)},HTMLLayer.prototype.onUnmount=function(){_super.prototype.onUnmount.call(this),this.elm.remove(),this.elm=null},HTMLLayer.prototype.onResize=function(event){this.elm&&(_super.prototype.onResize.call(this,event),this.elm.style("height","".concat(event.height,"px")).style("width","".concat(event.width,"px")))},HTMLLayer.prototype.setVisibility=function(visible){_super.prototype.setVisibility.call(this,visible),this.elm&&this.elm.attr("visibility",visible?"visible":"hidden")},HTMLLayer.prototype.onOpacityChanged=function(opacity){this.elm&&this.elm.style("opacity",opacity)},HTMLLayer.prototype.onOrderChanged=function(order){this.elm&&this.elm.style("z-index",order)},HTMLLayer.prototype.onInteractivityChanged=function(shouldBeInteractive){if(this.elm){var interactive=shouldBeInteractive?"auto":"none";this.elm.style("pointer-events",interactive)}},HTMLLayer}(Layer),SVGLayer=function(_super){function SVGLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(SVGLayer,_super),SVGLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event);var elm=event.elm,width=event.width||parseInt(elm.getAttribute("width"),10)||200,height=event.height||parseInt(elm.getAttribute("height"),10)||300;this.elm||(this.elm=select(elm).append("svg"),this.elm.attr("id","".concat(this.id)),this.elm.attr("class","svg-layer")),this.elm.attr("height",height).attr("width",width);var interactive=this.interactive?"auto":"none";this.elm.style("position","absolute").style("pointer-events",interactive).style("opacity",this.opacity).style("z-index",this.order)},SVGLayer.prototype.onUnmount=function(){_super.prototype.onUnmount.call(this),this.elm.remove(),this.elm=null},SVGLayer.prototype.onResize=function(event){this.elm&&(_super.prototype.onResize.call(this,event),this.elm.attr("height",event.height).attr("width",event.width))},SVGLayer.prototype.setVisibility=function(visible){_super.prototype.setVisibility.call(this,visible),this.elm&&this.elm.attr("visibility",visible?"visible":"hidden")},SVGLayer.prototype.onOpacityChanged=function(opacity){this.elm&&this.elm.style("opacity",opacity)},SVGLayer.prototype.onOrderChanged=function(order){this.elm&&this.elm.style("z-index",order)},SVGLayer.prototype.onInteractivityChanged=function(shouldBeInteractive){if(this.elm){var interactive=shouldBeInteractive?"auto":"none";this.elm.style("pointer-events",interactive)}},SVGLayer}(Layer),PixiRenderApplication=function(){function PixiRenderApplication(pixiRenderOptions){var options=__assign({width:200,height:300,antialias:!0,backgroundAlpha:0,clearBeforeRender:!0,preserveDrawingBuffer:!0},pixiRenderOptions);this.renderer=autoDetectRenderer(options),this.stage=new Container}return PixiRenderApplication.prototype.destroy=function(){var _a,_b;this.stage.destroy({children:!0,texture:!0,baseTexture:!0}),this.stage=null;var renderType=this.renderer.type,glContext=this.renderer instanceof Renderer?null===(_a=this.renderer)||void 0===_a?void 0:_a.gl:void 0;renderType===RENDERER_TYPE.WEBGL&&glContext&&(null===(_b=null==glContext?void 0:glContext.getExtension("WEBGL_lose_context"))||void 0===_b||_b.loseContext()),this.renderer.destroy(!0),this.renderer=null},Object.defineProperty(PixiRenderApplication.prototype,"view",{get:function(){return this.renderer.view},enumerable:!1,configurable:!0}),PixiRenderApplication.prototype.render=function(){this.renderer.render(this.stage)},PixiRenderApplication}(),PixiLayer=function(_super){function PixiLayer(ctx,id,options){var _this=_super.call(this,id,options)||this;return _this.ctx=ctx,_this.container=new Container,_this.ctx.stage.addChild(_this.container),_this}return __extends(PixiLayer,_super),PixiLayer.prototype.render=function(){this.ctx.render()},PixiLayer.prototype.addChild=function(child){this.container.addChild(child)},PixiLayer.prototype.clearLayer=function(){this.container.removeChildren().forEach((function(child){child.destroy()}))},PixiLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event),this.pixiViewContainer=this.element.querySelector("#webgl-layer"),this.pixiViewContainer||(this.pixiViewContainer=document.createElement("div"),this.pixiViewContainer.setAttribute("id","".concat(this.id)),this.pixiViewContainer.setAttribute("class","webgl-layer"),this.pixiViewContainer.appendChild(this.ctx.view),this.element.appendChild(this.pixiViewContainer),this.updateStyle())},PixiLayer.prototype.onUnmount=function(event){_super.prototype.onUnmount.call(this,event),this.clearLayer(),this.ctx.stage.removeChild(this.container),this.container.destroy(),this.pixiViewContainer.remove(),this.pixiViewContainer=void 0},PixiLayer.prototype.onResize=function(event){_super.prototype.onResize.call(this,event),this.ctx.renderer.resize(event.width,event.height)},PixiLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event);var flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.setContainerPosition(event.xScale(0),event.yScale(0)),this.setContainerScale(event.xRatio*(flippedX?-1:1),event.yRatio*(flippedY?-1:1))},PixiLayer.prototype.setContainerPosition=function(x,y){this.container.position.set(x,y)},PixiLayer.prototype.setContainerScale=function(x,y){this.container.scale.set(x,y)},PixiLayer.prototype.updateStyle=function(visible){var isVisible=visible||this.isVisible,interactive=this.interactive?"auto":"none";this.container.visible=isVisible;var styles=[["position","absolute"],["pointer-events","".concat(interactive)],["z-index","".concat(this.order)],["opacity","".concat(this.opacity)]].map((function(pair){return pair.join(":")})).join(";");this.pixiViewContainer.setAttribute("style",styles)},PixiLayer.prototype.setVisibility=function(visible,layerId){_super.prototype.setVisibility.call(this,visible,layerId),this.pixiViewContainer&&this.updateStyle(visible)},PixiLayer.prototype.onOpacityChanged=function(_opacity){this.pixiViewContainer&&this.updateStyle()},PixiLayer.prototype.onOrderChanged=function(_order){this.pixiViewContainer&&this.updateStyle()},PixiLayer.prototype.onInteractivityChanged=function(_interactive){this.pixiViewContainer&&this.updateStyle()},PixiLayer.prototype.renderType=function(){return this.ctx.renderer.type},PixiLayer}(Layer);function assertNever(x){throw new Error("Unexpected object: ".concat(JSON.stringify(x)))}var isPAndASymbol=function(item){return"pAndASymbol"===item.kind},isCementSqueeze=function(item){return"cementSqueeze"===item.kind},isCementPlug=function(item){return"cementPlug"===item.kind},foldCompletion=function(fScreen,fTubing,fSymbol){return function(completion){switch(completion.kind){case"screen":return fScreen(completion);case"tubing":return fTubing(completion);case"completionSymbol":return fSymbol(completion);default:return assertNever(completion)}}},foldPerforationSubKind=function(options,subKind){switch(subKind){case"Perforation":return options.Perforation(subKind);case"Open hole gravel pack":return options.OpenHoleGravelPack(subKind);case"Open hole frac pack":return options.OpenHoleFracPack(subKind);case"Cased hole fracturation":return options.CasedHoleFracturation(subKind);case"Cased hole frac pack":return options.CasedHoleFracPack(subKind);case"Cased hole gravel pack":return options.CasedHoleGravelPack(subKind);default:return assertNever(subKind)}},shouldPerforationStartAtHoleDiameter=function(perf){return foldPerforationSubKind({Perforation:function(){return!0},OpenHoleGravelPack:function(){return!0},OpenHoleFracPack:function(){return!1},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!1}},perf.subKind)},shouldPerforationStartAtCasingDiameter=function(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!0},CasedHoleFracturation:function(){return!0},CasedHoleGravelPack:function(){return!0},CasedHoleFracPack:function(){return!0}},perf.subKind)},hasPacking=function(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!0},OpenHoleFracPack:function(){return!0},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!0},CasedHoleFracPack:function(){return!0}},perf.subKind)};function hasFracLines(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!0},CasedHoleFracturation:function(){return!0},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!0}},perf.subKind)}function hasSpikes(perf){return foldPerforationSubKind({Perforation:function(){return!0},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!1},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!1}},perf.subKind)}function isSubkindCasedHoleGravelPack(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!1},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!0},CasedHoleFracPack:function(){return!1}},perf.subKind)}function isSubKindPerforation(perf){return foldPerforationSubKind({Perforation:function(){return!0},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!1},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!1}},perf.subKind)}function isSubKindCasedHoleFracPack(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!1},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!0}},perf.subKind)}function isOpenHoleFracPack(perf){return foldPerforationSubKind({Perforation:function(){return!1},OpenHoleGravelPack:function(){return!1},OpenHoleFracPack:function(){return!0},CasedHoleFracturation:function(){return!1},CasedHoleGravelPack:function(){return!1},CasedHoleFracPack:function(){return!1}},perf.subKind)}var intersect=function(a,b){return a.start<b.end&&a.end>b.start},defaultInternalLayerOptions=function(layerId){return{holeLayerId:"".concat(layerId,"-hole"),casingLayerId:"".concat(layerId,"-casing"),completionLayerId:"".concat(layerId,"-completion"),cementLayerId:"".concat(layerId,"-cement"),pAndALayerId:"".concat(layerId,"-pAndA"),perforationLayerId:"".concat(layerId,"-perforation")}},defaultHoleOptions={firstColor:"#8c541d",secondColor:"#eee3d8",lineColor:"#8b4513"},defaultCasingOptions={solidColor:"#dcdcdc",lineColor:"#575757",shoeSize:{width:8,length:16},windowOptions:{dashColor:"#dc0000",dashLength:5,spaceLength:3}},defaultPerforationOptions={stroke:"rgba(0, 0, 0, 0.25)",yellow:"#FFFC00",grey:"gray",red:"#FF5050",outline:"black",transparent:"rgba(255, 255, 255, 0)",spikeWidth:50,spikeLength:50,packingOpacity:.5,fracLineCurve:10,fracLineLength:25,scalingFactor:25},defaultCementOptions={firstColor:"#c7b9ab",secondColor:"#5b5b5b",scalingFactor:4},defaultCementSqueezeOptions={firstColor:"#8b6713",secondColor:"#000000",scalingFactor:4},defaultScreenOptions={scalingFactor:4,lineColor:"#63666a"},defaultTubingOptions={scalingFactor:1,innerColor:"#eeeeff",outerColor:"#777788"},defaultCementPlugOptions={firstColor:"#c7b9ab",secondColor:"#000000",scalingFactor:4};function pixelsPerUnit(x){var min=x.domain()[0];return Math.abs(x(min+1))}function calcSize(factor,min,max,x){return clamp(pixelsPerUnit(x)*factor,min,max)}function isOverlappingHorizontally(r1,r2){var r1x2=r1.x+r1.width,r2x2=r2.x+r2.width;return!(r2.x>r1x2||r2x2<r1.x)}function isOverlapping(r1,r2,horizontalPadding,verticalPadding){void 0===horizontalPadding&&(horizontalPadding=4),void 0===verticalPadding&&(verticalPadding=2);var r1x2=r1.x+r1.width+horizontalPadding,r2x2=r2.x+r2.width+horizontalPadding,r1y2=r1.y+r1.height+verticalPadding,r2y2=r2.y+r2.height+verticalPadding;return!(r2.x-horizontalPadding>r1x2||r2.y-verticalPadding>r1y2||r2x2+horizontalPadding<r1.x||r2y2+verticalPadding<r1.y)}function getOverlap(r1,r2){var r1x2=r1.x+r1.width,r2x2=r2.x+r2.width,r1y2=r1.y+r1.height,r2y2=r2.y+r2.height;return r2.x>r1x2||r2.y>r1y2||r2x2<r1.x||r2y2<r1.y?null:{dx:Math.max(0,Math.min(r1.x+r1.width,r2.x+r2.width)-Math.max(r1.x,r2.x)),dy:Math.max(0,Math.min(r1.y+r1.height,r2.y+r2.height)-Math.max(r1.y,r2.y))}}function getOverlapOffset(r1,r2,horizontalPadding,verticalPadding){void 0===horizontalPadding&&(horizontalPadding=4),void 0===verticalPadding&&(verticalPadding=2);var r1x2=r1.x+r1.width,r2x2=r2.x+r2.width,r1y2=r1.y+r1.height,r2y2=r2.y+r2.height;return r2.x-horizontalPadding>r1x2||r2.y-verticalPadding>r1y2||r2x2+horizontalPadding<r1.x||r2y2+verticalPadding<r1.y?null:{dx:r1.x+r1.width-r2.x+horizontalPadding,dy:r1.y+r1.height-r2.y+verticalPadding}}var Location_topleft="topleft",Location_topright="topright",Location_bottomleft="bottomleft",Location_bottomright="bottomright",CalloutCanvasLayer=function(_super){function CalloutCanvasLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.groupFilter=null,_this.renderAnnotation=function(title,label,x,y,fontSize,color){_this.renderText(title,x,y-fontSize,fontSize,color,"arial","bold"),_this.renderText(label,x,y,fontSize,color)},_this.renderLine=function(x,y,width,dotX,dotY,color,placeLeft){void 0===placeLeft&&(placeLeft=!0);var ctx=_this.ctx,textX=placeLeft?x:x+width,inverseTextX=placeLeft?x+width:x,textY=y+2;ctx.strokeStyle=color,ctx.lineWidth=1,ctx.beginPath(),ctx.moveTo(dotX,dotY),ctx.lineTo(textX,textY),ctx.lineTo(inverseTextX,textY),ctx.stroke()},_this.minFontSize=options.minFontSize||7,_this.maxFontSize=options.maxFontSize||11,_this.fontSizeFactor=options.fontSizeFactor||7,_this.offsetMin=options.offsetMin||20,_this.offsetMax=options.offsetMax||120,_this.offsetFactor=options.offsetFactor||19,_this}return __extends(CalloutCanvasLayer,_super),CalloutCanvasLayer.prototype.setGroupFilter=function(filter){this.groupFilter=filter,this.callouts=void 0,this.render()},CalloutCanvasLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.callouts=void 0,this.render()},CalloutCanvasLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event);var isPanning=this.rescaleEvent&&this.rescaleEvent.xRatio===event.xRatio;this.rescaleEvent=event,this.render(isPanning)},CalloutCanvasLayer.prototype.render=function(isPanning){var _this=this;void 0===isPanning&&(isPanning=!1),requestAnimationFrame((function(){if(_this.clearCanvas(),_this.data&&_this.rescaleEvent&&_this.referenceSystem){var _a=_this.rescaleEvent,xScale=_a.xScale,yScale=_a.yScale,xBounds=_a.xBounds,fontSize=calcSize(_this.fontSizeFactor,_this.minFontSize,_this.maxFontSize,xScale);if(!isPanning||!_this.callouts){var _b=_this,data=_b.data,ctx=_b.ctx,groupFilter_1=_b.groupFilter,isLeftToRight=_this.referenceSystem.options.calculateDisplacementFromBottom?xBounds[0]<xBounds[1]:xBounds[0]>xBounds[1];ctx.font="bold ".concat(fontSize,"px arial");var filtered=data.filter((function(d){return!groupFilter_1||groupFilter_1.includes(d.group)})),offset=calcSize(_this.offsetFactor,_this.offsetMin,_this.offsetMax,xScale);_this.callouts=_this.positionCallouts(filtered,isLeftToRight,xScale,yScale,0,fontSize,offset)}_this.callouts.forEach((function(callout){var pos=callout.pos,title=callout.title,color=callout.color,calloutBB={x:xScale(pos.x),y:yScale(pos.y),width:callout.boundingBox.width,height:fontSize,offsetX:callout.dx,offsetY:callout.dy};_this.renderCallout(title,callout.label,calloutBB,color,callout.alignment)}))}}))},CalloutCanvasLayer.prototype.renderText=function(title,x,y,fontSize,color,font,fontStyle){void 0===font&&(font="arial"),void 0===fontStyle&&(fontStyle="normal");var ctx=this.ctx;ctx.font="".concat(fontStyle," ").concat(fontSize,"px ").concat(font),ctx.fillStyle=color,ctx.fillText(title,x,y)},CalloutCanvasLayer.prototype.renderPoint=function(x,y,radius){void 0===radius&&(radius=3);var ctx=this.ctx;ctx.beginPath(),ctx.moveTo(x,y),ctx.arc(x,y,radius,0,2*Math.PI),ctx.fill()},CalloutCanvasLayer.prototype.renderCallout=function(title,label,boundingBox,color,location){var pos=this.getPosition(boundingBox,location),x=pos.x,y=pos.y,height=boundingBox.height,width=boundingBox.width,dotX=boundingBox.x,dotY=boundingBox.y,placeLeft=location===Location_topright||location===Location_bottomright;this.renderAnnotation(title,label,x,y,height,color),this.renderPoint(dotX,dotY),this.renderLine(x,y,width,dotX,dotY,color,placeLeft)},CalloutCanvasLayer.prototype.getPosition=function(boundingBox,location){var x=boundingBox.x,y=boundingBox.y,offsetX=boundingBox.offsetX,offsetY=boundingBox.offsetY,width=boundingBox.width;switch(location){case Location_topleft:return{x:x-width-offsetX,y:y-offsetY};case Location_topright:return{x:x+offsetX,y:y-offsetY};case Location_bottomleft:return{x:x-width-offsetX,y:y+offsetY};case Location_bottomright:return{x:x+offsetX,y:y+offsetY};default:return{x:x,y:y}}},CalloutCanvasLayer.prototype.positionCallouts=function(annotations,isLeftToRight,xScale,yScale,_scale,fontSize,offset){var _this=this;if(void 0===offset&&(offset=20),0===annotations.length)return[];var alignment=isLeftToRight?Location_topleft:Location_topright,nodes=annotations.map((function(a){var pos=a.pos?a.pos:_this.referenceSystem.project(a.md);return{title:a.title,label:a.label,color:a.color,pos:{x:pos[0],y:pos[1]},group:a.group,alignment:alignment,boundingBox:_this.getAnnotationBoundingBox(a.title,a.label,pos,xScale,yScale,fontSize),dx:offset,dy:offset}})),top=[nodes[nodes.length-1]],bottom=[];return this.chooseTopOrBottomPosition(nodes,bottom,top),this.adjustTopPositions(top),this.adjustBottomPositions(bottom),nodes},CalloutCanvasLayer.prototype.getAnnotationBoundingBox=function(title,label,pos,xScale,yScale,height){var ctx=this.ctx,ax1=xScale(pos[0]),ay1=yScale(pos[1]),labelWidth=ctx.measureText(label).width,titleWidth=ctx.measureText(title).width;return{x:ax1,y:ay1,width:Math.max(labelWidth,titleWidth),height:2*height+4}},CalloutCanvasLayer.prototype.chooseTopOrBottomPosition=function(nodes,bottom,top){for(var i=nodes.length-2;i>=0;--i){var node=nodes[i],prevNode=top[0];isOverlapping(node.boundingBox,prevNode.boundingBox)?(node.alignment=node.alignment===Location_topleft?Location_bottomright:Location_bottomleft,bottom.push(node),i>0&&top.unshift(nodes[--i])):top.unshift(node)}},CalloutCanvasLayer.prototype.adjustTopPositions=function(top){for(var i=top.length-2;i>=0;--i)for(var currentNode=top[i],j=top.length-1;j>i;--j){var prevNode=top[j],overlap=getOverlapOffset(currentNode.boundingBox,prevNode.boundingBox);overlap&&(currentNode.dy+=overlap.dy,currentNode.boundingBox.y-=overlap.dy)}},CalloutCanvasLayer.prototype.adjustBottomPositions=function(bottom){for(var i=bottom.length-2;i>=0;--i)for(var currentNode=bottom[i],j=bottom.length-1;j>i;--j){var overlap=getOverlapOffset(bottom[j].boundingBox,currentNode.boundingBox);overlap&&(currentNode.dy+=overlap.dy,currentNode.boundingBox.y+=overlap.dy)}},CalloutCanvasLayer}(CanvasLayer);function convertColor(colorStr){var d=color(colorStr).formatHex();return parseInt(d.replace("#","0x"))}var GeomodelCanvasLayer=function(_super){function GeomodelCanvasLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.surfaceAreasPaths=[],_this.surfaceLinesPaths=[],_this.maxDepth=1e4,_this.drawPolygonPath=function(color,path){var ctx=_this.ctx;ctx.fillStyle=color,ctx.fill(path)},_this.drawLinePath=function(color,path){var ctx=_this.ctx;ctx.strokeStyle=color,ctx.stroke(path)},_this.createPolygons=function(data){for(var polygons=[],polygon=null,i=0;i<data.length;i++){var topIsValid=!!data[i][1];topIsValid&&(null===polygon&&(polygon=[]),polygon.push(data[i][0],data[i][1]));var endIsReached=i===data.length-1;if((!topIsValid||endIsReached)&&polygon){for(var j=topIsValid?i:i-1;j>=0&&data[j][1];j--)polygon.push(data[j][0],data[j][2]||_this.maxDepth);polygons.push(polygon),polygon=null}}return polygons},_this.generatePolygonPath=function(polygon){var path=new Path2D;path.moveTo(polygon[0],polygon[1]);for(var i=2;i<polygon.length;i+=2)path.lineTo(polygon[i],polygon[i+1]);return path.closePath(),path},_this.generateLinePaths=function(s){for(var paths=[],d=s.data,penDown=!1,path=null,i=0;i<d.length;i++)d[i][1]?penDown?path.lineTo(d[i][0],d[i][1]):((path=new Path2D).moveTo(d[i][0],d[i][1]),penDown=!0):penDown&&(paths.push(path),penDown=!1);return penDown&&paths.push(path),paths},_this.render=_this.render.bind(_this),_this.generateSurfaceAreasPaths=_this.generateSurfaceAreasPaths.bind(_this),_this.generateSurfaceLinesPaths=_this.generateSurfaceLinesPaths.bind(_this),_this.drawPolygonPath=_this.drawPolygonPath.bind(_this),_this.drawLinePath=_this.drawLinePath.bind(_this),_this.updatePaths=_this.updatePaths.bind(_this),_this}return __extends(GeomodelCanvasLayer,_super),GeomodelCanvasLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.updatePaths(),this.render()},GeomodelCanvasLayer.prototype.onRescale=function(event){this.rescaleEvent=event,this.setTransform(this.rescaleEvent),this.render()},GeomodelCanvasLayer.prototype.updatePaths=function(){this.data?(this.generateSurfaceAreasPaths(),this.generateSurfaceLinesPaths()):(this.surfaceAreasPaths=[],this.surfaceLinesPaths=[])},GeomodelCanvasLayer.prototype.render=function(){var _this=this;this.ctx&&this.rescaleEvent&&requestAnimationFrame((function(){_this.clearCanvas(),_this.surfaceAreasPaths.forEach((function(p){return _this.drawPolygonPath(p.color,p.path)})),_this.surfaceLinesPaths.forEach((function(l){return _this.drawLinePath(l.color,l.path)}))}))},GeomodelCanvasLayer.prototype.colorToCSSColor=function(color){return function(color){if("string"==typeof color)return color;var colorHexString=color.toString(16);return"#".concat(colorHexString.padStart(6,"0"))}(color)},GeomodelCanvasLayer.prototype.generateSurfaceAreasPaths=function(){var _this=this;this.surfaceAreasPaths=this.data.areas.reduce((function(acc,s){var mapped=_this.createPolygons(s.data).map((function(polygon){return{color:_this.colorToCSSColor(s.color),path:_this.generatePolygonPath(polygon)}}));return acc.push.apply(acc,mapped),acc}),[])},GeomodelCanvasLayer.prototype.generateSurfaceLinesPaths=function(){var _this=this;this.surfaceLinesPaths=this.data.lines.reduce((function(acc,l){var mapped=_this.generateLinePaths(l).map((function(path){return{color:_this.colorToCSSColor(l.color),path:path}}));return acc.push.apply(acc,mapped),acc}),[])},GeomodelCanvasLayer}(CanvasLayer);function findIndexOfSample(data,pos){for(var a=0,b=data.length-1,aPos=data[a][0],bPos=data[b][0];b-a>20;){var splitAt=Math.floor((b+a)/2),splitPos=data[splitAt][0];if(pos>=aPos&&pos<splitPos)bPos=data[b=splitAt][0];else if(pos>=splitPos&&pos<=bPos)aPos=data[a=splitAt][0];else if(pos<=aPos&&pos>splitPos)bPos=data[b=splitAt][0];else{if(!(pos<=splitPos&&pos>=bPos))return-1;aPos=data[a=splitAt][0]}}for(var index=-1,i=a;i<b;i++){var v1=data[i][0],v2=data[i+1][0];if(Math.min(v1,v2)<=pos&&pos<=Math.max(v1,v2)){index=i;break}}return index}function findSampleAtPos(data,pos,topLimit,bottomLimit){void 0===topLimit&&(topLimit=null),void 0===bottomLimit&&(bottomLimit=null);var y=null,index=findIndexOfSample(data,pos);if(-1!==index){var v1=data[index][1],v2=data[index+1][1];if(v2&&v2){var x1=data[index][0],f=(pos-x1)/(data[index+1][0]-x1);y=v1*(1-f)+v2*f,topLimit&&topLimit>y&&(y=topLimit),bottomLimit&&bottomLimit<y&&(y=bottomLimit)}}return y}var mapPick=function(p,groupName){return{title:p.pickIdentifier||p.identifier,group:groupName,label:"".concat(p.md," ").concat(p.mdUnit," ").concat(p.depthReferencePoint),color:"strat-picks"===groupName?"#227":"rgba(0,0,0,0.8)",md:p.md}};var getPicksData=function(picksData){return __spreadArray(__spreadArray(__spreadArray([],(picks=picksData.nonUnitPicks,picks?picks.map((function(p){return mapPick(p,"ref-picks")})):[]),!0),(formationPicks=picksData.unitPicks,formationPicks?formationPicks.filter((function(d){return d.entryPick.md===d.from})).map((function(p){return mapPick(p.entryPick,"strat-picks")})):[]),!0),function(formationPicks){return formationPicks?formationPicks.filter((function(d){return-1===formationPicks.findIndex((function(p){return Math.abs(p.entryPick.md-d.exitPick.md)<.5}))})).map((function(p){return mapPick(p.exitPick,"strat-picks")})).filter((function(obj,i,array){return i===array.findIndex((function(v){return v.title===obj.title&&v.md===obj.md}))})):[]}(picksData.unitPicks),!0).sort((function(a,b){return a.md-b.md}));var formationPicks,picks},unitDto=function(u){return{unitName:u.identifier,topSurface:u.top,baseSurface:u.base,ageBase:u.baseAge,ageTop:u.topAge,color:{r:null===u.colorR?255:u.colorR,g:null===u.colorG?255:u.colorG,b:null===u.colorB?255:u.colorB},level:u.stratUnitLevel,lithType:u.lithologyType,parent:u.stratUnitParent}};function joinPicksAndStratColumn(picks,stratColumn){var transformed=stratColumn.map(unitDto),nonUnitPicks=[],joined=[];return picks.forEach((function(p){var matches=transformed.filter((function(u){return-1!==p.pickIdentifier.search(new RegExp("(".concat(u.topSurface,"|").concat(u.baseSurface,")"),"i"))}));matches.length>0?matches.forEach((function(u){return joined.push(__assign({md:p.md,tvd:p.tvd,identifier:p.pickIdentifier,confidence:p.confidence,mdUnit:p.mdUnit,depthReferencePoint:p.depthReferencePoint},u))})):nonUnitPicks.push(__assign({identifier:p.pickIdentifier},p))})),{joined:joined,nonUnitPicks:nonUnitPicks}}function transformFormationData(picks,stratColumn){for(var _a=joinPicksAndStratColumn(picks,stratColumn),joined=_a.joined,nonUnitPicks=_a.nonUnitPicks,pairs=function(joined){for(var pairs=[],current=null,sorted=joined.filter((function(d){return d.level})).sort((function(a,b){return a.unitName.localeCompare(b.unitName)||a.md-b.md||a.ageTop-b.ageTop})),_loop_1=function(){var _a,pairWithName,top_1,base,name_1=(current=sorted.shift()).identifier,isTop=name_1===current.topSurface,isBase=name_1===current.baseSurface;if(isTop)pairWithName=current.baseSurface;else{if(!isBase)return console.warn("Unable to match ".concat(name_1," with top or base surface, ignored")),"continue";pairWithName=current.topSurface}var pairWith=sorted.find((function(p){return p.identifier===pairWithName}));if(pairWith)base=isTop?pairWith:current,(top_1=isTop?current:pairWith).md>base.md&&(top_1=(_a=[base,top_1])[0],base=_a[1]),sorted.splice(sorted.indexOf(pairWith),1);else if(console.warn("Unable to find ".concat(pairWithName," pick for ").concat(name_1)),isTop){if(top_1=current,!(base=joined.filter((function(d){return d.level})).sort((function(a,b){return a.md-b.md})).find((function(p){return p.md>top_1.md}))))return console.warn("Unable to find a base pick for ".concat(name_1," pick at ").concat(top_1.md,", ignored")),"continue";console.warn("Using ".concat(base.identifier," as base for ").concat(name_1))}else{if(!isBase)return console.warn("".concat(name_1," ignored")),"continue";if(base=current,!(top_1=joined.filter((function(d){return d.level})).sort((function(a,b){return b.md-a.md})).find((function(p){return p.md<base.md}))))return console.warn("Unable to find a top pick for ".concat(name_1," pick at ").concat(base.md,", ignored")),"continue";console.warn("Using ".concat(top_1.identifier," as top for ").concat(name_1))}pairs.push({name:top_1.unitName,mdEntry:top_1.md,tvdEntry:top_1.tvd,color:top_1.color,level:top_1.level,entryPick:top_1,mdExit:base.md,tvdExit:base.tvd,exitPick:base,confidenceEntry:top_1.confidence,confidenceExit:base.confidence})};sorted.length>0;)_loop_1();return pairs}(joined),itemstack=pairs.filter((function(d){return d.mdEntry<d.mdExit})).sort((function(a,b){return a.mdEntry-b.mdEntry||a.level-b.level})).reverse(),unitPicks=[],_loop_2=function(){for(var first=itemstack.pop(),group=[];itemstack.length>0&&itemstack[itemstack.length-1].level>first.level;)group.push(itemstack.pop());group.reverse(),group.push(first);var arr=[];group.forEach((function(itm){var gaps=function(from,to,arr){if(0===arr.length)return[[from,to]];for(var gaps=[],d=from,i=0;d<to&&i<arr.length;){var itm=arr[i];itm.from>d&&gaps.push([d,Math.min(itm.from,to)]),d=Math.min(to,Math.max(from,itm.to)),i+=1}return d<to&&gaps.push([d,to]),gaps}(itm.mdEntry,itm.mdExit,arr);arr.push.apply(arr,gaps.map((function(g){return{from:g[0],to:g[1],itm:itm}})))})),arr.sort((function(a,b){return a.from-b.from})),unitPicks.push.apply(unitPicks,arr.map((function(d){return __assign({from:d.from,to:d.to},d.itm)})))};itemstack.length>0;)_loop_2();return{unitPicks:unitPicks,nonUnitPicks:nonUnitPicks}}var getSeismicOptions=function(info){return info?{x:info.minX,y:info.minTvdMsl,width:info.maxX-info.minX,height:info.maxTvdMsl-info.minTvdMsl}:{x:0,y:0,width:0,height:0}};function getSeismicInfo(data,trajectory){if(!data||!data.datapoints)return null;var minX=trajectory.reduce((function(acc,val){return Math.min(acc,val[0])}),0),maxX=trajectory.reduce((function(acc,val){return Math.max(acc,val[0])}),0),minTvdMsl=data.yAxisValues&&data.yAxisValues[0],maxTvdMsl=data.yAxisValues&&data.yAxisValues[data.yAxisValues.length-1],dp=data.datapoints||[],min=-dp.reduce((function(val,array){return Math.min.apply(Math,__spreadArray(__spreadArray([],array,!1),[val],!1))}),0),max=dp.reduce((function(val,array){return Math.max.apply(Math,__spreadArray(__spreadArray([],array,!1),[val],!1))}),0),absMax=Math.max(Math.abs(min),Math.abs(max)),dmin=-absMax;return{minX:minX,maxX:maxX,minTvdMsl:minTvdMsl,maxTvdMsl:maxTvdMsl,domain:{min:dmin,max:absMax,difference:absMax-dmin}}}function generateSeismicSliceImage(data,trajectory,colormap,options){return __awaiter(this,void 0,void 0,(function(){var dp,min,max,absMax,dmin,dmax,domain,length,width,height,colorTable,d,offset,colorFactor,pos,step,val1,val2,i,col,black,opacity,x,index,x1,x2,ratio,y,imageData;return __generator(this,(function(_a){switch(_a.label){case 0:if(!(data&&data.datapoints&&data.datapoints.length>0))return[2];for(dp=data.datapoints,min=(null==options?void 0:options.seismicMin)||(null==options?void 0:options.seismicRange)||dp.reduce((function(val,array){return Math.min.apply(Math,__spreadArray(__spreadArray([],array,!1),[val],!1))}),0),max=(null==options?void 0:options.seismicMax)||(null==options?void 0:options.seismicRange)||dp.reduce((function(val,array){return Math.max.apply(Math,__spreadArray(__spreadArray([],array,!1),[val],!1))}),0),absMax=Math.max(Math.abs(min),Math.abs(max)),domain={min:dmin=-absMax,max:dmax=absMax,difference:dmax-dmin},length=trajectory[0][0]-trajectory[trajectory.length-1][0],width=Math.abs(Math.floor(length/5)),height=data.yAxisValues.length,1e3,size=1e3,colorDomain=(colorMap=colormap).map((function(_v,i){return i*size/colorMap.length})),colorScale=scaleLinear().domain(colorDomain).range(colorMap),colorTable=Array.from(new Array(size).keys()).map((function(i){var rgb=color(colorScale(i)).rgb();return[rgb.r,rgb.g,rgb.b]})),d=new Uint8ClampedArray(width*height*4),offset=0,colorFactor=999/domain.difference,pos=(null==options?void 0:options.isLeftToRight)?trajectory[0][0]:trajectory[trajectory.length-1][0],step=length/width*((null==options?void 0:options.isLeftToRight)?-1:1),black=[0,0,0],x=0;x<width;x++){for(offset=4*x,index=findIndexOfSample(trajectory,pos),x1=trajectory[index][0],x2=trajectory[index+1][0],ratio=(pos-x1)/(x2-x1),y=0;y<height;y++)val1=dp[y][index],val2=dp[y][index+1],null==val1||null==val2?(col=black,opacity=0):(i=clamp(~~(i=(val1*(1-ratio)+val2*ratio-domain.min)*colorFactor),0,999),col=colorTable[i],opacity=255),d.set([col[0],col[1],col[2],opacity],offset),offset+=4*width;pos+=step}return imageData=new ImageData(d,width,height),[4,createImageBitmap(imageData,0,0,width,height)];case 1:return[2,_a.sent()]}var colorMap,size,colorDomain,colorScale}))}))}function generateSurfaceData(trajectory,stratColumn,surfaceData){var filteredSurfaces=surfaceData.filter((function(s){return s.data.values})),mappedSurfaces=filteredSurfaces.map((function(s){var displayName=s.visualSettings.displayName;return{name:displayName.replace(/\s(Base|Top)/gi,""),isBase:displayName.toLowerCase().endsWith("base"),values:s.data.values,color:s.visualSettings.colors.crossSection,visualization:s.visualSettings.crossSection.toLowerCase()}})),stratGroups=new Map,stratigraphies=function(mappedSurfaces,stratColumn,stratGroups){var firstUnit=stratColumn&&stratColumn.find((function(d){return 1===d.stratUnitLevel})),defaultGroupName=firstUnit?firstUnit.identifier:"SEABED",stratigrafies=mappedSurfaces.filter((function(d){return"interval"===d.visualization||"none"===d.visualization})).map((function(s){var path=[],stratUnit=findStratcolumnUnit(stratColumn,s.name,path);stratUnit||console.warn("No match for ".concat(s.name," in strat column"));var group=path[0]||stratUnit,groupName=group&&group.identifier||defaultGroupName;return group&&!stratGroups.has(groupName)&&stratGroups.set(groupName,{age:group.topAge,name:group.identifier}),__assign(__assign({},s),{unit:stratUnit,group:groupName})}));return stratigrafies}(mappedSurfaces,stratColumn,stratGroups);stratigraphies.sort((function(a,b){if(!a.unit&&!b.unit)return 0;if(!a.unit)return-1;if(!b.unit)return 1;var aAge=a.isBase?a.unit.baseAge:a.unit.topAge,bAge=b.isBase?b.unit.baseAge:b.unit.topAge;return aAge!==bAge?aAge-bAge:a.isBase&&!b.isBase?1:!a.isBase&&b.isBase?-1:a.unit.stratUnitLevel-b.unit.stratUnitLevel}));var lines=function(mappedSurfaces,trajectory){var lines=mappedSurfaces.filter((function(d){return"line"===d.visualization})).map((function(l){return{id:l.name,label:l.name,width:2,color:convertColor(l.color||"black"),data:trajectory.map((function(p,j){return[p[0],l.values[j]]}))}}));return lines}(mappedSurfaces,trajectory),surfaceAreas=function(projection,surfaces,stratColumn){var areas=surfaces.reduce((function(acc,surface,i){if(!surface.isBase){acc[surface.group]||(acc[surface.group]=[]);var baseIndex_1=function(top,index,surfaces,stratColumn){var nextIndex=index+1;if(!surfaces||nextIndex>=surfaces.length)return null;var baseSurfaceIndex=surfaces.findIndex((function(candidate){return candidate.isBase&&candidate.name===top.name}));if(-1!==baseSurfaceIndex)return baseSurfaceIndex;for(var i=nextIndex;i<surfaces.length;i++){var candidate=surfaces[i];if(!candidate.isBase)return i;if(isAnchestor(top,candidate,stratColumn))return i}return null}(surface,i,surfaces,stratColumn);acc[surface.group].push({id:surface.name,label:surface.name,color:surface.unit&&getColorFromUnit(surface.unit)||4294967295,exclude:"none"===surface.visualization||!surface.unit,data:projection.map((function(p,j){var baseValue=null!==surface.values[j]?function(index,surfaces,datapoint){if(!surfaces||!index||index>=surfaces.length)return null;for(var i=index;i<surfaces.length;i++)if(null!==surfaces[i].values[datapoint])return surfaces[i].values[datapoint];return null}(baseIndex_1,surfaces,j):null;return[p[0],surface.values[j],baseValue]}))})}return acc}),{});return areas}(trajectory,stratigraphies,stratColumn),groups=function(stratGroups,surfaceAreas){var groups=Array.from(stratGroups.values()).sort((function(a,b){return a.age-b.age})).filter((function(g){var surfaces=surfaceAreas[g.name],isValid=surfaces&&surfaces.length>0;return isValid||console.warn("Intersection surface group '".concat(g.name,"' has no valid entries and will be discarded.")),isValid})).map((function(g,i){var top=surfaceAreas[g.name][0];return{id:g.name,label:g.name,color:unassignedColorScale(i),top:top.data.map((function(d){return d[1]}))}}));return groups}(stratGroups,surfaceAreas),groupAreas=function(groups,trajectory){var groupAreas=groups.map((function(g,i){var next=i+1<groups.length?groups[i+1]:null;return{id:g.id,label:g.label,color:convertColor(g.color),data:trajectory.map((function(p,j){return[p[0],g.top[j],next?next.top[j]:null]}))}}));return groupAreas}(groups,trajectory);return{lines:lines,areas:__spreadArray(__spreadArray([],groupAreas,!0),Object.values(surfaceAreas).flat().filter((function(d){return!d.exclude})),!0)}}function findStratcolumnUnit(units,unitname,path){void 0===path&&(path=[]);var unit=units.find((function(u){return u.identifier.toLowerCase()===unitname.toLowerCase()}));if(unit){var temp_1=unit;do{path.unshift(temp_1),temp_1=units.find((function(u){return u.identifier===temp_1.stratUnitParent}))}while(temp_1);return unit}return null}function getColorFromUnit(unit){return null===unit.colorR||null===unit.colorG||null===unit.colorB?2147483648:unit.colorR<<16|unit.colorG<<8|unit.colorB}var unassignedColorScale=scaleOrdinal().domain([0,100]).range(quantize(interpolateRgb("#e6f1cf","#85906d"),10));function isAnchestor(descendant,candidate,stratColumn){var path=[];return findStratcolumnUnit(stratColumn,descendant.name,path),path.some((function(p){return candidate.name===p.identifier}))}function generateProjectedWellborePath(poslog){if(!poslog||0===poslog.length)return[];var projection=simplify(projectCurtain(poslog?poslog.map((function(p){return[p.easting,p.northing,p.tvd,p.md]})):[])),offset=projection[projection.length-1][0];return projection.forEach((function(p,i){projection[i][0]=offset-p[0]})),projection}function generateProjectedTrajectory(poslog,defaultIntersectionAngle){if(!poslog||0===poslog.length)return[];var points=poslog?poslog.map((function(p){return[p.easting,p.northing,p.tvd,p.md]})):[],interpolator=new CurveInterpolator(points,{tension:.75,arcDivisions:5e3}),displacement=interpolator.length,nPoints=Math.round(10*displacement),path=null;if(nPoints>0){path=simplify(interpolator.getPoints(nPoints),5e-4,10)}else path=[[points[0][0],points[0][1]]];var first=path[0],last=path[path.length-1],relativeDist=Vector2.distance(first,last),v=null;if(relativeDist<150){var radCurtainDirection=defaultIntersectionAngle/180*Math.PI;v=new Vector2(Math.cos(radCurtainDirection),Math.sin(radCurtainDirection)).mutable}else v=function(path,threshold){for(var res=Vector2.zero.mutable,len=0,temp=Vector2.zero.mutable,i=0;i<path.length-1;i++){var index=path.length-1-i;if(temp.set(path[index]).sub(path[index-1]),res.add(temp),(len=res.magnitude)>threshold)break}if(0===len)return new Vector2([0,0]);return res.scale(1/len)}(path,30);var extensionLengthStart=Math.max(0,1e3-displacement),offset=extensionLengthStart+displacement,trajectory=[],firstPoints=[],initial=v.toArray();extensionLengthStart>0&&((firstPoints=seqI(Math.ceil(.1*extensionLengthStart)).map((function(t){return v.set(initial).scale(extensionLengthStart*(1-t)).subFrom(first).toArray()}))).pop(),trajectory.push.apply(trajectory,firstPoints)),trajectory.push.apply(trajectory,path);var endPoints=seqI(Math.ceil(100)).map((function(t){return v.set(initial).scale(1e3*t).add(last).toArray()})).splice(1);return trajectory.push.apply(trajectory,endPoints),projectCurtain(trajectory,null,offset)}function simplify(inputArr,maxOffset,maxDistance){var _a;if(void 0===maxOffset&&(maxOffset=.001),void 0===maxDistance&&(maxDistance=10),inputArr.length<=4)return inputArr;for(var _b=inputArr[0],o0=_b[0],o1=_b[1],arr=inputArr.map((function(d){return[d[0]-o0,d[1]-o1]})),_c=arr[0],a0=_c[0],a1=_c[1],sim=[inputArr[0]],i=1;i+1<arr.length;i++){var _d=arr[i],t0=_d[0],t1=_d[1],_e=arr[i+1],b0=_e[0],b1=_e[1];if(b0-t0!=0||b1-t1!=0){var proximity=Math.abs(a0*b1-a1*b0+b0*t1-b1*t0+a1*t0-a0*t1)/Math.sqrt(Math.pow(b0-a0,2)+Math.pow(b1-a1,2)),dir=[a0-t0,a1-t1],len=Math.sqrt(Math.pow(dir[0],2)+Math.pow(dir[1],2));(proximity>maxOffset||len>=maxDistance)&&(sim.push([t0+o0,t1+o1]),a0=(_a=[t0,t1])[0],a1=_a[1])}}var last=arr[arr.length-1];return sim.push([last[0]+o0,last[1]+o1]),sim}function projectCurtain(points,origin,offset){void 0===origin&&(origin=null),void 0===offset&&(offset=0);var p0=origin||points[0],l=0;return points.map((function(p1){var dx=p1[0]-p0[0],dy=p1[1]-p0[1];return l+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2)),p0=p1,[offset>0?offset-l:l,p1[2]||0]}))}var GeomodelLabelsLayer=function(_super){function GeomodelLabelsLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.defaultMargins=18,_this.defaultMinFontSize=8,_this.defaultMaxFontSize=13,_this.defaultTextColor="black",_this.defaultFont="Arial",_this.isLabelsOnLeftSide=!0,_this.maxFontSizeInWorldCoordinates=70,_this.isXFlipped=!1,_this.areasWithAvgTopDepth=null,_this.drawAreaLabel=function(surfaceArea,nextSurfaceArea,surfaces,i){var data=surfaceArea.data,_a=_this,ctx=_a.ctx,maxFontSizeInWorldCoordinates=_a.maxFontSizeInWorldCoordinates,isXFlipped=_a.isXFlipped,_b=_this.rescaleEvent,xScale=_b.xScale,yScale=_b.yScale,xRatio=_b.xRatio,yRatio=_b.yRatio,zFactor=_b.zFactor,isLabelsOnLeftSide=_this.checkDrawLabelsOnLeftSide(),marginsInWorldCoords=(_this.options.margins||_this.defaultMargins)*(isXFlipped?-1:1)/xRatio,minFontSize=_this.options.minFontSize||_this.defaultMinFontSize,fontSizeInWorldCoords=(_this.options.maxFontSize||_this.defaultMaxFontSize)/yRatio;fontSizeInWorldCoords>maxFontSizeInWorldCoordinates&&(fontSizeInWorldCoords=maxFontSizeInWorldCoordinates)*yRatio<minFontSize&&(fontSizeInWorldCoords=minFontSize/yRatio);var leftEdge=xScale.invert(xScale.range()[0])+marginsInWorldCoords,rightEdge=xScale.invert(xScale.range()[1])-marginsInWorldCoords,_c=_this.getSurfacesAreaEdges(),surfaceAreaLeftEdge=_c[0],surfaceAreaRightEdge=_c[1];ctx.save(),ctx.font="".concat(fontSizeInWorldCoords*yRatio,"px ").concat(_this.options.font||_this.defaultFont);var startPos,labelMetrics=ctx.measureText(surfaceArea.label),labelLengthInWorldCoords=labelMetrics.width/xRatio;if(isLabelsOnLeftSide){var labelRightEdge=leftEdge+(isXFlipped?-labelLengthInWorldCoords:labelLengthInWorldCoords);(!isXFlipped&&labelRightEdge>surfaceAreaRightEdge||isXFlipped&&labelRightEdge<surfaceAreaRightEdge)&&(isLabelsOnLeftSide=!1)}else{var labelLeftEdge=rightEdge+(isXFlipped?labelLengthInWorldCoords:-labelLengthInWorldCoords);(!isXFlipped&&labelLeftEdge<surfaceAreaLeftEdge||isXFlipped&&labelLeftEdge>surfaceAreaLeftEdge)&&(isLabelsOnLeftSide=!0)}startPos=isLabelsOnLeftSide?isXFlipped?Math.min(surfaceAreaLeftEdge,leftEdge):Math.max(surfaceAreaLeftEdge,leftEdge):isXFlipped?Math.max(surfaceAreaRightEdge,rightEdge):Math.min(surfaceAreaRightEdge,rightEdge);var topEdge=yScale.invert(yScale.range()[0]),bottomEdge=yScale.invert(yScale.range()[1]),posStep=labelLengthInWorldCoords/3*.07*(isLabelsOnLeftSide?1:-1)*(isXFlipped?-1:1),dirStep=labelLengthInWorldCoords/5*(isLabelsOnLeftSide?1:-1)*(isXFlipped?-1:1),topData=data.map((function(d){return[d[0],d[1]]})),topPos=_this.calcPos(topData,startPos,3,posStep,topEdge,bottomEdge);if(topPos){var bottomData=data.map((function(d){return[d[0],d[2]]})),bottomPos=_this.calcPos(bottomData,startPos,3,posStep,topEdge,bottomEdge,nextSurfaceArea?nextSurfaceArea.data.map((function(d){return[d[0],d[1]]})):null,surfaces,i);bottomPos||(bottomPos=new Vector2(topPos.x,bottomEdge));var thickness=bottomPos.y-topPos.y;if(thickness<fontSizeInWorldCoords){if(thickness*yRatio<minFontSize)return;fontSizeInWorldCoords=thickness,ctx.font="".concat(fontSizeInWorldCoords*yRatio,"px ").concat(_this.options.font||_this.defaultFont),labelLengthInWorldCoords=(labelMetrics=ctx.measureText(surfaceArea.label)).width/xRatio}var initialDirVec=isLabelsOnLeftSide!==isXFlipped?Vector2.right:Vector2.left,areaDir=_this.calcAreaDir(topData,bottomData,startPos,5,dirStep,initialDirVec,topEdge,bottomEdge,0,Math.PI/4,4,nextSurfaceArea?nextSurfaceArea.data.map((function(d){return[d[0],d[1]]})):null,surfaces,i),scaledAngle=Math.atan(Math.tan(areaDir)*zFactor),textX=startPos,textY=(topPos.y+bottomPos.y)/2,textAngle=isXFlipped?-scaledAngle:scaledAngle;ctx.textAlign=isLabelsOnLeftSide?"left":"right",ctx.translate(xScale(textX),yScale(textY)),ctx.rotate(textAngle),ctx.fillStyle=_this.options.textColor||_this.defaultTextColor,ctx.font="".concat(fontSizeInWorldCoords*yRatio,"px ").concat(_this.options.font||_this.defaultFont),ctx.textBaseline="middle",ctx.fillText(surfaceArea.label,0,0),ctx.restore()}},_this.drawLineLabel=function(s){var _a=_this,ctx=_a.ctx,isXFlipped=_a.isXFlipped,_b=_this.rescaleEvent,xScale=_b.xScale,yScale=_b.yScale,xRatio=_b.xRatio,yRatio=_b.yRatio,zFactor=_b.zFactor,isLabelsOnLeftSide=_this.checkDrawLabelsOnLeftSide(),marginsInWorldCoords=_this.getMarginsInWorldCoordinates(),fontSizeInWorldCoords=(_this.options.maxFontSize||_this.defaultMaxFontSize)/yRatio;ctx.save(),ctx.font="".concat(fontSizeInWorldCoords*yRatio,"px ").concat(_this.options.font||_this.defaultFont);var startPos,labelLengthInWorldCoords=ctx.measureText(s.label).width/xRatio,leftEdge=xScale.invert(xScale.range()[0])+marginsInWorldCoords,rightEdge=xScale.invert(xScale.range()[1])-marginsInWorldCoords,_c=_this.getSurfacesAreaEdges(),surfaceAreaLeftEdge=_c[0],surfaceAreaRightEdge=_c[1];startPos=isLabelsOnLeftSide?isXFlipped?Math.max(surfaceAreaRightEdge,rightEdge):Math.min(surfaceAreaRightEdge,rightEdge):isXFlipped?Math.min(surfaceAreaLeftEdge,leftEdge):Math.max(surfaceAreaLeftEdge,leftEdge);var step=labelLengthInWorldCoords/5*(isLabelsOnLeftSide?-1:1),data=s.data,pos=_this.calcPos(data,startPos,5,step),dir=_this.calcLineDir(data,startPos,5,step,zFactor,isLabelsOnLeftSide?Vector2.left:Vector2.right);if(pos&&dir){var textX=startPos,textY=pos.y-1-fontSizeInWorldCoords/2,textDir=Vector2.angleRight(dir)-(isLabelsOnLeftSide?Math.PI:0);ctx.textAlign=isLabelsOnLeftSide?"right":"left",ctx.translate(xScale(textX),yScale(textY)),ctx.rotate(textDir),ctx.fillStyle=_this.colorToCSSColor(s.color),ctx.textBaseline="middle",ctx.fillText(s.label,0,0),ctx.restore()}},_this.render=_this.render.bind(_this),_this.getMarginsInWorldCoordinates=_this.getMarginsInWorldCoordinates.bind(_this),_this.getSurfacesAreaEdges=_this.getSurfacesAreaEdges.bind(_this),_this.updateXFlipped=_this.updateXFlipped.bind(_this),_this.generateSurfacesWithAvgDepth=_this.generateSurfacesWithAvgDepth.bind(_this),_this}return __extends(GeomodelLabelsLayer,_super),Object.defineProperty(GeomodelLabelsLayer.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),GeomodelLabelsLayer.prototype.setData=function(data){_super.prototype.setData.call(this,data),this.areasWithAvgTopDepth=null},GeomodelLabelsLayer.prototype.generateSurfacesWithAvgDepth=function(){var areas=this.data.areas;this.areasWithAvgTopDepth=areas.reduce((function(acc,area){if(!area.label)return acc;var sumAndCount=area.data.reduce((function(a,d){return null!=d[1]&&(a.sum+=d[1],a.count++),a}),{sum:0,count:0});if(0===sumAndCount.count)return acc;var avgTopDepth=sumAndCount.sum/sumAndCount.count;return acc.push(__assign(__assign({},area),{avgTopDepth:avgTopDepth})),acc}),[])},GeomodelLabelsLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event)},GeomodelLabelsLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.render()},GeomodelLabelsLayer.prototype.onRescale=function(event){this.rescaleEvent=event,this.updateXFlipped(),this.resetTransform(),this.render()},GeomodelLabelsLayer.prototype.render=function(){var _this=this;this.rescaleEvent&&requestAnimationFrame((function(){_this.clearCanvas(),_this.data&&(_this.areasWithAvgTopDepth||_this.generateSurfacesWithAvgDepth(),_this.drawAreaLabels(),_this.drawLineLabels())}))},GeomodelLabelsLayer.prototype.drawAreaLabels=function(){var _this=this;this.areasWithAvgTopDepth.forEach((function(s,i,array){var topmostSurfaceNotDrawnYet=array.reduce((function(acc,v,index){return index>i&&(null==acc||v.avgTopDepth<acc.avgTopDepth)&&(acc=v),acc}),null);topmostSurfaceNotDrawnYet&&_this.drawAreaLabel(s,topmostSurfaceNotDrawnYet,array,i)}))},GeomodelLabelsLayer.prototype.drawLineLabels=function(){var _this=this;this.data.lines.filter((function(surfaceLine){return surfaceLine.label})).forEach((function(surfaceLine){return _this.drawLineLabel(surfaceLine)}))},GeomodelLabelsLayer.prototype.colorToCSSColor=function(color){if("string"==typeof color)return color;var hexString=color.toString(16);return hexString="000000".substr(0,6-hexString.length)+hexString,"#".concat(hexString)},GeomodelLabelsLayer.prototype.calcPos=function(data,offset,count,step,topLimit,bottomLimit,alternativeSurfaceData,surfaces,currentSurfaceIndex){void 0===topLimit&&(topLimit=null),void 0===bottomLimit&&(bottomLimit=null),void 0===alternativeSurfaceData&&(alternativeSurfaceData=null),void 0===surfaces&&(surfaces=null),void 0===currentSurfaceIndex&&(currentSurfaceIndex=null);for(var pos=Vector2.zero.mutable,samples=0,i=0;i<count;i++){var x=offset+i*step,y=findSampleAtPos(data,x,topLimit,bottomLimit);if(y){var alternativeY=this.getAlternativeYValueIfAvailable(x,topLimit,bottomLimit,alternativeSurfaceData,surfaces,currentSurfaceIndex),usedY=alternativeY?Math.min(y,alternativeY):y;pos.add(x,usedY),samples++}}return 0===samples?null:Vector2.divide(pos,samples)},GeomodelLabelsLayer.prototype.getAlternativeYValueIfAvailable=function(x,topLimit,bottomLimit,alternativeSurfaceData,surfaces,currentSurfaceIndex){if(!alternativeSurfaceData)return null;var altY=findSampleAtPos(alternativeSurfaceData,x,topLimit,bottomLimit);if(null==altY&&surfaces&&null!=currentSurfaceIndex)for(var si=currentSurfaceIndex+1;null==altY&&si<surfaces.length;){altY=findSampleAtPos(surfaces[si++].data.map((function(d){return[d[0],d[1]]})),x,topLimit,bottomLimit)}return altY},GeomodelLabelsLayer.prototype.calcLineDir=function(data,offset,count,step,zFactor,initalVector,topLimit,bottomLimit){void 0===initalVector&&(initalVector=Vector2.left),void 0===topLimit&&(topLimit=null),void 0===bottomLimit&&(bottomLimit=null);var dir=initalVector.mutable,startY=findSampleAtPos(data,offset,topLimit,bottomLimit);if(null===startY)return dir;for(var vecAtEnd=new Vector2(offset,startY*zFactor),tmpVec=Vector2.zero.mutable,i=1;i<=count;i++){var x=offset+i*step,y=findSampleAtPos(data,offset,topLimit,bottomLimit);null!==y&&(tmpVec.set(x,y*zFactor),tmpVec.sub(vecAtEnd),dir.add(tmpVec))}return dir},GeomodelLabelsLayer.prototype.calcAreaDir=function(top,bottom,offset,count,step,initalVector,topLimit,bottomLimit,minReductionAngle,maxReductionAngle,angleReductionExponent,alternativeSurfaceBottomData,surfaces,currentSurfaceIndex){void 0===initalVector&&(initalVector=Vector2.left),void 0===topLimit&&(topLimit=null),void 0===bottomLimit&&(bottomLimit=null),void 0===minReductionAngle&&(minReductionAngle=0),void 0===maxReductionAngle&&(maxReductionAngle=Math.PI/4),void 0===angleReductionExponent&&(angleReductionExponent=4),void 0===alternativeSurfaceBottomData&&(alternativeSurfaceBottomData=null),void 0===surfaces&&(surfaces=null),void 0===currentSurfaceIndex&&(currentSurfaceIndex=null);for(var vecAtEnd,angles=[],tmpVec=Vector2.zero.mutable,i=0;i<=count;i++){var x=offset+i*step,topY=findSampleAtPos(top,x,topLimit,bottomLimit),bottomY=findSampleAtPos(bottom,x,topLimit,bottomLimit)||bottomLimit,alternativeBottomY=this.getAlternativeYValueIfAvailable(x,topLimit,bottomLimit,alternativeSurfaceBottomData,surfaces,currentSurfaceIndex),usedBottomY=alternativeBottomY?Math.min(bottomY,alternativeBottomY):bottomY;if(0===i){if(null===topY)return Vector2.angleRight(initalVector);vecAtEnd=new Vector2(offset,(topY+usedBottomY)/2)}else null!==topY?(tmpVec.set(x,(topY+usedBottomY)/2),tmpVec.sub(vecAtEnd),angles.push(Vector2.angleRight(tmpVec))):angles.push(Vector2.angleRight(initalVector))}var refAngle=angles[0],offsetAngles=angles.map((function(d){return d-refAngle})),factors=0;return offsetAngles.reduce((function(acc,v){var ratio=(Math.abs(v)-minReductionAngle)/maxReductionAngle,factor=Math.pow(1-clamp(ratio,0,1),angleReductionExponent);return factors+=factor,acc+v*factor}),0)/factors+refAngle},GeomodelLabelsLayer.prototype.updateXFlipped=function(){var xBounds=this.rescaleEvent.xBounds;this.isXFlipped=xBounds[0]>xBounds[1]},GeomodelLabelsLayer.prototype.getMarginsInWorldCoordinates=function(){var xRatio=this.rescaleEvent.xRatio;return(this.options.margins||this.defaultMargins)*(this.isXFlipped?-1:1)/xRatio},GeomodelLabelsLayer.prototype.getSurfacesAreaEdges=function(){var endPoints=this.data.areas.reduce((function(acc,area){var data=area.data,firstValidPoint=data.find((function(d){return null!=d[1]}));firstValidPoint&&acc.push(firstValidPoint[0]);for(var i=data.length-1;i>=0;i--)if(null!=data[i][1]){acc.push(data[i][0]);break}return acc}),[]);endPoints.push.apply(endPoints,this.data.lines.reduce((function(acc,line){var data=line.data,firstValidPoint=data.find((function(d){return null!=d[1]}));firstValidPoint&&acc.push(firstValidPoint[0]);for(var i=data.length-1;i>=0;i--)if(null!=data[i][1]){acc.push(data[i][0]);break}return acc}),[]));var minX=Math.min.apply(Math,endPoints),maxX=Math.max.apply(Math,endPoints),marginsInWorldCoords=this.getMarginsInWorldCoordinates(),isXFlipped=this.isXFlipped;return[isXFlipped?maxX+marginsInWorldCoords:minX+marginsInWorldCoords,isXFlipped?minX-marginsInWorldCoords:maxX-marginsInWorldCoords]},GeomodelLabelsLayer.prototype.checkDrawLabelsOnLeftSide=function(){var referenceSystem=this.referenceSystem,isXFlipped=this.isXFlipped;if(!referenceSystem)return!0;var _b=this.rescaleEvent,xScale=_b.xScale,yScale=_b.yScale,xRatio=_b.xRatio,_c=xScale.domain(),dx1=_c[0],dx2=_c[1],_d=yScale.domain(),dy1=_d[0],dy2=_d[1],top=referenceSystem.interpolators.curtain.lookup(dy1,1,0);0===top.length&&(top=[referenceSystem.interpolators.curtain.getPointAt(0)]);var bottom=referenceSystem.interpolators.curtain.lookup(dy2,1,0);0===bottom.length&&(bottom=[referenceSystem.interpolators.curtain.getPointAt(1)]);var maxX=Math.max(top[0][0],bottom[0][0]),minX=Math.min(top[0][0],bottom[0][0]),wbBBox_left=isXFlipped?maxX:minX,wbBBox_right=isXFlipped?minX:maxX,margin=this.getMarginsInWorldCoordinates(),screenLeftEdge=dx1+margin,screenRightEdge=dx2-margin,_e=this.getSurfacesAreaEdges(),surfaceAreaLeftEdge=_e[0],surfaceAreaRightEdge=_e[1],leftLimit=isXFlipped?Math.min(screenLeftEdge,surfaceAreaLeftEdge):Math.max(screenLeftEdge,surfaceAreaLeftEdge),rightLimit=isXFlipped?Math.max(screenRightEdge,surfaceAreaRightEdge):Math.min(screenRightEdge,surfaceAreaRightEdge),spaceOnLeftSide=Math.max(isXFlipped?leftLimit-wbBBox_left:wbBBox_left-leftLimit,0),spaceOnRightSide=Math.max(isXFlipped?wbBBox_right-rightLimit:rightLimit-wbBBox_right,0),spaceOnLeftSideInScreenCoordinates=spaceOnLeftSide*xRatio;return spaceOnLeftSide>spaceOnRightSide||spaceOnLeftSideInScreenCoordinates>200||spaceOnLeftSideInScreenCoordinates<200&&spaceOnRightSide*xRatio<200&&isXFlipped||bottom[0][1]<dy1},GeomodelLabelsLayer}(CanvasLayer),GeomodelLayerV2=function(_super){function GeomodelLayerV2(){var _this=null!==_super&&_super.apply(this,arguments)||this;return _this.isPreRendered=!1,_this.createPolygons=function(data){for(var polygons=[],polygon=null,i=0;i<data.length;i++){var topIsValid=!!data[i][1];topIsValid&&(null===polygon&&(polygon=[]),polygon.push(data[i][0],data[i][1]));var endIsReached=i===data.length-1;if((!topIsValid||endIsReached)&&polygon){for(var j=topIsValid?i:i-1;j>=0&&data[j][1];j--)polygon.push(data[j][0],data[j][2]||1e4);polygons.push(polygon),polygon=null}}return polygons},_this.generateAreaPolygon=function(s){var g=new Graphics;g.lineStyle(1,s.color,1),g.beginFill(s.color),_this.createPolygons(s.data).forEach((function(polygon){return g.drawPolygon(polygon)})),g.endFill(),_this.addChild(g)},_this.generateSurfaceLine=function(s){var g=new Graphics,d=s.data;g.lineStyle(1,s.color,1,.5,!0);for(var penDown=!1,i=0;i<d.length;i++)d[i][1]?penDown?g.lineTo(d[i][0],d[i][1]):(g.moveTo(d[i][0],d[i][1]),penDown=!0):penDown=!1;_this.addChild(g)},_this}return __extends(GeomodelLayerV2,_super),GeomodelLayerV2.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.isPreRendered||(this.clearLayer(),this.preRender()),this.render()},GeomodelLayerV2.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.isPreRendered=!1,this.clearLayer(),this.preRender(),this.render()},GeomodelLayerV2.prototype.preRender=function(){var _this=this,data=this.data;data&&(data.areas.forEach((function(a){return _this.generateAreaPolygon(a)})),data.lines.forEach((function(l){return _this.generateSurfaceLine(l)})),this.isPreRendered=!0)},GeomodelLayerV2}(PixiLayer),defaultOptions={minorColor:"lightgray",majorColor:"gray",minorWidth:.25,majorWidth:.75},GridLayer=function(_super){function GridLayer(id,options){var _this=_super.call(this,id,options)||this;return _this._offsetX=0,_this._offsetY=0,_this.options=__assign(__assign({},_this.options),options||defaultOptions),_this.render=_this.render.bind(_this),_this}return __extends(GridLayer,_super),GridLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.render(event)},GridLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.render(event)},GridLayer.prototype.render=function(event){var ctx=this.ctx,_a=this.options,minorWidth=_a.minorWidth,minorColor=_a.minorColor,majorWidth=_a.majorWidth,majorColor=_a.majorColor;if(ctx&&(this.clearCanvas(),event.xScale||event.yScale)){var xScale=event.xScale.copy(),yScale=event.yScale.copy(),xDomain=xScale.domain(),yDomain=yScale.domain(),offsetX=this.offsetX,offsetY=this.offsetY;xScale.domain([xDomain[0]-offsetX,xDomain[1]-offsetX]),yScale.domain([yDomain[0]-offsetY,yDomain[1]-offsetY]);var _b=xScale.range(),rx1=_b[0],rx2=_b[1],_c=yScale.range(),ry1=_c[0],ry2=_c[1];ctx.lineWidth=minorWidth||.25,ctx.strokeStyle=minorColor||"lightgray";var xminticks=this.mapMinorTicks(xScale.ticks()),yminticks=this.mapMinorTicks(yScale.ticks());this.renderTicksX(xScale,xminticks,ry1,ry2),this.renderTicksY(yScale,yminticks,rx1,rx2),ctx.lineWidth=majorWidth||.75,ctx.strokeStyle=majorColor||"gray",this.renderTicksX(xScale,xScale.ticks(),ry1,ry2),this.renderTicksY(yScale,yScale.ticks(),rx1,rx2),ctx.restore()}},GridLayer.prototype.renderTicksX=function(xscale,xticks,ry1,ry2){var _this=this;xticks.forEach((function(tx){var x=xscale(tx);_this.ctx.beginPath(),_this.ctx.moveTo(x,ry1),_this.ctx.lineTo(x,ry2),_this.ctx.stroke()}))},GridLayer.prototype.renderTicksY=function(yscale,yticks,rx1,rx2){var _this=this;yticks.forEach((function(ty){var y=yscale(ty);_this.ctx.beginPath(),_this.ctx.moveTo(rx1,y),_this.ctx.lineTo(rx2,y),_this.ctx.stroke()}))},GridLayer.prototype.mapMinorTicks=function(ticks){var xminticks=[];return ticks.length>=2&&(xminticks=ticks.map((function(v){return v+(ticks[1]-ticks[0])/2}))).pop(),xminticks},Object.defineProperty(GridLayer.prototype,"offsetX",{get:function(){return this._offsetX},set:function(offset){this._offsetX=offset},enumerable:!1,configurable:!0}),Object.defineProperty(GridLayer.prototype,"offsetY",{get:function(){return this._offsetY},set:function(offset){this._offsetY=offset},enumerable:!1,configurable:!0}),GridLayer}(CanvasLayer),ImageLayer=function(_super){function ImageLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(ImageLayer,_super),ImageLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event);var img=document.createElement("img");this.img=img,this.isLoading=!0},ImageLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.img.src=event.url,this.render(event)},ImageLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.setTransform(event),this.render(event)},ImageLayer.prototype.render=function(event){var _this=this,width=parseInt(this.elm.getAttribute("width"),10),height=parseInt(this.elm.getAttribute("height"),10),xScale=event.xScale,yScale=event.yScale,xRatio=event.xRatio,yRatio=event.yRatio,x=event.x,y=event.y,calcWidth=width*(xRatio||1),calcHeight=height*(yRatio||1);this.clearCanvas(),this.isLoading?this.img.onload=function(){_this.isLoading=!1,_this.ctx.drawImage(_this.img,xScale(x||0),yScale(y||0),calcWidth,calcHeight)}:this.ctx.drawImage(this.img,xScale(x||0),yScale(y||0),calcWidth,calcHeight)},ImageLayer}(CanvasLayer),pointToVector=function(p){return new Vector2(p.x,p.y)},createNormals=function(points){return points.length<2?[new Vector2(0)]:points.map((function(_coord,i,list){if(i<list.length-1){var p=pointToVector(list[i]),rotate=pointToVector(list[i+1]).sub(p).rotate90();return n=rotate.normalized()}return n}));var n},offsetPoint=function(point,vector,offset){var v,p=pointToVector(point);return v=p.add(vector.scale(offset)),new Point(v[0],v[1])},offsetPoints=function(points,vectors,offset){if(points.length!==vectors.length)throw new Error("Number of vectors does not match number of points");return points.map((function(point,index){var vector=vectors[index];return offsetPoint(point,vector,offset)}))},makeTubularPolygon=function(rightPath,leftPath){return __spreadArray(__spreadArray([],leftPath,!0),rightPath.map((function(d){return d.clone()})).reverse(),!0)},overlaps=function(top1,bottom1,top2,bottom2){return top1<=bottom2&&top2<=bottom1},findIntersectingItems=function(start,end,otherStrings,holes){return{overlappingHoles:holes.filter((function(hole){return overlaps(start,end,hole.start,hole.end)})),overlappingOuterStrings:otherStrings.filter((function(casing){return overlaps(start,end,casing.start,casing.end)}))}},getUniqueDiameterChangeDepths=function(_a,diameterIntervals){var arr,intervalStart=_a[0],intervalEnd=_a[1],trimmedChangedDepths=diameterIntervals.flatMap((function(d){return[d.start-1e-4,d.start,d.end,d.end+1e-4]})).filter((function(d){return d>=intervalStart&&d<=intervalEnd}));return trimmedChangedDepths.push(intervalStart),trimmedChangedDepths.push(intervalEnd),(arr=trimmedChangedDepths,Array.from(new Set(arr))).sort((function(a,b){return a-b}))},getInnerStringDiameter=function(stringType){return"casing"===stringType.kind?stringType.innerDiameter:stringType.diameter},findCementOuterDiameterAtDepth=function(attachedStrings,nonAttachedStrings,holes,depth){var attachedStringAtDepth=attachedStrings.find((function(casingOrCompletion){return casingOrCompletion.start<=depth&&casingOrCompletion.end>=depth})),attachedOuterDiameter=attachedStringAtDepth?attachedStringAtDepth.diameter:0,outerCasingAtDepth=nonAttachedStrings.filter((function(casingOrCompletion){return getInnerStringDiameter(casingOrCompletion)>attachedOuterDiameter})).sort((function(a,b){return getInnerStringDiameter(a)-getInnerStringDiameter(b)})).find((function(casing){return casing.start<=depth&&casing.end>=depth})),holeAtDepth=holes.find((function(hole){return hole.start<=depth&&hole.end>=depth&&hole.diameter>attachedOuterDiameter}));return outerCasingAtDepth?getInnerStringDiameter(outerCasingAtDepth):holeAtDepth?holeAtDepth.diameter:100},createComplexRopeSegmentsForCement=function(cement,casings,completion,holes,exaggerationFactor,getPoints){var _a=splitByReferencedStrings(cement.referenceIds,casings,completion),attachedStrings=_a.attachedStrings,nonAttachedStrings=_a.nonAttachedStrings;if(0===attachedStrings.length)throw new Error("Invalid cement data, can't find referenced casing/completion string for cement with id '".concat(cement.id,"'"));attachedStrings.sort((function(a,b){return a.end-b.end}));var bottomOfCement=attachedStrings[attachedStrings.length-1].end,_b=findIntersectingItems(cement.toc,bottomOfCement,nonAttachedStrings,holes),overlappingOuterStrings=_b.overlappingOuterStrings,overlappingHoles=_b.overlappingHoles,outerDiameterIntervals=__spreadArray(__spreadArray([],overlappingOuterStrings,!0),overlappingHoles,!0).map((function(d){return{start:d.start,end:d.end}}));return getUniqueDiameterChangeDepths([cement.toc,bottomOfCement],outerDiameterIntervals).flatMap((function(depth,index,list){return index===list.length-1?[]:[{top:depth,bottom:list[index+1],diameter:findCementOuterDiameterAtDepth(attachedStrings,overlappingOuterStrings,overlappingHoles,depth)*exaggerationFactor}]})).map((function(interval){return{diameter:interval.diameter,points:getPoints(interval.top,interval.bottom)}}))},splitByReferencedStrings=function(referenceIds,casings,completion){return __spreadArray(__spreadArray([],casings,!0),completion,!0).reduce((function(acc,current){return referenceIds.includes(current.id)?__assign(__assign({},acc),{attachedStrings:__spreadArray(__spreadArray([],acc.attachedStrings,!0),[current],!1)}):__assign(__assign({},acc),{nonAttachedStrings:__spreadArray(__spreadArray([],acc.nonAttachedStrings,!0),[current],!1)})}),{attachedStrings:[],nonAttachedStrings:[]})},createComplexRopeSegmentsForCementPlug=function(plug,casings,completion,holes,exaggerationFactor,getPoints){var _a=splitByReferencedStrings(plug.referenceIds,casings,completion),attachedStrings=_a.attachedStrings,nonAttachedStrings=_a.nonAttachedStrings,_b=findIntersectingItems(plug.start,plug.end,nonAttachedStrings,holes),overlappingHoles=_b.overlappingHoles,overlappingOuterStrings=_b.overlappingOuterStrings,innerDiameterIntervals=__spreadArray(__spreadArray(__spreadArray([],attachedStrings,!0),overlappingHoles,!0),overlappingOuterStrings,!0).map((function(d){return{start:d.start,end:d.end}})),diameterIntervals=getUniqueDiameterChangeDepths([plug.start,plug.end],innerDiameterIntervals).flatMap((function(depth,index,list){if(index===list.length-1)return[];var nextDepth=list[index+1],diameterAtDepth=function(attachedStrings,nonAttachedStrings,holes,depth){var attachedStringAtDepth=attachedStrings.sort((function(a,b){return getInnerStringDiameter(a)-getInnerStringDiameter(b)})).find((function(casingOrCompletion){return casingOrCompletion.start<=depth&&casingOrCompletion.end>=depth}));if(attachedStringAtDepth)return getInnerStringDiameter(attachedStringAtDepth);var minimumDiameter=attachedStrings.length?Math.min.apply(Math,attachedStrings.map((function(c){return getInnerStringDiameter(c)}))):0,nonAttachedStringAtDepth=nonAttachedStrings.sort((function(a,b){return getInnerStringDiameter(a)-getInnerStringDiameter(b)})).find((function(casingOrCompletion){return casingOrCompletion.start<=depth&&casingOrCompletion.end>=depth&&minimumDiameter<=getInnerStringDiameter(casingOrCompletion)}));if(nonAttachedStringAtDepth)return getInnerStringDiameter(nonAttachedStringAtDepth);var holeAtDepth=holes.find((function(hole){return hole.start<=depth&&hole.end>=depth&&hole.diameter}));return holeAtDepth?holeAtDepth.diameter:100}(attachedStrings,overlappingOuterStrings,overlappingHoles,depth);return[{top:depth,bottom:nextDepth,diameter:diameterAtDepth*exaggerationFactor}]}));return diameterIntervals.map((function(interval){return{diameter:interval.diameter,points:getPoints(interval.top,interval.bottom)}}))},createTubularRenderingObject=function(radius,pathPoints){var normals=createNormals(pathPoints),rightPath=offsetPoints(pathPoints,normals,radius);return{leftPath:offsetPoints(pathPoints,normals,-radius),rightPath:rightPath}},createCasingInterval=function(start,end){return{kind:"casing",start:start,end:end}},prepareCasingRenderObject=function(exaggerationFactor,casing,getPathPoints){var exaggeratedDiameter=casing.diameter*exaggerationFactor,exaggeratedRadius=exaggeratedDiameter/2,exaggeratedInnerDiameter=casing.innerDiameter*exaggerationFactor,casingWallWidth=exaggeratedRadius-exaggeratedInnerDiameter/2,sections=function(casing){var result=(casing.windows||[]).filter((function(cw){return top1=casing.start,bottom1=casing.end,top2=cw.start,top1<cw.end&&top2<bottom1;var top1,bottom1,top2})).reduce((function(_a,currentWindow,index,list){var intervals=_a.intervals,lastBottom=_a.lastBottom,startCasingInterval=lastBottom<currentWindow.start?createCasingInterval(lastBottom,currentWindow.start):null,updatedLastBottom=startCasingInterval?startCasingInterval.end:lastBottom,windowStart=Math.max(updatedLastBottom,currentWindow.start),windowEnd=Math.min(casing.end,currentWindow.end),nextLastBottom=windowEnd,newIntervals=[startCasingInterval,{kind:"casing-window",start:windowStart,end:windowEnd},index===list.length-1&&nextLastBottom<casing.end?createCasingInterval(nextLastBottom,casing.end):null].filter((function(i){return i}));return{intervals:__spreadArray(__spreadArray([],intervals,!0),newIntervals,!0),lastBottom:nextLastBottom}}),{intervals:[],lastBottom:casing.start});return result.intervals.length?result.intervals:[createCasingInterval(casing.start,casing.end)]}(casing).map((function(casingInterval){var pathPoints=getPathPoints(casingInterval.start,casingInterval.end),_a=createTubularRenderingObject(exaggeratedRadius,pathPoints),leftPath=_a.leftPath,rightPath=_a.rightPath;return{kind:casingInterval.kind,leftPath:leftPath,rightPath:rightPath,pathPoints:pathPoints,polygon:makeTubularPolygon(leftPath,rightPath)}}));return{kind:"casing",id:casing.id,referenceDiameter:exaggeratedDiameter,referenceRadius:exaggeratedRadius,sections:sections,casingWallWidth:casingWallWidth,hasShoe:casing.hasShoe,bottom:casing.end}},createComplexRopeSegmentsForPerforation=function(perforation,casings,holes,exaggerationFactor,getPoints){var _a=findIntersectingItems(perforation.start,perforation.end,casings,holes),overlappingOuterStrings=_a.overlappingOuterStrings,overlappingHoles=_a.overlappingHoles,outerDiameterIntervals=__spreadArray(__spreadArray([],overlappingOuterStrings,!0),overlappingHoles,!0).map((function(d){return{start:d.start,end:d.end}})),diameterIntervals=getUniqueDiameterChangeDepths([perforation.start,perforation.end],outerDiameterIntervals).flatMap((function(depth,index,list){if(index===list.length-1)return[];var nextDepth=list[index+1],diameterAtDepth=function(nonAttachedStrings,holes,depth,perforationSubKind){var outerCasingAtDepth=nonAttachedStrings.sort((function(a,b){return b.diameter-a.diameter})).find((function(casing){return casing.start<=depth&&casing.end>=depth})),holeAtDepth=holes.find((function(hole){return hole.start<=depth&&hole.end>=depth}));return outerCasingAtDepth&&"Open hole frac pack"!==perforationSubKind&&"Open hole gravel pack"!==perforationSubKind?getInnerStringDiameter(outerCasingAtDepth):holeAtDepth?holeAtDepth.diameter:100}(overlappingOuterStrings,overlappingHoles,depth,perforation.subKind);return[{top:depth,bottom:nextDepth,diameter:diameterAtDepth*exaggerationFactor}]}));return diameterIntervals.map((function(interval){var points=getPoints(interval.top,interval.bottom);return{diameter:interval.diameter,points:points}}))},drawPacking=function(canvas,ctx,perforationOptions){var packingOpacity=perforationOptions.packingOpacity,yellow=perforationOptions.yellow;ctx.fillStyle=yellow,ctx.strokeStyle=yellow;var wh=[canvas.width,canvas.height];ctx.save(),ctx.globalAlpha=packingOpacity,ctx.fillRect.apply(ctx,__spreadArray(__spreadArray([],[0,0],!1),wh,!1)),ctx.restore()},drawFracLines=function(canvas,ctx,extendedPerfShapeDiameter,perforationOptions,startAt){var fracLineCurve=perforationOptions.fracLineCurve,spikeWidth=canvas.width/10,diameter=extendedPerfShapeDiameter/3*perforationOptions.scalingFactor,fracLineLength=diameter/4,offsetY="diameter"===startAt?0:diameter/2,fracLines=function(){for(var i=-1;i<10;i++){var bottom=[i*spikeWidth+0+spikeWidth/2,canvas.height/2-fracLineLength-offsetY-fracLineLength];ctx.beginPath();var start=__spreadArray([],bottom,!0),controlPoint1=[bottom[0]-2*fracLineCurve,bottom[1]-fracLineLength/4],middle=[bottom[0],bottom[1]-fracLineLength/2],controlPoint2=[bottom[0]+2*fracLineCurve,bottom[1]-fracLineLength/2-fracLineLength/4],end=[bottom[0],bottom[1]-fracLineLength];ctx.bezierCurveTo.apply(ctx,__spreadArray(__spreadArray(__spreadArray([],start,!1),controlPoint1,!1),middle,!1)),ctx.bezierCurveTo.apply(ctx,__spreadArray(__spreadArray(__spreadArray([],middle,!1),controlPoint2,!1),end,!1)),ctx.stroke()}for(i=-1;i<10;i++){bottom=[i*spikeWidth+spikeWidth+0+spikeWidth/2,canvas.height/2+diameter/2+offsetY];ctx.beginPath();start=__spreadArray([],bottom,!0),controlPoint1=[bottom[0]-2*fracLineCurve,bottom[1]+fracLineLength/4],middle=[bottom[0],bottom[1]+fracLineLength/2],controlPoint2=[bottom[0]+2*fracLineCurve,bottom[1]+fracLineLength/2+fracLineLength/4],end=[bottom[0],bottom[1]+fracLineLength];ctx.bezierCurveTo.apply(ctx,__spreadArray(__spreadArray(__spreadArray([],start,!1),controlPoint1,!1),middle,!1)),ctx.bezierCurveTo.apply(ctx,__spreadArray(__spreadArray(__spreadArray([],middle,!1),controlPoint2,!1),end,!1)),ctx.stroke()}};ctx.strokeStyle=perforationOptions.yellow,ctx.lineWidth=6,ctx.save(),ctx.globalAlpha=perforationOptions.packingOpacity,fracLines(),ctx.restore(),ctx.lineWidth=1,ctx.strokeStyle=perforationOptions.outline,fracLines(),ctx.closePath()},errorTexture=function(errorMessage,existingContext){void 0===errorMessage&&(errorMessage="Error!"),console.error("".concat(errorMessage));var canvas=(null==existingContext?void 0:existingContext.canvas)||document.createElement("canvas");canvas.width=32,canvas.height=64;var canvasCtx=(null==existingContext?void 0:existingContext.canvasCtx)||canvas.getContext("2d"),wh=[canvas.width,canvas.height];return canvasCtx.fillStyle="#ff00ff",canvasCtx.fillRect.apply(canvasCtx,__spreadArray(__spreadArray([],[0,0],!1),wh,!1)),new Texture(Texture.from(canvas,{wrapMode:WRAP_MODES.CLAMP}).baseTexture,null,new Rectangle(0,0,canvas.width,canvas.height),null,groupD8.MIRROR_HORIZONTAL)},createPerforationCanvas=function(perfShape,options){var canvas=document.createElement("canvas"),size=perfShape.diameter*options.scalingFactor;canvas.width=size/2,canvas.height=size;var ctx=canvas.getContext("2d");return{canvas:canvas,ctx:ctx}},createPerforationTexture=function(canvas){return new Texture(Texture.from(canvas,{wrapMode:WRAP_MODES.CLAMP}).baseTexture,null,new Rectangle(0,0,canvas.width,canvas.height),null,groupD8.MIRROR_HORIZONTAL)},createSubkindPerforationTexture_packing=function(){return errorTexture()},createSubkindPerforationTexture_fracLines=function(){return errorTexture()},createSubkindPerforationTexture_spikes=function(perforation,perfShape,otherPerforations,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx,intersectionsWithCasedHoleGravel=otherPerforations.some((function(perf){return isSubkindCasedHoleGravelPack(perf)&&intersect(perforation,perf)})),intersectionsWithCasedHoleFracPack=otherPerforations.some((function(perf){return isSubKindCasedHoleFracPack(perf)&&intersect(perforation,perf)}));return intersectionsWithCasedHoleGravel||intersectionsWithCasedHoleFracPack?perforation.isOpen?(ctx.fillStyle=perforationOptions.yellow,ctx.strokeStyle=perforationOptions.yellow):(ctx.fillStyle=perforationOptions.grey,ctx.strokeStyle=perforationOptions.grey):perforation.isOpen?(ctx.fillStyle=perforationOptions.red,ctx.strokeStyle=perforationOptions.red):(ctx.fillStyle=perforationOptions.grey,ctx.strokeStyle=perforationOptions.grey),function(canvas,ctx,extendedPerfShapeDiameter,perforationOptions){var spikeWidth=canvas.width/10;ctx.strokeStyle=perforationOptions.outline;var diameter=extendedPerfShapeDiameter/3*perforationOptions.scalingFactor;ctx.lineWidth=1;for(var spikeLength=diameter/2,i=0;i<=10;i++){var bottom=[(left=[i*spikeWidth+0,canvas.height/2-diameter/2])[0]-spikeWidth/2,left[1]-spikeLength],right=[left[0]-spikeWidth,left[1]];ctx.beginPath(),ctx.moveTo.apply(ctx,left),ctx.lineTo.apply(ctx,bottom),ctx.lineTo.apply(ctx,right),ctx.fill(),ctx.lineWidth=1,ctx.stroke()}for(i=0;i<=10;i++){var left;bottom=[(left=[i*spikeWidth+0,canvas.height/2+diameter/2])[0]-spikeWidth/2,left[1]+spikeLength],right=[left[0]-spikeWidth,left[1]],ctx.beginPath(),ctx.moveTo.apply(ctx,left),ctx.lineTo.apply(ctx,bottom),ctx.lineTo.apply(ctx,right),ctx.fill(),ctx.lineWidth=1,ctx.stroke()}ctx.closePath()}(canvas,ctx,perfShape.diameter,perforationOptions),intersectionsWithCasedHoleFracPack&&drawFracLines(canvas,ctx,perfShape.diameter,perforationOptions,"spike"),createPerforationTexture(canvas)},createSubkindCasedHoleFracturationTexture_fracLines=function(perfShape,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawFracLines(canvas,ctx,perfShape.diameter,perforationOptions,"diameter"),createPerforationTexture(canvas)},createSubkindCasedHoleFracturationTexture_spikes=function(){return errorTexture()},createSubkindCasedHoleFracPackTexture_packing=function(perfShape,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawPacking(canvas,ctx,perforationOptions),createPerforationTexture(canvas)},createSubkindCasedHoleFracPackTexture_fracLines=function(perfShape,perforationOptions){var canvas=createPerforationCanvas(perfShape,perforationOptions).canvas;return createPerforationTexture(canvas)},createSubkindCasedHoleFracPackTexture_spikes=function(){return errorTexture()},createSubkindCasedHoleGravelPackTexture_packing=function(perfShape,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawPacking(canvas,ctx,perforationOptions),createPerforationTexture(canvas)},createSubkindCasedHoleGravelPackTexture_fracLines=function(){return errorTexture()},createSubkindCasedHoleGravelPackTexture_spikes=function(){return errorTexture()},createSubkindOpenHoleGravelPackTexture_packing=function(perfShape,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawPacking(canvas,ctx,perforationOptions),createPerforationTexture(canvas)},createSubkindOpenHoleGravelPackTexture_fracLines=function(){return errorTexture()},createSubkindOpenHoleGravelPackTexture_spikes=function(){return errorTexture()},createSubkindOpenHoleFracPackTexture_packing=function(perforation,perfShape,perforationOptions){console.log({perforation:perforation});var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawPacking(canvas,ctx,perforationOptions),createPerforationTexture(canvas)},createSubkindOpenHoleFracPackTexture_fracLines=function(perfShape,perforationOptions){var _a=createPerforationCanvas(perfShape,perforationOptions),canvas=_a.canvas,ctx=_a.ctx;return drawFracLines(canvas,ctx,perfShape.diameter,perforationOptions,"diameter"),createPerforationTexture(canvas)},createSubkindOpenHoleFracPackTexture_spikes=function(){return errorTexture()},ComplexRopeGeometry=function(_super){function ComplexRopeGeometry(segments,textureScale){void 0===textureScale&&(textureScale=0);var _this=this,pointCount=sum(segments,(function(segment){return segment.points.length}));return(_this=_super.call(this,new Float32Array(4*pointCount),new Float32Array(4*pointCount),new Uint16Array(6*(pointCount-1)))||this).segments=segments,_this.textureScale=textureScale,_this.build(),_this}return __extends(ComplexRopeGeometry,_super),Object.defineProperty(ComplexRopeGeometry.prototype,"width",{get:function(){return max(this.segments,(function(segment){return segment.diameter}))},enumerable:!1,configurable:!0}),ComplexRopeGeometry.prototype.build=function(){var segments=this.segments;if(segments){var vertexBuffer=this.getBuffer("aVertexPosition"),uvBuffer=this.getBuffer("aTextureCoord"),indexBuffer=this.getIndex(),pointCount=sum(segments,(function(segment){return segment.points.length}));if(!(pointCount<1)){vertexBuffer.data.length/4!==pointCount&&(vertexBuffer.data=new Float32Array(4*pointCount),uvBuffer.data=new Float32Array(4*pointCount),indexBuffer.data=new Uint16Array(6*(pointCount-1)));var uvs=uvBuffer.data,indices=indexBuffer.data;uvs[0]=0,uvs[1]=0,uvs[2]=0,uvs[3]=1;for(var segmentCount=segments.length,maxDiameter=max(segments,(function(segment){return segment.diameter})),amount=0,uvIndex=0,indicesIndex=0,indexCount=0,i=0;i<segmentCount;i++){for(var prev=segments[i].points[0],textureWidth=maxDiameter,radius=segments[i].diameter/maxDiameter/2,total=segments[i].points.length,j=0;j<total;j++){var dx=prev.x-segments[i].points[j].x,dy=prev.y-segments[i].points[j].y,distance=Math.sqrt(dx*dx+dy*dy);prev=segments[i].points[j],amount+=distance/textureWidth,uvs[uvIndex]=amount,uvs[uvIndex+1]=.5-radius,uvs[uvIndex+2]=amount,uvs[uvIndex+3]=.5+radius,uvIndex+=4}for(j=0;j<total-1;j++)indices[indexCount++]=indicesIndex,indices[indexCount++]=indicesIndex+1,indices[indexCount++]=indicesIndex+2,indices[indexCount++]=indicesIndex+2,indices[indexCount++]=indicesIndex+1,indices[indexCount++]=indicesIndex+3,indicesIndex+=2;indicesIndex+=2}uvBuffer.update(),indexBuffer.update(),this.updateVertices()}}},ComplexRopeGeometry.prototype.updateVertices=function(){var segments=this.segments;if(!(sum(segments,(function(segment){return segment.points.length}))<1)){for(var segmentCount=segments.length,lastIndex=0,i=0;i<segmentCount;i++){for(var lastPoint=segments[i].points[0],nextPoint=void 0,perpX=0,perpY=0,vertices=this.buffers[0].data,total=segments[i].points.length,index=0,j=0;j<total;j++){var point=segments[i].points[j];index=lastIndex+4*j,perpY=-((nextPoint=j<segments[i].points.length-1?segments[i].points[j+1]:point).x-lastPoint.x),perpX=nextPoint.y-lastPoint.y;var perpLength=Math.sqrt(perpX*perpX+perpY*perpY),num=segments[i].diameter/2;perpX/=perpLength,perpY/=perpLength,perpX*=num,perpY*=num,vertices[index]=point.x+perpX,vertices[index+1]=point.y+perpY,vertices[index+2]=point.x-perpX,vertices[index+3]=point.y-perpY,lastPoint=point}lastIndex=index+4}this.buffers[0].update()}},ComplexRopeGeometry.prototype.update=function(){this.build()},ComplexRopeGeometry}(MeshGeometry),ComplexRope=function(_super){function ComplexRope(texture,segments,textureScale){void 0===textureScale&&(textureScale=0);var _this=this,ropeGeometry=new ComplexRopeGeometry(segments,textureScale),meshMaterial=new MeshMaterial(texture);return texture.baseTexture.wrapMode=WRAP_MODES.REPEAT,(_this=_super.call(this,ropeGeometry,meshMaterial)||this).autoUpdate=!0,_this}return __extends(ComplexRope,_super),ComplexRope.prototype._render=function(renderer){var geometry=this.geometry;this.autoUpdate&&geometry.update(),_super.prototype._render.call(this,renderer)},ComplexRope}(Mesh),FixedWidthSimpleRopeGeometry=function(_super){function FixedWidthSimpleRopeGeometry(points,width){void 0===width&&(width=200);var _this=_super.call(this,new Float32Array(4*points.length),new Float32Array(4*points.length),new Uint16Array(6*(points.length-1)))||this;return _this.points=points,_this._width=width,_this.build(),_this}return __extends(FixedWidthSimpleRopeGeometry,_super),Object.defineProperty(FixedWidthSimpleRopeGeometry.prototype,"width",{get:function(){return this._width},enumerable:!1,configurable:!0}),FixedWidthSimpleRopeGeometry.prototype.build=function(){var points=this.points;if(points){var vertexBuffer=this.getBuffer("aVertexPosition"),uvBuffer=this.getBuffer("aTextureCoord"),indexBuffer=this.getIndex();if(!(points.length<1)){vertexBuffer.data.length/4!==points.length&&(vertexBuffer.data=new Float32Array(4*points.length),uvBuffer.data=new Float32Array(4*points.length),indexBuffer.data=new Uint16Array(6*(points.length-1)));var uvs=uvBuffer.data,indices=indexBuffer.data;uvs[0]=0,uvs[1]=0,uvs[2]=0,uvs[3]=1;for(var amount=0,prev=points[0],total=points.length,i=0;i<total;i++){var index=4*i,dx=prev.x-points[i].x,dy=prev.y-points[i].y,distance=Math.sqrt(dx*dx+dy*dy);prev=points[i],amount+=distance/this._width,uvs[index]=amount,uvs[index+1]=0,uvs[index+2]=amount,uvs[index+3]=1}var indexCount=0;for(i=0;i<total-1;i++){index=2*i;indices[indexCount++]=index,indices[indexCount++]=index+1,indices[indexCount++]=index+2,indices[indexCount++]=index+2,indices[indexCount++]=index+1,indices[indexCount++]=index+3}uvBuffer.update(),indexBuffer.update(),this.updateVertices()}}},FixedWidthSimpleRopeGeometry.prototype.updateVertices=function(){var points=this.points;if(!(points.length<1)){for(var nextPoint,lastPoint=points[0],perpX=0,perpY=0,vertices=this.buffers[0].data,total=points.length,i=0;i<total;i++){var point=points[i],index=4*i;perpY=-((nextPoint=i<points.length-1?points[i+1]:point).x-lastPoint.x),perpX=nextPoint.y-lastPoint.y;var perpLength=Math.sqrt(perpX*perpX+perpY*perpY),num=this._width/2;perpX/=perpLength,perpY/=perpLength,perpX*=num,perpY*=num,vertices[index]=point.x+perpX,vertices[index+1]=point.y+perpY,vertices[index+2]=point.x-perpX,vertices[index+3]=point.y-perpY,lastPoint=point}this.buffers[0].update()}},FixedWidthSimpleRopeGeometry.prototype.update=function(){this.build()},FixedWidthSimpleRopeGeometry}(MeshGeometry),FixedWidthSimpleRope=function(_super){function FixedWidthSimpleRope(texture,points,width){var _this=this,ropeGeometry=new FixedWidthSimpleRopeGeometry(points,width),meshMaterial=new MeshMaterial(texture);return texture.baseTexture.wrapMode=WRAP_MODES.REPEAT,(_this=_super.call(this,ropeGeometry,meshMaterial)||this).autoUpdate=!0,_this}return __extends(FixedWidthSimpleRope,_super),FixedWidthSimpleRope.prototype._render=function(renderer){var geometry=this.geometry;this.autoUpdate&&geometry.update(),_super.prototype._render.call(this,renderer)},FixedWidthSimpleRope}(Mesh),UniformTextureStretchRopeGeometry=function(_super){function UniformTextureStretchRopeGeometry(points,width){void 0===width&&(width=200);var _this=_super.call(this,new Float32Array(4*points.length),new Float32Array(4*points.length),new Uint16Array(6*(points.length-1)))||this;return _this.points=points,_this._width=width,_this.build(),_this}return __extends(UniformTextureStretchRopeGeometry,_super),UniformTextureStretchRopeGeometry.prototype.build=function(){var points=this.points;if(points){var vertexBuffer=this.getBuffer("aVertexPosition"),uvBuffer=this.getBuffer("aTextureCoord"),indexBuffer=this.getIndex();if(!(points.length<1)){vertexBuffer.data.length/4!==points.length&&(vertexBuffer.data=new Float32Array(4*points.length),uvBuffer.data=new Float32Array(4*points.length),indexBuffer.data=new Uint16Array(6*(points.length-1)));for(var total=points.length,totalLength=0,prevPoint=points[0],i=0;i<total;i++){var dx=prevPoint.x-points[i].x,dy=prevPoint.y-points[i].y,distance=Math.sqrt(dx*dx+dy*dy);prevPoint=points[i],totalLength+=distance}var uvs=uvBuffer.data,indices=indexBuffer.data;uvs[0]=0,uvs[1]=0,uvs[2]=0,uvs[3]=1;var amount=0,prev=points[0];for(i=0;i<total;i++){var index=4*i;dx=prev.x-points[i].x,dy=prev.y-points[i].y,distance=Math.sqrt(dx*dx+dy*dy);prev=points[i],amount+=distance/totalLength,uvs[index]=amount,uvs[index+1]=0,uvs[index+2]=amount,uvs[index+3]=1}var indexCount=0;for(i=0;i<total-1;i++){index=2*i;indices[indexCount++]=index,indices[indexCount++]=index+1,indices[indexCount++]=index+2,indices[indexCount++]=index+2,indices[indexCount++]=index+1,indices[indexCount++]=index+3}uvBuffer.update(),indexBuffer.update(),this.updateVertices()}}},UniformTextureStretchRopeGeometry.prototype.updateVertices=function(){var points=this.points;if(!(points.length<1)){for(var nextPoint,lastPoint=points[0],perpX=0,perpY=0,vertices=this.buffers[0].data,total=points.length,i=0;i<total;i++){var point=points[i],index=4*i;perpY=-((nextPoint=i<points.length-1?points[i+1]:point).x-lastPoint.x),perpX=nextPoint.y-lastPoint.y;var perpLength=Math.sqrt(perpX*perpX+perpY*perpY),num=this._width/2;perpX/=perpLength,perpY/=perpLength,perpX*=num,perpY*=num,vertices[index]=point.x+perpX,vertices[index+1]=point.y+perpY,vertices[index+2]=point.x-perpX,vertices[index+3]=point.y-perpY,lastPoint=point}this.buffers[0].update()}},UniformTextureStretchRopeGeometry.prototype.update=function(){this.updateVertices()},UniformTextureStretchRopeGeometry}(MeshGeometry),UniformTextureStretchRope=function(_super){function UniformTextureStretchRope(texture,points){var _this=this,ropeGeometry=new UniformTextureStretchRopeGeometry(points,texture.height),meshMaterial=new MeshMaterial(texture);return(_this=_super.call(this,ropeGeometry,meshMaterial)||this).autoUpdate=!0,_this}return __extends(UniformTextureStretchRope,_super),UniformTextureStretchRope.prototype._render=function(renderer){var geometry=this.geometry;(this.autoUpdate||geometry._width!==this.shader.texture.height)&&(geometry._width=this.shader.texture.height,geometry.update()),_super.prototype._render.call(this,renderer)},UniformTextureStretchRope}(Mesh),SchematicLayer=function(_super){function SchematicLayer(ctx,id,options){var layerId,_this=_super.call(this,ctx,id,options)||this;return _this.internalLayerVisibility={holeLayerId:!0,casingLayerId:!0,completionLayerId:!0,cementLayerId:!0,pAndALayerId:!0,perforationLayerId:!0},_this.scalingFactors={height:600,zFactor:1,yScale:scaleLinear()},_this.getZFactorScaledPathForPoints=function(start,end){return _this.referenceSystem.getCurtainPath(start,end,!0).map((function(p){return new Point(p.point[0],function(y){return y*_this.scalingFactors.zFactor}(p.point[1]))}))},_this.drawBigPolygon=function(coords,color){void 0===color&&(color=0);var polygon=new Graphics;polygon.beginFill(color),polygon.drawPolygon(coords),polygon.endFill(),_this.addChild(polygon)},_this.drawBigTexturedPolygon=function(coords,t){var polygon=(new Graphics).beginTextureFill({texture:t}).drawPolygon(coords).endFill();return _this.addChild(polygon),polygon},_this.perforationRopeAndTextureReferences=[],_this.prepareSymbolRenderObject=function(component){var exaggerationFactor=_this.options.exaggerationFactor,exaggeratedDiameter=component.diameter*exaggerationFactor;return{pathPoints:_this.getZFactorScaledPathForPoints(component.start,component.end),referenceDiameter:exaggeratedDiameter,symbolKey:component.symbolKey}},_this.drawSymbolComponent=function(_a){var pathPoints=_a.pathPoints,referenceDiameter=_a.referenceDiameter,symbolKey=_a.symbolKey,texture=_this.getSymbolTexture(symbolKey,referenceDiameter);_this.drawSVGRope(pathPoints,texture)},_this.drawHoleSize=function(maxHoleDiameter,holeObject){if(null!=holeObject){var pathPoints=_this.getZFactorScaledPathForPoints(holeObject.start,holeObject.end);if(0!==pathPoints.length){var _a=_this.options,exaggerationFactor=_a.exaggerationFactor,holeOptions=_a.holeOptions,exaggeratedDiameter=holeObject.diameter*exaggerationFactor,_b=createTubularRenderingObject(exaggeratedDiameter/2,pathPoints),rightPath=_b.rightPath,leftPath=_b.leftPath;if(_this.renderType()===RENDERER_TYPE.CANVAS){var polygonCoords=makeTubularPolygon(leftPath,rightPath);_this.drawBigPolygon(polygonCoords,convertColor(holeOptions.firstColor))}else{var texture=_this.getHoleTexture(holeOptions,exaggeratedDiameter,maxHoleDiameter);_this.drawHoleRope(pathPoints,texture,maxHoleDiameter)}_this.drawOutline(leftPath,rightPath,convertColor(holeOptions.lineColor),.6*exaggerationFactor,"TopAndBottom",0)}}},_this.drawCasing=function(casingRenderObject){var casingOptions=_this.options.casingOptions,casingSolidColorNumber=convertColor(casingOptions.solidColor),casingLineColorNumber=convertColor(casingOptions.lineColor);casingRenderObject.sections.forEach((function(section,index,list){var outlineClosureType=SchematicLayer.getOutlineClosureType(index,list.length-1);if(_this.renderType()===RENDERER_TYPE.CANVAS)_this.drawBigPolygon(section.polygon,casingSolidColorNumber);else{var texture=_this.createCasingTexture(casingRenderObject.referenceDiameter);_this.drawRope(section.pathPoints,texture,casingSolidColorNumber)}"casing-window"===section.kind?_this.drawCasingWindowOutline(section.leftPath,section.rightPath,casingOptions,casingRenderObject.casingWallWidth):_this.drawOutline(section.leftPath,section.rightPath,casingLineColorNumber,casingRenderObject.casingWallWidth,outlineClosureType)}))},_this.generateShoe=function(casingEnd,casingRadius,length,width){var start=casingEnd-length,end=casingEnd,points=_this.getZFactorScaledPathForPoints(start,end),normal=createNormals(points),shoeEdge=offsetPoints(points,normal,casingRadius*(width<0?-1:1)),shoeTipPoint=points[points.length-1],shoeTipNormal=normal[normal.length-1],shoeTip=offsetPoint(shoeTipPoint,shoeTipNormal,width+casingRadius*(width<0?-1:1));return __spreadArray(__spreadArray([],shoeEdge,!0),[shoeTip],!1)},_this.createCementSqueezeShape=function(squeeze,casings,completion,holes){return function(squeeze,casings,completion,holes,exaggerationFactor,getPoints){var _a=splitByReferencedStrings(squeeze.referenceIds,casings,completion),attachedStrings=_a.attachedStrings,nonAttachedStrings=_a.nonAttachedStrings;if(0===attachedStrings.length)throw new Error("Invalid cement squeeze data, can't find referenced casing/completion for squeeze with id '".concat(squeeze.id,"'"));var _b=findIntersectingItems(squeeze.start,squeeze.end,nonAttachedStrings,holes),overlappingOuterStrings=_b.overlappingOuterStrings,overlappingHoles=_b.overlappingHoles,outerDiameterIntervals=__spreadArray(__spreadArray([],overlappingOuterStrings,!0),overlappingHoles,!0).map((function(d){return{start:d.start,end:d.end}}));return getUniqueDiameterChangeDepths([squeeze.start,squeeze.end],outerDiameterIntervals).flatMap((function(depth,index,list){return index===list.length-1?[]:[{top:depth,bottom:list[index+1],diameter:findCementOuterDiameterAtDepth(attachedStrings,overlappingOuterStrings,overlappingHoles,depth)*exaggerationFactor}]})).map((function(interval){return{diameter:interval.diameter,points:getPoints(interval.top,interval.bottom)}}))}(squeeze,casings,completion,holes,_this.options.exaggerationFactor,_this.getZFactorScaledPathForPoints)},_this.createPerforationShape=function(perforation,casings,holes){var exaggerationFactor=_this.options.exaggerationFactor;return createComplexRopeSegmentsForPerforation(perforation,casings,holes,exaggerationFactor,_this.getZFactorScaledPathForPoints)},_this.options=__assign(__assign(__assign({},_this.options),(layerId=_this.id,{exaggerationFactor:2,internalLayerOptions:defaultInternalLayerOptions(layerId),holeOptions:defaultHoleOptions,casingOptions:defaultCasingOptions,cementOptions:defaultCementOptions,cementSqueezeOptions:defaultCementSqueezeOptions,screenOptions:defaultScreenOptions,tubingOptions:defaultTubingOptions,cementPlugOptions:defaultCementPlugOptions,perforationOptions:defaultPerforationOptions})),options),_this}return __extends(SchematicLayer,_super),SchematicLayer.prototype.onUnmount=function(event){_super.prototype.onUnmount.call(this,event),this.scalingFactors=null,this.cementTextureCache=null,this.cementSqueezeTextureCache=null,this.holeTextureCache=null,this.screenTextureCache=null,this.tubingTextureCache=null,this.textureSymbolCacheArray=null,this.internalLayerVisibility=null},SchematicLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clearLayer(),this.preRender(),this.render()},SchematicLayer.prototype.onRescale=function(event){var shouldRecalculate=this.scalingFactors.zFactor!==event.zFactor;this.scalingFactors={height:event.height,zFactor:event.zFactor,yScale:event.yScale},_super.prototype.optionsRescale.call(this,event);var yRatio=this.yRatio(),flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.setContainerPosition(event.xScale(0),event.yScale(0)),this.setContainerScale(event.xRatio*(flippedX?-1:1),yRatio*(flippedY?-1:1)),shouldRecalculate&&(this.clearLayer(),this.preRender()),this.render()},SchematicLayer.prototype.setVisibility=function(isVisible,layerId){if(layerId!==this.id){var internalLayerOptions=this.options.internalLayerOptions,keyFound=Object.entries(internalLayerOptions).find((function(_a){return _a[0],_a[1]===layerId}))[0];keyFound&&(this.internalLayerVisibility[keyFound]=isVisible,this.clearLayer(),this.preRender(),this.render())}else _super.prototype.setVisibility.call(this,isVisible,layerId)},SchematicLayer.prototype.getInternalLayerIds=function(){var internalLayerOptions=this.options.internalLayerOptions;return Object.values(internalLayerOptions)},SchematicLayer.prototype.yRatio=function(){var domain=this.scalingFactors.yScale.domain(),baseYSpan=(domain[1]-domain[0])*this.scalingFactors.zFactor,baseDomain=[domain[0],domain[0]+baseYSpan];return Math.abs(this.scalingFactors.height/(baseDomain[1]-baseDomain[0]))},SchematicLayer.prototype.drawRope=function(path,texture,tint){if(0===path.length)return null;var rope=new SimpleRope(texture,path,1);rope.tint=tint||rope.tint,this.addChild(rope)},SchematicLayer.prototype.drawOutline=function(leftPath,rightPath,lineColor,lineWidth,outlineClosure,lineAlignment){void 0===lineWidth&&(lineWidth=1),void 0===outlineClosure&&(outlineClosure="None"),void 0===lineAlignment&&(lineAlignment=1);var leftPathReverse=leftPath.map((function(d){return d.clone()})).reverse(),startPointRight=rightPath[0],startPointLeft=leftPathReverse[0],line=new Graphics;line.lineStyle(lineWidth,lineColor,void 0,lineAlignment),line.moveTo(startPointRight.x,startPointRight.y),rightPath.forEach((function(p){return line.lineTo(p.x,p.y)})),"None"!==outlineClosure&&"Top"!==outlineClosure||line.moveTo(startPointLeft.x,startPointLeft.y),leftPathReverse.forEach((function(p){return line.lineTo(p.x,p.y)})),"TopAndBottom"!==outlineClosure&&"Top"!==outlineClosure||line.lineTo(startPointRight.x,startPointRight.y),this.addChild(line)},SchematicLayer.prototype.drawCasingWindowOutline=function(leftPath,rightPath,_a,lineWidth){var _b,_c,lineColor=_a.lineColor,windowOptions=_a.windowOptions;void 0===lineWidth&&(lineWidth=1);var flippedPaths=!!(null===(_c=null===(_b=this.referenceSystem)||void 0===_b?void 0:_b.options)||void 0===_c?void 0:_c.calculateDisplacementFromBottom),_d=flippedPaths?[leftPath,rightPath]:[rightPath,leftPath],linePath=_d[0],dashedPath=_d[1],_e=flippedPaths?[1,0]:[0,1],dashedAlignment=_e[0],solidAlignment=_e[1],graphics=new Graphics;graphics.lineStyle(lineWidth,convertColor(lineColor),void 0,solidAlignment);var startPointLinePath=linePath[0];graphics.moveTo(startPointLinePath.x,startPointLinePath.y),linePath.forEach((function(p){return graphics.lineTo(p.x,p.y)}));var dashedLine=new DashLine(graphics,{dash:[windowOptions.dashLength,windowOptions.spaceLength],color:convertColor(windowOptions.dashColor),width:lineWidth,alignment:dashedAlignment}),startPointDashedPath=dashedPath[0];dashedLine.moveTo(startPointDashedPath.x,startPointDashedPath.y),dashedPath.forEach((function(currentPoint){dashedLine.lineTo(currentPoint.x,currentPoint.y)})),this.addChild(graphics)},SchematicLayer.prototype.preRender=function(){var _this=this;if(this.data&&this.referenceSystem){var exaggerationFactor=this.options.exaggerationFactor,_a=this.data,holeSizes=_a.holeSizes,casings=_a.casings,cements=_a.cements,completion=_a.completion,symbols=_a.symbols,pAndA=_a.pAndA,perforations=_a.perforations;this.updateSymbolCache(symbols),holeSizes.sort((function(a,b){return b.diameter-a.diameter}));var maxHoleDiameter=holeSizes.length>0?max(holeSizes,(function(d){return d.diameter}))*exaggerationFactor:100*exaggerationFactor;this.internalLayerVisibility.holeLayerId&&holeSizes.forEach((function(hole){return _this.drawHoleSize(maxHoleDiameter,hole)})),casings.sort((function(a,b){return b.diameter-a.diameter}));var fCasing,fCement,fCementSqueeze,casingRenderObjects=casings.map((function(casing){return _this.createCasingRenderObject(casing)})),cementShapes=cements.map((function(cement){return{kind:"cement",segments:createComplexRopeSegmentsForCement(cement,casings,completion,holeSizes,exaggerationFactor,_this.getZFactorScaledPathForPoints),casingIds:(cement.referenceIds||[]).filter((function(id){return id}))}})),_b=pAndA.reduce((function(_a,current){var squeezes=_a[0],remaining=_a[1];return isCementSqueeze(current)?[__spreadArray([current],squeezes,!0),remaining]:[squeezes,__spreadArray([current],remaining,!0)]}),[[],[]]),cementSqueezes=_b[0],remainingPAndA=_b[1],cementSqueezesShape=cementSqueezes.map((function(squeeze){return{kind:"cementSqueeze",segments:_this.createCementSqueezeShape(squeeze,casings,completion,holeSizes),casingIds:squeeze.referenceIds}}));if(this.sortCementAndCasingRenderObjects(casingRenderObjects,cementShapes,cementSqueezesShape).forEach((fCasing=function(casingRO){_this.internalLayerVisibility.casingLayerId&&(_this.drawCasing(casingRO),casingRO.hasShoe&&_this.drawShoe(casingRO.bottom,casingRO.referenceRadius))},fCement=function(cementRO){_this.internalLayerVisibility.cementLayerId&&_this.drawComplexRope(cementRO.segments,_this.getCementTexture())},fCementSqueeze=function(cementSqueezesRO){_this.internalLayerVisibility.pAndALayerId&&_this.drawComplexRope(cementSqueezesRO.segments,_this.getCementSqueezeTexture())},function(renderObject){switch(renderObject.kind){case"casing":return fCasing(renderObject);case"cement":return fCement(renderObject);case"cementSqueeze":return fCementSqueeze(renderObject);default:return assertNever(renderObject)}})),this.perforationRopeAndTextureReferences.forEach((function(_a){var rope=_a.rope,texture=_a.texture;rope.destroy({children:!0,texture:!0,baseTexture:!0}),texture.destroy(!0)})),this.perforationRopeAndTextureReferences=[],this.internalLayerVisibility.perforationLayerId){var perforationOptions_1=this.options.perforationOptions,packings=perforations.filter(hasPacking),fracLines=perforations.filter(hasFracLines),spikes=perforations.filter(hasSpikes);packings.forEach((function(perforation){var perfShapesByDiameter=_this.createPerforationShape(perforation,casings,holeSizes).reduce((function(dict,ps){return dict[ps.diameter]||(dict[ps.diameter]=[]),dict[ps.diameter]=__spreadArray(__spreadArray([],dict[ps.diameter],!0),[ps],!1),dict}),{});Object.values(perfShapesByDiameter).forEach((function(perfShapesWithSameDiameter){var texture=function(perforation,perfShape,perforationOptions){return foldPerforationSubKind({Perforation:function(){return createSubkindPerforationTexture_packing()},CasedHoleFracturation:function(){return createSubkindCasedHoleFracPackTexture_packing(perfShape,perforationOptions)},CasedHoleFracPack:function(){return createSubkindCasedHoleFracPackTexture_packing(perfShape,perforationOptions)},OpenHoleGravelPack:function(){return createSubkindOpenHoleGravelPackTexture_packing(perfShape,perforationOptions)},OpenHoleFracPack:function(){return createSubkindOpenHoleFracPackTexture_packing(perforation,perfShape,perforationOptions)},CasedHoleGravelPack:function(){return createSubkindCasedHoleGravelPackTexture_packing(perfShape,perforationOptions)}},perforation.subKind)}(perforation,perfShapesWithSameDiameter[0],perforationOptions_1),rope=_this.drawComplexRope(perfShapesWithSameDiameter,texture);_this.perforationRopeAndTextureReferences.push({rope:rope,texture:texture})}))})),fracLines.forEach((function(perforation){var perfShapesByDiameter=_this.createPerforationShape(perforation,casings,holeSizes).map((function(ps){return __assign(__assign({},ps),{diameter:3*ps.diameter})})).reduce((function(dict,ps){return dict[ps.diameter]||(dict[ps.diameter]=[]),dict[ps.diameter]=__spreadArray(__spreadArray([],dict[ps.diameter],!0),[ps],!1),dict}),{});Object.values(perfShapesByDiameter).forEach((function(perfShapesWithSameDiameter){perfShapesWithSameDiameter.forEach((function(perfShape){var texture=function(perforation,perfShape,perforationOptions){return foldPerforationSubKind({Perforation:function(){return createSubkindPerforationTexture_fracLines()},OpenHoleGravelPack:function(){return createSubkindOpenHoleGravelPackTexture_fracLines()},OpenHoleFracPack:function(){return createSubkindOpenHoleFracPackTexture_fracLines(perfShape,perforationOptions)},CasedHoleFracturation:function(){return createSubkindCasedHoleFracturationTexture_fracLines(perfShape,perforationOptions)},CasedHoleGravelPack:function(){return createSubkindCasedHoleGravelPackTexture_fracLines()},CasedHoleFracPack:function(){return createSubkindCasedHoleFracPackTexture_fracLines(perfShape,perforationOptions)}},perforation.subKind)}(perforation,perfShape,perforationOptions_1),rope=_this.drawComplexRope([perfShape],texture);_this.perforationRopeAndTextureReferences.push({rope:rope,texture:texture})}))}))})),spikes.forEach((function(perforation){var perfShapesByDiameter=_this.createPerforationShape(perforation,casings,holeSizes).map((function(ps){return __assign(__assign({},ps),{diameter:3*ps.diameter})})).reduce((function(dict,ps){return dict[ps.diameter]||(dict[ps.diameter]=[]),dict[ps.diameter]=__spreadArray(__spreadArray([],dict[ps.diameter],!0),[ps],!1),dict}),{});Object.values(perfShapesByDiameter).forEach((function(perfShapesWithSameDiameter){perfShapesWithSameDiameter.forEach((function(perfShape){var texture=function(perforation,otherPerforations,perfShape,perforationOptions){return foldPerforationSubKind({Perforation:function(){return createSubkindPerforationTexture_spikes(perforation,perfShape,otherPerforations,perforationOptions)},OpenHoleGravelPack:function(){return createSubkindOpenHoleGravelPackTexture_spikes()},OpenHoleFracPack:function(){return createSubkindOpenHoleFracPackTexture_spikes()},CasedHoleFracturation:function(){return createSubkindCasedHoleFracturationTexture_spikes()},CasedHoleGravelPack:function(){return createSubkindCasedHoleGravelPackTexture_spikes()},CasedHoleFracPack:function(){return createSubkindCasedHoleFracPackTexture_spikes()}},perforation.subKind)}(perforation,perforations,perfShape,perforationOptions_1),rope=_this.drawComplexRope([perfShape],texture);_this.perforationRopeAndTextureReferences.push({rope:rope,texture:texture})}))}))}))}this.internalLayerVisibility.completionLayerId&&completion.forEach(foldCompletion((function(obj){return _this.drawScreen(obj)}),(function(obj){return _this.drawTubing(obj)}),(function(obj){var symbolRenderObject=_this.prepareSymbolRenderObject(obj);_this.drawSymbolComponent(symbolRenderObject)}))),this.internalLayerVisibility.pAndALayerId&&remainingPAndA.forEach((function(obj){if(isPAndASymbol(obj)){var symbolRenderObject=_this.prepareSymbolRenderObject(obj);_this.drawSymbolComponent(symbolRenderObject)}isCementPlug(obj)&&_this.drawCementPlug(obj,casings,completion,holeSizes)}))}},SchematicLayer.prototype.updateSymbolCache=function(symbols){var _this=this;if(this.textureSymbolCacheArray||(this.textureSymbolCacheArray={}),symbols){var existingKeys=Object.keys(this.textureSymbolCacheArray);Object.entries(symbols).forEach((function(_a){var key=_a[0],symbol=_a[1];existingKeys.includes(key)||(_this.textureSymbolCacheArray[key]=Texture.from(symbol))}))}},SchematicLayer.prototype.drawCementPlug=function(cementPlug,casings,completion,holes){var _a=this.options,exaggerationFactor=_a.exaggerationFactor,cementPlugOptions=_a.cementPlugOptions,cementPlugSegments=createComplexRopeSegmentsForCementPlug(cementPlug,casings,completion,holes,exaggerationFactor,this.getZFactorScaledPathForPoints);this.drawComplexRope(cementPlugSegments,this.getCementPlugTexture(cementPlugOptions));var _b=cementPlugSegments.reduce((function(acc,current){var _a=createTubularRenderingObject(current.diameter/2,current.points),leftPath=_a.leftPath,rightPath=_a.rightPath;return{rightPath:__spreadArray(__spreadArray([],acc.rightPath,!0),rightPath,!0),leftPath:__spreadArray(__spreadArray([],acc.leftPath,!0),leftPath,!0)}}),{rightPath:[],leftPath:[]}),rightPath=_b.rightPath,leftPath=_b.leftPath;this.drawOutline(leftPath,rightPath,convertColor("black"),.25,"TopAndBottom")},SchematicLayer.prototype.createCasingRenderObject=function(casing){var exaggerationFactor=this.options.exaggerationFactor;return prepareCasingRenderObject(exaggerationFactor,casing,this.getZFactorScaledPathForPoints)},SchematicLayer.prototype.getCementPlugTexture=function(cementPlugOptions){return this.cementPlugTextureCache||(this.cementPlugTextureCache=function(_a){var firstColor=_a.firstColor,secondColor=_a.secondColor,scalingFactor=_a.scalingFactor,canvas=document.createElement("canvas"),size=64*scalingFactor;canvas.width=size,canvas.height=size;var canvasCtx=canvas.getContext("2d");canvasCtx.fillStyle=firstColor,canvasCtx.fillRect(0,0,canvas.width,canvas.height),canvasCtx.lineWidth=scalingFactor,canvasCtx.strokeStyle=secondColor,canvasCtx.beginPath(),canvasCtx.setLineDash([20,10]);for(var distanceBetweenLines=size/12,i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+distanceBetweenLines*i,-canvas.height),canvasCtx.lineTo(canvas.width+distanceBetweenLines*i,2*canvas.height);return canvasCtx.stroke(),Texture.from(canvas)}(cementPlugOptions)),this.cementPlugTextureCache},SchematicLayer.prototype.drawSVGRope=function(path,texture){if(0===path.length)return null;var rope=new UniformTextureStretchRope(texture,path);this.addChild(rope)},SchematicLayer.prototype.getSymbolTexture=function(symbolKey,diameter){return new Texture(this.textureSymbolCacheArray[symbolKey].baseTexture,null,new Rectangle(0,0,0,diameter),null,groupD8.MAIN_DIAGONAL)},SchematicLayer.prototype.drawHoleRope=function(path,texture,maxHoleDiameter){if(0===path.length)return null;var rope=new SimpleRope(texture,path,maxHoleDiameter/64);this.addChild(rope)},SchematicLayer.prototype.getHoleTexture=function(holeOptions,diameter,maxHoleDiameter){var textureDiameter=diameter/maxHoleDiameter*64;this.holeTextureCache||(this.holeTextureCache=function(_a,width,height){var firstColor=_a.firstColor,secondColor=_a.secondColor,canvas=document.createElement("canvas");canvas.width=width,canvas.height=height;var canvasCtx=canvas.getContext("2d");return canvasCtx.fillStyle=function(canvas,canvasCtx,firstColor,secondColor,startPctOffset){var gradient=canvasCtx.createLinearGradient(0,0,0,canvas.height);return gradient.addColorStop(0,firstColor),gradient.addColorStop(.5-startPctOffset,secondColor),gradient.addColorStop(.5+startPctOffset,secondColor),gradient.addColorStop(1,firstColor),gradient}(canvas,canvasCtx,firstColor,secondColor,0),canvasCtx.fillRect(0,0,canvas.width,canvas.height),Texture.from(canvas)}(holeOptions,64,64));var baseTexture=this.holeTextureCache.baseTexture,frame=new Rectangle(0,(64-textureDiameter)/2,64,textureDiameter);return new Texture(baseTexture,frame)},SchematicLayer.prototype.sortCementAndCasingRenderObjects=function(casingRenderObjects,cementRenderObject,cementSqueezes){var zIndex=0;return casingRenderObjects.reduce((function(acc,casingRenderObject){var foundCementShape=acc.remainingCement.find((function(cement){return cement.casingIds.includes(casingRenderObject.id)})),foundCementSqueezes=acc.remainingCementSqueezes.filter((function(squeeze){return squeeze.casingIds.includes(casingRenderObject.id)}));return foundCementShape&&(foundCementShape.zIndex=zIndex++),foundCementSqueezes.forEach((function(item){return item.zIndex=zIndex++})),casingRenderObject.zIndex=zIndex++,{result:__spreadArray(__spreadArray(__spreadArray([],acc.result,!0),[foundCementShape,casingRenderObject],!1),foundCementSqueezes,!0),remainingCement:acc.remainingCement.filter((function(c){return c!==foundCementShape})),remainingCementSqueezes:acc.remainingCementSqueezes.filter((function(squeeze){return!foundCementSqueezes.includes(squeeze)}))}}),{result:[],remainingCement:cementRenderObject,remainingCementSqueezes:cementSqueezes}).result.filter((function(item){return void 0!==item})).sort((function(a,b){return a.zIndex-b.zIndex}))},SchematicLayer.prototype.drawComplexRope=function(intervals,texture){if(0===intervals.length)return null;var exaggerationFactor=this.options.exaggerationFactor,rope=new ComplexRope(texture,intervals,exaggerationFactor);return this.addChild(rope),rope},SchematicLayer.prototype.createCasingTexture=function(diameter){return new Texture(Texture.WHITE.baseTexture,null,new Rectangle(0,0,16,diameter))},SchematicLayer.prototype.drawShoe=function(casingEnd,casingRadius){var _a=this.options,exaggerationFactor=_a.exaggerationFactor,casingOptions=_a.casingOptions,shoeWidth=casingOptions.shoeSize.width*exaggerationFactor,shoeLength=casingOptions.shoeSize.length*exaggerationFactor,shoeCoords=this.generateShoe(casingEnd,casingRadius,shoeLength,shoeWidth),shoeCoords2=this.generateShoe(casingEnd,casingRadius,shoeLength,-shoeWidth);this.drawBigPolygon(shoeCoords2),this.drawBigPolygon(shoeCoords)},SchematicLayer.prototype.getCementTexture=function(){if(!this.cementTextureCache){var cementOptions=this.options.cementOptions;this.cementTextureCache=function(_a){var firstColor=_a.firstColor,secondColor=_a.secondColor,scalingFactor=_a.scalingFactor,canvas=document.createElement("canvas"),size=64*scalingFactor,lineWidth=scalingFactor;canvas.width=size,canvas.height=size;var canvasCtx=canvas.getContext("2d");canvasCtx.fillStyle=firstColor,canvasCtx.fillRect(0,0,canvas.width,canvas.height),canvasCtx.lineWidth=lineWidth,canvasCtx.fillStyle=secondColor,canvasCtx.beginPath();for(var distanceBetweenLines=size/12,i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+distanceBetweenLines*i,-canvas.height),canvasCtx.lineTo(canvas.width+distanceBetweenLines*i,canvas.height);return canvasCtx.stroke(),Texture.from(canvas)}(cementOptions)}return this.cementTextureCache},SchematicLayer.prototype.getCementSqueezeTexture=function(){if(!this.cementSqueezeTextureCache){var cementSqueezeOptions=this.options.cementSqueezeOptions;this.cementSqueezeTextureCache=function(_a){var firstColor=_a.firstColor,secondColor=_a.secondColor,scalingFactor=_a.scalingFactor,canvas=document.createElement("canvas"),size=64*scalingFactor,lineWidth=scalingFactor;canvas.width=size,canvas.height=size;var canvasCtx=canvas.getContext("2d");canvasCtx.lineWidth=lineWidth,canvasCtx.fillStyle=firstColor,canvasCtx.strokeStyle=secondColor,canvasCtx.fillRect(0,0,canvas.width,canvas.height),canvasCtx.beginPath(),canvasCtx.setLineDash([20,10]);for(var distanceBetweenLines=size/12,i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+distanceBetweenLines*i,-canvas.height),canvasCtx.lineTo(canvas.width+distanceBetweenLines*i,2*canvas.height);return canvasCtx.stroke(),Texture.from(canvas)}(cementSqueezeOptions)}return this.cementSqueezeTextureCache},SchematicLayer.prototype.drawScreen=function(_a){var start=_a.start,end=_a.end,diameter=_a.diameter,_b=this.options,exaggerationFactor=_b.exaggerationFactor,screenOptions=_b.screenOptions,exaggeratedDiameter=exaggerationFactor*diameter,pathPoints=this.getZFactorScaledPathForPoints(start,end),_c=createTubularRenderingObject(exaggeratedDiameter/2,pathPoints),leftPath=_c.leftPath,rightPath=_c.rightPath,polygon=makeTubularPolygon(leftPath,rightPath),texture=this.getScreenTexture();this.renderType()===RENDERER_TYPE.CANVAS?this.drawBigTexturedPolygon(polygon,texture):this.drawCompletionRope(pathPoints,texture,exaggeratedDiameter),this.drawOutline(leftPath,rightPath,convertColor(screenOptions.lineColor),.3*exaggerationFactor,"TopAndBottom")},SchematicLayer.prototype.drawTubing=function(_a){var diameter=_a.diameter,start=_a.start,end=_a.end,_b=this.options,exaggerationFactor=_b.exaggerationFactor,tubingOptions=_b.tubingOptions,exaggeratedDiameter=exaggerationFactor*diameter,pathPoints=this.getZFactorScaledPathForPoints(start,end),_c=createTubularRenderingObject(exaggeratedDiameter/2,pathPoints),leftPath=_c.leftPath,rightPath=_c.rightPath,polygon=makeTubularPolygon(leftPath,rightPath),texture=this.getTubingTexture(tubingOptions);this.renderType()===RENDERER_TYPE.CANVAS?this.drawBigTexturedPolygon(polygon,texture):this.drawCompletionRope(pathPoints,texture,exaggeratedDiameter)},SchematicLayer.prototype.getTubingTexture=function(tubingOptions){return this.tubingTextureCache||(this.tubingTextureCache=function(_a){var innerColor=_a.innerColor,outerColor=_a.outerColor,size=64*_a.scalingFactor,canvas=document.createElement("canvas");canvas.width=size,canvas.height=size;var canvasCtx=canvas.getContext("2d"),gradient=canvasCtx.createLinearGradient(0,0,0,size);return gradient.addColorStop(0,outerColor),gradient.addColorStop(.3,innerColor),gradient.addColorStop(.7,innerColor),gradient.addColorStop(1,outerColor),canvasCtx.fillStyle=gradient,canvasCtx.fillRect(0,0,canvas.width,canvas.height),Texture.from(canvas)}(tubingOptions)),this.tubingTextureCache},SchematicLayer.prototype.getScreenTexture=function(){if(!this.screenTextureCache){var screenOptions=this.options.screenOptions;this.screenTextureCache=function(_a){var scalingFactor=_a.scalingFactor,canvas=document.createElement("canvas"),size=64*scalingFactor;canvas.width=size,canvas.height=size;var canvasCtx=canvas.getContext("2d");canvasCtx.fillStyle="white",canvasCtx.fillRect(0,0,canvas.width,canvas.height);var baseLineWidth=size/10;canvasCtx.strokeStyle="#AAAAAA",canvasCtx.lineWidth=baseLineWidth,canvasCtx.beginPath();for(var distanceBetweenLines=size/3,i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+distanceBetweenLines*i,-canvas.height),canvasCtx.lineTo(canvas.width+distanceBetweenLines*i,2*canvas.height);return canvasCtx.stroke(),Texture.from(canvas)}(screenOptions)}return this.screenTextureCache},SchematicLayer.prototype.drawCompletionRope=function(path,texture,diameter){if(0!==path.length){var rope=new FixedWidthSimpleRope(texture,path,diameter);this.addChild(rope)}},SchematicLayer.getOutlineClosureType=function(index,maxIndex){return 0===index?index===maxIndex?"TopAndBottom":"Top":index===maxIndex?"Bottom":"None"},SchematicLayer}(PixiLayer),SeismicCanvasLayer=function(_super){function SeismicCanvasLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(SeismicCanvasLayer,_super),SeismicCanvasLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event)},SeismicCanvasLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clearCanvas(),this.render()},SeismicCanvasLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.setTransform(event),this.render()},SeismicCanvasLayer.prototype.render=function(){if(this.data&&this.ctx&&this.data.image){var ctx=this.ctx,_a=this.data,options=_a.options,image=_a.image;this.clearCanvas(),ctx.drawImage(image,options.x,options.y,options.width,options.height)}},SeismicCanvasLayer}(CanvasLayer),WellborepathLayer=function(_super){function WellborepathLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.options=__assign(__assign({},_this.options),options),_this.render=_this.render.bind(_this),_this}return __extends(WellborepathLayer,_super),WellborepathLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.render()},WellborepathLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.elm&&(this.rescaleEvent=event,this.render())},WellborepathLayer.prototype.render=function(){var _a=this.options,strokeWidth=_a.strokeWidth,stroke=_a.stroke;if(this.elm){this.elm.select("g").remove();var data=this.data||this.referenceSystem&&this.referenceSystem.projectedPath;data&&this.rescaleEvent&&this.elm.append("g").attr("class","well-path").append("path").attr("d",this.renderWellborePath(data)).attr("stroke-width",strokeWidth||"2px").attr("stroke",stroke||"red").attr("fill","none")}},WellborepathLayer.prototype.renderWellborePath=function(data){var curveFactory,_a=this.rescaleEvent,xScale=_a.xScale,yScale=_a.yScale,transformedData=data.map((function(d){return[xScale(d[0]),yScale(d[1])]})),_b=this.options,curveType=_b.curveType,tension=_b.tension;switch(curveType){default:case"curveCatmullRom":curveFactory=curveCatmullRom.alpha(tension||.7);break;case"curveLinear":curveFactory=curveLinear;break;case"curveBasis":curveFactory=curveBasis;break;case"curveBasisClosed":curveFactory=curveBasisClosed;break;case"curveBundle":curveFactory=curveBundle.beta(tension||1);break;case"curveCardinal":curveFactory=curveCardinal.tension(tension||.9);break;case"curveMonotoneX":curveFactory=curveMonotoneX;break;case"curveMonotoneY":curveFactory=curveMonotoneY;break;case"curveNatural":curveFactory=curveNatural;break;case"curveStep":curveFactory=curveStep;break;case"curveStepAfter":curveFactory=curveStepAfter;break;case"curveStepBefore":curveFactory=curveStepBefore}return line().curve(curveFactory)(transformedData)},WellborepathLayer}(SVGLayer),foldReferenceLine=function(options,refLine){switch(refLine.lineType){case"wavy":return options.wavy(refLine);case"dashed":return options.dashed(refLine);case"solid":return options.solid(refLine);default:return assertNever(refLine.lineType)}},ReferenceLineLayer=function(_super){function ReferenceLineLayer(){var _this=null!==_super&&_super.apply(this,arguments)||this;return _this.yScale=null,_this.xScale=null,_this}return __extends(ReferenceLineLayer,_super),ReferenceLineLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event)},ReferenceLineLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clearCanvas(),this.render()},ReferenceLineLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.yScale=event.yScale,this.xScale=event.xScale,this.resetTransform(),this.render()},ReferenceLineLayer.prototype.drawDashed=function(dashed){var ctx=this.ctx,canvas=this.canvas,y=this.yScale(dashed.depth);ctx.save(),ctx.strokeStyle=dashed.color,this.setCtxLineStyle(ctx,dashed),this.setCtxLineWidth(ctx,dashed),ctx.beginPath(),ctx.moveTo(0,y),ctx.lineTo(canvas.width,y),ctx.stroke(),ctx.restore(),dashed.text&&this.drawText(ctx,dashed,ctx.canvas.width,y)},ReferenceLineLayer.prototype.drawSolid=function(solid){var ctx=this.ctx,canvas=this.canvas,y=this.yScale(solid.depth);ctx.save(),ctx.strokeStyle=solid.color,this.setCtxLineStyle(ctx,solid),this.setCtxLineWidth(ctx,solid),ctx.beginPath(),ctx.moveTo(0,y),ctx.lineTo(canvas.width,y),ctx.stroke(),ctx.restore(),solid.text&&this.drawText(ctx,solid,ctx.canvas.width,y)},ReferenceLineLayer.prototype.drawWavy=function(wavy){var ctx=this.ctx,canvas=this.canvas,waveHeight=calcSize(4,2.5,500,this.yScale),wavePeriod=2*waveHeight,y=this.yScale(wavy.depth)-waveHeight,steps=Math.ceil(canvas.width/wavePeriod)+1,xOffset=this.xScale(0)%wavePeriod;ctx.save(),ctx.strokeStyle=wavy.color,this.setCtxLineStyle(ctx,wavy),this.setCtxLineWidth(ctx,wavy);for(var i=-1;i<steps;i++)ctx.beginPath(),ctx.arc(i*wavePeriod+xOffset+waveHeight,y,waveHeight,0,Math.PI),ctx.stroke();ctx.restore(),wavy.text&&this.drawText(ctx,wavy,ctx.canvas.width,y)},ReferenceLineLayer.prototype.drawText=function(ctx,refLine,x,y){var textColor=refLine.textColor||"#000",fontSize=refLine.fontSize||"10px sans-serif";ctx.save(),ctx.strokeStyle=textColor,ctx.font=fontSize,ctx.textAlign="end",ctx.textBaseline="bottom",ctx.fillText(refLine.text,x-10,y),ctx.restore()},ReferenceLineLayer.prototype.setCtxLineStyle=function(ctx,refLine){foldReferenceLine({solid:function(){ctx.setLineDash([])},dashed:function(){ctx.setLineDash([8,10])},wavy:function(){ctx.setLineDash([])}},refLine)},ReferenceLineLayer.prototype.setCtxLineWidth=function(ctx,refLine){ctx.lineWidth=refLine.lineWidth||1},ReferenceLineLayer.prototype.render=function(){var _this=this;this.ctx&&this.yScale&&this.xScale&&requestAnimationFrame((function(){var _a;_this.clearCanvas(),null===(_a=_this.data)||void 0===_a||_a.forEach((function(refLine){foldReferenceLine({solid:function(solid){return _this.drawSolid(solid)},dashed:function(dashed){return _this.drawDashed(dashed)},wavy:function(wavy){return _this.drawWavy(wavy)}},refLine)}))}))},ReferenceLineLayer}(CanvasLayer),LayerManager=function(){function LayerManager(container,scaleOptions,axisOptions){var _this=this;if(this.layers=[],this.createAxis=function(options){var container=_this.container;_this._svgContainer=select(container).append("div").attr("class","axis").style("position","absolute").style("z-index","10").style("pointer-events","none");var svg=_this._svgContainer.append("svg").attr("height","".concat(container.offsetHeight,"px")).attr("width","".concat(container.offsetWidth,"px"));return new Axis(svg,!0,options.xLabel,options.yLabel,options.unitOfMeasure)},this.container=container,this.layerContainer=document.createElement("div"),this.layerContainer.className="layer-container",this.container.appendChild(this.layerContainer),this.adjustToSize(+this.container.getAttribute("width"),+this.container.getAttribute("height")),this._zoomPanHandler=new ZoomPanHandler(container,(function(event){return _this.rescale(event)})),scaleOptions){var xMin=scaleOptions.xMin,xMax=scaleOptions.xMax,yMin=scaleOptions.yMin,yMax=scaleOptions.yMax,xBounds=scaleOptions.xBounds,yBounds=scaleOptions.yBounds;void 0!==xMin&&void 0!==xMax&&void 0!==yMin&&void 0!==yMax&&this._zoomPanHandler.setBounds([xMin,xMax],[yMin,yMax]),xBounds&&yBounds&&this._zoomPanHandler.setBounds(xBounds,yBounds)}else this._zoomPanHandler.setBounds([0,1],[0,1]);axisOptions&&(this._axis=this.createAxis(axisOptions)),this.rescale=this.rescale.bind(this)}return LayerManager.prototype.addLayers=function(layers){var _this=this;return layers.forEach((function(layer){return _this.addLayer(layer)})),this},LayerManager.prototype.getLayers=function(){return this.layers},LayerManager.prototype.clearAllData=function(includeReferenceSystem){return void 0===includeReferenceSystem&&(includeReferenceSystem=!0),this.layers.forEach((function(l){return l.clearData(includeReferenceSystem)})),this},LayerManager.prototype.addLayer=function(layer,params){return this.layers.push(layer),this.initLayer(layer,params),this},LayerManager.prototype.removeLayer=function(layerId){var layer=this.layers.find((function(l){return l.id===layerId}));return layer&&(layer.onUnmount(),this.layers=this.layers.filter((function(l){return l.id!==layerId}))),this},LayerManager.prototype.removeAllLayers=function(){var _this=this;return this.layers.forEach((function(layer){_this.removeLayer(layer.id)})),this},LayerManager.prototype.getLayer=function(layerId){return this.layers.find((function(l){return l.id===layerId||l.getInternalLayerIds().includes(layerId)}))},LayerManager.prototype.initLayer=function(layer,params){var event={elm:this.layerContainer};layer.onMount(event);var rescaleEvent=this.zoomPanHandler.currentStateAsEvent();if(layer.onUpdate(__assign(__assign({},rescaleEvent),params)),layer.onRescale(rescaleEvent),this._svgContainer){var highestZIndex=this.layers.length>0?this.layers.reduce((function(max,layers){return max.order>layers.order?max:layers})).order:1;this._svgContainer.style("z-index","".concat(highestZIndex+1))}return this},LayerManager.prototype.showLayer=function(layerId){var layer=this.getLayer(layerId);return layer?(layer.setVisibility(!0,layerId),layer.onRescale(this.zoomPanHandler.currentStateAsEvent()),this):this},LayerManager.prototype.hideLayer=function(layerId){var layer=this.getLayer(layerId);return layer?(layer.setVisibility(!1,layerId),layer.onRescale(this.zoomPanHandler.currentStateAsEvent()),this):this},LayerManager.prototype.adjustToSize=function(width,height){var layersWidth=Math.max(this._axis?width-40:width,0),layersHeight=Math.max(this._axis?height-30:height,0);if(this._axis){var resizeEvent={width:width,height:height};this._axis.onResize(resizeEvent)}if(this.layers){var resizeEvent_1={width:layersWidth,height:layersHeight};this.layers.forEach((function(layer){return layer.onResize(resizeEvent_1)}))}this._zoomPanHandler&&this._zoomPanHandler.adjustToSize(layersWidth,layersHeight,!0)},LayerManager.prototype.setReferenceSystem=function(irs){this.layers.forEach((function(layer){return layer.referenceSystem=irs}))},LayerManager.prototype.showAxis=function(){return this._axis.show(),this},LayerManager.prototype.hideAxis=function(){return this._axis.hide(),this},LayerManager.prototype.showAxisLabels=function(){return this._axis.showLabels(),this},LayerManager.prototype.hideAxisLabels=function(){return this._axis.hideLabels(),this},LayerManager.prototype.setAxisOffset=function(x,y){return this._axis.offsetX=x,this._axis.offsetY=y,this.layers.filter((function(l){return l instanceof GridLayer})).forEach((function(l){l.offsetX=x,l.offsetY=y})),this},LayerManager.prototype.setXAxisOffset=function(x){return this._axis.offsetX=x,this.layers.filter((function(l){return l instanceof GridLayer})).forEach((function(l){l.offsetX=x})),this},LayerManager.prototype.setYAxisOffset=function(y){return this._axis.offsetY=y,this.layers.filter((function(l){return l instanceof GridLayer})).forEach((function(l){l.offsetY=y})),this},LayerManager.prototype.setZoomLevelBoundary=function(zoomlevels){return this._zoomPanHandler.setZoomLevelBoundary(zoomlevels),this},LayerManager.prototype.setMaxZoomLevel=function(zoomlevel){return this._zoomPanHandler.setMaxZoomLevel(zoomlevel),this},LayerManager.prototype.setMinZoomLevel=function(zoomlevel){return this._zoomPanHandler.setMinZoomLevel(zoomlevel),this},LayerManager.prototype.destroy=function(){return this.removeAllLayers(),this.layerContainer.remove(),this.layerContainer=void 0,this.container=void 0,this.layers=void 0,this._zoomPanHandler=void 0,this._axis=void 0,this._svgContainer=void 0,this},Object.defineProperty(LayerManager.prototype,"zoomPanHandler",{get:function(){return this._zoomPanHandler},enumerable:!1,configurable:!0}),Object.defineProperty(LayerManager.prototype,"axis",{get:function(){return this._axis},enumerable:!1,configurable:!0}),LayerManager.prototype.rescale=function(event){this._axis&&this._axis.onRescale(event),this.layers&&this.layers.forEach((function(layer){return!0===layer.isVisible?layer.onRescale(event):{}}))},LayerManager}(),Overlay=function(){function Overlay(caller,container){var _this=this;this.elements={},this.listeners={},this.enabled=!0;var con=select(container);this.elm=con.append("div").attr("id","overlay").style("z-index","11").style("position","absolute"),this.source=this.elm.node();var elm=this.elm;elm.on("resize",(function(event){var _a=event.detail,width=_a.width,height=_a.height;elm.style("width","".concat(width,"px")).style("height","".concat(height,"px")),_this.enabled&&Object.keys(_this.listeners).forEach((function(key){var target=_this.elements[key]||null,ops=_this.listeners[key];ops&&ops.onResize&&requestAnimationFrame((function(){return ops.onResize({target:target,source:_this.source,caller:caller,width:width,height:height})}))}))})),elm.on("mousemove",(function(event){if(_this.enabled){var _a=pointer(event,_this.elm.node()),mx=_a[0],my=_a[1];Object.keys(_this.listeners).forEach((function(key){var target=_this.elements[key]||null,ops=_this.listeners[key];ops&&ops.onMouseMove&&requestAnimationFrame((function(){return ops.onMouseMove({x:mx,y:my,target:target,source:_this.source,caller:caller})}))}))}})),elm.on("mouseout",(function(){_this.enabled&&Object.keys(_this.listeners).forEach((function(key){var target=_this.elements[key]||null,ops=_this.listeners[key];ops&&ops.onMouseExit&&requestAnimationFrame((function(){return ops.onMouseExit({target:target,source:_this.source,caller:caller})}))}))}))}return Overlay.prototype.create=function(key,callbacks){var newElm=this.elm.append("div").style("position","relative").style("pointer-events","none").node();return this.elements[key]=newElm,callbacks&&(this.listeners[key]=callbacks),newElm},Overlay.prototype.register=function(key,callbacks){this.listeners[key]=callbacks},Overlay.prototype.remove=function(key){var el=this.elements[key];el&&(select(el).remove(),delete this.elements[key]),delete this.listeners[key]},Overlay.prototype.setZIndex=function(zIndex){this.elm.style("z-index",zIndex)},Overlay.prototype.destroy=function(){this.source.remove()},Overlay}(),Controller=function(){function Controller(options){var container=options.container,axisOptions=options.axisOptions,scaleOptions=options.scaleOptions,referenceSystem=options.referenceSystem,layers=options.layers,path=options.path;this._referenceSystem=referenceSystem||path&&new IntersectionReferenceSystem(path),this._overlay=function(caller,container){return new Overlay(caller,container)}(this,container),this.layerManager=new LayerManager(this._overlay.elm.node(),scaleOptions,axisOptions),layers&&(this.layerManager.addLayers(layers),this.setOverlayZIndex(layers))}return Controller.prototype.setReferenceSystem=function(referenceSystem){return this._referenceSystem=referenceSystem,this.layerManager.setReferenceSystem(referenceSystem),this},Controller.prototype.updatePath=function(path,options){return this.setReferenceSystem(new IntersectionReferenceSystem(path,options)),this},Controller.prototype.clearAllData=function(includeReferenceSystem){return void 0===includeReferenceSystem&&(includeReferenceSystem=!0),this.layerManager.clearAllData(includeReferenceSystem),this},Controller.prototype.addLayer=function(layer,params){return this.layerManager.addLayer(layer,params),this.setOverlayZIndex(this.layerManager.getLayers()),this},Controller.prototype.removeLayer=function(layerId){return this.layerManager.removeLayer(layerId),this},Controller.prototype.removeAllLayers=function(){return this.layerManager.removeAllLayers(),this},Controller.prototype.getLayer=function(layerId){return this.layerManager.getLayer(layerId)},Controller.prototype.showLayer=function(layerId){return this.layerManager.showLayer(layerId),this},Controller.prototype.hideLayer=function(layerId){return this.layerManager.hideLayer(layerId),this},Controller.prototype.adjustToSize=function(width,height){this.layerManager.adjustToSize(width,height);var dimensions={width:Math.max(width-40,0),height:Math.max(height-30,0)};return this.overlay.elm.dispatch("resize",{detail:dimensions,bubbles:!0,cancelable:!0}),this},Controller.prototype.setViewport=function(cx,cy,displacement,duration){return this.zoomPanHandler.setViewport(cx,cy,displacement,duration),this},Controller.prototype.setBounds=function(xBounds,yBounds){return this.zoomPanHandler.setBounds(xBounds,yBounds),this},Controller.prototype.showAxis=function(){return this.layerManager.showAxis(),this},Controller.prototype.hideAxis=function(){return this.layerManager.hideAxis(),this},Controller.prototype.showAxisLabels=function(){return this.layerManager.showAxisLabels(),this},Controller.prototype.hideAxisLabels=function(){return this.layerManager.hideAxisLabels(),this},Controller.prototype.setAxisOffset=function(x,y){return this.layerManager.setAxisOffset(x,y),this},Controller.prototype.setXAxisOffset=function(x){return this.layerManager.setXAxisOffset(x),this},Controller.prototype.setYAxisOffset=function(y){return this.layerManager.setYAxisOffset(y),this},Controller.prototype.setZoomLevelBoundary=function(zoomlevels){return this.zoomPanHandler.setZoomLevelBoundary(zoomlevels),this},Controller.prototype.setMaxZoomLevel=function(zoomlevel){return this.zoomPanHandler.setMaxZoomLevel(zoomlevel),this},Controller.prototype.setMinZoomLevel=function(zoomlevel){return this.zoomPanHandler.setMinZoomLevel(zoomlevel),this},Controller.prototype.destroy=function(){return this.layerManager.destroy(),this._overlay.destroy(),this._referenceSystem=void 0,this.layerManager=void 0,this._overlay=void 0,this},Controller.prototype.getHighestZIndex=function(layers){var highestZIndex=layers.length>0?layers.reduce((function(max,layers){return max.order>layers.order?max:layers})).order:1;return highestZIndex},Controller.prototype.setOverlayZIndex=function(layers){var highestZIndex=this.getHighestZIndex(layers);this.overlay.setZIndex(highestZIndex+2)},Object.defineProperty(Controller.prototype,"overlay",{get:function(){return this._overlay},enumerable:!1,configurable:!0}),Object.defineProperty(Controller.prototype,"referenceSystem",{get:function(){return this._referenceSystem},enumerable:!1,configurable:!0}),Object.defineProperty(Controller.prototype,"zoomPanHandler",{get:function(){return this.layerManager.zoomPanHandler},enumerable:!1,configurable:!0}),Object.defineProperty(Controller.prototype,"axis",{get:function(){return this.layerManager.axis},enumerable:!1,configurable:!0}),Object.defineProperty(Controller.prototype,"currentStateAsEvent",{get:function(){return this.zoomPanHandler.currentStateAsEvent()},enumerable:!1,configurable:!0}),Controller}();export{Axis,CalloutCanvasLayer,CanvasLayer,Controller,GeomodelCanvasLayer,GeomodelLabelsLayer,GeomodelLayerV2,GridLayer,HTMLLayer,ImageLayer,IntersectionReferenceSystem,Layer,LayerManager,PixiLayer,PixiRenderApplication,ReferenceLineLayer,SVGLayer,SchematicLayer,SeismicCanvasLayer,WellborepathLayer,ZoomPanHandler,assertNever,calcSize,defaultCasingOptions,defaultCementOptions,defaultCementPlugOptions,defaultCementSqueezeOptions,defaultHoleOptions,defaultInternalLayerOptions,defaultPerforationOptions,defaultScreenOptions,defaultTubingOptions,findIndexOfSample,findSampleAtPos,foldCompletion,foldPerforationSubKind,generateProjectedTrajectory,generateProjectedWellborePath,generateSeismicSliceImage,generateSurfaceData,getOverlap,getOverlapOffset,getPicksData,getSeismicInfo,getSeismicOptions,hasFracLines,hasPacking,hasSpikes,intersect,isCementPlug,isCementSqueeze,isOpenHoleFracPack,isOverlapping,isOverlappingHorizontally,isPAndASymbol,isSubKindCasedHoleFracPack,isSubKindPerforation,isSubkindCasedHoleGravelPack,pixelsPerUnit,shouldPerforationStartAtCasingDiameter,shouldPerforationStartAtHoleDiameter,transformFormationData};
|