@equinor/esv-intersection 1.8.0 → 2.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/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{select,pointer}from"d3-selection";import{curveCardinal,curveBundle,curveCatmullRom,line,curveStepBefore,curveStepAfter,curveStep,curveNatural,curveMonotoneY,curveMonotoneX,curveBasisClosed,curveBasis,curveLinear}from"d3-shape";import{Application,RENDERER_TYPE,Graphics,SimpleRope,Point,Rectangle,Texture}from"pixi.js";import Vector2 from"@equinor/videx-vector2";import{seqI,clamp,radians}from"@equinor/videx-math";import{scaleOrdinal,scaleLinear}from"d3-scale";import{CurveInterpolator,normalize}from"curve-interpolator";import{merge,zip}from"d3-array";import{zoom,zoomIdentity}from"d3-zoom";import{axisRight,axisBottom}from"d3-axis";
1
+ import{select,pointer}from"d3-selection";import{curveCardinal,curveBundle,curveCatmullRom,line,curveStepBefore,curveStepAfter,curveStep,curveNatural,curveMonotoneY,curveMonotoneX,curveBasisClosed,curveBasis,curveLinear}from"d3-shape";import{Renderer,RENDERER_TYPE,autoDetectRenderer,Container,Graphics,SimpleRope,Point,Rectangle,Texture}from"pixi.js";import Vector2 from"@equinor/videx-vector2";import{seqI,clamp,radians}from"@equinor/videx-math";import{scaleOrdinal,scaleLinear}from"d3-scale";import{CurveInterpolator,normalize}from"curve-interpolator";import{merge,zip}from"d3-array";import{zoom,zoomIdentity}from"d3-zoom";import{axisRight,axisBottom}from"d3-axis";
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */var 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])})(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}).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(;_;)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){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to}var defaultOptions={order:1,layerOpacity:1,interactive:!1},Layer=function(){function Layer(id,options){this._referenceSystem=null,this._interactive=!1,this._id=id||"layer-"+Math.floor(1e3*Math.random());var opts=options||defaultOptions;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){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.onOpacityChanged=function(opacity){},Layer.prototype.onOrderChanged=function(order){},Layer.prototype.onInteractivityChanged=function(interactive){},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:"+interactive+";z-index:"+this.order+";opacity:"+this.opacity+";visibility:"+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",""+this.id),this.canvas.setAttribute("width",width+"px"),this.canvas.setAttribute("height",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",width+"px"),ctx.canvas.setAttribute("height",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),defaultOptions$1={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$1),_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),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",""+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),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",""+this.id),this.elm.attr("class","html-layer"));var interactive=this.interactive?"auto":"none";this.elm.style("position","absolute").style("height",height+"px").style("width",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",event.height+"px").style("width",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),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),PixiLayer=function(_super){function PixiLayer(id,options){return _super.call(this,id,options)||this}return __extends(PixiLayer,_super),PixiLayer.prototype.onMount=function(event){if(_super.prototype.onMount.call(this,event),!this.elm){var container=document.createElement("div");container.setAttribute("id",""+this.id),container.setAttribute("class","webgl-layer"),this.elm=container,this.updateStyle();var elm=event.elm,height=event.height,width=event.width,pixiApplicationOptions=this.options.pixiApplicationOptions,pixiOptions=__assign({width:width||parseInt(this.elm.getAttribute("width"),10)||200,height:height||parseInt(this.elm.getAttribute("height"),10)||300,antialias:!0,transparent:!0,clearBeforeRender:!0,autoResize:!0,preserveDrawingBuffer:!0},pixiApplicationOptions);this.ctx=new Application(pixiOptions),container.appendChild(this.ctx.view),elm.appendChild(container)}},PixiLayer.prototype.onUnmount=function(event){var _a,_b;_super.prototype.onUnmount.call(this,event);var renderType=this.renderType(),glContext=null===(_a=this.ctx.renderer)||void 0===_a?void 0:_a.gl;this.ctx.stop(),this.ctx.destroy(!0,{children:!0,texture:!0,baseTexture:!0}),renderType===RENDERER_TYPE.WEBGL&&(null===(_b=null==glContext?void 0:glContext.getExtension("WEBGL_lose_context"))||void 0===_b||_b.loseContext()),this.elm.remove(),this.elm=null,this.ctx=null},PixiLayer.prototype.onResize=function(event){_super.prototype.onResize.call(this,event),this.ctx.renderer.resize(event.width,event.height)},PixiLayer.prototype.onRescale=function(event){if(_super.prototype.onRescale.call(this,event),this.ctx){var flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.ctx.stage.position.set(event.xScale(0),event.yScale(0)),this.ctx.stage.scale.set(event.xRatio*(flippedX?-1:1),event.yRatio*(flippedY?-1:1))}},PixiLayer.prototype.updateStyle=function(visible){var visibility=visible||this.isVisible?"visible":"hidden",interactive=this.interactive?"auto":"none";this.elm.setAttribute("style","position:absolute;pointer-events:"+interactive+";z-index:"+this.order+";opacity:"+this.opacity+";visibility:"+visibility)},PixiLayer.prototype.setVisibility=function(visible){_super.prototype.setVisibility.call(this,visible),this.elm&&this.updateStyle(visible)},PixiLayer.prototype.onOpacityChanged=function(opacity){this.elm&&this.updateStyle()},PixiLayer.prototype.onOrderChanged=function(order){this.elm&&this.updateStyle()},PixiLayer.prototype.onInteractivityChanged=function(interactive){this.elm&&this.updateStyle()},PixiLayer.prototype.renderType=function(){return this.ctx.renderer.type},PixiLayer}(Layer),GeomodelLayerV2=function(_super){function GeomodelLayerV2(){var _this=null!==_super&&_super.apply(this,arguments)||this;return _this.isRendered=!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.ctx.stage.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.ctx.stage.addChild(g)},_this}return __extends(GeomodelLayerV2,_super),GeomodelLayerV2.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.isRendered||this.render()},GeomodelLayerV2.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.isRendered=!1,this.cleanUpStage(),this.render()},GeomodelLayerV2.prototype.cleanUpStage=function(){this.ctx.stage.children.forEach((function(g){return g.destroy()})),this.ctx.stage.removeChildren()},GeomodelLayerV2.prototype.render=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.isRendered=!0)},GeomodelLayerV2}(PixiLayer),GeomodelLayer=function(_super){function GeomodelLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(GeomodelLayer,_super),GeomodelLayer}(GeomodelLayerV2);function define(constructor,factory,prototype){constructor.prototype=factory.prototype=prototype,prototype.constructor=constructor}function extend(parent,definition){var prototype=Object.create(parent.prototype);for(var key in definition)prototype[key]=definition[key];return prototype}function Color(){}var brighter=1/.7,reI="\\s*([+-]?\\d+)\\s*",reN="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",reP="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",reHex=/^#([0-9a-f]{3,8})$/,reRgbInteger=new RegExp("^rgb\\("+[reI,reI,reI]+"\\)$"),reRgbPercent=new RegExp("^rgb\\("+[reP,reP,reP]+"\\)$"),reRgbaInteger=new RegExp("^rgba\\("+[reI,reI,reI,reN]+"\\)$"),reRgbaPercent=new RegExp("^rgba\\("+[reP,reP,reP,reN]+"\\)$"),reHslPercent=new RegExp("^hsl\\("+[reN,reP,reP]+"\\)$"),reHslaPercent=new RegExp("^hsla\\("+[reN,reP,reP,reN]+"\\)$"),named={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function color_formatHex(){return this.rgb().formatHex()}function color_formatRgb(){return this.rgb().formatRgb()}function color(format){var m,l;return format=(format+"").trim().toLowerCase(),(m=reHex.exec(format))?(l=m[1].length,m=parseInt(m[1],16),6===l?rgbn(m):3===l?new Rgb(m>>8&15|m>>4&240,m>>4&15|240&m,(15&m)<<4|15&m,1):8===l?rgba(m>>24&255,m>>16&255,m>>8&255,(255&m)/255):4===l?rgba(m>>12&15|m>>8&240,m>>8&15|m>>4&240,m>>4&15|240&m,((15&m)<<4|15&m)/255):null):(m=reRgbInteger.exec(format))?new Rgb(m[1],m[2],m[3],1):(m=reRgbPercent.exec(format))?new Rgb(255*m[1]/100,255*m[2]/100,255*m[3]/100,1):(m=reRgbaInteger.exec(format))?rgba(m[1],m[2],m[3],m[4]):(m=reRgbaPercent.exec(format))?rgba(255*m[1]/100,255*m[2]/100,255*m[3]/100,m[4]):(m=reHslPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,1):(m=reHslaPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,m[4]):named.hasOwnProperty(format)?rgbn(named[format]):"transparent"===format?new Rgb(NaN,NaN,NaN,0):null}function rgbn(n){return new Rgb(n>>16&255,n>>8&255,255&n,1)}function rgba(r,g,b,a){return a<=0&&(r=g=b=NaN),new Rgb(r,g,b,a)}function rgbConvert(o){return o instanceof Color||(o=color(o)),o?new Rgb((o=o.rgb()).r,o.g,o.b,o.opacity):new Rgb}function rgb(r,g,b,opacity){return 1===arguments.length?rgbConvert(r):new Rgb(r,g,b,null==opacity?1:opacity)}function Rgb(r,g,b,opacity){this.r=+r,this.g=+g,this.b=+b,this.opacity=+opacity}function rgb_formatHex(){return"#"+hex(this.r)+hex(this.g)+hex(this.b)}function rgb_formatRgb(){var a=this.opacity;return(1===(a=isNaN(a)?1:Math.max(0,Math.min(1,a)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===a?")":", "+a+")")}function hex(value){return((value=Math.max(0,Math.min(255,Math.round(value)||0)))<16?"0":"")+value.toString(16)}function hsla(h,s,l,a){return a<=0?h=s=l=NaN:l<=0||l>=1?h=s=NaN:s<=0&&(h=NaN),new Hsl(h,s,l,a)}function hslConvert(o){if(o instanceof Hsl)return new Hsl(o.h,o.s,o.l,o.opacity);if(o instanceof Color||(o=color(o)),!o)return new Hsl;if(o instanceof Hsl)return o;var r=(o=o.rgb()).r/255,g=o.g/255,b=o.b/255,min=Math.min(r,g,b),max=Math.max(r,g,b),h=NaN,s=max-min,l=(max+min)/2;return s?(h=r===max?(g-b)/s+6*(g<b):g===max?(b-r)/s+2:(r-g)/s+4,s/=l<.5?max+min:2-max-min,h*=60):s=l>0&&l<1?0:h,new Hsl(h,s,l,o.opacity)}function Hsl(h,s,l,opacity){this.h=+h,this.s=+s,this.l=+l,this.opacity=+opacity}function hsl2rgb(h,m1,m2){return 255*(h<60?m1+(m2-m1)*h/60:h<180?m2:h<240?m1+(m2-m1)*(240-h)/60:m1)}function convertColor(colorStr){var d=color(colorStr).hex();return parseInt(d.replace("#","0x"))}define(Color,color,{copy:function(channels){return Object.assign(new this.constructor,this,channels)},displayable:function(){return this.rgb().displayable()},hex:color_formatHex,formatHex:color_formatHex,formatHsl:function(){return hslConvert(this).formatHsl()},formatRgb:color_formatRgb,toString:color_formatRgb}),define(Rgb,rgb,extend(Color,{brighter:function(k){return k=null==k?brighter:Math.pow(brighter,k),new Rgb(this.r*k,this.g*k,this.b*k,this.opacity)},darker:function(k){return k=null==k?.7:Math.pow(.7,k),new Rgb(this.r*k,this.g*k,this.b*k,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:rgb_formatHex,formatHex:rgb_formatHex,formatRgb:rgb_formatRgb,toString:rgb_formatRgb})),define(Hsl,(function(h,s,l,opacity){return 1===arguments.length?hslConvert(h):new Hsl(h,s,l,null==opacity?1:opacity)}),extend(Color,{brighter:function(k){return k=null==k?brighter:Math.pow(brighter,k),new Hsl(this.h,this.s,this.l*k,this.opacity)},darker:function(k){return k=null==k?.7:Math.pow(.7,k),new Hsl(this.h,this.s,this.l*k,this.opacity)},rgb:function(){var h=this.h%360+360*(this.h<0),s=isNaN(h)||isNaN(this.s)?0:this.s,l=this.l,m2=l+(l<.5?l:1-l)*s,m1=2*l-m2;return new Rgb(hsl2rgb(h>=240?h-240:h+120,m1,m2),hsl2rgb(h,m1,m2),hsl2rgb(h<120?h+240:h-120,m1,m2),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var a=this.opacity;return(1===(a=isNaN(a)?1:Math.max(0,Math.min(1,a)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===a?")":", "+a+")")}}));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),Object.defineProperty(GeomodelCanvasLayer.prototype,"data",{get:function(){return _super.prototype.getData.call(this)},set:function(data){this.setData(data)},enumerable:!1,configurable:!0}),GeomodelCanvasLayer.prototype.getData=function(){return _super.prototype.getData.call(this)},GeomodelCanvasLayer.prototype.setData=function(data){_super.prototype.setData.call(this,data)},GeomodelCanvasLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event)},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 hexString=color.toString(16);return"#"+("000000".substr(0,6-hexString.length)+hexString)}(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),constant=x=>()=>x;function gamma(y){return 1==(y=+y)?nogamma:function(a,b){return b-a?function(a,b,y){return a=Math.pow(a,y),b=Math.pow(b,y)-a,y=1/y,function(t){return Math.pow(a+t*b,y)}}(a,b,y):constant(isNaN(a)?b:a)}}function nogamma(a,b){var d=b-a;return d?function(a,d){return function(t){return a+t*d}}(a,d):constant(isNaN(a)?b:a)}var interpolateRgb=function rgbGamma(y){var color=gamma(y);function rgb$1(start,end){var r=color((start=rgb(start)).r,(end=rgb(end)).r),g=color(start.g,end.g),b=color(start.b,end.b),opacity=nogamma(start.opacity,end.opacity);return function(t){return start.r=r(t),start.g=g(t),start.b=b(t),start.opacity=opacity(t),start+""}}return rgb$1.gamma=rgbGamma,rgb$1}(1);function generateSurfaceData(trajectory,stratColumn,surfaceData){if(!(trajectory.length<0)){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";return 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 "+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})}))}(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){return 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]]}))}}))}(mappedSurfaces,trajectory),surfaceAreas=function(projection,surfaces,stratColumn){return 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}),{})}(trajectory,stratigraphies,stratColumn);return{lines:lines,areas:__spreadArray(__spreadArray([],function(groups,trajectory){return groups.map((function(g,i){var next=i+1<groups.length?groups[i+1]:null;return{id:g.id,color:convertColor(g.color),data:trajectory.map((function(p,j){return[p[0],g.top[j],next?next.top[j]:null]}))}}))}(function(stratGroups,surfaceAreas){return 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 '"+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]}))}}))}(stratGroups,surfaceAreas),trajectory)),Object.values(surfaceAreas).flat().filter((function(d){return!d.exclude})))}}}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(function(interpolator,n){for(var samples=new Array(n),i=0;i<n;++i)samples[i]=interpolator(i/(n-1));return samples}(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,first=(path=nPoints>0?simplify(interpolator.getPoints(nPoints),5e-4,10):[[points[0][0],points[0][1]]])[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}return 0===len?new Vector2([0,0]):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),Vector2.angleRight(initial),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]}))}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}function getSeismicInfo(data,trajectory){if(data&&data.datapoints){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),[val]))}),0),max=dp.reduce((function(val,array){return Math.max.apply(Math,__spreadArray(__spreadArray([],array),[val]))}),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),[val]))}),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),[val]))}),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 mapPick(p,groupName){return{title:p.pickIdentifier||p.identifier,group:groupName,label:p.md+" "+p.mdUnit+" "+p.depthReferencePoint,color:"strat-picks"===groupName?"#227":"rgba(0,0,0,0.8)",md:p.md}}function getPicksData(picksData){var formationPicks,unitPicks=picksData.unitPicks,picks=__spreadArray(__spreadArray(__spreadArray([],function(picks){return picks?picks.map((function(p){return mapPick(p,"ref-picks")})):[]}(picksData.nonUnitPicks)),(formationPicks=unitPicks)?formationPicks.filter((function(d){return d.entryPick.md===d.from})).map((function(p){return mapPick(p.entryPick,"strat-picks")})):[]),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}))})):[]}(unitPicks));return picks.sort((function(a,b){return a.md-b.md})),picks}function transformFormationData(picks,stratColumn){for(var _a=function(picks,stratColumn){var transformed=function(units,res){void 0===res&&(res=[]);for(var i=0;i<units.length;i+=1){var unit={unitName:(u=units[i]).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};res.push(unit)}var u;return res}(stratColumn),nonUnitPicks=[],joined=[];return picks.forEach((function(p){var matches=transformed.filter((function(u){return-1!==p.pickIdentifier.search(new RegExp("("+u.topSurface+"|"+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(p)})),{joined:joined,nonUnitPicks:nonUnitPicks}}(picks,stratColumn),joined=_a.joined,nonUnitPicks=_a.nonUnitPicks,itemstack=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 "+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 "+pairWithName+" pick for "+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 "+name_1+" pick at "+top_1.md+", ignored"),"continue";console.warn("Using "+base.identifier+" as base for "+name_1)}else{if(!isBase)return console.warn(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 "+name_1+" pick at "+base.md+", ignored"),"continue";console.warn("Using "+top_1.identifier+" as top for "+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).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 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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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);_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)},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 data=this.data.areas[0].data,maxX=Math.max(data[data.length-1][0],data[0][0]),minX=Math.min(data[0][0],data[data.length-1][0]),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[1]<dy1},GeomodelLabelsLayer}(CanvasLayer);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 "+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=fontStyle+" "+fontSize+"px "+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),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),WellboreBaseComponentLayer=function(_super){function WellboreBaseComponentLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.getMdPoint=function(md){return{point:_this.referenceSystem.project(md),md:md}},_this.getPathForPoints=function(start,end,interestPoints){var pathPoints=_this.referenceSystem.getCurtainPath(start,end),interestMdPoints=interestPoints.filter((function(ip){return!pathPoints.some((function(p){return p.md===ip}))})).map(_this.getMdPoint),points=__spreadArray(__spreadArray([],pathPoints),interestMdPoints);return points.sort((function(a,b){return a.md-b.md})),points},_this.getZFactorScaledPathForPoints=function(start,end,interestPoints){var y=function(y){return y*_this.rescaleEvent.zFactor};return _this.getPathForPoints(start,end,interestPoints).map((function(p){return{point:[p.point[0],y(p.point[1])],md:p.md}}))},_this.drawBigPolygon=function(coords,color){void 0===color&&(color=0);var polygon=new Graphics;return polygon.beginFill(color),polygon.drawPolygon(coords),polygon.endFill(),_this.ctx.stage.addChild(polygon),polygon},_this.drawBigTexturedPolygon=function(coords,t){var polygon=new Graphics;return polygon.beginTextureFill({texture:t}),polygon.drawPolygon(coords),polygon.endFill(),_this.ctx.stage.addChild(polygon),polygon},_this.options=__assign(__assign(__assign({},_this.options),{exaggerationFactor:2}),options),_this.render=_this.render.bind(_this),_this}return __extends(WellboreBaseComponentLayer,_super),WellboreBaseComponentLayer.prototype.onUnmount=function(event){_super.prototype.onUnmount.call(this,event),this._textureCache=null,this.rescaleEvent=null},WellboreBaseComponentLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clear(),this.render()},WellboreBaseComponentLayer.prototype.onRescale=function(event){var _a,shouldRender=(null===(_a=this.rescaleEvent)||void 0===_a?void 0:_a.zFactor)!==event.zFactor;if(this.rescaleEvent=event,_super.prototype.optionsRescale.call(this,event),this.ctx){var yRatio=this.yRatio(),flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.ctx.stage.position.set(event.xScale(0),event.yScale(0)),this.ctx.stage.scale.set(event.xRatio*(flippedX?-1:1),yRatio*(flippedY?-1:1)),shouldRender&&(this.clear(),this.render())}},WellboreBaseComponentLayer.prototype.clear=function(){this.ctx.stage.removeChildren().forEach((function(child){child.destroy()}))},WellboreBaseComponentLayer.prototype.yRatio=function(){var domain=this.rescaleEvent.yScale.domain(),baseYSpan=(domain[1]-domain[0])*this.rescaleEvent.zFactor,baseDomain=[domain[0],domain[0]+baseYSpan];return Math.abs(this.rescaleEvent.height/(baseDomain[1]-baseDomain[0]))},WellboreBaseComponentLayer.prototype.drawRopeWithMask=function(path,maskPolygon,texture){if(0===maskPolygon.length||0===path.length)return null;var rope=new SimpleRope(texture,path,1),mask=new Graphics;mask.beginFill(0),mask.drawPolygon(maskPolygon),mask.endFill(),this.ctx.stage.addChild(mask),rope.mask=mask,this.ctx.stage.addChild(rope)},WellboreBaseComponentLayer.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.ctx.stage.addChild(rope)},WellboreBaseComponentLayer.prototype.drawOutline=function(leftPath,rightPath,lineColor,lineWidth,close){void 0===lineWidth&&(lineWidth=1),void 0===close&&(close=!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,1),line.moveTo(startPointRight.x,startPointRight.y),rightPath.forEach((function(p){return line.lineTo(p.x,p.y)})),close||line.moveTo(startPointLeft.x,startPointLeft.y),leftPathReverse.forEach((function(p){return line.lineTo(p.x,p.y)})),close&&line.lineTo(startPointRight.x,startPointRight.y),this.ctx.stage.addChild(line)},WellboreBaseComponentLayer}(PixiLayer),makeTubularPolygon=function(rightPath,leftPath){return __spreadArray(__spreadArray([],leftPath),rightPath.map((function(d){return d.clone()})).reverse())},overlaps=function(top1,bottom1,top2,bottom2){return top1<=bottom2&&top2<=bottom1},cementDiameterChangeDepths=function(cement,bottomOfCement,diameterIntervals){var arr,topOfCement=cement.toc,diameterChangeDepths=merge(diameterIntervals.map((function(d){return[d.start-1e-4,d.start,d.end,d.end+1e-4]}))).filter((function(d){return d>=topOfCement&&d<=bottomOfCement}));return diameterChangeDepths.push(topOfCement),diameterChangeDepths.push(bottomOfCement),(arr=diameterChangeDepths,Array.from(new Set(arr))).sort((function(a,b){return a-b}))},arrayToVector=function(a){return new Vector2(a[0],a[1])},createNormals=function(points){return points.length<2?[new Vector2(0)]:points.map((function(coord,i,list){if(i<list.length-1){var p=arrayToVector(list[i]),rotate=arrayToVector(list[i+1]).sub(p).rotate90();return n=rotate.normalized()}return n}));var n},offsetPoint=function(point,vector,offset){var v,p=arrayToVector(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)}))},HoleSizeLayer=function(_super){function HoleSizeLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.drawHoleSize=function(holeObject){if(null!=holeObject){var _a=_this.options,exaggerationFactor=_a.exaggerationFactor,firstColor=_a.firstColor,lineColor=_a.lineColor,diameter=holeObject.diameter*exaggerationFactor,radius=diameter/2,pathPoints=_this.getZFactorScaledPathForPoints(holeObject.start,holeObject.end,[holeObject.start,holeObject.end]).map((function(p){return p.point})),normals=createNormals(pathPoints),rightPath=offsetPoints(pathPoints,normals,radius),leftPath=offsetPoints(pathPoints,normals,-radius);if(0!==pathPoints.length){if(_this.renderType()===RENDERER_TYPE.CANVAS){var polygonCoords=makeTubularPolygon(leftPath,rightPath);_this.drawBigPolygon(polygonCoords,convertColor(firstColor))}else{var texture=_this.createTexture(diameter);_this.drawRope(pathPoints.map((function(p){return new Point(p[0],p[1])})),texture)}_this.drawOutline(leftPath,rightPath,lineColor,1,!1)}}},_this.options=__assign(__assign(__assign({},_this.options),{firstColor:"rgb(140, 84, 29)",secondColor:"rgb(238, 227, 216)",lineColor:9127187}),options),_this}return __extends(HoleSizeLayer,_super),HoleSizeLayer.prototype.render=function(){var _this=this,data=this.data;data&&this.rescaleEvent&&this.referenceSystem&&(data.sort((function(a,b){return b.diameter-a.diameter})),this.maxDiameter=data.length>0?data[0].diameter:100,data.forEach((function(hole){return _this.drawHoleSize(hole)})))},HoleSizeLayer.prototype.createTexture=function(diameter){var exaggerationFactor=this.options.exaggerationFactor,height=this.maxDiameter*exaggerationFactor;this._textureCache||(this._textureCache=this.createBaseTexture(16,height));var baseTexture=this._textureCache.baseTexture,sidePadding=Math.floor((height-diameter)/2),frame=new Rectangle(0,sidePadding,16,diameter);return new Texture(baseTexture,frame)},HoleSizeLayer.prototype.createBaseTexture=function(width,height){var _a=this.options,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)},HoleSizeLayer}(WellboreBaseComponentLayer),CasingLayer=function(_super){function CasingLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.prepareCasingRenderObject=function(casing){if(null!=casing){var exaggerationFactor=_this.options.exaggerationFactor,diameter=casing.diameter*exaggerationFactor,radius=diameter/2,innerRadius=casing.innerDiameter*exaggerationFactor/2,pathPoints=_this.getZFactorScaledPathForPoints(casing.start,casing.end,[casing.start,casing.end]).map((function(p){return p.point})),normals=createNormals(pathPoints),rightPath=offsetPoints(pathPoints,normals,radius),leftPath=offsetPoints(pathPoints,normals,-radius);return{pathPoints:pathPoints,polygon:makeTubularPolygon(leftPath,rightPath),leftPath:leftPath,rightPath:rightPath,radius:radius,diameter:diameter,casingWallWidth:Math.abs(radius-innerRadius)}}},_this.drawCasing=function(zippedRenderObject){var _a=_this.options,lineColor=_a.lineColor,solidColor=_a.solidColor,casing=zippedRenderObject[0],_b=zippedRenderObject[1],pathPoints=_b.pathPoints,polygon=_b.polygon,leftPath=_b.leftPath,rightPath=_b.rightPath,radius=_b.radius,diameter=_b.diameter,casingWallWidth=_b.casingWallWidth;if(_this.renderType()===RENDERER_TYPE.CANVAS)_this.drawBigPolygon(polygon,solidColor);else{var texture=_this.createTexture(diameter);_this.drawRope(pathPoints.map((function(p){return new Point(p[0],p[1])})),texture,solidColor)}_this.drawOutline(leftPath,rightPath,lineColor,casingWallWidth,!0),casing.hasShoe&&_this.drawShoe(casing.end,radius)},_this.generateShoe=function(casingEnd,casingRadius,length,width){var start=casingEnd-length,end=casingEnd,points=_this.getZFactorScaledPathForPoints(start,end,[start,end]).map((function(p){return p.point})),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);return __spreadArray(__spreadArray([],shoeEdge),[shoeTip])},_this.options=__assign(__assign(__assign({},_this.options),{solidColor:14474460,lineColor:5723991}),options),_this}return __extends(CasingLayer,_super),CasingLayer.prototype.render=function(){var _this=this,data=this.data;if(data&&this.rescaleEvent&&this.referenceSystem){var sortedCasings=data.sort((function(a,b){return b.diameter-a.diameter})),casingRenderObjects=sortedCasings.map((function(casing){return _this.prepareCasingRenderObject(casing)}));zip(sortedCasings,casingRenderObjects).forEach((function(zippedRenderObject){return _this.drawCasing(zippedRenderObject)}))}},CasingLayer.prototype.drawShoe=function(casingEnd,casingRadius){var exaggerationFactor=this.options.exaggerationFactor,shoeWidth=25*exaggerationFactor,shoeLength=12*exaggerationFactor,shoeCoords=this.generateShoe(casingEnd,casingRadius,shoeLength,shoeWidth),shoeCoords2=this.generateShoe(casingEnd,casingRadius,shoeLength,-shoeWidth);this.drawBigPolygon(shoeCoords2),this.drawBigPolygon(shoeCoords)},CasingLayer.prototype.createTexture=function(diameter){return new Texture(Texture.WHITE.baseTexture,null,new Rectangle(0,0,16,diameter))},CasingLayer}(WellboreBaseComponentLayer),CementLayer=function(_super){function CementLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.createCementShape=function(cement,casings,holes){var exaggerationFactor=_this.options.exaggerationFactor,attachedCasings=__spreadArray([cement.casingId],cement.casingIds||[]).filter((function(id){return id})).map((function(casingId){return casings.find((function(casing){return casing.casingId===casingId}))}));if(0===attachedCasings.length||attachedCasings.includes(void 0))throw new Error("Invalid cement data, cement is missing attached casing");attachedCasings.sort((function(a,b){return a.end-b.end}));for(var bottomOfCement=attachedCasings[attachedCasings.length-1].end,_a=function(cement,bottomOfCement,parentCasings,casings,holes){var start=cement.toc,end=bottomOfCement;return{holes:holes.filter((function(h){return overlaps(start,end,h.start,h.end)})),outerCasings:casings.filter((function(c){return!parentCasings.includes(c)})).filter((function(c){return overlaps(start,end,c.start,c.end)}))}}(cement,bottomOfCement,attachedCasings,casings,holes),outerCasings=_a.outerCasings,overlappingHoles=_a.holes,innerDiameterIntervals=attachedCasings,outerDiameterIntervals=__spreadArray(__spreadArray([],outerCasings),overlappingHoles).map((function(d){return{start:d.start,end:d.end}})),diameterAtChangeDepths=cementDiameterChangeDepths(cement,bottomOfCement,__spreadArray(__spreadArray([],innerDiameterIntervals),outerDiameterIntervals)).map(function(innerCasing,nonAttachedCasings,holes){return function(depth){var outerDiameter,innerCasingAtDepth=innerCasing.find((function(casing){return casing.start<=depth&&casing.end>=depth})),innerDiameter=innerCasingAtDepth?innerCasingAtDepth.diameter:0,outerCasings=nonAttachedCasings.filter((function(casing){return casing.innerDiameter>innerDiameter})),holeAtDepth=holes.find((function(hole){return hole.start<=depth&&hole.end>=depth&&hole.diameter>innerDiameter})),outerCasingAtDepth=outerCasings.filter((function(d){return d})).sort((function(a,b){return a.innerDiameter-b.innerDiameter})).find((function(casing){return casing.start<=depth&&casing.end>=depth&&casing.diameter>innerDiameter}));return outerDiameter=outerCasingAtDepth?outerCasingAtDepth.innerDiameter:holeAtDepth?holeAtDepth.diameter-1:100,{md:depth,innerDiameter:innerDiameter,outerDiameter:outerDiameter}}}(attachedCasings,outerCasings,overlappingHoles)),path=_this.getZFactorScaledPathForPoints(cement.toc,bottomOfCement,diameterAtChangeDepths.map((function(d){return d.md}))),normals=createNormals(path.map((function(p){return p.point}))),pathWithNormals=path.map((function(p,i){return __assign(__assign({},p),{normal:normals[i]})})),side1Left=[],side1Right=[],side2Left=[],side2Right=[],previousDepth=diameterAtChangeDepths.shift(),_loop_1=function(depth){var intervalMdPoints=pathWithNormals.filter((function(x){return x.md>=previousDepth.md&&x.md<=depth.md})),intervalPoints=intervalMdPoints.map((function(s){return s.point})),intervalPointNormals=intervalMdPoints.map((function(s){return s.normal})),outerRadius=previousDepth.outerDiameter/2*exaggerationFactor,innerRadius=previousDepth.innerDiameter/2*exaggerationFactor,intervalSide1Left=offsetPoints(intervalPoints,intervalPointNormals,outerRadius),intervalSide1Right=offsetPoints(intervalPoints,intervalPointNormals,innerRadius),intervalSide2Left=offsetPoints(intervalPoints,intervalPointNormals,-innerRadius),intervalSide2Right=offsetPoints(intervalPoints,intervalPointNormals,-outerRadius);side1Left.push.apply(side1Left,intervalSide1Left),side1Right.push.apply(side1Right,intervalSide1Right),side2Left.push.apply(side2Left,intervalSide2Left),side2Right.push.apply(side2Right,intervalSide2Right),previousDepth=depth},_i=0,diameterAtChangeDepths_1=diameterAtChangeDepths;_i<diameterAtChangeDepths_1.length;_i++){_loop_1(diameterAtChangeDepths_1[_i])}var pathPoints=pathWithNormals.map((function(p){return new Point(p.point[0],p.point[1])}));return{leftPolygon:makeTubularPolygon(side1Left,side1Right),rightPolygon:makeTubularPolygon(side2Left,side2Right),path:pathPoints}},_this.options=__assign(__assign(__assign({},_this.options),{firstColor:"#c7b9ab",secondColor:"#5b5b5b"}),options),_this}return __extends(CementLayer,_super),CementLayer.prototype.render=function(){var _this=this;if(this.data&&this.rescaleEvent&&this.referenceSystem){var _a=this.data,cement=_a.cement,casings=_a.casings,holes=_a.holes,cementShapes=cement.map((function(cement){return _this.createCementShape(cement,casings,holes)})),texture=this.createTexture();cementShapes.forEach((function(cementShape){_this.renderType()===RENDERER_TYPE.CANVAS?(_this.drawBigTexturedPolygon(cementShape.leftPolygon,texture),_this.drawBigTexturedPolygon(cementShape.rightPolygon,texture)):(_this.drawRopeWithMask(cementShape.path,cementShape.leftPolygon,texture),_this.drawRopeWithMask(cementShape.path,cementShape.rightPolygon,texture))}))}},CementLayer.prototype.createTexture=function(){if(this._textureCache)return this._textureCache;var _a=this.options,firstColor=_a.firstColor,secondColor=_a.secondColor,canvas=document.createElement("canvas");canvas.width=150,canvas.height=150;var canvasCtx=canvas.getContext("2d");canvasCtx.fillStyle=firstColor,canvasCtx.fillRect(0,0,canvas.width,canvas.height),canvasCtx.lineWidth=1,canvasCtx.fillStyle=secondColor,canvasCtx.beginPath(),canvasCtx.lineWidth=1;for(var i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+10*i,-canvas.height),canvasCtx.lineTo(canvas.width+10*i,canvas.height);return canvasCtx.stroke(),this._textureCache=Texture.from(canvas),this._textureCache},CementLayer}(WellboreBaseComponentLayer),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),CompletionLayer=function(_super){function CompletionLayer(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(CompletionLayer,_super),CompletionLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.render()},CompletionLayer.prototype.render=function(){var _a,_this=this,wellborePath=this.referenceSystem?this.referenceSystem.projectedPath:[];null!=wellborePath&&((null===(_a=this.data)||void 0===_a?void 0:_a.length)>0?this.data.map((function(d){return _this.generateCompletionItem(wellborePath,d)})):[]).map((function(s){return _this.drawCompletionItem(s)}))},CompletionLayer.prototype.getShape=function(type){var graphics=new Graphics;return graphics.beginFill(3421236),graphics.drawRect(-5,-5,10,10),graphics.endFill(),graphics},CompletionLayer.prototype.getScale=function(type,length,width){return{scaleX:1,scaleY:1}},CompletionLayer.prototype.generateCompletionItem=function(wbp,data){if(this.referenceSystem){var pointTop=this.referenceSystem.project(data.start),pointBottom=this.referenceSystem.project(data.end),rotation=Vector2.angle(pointTop,pointBottom),graphics=this.getShape(data.shape),_a=this.getScale(data.shape,data.start-data.end,data.diameter),scaleX=_a.scaleX,scaleY=_a.scaleY,x=pointTop[0],y=pointTop[1];return graphics.setTransform(x,y,scaleX,scaleY,rotation),{graphics:graphics}}},CompletionLayer.prototype.drawCompletionItem=function(item){this.ctx.stage.addChild(item.graphics)},CompletionLayer}(PixiLayer),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.onZoom=this.onZoom.bind(this),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;_a.ySpan;var 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;_a.ySpan;var 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){void 0===cx&&(cx=null),void 0===cy&&(cy=null),void 0===displ&&(displ=null),void 0===duration&&(duration=null);var _a=this,zoom=_a.zoom,container=_a.container,calculateTransform=_a.calculateTransform;_a.viewportRatio;var scaleX=_a.scaleX,scaleY=_a.scaleY,isXInverted=_a.isXInverted;if(null===cx||null===displ){var xd=scaleX.domain(),dspan=xd[1]-xd[0];null===cx&&(cx=xd[0]+dspan/2||0),null===displ&&(displ=Math.abs(dspan)||1)}if(null===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.containerWidth,h=_b.containerHeight}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}(),Axis=function(){function Axis(mainGroup,showLabels,labelXDesc,labelYDesc,unitOfMeasure,options){var _this=this;void 0===showLabels&&(showLabels=!0),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."+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(labelXDesc+" ("+unitOfMeasure+")")):labelx.remove(),labelx.attr("transform","translate("+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(labelYDesc+" ("+unitOfMeasure+")")),labely.attr("transform","translate(-10,"+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("+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 "+height+")"),gx.call(xAxis),gx},Axis.prototype.render=function(){this.renderLabelx(),this.renderLabely()},Axis.prototype.onResize=function(event){this.mainGroup.attr("height",event.height+"px").attr("width",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}(),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",container.offsetHeight+"px").attr("width",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}))},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",""+(highestZIndex+1))}return this},LayerManager.prototype.showLayer=function(layerId){var layer=this.getLayer(layerId);return layer.setVisibility(!0),layer.onRescale(this.zoomPanHandler.currentStateAsEvent()),this},LayerManager.prototype.hideLayer=function(layerId){return this.getLayer(layerId).setVisibility(!1),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}(),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;return void 0===from&&(from=0),void 0===to&&(to=1),0===from&&1===to?this.length: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(start,end){if(!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}return this._curtainPathCache.filter((function(p){return p.md>=start&&p.md<=end}))},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())}points.push.apply(points,this.interpolators.trajectory.getPoints(curveSteps,null,0,1));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}(),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",width+"px").style("height",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){return layers.length>0?layers.reduce((function(max,layers){return max.order>layers.order?max:layers})).order:1},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,CasingLayer,CementLayer,CompletionLayer,Controller,GeomodelCanvasLayer,GeomodelLabelsLayer,GeomodelLayer,GeomodelLayerV2,GridLayer,HTMLLayer,HoleSizeLayer,ImageLayer,IntersectionReferenceSystem,Layer,LayerManager,PixiLayer,SVGLayer,SeismicCanvasLayer,WellborepathLayer,ZoomPanHandler,calcSize,findIndexOfSample,findSampleAtPos,generateProjectedTrajectory,generateProjectedWellborePath,generateSeismicSliceImage,generateSurfaceData,getOverlap,getOverlapOffset,getPicksData,getSeismicInfo,isOverlapping,isOverlappingHorizontally,pixelsPerUnit,transformFormationData};
15
+ ***************************************************************************** */var 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])})(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}).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(;_;)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){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to}var defaultOptions={order:1,layerOpacity:1,interactive:!1},Layer=function(){function Layer(id,options){this._referenceSystem=null,this._interactive=!1,this._id=id||"layer-"+Math.floor(1e3*Math.random());var opts=options||defaultOptions;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){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.onOpacityChanged=function(opacity){},Layer.prototype.onOrderChanged=function(order){},Layer.prototype.onInteractivityChanged=function(interactive){},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:"+interactive+";z-index:"+this.order+";opacity:"+this.opacity+";visibility:"+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",""+this.id),this.canvas.setAttribute("width",width+"px"),this.canvas.setAttribute("height",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",width+"px"),ctx.canvas.setAttribute("height",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),defaultOptions$1={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$1),_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),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",""+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),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",""+this.id),this.elm.attr("class","html-layer"));var interactive=this.interactive?"auto":"none";this.elm.style("position","absolute").style("height",height+"px").style("width",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",event.height+"px").style("width",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),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),PixiRenderApplication=function(){function PixiRenderApplication(pixiRenderOptions){this.renderer=autoDetectRenderer(pixiRenderOptions),this.stage=new Container}return PixiRenderApplication.prototype.destroy=function(){this.stage.destroy({children:!0,texture:!0,baseTexture:!0}),this.stage=null,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(id,options){return _super.call(this,id,options)||this}return __extends(PixiLayer,_super),PixiLayer.prototype.onMount=function(event){if(_super.prototype.onMount.call(this,event),!this.elm){var container=document.createElement("div");container.setAttribute("id",""+this.id),container.setAttribute("class","webgl-layer"),this.elm=container,this.updateStyle();var elm=event.elm,height=event.height,width=event.width,pixiApplicationOptions=this.options.pixiApplicationOptions,pixiOptions=__assign({width:width||parseInt(this.elm.getAttribute("width"),10)||200,height:height||parseInt(this.elm.getAttribute("height"),10)||300,antialias:!0,transparent:!0,clearBeforeRender:!0,autoResize:!0,preserveDrawingBuffer:!0},pixiApplicationOptions);this.ctx=new PixiRenderApplication(pixiOptions),container.appendChild(this.ctx.view),elm.appendChild(container)}},PixiLayer.prototype.render=function(){this.ctx.render()},PixiLayer.prototype.onUnmount=function(event){var _a,_b;_super.prototype.onUnmount.call(this,event);var renderType=this.renderType(),glContext=this.ctx.renderer instanceof Renderer?null===(_a=this.ctx.renderer)||void 0===_a?void 0:_a.gl:void 0;this.ctx.destroy(),this.ctx=void 0,renderType===RENDERER_TYPE.WEBGL&&glContext&&(null===(_b=null==glContext?void 0:glContext.getExtension("WEBGL_lose_context"))||void 0===_b||_b.loseContext()),this.elm.remove(),this.elm=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){if(_super.prototype.onRescale.call(this,event),this.ctx){var flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.ctx.stage.position.set(event.xScale(0),event.yScale(0)),this.ctx.stage.scale.set(event.xRatio*(flippedX?-1:1),event.yRatio*(flippedY?-1:1))}},PixiLayer.prototype.updateStyle=function(visible){var visibility=visible||this.isVisible?"visible":"hidden",interactive=this.interactive?"auto":"none";this.elm.setAttribute("style","position:absolute;pointer-events:"+interactive+";z-index:"+this.order+";opacity:"+this.opacity+";visibility:"+visibility)},PixiLayer.prototype.setVisibility=function(visible){_super.prototype.setVisibility.call(this,visible),this.elm&&this.updateStyle(visible)},PixiLayer.prototype.onOpacityChanged=function(opacity){this.elm&&this.updateStyle()},PixiLayer.prototype.onOrderChanged=function(order){this.elm&&this.updateStyle()},PixiLayer.prototype.onInteractivityChanged=function(interactive){this.elm&&this.updateStyle()},PixiLayer.prototype.renderType=function(){return this.ctx.renderer.type},PixiLayer}(Layer),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.ctx.stage.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.ctx.stage.addChild(g)},_this}return __extends(GeomodelLayerV2,_super),GeomodelLayerV2.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.isPreRendered||(this.clearStage(),this.preRender()),this.render()},GeomodelLayerV2.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.isPreRendered=!1,this.clearStage(),this.preRender(),this.render()},GeomodelLayerV2.prototype.clearStage=function(){this.ctx.stage.children.forEach((function(g){return g.destroy()})),this.ctx.stage.removeChildren()},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),GeomodelLayer=function(_super){function GeomodelLayer(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(GeomodelLayer,_super),GeomodelLayer}(GeomodelLayerV2);function define(constructor,factory,prototype){constructor.prototype=factory.prototype=prototype,prototype.constructor=constructor}function extend(parent,definition){var prototype=Object.create(parent.prototype);for(var key in definition)prototype[key]=definition[key];return prototype}function Color(){}var brighter=1/.7,reI="\\s*([+-]?\\d+)\\s*",reN="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",reP="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",reHex=/^#([0-9a-f]{3,8})$/,reRgbInteger=new RegExp("^rgb\\("+[reI,reI,reI]+"\\)$"),reRgbPercent=new RegExp("^rgb\\("+[reP,reP,reP]+"\\)$"),reRgbaInteger=new RegExp("^rgba\\("+[reI,reI,reI,reN]+"\\)$"),reRgbaPercent=new RegExp("^rgba\\("+[reP,reP,reP,reN]+"\\)$"),reHslPercent=new RegExp("^hsl\\("+[reN,reP,reP]+"\\)$"),reHslaPercent=new RegExp("^hsla\\("+[reN,reP,reP,reN]+"\\)$"),named={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function color_formatHex(){return this.rgb().formatHex()}function color_formatRgb(){return this.rgb().formatRgb()}function color(format){var m,l;return format=(format+"").trim().toLowerCase(),(m=reHex.exec(format))?(l=m[1].length,m=parseInt(m[1],16),6===l?rgbn(m):3===l?new Rgb(m>>8&15|m>>4&240,m>>4&15|240&m,(15&m)<<4|15&m,1):8===l?rgba(m>>24&255,m>>16&255,m>>8&255,(255&m)/255):4===l?rgba(m>>12&15|m>>8&240,m>>8&15|m>>4&240,m>>4&15|240&m,((15&m)<<4|15&m)/255):null):(m=reRgbInteger.exec(format))?new Rgb(m[1],m[2],m[3],1):(m=reRgbPercent.exec(format))?new Rgb(255*m[1]/100,255*m[2]/100,255*m[3]/100,1):(m=reRgbaInteger.exec(format))?rgba(m[1],m[2],m[3],m[4]):(m=reRgbaPercent.exec(format))?rgba(255*m[1]/100,255*m[2]/100,255*m[3]/100,m[4]):(m=reHslPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,1):(m=reHslaPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,m[4]):named.hasOwnProperty(format)?rgbn(named[format]):"transparent"===format?new Rgb(NaN,NaN,NaN,0):null}function rgbn(n){return new Rgb(n>>16&255,n>>8&255,255&n,1)}function rgba(r,g,b,a){return a<=0&&(r=g=b=NaN),new Rgb(r,g,b,a)}function rgbConvert(o){return o instanceof Color||(o=color(o)),o?new Rgb((o=o.rgb()).r,o.g,o.b,o.opacity):new Rgb}function rgb(r,g,b,opacity){return 1===arguments.length?rgbConvert(r):new Rgb(r,g,b,null==opacity?1:opacity)}function Rgb(r,g,b,opacity){this.r=+r,this.g=+g,this.b=+b,this.opacity=+opacity}function rgb_formatHex(){return"#"+hex(this.r)+hex(this.g)+hex(this.b)}function rgb_formatRgb(){var a=this.opacity;return(1===(a=isNaN(a)?1:Math.max(0,Math.min(1,a)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===a?")":", "+a+")")}function hex(value){return((value=Math.max(0,Math.min(255,Math.round(value)||0)))<16?"0":"")+value.toString(16)}function hsla(h,s,l,a){return a<=0?h=s=l=NaN:l<=0||l>=1?h=s=NaN:s<=0&&(h=NaN),new Hsl(h,s,l,a)}function hslConvert(o){if(o instanceof Hsl)return new Hsl(o.h,o.s,o.l,o.opacity);if(o instanceof Color||(o=color(o)),!o)return new Hsl;if(o instanceof Hsl)return o;var r=(o=o.rgb()).r/255,g=o.g/255,b=o.b/255,min=Math.min(r,g,b),max=Math.max(r,g,b),h=NaN,s=max-min,l=(max+min)/2;return s?(h=r===max?(g-b)/s+6*(g<b):g===max?(b-r)/s+2:(r-g)/s+4,s/=l<.5?max+min:2-max-min,h*=60):s=l>0&&l<1?0:h,new Hsl(h,s,l,o.opacity)}function Hsl(h,s,l,opacity){this.h=+h,this.s=+s,this.l=+l,this.opacity=+opacity}function hsl2rgb(h,m1,m2){return 255*(h<60?m1+(m2-m1)*h/60:h<180?m2:h<240?m1+(m2-m1)*(240-h)/60:m1)}function convertColor(colorStr){var d=color(colorStr).hex();return parseInt(d.replace("#","0x"))}define(Color,color,{copy:function(channels){return Object.assign(new this.constructor,this,channels)},displayable:function(){return this.rgb().displayable()},hex:color_formatHex,formatHex:color_formatHex,formatHsl:function(){return hslConvert(this).formatHsl()},formatRgb:color_formatRgb,toString:color_formatRgb}),define(Rgb,rgb,extend(Color,{brighter:function(k){return k=null==k?brighter:Math.pow(brighter,k),new Rgb(this.r*k,this.g*k,this.b*k,this.opacity)},darker:function(k){return k=null==k?.7:Math.pow(.7,k),new Rgb(this.r*k,this.g*k,this.b*k,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:rgb_formatHex,formatHex:rgb_formatHex,formatRgb:rgb_formatRgb,toString:rgb_formatRgb})),define(Hsl,(function(h,s,l,opacity){return 1===arguments.length?hslConvert(h):new Hsl(h,s,l,null==opacity?1:opacity)}),extend(Color,{brighter:function(k){return k=null==k?brighter:Math.pow(brighter,k),new Hsl(this.h,this.s,this.l*k,this.opacity)},darker:function(k){return k=null==k?.7:Math.pow(.7,k),new Hsl(this.h,this.s,this.l*k,this.opacity)},rgb:function(){var h=this.h%360+360*(this.h<0),s=isNaN(h)||isNaN(this.s)?0:this.s,l=this.l,m2=l+(l<.5?l:1-l)*s,m1=2*l-m2;return new Rgb(hsl2rgb(h>=240?h-240:h+120,m1,m2),hsl2rgb(h,m1,m2),hsl2rgb(h<120?h+240:h-120,m1,m2),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var a=this.opacity;return(1===(a=isNaN(a)?1:Math.max(0,Math.min(1,a)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===a?")":", "+a+")")}}));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),Object.defineProperty(GeomodelCanvasLayer.prototype,"data",{get:function(){return _super.prototype.getData.call(this)},set:function(data){this.setData(data)},enumerable:!1,configurable:!0}),GeomodelCanvasLayer.prototype.getData=function(){return _super.prototype.getData.call(this)},GeomodelCanvasLayer.prototype.setData=function(data){_super.prototype.setData.call(this,data)},GeomodelCanvasLayer.prototype.onMount=function(event){_super.prototype.onMount.call(this,event)},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 hexString=color.toString(16);return"#"+("000000".substr(0,6-hexString.length)+hexString)}(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),constant=x=>()=>x;function gamma(y){return 1==(y=+y)?nogamma:function(a,b){return b-a?function(a,b,y){return a=Math.pow(a,y),b=Math.pow(b,y)-a,y=1/y,function(t){return Math.pow(a+t*b,y)}}(a,b,y):constant(isNaN(a)?b:a)}}function nogamma(a,b){var d=b-a;return d?function(a,d){return function(t){return a+t*d}}(a,d):constant(isNaN(a)?b:a)}var interpolateRgb=function rgbGamma(y){var color=gamma(y);function rgb$1(start,end){var r=color((start=rgb(start)).r,(end=rgb(end)).r),g=color(start.g,end.g),b=color(start.b,end.b),opacity=nogamma(start.opacity,end.opacity);return function(t){return start.r=r(t),start.g=g(t),start.b=b(t),start.opacity=opacity(t),start+""}}return rgb$1.gamma=rgbGamma,rgb$1}(1);function generateSurfaceData(trajectory,stratColumn,surfaceData){if(!(trajectory.length<0)){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";return 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 "+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})}))}(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){return 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]]}))}}))}(mappedSurfaces,trajectory),surfaceAreas=function(projection,surfaces,stratColumn){return 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}),{})}(trajectory,stratigraphies,stratColumn);return{lines:lines,areas:__spreadArray(__spreadArray([],function(groups,trajectory){return groups.map((function(g,i){var next=i+1<groups.length?groups[i+1]:null;return{id:g.id,color:convertColor(g.color),data:trajectory.map((function(p,j){return[p[0],g.top[j],next?next.top[j]:null]}))}}))}(function(stratGroups,surfaceAreas){return 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 '"+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]}))}}))}(stratGroups,surfaceAreas),trajectory)),Object.values(surfaceAreas).flat().filter((function(d){return!d.exclude})))}}}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(function(interpolator,n){for(var samples=new Array(n),i=0;i<n;++i)samples[i]=interpolator(i/(n-1));return samples}(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,first=(path=nPoints>0?simplify(interpolator.getPoints(nPoints),5e-4,10):[[points[0][0],points[0][1]]])[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}return 0===len?new Vector2([0,0]):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),Vector2.angleRight(initial),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]}))}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}function getSeismicInfo(data,trajectory){if(data&&data.datapoints){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),[val]))}),0),max=dp.reduce((function(val,array){return Math.max.apply(Math,__spreadArray(__spreadArray([],array),[val]))}),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),[val]))}),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),[val]))}),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 mapPick(p,groupName){return{title:p.pickIdentifier||p.identifier,group:groupName,label:p.md+" "+p.mdUnit+" "+p.depthReferencePoint,color:"strat-picks"===groupName?"#227":"rgba(0,0,0,0.8)",md:p.md}}function getPicksData(picksData){var formationPicks,unitPicks=picksData.unitPicks,picks=__spreadArray(__spreadArray(__spreadArray([],function(picks){return picks?picks.map((function(p){return mapPick(p,"ref-picks")})):[]}(picksData.nonUnitPicks)),(formationPicks=unitPicks)?formationPicks.filter((function(d){return d.entryPick.md===d.from})).map((function(p){return mapPick(p.entryPick,"strat-picks")})):[]),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}))})):[]}(unitPicks));return picks.sort((function(a,b){return a.md-b.md})),picks}function transformFormationData(picks,stratColumn){for(var _a=function(picks,stratColumn){var transformed=function(units,res){void 0===res&&(res=[]);for(var i=0;i<units.length;i+=1){var unit={unitName:(u=units[i]).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};res.push(unit)}var u;return res}(stratColumn),nonUnitPicks=[],joined=[];return picks.forEach((function(p){var matches=transformed.filter((function(u){return-1!==p.pickIdentifier.search(new RegExp("("+u.topSurface+"|"+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(p)})),{joined:joined,nonUnitPicks:nonUnitPicks}}(picks,stratColumn),joined=_a.joined,nonUnitPicks=_a.nonUnitPicks,itemstack=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 "+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 "+pairWithName+" pick for "+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 "+name_1+" pick at "+top_1.md+", ignored"),"continue";console.warn("Using "+base.identifier+" as base for "+name_1)}else{if(!isBase)return console.warn(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 "+name_1+" pick at "+base.md+", ignored"),"continue";console.warn("Using "+top_1.identifier+" as top for "+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).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 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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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=fontSizeInWorldCoords*yRatio+"px "+(_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);_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)},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 data=this.data.areas[0].data,maxX=Math.max(data[data.length-1][0],data[0][0]),minX=Math.min(data[0][0],data[data.length-1][0]),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[1]<dy1},GeomodelLabelsLayer}(CanvasLayer);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 "+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=fontStyle+" "+fontSize+"px "+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),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),WellboreBaseComponentLayer=function(_super){function WellboreBaseComponentLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.getMdPoint=function(md){return{point:_this.referenceSystem.project(md),md:md}},_this.getPathForPoints=function(start,end,interestPoints){var pathPoints=_this.referenceSystem.getCurtainPath(start,end),interestMdPoints=interestPoints.filter((function(ip){return!pathPoints.some((function(p){return p.md===ip}))})).map(_this.getMdPoint),points=__spreadArray(__spreadArray([],pathPoints),interestMdPoints);return points.sort((function(a,b){return a.md-b.md})),points},_this.getZFactorScaledPathForPoints=function(start,end,interestPoints){var y=function(y){return y*_this.rescaleEvent.zFactor};return _this.getPathForPoints(start,end,interestPoints).map((function(p){return{point:[p.point[0],y(p.point[1])],md:p.md}}))},_this.drawBigPolygon=function(coords,color){void 0===color&&(color=0);var polygon=new Graphics;return polygon.beginFill(color),polygon.drawPolygon(coords),polygon.endFill(),_this.ctx.stage.addChild(polygon),polygon},_this.drawBigTexturedPolygon=function(coords,t){var polygon=new Graphics;return polygon.beginTextureFill({texture:t}),polygon.drawPolygon(coords),polygon.endFill(),_this.ctx.stage.addChild(polygon),polygon},_this.options=__assign(__assign(__assign({},_this.options),{exaggerationFactor:2}),options),_this.render=_this.render.bind(_this),_this}return __extends(WellboreBaseComponentLayer,_super),WellboreBaseComponentLayer.prototype.onUnmount=function(event){_super.prototype.onUnmount.call(this,event),this._textureCache=null,this.rescaleEvent=null},WellboreBaseComponentLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clearStage(),this.preRender(),this.render()},WellboreBaseComponentLayer.prototype.onRescale=function(event){var _a,shouldRecalculate=(null===(_a=this.rescaleEvent)||void 0===_a?void 0:_a.zFactor)!==event.zFactor;if(this.rescaleEvent=event,_super.prototype.optionsRescale.call(this,event),this.ctx){var yRatio=this.yRatio(),flippedX=event.xBounds[0]>event.xBounds[1],flippedY=event.yBounds[0]>event.yBounds[1];this.ctx.stage.position.set(event.xScale(0),event.yScale(0)),this.ctx.stage.scale.set(event.xRatio*(flippedX?-1:1),yRatio*(flippedY?-1:1)),shouldRecalculate&&(this.clearStage(),this.preRender()),this.render()}},WellboreBaseComponentLayer.prototype.clearStage=function(){this.ctx.stage.removeChildren().forEach((function(child){child.destroy()}))},WellboreBaseComponentLayer.prototype.yRatio=function(){var domain=this.rescaleEvent.yScale.domain(),baseYSpan=(domain[1]-domain[0])*this.rescaleEvent.zFactor,baseDomain=[domain[0],domain[0]+baseYSpan];return Math.abs(this.rescaleEvent.height/(baseDomain[1]-baseDomain[0]))},WellboreBaseComponentLayer.prototype.drawRopeWithMask=function(path,maskPolygon,texture){if(0===maskPolygon.length||0===path.length)return null;var rope=new SimpleRope(texture,path,1),mask=new Graphics;mask.beginFill(0),mask.drawPolygon(maskPolygon),mask.endFill(),this.ctx.stage.addChild(mask),rope.mask=mask,this.ctx.stage.addChild(rope)},WellboreBaseComponentLayer.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.ctx.stage.addChild(rope)},WellboreBaseComponentLayer.prototype.drawOutline=function(leftPath,rightPath,lineColor,lineWidth,close){void 0===lineWidth&&(lineWidth=1),void 0===close&&(close=!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,1),line.moveTo(startPointRight.x,startPointRight.y),rightPath.forEach((function(p){return line.lineTo(p.x,p.y)})),close||line.moveTo(startPointLeft.x,startPointLeft.y),leftPathReverse.forEach((function(p){return line.lineTo(p.x,p.y)})),close&&line.lineTo(startPointRight.x,startPointRight.y),this.ctx.stage.addChild(line)},WellboreBaseComponentLayer}(PixiLayer),makeTubularPolygon=function(rightPath,leftPath){return __spreadArray(__spreadArray([],leftPath),rightPath.map((function(d){return d.clone()})).reverse())},overlaps=function(top1,bottom1,top2,bottom2){return top1<=bottom2&&top2<=bottom1},cementDiameterChangeDepths=function(cement,bottomOfCement,diameterIntervals){var arr,topOfCement=cement.toc,diameterChangeDepths=merge(diameterIntervals.map((function(d){return[d.start-1e-4,d.start,d.end,d.end+1e-4]}))).filter((function(d){return d>=topOfCement&&d<=bottomOfCement}));return diameterChangeDepths.push(topOfCement),diameterChangeDepths.push(bottomOfCement),(arr=diameterChangeDepths,Array.from(new Set(arr))).sort((function(a,b){return a-b}))},arrayToVector=function(a){return new Vector2(a[0],a[1])},createNormals=function(points){return points.length<2?[new Vector2(0)]:points.map((function(coord,i,list){if(i<list.length-1){var p=arrayToVector(list[i]),rotate=arrayToVector(list[i+1]).sub(p).rotate90();return n=rotate.normalized()}return n}));var n},offsetPoint=function(point,vector,offset){var v,p=arrayToVector(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)}))},HoleSizeLayer=function(_super){function HoleSizeLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.drawHoleSize=function(holeObject){if(null!=holeObject){var _a=_this.options,exaggerationFactor=_a.exaggerationFactor,firstColor=_a.firstColor,lineColor=_a.lineColor,diameter=holeObject.diameter*exaggerationFactor,radius=diameter/2,pathPoints=_this.getZFactorScaledPathForPoints(holeObject.start,holeObject.end,[holeObject.start,holeObject.end]).map((function(p){return p.point})),normals=createNormals(pathPoints),rightPath=offsetPoints(pathPoints,normals,radius),leftPath=offsetPoints(pathPoints,normals,-radius);if(0!==pathPoints.length){if(_this.renderType()===RENDERER_TYPE.CANVAS){var polygonCoords=makeTubularPolygon(leftPath,rightPath);_this.drawBigPolygon(polygonCoords,convertColor(firstColor))}else{var texture=_this.createTexture(diameter);_this.drawRope(pathPoints.map((function(p){return new Point(p[0],p[1])})),texture)}_this.drawOutline(leftPath,rightPath,lineColor,1,!1)}}},_this.options=__assign(__assign(__assign({},_this.options),{firstColor:"rgb(140, 84, 29)",secondColor:"rgb(238, 227, 216)",lineColor:9127187}),options),_this}return __extends(HoleSizeLayer,_super),HoleSizeLayer.prototype.preRender=function(){var _this=this,data=this.data;data&&this.rescaleEvent&&this.referenceSystem&&(data.sort((function(a,b){return b.diameter-a.diameter})),this.maxDiameter=data.length>0?data[0].diameter:100,data.forEach((function(hole){return _this.drawHoleSize(hole)})))},HoleSizeLayer.prototype.createTexture=function(diameter){var exaggerationFactor=this.options.exaggerationFactor,height=this.maxDiameter*exaggerationFactor;this._textureCache||(this._textureCache=this.createBaseTexture(16,height));var baseTexture=this._textureCache.baseTexture,sidePadding=Math.floor((height-diameter)/2),frame=new Rectangle(0,sidePadding,16,diameter);return new Texture(baseTexture,frame)},HoleSizeLayer.prototype.createBaseTexture=function(width,height){var _a=this.options,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)},HoleSizeLayer}(WellboreBaseComponentLayer),CasingLayer=function(_super){function CasingLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.prepareCasingRenderObject=function(casing){if(null!=casing){var exaggerationFactor=_this.options.exaggerationFactor,diameter=casing.diameter*exaggerationFactor,radius=diameter/2,innerRadius=casing.innerDiameter*exaggerationFactor/2,pathPoints=_this.getZFactorScaledPathForPoints(casing.start,casing.end,[casing.start,casing.end]).map((function(p){return p.point})),normals=createNormals(pathPoints),rightPath=offsetPoints(pathPoints,normals,radius),leftPath=offsetPoints(pathPoints,normals,-radius);return{pathPoints:pathPoints,polygon:makeTubularPolygon(leftPath,rightPath),leftPath:leftPath,rightPath:rightPath,radius:radius,diameter:diameter,casingWallWidth:Math.abs(radius-innerRadius)}}},_this.drawCasing=function(zippedRenderObject){var _a=_this.options,lineColor=_a.lineColor,solidColor=_a.solidColor,casing=zippedRenderObject[0],_b=zippedRenderObject[1],pathPoints=_b.pathPoints,polygon=_b.polygon,leftPath=_b.leftPath,rightPath=_b.rightPath,radius=_b.radius,diameter=_b.diameter,casingWallWidth=_b.casingWallWidth;if(_this.renderType()===RENDERER_TYPE.CANVAS)_this.drawBigPolygon(polygon,solidColor);else{var texture=_this.createTexture(diameter);_this.drawRope(pathPoints.map((function(p){return new Point(p[0],p[1])})),texture,solidColor)}_this.drawOutline(leftPath,rightPath,lineColor,casingWallWidth,!0),casing.hasShoe&&_this.drawShoe(casing.end,radius)},_this.generateShoe=function(casingEnd,casingRadius,length,width){var start=casingEnd-length,end=casingEnd,points=_this.getZFactorScaledPathForPoints(start,end,[start,end]).map((function(p){return p.point})),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);return __spreadArray(__spreadArray([],shoeEdge),[shoeTip])},_this.options=__assign(__assign(__assign({},_this.options),{solidColor:14474460,lineColor:5723991}),options),_this}return __extends(CasingLayer,_super),CasingLayer.prototype.preRender=function(){var _this=this,data=this.data;if(data&&this.rescaleEvent&&this.referenceSystem){var sortedCasings=data.sort((function(a,b){return b.diameter-a.diameter})),casingRenderObjects=sortedCasings.map((function(casing){return _this.prepareCasingRenderObject(casing)}));zip(sortedCasings,casingRenderObjects).forEach((function(zippedRenderObject){return _this.drawCasing(zippedRenderObject)}))}},CasingLayer.prototype.drawShoe=function(casingEnd,casingRadius){var exaggerationFactor=this.options.exaggerationFactor,shoeWidth=25*exaggerationFactor,shoeLength=12*exaggerationFactor,shoeCoords=this.generateShoe(casingEnd,casingRadius,shoeLength,shoeWidth),shoeCoords2=this.generateShoe(casingEnd,casingRadius,shoeLength,-shoeWidth);this.drawBigPolygon(shoeCoords2),this.drawBigPolygon(shoeCoords)},CasingLayer.prototype.createTexture=function(diameter){return new Texture(Texture.WHITE.baseTexture,null,new Rectangle(0,0,16,diameter))},CasingLayer}(WellboreBaseComponentLayer),CementLayer=function(_super){function CementLayer(id,options){var _this=_super.call(this,id,options)||this;return _this.createCementShape=function(cement,casings,holes){var exaggerationFactor=_this.options.exaggerationFactor,attachedCasings=__spreadArray([cement.casingId],cement.casingIds||[]).filter((function(id){return id})).map((function(casingId){return casings.find((function(casing){return casing.casingId===casingId}))}));if(0===attachedCasings.length||attachedCasings.includes(void 0))throw new Error("Invalid cement data, cement is missing attached casing");attachedCasings.sort((function(a,b){return a.end-b.end}));for(var bottomOfCement=attachedCasings[attachedCasings.length-1].end,_a=function(cement,bottomOfCement,parentCasings,casings,holes){var start=cement.toc,end=bottomOfCement;return{holes:holes.filter((function(h){return overlaps(start,end,h.start,h.end)})),outerCasings:casings.filter((function(c){return!parentCasings.includes(c)})).filter((function(c){return overlaps(start,end,c.start,c.end)}))}}(cement,bottomOfCement,attachedCasings,casings,holes),outerCasings=_a.outerCasings,overlappingHoles=_a.holes,innerDiameterIntervals=attachedCasings,outerDiameterIntervals=__spreadArray(__spreadArray([],outerCasings),overlappingHoles).map((function(d){return{start:d.start,end:d.end}})),diameterAtChangeDepths=cementDiameterChangeDepths(cement,bottomOfCement,__spreadArray(__spreadArray([],innerDiameterIntervals),outerDiameterIntervals)).map(function(innerCasing,nonAttachedCasings,holes){return function(depth){var outerDiameter,innerCasingAtDepth=innerCasing.find((function(casing){return casing.start<=depth&&casing.end>=depth})),innerDiameter=innerCasingAtDepth?innerCasingAtDepth.diameter:0,outerCasings=nonAttachedCasings.filter((function(casing){return casing.innerDiameter>innerDiameter})),holeAtDepth=holes.find((function(hole){return hole.start<=depth&&hole.end>=depth&&hole.diameter>innerDiameter})),outerCasingAtDepth=outerCasings.filter((function(d){return d})).sort((function(a,b){return a.innerDiameter-b.innerDiameter})).find((function(casing){return casing.start<=depth&&casing.end>=depth&&casing.diameter>innerDiameter}));return outerDiameter=outerCasingAtDepth?outerCasingAtDepth.innerDiameter:holeAtDepth?holeAtDepth.diameter-1:100,{md:depth,innerDiameter:innerDiameter,outerDiameter:outerDiameter}}}(attachedCasings,outerCasings,overlappingHoles)),path=_this.getZFactorScaledPathForPoints(cement.toc,bottomOfCement,diameterAtChangeDepths.map((function(d){return d.md}))),normals=createNormals(path.map((function(p){return p.point}))),pathWithNormals=path.map((function(p,i){return __assign(__assign({},p),{normal:normals[i]})})),side1Left=[],side1Right=[],side2Left=[],side2Right=[],previousDepth=diameterAtChangeDepths.shift(),_loop_1=function(depth){var intervalMdPoints=pathWithNormals.filter((function(x){return x.md>=previousDepth.md&&x.md<=depth.md})),intervalPoints=intervalMdPoints.map((function(s){return s.point})),intervalPointNormals=intervalMdPoints.map((function(s){return s.normal})),outerRadius=previousDepth.outerDiameter/2*exaggerationFactor,innerRadius=previousDepth.innerDiameter/2*exaggerationFactor,intervalSide1Left=offsetPoints(intervalPoints,intervalPointNormals,outerRadius),intervalSide1Right=offsetPoints(intervalPoints,intervalPointNormals,innerRadius),intervalSide2Left=offsetPoints(intervalPoints,intervalPointNormals,-innerRadius),intervalSide2Right=offsetPoints(intervalPoints,intervalPointNormals,-outerRadius);side1Left.push.apply(side1Left,intervalSide1Left),side1Right.push.apply(side1Right,intervalSide1Right),side2Left.push.apply(side2Left,intervalSide2Left),side2Right.push.apply(side2Right,intervalSide2Right),previousDepth=depth},_i=0,diameterAtChangeDepths_1=diameterAtChangeDepths;_i<diameterAtChangeDepths_1.length;_i++){_loop_1(diameterAtChangeDepths_1[_i])}var pathPoints=pathWithNormals.map((function(p){return new Point(p.point[0],p.point[1])}));return{leftPolygon:makeTubularPolygon(side1Left,side1Right),rightPolygon:makeTubularPolygon(side2Left,side2Right),path:pathPoints}},_this.options=__assign(__assign(__assign({},_this.options),{firstColor:"#c7b9ab",secondColor:"#5b5b5b"}),options),_this}return __extends(CementLayer,_super),CementLayer.prototype.preRender=function(){var _this=this;if(this.data&&this.rescaleEvent&&this.referenceSystem){var _a=this.data,cement=_a.cement,casings=_a.casings,holes=_a.holes,cementShapes=cement.map((function(cement){return _this.createCementShape(cement,casings,holes)})),texture=this.createTexture();cementShapes.forEach((function(cementShape){_this.renderType()===RENDERER_TYPE.CANVAS?(_this.drawBigTexturedPolygon(cementShape.leftPolygon,texture),_this.drawBigTexturedPolygon(cementShape.rightPolygon,texture)):(_this.drawRopeWithMask(cementShape.path,cementShape.leftPolygon,texture),_this.drawRopeWithMask(cementShape.path,cementShape.rightPolygon,texture))}))}},CementLayer.prototype.createTexture=function(){if(this._textureCache)return this._textureCache;var _a=this.options,firstColor=_a.firstColor,secondColor=_a.secondColor,canvas=document.createElement("canvas");canvas.width=150,canvas.height=150;var canvasCtx=canvas.getContext("2d");canvasCtx.fillStyle=firstColor,canvasCtx.fillRect(0,0,canvas.width,canvas.height),canvasCtx.lineWidth=1,canvasCtx.fillStyle=secondColor,canvasCtx.beginPath(),canvasCtx.lineWidth=1;for(var i=-canvas.width;i<canvas.width;i++)canvasCtx.moveTo(-canvas.width+10*i,-canvas.height),canvasCtx.lineTo(canvas.width+10*i,canvas.height);return canvasCtx.stroke(),this._textureCache=Texture.from(canvas),this._textureCache},CementLayer}(WellboreBaseComponentLayer),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),CompletionLayer=function(_super){function CompletionLayer(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(CompletionLayer,_super),CompletionLayer.prototype.onRescale=function(event){_super.prototype.onRescale.call(this,event),this.clearStage(),this.preRender(),this.render()},CompletionLayer.prototype.onUpdate=function(event){_super.prototype.onUpdate.call(this,event),this.clearStage(),this.preRender(),this.render()},CompletionLayer.prototype.preRender=function(){var _a,_this=this,wellborePath=this.referenceSystem?this.referenceSystem.projectedPath:[];null!=wellborePath&&((null===(_a=this.data)||void 0===_a?void 0:_a.length)>0?this.data.map((function(d){return _this.generateCompletionItem(wellborePath,d)})):[]).map((function(s){return _this.drawCompletionItem(s)}))},CompletionLayer.prototype.clearStage=function(){this.ctx.stage.removeChildren().forEach((function(child){child.destroy()}))},CompletionLayer.prototype.getShape=function(type){var graphics=new Graphics;return graphics.beginFill(3421236),graphics.drawRect(-5,-5,10,10),graphics.endFill(),graphics},CompletionLayer.prototype.getScale=function(type,length,width){return{scaleX:1,scaleY:1}},CompletionLayer.prototype.generateCompletionItem=function(wbp,data){if(this.referenceSystem){var pointTop=this.referenceSystem.project(data.start),pointBottom=this.referenceSystem.project(data.end),rotation=Vector2.angle(pointTop,pointBottom),graphics=this.getShape(data.shape),_a=this.getScale(data.shape,data.start-data.end,data.diameter),scaleX=_a.scaleX,scaleY=_a.scaleY,x=pointTop[0],y=pointTop[1];return graphics.setTransform(x,y,scaleX,scaleY,rotation),{graphics:graphics}}},CompletionLayer.prototype.drawCompletionItem=function(item){this.ctx.stage.addChild(item.graphics)},CompletionLayer}(PixiLayer),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.onZoom=this.onZoom.bind(this),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;_a.ySpan;var 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;_a.ySpan;var 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){void 0===cx&&(cx=null),void 0===cy&&(cy=null),void 0===displ&&(displ=null),void 0===duration&&(duration=null);var _a=this,zoom=_a.zoom,container=_a.container,calculateTransform=_a.calculateTransform;_a.viewportRatio;var scaleX=_a.scaleX,scaleY=_a.scaleY,isXInverted=_a.isXInverted;if(null===cx||null===displ){var xd=scaleX.domain(),dspan=xd[1]-xd[0];null===cx&&(cx=xd[0]+dspan/2||0),null===displ&&(displ=Math.abs(dspan)||1)}if(null===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.containerWidth,h=_b.containerHeight}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}(),Axis=function(){function Axis(mainGroup,showLabels,labelXDesc,labelYDesc,unitOfMeasure,options){var _this=this;void 0===showLabels&&(showLabels=!0),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."+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(labelXDesc+" ("+unitOfMeasure+")")):labelx.remove(),labelx.attr("transform","translate("+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(labelYDesc+" ("+unitOfMeasure+")")),labely.attr("transform","translate(-10,"+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("+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 "+height+")"),gx.call(xAxis),gx},Axis.prototype.render=function(){this.renderLabelx(),this.renderLabely()},Axis.prototype.onResize=function(event){this.mainGroup.attr("height",event.height+"px").attr("width",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}(),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",container.offsetHeight+"px").attr("width",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}))},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",""+(highestZIndex+1))}return this},LayerManager.prototype.showLayer=function(layerId){var layer=this.getLayer(layerId);return layer.setVisibility(!0),layer.onRescale(this.zoomPanHandler.currentStateAsEvent()),this},LayerManager.prototype.hideLayer=function(layerId){return this.getLayer(layerId).setVisibility(!1),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}(),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;return void 0===from&&(from=0),void 0===to&&(to=1),0===from&&1===to?this.length: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(start,end){if(!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}return this._curtainPathCache.filter((function(p){return p.md>=start&&p.md<=end}))},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())}points.push.apply(points,this.interpolators.trajectory.getPoints(curveSteps,null,0,1));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}(),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",width+"px").style("height",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){return layers.length>0?layers.reduce((function(max,layers){return max.order>layers.order?max:layers})).order:1},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,CasingLayer,CementLayer,CompletionLayer,Controller,GeomodelCanvasLayer,GeomodelLabelsLayer,GeomodelLayer,GeomodelLayerV2,GridLayer,HTMLLayer,HoleSizeLayer,ImageLayer,IntersectionReferenceSystem,Layer,LayerManager,PixiLayer,SVGLayer,SeismicCanvasLayer,WellborepathLayer,ZoomPanHandler,calcSize,findIndexOfSample,findSampleAtPos,generateProjectedTrajectory,generateProjectedWellborePath,generateSeismicSliceImage,generateSurfaceData,getOverlap,getOverlapOffset,getPicksData,getSeismicInfo,isOverlapping,isOverlappingHorizontally,pixelsPerUnit,transformFormationData};