Team:SUSTech Shenzhen/js/ami-min-js

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AMI=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var ColorSpace={Unkown:0,Grayscale:1,AdobeRGB:2,RGB:3,CYMK:4};var JpegImage=function jpegImage(){"use strict";var dctZigZag=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);var dctCos1=4017;var dctSin1=799;var dctCos3=3406;var dctSin3=2276;var dctCos6=1567;var dctSin6=3784;var dctSqrt2=5793;var dctSqrt1d2=2896;function constructor(){}function buildHuffmanTable(codeLengths,values){var k=0,code=[],i,j,length=16;while(length>0&&!codeLengths[length-1])length--;code.push({children:[],index:0});var p=code[0],q;for(i=0;i<length;i++){for(j=0;j<codeLengths[i];j++){p=code.pop();p.children[p.index]=values[k];while(p.index>0){p=code.pop()}p.index++;code.push(p);while(code.length<=i){code.push(q={children:[],index:0});p.children[p.index]=q.children;p=q}k++}if(i+1<length){code.push(q={children:[],index:0});p.children[p.index]=q.children;p=q}}return code[0].children}function getBlockBufferOffset(component,row,col){return 64*((component.blocksPerLine+1)*row+col)}function decodeScan(data,offset,frame,components,resetInterval,spectralStart,spectralEnd,successivePrev,successive){var precision=frame.precision;var samplesPerLine=frame.samplesPerLine;var scanLines=frame.scanLines;var mcusPerLine=frame.mcusPerLine;var progressive=frame.progressive;var maxH=frame.maxH,maxV=frame.maxV;var startOffset=offset,bitsData=0,bitsCount=0;function readBit(){if(bitsCount>0){bitsCount--;return bitsData>>bitsCount&1}bitsData=data[offset++];if(bitsData==255){var nextByte=data[offset++];if(nextByte){throw"unexpected marker: "+(bitsData<<8|nextByte).toString(16)}}bitsCount=7;return bitsData>>>7}function decodeHuffman(tree){var node=tree;var bit;while((bit=readBit())!==null){node=node[bit];if(typeof node==="number")return node;if(typeof node!=="object")throw"invalid huffman sequence"}return null}function receive(length){var n=0;while(length>0){var bit=readBit();if(bit===null)return;n=n<<1|bit;length--}return n}function receiveAndExtend(length){var n=receive(length);if(n>=1<<length-1)return n;return n+(-1<<length)+1}function decodeBaseline(component,offset){var t=decodeHuffman(component.huffmanTableDC);var diff=t===0?0:receiveAndExtend(t);component.blockData[offset]=component.pred+=diff;var k=1;while(k<64){var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15,r=rs>>4;if(s===0){if(r<15)break;k+=16;continue}k+=r;var z=dctZigZag[k];component.blockData[offset+z]=receiveAndExtend(s);k++}}function decodeDCFirst(component,offset){var t=decodeHuffman(component.huffmanTableDC);var diff=t===0?0:receiveAndExtend(t)<<successive;component.blockData[offset]=component.pred+=diff}function decodeDCSuccessive(component,offset){component.blockData[offset]|=readBit()<<successive}var eobrun=0;function decodeACFirst(component,offset){if(eobrun>0){eobrun--;return}var k=spectralStart,e=spectralEnd;while(k<=e){var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15,r=rs>>4;if(s===0){if(r<15){eobrun=receive(r)+(1<<r)-1;break}k+=16;continue}k+=r;var z=dctZigZag[k];component.blockData[offset+z]=receiveAndExtend(s)*(1<<successive);k++}}var successiveACState=0,successiveACNextValue;function decodeACSuccessive(component,offset){var k=spectralStart,e=spectralEnd,r=0;while(k<=e){var z=dctZigZag[k];switch(successiveACState){case 0:var rs=decodeHuffman(component.huffmanTableAC);var s=rs&15;r=rs>>4;if(s===0){if(r<15){eobrun=receive(r)+(1<<r);successiveACState=4}else{r=16;successiveACState=1}}else{if(s!==1)throw"invalid ACn encoding";successiveACNextValue=receiveAndExtend(s);successiveACState=r?2:3}continue;case 1:case 2:if(component.blockData[offset+z]){component.blockData[offset+z]+=readBit()<<successive}else{r--;if(r===0)successiveACState=successiveACState==2?3:0}break;case 3:if(component.blockData[offset+z]){component.blockData[offset+z]+=readBit()<<successive}else{component.blockData[offset+z]=successiveACNextValue<<successive;successiveACState=0}break;case 4:if(component.blockData[offset+z]){component.blockData[offset+z]+=readBit()<<successive}break}k++}if(successiveACState===4){eobrun--;if(eobrun===0)successiveACState=0}}function decodeMcu(component,decode,mcu,row,col){var mcuRow=mcu/mcusPerLine|0;var mcuCol=mcu%mcusPerLine;var blockRow=mcuRow*component.v+row;var blockCol=mcuCol*component.h+col;var offset=getBlockBufferOffset(component,blockRow,blockCol);decode(component,offset)}function decodeBlock(component,decode,mcu){var blockRow=mcu/component.blocksPerLine|0;var blockCol=mcu%component.blocksPerLine;var offset=getBlockBufferOffset(component,blockRow,blockCol);decode(component,offset)}var componentsLength=components.length;var component,i,j,k,n;var decodeFn;if(progressive){if(spectralStart===0)decodeFn=successivePrev===0?decodeDCFirst:decodeDCSuccessive;else decodeFn=successivePrev===0?decodeACFirst:decodeACSuccessive}else{decodeFn=decodeBaseline}var mcu=0,marker;var mcuExpected;if(componentsLength==1){mcuExpected=components[0].blocksPerLine*components[0].blocksPerColumn}else{mcuExpected=mcusPerLine*frame.mcusPerColumn}if(!resetInterval){resetInterval=mcuExpected}var h,v;while(mcu<mcuExpected){for(i=0;i<componentsLength;i++){components[i].pred=0}eobrun=0;if(componentsLength==1){component=components[0];for(n=0;n<resetInterval;n++){decodeBlock(component,decodeFn,mcu);mcu++}}else{for(n=0;n<resetInterval;n++){for(i=0;i<componentsLength;i++){component=components[i];h=component.h;v=component.v;for(j=0;j<v;j++){for(k=0;k<h;k++){decodeMcu(component,decodeFn,mcu,j,k)}}}mcu++}}bitsCount=0;marker=data[offset]<<8|data[offset+1];if(marker<=65280){throw"marker was not found"}if(marker>=65488&&marker<=65495){offset+=2}else{break}}return offset-startOffset}function quantizeAndInverse(component,blockBufferOffset,p){var qt=component.quantizationTable;var v0,v1,v2,v3,v4,v5,v6,v7,t;var i;for(i=0;i<64;i++){p[i]=component.blockData[blockBufferOffset+i]*qt[i]}for(i=0;i<8;++i){var row=8*i;if(p[1+row]===0&&p[2+row]===0&&p[3+row]===0&&p[4+row]===0&&p[5+row]===0&&p[6+row]===0&&p[7+row]===0){t=dctSqrt2*p[0+row]+512>>10;p[0+row]=t;p[1+row]=t;p[2+row]=t;p[3+row]=t;p[4+row]=t;p[5+row]=t;p[6+row]=t;p[7+row]=t;continue}v0=dctSqrt2*p[0+row]+128>>8;v1=dctSqrt2*p[4+row]+128>>8;v2=p[2+row];v3=p[6+row];v4=dctSqrt1d2*(p[1+row]-p[7+row])+128>>8;v7=dctSqrt1d2*(p[1+row]+p[7+row])+128>>8;v5=p[3+row]<<4;v6=p[5+row]<<4;t=v0-v1+1>>1;v0=v0+v1+1>>1;v1=t;t=v2*dctSin6+v3*dctCos6+128>>8;v2=v2*dctCos6-v3*dctSin6+128>>8;v3=t;t=v4-v6+1>>1;v4=v4+v6+1>>1;v6=t;t=v7+v5+1>>1;v5=v7-v5+1>>1;v7=t;t=v0-v3+1>>1;v0=v0+v3+1>>1;v3=t;t=v1-v2+1>>1;v1=v1+v2+1>>1;v2=t;t=v4*dctSin3+v7*dctCos3+2048>>12;v4=v4*dctCos3-v7*dctSin3+2048>>12;v7=t;t=v5*dctSin1+v6*dctCos1+2048>>12;v5=v5*dctCos1-v6*dctSin1+2048>>12;v6=t;p[0+row]=v0+v7;p[7+row]=v0-v7;p[1+row]=v1+v6;p[6+row]=v1-v6;p[2+row]=v2+v5;p[5+row]=v2-v5;p[3+row]=v3+v4;p[4+row]=v3-v4}for(i=0;i<8;++i){var col=i;if(p[1*8+col]===0&&p[2*8+col]===0&&p[3*8+col]===0&&p[4*8+col]===0&&p[5*8+col]===0&&p[6*8+col]===0&&p[7*8+col]===0){t=dctSqrt2*p[i+0]+8192>>14;p[0*8+col]=t;p[1*8+col]=t;p[2*8+col]=t;p[3*8+col]=t;p[4*8+col]=t;p[5*8+col]=t;p[6*8+col]=t;p[7*8+col]=t;continue}v0=dctSqrt2*p[0*8+col]+2048>>12;v1=dctSqrt2*p[4*8+col]+2048>>12;v2=p[2*8+col];v3=p[6*8+col];v4=dctSqrt1d2*(p[1*8+col]-p[7*8+col])+2048>>12;v7=dctSqrt1d2*(p[1*8+col]+p[7*8+col])+2048>>12;v5=p[3*8+col];v6=p[5*8+col];t=v0-v1+1>>1;v0=v0+v1+1>>1;v1=t;t=v2*dctSin6+v3*dctCos6+2048>>12;v2=v2*dctCos6-v3*dctSin6+2048>>12;v3=t;t=v4-v6+1>>1;v4=v4+v6+1>>1;v6=t;t=v7+v5+1>>1;v5=v7-v5+1>>1;v7=t;t=v0-v3+1>>1;v0=v0+v3+1>>1;v3=t;t=v1-v2+1>>1;v1=v1+v2+1>>1;v2=t;t=v4*dctSin3+v7*dctCos3+2048>>12;v4=v4*dctCos3-v7*dctSin3+2048>>12;v7=t;t=v5*dctSin1+v6*dctCos1+2048>>12;v5=v5*dctCos1-v6*dctSin1+2048>>12;v6=t;p[0*8+col]=v0+v7;p[7*8+col]=v0-v7;p[1*8+col]=v1+v6;p[6*8+col]=v1-v6;p[2*8+col]=v2+v5;p[5*8+col]=v2-v5;p[3*8+col]=v3+v4;p[4*8+col]=v3-v4}for(i=0;i<64;++i){var index=blockBufferOffset+i;var q=p[i];q=q<=-2056/component.bitConversion?0:q>=2024/component.bitConversion?255/component.bitConversion:q+2056/component.bitConversion>>4;component.blockData[index]=q}}function buildComponentData(frame,component){var lines=[];var blocksPerLine=component.blocksPerLine;var blocksPerColumn=component.blocksPerColumn;var samplesPerLine=blocksPerLine<<3;var computationBuffer=new Int32Array(64);var i,j,ll=0;for(var blockRow=0;blockRow<blocksPerColumn;blockRow++){for(var blockCol=0;blockCol<blocksPerLine;blockCol++){var offset=getBlockBufferOffset(component,blockRow,blockCol);quantizeAndInverse(component,offset,computationBuffer)}}return component.blockData}function clampToUint8(a){return a<=0?0:a>=255?255:a|0}constructor.prototype={load:function load(path){var handleData=function(data){this.parse(data);if(this.onload)this.onload()}.bind(this);if(path.indexOf("data:")>-1){var offset=path.indexOf("base64,")+7;var data=atob(path.substring(offset));var arr=new Uint8Array(data.length);for(var i=data.length-1;i>=0;i--){arr[i]=data.charCodeAt(i)}handleData(data)}else{var xhr=new XMLHttpRequest;xhr.open("GET",path,true);xhr.responseType="arraybuffer";xhr.onload=function(){var data=new Uint8Array(xhr.response);handleData(data)}.bind(this);xhr.send(null)}},parse:function parse(data){function readUint16(){var value=data[offset]<<8|data[offset+1];offset+=2;return value}function readDataBlock(){var length=readUint16();var array=data.subarray(offset,offset+length-2);offset+=array.length;return array}function prepareComponents(frame){var mcusPerLine=Math.ceil(frame.samplesPerLine/8/frame.maxH);var mcusPerColumn=Math.ceil(frame.scanLines/8/frame.maxV);for(var i=0;i<frame.components.length;i++){component=frame.components[i];var blocksPerLine=Math.ceil(Math.ceil(frame.samplesPerLine/8)*component.h/frame.maxH);var blocksPerColumn=Math.ceil(Math.ceil(frame.scanLines/8)*component.v/frame.maxV);var blocksPerLineForMcu=mcusPerLine*component.h;var blocksPerColumnForMcu=mcusPerColumn*component.v;var blocksBufferSize=64*blocksPerColumnForMcu*(blocksPerLineForMcu+1);component.blockData=new Int16Array(blocksBufferSize);component.blocksPerLine=blocksPerLine;component.blocksPerColumn=blocksPerColumn}frame.mcusPerLine=mcusPerLine;frame.mcusPerColumn=mcusPerColumn}var offset=0,length=data.length;var jfif=null;var adobe=null;var pixels=null;var frame,resetInterval;var quantizationTables=[];var huffmanTablesAC=[],huffmanTablesDC=[];var fileMarker=readUint16();if(fileMarker!=65496){throw"SOI not found"}fileMarker=readUint16();while(fileMarker!=65497){var i,j,l;switch(fileMarker){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var appData=readDataBlock();if(fileMarker===65504){if(appData[0]===74&&appData[1]===70&&appData[2]===73&&appData[3]===70&&appData[4]===0){jfif={version:{major:appData[5],minor:appData[6]},densityUnits:appData[7],xDensity:appData[8]<<8|appData[9],yDensity:appData[10]<<8|appData[11],thumbWidth:appData[12],thumbHeight:appData[13],thumbData:appData.subarray(14,14+3*appData[12]*appData[13])}}}if(fileMarker===65518){if(appData[0]===65&&appData[1]===100&&appData[2]===111&&appData[3]===98&&appData[4]===101&&appData[5]===0){adobe={version:appData[6],flags0:appData[7]<<8|appData[8],flags1:appData[9]<<8|appData[10],transformCode:appData[11]}}}break;case 65499:var quantizationTablesLength=readUint16();var quantizationTablesEnd=quantizationTablesLength+offset-2;while(offset<quantizationTablesEnd){var quantizationTableSpec=data[offset++];var tableData=new Int32Array(64);if(quantizationTableSpec>>4===0){for(j=0;j<64;j++){var z=dctZigZag[j];tableData[z]=data[offset++]}}else if(quantizationTableSpec>>4===1){for(j=0;j<64;j++){var zz=dctZigZag[j];tableData[zz]=readUint16()}}else throw"DQT: invalid table spec";quantizationTables[quantizationTableSpec&15]=tableData}break;case 65472:case 65473:case 65474:if(frame){throw"Only single frame JPEGs supported"}readUint16();frame={};frame.extended=fileMarker===65473;frame.progressive=fileMarker===65474;frame.precision=data[offset++];frame.scanLines=readUint16();frame.samplesPerLine=readUint16();frame.components=[];frame.componentIds={};var componentsCount=data[offset++],componentId;var maxH=0,maxV=0;for(i=0;i<componentsCount;i++){componentId=data[offset];var h=data[offset+1]>>4;var v=data[offset+1]&15;if(maxH<h)maxH=h;if(maxV<v)maxV=v;var qId=data[offset+2];l=frame.components.push({h:h,v:v,quantizationTable:quantizationTables[qId],quantizationTableId:qId,bitConversion:255/((1<<frame.precision)-1)});frame.componentIds[componentId]=l-1;offset+=3}frame.maxH=maxH;frame.maxV=maxV;prepareComponents(frame);break;case 65476:var huffmanLength=readUint16();for(i=2;i<huffmanLength;){var huffmanTableSpec=data[offset++];var codeLengths=new Uint8Array(16);var codeLengthSum=0;for(j=0;j<16;j++,offset++)codeLengthSum+=codeLengths[j]=data[offset];var huffmanValues=new Uint8Array(codeLengthSum);for(j=0;j<codeLengthSum;j++,offset++)huffmanValues[j]=data[offset];i+=17+codeLengthSum;(huffmanTableSpec>>4===0?huffmanTablesDC:huffmanTablesAC)[huffmanTableSpec&15]=buildHuffmanTable(codeLengths,huffmanValues)}break;case 65501:readUint16();resetInterval=readUint16();break;case 65498:var scanLength=readUint16();var selectorsCount=data[offset++];var components=[],component;for(i=0;i<selectorsCount;i++){var componentIndex=frame.componentIds[data[offset++]];component=frame.components[componentIndex];var tableSpec=data[offset++];component.huffmanTableDC=huffmanTablesDC[tableSpec>>4];component.huffmanTableAC=huffmanTablesAC[tableSpec&15];components.push(component)}var spectralStart=data[offset++];var spectralEnd=data[offset++];var successiveApproximation=data[offset++];var processed=decodeScan(data,offset,frame,components,resetInterval,spectralStart,spectralEnd,successiveApproximation>>4,successiveApproximation&15);offset+=processed;break;default:if(data[offset-3]==255&&data[offset-2]>=192&&data[offset-2]<=254){offset-=3;break}throw"unknown JPEG marker "+fileMarker.toString(16)}fileMarker=readUint16()}this.width=frame.samplesPerLine;this.height=frame.scanLines;this.jfif=jfif;this.adobe=adobe;this.components=[];switch(frame.components.length){case 1:this.colorspace=ColorSpace.Grayscale;break;case 3:if(this.adobe)this.colorspace=ColorSpace.AdobeRGB;else this.colorspace=ColorSpace.RGB;break;case 4:this.colorspace=ColorSpace.CYMK;break;default:this.colorspace=ColorSpace.Unknown}for(var i=0;i<frame.components.length;i++){var component=frame.components[i];if(!component.quantizationTable&&component.quantizationTableId!==null)component.quantizationTable=quantizationTables[component.quantizationTableId];this.components.push({output:buildComponentData(frame,component),scaleX:component.h/frame.maxH,scaleY:component.v/frame.maxV,blocksPerLine:component.blocksPerLine,blocksPerColumn:component.blocksPerColumn,bitConversion:component.bitConversion})}},getData16:function getData16(width,height){if(this.components.length!==1)throw"Unsupported color mode";var scaleX=this.width/width,scaleY=this.height/height;var component,componentScaleX,componentScaleY;var x,y,i;var offset=0;var numComponents=this.components.length;var dataLength=width*height*numComponents;var data=new Uint16Array(dataLength);var componentLine;var lineData=new Uint16Array((this.components[0].blocksPerLine<<3)*this.components[0].blocksPerColumn*8);for(i=0;i<numComponents;i++){component=this.components[i];var blocksPerLine=component.blocksPerLine;var blocksPerColumn=component.blocksPerColumn;var samplesPerLine=blocksPerLine<<3;var j,k,ll=0;var lineOffset=0;for(var blockRow=0;blockRow<blocksPerColumn;blockRow++){var scanLine=blockRow<<3;for(var blockCol=0;blockCol<blocksPerLine;blockCol++){var bufferOffset=getBlockBufferOffset(component,blockRow,blockCol);var offset=0,sample=blockCol<<3;for(j=0;j<8;j++){var lineOffset=(scanLine+j)*samplesPerLine;for(k=0;k<8;k++){lineData[lineOffset+sample+k]=component.output[bufferOffset+offset++]}}}}componentScaleX=component.scaleX*scaleX;componentScaleY=component.scaleY*scaleY;offset=i;var cx,cy;var index;for(y=0;y<height;y++){for(x=0;x<width;x++){cy=0|y*componentScaleY;cx=0|x*componentScaleX;index=cy*samplesPerLine+cx;data[offset]=lineData[index];offset+=numComponents}}}return data},getData:function getData(width,height){var scaleX=this.width/width,scaleY=this.height/height;var component,componentScaleX,componentScaleY;var x,y,i;var offset=0;var Y,Cb,Cr,K,C,M,Ye,R,G,B;var colorTransform;var numComponents=this.components.length;var dataLength=width*height*numComponents;var data=new Uint8Array(dataLength);var componentLine;var lineData=new Uint8Array((this.components[0].blocksPerLine<<3)*this.components[0].blocksPerColumn*8);for(i=0;i<numComponents;i++){component=this.components[i];var blocksPerLine=component.blocksPerLine;var blocksPerColumn=component.blocksPerColumn;var samplesPerLine=blocksPerLine<<3;var j,k,ll=0;var lineOffset=0;for(var blockRow=0;blockRow<blocksPerColumn;blockRow++){var scanLine=blockRow<<3;for(var blockCol=0;blockCol<blocksPerLine;blockCol++){var bufferOffset=getBlockBufferOffset(component,blockRow,blockCol);var offset=0,sample=blockCol<<3;for(j=0;j<8;j++){var lineOffset=(scanLine+j)*samplesPerLine;for(k=0;k<8;k++){lineData[lineOffset+sample+k]=component.output[bufferOffset+offset++]*component.bitConversion}}}}componentScaleX=component.scaleX*scaleX;componentScaleY=component.scaleY*scaleY;offset=i;var cx,cy;var index;for(y=0;y<height;y++){for(x=0;x<width;x++){cy=0|y*componentScaleY;cx=0|x*componentScaleX;index=cy*samplesPerLine+cx;data[offset]=lineData[index];offset+=numComponents}}}switch(numComponents){case 1:case 2:break;case 3:colorTransform=true;if(this.adobe&&this.adobe.transformCode)colorTransform=true;else if(typeof this.colorTransform!=="undefined")colorTransform=!!this.colorTransform;if(colorTransform){for(i=0;i<dataLength;i+=numComponents){Y=data[i];Cb=data[i+1];Cr=data[i+2];R=clampToUint8(Y-179.456+1.402*Cr);G=clampToUint8(Y+135.459-.344*Cb-.714*Cr);B=clampToUint8(Y-226.816+1.772*Cb);data[i]=R;data[i+1]=G;data[i+2]=B}}break;case 4:if(!this.adobe)throw"Unsupported color mode (4 components)";colorTransform=false;if(this.adobe&&this.adobe.transformCode)colorTransform=true;else if(typeof this.colorTransform!=="undefined")colorTransform=!!this.colorTransform;if(colorTransform){for(i=0;i<dataLength;i+=numComponents){Y=data[i];Cb=data[i+1];Cr=data[i+2];C=clampToUint8(434.456-Y-1.402*Cr);M=clampToUint8(119.541-Y+.344*Cb+.714*Cr);Y=clampToUint8(481.816-Y-1.772*Cb);data[i]=C;data[i+1]=M;data[i+2]=Y}}break;default:throw"Unsupported color mode"}return data}};return constructor}();var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=JpegImage}},{}],2:[function(require,module,exports){"use strict";var JpxImage=function JpxImageClosure(){var SubbandsGainLog2={LL:0,LH:1,HL:1,HH:2};function JpxImage(){this.failOnCorruptedImage=false}JpxImage.prototype={parse:function JpxImage_parse(data){var head=readUint16(data,0);if(head===65359){this.parseCodestream(data,0,data.length);return}var position=0,length=data.length;while(position<length){var headerSize=8;var lbox=readUint32(data,position);var tbox=readUint32(data,position+4);position+=headerSize;if(lbox===1){lbox=readUint32(data,position)*4294967296+readUint32(data,position+4);position+=8;headerSize+=8}if(lbox===0){lbox=length-position+headerSize}if(lbox<headerSize){throw new Error("JPX Error: Invalid box field size")}var dataLength=lbox-headerSize;var jumpDataLength=true;switch(tbox){case 1785737832:jumpDataLength=false;break;case 1668246642:var method=data[position];var precedence=data[position+1];var approximation=data[position+2];if(method===1){var colorspace=readUint32(data,position+3);switch(colorspace){case 16:case 17:case 18:break;default:warn("Unknown colorspace "+colorspace);break}}else if(method===2){info("ICC profile not supported")}break;case 1785737827:this.parseCodestream(data,position,position+dataLength);break;case 1783636e3:if(218793738!==readUint32(data,position)){warn("Invalid JP2 signature")}break;case 1783634458:case 1718909296:case 1920099697:case 1919251232:case 1768449138:break;default:var headerType=String.fromCharCode(tbox>>24&255,tbox>>16&255,tbox>>8&255,tbox&255);warn("Unsupported header type "+tbox+" ("+headerType+")");break}if(jumpDataLength){position+=dataLength}}},parseImageProperties:function JpxImage_parseImageProperties(stream){var newByte=stream.getByte();while(newByte>=0){var oldByte=newByte;newByte=stream.getByte();var code=oldByte<<8|newByte;if(code===65361){stream.skip(4);var Xsiz=stream.getInt32()>>>0;var Ysiz=stream.getInt32()>>>0;var XOsiz=stream.getInt32()>>>0;var YOsiz=stream.getInt32()>>>0;stream.skip(16);var Csiz=stream.getUint16();this.width=Xsiz-XOsiz;this.height=Ysiz-YOsiz;this.componentsCount=Csiz;this.bitsPerComponent=8;return}}throw new Error("JPX Error: No size marker found in JPX stream")},parseCodestream:function JpxImage_parseCodestream(data,start,end){var context={};try{var doNotRecover=false;var position=start;while(position+1<end){var code=readUint16(data,position);position+=2;var length=0,j,sqcd,spqcds,spqcdSize,scalarExpounded,tile;switch(code){case 65359:context.mainHeader=true;break;case 65497:break;case 65361:length=readUint16(data,position);var siz={};siz.Xsiz=readUint32(data,position+4);siz.Ysiz=readUint32(data,position+8);siz.XOsiz=readUint32(data,position+12);siz.YOsiz=readUint32(data,position+16);siz.XTsiz=readUint32(data,position+20);siz.YTsiz=readUint32(data,position+24);siz.XTOsiz=readUint32(data,position+28);siz.YTOsiz=readUint32(data,position+32);var componentsCount=readUint16(data,position+36);siz.Csiz=componentsCount;var components=[];j=position+38;for(var i=0;i<componentsCount;i++){var component={precision:(data[j]&127)+1,isSigned:!!(data[j]&128),XRsiz:data[j+1],YRsiz:data[j+1]};calculateComponentDimensions(component,siz);components.push(component)}context.SIZ=siz;context.components=components;calculateTileGrids(context,components);context.QCC=[];context.COC=[];break;case 65372:length=readUint16(data,position);var qcd={};j=position+2;sqcd=data[j++];switch(sqcd&31){case 0:spqcdSize=8;scalarExpounded=true;break;case 1:spqcdSize=16;scalarExpounded=false;break;case 2:spqcdSize=16;scalarExpounded=true;break;default:throw new Error("JPX Error: Invalid SQcd value "+sqcd)}qcd.noQuantization=spqcdSize===8;qcd.scalarExpounded=scalarExpounded;qcd.guardBits=sqcd>>5;spqcds=[];while(j<length+position){var spqcd={};if(spqcdSize===8){spqcd.epsilon=data[j++]>>3;spqcd.mu=0}else{spqcd.epsilon=data[j]>>3;spqcd.mu=(data[j]&7)<<8|data[j+1];j+=2}spqcds.push(spqcd)}qcd.SPqcds=spqcds;if(context.mainHeader){context.QCD=qcd}else{context.currentTile.QCD=qcd;context.currentTile.QCC=[]}break;case 65373:length=readUint16(data,position);var qcc={};j=position+2;var cqcc;if(context.SIZ.Csiz<257){cqcc=data[j++]}else{cqcc=readUint16(data,j);j+=2}sqcd=data[j++];switch(sqcd&31){case 0:spqcdSize=8;scalarExpounded=true;break;case 1:spqcdSize=16;scalarExpounded=false;break;case 2:spqcdSize=16;scalarExpounded=true;break;default:throw new Error("JPX Error: Invalid SQcd value "+sqcd)}qcc.noQuantization=spqcdSize===8;qcc.scalarExpounded=scalarExpounded;qcc.guardBits=sqcd>>5;spqcds=[];while(j<length+position){spqcd={};if(spqcdSize===8){spqcd.epsilon=data[j++]>>3;spqcd.mu=0}else{spqcd.epsilon=data[j]>>3;spqcd.mu=(data[j]&7)<<8|data[j+1];j+=2}spqcds.push(spqcd)}qcc.SPqcds=spqcds;if(context.mainHeader){context.QCC[cqcc]=qcc}else{context.currentTile.QCC[cqcc]=qcc}break;case 65362:length=readUint16(data,position);var cod={};j=position+2;var scod=data[j++];cod.entropyCoderWithCustomPrecincts=!!(scod&1);cod.sopMarkerUsed=!!(scod&2);cod.ephMarkerUsed=!!(scod&4);cod.progressionOrder=data[j++];cod.layersCount=readUint16(data,j);j+=2;cod.multipleComponentTransform=data[j++];cod.decompositionLevelsCount=data[j++];cod.xcb=(data[j++]&15)+2;cod.ycb=(data[j++]&15)+2;var blockStyle=data[j++];cod.selectiveArithmeticCodingBypass=!!(blockStyle&1);cod.resetContextProbabilities=!!(blockStyle&2);cod.terminationOnEachCodingPass=!!(blockStyle&4);cod.verticalyStripe=!!(blockStyle&8);cod.predictableTermination=!!(blockStyle&16);cod.segmentationSymbolUsed=!!(blockStyle&32);cod.reversibleTransformation=data[j++];if(cod.entropyCoderWithCustomPrecincts){var precinctsSizes=[];while(j<length+position){var precinctsSize=data[j++];precinctsSizes.push({PPx:precinctsSize&15,PPy:precinctsSize>>4})}cod.precinctsSizes=precinctsSizes}var unsupported=[];if(cod.selectiveArithmeticCodingBypass){unsupported.push("selectiveArithmeticCodingBypass")}if(cod.resetContextProbabilities){unsupported.push("resetContextProbabilities")}if(cod.terminationOnEachCodingPass){unsupported.push("terminationOnEachCodingPass")}if(cod.verticalyStripe){unsupported.push("verticalyStripe")}if(cod.predictableTermination){unsupported.push("predictableTermination")}if(unsupported.length>0){doNotRecover=true;throw new Error("JPX Error: Unsupported COD options ("+unsupported.join(", ")+")")}if(context.mainHeader){context.COD=cod}else{context.currentTile.COD=cod;context.currentTile.COC=[]}break;case 65424:length=readUint16(data,position);tile={};tile.index=readUint16(data,position+2);tile.length=readUint32(data,position+4);tile.dataEnd=tile.length+position-2;tile.partIndex=data[position+8];tile.partsCount=data[position+9];context.mainHeader=false;if(tile.partIndex===0){tile.COD=context.COD;tile.COC=context.COC.slice(0);tile.QCD=context.QCD;tile.QCC=context.QCC.slice(0)}context.currentTile=tile;break;case 65427:tile=context.currentTile;if(tile.partIndex===0){initializeTile(context,tile.index);buildPackets(context)}length=tile.dataEnd-position;parseTilePackets(context,data,position,length);break;case 65365:case 65367:case 65368:case 65380:length=readUint16(data,position);break;case 65363:throw new Error("JPX Error: Codestream code 0xFF53 (COC) is "+"not implemented");default:throw new Error("JPX Error: Unknown codestream code: "+code.toString(16))}position+=length}}catch(e){if(doNotRecover||this.failOnCorruptedImage){throw e}else{warn("Trying to recover from "+e.message)}}this.tiles=transformComponents(context);this.width=context.SIZ.Xsiz-context.SIZ.XOsiz;this.height=context.SIZ.Ysiz-context.SIZ.YOsiz;this.componentsCount=context.SIZ.Csiz}};function calculateComponentDimensions(component,siz){component.x0=Math.ceil(siz.XOsiz/component.XRsiz);component.x1=Math.ceil(siz.Xsiz/component.XRsiz);component.y0=Math.ceil(siz.YOsiz/component.YRsiz);component.y1=Math.ceil(siz.Ysiz/component.YRsiz);component.width=component.x1-component.x0;component.height=component.y1-component.y0}function calculateTileGrids(context,components){var siz=context.SIZ;var tile,tiles=[];var numXtiles=Math.ceil((siz.Xsiz-siz.XTOsiz)/siz.XTsiz);var numYtiles=Math.ceil((siz.Ysiz-siz.YTOsiz)/siz.YTsiz);for(var q=0;q<numYtiles;q++){for(var p=0;p<numXtiles;p++){tile={};tile.tx0=Math.max(siz.XTOsiz+p*siz.XTsiz,siz.XOsiz);tile.ty0=Math.max(siz.YTOsiz+q*siz.YTsiz,siz.YOsiz);tile.tx1=Math.min(siz.XTOsiz+(p+1)*siz.XTsiz,siz.Xsiz);tile.ty1=Math.min(siz.YTOsiz+(q+1)*siz.YTsiz,siz.Ysiz);tile.width=tile.tx1-tile.tx0;tile.height=tile.ty1-tile.ty0;tile.components=[];tiles.push(tile)}}context.tiles=tiles;var componentsCount=siz.Csiz;for(var i=0,ii=componentsCount;i<ii;i++){var component=components[i];for(var j=0,jj=tiles.length;j<jj;j++){var tileComponent={};tile=tiles[j];tileComponent.tcx0=Math.ceil(tile.tx0/component.XRsiz);tileComponent.tcy0=Math.ceil(tile.ty0/component.YRsiz);tileComponent.tcx1=Math.ceil(tile.tx1/component.XRsiz);tileComponent.tcy1=Math.ceil(tile.ty1/component.YRsiz);tileComponent.width=tileComponent.tcx1-tileComponent.tcx0;tileComponent.height=tileComponent.tcy1-tileComponent.tcy0;tile.components[i]=tileComponent}}}function getBlocksDimensions(context,component,r){var codOrCoc=component.codingStyleParameters;var result={};if(!codOrCoc.entropyCoderWithCustomPrecincts){result.PPx=15;result.PPy=15}else{result.PPx=codOrCoc.precinctsSizes[r].PPx;result.PPy=codOrCoc.precinctsSizes[r].PPy}result.xcb_=r>0?Math.min(codOrCoc.xcb,result.PPx-1):Math.min(codOrCoc.xcb,result.PPx);result.ycb_=r>0?Math.min(codOrCoc.ycb,result.PPy-1):Math.min(codOrCoc.ycb,result.PPy);return result}function buildPrecincts(context,resolution,dimensions){var precinctWidth=1<<dimensions.PPx;var precinctHeight=1<<dimensions.PPy;var isZeroRes=resolution.resLevel===0;var precinctWidthInSubband=1<<dimensions.PPx+(isZeroRes?0:-1);var precinctHeightInSubband=1<<dimensions.PPy+(isZeroRes?0:-1);var numprecinctswide=resolution.trx1>resolution.trx0?Math.ceil(resolution.trx1/precinctWidth)-Math.floor(resolution.trx0/precinctWidth):0;var numprecinctshigh=resolution.try1>resolution.try0?Math.ceil(resolution.try1/precinctHeight)-Math.floor(resolution.try0/precinctHeight):0;var numprecincts=numprecinctswide*numprecinctshigh;resolution.precinctParameters={precinctWidth:precinctWidth,precinctHeight:precinctHeight,numprecinctswide:numprecinctswide,numprecinctshigh:numprecinctshigh,numprecincts:numprecincts,precinctWidthInSubband:precinctWidthInSubband,precinctHeightInSubband:precinctHeightInSubband}}function buildCodeblocks(context,subband,dimensions){var xcb_=dimensions.xcb_;var ycb_=dimensions.ycb_;var codeblockWidth=1<<xcb_;var codeblockHeight=1<<ycb_;var cbx0=subband.tbx0>>xcb_;var cby0=subband.tby0>>ycb_;var cbx1=subband.tbx1+codeblockWidth-1>>xcb_;var cby1=subband.tby1+codeblockHeight-1>>ycb_;var precinctParameters=subband.resolution.precinctParameters;var codeblocks=[];var precincts=[];var i,j,codeblock,precinctNumber;for(j=cby0;j<cby1;j++){for(i=cbx0;i<cbx1;i++){codeblock={cbx:i,cby:j,tbx0:codeblockWidth*i,tby0:codeblockHeight*j,tbx1:codeblockWidth*(i+1),tby1:codeblockHeight*(j+1)};codeblock.tbx0_=Math.max(subband.tbx0,codeblock.tbx0);codeblock.tby0_=Math.max(subband.tby0,codeblock.tby0);codeblock.tbx1_=Math.min(subband.tbx1,codeblock.tbx1);codeblock.tby1_=Math.min(subband.tby1,codeblock.tby1);var pi=Math.floor((codeblock.tbx0_-subband.tbx0)/precinctParameters.precinctWidthInSubband);var pj=Math.floor((codeblock.tby0_-subband.tby0)/precinctParameters.precinctHeightInSubband);precinctNumber=pi+pj*precinctParameters.numprecinctswide;codeblock.precinctNumber=precinctNumber;codeblock.subbandType=subband.type;codeblock.Lblock=3;if(codeblock.tbx1_<=codeblock.tbx0_||codeblock.tby1_<=codeblock.tby0_){continue}codeblocks.push(codeblock);var precinct=precincts[precinctNumber];if(precinct!==undefined){if(i<precinct.cbxMin){precinct.cbxMin=i}else if(i>precinct.cbxMax){precinct.cbxMax=i}if(j<precinct.cbyMin){precinct.cbxMin=j}else if(j>precinct.cbyMax){precinct.cbyMax=j}}else{precincts[precinctNumber]=precinct={cbxMin:i,cbyMin:j,cbxMax:i,cbyMax:j}}codeblock.precinct=precinct}}subband.codeblockParameters={codeblockWidth:xcb_,codeblockHeight:ycb_,numcodeblockwide:cbx1-cbx0+1,numcodeblockhigh:cby1-cby0+1};subband.codeblocks=codeblocks;subband.precincts=precincts}function createPacket(resolution,precinctNumber,layerNumber){var precinctCodeblocks=[];var subbands=resolution.subbands;for(var i=0,ii=subbands.length;i<ii;i++){var subband=subbands[i];var codeblocks=subband.codeblocks;for(var j=0,jj=codeblocks.length;j<jj;j++){ var codeblock=codeblocks[j];if(codeblock.precinctNumber!==precinctNumber){continue}precinctCodeblocks.push(codeblock)}}return{layerNumber:layerNumber,codeblocks:precinctCodeblocks}}function LayerResolutionComponentPositionIterator(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var layersCount=tile.codingStyleDefaultParameters.layersCount;var componentsCount=siz.Csiz;var maxDecompositionLevelsCount=0;for(var q=0;q<componentsCount;q++){maxDecompositionLevelsCount=Math.max(maxDecompositionLevelsCount,tile.components[q].codingStyleParameters.decompositionLevelsCount)}var l=0,r=0,i=0,k=0;this.nextPacket=function JpxImage_nextPacket(){for(;l<layersCount;l++){for(;r<=maxDecompositionLevelsCount;r++){for(;i<componentsCount;i++){var component=tile.components[i];if(r>component.codingStyleParameters.decompositionLevelsCount){continue}var resolution=component.resolutions[r];var numprecincts=resolution.precinctParameters.numprecincts;for(;k<numprecincts;){var packet=createPacket(resolution,k,l);k++;return packet}k=0}i=0}r=0}}}function ResolutionLayerComponentPositionIterator(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var layersCount=tile.codingStyleDefaultParameters.layersCount;var componentsCount=siz.Csiz;var maxDecompositionLevelsCount=0;for(var q=0;q<componentsCount;q++){maxDecompositionLevelsCount=Math.max(maxDecompositionLevelsCount,tile.components[q].codingStyleParameters.decompositionLevelsCount)}var r=0,l=0,i=0,k=0;this.nextPacket=function JpxImage_nextPacket(){for(;r<=maxDecompositionLevelsCount;r++){for(;l<layersCount;l++){for(;i<componentsCount;i++){var component=tile.components[i];if(r>component.codingStyleParameters.decompositionLevelsCount){continue}var resolution=component.resolutions[r];var numprecincts=resolution.precinctParameters.numprecincts;for(;k<numprecincts;){var packet=createPacket(resolution,k,l);k++;return packet}k=0}i=0}l=0}}}function ResolutionPositionComponentLayerIterator(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var layersCount=tile.codingStyleDefaultParameters.layersCount;var componentsCount=siz.Csiz;var l,r,c,p;var maxDecompositionLevelsCount=0;for(c=0;c<componentsCount;c++){var component=tile.components[c];maxDecompositionLevelsCount=Math.max(maxDecompositionLevelsCount,component.codingStyleParameters.decompositionLevelsCount)}var maxNumPrecinctsInLevel=new Int32Array(maxDecompositionLevelsCount+1);for(r=0;r<=maxDecompositionLevelsCount;++r){var maxNumPrecincts=0;for(c=0;c<componentsCount;++c){var resolutions=tile.components[c].resolutions;if(r<resolutions.length){maxNumPrecincts=Math.max(maxNumPrecincts,resolutions[r].precinctParameters.numprecincts)}}maxNumPrecinctsInLevel[r]=maxNumPrecincts}l=0;r=0;c=0;p=0;this.nextPacket=function JpxImage_nextPacket(){for(;r<=maxDecompositionLevelsCount;r++){for(;p<maxNumPrecinctsInLevel[r];p++){for(;c<componentsCount;c++){var component=tile.components[c];if(r>component.codingStyleParameters.decompositionLevelsCount){continue}var resolution=component.resolutions[r];var numprecincts=resolution.precinctParameters.numprecincts;if(p>=numprecincts){continue}for(;l<layersCount;){var packet=createPacket(resolution,p,l);l++;return packet}l=0}c=0}p=0}}}function PositionComponentResolutionLayerIterator(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var layersCount=tile.codingStyleDefaultParameters.layersCount;var componentsCount=siz.Csiz;var precinctsSizes=getPrecinctSizesInImageScale(tile);var precinctsIterationSizes=precinctsSizes;var l=0,r=0,c=0,px=0,py=0;this.nextPacket=function JpxImage_nextPacket(){for(;py<precinctsIterationSizes.maxNumHigh;py++){for(;px<precinctsIterationSizes.maxNumWide;px++){for(;c<componentsCount;c++){var component=tile.components[c];var decompositionLevelsCount=component.codingStyleParameters.decompositionLevelsCount;for(;r<=decompositionLevelsCount;r++){var resolution=component.resolutions[r];var sizeInImageScale=precinctsSizes.components[c].resolutions[r];var k=getPrecinctIndexIfExist(px,py,sizeInImageScale,precinctsIterationSizes,resolution);if(k===null){continue}for(;l<layersCount;){var packet=createPacket(resolution,k,l);l++;return packet}l=0}r=0}c=0}px=0}}}function ComponentPositionResolutionLayerIterator(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var layersCount=tile.codingStyleDefaultParameters.layersCount;var componentsCount=siz.Csiz;var precinctsSizes=getPrecinctSizesInImageScale(tile);var l=0,r=0,c=0,px=0,py=0;this.nextPacket=function JpxImage_nextPacket(){for(;c<componentsCount;++c){var component=tile.components[c];var precinctsIterationSizes=precinctsSizes.components[c];var decompositionLevelsCount=component.codingStyleParameters.decompositionLevelsCount;for(;py<precinctsIterationSizes.maxNumHigh;py++){for(;px<precinctsIterationSizes.maxNumWide;px++){for(;r<=decompositionLevelsCount;r++){var resolution=component.resolutions[r];var sizeInImageScale=precinctsIterationSizes.resolutions[r];var k=getPrecinctIndexIfExist(px,py,sizeInImageScale,precinctsIterationSizes,resolution);if(k===null){continue}for(;l<layersCount;){var packet=createPacket(resolution,k,l);l++;return packet}l=0}r=0}px=0}py=0}}}function getPrecinctIndexIfExist(pxIndex,pyIndex,sizeInImageScale,precinctIterationSizes,resolution){var posX=pxIndex*precinctIterationSizes.minWidth;var posY=pyIndex*precinctIterationSizes.minHeight;if(posX%sizeInImageScale.width!==0||posY%sizeInImageScale.height!==0){return null}var startPrecinctRowIndex=posY/sizeInImageScale.width*resolution.precinctParameters.numprecinctswide;return posX/sizeInImageScale.height+startPrecinctRowIndex}function getPrecinctSizesInImageScale(tile){var componentsCount=tile.components.length;var minWidth=Number.MAX_VALUE;var minHeight=Number.MAX_VALUE;var maxNumWide=0;var maxNumHigh=0;var sizePerComponent=new Array(componentsCount);for(var c=0;c<componentsCount;c++){var component=tile.components[c];var decompositionLevelsCount=component.codingStyleParameters.decompositionLevelsCount;var sizePerResolution=new Array(decompositionLevelsCount+1);var minWidthCurrentComponent=Number.MAX_VALUE;var minHeightCurrentComponent=Number.MAX_VALUE;var maxNumWideCurrentComponent=0;var maxNumHighCurrentComponent=0;var scale=1;for(var r=decompositionLevelsCount;r>=0;--r){var resolution=component.resolutions[r];var widthCurrentResolution=scale*resolution.precinctParameters.precinctWidth;var heightCurrentResolution=scale*resolution.precinctParameters.precinctHeight;minWidthCurrentComponent=Math.min(minWidthCurrentComponent,widthCurrentResolution);minHeightCurrentComponent=Math.min(minHeightCurrentComponent,heightCurrentResolution);maxNumWideCurrentComponent=Math.max(maxNumWideCurrentComponent,resolution.precinctParameters.numprecinctswide);maxNumHighCurrentComponent=Math.max(maxNumHighCurrentComponent,resolution.precinctParameters.numprecinctshigh);sizePerResolution[r]={width:widthCurrentResolution,height:heightCurrentResolution};scale<<=1}minWidth=Math.min(minWidth,minWidthCurrentComponent);minHeight=Math.min(minHeight,minHeightCurrentComponent);maxNumWide=Math.max(maxNumWide,maxNumWideCurrentComponent);maxNumHigh=Math.max(maxNumHigh,maxNumHighCurrentComponent);sizePerComponent[c]={resolutions:sizePerResolution,minWidth:minWidthCurrentComponent,minHeight:minHeightCurrentComponent,maxNumWide:maxNumWideCurrentComponent,maxNumHigh:maxNumHighCurrentComponent}}return{components:sizePerComponent,minWidth:minWidth,minHeight:minHeight,maxNumWide:maxNumWide,maxNumHigh:maxNumHigh}}function buildPackets(context){var siz=context.SIZ;var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var componentsCount=siz.Csiz;for(var c=0;c<componentsCount;c++){var component=tile.components[c];var decompositionLevelsCount=component.codingStyleParameters.decompositionLevelsCount;var resolutions=[];var subbands=[];for(var r=0;r<=decompositionLevelsCount;r++){var blocksDimensions=getBlocksDimensions(context,component,r);var resolution={};var scale=1<<decompositionLevelsCount-r;resolution.trx0=Math.ceil(component.tcx0/scale);resolution.try0=Math.ceil(component.tcy0/scale);resolution.trx1=Math.ceil(component.tcx1/scale);resolution.try1=Math.ceil(component.tcy1/scale);resolution.resLevel=r;buildPrecincts(context,resolution,blocksDimensions);resolutions.push(resolution);var subband;if(r===0){subband={};subband.type="LL";subband.tbx0=Math.ceil(component.tcx0/scale);subband.tby0=Math.ceil(component.tcy0/scale);subband.tbx1=Math.ceil(component.tcx1/scale);subband.tby1=Math.ceil(component.tcy1/scale);subband.resolution=resolution;buildCodeblocks(context,subband,blocksDimensions);subbands.push(subband);resolution.subbands=[subband]}else{var bscale=1<<decompositionLevelsCount-r+1;var resolutionSubbands=[];subband={};subband.type="HL";subband.tbx0=Math.ceil(component.tcx0/bscale-.5);subband.tby0=Math.ceil(component.tcy0/bscale);subband.tbx1=Math.ceil(component.tcx1/bscale-.5);subband.tby1=Math.ceil(component.tcy1/bscale);subband.resolution=resolution;buildCodeblocks(context,subband,blocksDimensions);subbands.push(subband);resolutionSubbands.push(subband);subband={};subband.type="LH";subband.tbx0=Math.ceil(component.tcx0/bscale);subband.tby0=Math.ceil(component.tcy0/bscale-.5);subband.tbx1=Math.ceil(component.tcx1/bscale);subband.tby1=Math.ceil(component.tcy1/bscale-.5);subband.resolution=resolution;buildCodeblocks(context,subband,blocksDimensions);subbands.push(subband);resolutionSubbands.push(subband);subband={};subband.type="HH";subband.tbx0=Math.ceil(component.tcx0/bscale-.5);subband.tby0=Math.ceil(component.tcy0/bscale-.5);subband.tbx1=Math.ceil(component.tcx1/bscale-.5);subband.tby1=Math.ceil(component.tcy1/bscale-.5);subband.resolution=resolution;buildCodeblocks(context,subband,blocksDimensions);subbands.push(subband);resolutionSubbands.push(subband);resolution.subbands=resolutionSubbands}}component.resolutions=resolutions;component.subbands=subbands}var progressionOrder=tile.codingStyleDefaultParameters.progressionOrder;switch(progressionOrder){case 0:tile.packetsIterator=new LayerResolutionComponentPositionIterator(context);break;case 1:tile.packetsIterator=new ResolutionLayerComponentPositionIterator(context);break;case 2:tile.packetsIterator=new ResolutionPositionComponentLayerIterator(context);break;case 3:tile.packetsIterator=new PositionComponentResolutionLayerIterator(context);break;case 4:tile.packetsIterator=new ComponentPositionResolutionLayerIterator(context);break;default:throw new Error("JPX Error: Unsupported progression order "+progressionOrder)}}function parseTilePackets(context,data,offset,dataLength){var position=0;var buffer,bufferSize=0,skipNextBit=false;function readBits(count){while(bufferSize<count){if(offset+position>=data.length){throw new Error("Unexpected EOF")}var b=data[offset+position];position++;if(skipNextBit){buffer=buffer<<7|b;bufferSize+=7;skipNextBit=false}else{buffer=buffer<<8|b;bufferSize+=8}if(b===255){skipNextBit=true}}bufferSize-=count;return buffer>>>bufferSize&(1<<count)-1}function skipMarkerIfEqual(value){if(data[offset+position-1]===255&&data[offset+position]===value){skipBytes(1);return true}else if(data[offset+position]===255&&data[offset+position+1]===value){skipBytes(2);return true}return false}function skipBytes(count){position+=count}function alignToByte(){bufferSize=0;if(skipNextBit){position++;skipNextBit=false}}function readCodingpasses(){if(readBits(1)===0){return 1}if(readBits(1)===0){return 2}var value=readBits(2);if(value<3){return value+3}value=readBits(5);if(value<31){return value+6}value=readBits(7);return value+37}var tileIndex=context.currentTile.index;var tile=context.tiles[tileIndex];var sopMarkerUsed=context.COD.sopMarkerUsed;var ephMarkerUsed=context.COD.ephMarkerUsed;var packetsIterator=tile.packetsIterator;while(position<dataLength){try{alignToByte();if(sopMarkerUsed&&skipMarkerIfEqual(145)){skipBytes(4)}var packet=packetsIterator.nextPacket();if(packet===undefined){return}if(!readBits(1)){continue}var layerNumber=packet.layerNumber;var queue=[],codeblock;for(var i=0,ii=packet.codeblocks.length;i<ii;i++){codeblock=packet.codeblocks[i];var precinct=codeblock.precinct;var codeblockColumn=codeblock.cbx-precinct.cbxMin;var codeblockRow=codeblock.cby-precinct.cbyMin;var codeblockIncluded=false;var firstTimeInclusion=false;var valueReady;if(codeblock["included"]!==undefined){codeblockIncluded=!!readBits(1)}else{precinct=codeblock.precinct;var inclusionTree,zeroBitPlanesTree;if(precinct["inclusionTree"]!==undefined){inclusionTree=precinct.inclusionTree}else{var width=precinct.cbxMax-precinct.cbxMin+1;var height=precinct.cbyMax-precinct.cbyMin+1;inclusionTree=new InclusionTree(width,height);zeroBitPlanesTree=new TagTree(width,height);precinct.inclusionTree=inclusionTree;precinct.zeroBitPlanesTree=zeroBitPlanesTree}inclusionTree.reset(codeblockColumn,codeblockRow,layerNumber);while(true){if(position>=data.length){return}if(inclusionTree.isAboveThreshold()){break}if(inclusionTree.isKnown()){inclusionTree.nextLevel();continue}if(readBits(1)){inclusionTree.setKnown();if(inclusionTree.isLeaf()){codeblock.included=true;codeblockIncluded=firstTimeInclusion=true;break}else{inclusionTree.nextLevel()}}else{inclusionTree.incrementValue()}}}if(!codeblockIncluded){continue}if(firstTimeInclusion){zeroBitPlanesTree=precinct.zeroBitPlanesTree;zeroBitPlanesTree.reset(codeblockColumn,codeblockRow);while(true){if(position>=data.length){return}if(readBits(1)){valueReady=!zeroBitPlanesTree.nextLevel();if(valueReady){break}}else{zeroBitPlanesTree.incrementValue()}}codeblock.zeroBitPlanes=zeroBitPlanesTree.value}var codingpasses=readCodingpasses();while(readBits(1)){codeblock.Lblock++}var codingpassesLog2=log2(codingpasses);var bits=(codingpasses<1<<codingpassesLog2?codingpassesLog2-1:codingpassesLog2)+codeblock.Lblock;var codedDataLength=readBits(bits);queue.push({codeblock:codeblock,codingpasses:codingpasses,dataLength:codedDataLength})}alignToByte();if(ephMarkerUsed){skipMarkerIfEqual(146)}while(queue.length>0){var packetItem=queue.shift();codeblock=packetItem.codeblock;if(codeblock["data"]===undefined){codeblock.data=[]}codeblock.data.push({data:data,start:offset+position,end:offset+position+packetItem.dataLength,codingpasses:packetItem.codingpasses});position+=packetItem.dataLength}}catch(e){return}}return position}function copyCoefficients(coefficients,levelWidth,levelHeight,subband,delta,mb,reversible,segmentationSymbolUsed){var x0=subband.tbx0;var y0=subband.tby0;var width=subband.tbx1-subband.tbx0;var codeblocks=subband.codeblocks;var right=subband.type.charAt(0)==="H"?1:0;var bottom=subband.type.charAt(1)==="H"?levelWidth:0;for(var i=0,ii=codeblocks.length;i<ii;++i){var codeblock=codeblocks[i];var blockWidth=codeblock.tbx1_-codeblock.tbx0_;var blockHeight=codeblock.tby1_-codeblock.tby0_;if(blockWidth===0||blockHeight===0){continue}if(codeblock["data"]===undefined){continue}var bitModel,currentCodingpassType;bitModel=new BitModel(blockWidth,blockHeight,codeblock.subbandType,codeblock.zeroBitPlanes,mb);currentCodingpassType=2;var data=codeblock.data,totalLength=0,codingpasses=0;var j,jj,dataItem;for(j=0,jj=data.length;j<jj;j++){dataItem=data[j];totalLength+=dataItem.end-dataItem.start;codingpasses+=dataItem.codingpasses}var encodedData=new Int16Array(totalLength);var position=0;for(j=0,jj=data.length;j<jj;j++){dataItem=data[j];var chunk=dataItem.data.subarray(dataItem.start,dataItem.end);encodedData.set(chunk,position);position+=chunk.length}var decoder=new ArithmeticDecoder(encodedData,0,totalLength);bitModel.setDecoder(decoder);for(j=0;j<codingpasses;j++){switch(currentCodingpassType){case 0:bitModel.runSignificancePropogationPass();break;case 1:bitModel.runMagnitudeRefinementPass();break;case 2:bitModel.runCleanupPass();if(segmentationSymbolUsed){bitModel.checkSegmentationSymbol()}break}currentCodingpassType=(currentCodingpassType+1)%3}var offset=codeblock.tbx0_-x0+(codeblock.tby0_-y0)*width;var sign=bitModel.coefficentsSign;var magnitude=bitModel.coefficentsMagnitude;var bitsDecoded=bitModel.bitsDecoded;var magnitudeCorrection=reversible?0:.5;var k,n,nb;position=0;var interleave=subband.type!=="LL";for(j=0;j<blockHeight;j++){var row=offset/width|0;var levelOffset=2*row*(levelWidth-width)+right+bottom;for(k=0;k<blockWidth;k++){n=magnitude[position];if(n!==0){n=(n+magnitudeCorrection)*delta;if(sign[position]!==0){n=-n}nb=bitsDecoded[position];var pos=interleave?levelOffset+(offset<<1):offset;if(reversible&&nb>=mb){coefficients[pos]=n}else{coefficients[pos]=n*(1<<mb-nb)}}offset++;position++}offset+=width-blockWidth}}}function transformTile(context,tile,c){var component=tile.components[c];var codingStyleParameters=component.codingStyleParameters;var quantizationParameters=component.quantizationParameters;var decompositionLevelsCount=codingStyleParameters.decompositionLevelsCount;var spqcds=quantizationParameters.SPqcds;var scalarExpounded=quantizationParameters.scalarExpounded;var guardBits=quantizationParameters.guardBits;var segmentationSymbolUsed=codingStyleParameters.segmentationSymbolUsed;var precision=context.components[c].precision;var reversible=codingStyleParameters.reversibleTransformation;var transform=reversible?new ReversibleTransform:new IrreversibleTransform;var subbandCoefficients=[];var b=0;for(var i=0;i<=decompositionLevelsCount;i++){var resolution=component.resolutions[i];var width=resolution.trx1-resolution.trx0;var height=resolution.try1-resolution.try0;var coefficients=new Float32Array(width*height);for(var j=0,jj=resolution.subbands.length;j<jj;j++){var mu,epsilon;if(!scalarExpounded){mu=spqcds[0].mu;epsilon=spqcds[0].epsilon+(i>0?1-i:0)}else{mu=spqcds[b].mu;epsilon=spqcds[b].epsilon;b++}var subband=resolution.subbands[j];var gainLog2=SubbandsGainLog2[subband.type];var delta=reversible?1:Math.pow(2,precision+gainLog2-epsilon)*(1+mu/2048);var mb=guardBits+epsilon-1;copyCoefficients(coefficients,width,height,subband,delta,mb,reversible,segmentationSymbolUsed)}subbandCoefficients.push({width:width,height:height,items:coefficients})}var result=transform.calculate(subbandCoefficients,component.tcx0,component.tcy0);return{left:component.tcx0,top:component.tcy0,width:result.width,height:result.height,items:result.items}}function transformComponents(context){var siz=context.SIZ;var components=context.components;var componentsCount=siz.Csiz;var resultImages=[];for(var i=0,ii=context.tiles.length;i<ii;i++){var tile=context.tiles[i];var transformedTiles=[];var c;for(c=0;c<componentsCount;c++){transformedTiles[c]=transformTile(context,tile,c)}var tile0=transformedTiles[0];var isSigned=components[0].isSigned;if(isSigned){var out=new Int16Array(tile0.items.length*componentsCount)}else{var out=new Uint16Array(tile0.items.length*componentsCount)}var result={left:tile0.left,top:tile0.top,width:tile0.width,height:tile0.height,items:out};var shift,offset,max,min,maxK;var pos=0,j,jj,y0,y1,y2,r,g,b,k,val;if(tile.codingStyleDefaultParameters.multipleComponentTransform){var fourComponents=componentsCount===4;var y0items=transformedTiles[0].items;var y1items=transformedTiles[1].items;var y2items=transformedTiles[2].items;var y3items=fourComponents?transformedTiles[3].items:null;shift=components[0].precision-8;offset=(128<<shift)+.5;max=255*(1<<shift);maxK=max*.5;min=-maxK;var component0=tile.components[0];var alpha01=componentsCount-3;jj=y0items.length;if(!component0.codingStyleParameters.reversibleTransformation){for(j=0;j<jj;j++,pos+=alpha01){y0=y0items[j]+offset;y1=y1items[j];y2=y2items[j];r=y0+1.402*y2;g=y0-.34413*y1-.71414*y2;b=y0+1.772*y1;out[pos++]=r<=0?0:r>=max?255:r>>shift;out[pos++]=g<=0?0:g>=max?255:g>>shift;out[pos++]=b<=0?0:b>=max?255:b>>shift}}else{for(j=0;j<jj;j++,pos+=alpha01){y0=y0items[j]+offset;y1=y1items[j];y2=y2items[j];g=y0-(y2+y1>>2);r=g+y2;b=g+y1;out[pos++]=r<=0?0:r>=max?255:r>>shift;out[pos++]=g<=0?0:g>=max?255:g>>shift;out[pos++]=b<=0?0:b>=max?255:b>>shift}}if(fourComponents){for(j=0,pos=3;j<jj;j++,pos+=4){k=y3items[j];out[pos]=k<=min?0:k>=maxK?255:k+offset>>shift}}}else{for(c=0;c<componentsCount;c++){if(components[c].precision===8){var items=transformedTiles[c].items;shift=components[c].precision-8;offset=(128<<shift)+.5;max=127.5*(1<<shift);min=-max;for(pos=c,j=0,jj=items.length;j<jj;j++){val=items[j];out[pos]=val<=min?0:val>=max?255:val+offset>>shift;pos+=componentsCount}}else{var isSigned=components[c].isSigned;var items=transformedTiles[c].items;if(isSigned){for(pos=c,j=0,jj=items.length;j<jj;j++){out[pos]=items[j];pos+=componentsCount}}else{shift=components[c].precision-8;offset=(128<<shift)+.5;var precisionMax=Math.pow(2,components[c].precision)-1;for(pos=c,j=0,jj=items.length;j<jj;j++){val=items[j];out[pos]=Math.max(Math.min(val+offset,precisionMax),0);pos+=componentsCount}}}}}resultImages.push(result)}return resultImages}function initializeTile(context,tileIndex){var siz=context.SIZ;var componentsCount=siz.Csiz;var tile=context.tiles[tileIndex];for(var c=0;c<componentsCount;c++){var component=tile.components[c];var qcdOrQcc=context.currentTile.QCC[c]!==undefined?context.currentTile.QCC[c]:context.currentTile.QCD;component.quantizationParameters=qcdOrQcc;var codOrCoc=context.currentTile.COC[c]!==undefined?context.currentTile.COC[c]:context.currentTile.COD;component.codingStyleParameters=codOrCoc}tile.codingStyleDefaultParameters=context.currentTile.COD}var TagTree=function TagTreeClosure(){function TagTree(width,height){var levelsLength=log2(Math.max(width,height))+1;this.levels=[];for(var i=0;i<levelsLength;i++){var level={width:width,height:height,items:[]};this.levels.push(level);width=Math.ceil(width/2);height=Math.ceil(height/2)}}TagTree.prototype={reset:function TagTree_reset(i,j){var currentLevel=0,value=0,level;while(currentLevel<this.levels.length){level=this.levels[currentLevel];var index=i+j*level.width;if(level.items[index]!==undefined){value=level.items[index];break}level.index=index;i>>=1;j>>=1;currentLevel++}currentLevel--;level=this.levels[currentLevel];level.items[level.index]=value;this.currentLevel=currentLevel;delete this.value},incrementValue:function TagTree_incrementValue(){var level=this.levels[this.currentLevel];level.items[level.index]++},nextLevel:function TagTree_nextLevel(){var currentLevel=this.currentLevel;var level=this.levels[currentLevel];var value=level.items[level.index];currentLevel--;if(currentLevel<0){this.value=value;return false}this.currentLevel=currentLevel;level=this.levels[currentLevel];level.items[level.index]=value;return true}};return TagTree}();var InclusionTree=function InclusionTreeClosure(){function InclusionTree(width,height){var levelsLength=log2(Math.max(width,height))+1;this.levels=[];for(var i=0;i<levelsLength;i++){var items=new Uint8Array(width*height);var status=new Uint8Array(width*height);for(var j=0,jj=items.length;j<jj;j++){items[j]=0;status[j]=0}var level={width:width,height:height,items:items,status:status};this.levels.push(level);width=Math.ceil(width/2);height=Math.ceil(height/2)}}InclusionTree.prototype={reset:function InclusionTree_reset(i,j,stopValue){this.currentStopValue=stopValue;var currentLevel=0;while(currentLevel<this.levels.length){var level=this.levels[currentLevel];var index=i+j*level.width;level.index=index;i>>=1;j>>=1;currentLevel++}this.currentLevel=this.levels.length-1;this.minValue=this.levels[this.currentLevel].items[0];return},incrementValue:function InclusionTree_incrementValue(){var level=this.levels[this.currentLevel];level.items[level.index]=level.items[level.index]+1;if(level.items[level.index]>this.minValue){this.minValue=level.items[level.index]}},nextLevel:function InclusionTree_nextLevel(){var currentLevel=this.currentLevel;currentLevel--;if(currentLevel<0){return false}else{this.currentLevel=currentLevel;var level=this.levels[currentLevel];if(level.items[level.index]<this.minValue){level.items[level.index]=this.minValue}else if(level.items[level.index]>this.minValue){this.minValue=level.items[level.index]}return true}},isLeaf:function InclusionTree_isLeaf(){return this.currentLevel===0},isAboveThreshold:function InclusionTree_isAboveThreshold(){var levelindex=this.currentLevel;var level=this.levels[levelindex];return level.items[level.index]>this.currentStopValue},isKnown:function InclusionTree_isKnown(){var levelindex=this.currentLevel;var level=this.levels[levelindex];return level.status[level.index]>0},setKnown:function InclusionTree_setKnown(){var levelindex=this.currentLevel;var level=this.levels[levelindex];level.status[level.index]=1;return}};return InclusionTree}();var BitModel=function BitModelClosure(){var UNIFORM_CONTEXT=17;var RUNLENGTH_CONTEXT=18;var LLAndLHContextsLabel=new Uint8Array([0,5,8,0,3,7,8,0,4,7,8,0,0,0,0,0,1,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8]);var HLContextLabel=new Uint8Array([0,3,4,0,5,7,7,0,8,8,8,0,0,0,0,0,1,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8]);var HHContextLabel=new Uint8Array([0,1,2,0,1,2,2,0,2,2,2,0,0,0,0,0,3,4,5,0,4,5,5,0,5,5,5,0,0,0,0,0,6,7,7,0,7,7,7,0,7,7,7,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8]);function BitModel(width,height,subband,zeroBitPlanes,mb){this.width=width;this.height=height;this.contextLabelTable=subband==="HH"?HHContextLabel:subband==="HL"?HLContextLabel:LLAndLHContextsLabel;var coefficientCount=width*height;this.neighborsSignificance=new Uint8Array(coefficientCount);this.coefficentsSign=new Uint8Array(coefficientCount);this.coefficentsMagnitude=mb>14?new Uint32Array(coefficientCount):mb>6?new Uint16Array(coefficientCount):new Uint8Array(coefficientCount);this.processingFlags=new Uint8Array(coefficientCount);var bitsDecoded=new Uint8Array(coefficientCount);if(zeroBitPlanes!==0){for(var i=0;i<coefficientCount;i++){bitsDecoded[i]=zeroBitPlanes}}this.bitsDecoded=bitsDecoded;this.reset()}BitModel.prototype={setDecoder:function BitModel_setDecoder(decoder){this.decoder=decoder},reset:function BitModel_reset(){this.contexts=new Int8Array(19);this.contexts[0]=4<<1|0;this.contexts[UNIFORM_CONTEXT]=46<<1|0;this.contexts[RUNLENGTH_CONTEXT]=3<<1|0},setNeighborsSignificance:function BitModel_setNeighborsSignificance(row,column,index){var neighborsSignificance=this.neighborsSignificance;var width=this.width,height=this.height;var left=column>0;var right=column+1<width;var i;if(row>0){i=index-width;if(left){neighborsSignificance[i-1]+=16}if(right){neighborsSignificance[i+1]+=16}neighborsSignificance[i]+=4}if(row+1<height){i=index+width;if(left){neighborsSignificance[i-1]+=16}if(right){neighborsSignificance[i+1]+=16}neighborsSignificance[i]+=4}if(left){neighborsSignificance[index-1]+=1}if(right){neighborsSignificance[index+1]+=1}neighborsSignificance[index]|=128},runSignificancePropogationPass:function BitModel_runSignificancePropogationPass(){var decoder=this.decoder;var width=this.width,height=this.height;var coefficentsMagnitude=this.coefficentsMagnitude;var coefficentsSign=this.coefficentsSign;var neighborsSignificance=this.neighborsSignificance;var processingFlags=this.processingFlags;var contexts=this.contexts;var labels=this.contextLabelTable;var bitsDecoded=this.bitsDecoded;var processedInverseMask=~1;var processedMask=1;var firstMagnitudeBitMask=2;for(var i0=0;i0<height;i0+=4){for(var j=0;j<width;j++){var index=i0*width+j;for(var i1=0;i1<4;i1++,index+=width){var i=i0+i1;if(i>=height){break}processingFlags[index]&=processedInverseMask;if(coefficentsMagnitude[index]||!neighborsSignificance[index]){continue}var contextLabel=labels[neighborsSignificance[index]];var decision=decoder.readBit(contexts,contextLabel);if(decision){var sign=this.decodeSignBit(i,j,index);coefficentsSign[index]=sign;coefficentsMagnitude[index]=1;this.setNeighborsSignificance(i,j,index);processingFlags[index]|=firstMagnitudeBitMask}bitsDecoded[index]++;processingFlags[index]|=processedMask}}}},decodeSignBit:function BitModel_decodeSignBit(row,column,index){var width=this.width,height=this.height;var coefficentsMagnitude=this.coefficentsMagnitude;var coefficentsSign=this.coefficentsSign;var contribution,sign0,sign1,significance1;var contextLabel,decoded;significance1=column>0&&coefficentsMagnitude[index-1]!==0;if(column+1<width&&coefficentsMagnitude[index+1]!==0){sign1=coefficentsSign[index+1];if(significance1){sign0=coefficentsSign[index-1];contribution=1-sign1-sign0}else{contribution=1-sign1-sign1}}else if(significance1){sign0=coefficentsSign[index-1];contribution=1-sign0-sign0}else{contribution=0}var horizontalContribution=3*contribution;significance1=row>0&&coefficentsMagnitude[index-width]!==0;if(row+1<height&&coefficentsMagnitude[index+width]!==0){sign1=coefficentsSign[index+width];if(significance1){sign0=coefficentsSign[index-width];contribution=1-sign1-sign0+horizontalContribution}else{contribution=1-sign1-sign1+horizontalContribution}}else if(significance1){sign0=coefficentsSign[index-width];contribution=1-sign0-sign0+horizontalContribution}else{contribution=horizontalContribution}if(contribution>=0){contextLabel=9+contribution;decoded=this.decoder.readBit(this.contexts,contextLabel)}else{contextLabel=9-contribution;decoded=this.decoder.readBit(this.contexts,contextLabel)^1}return decoded},runMagnitudeRefinementPass:function BitModel_runMagnitudeRefinementPass(){var decoder=this.decoder;var width=this.width,height=this.height;var coefficentsMagnitude=this.coefficentsMagnitude;var neighborsSignificance=this.neighborsSignificance;var contexts=this.contexts;var bitsDecoded=this.bitsDecoded;var processingFlags=this.processingFlags;var processedMask=1;var firstMagnitudeBitMask=2;var length=width*height;var width4=width*4;for(var index0=0,indexNext;index0<length;index0=indexNext){indexNext=Math.min(length,index0+width4);for(var j=0;j<width;j++){for(var index=index0+j;index<indexNext;index+=width){if(!coefficentsMagnitude[index]||(processingFlags[index]&processedMask)!==0){continue}var contextLabel=16;if((processingFlags[index]&firstMagnitudeBitMask)!==0){processingFlags[index]^=firstMagnitudeBitMask;var significance=neighborsSignificance[index]&127;contextLabel=significance===0?15:14}var bit=decoder.readBit(contexts,contextLabel);coefficentsMagnitude[index]=coefficentsMagnitude[index]<<1|bit;bitsDecoded[index]++;processingFlags[index]|=processedMask}}}},runCleanupPass:function BitModel_runCleanupPass(){var decoder=this.decoder;var width=this.width,height=this.height;var neighborsSignificance=this.neighborsSignificance;var coefficentsMagnitude=this.coefficentsMagnitude;var coefficentsSign=this.coefficentsSign;var contexts=this.contexts;var labels=this.contextLabelTable;var bitsDecoded=this.bitsDecoded;var processingFlags=this.processingFlags;var processedMask=1;var firstMagnitudeBitMask=2;var oneRowDown=width;var twoRowsDown=width*2;var threeRowsDown=width*3;var iNext;for(var i0=0;i0<height;i0=iNext){iNext=Math.min(i0+4,height);var indexBase=i0*width;var checkAllEmpty=i0+3<height;for(var j=0;j<width;j++){var index0=indexBase+j;var allEmpty=checkAllEmpty&&processingFlags[index0]===0&&processingFlags[index0+oneRowDown]===0&&processingFlags[index0+twoRowsDown]===0&&processingFlags[index0+threeRowsDown]===0&&neighborsSignificance[index0]===0&&neighborsSignificance[index0+oneRowDown]===0&&neighborsSignificance[index0+twoRowsDown]===0&&neighborsSignificance[index0+threeRowsDown]===0;var i1=0,index=index0;var i=i0,sign;if(allEmpty){var hasSignificantCoefficent=decoder.readBit(contexts,RUNLENGTH_CONTEXT);if(!hasSignificantCoefficent){bitsDecoded[index0]++;bitsDecoded[index0+oneRowDown]++;bitsDecoded[index0+twoRowsDown]++;bitsDecoded[index0+threeRowsDown]++;continue}i1=decoder.readBit(contexts,UNIFORM_CONTEXT)<<1|decoder.readBit(contexts,UNIFORM_CONTEXT);if(i1!==0){i=i0+i1;index+=i1*width}sign=this.decodeSignBit(i,j,index);coefficentsSign[index]=sign

coefficentsMagnitude[index]=1;this.setNeighborsSignificance(i,j,index);processingFlags[index]|=firstMagnitudeBitMask;index=index0;for(var i2=i0;i2<=i;i2++,index+=width){bitsDecoded[index]++}i1++}for(i=i0+i1;i<iNext;i++,index+=width){if(coefficentsMagnitude[index]||(processingFlags[index]&processedMask)!==0){continue}var contextLabel=labels[neighborsSignificance[index]];var decision=decoder.readBit(contexts,contextLabel);if(decision===1){sign=this.decodeSignBit(i,j,index);coefficentsSign[index]=sign;coefficentsMagnitude[index]=1;this.setNeighborsSignificance(i,j,index);processingFlags[index]|=firstMagnitudeBitMask}bitsDecoded[index]++}}}},checkSegmentationSymbol
function BitModel_checkSegmentationSymbol(){var decoder=this.decoder;var contexts=this.contexts;var symbol=decoder.readBit(contexts,UNIFORM_CONTEXT)<<3|decoder.readBit(contexts,UNIFORM_CONTEXT)<<2|decoder.readBit(contexts,UNIFORM_CONTEXT)<<1|decoder.readBit(contexts,UNIFORM_CONTEXT);if(symbol!==10){throw new Error("JPX Error: Invalid segmentation symbol")}}};return BitModel}();var Transform=function TransformClosure(){function Transform(){}Transform.prototype.calculate=function transformCalculate(subbands,u0,v0){var ll=subbands[0];for(var i=1,ii=subbands.length;i<ii;i++){ll=this.iterate(ll,subbands[i],u0,v0)}return ll};Transform.prototype.extend=function extend(buffer,offset,size){var i1=offset-1,j1=offset+1;var i2=offset+size-2,j2=offset+size;buffer[i1--]=buffer[j1++];buffer[j2++]=buffer[i2--];buffer[i1--]=buffer[j1++];buffer[j2++]=buffer[i2--];buffer[i1--]=buffer[j1++];buffer[j2++]=buffer[i2--];buffer[i1]=buffer[j1];buffer[j2]=buffer[i2]};Transform.prototype.iterate=function Transform_iterate(ll,hl_lh_hh,u0,v0){var llWidth=ll.width,llHeight=ll.height,llItems=ll.items;var width=hl_lh_hh.width;var height=hl_lh_hh.height;var items=hl_lh_hh.items;var i,j,k,l,u,v;for(k=0,i=0;i<llHeight;i++){l=i*2*width;for(j=0;j<llWidth;j++,k++,l+=2){items[l]=llItems[k]}}llItems=ll.items=null;var bufferPadding=4;var rowBuffer=new Float32Array(width+2*bufferPadding);if(width===1){if((u0&1)!==0){for(v=0,k=0;v<height;v++,k+=width){items[k]*=.5}}}else{for(v=0,k=0;v<height;v++,k+=width){rowBuffer.set(items.subarray(k,k+width),bufferPadding);this.extend(rowBuffer,bufferPadding,width);this.filter(rowBuffer,bufferPadding,width);items.set(rowBuffer.subarray(bufferPadding,bufferPadding+width),k)}}var numBuffers=16;var colBuffers=[];for(i=0;i<numBuffers;i++){colBuffers.push(new Float32Array(height+2*bufferPadding))}var b,currentBuffer=0;ll=bufferPadding+height;if(height===1){if((v0&1)!==0){for(u=0;u<width;u++){items[u]*=.5}}}else{for(u=0;u<width;u++){if(currentBuffer===0){numBuffers=Math.min(width-u,numBuffers);for(k=u,l=bufferPadding;l<ll;k+=width,l++){for(b=0;b<numBuffers;b++){colBuffers[b][l]=items[k+b]}}currentBuffer=numBuffers}currentBuffer--;var buffer=colBuffers[currentBuffer];this.extend(buffer,bufferPadding,height);this.filter(buffer,bufferPadding,height);if(currentBuffer===0){k=u-numBuffers+1;for(l=bufferPadding;l<ll;k+=width,l++){for(b=0;b<numBuffers;b++){items[k+b]=colBuffers[b][l]}}}}}return{width:width,height:height,items:items}};return Transform}();var IrreversibleTransform=function IrreversibleTransformClosure(){function IrreversibleTransform(){Transform.call(this)}IrreversibleTransform.prototype=Object.create(Transform.prototype);IrreversibleTransform.prototype.filter=function irreversibleTransformFilter(x,offset,length){var len=length>>1;offset=offset|0;var j,n,current,next;var alpha=-1.586134342059924;var beta=-.052980118572961;var gamma=.882911075530934;var delta=.443506852043971;var K=1.230174104914001;var K_=1/K;j=offset-3;for(n=len+4;n--;j+=2){x[j]*=K_}j=offset-2;current=delta*x[j-1];for(n=len+3;n--;j+=2){next=delta*x[j+1];x[j]=K*x[j]-current-next;if(n--){j+=2;current=delta*x[j+1];x[j]=K*x[j]-current-next}else{break}}j=offset-1;current=gamma*x[j-1];for(n=len+2;n--;j+=2){next=gamma*x[j+1];x[j]-=current+next;if(n--){j+=2;current=gamma*x[j+1];x[j]-=current+next}else{break}}j=offset;current=beta*x[j-1];for(n=len+1;n--;j+=2){next=beta*x[j+1];x[j]-=current+next;if(n--){j+=2;current=beta*x[j+1];x[j]-=current+next}else{break}}if(len!==0){j=offset+1;current=alpha*x[j-1];for(n=len;n--;j+=2){next=alpha*x[j+1];x[j]-=current+next;if(n--){j+=2;current=alpha*x[j+1];x[j]-=current+next}else{break}}}};return IrreversibleTransform}();var ReversibleTransform=function ReversibleTransformClosure(){function ReversibleTransform(){Transform.call(this)}ReversibleTransform.prototype=Object.create(Transform.prototype);ReversibleTransform.prototype.filter=function reversibleTransformFilter(x,offset,length){var len=length>>1;offset=offset|0;var j,n;for(j=offset,n=len+1;n--;j+=2){x[j]-=x[j-1]+x[j+1]+2>>2}for(j=offset+1,n=len;n--;j+=2){x[j]+=x[j-1]+x[j+1]>>1}};return ReversibleTransform}();return JpxImage}();"use strict";var ArithmeticDecoder=function ArithmeticDecoderClosure(){var QeTable=[{qe:22017,nmps:1,nlps:1,switchFlag:1},{qe:13313,nmps:2,nlps:6,switchFlag:0},{qe:6145,nmps:3,nlps:9,switchFlag:0},{qe:2753,nmps:4,nlps:12,switchFlag:0},{qe:1313,nmps:5,nlps:29,switchFlag:0},{qe:545,nmps:38,nlps:33,switchFlag:0},{qe:22017,nmps:7,nlps:6,switchFlag:1},{qe:21505,nmps:8,nlps:14,switchFlag:0},{qe:18433,nmps:9,nlps:14,switchFlag:0},{qe:14337,nmps:10,nlps:14,switchFlag:0},{qe:12289,nmps:11,nlps:17,switchFlag:0},{qe:9217,nmps:12,nlps:18,switchFlag:0},{qe:7169,nmps:13,nlps:20,switchFlag:0},{qe:5633,nmps:29,nlps:21,switchFlag:0},{qe:22017,nmps:15,nlps:14,switchFlag:1},{qe:21505,nmps:16,nlps:14,switchFlag:0},{qe:20737,nmps:17,nlps:15,switchFlag:0},{qe:18433,nmps:18,nlps:16,switchFlag:0},{qe:14337,nmps:19,nlps:17,switchFlag:0},{qe:13313,nmps:20,nlps:18,switchFlag:0},{qe:12289,nmps:21,nlps:19,switchFlag:0},{qe:10241,nmps:22,nlps:19,switchFlag:0},{qe:9217,nmps:23,nlps:20,switchFlag:0},{qe:8705,nmps:24,nlps:21,switchFlag:0},{qe:7169,nmps:25,nlps:22,switchFlag:0},{qe:6145,nmps:26,nlps:23,switchFlag:0},{qe:5633,nmps:27,nlps:24,switchFlag:0},{qe:5121,nmps:28,nlps:25,switchFlag:0},{qe:4609,nmps:29,nlps:26,switchFlag:0},{qe:4353,nmps:30,nlps:27,switchFlag:0},{qe:2753,nmps:31,nlps:28,switchFlag:0},{qe:2497,nmps:32,nlps:29,switchFlag:0},{qe:2209,nmps:33,nlps:30,switchFlag:0},{qe:1313,nmps:34,nlps:31,switchFlag:0},{qe:1089,nmps:35,nlps:32,switchFlag:0},{qe:673,nmps:36,nlps:33,switchFlag:0},{qe:545,nmps:37,nlps:34,switchFlag:0},{qe:321,nmps:38,nlps:35,switchFlag:0},{qe:273,nmps:39,nlps:36,switchFlag:0},{qe:133,nmps:40,nlps:37,switchFlag:0},{qe:73,nmps:41,nlps:38,switchFlag:0},{qe:37,nmps:42,nlps:39,switchFlag:0},{qe:21,nmps:43,nlps:40,switchFlag:0},{qe:9,nmps:44,nlps:41,switchFlag:0},{qe:5,nmps:45,nlps:42,switchFlag:0},{qe:1,nmps:45,nlps:43,switchFlag:0},{qe:22017,nmps:46,nlps:46,switchFlag:0}];function ArithmeticDecoder(data,start,end){this.data=data;this.bp=start;this.dataEnd=end;this.chigh=data[start];this.clow=0;this.byteIn();this.chigh=this.chigh<<7&65535|this.clow>>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}ArithmeticDecoder.prototype={byteIn:function ArithmeticDecoder_byteIn(){var data=this.data;var bp=this.bp;if(data[bp]===255){var b1=data[bp+1];if(b1>143){this.clow+=65280;this.ct=8}else{bp++;this.clow+=data[bp]<<9;this.ct=7;this.bp=bp}}else{bp++;this.clow+=bp<this.dataEnd?data[bp]<<8:65280;this.ct=8;this.bp=bp}if(this.clow>65535){this.chigh+=this.clow>>16;this.clow&=65535}},readBit:function ArithmeticDecoder_readBit(contexts,pos){var cx_index=contexts[pos]>>1,cx_mps=contexts[pos]&1;var qeTableIcx=QeTable[cx_index];var qeIcx=qeTableIcx.qe;var d;var a=this.a-qeIcx;if(this.chigh<qeIcx){if(a<qeIcx){a=qeIcx;d=cx_mps;cx_index=qeTableIcx.nmps}else{a=qeIcx;d=1^cx_mps;if(qeTableIcx.switchFlag===1){cx_mps=d}cx_index=qeTableIcx.nlps}}else{this.chigh-=qeIcx;if((a&32768)!==0){this.a=a;return cx_mps}if(a<qeIcx){d=1^cx_mps;if(qeTableIcx.switchFlag===1){cx_mps=d}cx_index=qeTableIcx.nlps}else{d=cx_mps;cx_index=qeTableIcx.nmps}}do{if(this.ct===0){this.byteIn()}a<<=1;this.chigh=this.chigh<<1&65535|this.clow>>15&1;this.clow=this.clow<<1&65535;this.ct--}while((a&32768)===0);this.a=a;contexts[pos]=cx_index<<1|cx_mps;return d}};return ArithmeticDecoder}();"use strict";var globalScope=typeof window==="undefined"?this:window;var isWorker=typeof window==="undefined";var FONT_IDENTITY_MATRIX=[.001,0,0,.001,0,0];var TextRenderingMode={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4};var ImageKind={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3};var AnnotationType={WIDGET:1,TEXT:2,LINK:3};var StreamType={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9};var FontType={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10};if(!globalScope.PDFJS){globalScope.PDFJS={}}globalScope.PDFJS.pdfBug=false;PDFJS.VERBOSITY_LEVELS={errors:0,warnings:1,infos:5};var OPS=PDFJS.OPS={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91};function info(msg){if(PDFJS.verbosity>=PDFJS.VERBOSITY_LEVELS.infos){console.log("Info: "+msg)}}function warn(msg){if(PDFJS.verbosity>=PDFJS.VERBOSITY_LEVELS.warnings){console.log("Warning: "+msg)}}function error(msg){if(arguments.length>1){var logArguments=["Error:"];logArguments.push.apply(logArguments,arguments);console.log.apply(console,logArguments);msg=[].join.call(arguments," ")}else{console.log("Error: "+msg)}console.log(backtrace());UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);throw new Error(msg)}function backtrace(){try{throw new Error}catch(e){return e.stack?e.stack.split("\n").slice(2).join("\n"):""}}function assert(cond,msg){if(!cond){error(msg)}}var UNSUPPORTED_FEATURES=PDFJS.UNSUPPORTED_FEATURES={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"};var UnsupportedManager=PDFJS.UnsupportedManager=function UnsupportedManagerClosure(){var listeners=[];return{listen:function(cb){listeners.push(cb)},notify:function(featureId){warn('Unsupported feature "'+featureId+'"');for(var i=0,ii=listeners.length;i<ii;i++){listeners[i](featureId)}}}}();function combineUrl(baseUrl,url){if(!url){return baseUrl}if(/^[a-z][a-z0-9+\-.]*:/i.test(url)){return url}var i;if(url.charAt(0)==="/"){i=baseUrl.indexOf("://");if(url.charAt(1)==="/"){++i}else{i=baseUrl.indexOf("/",i+3)}return baseUrl.substring(0,i)+url}else{var pathLength=baseUrl.length;i=baseUrl.lastIndexOf("#");pathLength=i>=0?i:pathLength;i=baseUrl.lastIndexOf("?",pathLength);pathLength=i>=0?i:pathLength;var prefixLength=baseUrl.lastIndexOf("/",pathLength);return baseUrl.substring(0,prefixLength+1)+url}}function isValidUrl(url,allowRelative){if(!url){return false}var protocol=/^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);if(!protocol){return allowRelative}protocol=protocol[0].toLowerCase();switch(protocol){case"http":case"https":case"ftp":case"mailto":case"tel":return true;default:return false}}PDFJS.isValidUrl=isValidUrl;function shadow(obj,prop,value){Object.defineProperty(obj,prop,{value:value,enumerable:true,configurable:true,writable:false});return value}PDFJS.shadow=shadow;var PasswordResponses=PDFJS.PasswordResponses={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};var PasswordException=function PasswordExceptionClosure(){function PasswordException(msg,code){this.name="PasswordException";this.message=msg;this.code=code}PasswordException.prototype=new Error;PasswordException.constructor=PasswordException;return PasswordException}();PDFJS.PasswordException=PasswordException;var UnknownErrorException=function UnknownErrorExceptionClosure(){function UnknownErrorException(msg,details){this.name="UnknownErrorException";this.message=msg;this.details=details}UnknownErrorException.prototype=new Error;UnknownErrorException.constructor=UnknownErrorException;return UnknownErrorException}();PDFJS.UnknownErrorException=UnknownErrorException;var InvalidPDFException=function InvalidPDFExceptionClosure(){function InvalidPDFException(msg){this.name="InvalidPDFException";this.message=msg}InvalidPDFException.prototype=new Error;InvalidPDFException.constructor=InvalidPDFException;return InvalidPDFException}();PDFJS.InvalidPDFException=InvalidPDFException;var MissingPDFException=function MissingPDFExceptionClosure(){function MissingPDFException(msg){this.name="MissingPDFException";this.message=msg}MissingPDFException.prototype=new Error;MissingPDFException.constructor=MissingPDFException;return MissingPDFException}();PDFJS.MissingPDFException=MissingPDFException;var UnexpectedResponseException=function UnexpectedResponseExceptionClosure(){function UnexpectedResponseException(msg,status){this.name="UnexpectedResponseException";this.message=msg;this.status=status}UnexpectedResponseException.prototype=new Error;UnexpectedResponseException.constructor=UnexpectedResponseException;return UnexpectedResponseException}();PDFJS.UnexpectedResponseException=UnexpectedResponseException;var NotImplementedException=function NotImplementedExceptionClosure(){function NotImplementedException(msg){this.message=msg}NotImplementedException.prototype=new Error;NotImplementedException.prototype.name="NotImplementedException";NotImplementedException.constructor=NotImplementedException;return NotImplementedException}();var MissingDataException=function MissingDataExceptionClosure(){function MissingDataException(begin,end){this.begin=begin;this.end=end;this.message="Missing data ["+begin+", "+end+")"}MissingDataException.prototype=new Error;MissingDataException.prototype.name="MissingDataException";MissingDataException.constructor=MissingDataException;return MissingDataException}();var XRefParseException=function XRefParseExceptionClosure(){function XRefParseException(msg){this.message=msg}XRefParseException.prototype=new Error;XRefParseException.prototype.name="XRefParseException";XRefParseException.constructor=XRefParseException;return XRefParseException}();function bytesToString(bytes){assert(bytes!==null&&typeof bytes==="object"&&bytes.length!==undefined,"Invalid argument for bytesToString");var length=bytes.length;var MAX_ARGUMENT_COUNT=8192;if(length<MAX_ARGUMENT_COUNT){return String.fromCharCode.apply(null,bytes)}var strBuf=[];for(var i=0;i<length;i+=MAX_ARGUMENT_COUNT){var chunkEnd=Math.min(i+MAX_ARGUMENT_COUNT,length);var chunk=bytes.subarray(i,chunkEnd);strBuf.push(String.fromCharCode.apply(null,chunk))}return strBuf.join("")}function stringToBytes(str){assert(typeof str==="string","Invalid argument for stringToBytes");var length=str.length;var bytes=new Uint8Array(length);for(var i=0;i<length;++i){bytes[i]=str.charCodeAt(i)&255}return bytes}function string32(value){return String.fromCharCode(value>>24&255,value>>16&255,value>>8&255,value&255)}function log2(x){var n=1,i=0;while(x>n){n<<=1;i++}return i}function readInt8(data,start){return data[start]<<24>>24}function readUint16(data,offset){return data[offset]<<8|data[offset+1]}function readUint32(data,offset){return(data[offset]<<24|data[offset+1]<<16|data[offset+2]<<8|data[offset+3])>>>0}function isLittleEndian(){var buffer8=new Uint8Array(2);buffer8[0]=1;var buffer16=new Uint16Array(buffer8.buffer);return buffer16[0]===1}Object.defineProperty(PDFJS,"isLittleEndian",{configurable:true,get:function PDFJS_isLittleEndian(){return shadow(PDFJS,"isLittleEndian",isLittleEndian())}});function hasCanvasTypedArrays(){var canvas=document.createElement("canvas");canvas.width=canvas.height=1;var ctx=canvas.getContext("2d");var imageData=ctx.createImageData(1,1);return typeof imageData.data.buffer!=="undefined"}Object.defineProperty(PDFJS,"hasCanvasTypedArrays",{configurable:true,get:function PDFJS_hasCanvasTypedArrays(){return shadow(PDFJS,"hasCanvasTypedArrays",hasCanvasTypedArrays())}});var Uint32ArrayView=function Uint32ArrayViewClosure(){function Uint32ArrayView(buffer,length){this.buffer=buffer;this.byteLength=buffer.length;this.length=length===undefined?this.byteLength>>2:length;ensureUint32ArrayViewProps(this.length)}Uint32ArrayView.prototype=Object.create(null);var uint32ArrayViewSetters=0;function createUint32ArrayProp(index){return{get:function(){var buffer=this.buffer,offset=index<<2;return(buffer[offset]|buffer[offset+1]<<8|buffer[offset+2]<<16|buffer[offset+3]<<24)>>>0},set:function(value){var buffer=this.buffer,offset=index<<2;buffer[offset]=value&255;buffer[offset+1]=value>>8&255;buffer[offset+2]=value>>16&255;buffer[offset+3]=value>>>24&255}}}function ensureUint32ArrayViewProps(length){while(uint32ArrayViewSetters<length){Object.defineProperty(Uint32ArrayView.prototype,uint32ArrayViewSetters,createUint32ArrayProp(uint32ArrayViewSetters));uint32ArrayViewSetters++}}return Uint32ArrayView}();var IDENTITY_MATRIX=[1,0,0,1,0,0];var Util=PDFJS.Util=function UtilClosure(){function Util(){}var rgbBuf=["rgb(",0,",",0,",",0,")"];Util.makeCssRgb=function Util_makeCssRgb(r,g,b){rgbBuf[1]=r;rgbBuf[3]=g;rgbBuf[5]=b;return rgbBuf.join("")};Util.transform=function Util_transform(m1,m2){return[m1[0]*m2[0]+m1[2]*m2[1],m1[1]*m2[0]+m1[3]*m2[1],m1[0]*m2[2]+m1[2]*m2[3],m1[1]*m2[2]+m1[3]*m2[3],m1[0]*m2[4]+m1[2]*m2[5]+m1[4],m1[1]*m2[4]+m1[3]*m2[5]+m1[5]]};Util.applyTransform=function Util_applyTransform(p,m){var xt=p[0]*m[0]+p[1]*m[2]+m[4];var yt=p[0]*m[1]+p[1]*m[3]+m[5];return[xt,yt]};Util.applyInverseTransform=function Util_applyInverseTransform(p,m){var d=m[0]*m[3]-m[1]*m[2];var xt=(p[0]*m[3]-p[1]*m[2]+m[2]*m[5]-m[4]*m[3])/d;var yt=(-p[0]*m[1]+p[1]*m[0]+m[4]*m[1]-m[5]*m[0])/d;return[xt,yt]};Util.getAxialAlignedBoundingBox=function Util_getAxialAlignedBoundingBox(r,m){var p1=Util.applyTransform(r,m);var p2=Util.applyTransform(r.slice(2,4),m);var p3=Util.applyTransform([r[0],r[3]],m);var p4=Util.applyTransform([r[2],r[1]],m);return[Math.min(p1[0],p2[0],p3[0],p4[0]),Math.min(p1[1],p2[1],p3[1],p4[1]),Math.max(p1[0],p2[0],p3[0],p4[0]),Math.max(p1[1],p2[1],p3[1],p4[1])]};Util.inverseTransform=function Util_inverseTransform(m){var d=m[0]*m[3]-m[1]*m[2];return[m[3]/d,-m[1]/d,-m[2]/d,m[0]/d,(m[2]*m[5]-m[4]*m[3])/d,(m[4]*m[1]-m[5]*m[0])/d]};Util.apply3dTransform=function Util_apply3dTransform(m,v){return[m[0]*v[0]+m[1]*v[1]+m[2]*v[2],m[3]*v[0]+m[4]*v[1]+m[5]*v[2],m[6]*v[0]+m[7]*v[1]+m[8]*v[2]]};Util.singularValueDecompose2dScale=function Util_singularValueDecompose2dScale(m){var transpose=[m[0],m[2],m[1],m[3]];var a=m[0]*transpose[0]+m[1]*transpose[2];var b=m[0]*transpose[1]+m[1]*transpose[3];var c=m[2]*transpose[0]+m[3]*transpose[2];var d=m[2]*transpose[1]+m[3]*transpose[3];var first=(a+d)/2;var second=Math.sqrt((a+d)*(a+d)-4*(a*d-c*b))/2;var sx=first+second||1;var sy=first-second||1;return[Math.sqrt(sx),Math.sqrt(sy)]};Util.normalizeRect=function Util_normalizeRect(rect){var r=rect.slice(0);if(rect[0]>rect[2]){r[0]=rect[2];r[2]=rect[0]}if(rect[1]>rect[3]){r[1]=rect[3];r[3]=rect[1]}return r};Util.intersect=function Util_intersect(rect1,rect2){function compare(a,b){return a-b}var orderedX=[rect1[0],rect1[2],rect2[0],rect2[2]].sort(compare),orderedY=[rect1[1],rect1[3],rect2[1],rect2[3]].sort(compare),result=[];rect1=Util.normalizeRect(rect1);rect2=Util.normalizeRect(rect2);if(orderedX[0]===rect1[0]&&orderedX[1]===rect2[0]||orderedX[0]===rect2[0]&&orderedX[1]===rect1[0]){result[0]=orderedX[1];result[2]=orderedX[2]}else{return false}if(orderedY[0]===rect1[1]&&orderedY[1]===rect2[1]||orderedY[0]===rect2[1]&&orderedY[1]===rect1[1]){result[1]=orderedY[1];result[3]=orderedY[2]}else{return false}return result};Util.sign=function Util_sign(num){return num<0?-1:1};Util.appendToArray=function Util_appendToArray(arr1,arr2){Array.prototype.push.apply(arr1,arr2)};Util.prependToArray=function Util_prependToArray(arr1,arr2){Array.prototype.unshift.apply(arr1,arr2)};Util.extendObj=function extendObj(obj1,obj2){for(var key in obj2){obj1[key]=obj2[key]}};Util.getInheritableProperty=function Util_getInheritableProperty(dict,name){while(dict&&!dict.has(name)){dict=dict.get("Parent")}if(!dict){return null}return dict.get(name)};Util.inherit=function Util_inherit(sub,base,prototype){sub.prototype=Object.create(base.prototype);sub.prototype.constructor=sub;for(var prop in prototype){sub.prototype[prop]=prototype[prop]}};Util.loadScript=function Util_loadScript(src,callback){var script=document.createElement("script");var loaded=false;script.setAttribute("src",src);if(callback){script.onload=function(){if(!loaded){callback()}loaded=true}}document.getElementsByTagName("head")[0].appendChild(script)};return Util}();var PageViewport=PDFJS.PageViewport=function PageViewportClosure(){function PageViewport(viewBox,scale,rotation,offsetX,offsetY,dontFlip){this.viewBox=viewBox;this.scale=scale;this.rotation=rotation;this.offsetX=offsetX;this.offsetY=offsetY;var centerX=(viewBox[2]+viewBox[0])/2;var centerY=(viewBox[3]+viewBox[1])/2;var rotateA,rotateB,rotateC,rotateD;rotation=rotation%360;rotation=rotation<0?rotation+360:rotation;switch(rotation){case 180:rotateA=-1;rotateB=0;rotateC=0;rotateD=1;break;case 90:rotateA=0;rotateB=1;rotateC=1;rotateD=0;break;case 270:rotateA=0;rotateB=-1;rotateC=-1;rotateD=0;break;default:rotateA=1;rotateB=0;rotateC=0;rotateD=-1;break}if(dontFlip){rotateC=-rotateC;rotateD=-rotateD}var offsetCanvasX,offsetCanvasY;var width,height;if(rotateA===0){offsetCanvasX=Math.abs(centerY-viewBox[1])*scale+offsetX;offsetCanvasY=Math.abs(centerX-viewBox[0])*scale+offsetY;width=Math.abs(viewBox[3]-viewBox[1])*scale;height=Math.abs(viewBox[2]-viewBox[0])*scale}else{offsetCanvasX=Math.abs(centerX-viewBox[0])*scale+offsetX;offsetCanvasY=Math.abs(centerY-viewBox[1])*scale+offsetY;width=Math.abs(viewBox[2]-viewBox[0])*scale;height=Math.abs(viewBox[3]-viewBox[1])*scale}this.transform=[rotateA*scale,rotateB*scale,rotateC*scale,rotateD*scale,offsetCanvasX-rotateA*scale*centerX-rotateC*scale*centerY,offsetCanvasY-rotateB*scale*centerX-rotateD*scale*centerY];this.width=width;this.height=height;this.fontScale=scale}PageViewport.prototype={clone:function PageViewPort_clone(args){args=args||{};var scale="scale"in args?args.scale:this.scale;var rotation="rotation"in args?args.rotation:this.rotation;return new PageViewport(this.viewBox.slice(),scale,rotation,this.offsetX,this.offsetY,args.dontFlip)},convertToViewportPoint:function PageViewport_convertToViewportPoint(x,y){return Util.applyTransform([x,y],this.transform)},convertToViewportRectangle:function PageViewport_convertToViewportRectangle(rect){var tl=Util.applyTransform([rect[0],rect[1]],this.transform);var br=Util.applyTransform([rect[2],rect[3]],this.transform);return[tl[0],tl[1],br[0],br[1]]},convertToPdfPoint:function PageViewport_convertToPdfPoint(x,y){return Util.applyInverseTransform([x,y],this.transform)}};return PageViewport}();var PDFStringTranslateTable=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(str){var i,n=str.length,strBuf=[];if(str[0]==="þ"&&str[1]==="ÿ"){for(i=2;i<n;i+=2){strBuf.push(String.fromCharCode(str.charCodeAt(i)<<8|str.charCodeAt(i+1)))}}else{for(i=0;i<n;++i){var code=PDFStringTranslateTable[str.charCodeAt(i)];strBuf.push(code?String.fromCharCode(code):str.charAt(i))}}return strBuf.join("")}function stringToUTF8String(str){return decodeURIComponent(escape(str))}function isEmptyObj(obj){for(var key in obj){return false}return true}function isBool(v){return typeof v==="boolean"}function isInt(v){return typeof v==="number"&&(v|0)===v}function isNum(v){return typeof v==="number"}function isString(v){return typeof v==="string"}function isNull(v){return v===null}function isName(v){return v instanceof Name}function isCmd(v,cmd){return v instanceof Cmd&&(cmd===undefined||v.cmd===cmd)}function isDict(v,type){if(!(v instanceof Dict)){return false}if(!type){return true}var dictType=v.get("Type");return isName(dictType)&&dictType.name===type}function isArray(v){return v instanceof Array}function isStream(v){return typeof v==="object"&&v!==null&&v.getBytes!==undefined}function isArrayBuffer(v){return typeof v==="object"&&v!==null&&v.byteLength!==undefined}function isRef(v){return v instanceof Ref}function createPromiseCapability(){var capability={};capability.promise=new Promise(function(resolve,reject){capability.resolve=resolve;capability.reject=reject});return capability}PDFJS.createPromiseCapability=createPromiseCapability;(function PromiseClosure(){if(globalScope.Promise){if(typeof globalScope.Promise.all!=="function"){globalScope.Promise.all=function(iterable){var count=0,results=[],resolve,reject;var promise=new globalScope.Promise(function(resolve_,reject_){resolve=resolve_;reject=reject_});iterable.forEach(function(p,i){count++;p.then(function(result){results[i]=result;count--;if(count===0){resolve(results)}},reject)});if(count===0){resolve(results)}return promise}}if(typeof globalScope.Promise.resolve!=="function"){globalScope.Promise.resolve=function(value){return new globalScope.Promise(function(resolve){resolve(value)})}}if(typeof globalScope.Promise.reject!=="function"){globalScope.Promise.reject=function(reason){return new globalScope.Promise(function(resolve,reject){reject(reason)})}}if(typeof globalScope.Promise.prototype.catch!=="function"){globalScope.Promise.prototype.catch=function(onReject){return globalScope.Promise.prototype.then(undefined,onReject)}}return}var STATUS_PENDING=0;var STATUS_RESOLVED=1;var STATUS_REJECTED=2;var REJECTION_TIMEOUT=500;var HandlerManager={handlers:[],running:false,unhandledRejections:[],pendingRejectionCheck:false,scheduleHandlers:function scheduleHandlers(promise){if(promise._status===STATUS_PENDING){return}this.handlers=this.handlers.concat(promise._handlers);promise._handlers=[];if(this.running){return}this.running=true;setTimeout(this.runHandlers.bind(this),0)},runHandlers:function runHandlers(){var RUN_TIMEOUT=1;var timeoutAt=Date.now()+RUN_TIMEOUT;while(this.handlers.length>0){var handler=this.handlers.shift();var nextStatus=handler.thisPromise._status;var nextValue=handler.thisPromise._value;try{if(nextStatus===STATUS_RESOLVED){if(typeof handler.onResolve==="function"){nextValue=handler.onResolve(nextValue)}}else if(typeof handler.onReject==="function"){nextValue=handler.onReject(nextValue);nextStatus=STATUS_RESOLVED;if(handler.thisPromise._unhandledRejection){this.removeUnhandeledRejection(handler.thisPromise)}}}catch(ex){nextStatus=STATUS_REJECTED;nextValue=ex}handler.nextPromise._updateStatus(nextStatus,nextValue);if(Date.now()>=timeoutAt){break}}if(this.handlers.length>0){setTimeout(this.runHandlers.bind(this),0);return}this.running=false},addUnhandledRejection:function addUnhandledRejection(promise){this.unhandledRejections.push({promise:promise,time:Date.now()});this.scheduleRejectionCheck()},removeUnhandeledRejection:function removeUnhandeledRejection(promise){promise._unhandledRejection=false;for(var i=0;i<this.unhandledRejections.length;i++){if(this.unhandledRejections[i].promise===promise){this.unhandledRejections.splice(i);i--}}},scheduleRejectionCheck:function scheduleRejectionCheck(){if(this.pendingRejectionCheck){return}this.pendingRejectionCheck=true;setTimeout(function rejectionCheck(){this.pendingRejectionCheck=false;var now=Date.now();for(var i=0;i<this.unhandledRejections.length;i++){if(now-this.unhandledRejections[i].time>REJECTION_TIMEOUT){var unhandled=this.unhandledRejections[i].promise._value;var msg="Unhandled rejection: "+unhandled;if(unhandled.stack){msg+="\n"+unhandled.stack}warn(msg);this.unhandledRejections.splice(i);i--}}if(this.unhandledRejections.length){this.scheduleRejectionCheck()}}.bind(this),REJECTION_TIMEOUT)}};function Promise(resolver){this._status=STATUS_PENDING;this._handlers=[];try{resolver.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(e){this._reject(e)}}Promise.all=function Promise_all(promises){var resolveAll,rejectAll;var deferred=new Promise(function(resolve,reject){resolveAll=resolve;rejectAll=reject});var unresolved=promises.length;var results=[];if(unresolved===0){resolveAll(results);return deferred}function reject(reason){if(deferred._status===STATUS_REJECTED){return}results=[];rejectAll(reason)}for(var i=0,ii=promises.length;i<ii;++i){var promise=promises[i];var resolve=function(i){return function(value){if(deferred._status===STATUS_REJECTED){return}results[i]=value;unresolved--;if(unresolved===0){resolveAll(results)}}}(i);if(Promise.isPromise(promise)){promise.then(resolve,reject)}else{resolve(promise)}}return deferred};Promise.isPromise=function Promise_isPromise(value){return value&&typeof value.then==="function"};Promise.resolve=function Promise_resolve(value){return new Promise(function(resolve){resolve(value)})};Promise.reject=function Promise_reject(reason){return new Promise(function(resolve,reject){reject(reason)})};Promise.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function Promise__updateStatus(status,value){if(this._status===STATUS_RESOLVED||this._status===STATUS_REJECTED){return}if(status===STATUS_RESOLVED&&Promise.isPromise(value)){value.then(this._updateStatus.bind(this,STATUS_RESOLVED),this._updateStatus.bind(this,STATUS_REJECTED));return}this._status=status;this._value=value;if(status===STATUS_REJECTED&&this._handlers.length===0){this._unhandledRejection=true;HandlerManager.addUnhandledRejection(this)}HandlerManager.scheduleHandlers(this)},_resolve:function Promise_resolve(value){this._updateStatus(STATUS_RESOLVED,value)},_reject:function Promise_reject(reason){this._updateStatus(STATUS_REJECTED,reason)},then:function Promise_then(onResolve,onReject){var nextPromise=new Promise(function(resolve,reject){this.resolve=resolve;this.reject=reject});this._handlers.push({thisPromise:this,onResolve:onResolve,onReject:onReject,nextPromise:nextPromise});HandlerManager.scheduleHandlers(this);return nextPromise},catch:function Promise_catch(onReject){return this.then(undefined,onReject)}};globalScope.Promise=Promise})();var StatTimer=function StatTimerClosure(){function rpad(str,pad,length){while(str.length<length){str+=pad}return str}function StatTimer(){this.started={};this.times=[];this.enabled=true}StatTimer.prototype={time:function StatTimer_time(name){if(!this.enabled){return}if(name in this.started){warn("Timer is already running for "+name)}this.started[name]=Date.now()},

timeEnd:function StatTimer_timeEnd(name){if(!this.enabled){return}if(!(name in this.started)){warn("Timer has not been started for "+name)}this.times.push({name:name,start:this.started[name],end:Date.now()});delete this.started[name]},toString:function StatTimer_toString(){var i,ii;var times=this.times;var out="";var longest=0;for(i=0,ii=times.length;i<ii;++i){var name=times[i]["name"];if(name.length>longest){longest=name.length}}for(i=0,ii=times.length;i<ii;++i){var span=times[i];var duration=span.end-span.start;out+=rpad(span["name"]," ",longest)+" "+duration+"ms\n"}return out}};return StatTimer}();PDFJS.createBlob=function createBlob(data,contentType){if(typeof Blob!=="undefined"){return new Blob([data],{type:contentType})}var bb=new MozBlobBuilder;bb.append(data);return bb.getBlob(contentType)};PDFJS.createObjectURL=function createObjectURLClosure(){var digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function createObjectURL(data,contentType){if(!PDFJS.disableCreateObjectURL&&typeof URL!=="undefined"&&URL.createObjectURL){var blob=PDFJS.createBlob(data,contentType);return URL.createObjectURL(blob)}var buffer="data:"+contentType+";base64,";for(var i=0,ii=data.length;i<ii;i+=3){var b1=data[i]&255;var b2=data[i+1]&255;var b3=data[i+2]&255;var d1=b1>>2,d2=(b1&3)<<4|b2>>4;var d3=i+1<ii?(b2&15)<<2|b3>>6:64;var d4=i+2<ii?b3&63:64;buffer+=digits[d1]+digits[d2]+digits[d3]+digits[d4]}return buffer}}();function MessageHandler(name,comObj){this.name=name;this.comObj=comObj;this.callbackIndex=1;this.postMessageTransfers=true;var callbacksCapabilities=this.callbacksCapabilities={};var ah=this.actionHandler={};ah["console_log"]=[function ahConsoleLog(data){console.log.apply(console,data)}];ah["console_error"]=[function ahConsoleError(data){console.error.apply(console,data)}];ah["_unsupported_feature"]=[function ah_unsupportedFeature(data){UnsupportedManager.notify(data)}];comObj.onmessage=function messageHandlerComObjOnMessage(event){var data=event.data;if(data.isReply){var callbackId=data.callbackId;if(data.callbackId in callbacksCapabilities){var callback=callbacksCapabilities[callbackId];delete callbacksCapabilities[callbackId];if("error"in data){callback.reject(data.error)}else{callback.resolve(data.data)}}else{error("Cannot resolve callback "+callbackId)}}else if(data.action in ah){var action=ah[data.action];if(data.callbackId){Promise.resolve().then(function(){return action[0].call(action[1],data.data)}).then(function(result){comObj.postMessage({isReply:true,callbackId:data.callbackId,data:result})},function(reason){comObj.postMessage({isReply:true,callbackId:data.callbackId,error:reason})})}else{action[0].call(action[1],data.data)}}else{error("Unknown action from worker: "+data.action)}}}MessageHandler.prototype={on:function messageHandlerOn(actionName,handler,scope){var ah=this.actionHandler;if(ah[actionName]){error('There is already an actionName called "'+actionName+'"')}ah[actionName]=[handler,scope]},send:function messageHandlerSend(actionName,data,transfers){var message={action:actionName,data:data};this.postMessage(message,transfers)},sendWithPromise:function messageHandlerSendWithPromise(actionName,data,transfers){var callbackId=this.callbackIndex++;var message={action:actionName,data:data,callbackId:callbackId};var capability=createPromiseCapability();this.callbacksCapabilities[callbackId]=capability;try{this.postMessage(message,transfers)}catch(e){capability.reject(e)}return capability.promise},postMessage:function(message,transfers){if(transfers&&this.postMessageTransfers){this.comObj.postMessage(message,transfers)}else{this.comObj.postMessage(message)}}};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=JpxImage}function loadJpegStream(id,imageUrl,objs){var img=new Image;img.onload=function loadJpegStream_onloadClosure(){objs.resolve(id,img)};img.onerror=function loadJpegStream_onerrorClosure(){objs.resolve(id,null);warn("Error during JPEG image loading")};img.src=imageUrl}},{}],3:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b){return 0}var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y){return-1}if(y<x){return 1}return 0}function isBuffer(b){if(global.Buffer&&typeof global.Buffer.isBuffer==="function"){return global.Buffer.isBuffer(b)}return!!(b!=null&&b._isBuffer)}var util=require("util/");var hasOwn=Object.prototype.hasOwnProperty;var pSlice=Array.prototype.slice;var functionsHaveNames=function(){return function foo(){}.name==="foo"}();function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){if(isBuffer(arrbuf)){return false}if(typeof global.ArrayBuffer!=="function"){return false}if(typeof ArrayBuffer.isView==="function"){return ArrayBuffer.isView(arrbuf)}if(!arrbuf){return false}if(arrbuf instanceof DataView){return true}if(arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer){return true}return false}var assert=module.exports=ok;var regex=/\s*function\s+([^\(\s]*)\s*/;function getName(func){if(!util.isFunction(func)){return}if(functionsHaveNames){return func.name}var str=func.toString();var match=str.match(regex);return match&&match[1]}assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=getName(stackStartFunction);var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function truncate(s,n){if(typeof s==="string"){return s.length<n?s:s.slice(0,n)}else{return s}}function inspect(something){if(functionsHaveNames||!util.isFunction(something)){return util.inspect(something)}var rawname=getName(something);var name=rawname?": "+rawname:"";return"[Function"+name+"]"}function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected,false)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(!_deepEqual(actual,expected,true)){fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)}};function _deepEqual(actual,expected,strict,memos){if(actual===expected){return true}else if(isBuffer(actual)&&isBuffer(expected)){return compare(actual,expected)===0}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if((actual===null||typeof actual!=="object")&&(expected===null||typeof expected!=="object")){return strict?actual===expected:actual==expected}else if(isView(actual)&&isView(expected)&&pToString(actual)===pToString(expected)&&!(actual instanceof Float32Array||actual instanceof Float64Array)){return compare(new Uint8Array(actual.buffer),new Uint8Array(expected.buffer))===0}else if(isBuffer(actual)!==isBuffer(expected)){return false}else{memos=memos||{actual:[],expected:[]};var actualIndex=memos.actual.indexOf(actual);if(actualIndex!==-1){if(actualIndex===memos.expected.indexOf(expected)){return true}}memos.actual.push(actual);memos.expected.push(expected);return objEquiv(actual,expected,strict,memos)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b,strict,actualVisitedObjects){if(a===null||a===undefined||b===null||b===undefined)return false;if(util.isPrimitive(a)||util.isPrimitive(b))return a===b;if(strict&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;var aIsArgs=isArguments(a);var bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b,strict)}var ka=objectKeys(a);var kb=objectKeys(b);var key,i;if(ka.length!==kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!==kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected,false)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(_deepEqual(actual,expected,true)){fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}}assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}try{if(actual instanceof expected){return true}}catch(e){}if(Error.isPrototypeOf(expected)){return false}return expected.call({},actual)===true}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if(typeof block!=="function"){throw new TypeError('"block" argument must be a function')}if(typeof expected==="string"){message=expected;expected=null}actual=_tryBlock(block);message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}var userProvidedMessage=typeof message==="string";var isUnwantedException=!shouldThrow&&util.isError(actual);var isUnexpectedException=!shouldThrow&&actual&&!expected;if(isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws(true,block,error,message)};assert.doesNotThrow=function(block,error,message){_throws(false,block,error,message)};assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"util/":87}],4:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i];revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;function placeHoldersCount(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i<l;i+=4,j+=3){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[L++]=tmp>>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;var output="";var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],5:[function(require,module,exports){},{}],6:[function(require,module,exports){"use strict";var TYPED_OK=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Int32Array!=="undefined";exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source){continue}if(typeof source!=="object"){throw new TypeError(source+"must be non-object")}for(var p in source){if(source.hasOwnProperty(p)){obj[p]=source[p]}}}return obj};exports.shrinkBuf=function(buf,size){if(buf.length===size){return buf}if(buf.subarray){return buf.subarray(0,size)}buf.length=size;return buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){var i,l,len,pos,chunk,result;len=0;for(i=0,l=chunks.length;i<l;i++){len+=chunks[i].length}result=new Uint8Array(len);pos=0;for(i=0,l=chunks.length;i<l;i++){chunk=chunks[i];result.set(chunk,pos);pos+=chunk.length}return result}};var fnUntyped={arraySet:function(dest,src,src_offs,len,dest_offs){for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){return[].concat.apply([],chunks)}};exports.setTyped=function(on){if(on){exports.Buf8=Uint8Array;exports.Buf16=Uint16Array;exports.Buf32=Int32Array;exports.assign(exports,fnTyped)}else{exports.Buf8=Array;exports.Buf16=Array;exports.Buf32=Array;exports.assign(exports,fnUntyped)}};exports.setTyped(TYPED_OK)},{}],7:[function(require,module,exports){"use strict";function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module.exports=adler32},{}],8:[function(require,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],9:[function(require,module,exports){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i<end;i++){crc=crc>>>8^t[(crc^buf[i])&255]}return crc^-1}module.exports=crc32},{}],10:[function(require,module,exports){"use strict";var utils=require("../utils/common");var trees=require("./trees");var adler32=require("./adler32");var crc32=require("./crc32");var msg=require("./messages");var Z_NO_FLUSH=0;var Z_PARTIAL_FLUSH=1;var Z_FULL_FLUSH=3;var Z_FINISH=4;var Z_BLOCK=5;var Z_OK=0;var Z_STREAM_END=1;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_BUF_ERROR=-5;var Z_DEFAULT_COMPRESSION=-1;var Z_FILTERED=1;var Z_HUFFMAN_ONLY=2;var Z_RLE=3;var Z_FIXED=4;var Z_DEFAULT_STRATEGY=0;var Z_UNKNOWN=2;var Z_DEFLATED=8;var MAX_MEM_LEVEL=9;var MAX_WBITS=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;function err(strm,errorCode){strm.msg=msg[errorCode];return errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}function flush_pending(strm){var s=strm.state;var len=s.pending;if(len>strm.avail_out){len=strm.avail_out}if(len===0){return}utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out);strm.next_out+=len;s.pending_out+=len;strm.total_out+=len;strm.avail_out-=len;s.pending-=len;if(s.pending===0){s.pending_out=0}}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last);s.block_start=s.strstart;flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255;s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size){len=size}if(len===0){return 0}strm.avail_in-=len;utils.arraySet(buf,strm.input,strm.next_in,len,start);if(strm.state.wrap===1){strm.adler=adler32(strm.adler,buf,len,start)}else if(strm.state.wrap===2){strm.adler=crc32(strm.adler,buf,len,start)}strm.next_in+=len;strm.total_in+=len;return len}function longest_match(s,cur_match){var chain_length=s.max_chain_length;var scan=s.strstart;var match;var len;var best_len=s.prev_length;var nice_match=s.nice_match;var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0;var _win=s.window;var wmask=s.w_mask;var prev=s.prev;var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match){chain_length>>=2}if(nice_match>s.lookahead){nice_match=s.lookahead}do{match=cur_match;if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue}scan+=2;match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len}return s.lookahead}function fill_window(s){var _w_size=s.w_size;var p,n,m,more,str;do{more=s.window_size-s.lookahead-s.strstart;if(s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0);s.match_start-=_w_size;s.strstart-=_w_size;s.block_start-=_w_size;n=s.hash_size;p=n;do{m=s.head[--p];s.head[p]=m>=_w_size?m-_w_size:0}while(--n);n=_w_size;p=n;do{m=s.prev[--p];s.prev[p]=m>=_w_size?m-_w_size:0}while(--n);more+=_w_size}if(s.strm.avail_in===0){break}n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more);s.lookahead+=n;if(s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert;s.ins_h=s.window[str];s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;while(s.insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;s.insert--;if(s.lookahead+s.insert<MIN_MATCH){break}}}}while(s.lookahead<MIN_LOOKAHEAD&&s.strm.avail_in!==0)}function deflate_stored(s,flush){var max_block_size=65535;if(max_block_size>s.pending_buf_size-5){max_block_size=s.pending_buf_size-5}for(;;){if(s.lookahead<=1){fill_window(s);if(s.lookahead===0&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.strstart+=s.lookahead;s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){s.lookahead=s.strstart-max_start;s.strstart=max_start;flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.strstart>s.block_start){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head;var bflush;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}if(hash_head!==0&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head)}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;if(s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do{s.strstart++;s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}while(--s.match_length!==0);s.strstart++}else{s.strstart+=s.match_length;s.match_length=0;s.ins_h=s.window[s.strstart];s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_slow(s,flush){var hash_head;var bflush;var max_insert;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}s.prev_length=s.match_length;s.prev_match=s.match_start;s.match_length=MIN_MATCH-1;if(hash_head!==0&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);if(s.match_length<=5&&(s.strategy===Z_FILTERED||s.match_length===MIN_MATCH&&s.strstart-s.match_start>4096)){s.match_length=MIN_MATCH-1}}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH;bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH);s.lookahead-=s.prev_length-1;s.prev_length-=2;do{if(++s.strstart<=max_insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}}while(--s.prev_length!==0);s.match_available=0;s.match_length=MIN_MATCH-1;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}else if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);if(bflush){flush_block_only(s,false)}s.strstart++;s.lookahead--;if(s.strm.avail_out===0){return BS_NEED_MORE}}else{s.match_available=1;s.strstart++;s.lookahead--}}if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);s.match_available=0}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_rle(s,flush){var bflush;var prev;var scan,strend;var _win=s.window;for(;;){if(s.lookahead<=MAX_MATCH){fill_window(s);if(s.lookahead<=MAX_MATCH&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.match_length=0;if(s.lookahead>=MIN_MATCH&&s.strstart>0){scan=s.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=MAX_MATCH-(strend-scan);if(s.match_length>s.lookahead){s.match_length=s.lookahead}}}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;s.strstart+=s.match_length;s.match_length=0}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){fill_window(s);if(s.lookahead===0){if(flush===Z_NO_FLUSH){return BS_NEED_MORE}break}}s.match_length=0;bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table;configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size;zero(s.head);s.max_lazy_match=configuration_table[s.level].max_lazy;s.good_match=configuration_table[s.level].good_length;s.nice_match=configuration_table[s.level].nice_length;s.max_chain_length=configuration_table[s.level].max_chain;s.strstart=0;s.block_start=0;s.lookahead=0;s.insert=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;s.ins_h=0}function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2);this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2);this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new utils.Buf16(MAX_BITS+1);this.heap=new utils.Buf16(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new utils.Buf16(2*L_CODES+1);zero(this.depth);this.l_buf=0;this.lit_bufsize=0;this.last_lit=0;this.d_buf=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state){return err(strm,Z_STREAM_ERROR)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;s=strm.state;s.pending=0;s.pending_out=0;if(s.wrap<0){s.wrap=-s.wrap}s.status=s.wrap?INIT_STATE:BUSY_STATE;strm.adler=s.wrap===2?0:1;s.last_flush=Z_NO_FLUSH;trees._tr_init(s);return Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK){lm_init(strm.state)}return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR}if(strm.state.wrap!==2){return Z_STREAM_ERROR}strm.state.gzhead=head;return Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm){return Z_STREAM_ERROR}var wrap=1;if(level===Z_DEFAULT_COMPRESSION){level=6}if(windowBits<0){wrap=0;windowBits=-windowBits}else if(windowBits>15){wrap=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED){return err(strm,Z_STREAM_ERROR)}if(windowBits===8){windowBits=9}var s=new DeflateState;strm.state=s;s.strm=strm;s.wrap=wrap;s.gzhead=null;s.w_bits=windowBits;s.w_size=1<<s.w_bits;s.w_mask=s.w_size-1;s.hash_bits=memLevel+7;s.hash_size=1<<s.hash_bits;s.hash_mask=s.hash_size-1;s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH);s.window=new utils.Buf8(s.w_size*2);s.head=new utils.Buf16(s.hash_size);s.prev=new utils.Buf16(s.w_size);s.lit_bufsize=1<<memLevel+6;s.pending_buf_size=s.lit_bufsize*4;s.pending_buf=new utils.Buf8(s.pending_buf_size);s.d_buf=1*s.lit_bufsize;s.l_buf=(1+2)*s.lit_bufsize;s.level=level;s.strategy=strategy;s.method=method;return deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,Z_DEFLATED,MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY)}function deflate(strm,flush){var old_flush,s;var beg,val;if(!strm||!strm.state||flush>Z_BLOCK||flush<0){return strm?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR}s=strm.state;if(!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH){return err(strm,strm.avail_out===0?Z_BUF_ERROR:Z_STREAM_ERROR)}s.strm=strm;old_flush=s.last_flush;s.last_flush=flush;if(s.status===INIT_STATE){if(s.wrap===2){strm.adler=0;put_byte(s,31);put_byte(s,139);put_byte(s,8);if(!s.gzhead){put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0)

put_byte(s,s.level===9?2
s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,OS_CODE);s.status=BUSY_STATE}else{put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(!s.gzhead.extra?0:4)+(!s.gzhead.name?0:8)+(!s.gzhead.comment?0:16));put_byte(s,s.gzhead.time&255);put_byte(s,s.gzhead.time>>8&255);put_byte(s,s.gzhead.time>>16&255);put_byte(s,s.gzhead.time>>24&255);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,s.gzhead.os&255);if(s.gzhead.extra&&s.gzhead.extra.length){put_byte(s,s.gzhead.extra.length&255);put_byte(s,s.gzhead.extra.length>>8&255)}if(s.gzhead.hcrc){strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)}s.gzindex=0;s.status=EXTRA_STATE}}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8;var level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2){level_flags=0}else if(s.level<6){level_flags=1}else if(s.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s.strstart!==0){header|=PRESET_DICT}header+=31-header%31;s.status=BUSY_STATE;putShortMSB(s,header);if(s.strstart!==0){putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}strm.adler=1}}if(s.status===EXTRA_STATE){if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){break}}put_byte(s,s.gzhead.extra[s.gzindex]&255);s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(s.gzindex===s.gzhead.extra.length){s.gzindex=0;s.status=NAME_STATE}}else{s.status=NAME_STATE}}if(s.status===NAME_STATE){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.name.length){val=s.gzhead.name.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.gzindex=0;s.status=COMMENT_STATE}}else{s.status=COMMENT_STATE}}if(s.status===COMMENT_STATE){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.comment.length){val=s.gzhead.comment.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.status=HCRC_STATE}}else{s.status=HCRC_STATE}}if(s.status===HCRC_STATE){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size){flush_pending(strm)}if(s.pending+2<=s.pending_buf_size){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);strm.adler=0;s.status=BUSY_STATE}}else{s.status=BUSY_STATE}}if(s.pending!==0){flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH){return err(strm,Z_BUF_ERROR)}if(s.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR)}if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY?deflate_huff(s,flush):s.strategy===Z_RLE?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s.last_flush=-1}return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH){trees._tr_align(s)}else if(flush!==Z_BLOCK){trees._tr_stored_block(s,0,0,false);if(flush===Z_FULL_FLUSH){zero(s.head);if(s.lookahead===0){s.strstart=0;s.block_start=0;s.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}}if(flush!==Z_FINISH){return Z_OK}if(s.wrap<=0){return Z_STREAM_END}if(s.wrap===2){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);put_byte(s,strm.adler>>16&255);put_byte(s,strm.adler>>24&255);put_byte(s,strm.total_in&255);put_byte(s,strm.total_in>>8&255);put_byte(s,strm.total_in>>16&255);put_byte(s,strm.total_in>>24&255)}else{putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}flush_pending(strm);if(s.wrap>0){s.wrap=-s.wrap}return s.pending!==0?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state){return Z_STREAM_ERROR}status=strm.state.status;if(status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE){return err(strm,Z_STREAM_ERROR)}strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var s;var str,n;var wrap;var avail;var next;var input;var tmpDict;if(!strm||!strm.state){return Z_STREAM_ERROR}s=strm.state;wrap=s.wrap;if(wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead){return Z_STREAM_ERROR}if(wrap===1){strm.adler=adler32(strm.adler,dictionary,dictLength,0)}s.wrap=0;if(dictLength>=s.w_size){if(wrap===0){zero(s.head);s.strstart=0;s.block_start=0;s.insert=0}tmpDict=new utils.Buf8(s.w_size);utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0);dictionary=tmpDict;dictLength=s.w_size}avail=strm.avail_in;next=strm.next_in;input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary;fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart;n=s.lookahead-(MIN_MATCH-1);do{s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++}while(--n);s.strstart=str;s.lookahead=MIN_MATCH-1;fill_window(s)}s.strstart+=s.lookahead;s.block_start=s.strstart;s.insert=s.lookahead;s.lookahead=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;strm.next_in=next;strm.input=input;strm.avail_in=avail;s.wrap=wrap;return Z_OK}exports.deflateInit=deflateInit;exports.deflateInit2=deflateInit2;exports.deflateReset=deflateReset;exports.deflateResetKeep=deflateResetKeep;exports.deflateSetHeader=deflateSetHeader;exports.deflate=deflate;exports.deflateEnd=deflateEnd;exports.deflateSetDictionary=deflateSetDictionary;exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":6,"./adler32":7,"./crc32":9,"./messages":14,"./trees":15}],11:[function(require,module,exports){"use strict";var BAD=30;var TYPE=12;module.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=lcode[hold&lmask];dolen:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits<op){hold+=input[_in++]<<bits;bits+=8}len+=hold&(1<<op)-1;hold>>>=op;bits-=op}if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=dcode[hold&dmask];dodist:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bits<op){hold+=input[_in++]<<bits;bits+=8;if(bits<op){hold+=input[_in++]<<bits;bits+=8}}dist+=hold&(1<<op)-1;if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}else if(wnext<op){from+=wsize+wnext-op;op-=wnext;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=0;if(wnext<len){op=wnext;len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}}else{from+=wnext-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}while(len>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<<op)-1)];continue dodist}else{strm.msg="invalid distance code";state.mode=BAD;break top}break}}else if((op&64)===0){here=lcode[(here&65535)+(hold&(1<<op)-1)];continue dolen}else if(op&32){state.mode=TYPE;break top}else{strm.msg="invalid literal/length code";state.mode=BAD;break top}break}}while(_in<last&&_out<end);len=bits>>3;_in-=len;bits-=len<<3;hold&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold;state.bits=bits;return}},{}],12:[function(require,module,exports){"use strict";var utils=require("../utils/common");var adler32=require("./adler32");var crc32=require("./crc32");var inflate_fast=require("./inffast");var inflate_table=require("./inftrees");var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0;state.window=new utils.Buf8(state.wsize)}if(copy>=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave<state.wsize){state.whave+=dist}}}return 0}function inflate(strm,flush){var state;var input,output;var next;var put;var have,left;var hold;var bits;var _in,_out;var copy;var from;var from_source;var here=0;var here_bits,here_op,here_val;var last_bits,last_op,last_val;var len;var ret;var hbuf=new utils.Buf8(4);var opts;var n;var order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!strm||!strm.state||!strm.output||!strm.input&&strm.avail_in!==0){return Z_STREAM_ERROR}state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO}put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break}while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.wrap&2&&hold===35615){state.check=0;hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<<len;strm.adler=state.check=1;state.mode=hold&512?DICTID:TYPE;hold=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.flags=hold;if((state.flags&255)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}if(state.flags&57344){strm.msg="unknown header flags set";state.mode=BAD;break}if(state.head){state.head.text=hold>>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.time=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.xflags=hold&255;state.head.os=hold>>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length=hold;if(state.head){state.head.extra_len=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.name=null}state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&4096){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.comment+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.comment=null}state.mode=HCRC;case HCRC:if(state.flags&512){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.check&65535)){strm.msg="header crc mismatch";state.mode=BAD;break}hold=0;bits=0}if(state.head){state.head.hcrc=state.flags>>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}strm.adler=state.check=zswap32(hold);hold=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;return Z_NEED_DICT}strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush===Z_BLOCK||flush===Z_TREES){break inf_leave}case TYPEDO:if(state.last){hold>>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.last=hold&1;hold>>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((hold&65535)!==(hold>>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.nlen=(hold&31)+257;hold>>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.lens[order[state.have++]]=hold&7;hold>>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_val<16){hold>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_op&&(here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<<state.distbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.offset+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<<bits;bits+=8}_out-=left;strm.total_out+=_out;state.total+=_out;if(_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)}_out=left;if((state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break}hold=0;bits=0}state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.total&4294967295)){strm.msg="incorrect length check";state.mode=BAD;break}hold=0;bits=0}state.mode=DONE;case DONE:ret=Z_STREAM_END;break inf_leave;case BAD:ret=Z_DATA_ERROR;break inf_leave;case MEM:return Z_MEM_ERROR;case SYNC:default:return Z_STREAM_ERROR}}strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;if(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush!==Z_FINISH)){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out)){state.mode=MEM;return Z_MEM_ERROR}}_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&&_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)}strm.data_type=state.bits+(state.last?64:0)+(state.mode===TYPE?128:0)+(state.mode===LEN_||state.mode===COPY_?256:0);if((_in===0&&_out===0||flush===Z_FINISH)&&ret===Z_OK){ret=Z_BUF_ERROR}return ret}function inflateEnd(strm){if(!strm||!strm.state){return Z_STREAM_ERROR}var state=strm.state;if(state.window){state.window=null}strm.state=null;return Z_OK}function inflateGetHeader(strm,head){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR}state.head=head;head.done=false;return Z_OK}function inflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var state;var dictid;var ret;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR}if(state.mode===DICT){dictid=1;dictid=adler32(dictid,dictionary,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR}}ret=updatewindow(strm,dictionary,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR}state.havedict=1;return Z_OK}exports.inflateReset=inflateReset;exports.inflateReset2=inflateReset2;exports.inflateResetKeep=inflateResetKeep;exports.inflateInit=inflateInit;exports.inflateInit2=inflateInit2;exports.inflate=inflate;exports.inflateEnd=inflateEnd;exports.inflateGetHeader=inflateGetHeader;exports.inflateSetDictionary=inflateSetDictionary;exports.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":6,"./adler32":7,"./crc32":9,"./inffast":11,"./inftrees":13}],13:[function(require,module,exports){"use strict";var utils=require("../utils/common");var MAXBITS=15;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var CODES=0;var LENS=1;var DISTS=2;var lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0];var lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78];var dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0];var dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var bits=opts.bits;var len=0;var sym=0;var min=0,max=0;var root=0;var curr=0;var drop=0;var left=0;var used=0;var huff=0;var incr;var fill;var low;var mask;var next;var base=null;var base_index=0;var end;var count=new utils.Buf16(MAXBITS+1);var offs=new utils.Buf16(MAXBITS+1);var extra=null;var extra_index=0;var here_bits,here_op,here_val;for(len=0;len<=MAXBITS;len++){count[len]=0}for(sym=0;sym<codes;sym++){count[lens[lens_index+sym]]++}root=bits;for(max=MAXBITS;max>=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min<max;min++){if(count[min]!==0){break}}if(root<min){root=min}left=1;for(len=1;len<=MAXBITS;len++){left<<=1;left-=count[len];if(left<0){return-1}}if(left>0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;len<MAXBITS;len++){offs[len+1]=offs[len]+count[len]}for(sym=0;sym<codes;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym}}if(type===CODES){base=extra=work;end=19}else if(type===LENS){base=lbase;base_index-=257;extra=lext;extra_index-=257;end=256}else{base=dbase;extra=dext;end=-1}huff=0;sym=0;len=min;next=table_index;curr=root;drop=0;low=-1;used=1<<root;mask=used-1;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}var i=0;for(;;){i++;here_bits=len-drop;if(work[sym]<end){here_op=0;here_val=work[sym]}else if(work[sym]>end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<<len-drop;fill=1<<curr;min=fill;do{fill-=incr;table[next+(huff>>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<<len-1;while(huff&incr){incr>>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<<curr;while(curr+drop<max){left-=count[curr+drop];if(left<=0){break}curr++;left<<=1}used+=1<<curr;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},{"../utils/common":6}],14:[function(require,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],15:[function(require,module,exports){"use strict";var utils=require("../utils/common");var Z_FIXED=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN=2;function zero(buf){var len=buf.length
while(--len>=0){buf[len]=0}}var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH=3;var MAX_MATCH=258;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];var extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];var extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];var bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length}var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc}function d_code(dist){return dist<256?_dist_code[dist]
_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255;s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length){s.bi_buf|=value<<s.bi_valid&65535;put_short(s,s.bi_buf);s.bi_buf=value>>Buf_size-s.bi_valid;s.bi_valid+=length-Buf_size}else{s.bi_buf|=value<<s.bi_valid&65535;s.bi_valid+=length}}function send_code(s,c,tree){send_bits(s,tree[c*2],tree[c*2+1])}function bi_reverse(code,len){var res=0;do{res|=code&1;code>>>=1;res<<=1}while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16){put_short(s,s.bi_buf);s.bi_buf=0;s.bi_valid=0}else if(s.bi_valid>=8){s.pending_buf[s.pending++]=s.bi_buf&255;s.bi_buf>>=8;s.bi_valid-=8}}function gen_bitlen(s,desc){var tree=desc.dyn_tree;var max_code=desc.max_code;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var extra=desc.stat_desc.extra_bits;var base=desc.stat_desc.extra_base;var max_length=desc.stat_desc.max_length;var h;var n,m;var bits;var xbits;var f;var overflow=0;for(bits=0;bits<=MAX_BITS;bits++){s.bl_count[bits]=0}tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;h<HEAP_SIZE;h++){n=s.heap[h];bits=tree[tree[n*2+1]*2+1]+1;if(bits>max_length){bits=max_length;overflow++}tree[n*2+1]=bits;if(n>max_code){continue}s.bl_count[bits]++;xbits=0;if(n>=base){xbits=extra[n-base]}f=tree[n*2];s.opt_len+=f*(bits+xbits);if(has_stree){s.static_len+=f*(stree[n*2+1]+xbits)}}if(overflow===0){return}do{bits=max_length-1;while(s.bl_count[bits]===0){bits--}s.bl_count[bits]--;s.bl_count[bits+1]+=2;s.bl_count[max_length]--;overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){m=s.heap[--h];if(m>max_code){continue}if(tree[m*2+1]!==bits){s.opt_len+=(bits-tree[m*2+1])*tree[m*2];tree[m*2+1]=bits}n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1);var code=0;var bits;var n;for(bits=1;bits<=MAX_BITS;bits++){next_code[bits]=code=code+bl_count[bits-1]<<1}for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0){continue}tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n;var bits;var length;var code;var dist;var bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code<LENGTH_CODES-1;code++){base_length[code]=length;for(n=0;n<1<<extra_lbits[code];n++){_length_code[length++]=code}}_length_code[length-1]=code;dist=0;for(code=0;code<16;code++){base_dist[code]=dist;for(n=0;n<1<<extra_dbits[code];n++){_dist_code[dist++]=code}}dist>>=7;for(;code<D_CODES;code++){base_dist[code]=dist<<7;for(n=0;n<1<<extra_dbits[code]-7;n++){_dist_code[256+dist++]=code}}for(bits=0;bits<=MAX_BITS;bits++){bl_count[bits]=0}n=0;while(n<=143){static_ltree[n*2+1]=8;n++;bl_count[8]++}while(n<=255){static_ltree[n*2+1]=9;n++;bl_count[9]++}while(n<=279){static_ltree[n*2+1]=7;n++;bl_count[7]++}while(n<=287){static_ltree[n*2+1]=8;n++;bl_count[8]++}gen_codes(static_ltree,L_CODES+1,bl_count);for(n=0;n<D_CODES;n++){static_dtree[n*2+1]=5;static_dtree[n*2]=bi_reverse(n,5)}static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS+1,L_CODES,MAX_BITS);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES,MAX_BITS);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES,MAX_BL_BITS)}function init_block(s){var n;for(n=0;n<L_CODES;n++){s.dyn_ltree[n*2]=0}for(n=0;n<D_CODES;n++){s.dyn_dtree[n*2]=0}for(n=0;n<BL_CODES;n++){s.bl_tree[n*2]=0}s.dyn_ltree[END_BLOCK*2]=1;s.opt_len=s.static_len=0;s.last_lit=s.matches=0}function bi_windup(s){if(s.bi_valid>8){put_short(s,s.bi_buf)}else if(s.bi_valid>0){s.pending_buf[s.pending++]=s.bi_buf}s.bi_buf=0;s.bi_valid=0}function copy_block(s,buf,len,header){bi_windup(s);if(header){put_short(s,len);put_short(s,~len)}utils.arraySet(s.pending_buf,s.window,buf,len,s.pending);s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2;var _m2=m*2;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]}function pqdownheap(s,tree,k){var v=s.heap[k];var j=k<<1;while(j<=s.heap_len){if(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)){j++}if(smaller(tree,v,s.heap[j],s.depth)){break}s.heap[k]=s.heap[j];k=j;j<<=1}s.heap[k]=v}function compress_block(s,ltree,dtree){var dist;var lc;var lx=0;var code;var extra;if(s.last_lit!==0){do{dist=s.pending_buf[s.d_buf+lx*2]<<8|s.pending_buf[s.d_buf+lx*2+1];lc=s.pending_buf[s.l_buf+lx];lx++;if(dist===0){send_code(s,lc,ltree)}else{code=_length_code[lc];send_code(s,code+LITERALS+1,ltree);extra=extra_lbits[code];if(extra!==0){lc-=base_length[code];send_bits(s,lc,extra)}dist--;code=d_code(dist);send_code(s,code,dtree);extra=extra_dbits[code];if(extra!==0){dist-=base_dist[code];send_bits(s,dist,extra)}}}while(lx<s.last_lit)}send_code(s,END_BLOCK,ltree)}function build_tree(s,desc){var tree=desc.dyn_tree;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var elems=desc.stat_desc.elems;var n,m;var max_code=-1;var node;s.heap_len=0;s.heap_max=HEAP_SIZE;for(n=0;n<elems;n++){if(tree[n*2]!==0){s.heap[++s.heap_len]=max_code=n;s.depth[n]=0}else{tree[n*2+1]=0}}while(s.heap_len<2){node=s.heap[++s.heap_len]=max_code<2?++max_code:0;tree[node*2]=1;s.depth[node]=0;s.opt_len--;if(has_stree){s.static_len-=stree[node*2+1]}}desc.max_code=max_code;for(n=s.heap_len>>1;n>=1;n--){pqdownheap(s,tree,n)}node=elems;do{n=s.heap[1];s.heap[1]=s.heap[s.heap_len--];pqdownheap(s,tree,1);m=s.heap[1];s.heap[--s.heap_max]=n;s.heap[--s.heap_max]=m;tree[node*2]=tree[n*2]+tree[m*2];s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1;tree[n*2+1]=tree[m*2+1]=node;s.heap[1]=node++;pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1];gen_bitlen(s,desc);gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){s.bl_tree[curlen*2]+=count}else if(curlen!==0){if(curlen!==prevlen){s.bl_tree[curlen*2]++}s.bl_tree[REP_3_6*2]++}else if(count<=10){s.bl_tree[REPZ_3_10*2]++}else{s.bl_tree[REPZ_11_138*2]++}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function send_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){do{send_code(s,curlen,s.bl_tree)}while(--count!==0)}else if(curlen!==0){if(curlen!==prevlen){send_code(s,curlen,s.bl_tree);count--}send_code(s,REP_3_6,s.bl_tree);send_bits(s,count-3,2)}else if(count<=10){send_code(s,REPZ_3_10,s.bl_tree);send_bits(s,count-3,3)}else{send_code(s,REPZ_11_138,s.bl_tree);send_bits(s,count-11,7)}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function build_bl_tree(s){var max_blindex;scan_tree(s,s.dyn_ltree,s.l_desc.max_code);scan_tree(s,s.dyn_dtree,s.d_desc.max_code);build_tree(s,s.bl_desc);for(max_blindex=BL_CODES-1;max_blindex>=3;max_blindex--){if(s.bl_tree[bl_order[max_blindex]*2+1]!==0){break}}s.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5);send_bits(s,dcodes-1,5);send_bits(s,blcodes-4,4);for(rank=0;rank<blcodes;rank++){send_bits(s,s.bl_tree[bl_order[rank]*2+1],3)}send_tree(s,s.dyn_ltree,lcodes-1);send_tree(s,s.dyn_dtree,dcodes-1)}function detect_data_type(s){var black_mask=4093624447;var n;for(n=0;n<=31;n++,black_mask>>>=1){if(black_mask&1&&s.dyn_ltree[n*2]!==0){return Z_BINARY}}if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0){return Z_TEXT}for(n=32;n<LITERALS;n++){if(s.dyn_ltree[n*2]!==0){return Z_TEXT}}return Z_BINARY}var static_init_done=false;function _tr_init(s){if(!static_init_done){tr_static_init();static_init_done=true}s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc);s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc);s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc);s.bi_buf=0;s.bi_valid=0;init_block(s)}function _tr_stored_block(s,buf,stored_len,last){send_bits(s,(STORED_BLOCK<<1)+(last?1:0),3);copy_block(s,buf,stored_len,true)}function _tr_align(s){send_bits(s,STATIC_TREES<<1,3);send_code(s,END_BLOCK,static_ltree);bi_flush(s)}function _tr_flush_block(s,buf,stored_len,last){var opt_lenb,static_lenb;var max_blindex=0;if(s.level>0){if(s.strm.data_type===Z_UNKNOWN){s.strm.data_type=detect_data_type(s)}build_tree(s,s.l_desc);build_tree(s,s.d_desc);max_blindex=build_bl_tree(s);opt_lenb=s.opt_len+3+7>>>3;static_lenb=s.static_len+3+7>>>3;if(static_lenb<=opt_lenb){opt_lenb=static_lenb}}else{opt_lenb=static_lenb=stored_len+5}if(stored_len+4<=opt_lenb&&buf!==-1){_tr_stored_block(s,buf,stored_len,last)}else if(s.strategy===Z_FIXED||static_lenb===opt_lenb){send_bits(s,(STATIC_TREES<<1)+(last?1:0),3);compress_block(s,static_ltree,static_dtree)}else{send_bits(s,(DYN_TREES<<1)+(last?1:0),3);send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1);compress_block(s,s.dyn_ltree,s.dyn_dtree)}init_block(s);if(last){bi_windup(s)}}function _tr_tally(s,dist,lc){s.pending_buf[s.d_buf+s.last_lit*2]=dist>>>8&255;s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&255;s.pending_buf[s.l_buf+s.last_lit]=lc&255;s.last_lit++;if(dist===0){s.dyn_ltree[lc*2]++}else{s.matches++;dist--;s.dyn_ltree[(_length_code[lc]+LITERALS+1)*2]++;s.dyn_dtree[d_code(dist)*2]++}return s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init;exports._tr_stored_block=_tr_stored_block;exports._tr_flush_block=_tr_flush_block;exports._tr_tally=_tr_tally;exports._tr_align=_tr_align},{"../utils/common":6}],16:[function(require,module,exports){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module.exports=ZStream},{}],17:[function(require,module,exports){(function(process,Buffer){var msg=require("pako/lib/zlib/messages");var zstream=require("pako/lib/zlib/zstream");var zlib_deflate=require("pako/lib/zlib/deflate.js");var zlib_inflate=require("pako/lib/zlib/inflate.js");var constants=require("pako/lib/zlib/constants");for(var key in constants){exports[key]=constants[key]}exports.NONE=0;exports.DEFLATE=1;exports.INFLATE=2;exports.GZIP=3;exports.GUNZIP=4;exports.DEFLATERAW=5;exports.INFLATERAW=6;exports.UNZIP=7;function Zlib(mode){if(mode<exports.DEFLATE||mode>exports.UNZIP)throw new TypeError("Bad argument");this.mode=mode;this.init_done=false;this.write_in_progress=false;this.pending_close=false;this.windowBits=0;this.level=0;this.memLevel=0;this.strategy=0;this.dictionary=null}Zlib.prototype.init=function(windowBits,level,memLevel,strategy,dictionary){this.windowBits=windowBits;this.level=level;this.memLevel=memLevel;this.strategy=strategy;if(this.mode===exports.GZIP||this.mode===exports.GUNZIP)this.windowBits+=16;if(this.mode===exports.UNZIP)this.windowBits+=32;if(this.mode===exports.DEFLATERAW||this.mode===exports.INFLATERAW)this.windowBits=-this.windowBits;this.strm=new zstream;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:var status=zlib_deflate.deflateInit2(this.strm,this.level,exports.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:case exports.UNZIP:var status=zlib_inflate.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(status!==exports.Z_OK){this._error(status);return}this.write_in_progress=false;this.init_done=true};Zlib.prototype.params=function(){throw new Error("deflateParams Not supported")};Zlib.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===exports.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")};Zlib.prototype.write=function(flush,input,in_off,in_len,out,out_off,out_len){this._writeCheck();this.write_in_progress=true;var self=this;process.nextTick(function(){self.write_in_progress=false;var res=self._write(flush,input,in_off,in_len,out,out_off,out_len);self.callback(res[0],res[1]);if(self.pending_close)self.close()});return this};function bufferSet(data,offset){for(var i=0;i<data.length;i++){this[offset+i]=data[i]}}Zlib.prototype.writeSync=function(flush,input,in_off,in_len,out,out_off,out_len){this._writeCheck();return this._write(flush,input,in_off,in_len,out,out_off,out_len)};Zlib.prototype._write=function(flush,input,in_off,in_len,out,out_off,out_len){this.write_in_progress=true;if(flush!==exports.Z_NO_FLUSH&&flush!==exports.Z_PARTIAL_FLUSH&&flush!==exports.Z_SYNC_FLUSH&&flush!==exports.Z_FULL_FLUSH&&flush!==exports.Z_FINISH&&flush!==exports.Z_BLOCK){throw new Error("Invalid flush value")}if(input==null){input=new Buffer(0);in_len=0;in_off=0}if(out._set)out.set=out._set;else out.set=bufferSet;var strm=this.strm;strm.avail_in=in_len;strm.input=input;strm.next_in=in_off;strm.avail_out=out_len;strm.output=out;strm.next_out=out_off;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:var status=zlib_deflate.deflate(strm,flush);break;case exports.UNZIP:case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:var status=zlib_inflate.inflate(strm,flush);break;default:throw new Error("Unknown mode "+this.mode)}if(status!==exports.Z_STREAM_END&&status!==exports.Z_OK){this._error(status)}this.write_in_progress=false;return[strm.avail_in,strm.avail_out]};Zlib.prototype.close=function(){if(this.write_in_progress){this.pending_close=true;return}this.pending_close=false;if(this.mode===exports.DEFLATE||this.mode===exports.GZIP||this.mode===exports.DEFLATERAW){zlib_deflate.deflateEnd(this.strm)}else{zlib_inflate.inflateEnd(this.strm)}this.mode=exports.NONE};Zlib.prototype.reset=function(){switch(this.mode){case exports.DEFLATE:case exports.DEFLATERAW:var status=zlib_deflate.deflateReset(this.strm);break;case exports.INFLATE:case exports.INFLATERAW:var status=zlib_inflate.inflateReset(this.strm);break}if(status!==exports.Z_OK){this._error(status)}};Zlib.prototype._error=function(status){this.onerror(msg[status]+": "+this.strm.msg,status);this.write_in_progress=false;if(this.pending_close)this.close()};exports.Zlib=Zlib}).call(this,require("_process"),require("buffer").Buffer)},{_process:68,buffer:20,"pako/lib/zlib/constants":8,"pako/lib/zlib/deflate.js":10,"pako/lib/zlib/inflate.js":12,"pako/lib/zlib/messages":14,"pako/lib/zlib/zstream":16}],18:[function(require,module,exports){(function(process,Buffer){var Transform=require("_stream_transform");var binding=require("./binding");var util=require("util");var assert=require("assert").ok;binding.Z_MIN_WINDOWBITS=8;binding.Z_MAX_WINDOWBITS=15;binding.Z_DEFAULT_WINDOWBITS=15;binding.Z_MIN_CHUNK=64;binding.Z_MAX_CHUNK=Infinity;binding.Z_DEFAULT_CHUNK=16*1024;binding.Z_MIN_MEMLEVEL=1;binding.Z_MAX_MEMLEVEL=9;binding.Z_DEFAULT_MEMLEVEL=8;binding.Z_MIN_LEVEL=-1;binding.Z_MAX_LEVEL=9;binding.Z_DEFAULT_LEVEL=binding.Z_DEFAULT_COMPRESSION;Object.keys(binding).forEach(function(k){if(k.match(/^Z/))exports[k]=binding[k]});exports.codes={Z_OK:binding.Z_OK,Z_STREAM_END:binding.Z_STREAM_END,Z_NEED_DICT:binding.Z_NEED_DICT,Z_ERRNO:binding.Z_ERRNO,Z_STREAM_ERROR:binding.Z_STREAM_ERROR,Z_DATA_ERROR:binding.Z_DATA_ERROR,Z_MEM_ERROR:binding.Z_MEM_ERROR,Z_BUF_ERROR:binding.Z_BUF_ERROR,Z_VERSION_ERROR:binding.Z_VERSION_ERROR};Object.keys(exports.codes).forEach(function(k){exports.codes[exports.codes[k]]=k});exports.Deflate=Deflate;exports.Inflate=Inflate;exports.Gzip=Gzip;exports.Gunzip=Gunzip;exports.DeflateRaw=DeflateRaw;exports.InflateRaw=InflateRaw;exports.Unzip=Unzip;exports.createDeflate=function(o){return new Deflate(o)};exports.createInflate=function(o){return new Inflate(o)};exports.createDeflateRaw=function(o){return new DeflateRaw(o)};exports.createInflateRaw=function(o){return new InflateRaw(o)};exports.createGzip=function(o){return new Gzip(o)};exports.createGunzip=function(o){return new Gunzip(o)};exports.createUnzip=function(o){return new Unzip(o)};exports.deflate=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Deflate(opts),buffer,callback)};exports.deflateSync=function(buffer,opts){return zlibBufferSync(new Deflate(opts),buffer)};exports.gzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Gzip(opts),buffer,callback)};exports.gzipSync=function(buffer,opts){return zlibBufferSync(new Gzip(opts),buffer)};exports.deflateRaw=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new DeflateRaw(opts),buffer,callback)};exports.deflateRawSync=function(buffer,opts){return zlibBufferSync(new DeflateRaw(opts),buffer)};exports.unzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Unzip(opts),buffer,callback)};exports.unzipSync=function(buffer,opts){return zlibBufferSync(new Unzip(opts),buffer)};exports.inflate=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Inflate(opts),buffer,callback)};exports.inflateSync=function(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)};exports.gunzip=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new Gunzip(opts),buffer,callback)};exports.gunzipSync=function(buffer,opts){return zlibBufferSync(new Gunzip(opts),buffer)};exports.inflateRaw=function(buffer,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return zlibBuffer(new InflateRaw(opts),buffer,callback)};exports.inflateRawSync=function(buffer,opts){return zlibBufferSync(new InflateRaw(opts),buffer)};function zlibBuffer(engine,buffer,callback){var buffers=[];var nread=0;engine.on("error",onError);engine.on("end",onEnd);engine.end(buffer);flow();function flow(){var chunk;while(null!==(chunk=engine.read())){buffers.push(chunk);nread+=chunk.length}engine.once("readable",flow)}function onError(err){engine.removeListener("end",onEnd);engine.removeListener("readable",flow);callback(err)}function onEnd(){var buf=Buffer.concat(buffers,nread);buffers=[];callback(null,buf);engine.close()}}function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=new Buffer(buffer);if(!Buffer.isBuffer(buffer))throw new TypeError("Not a string or buffer");var flushFlag=binding.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function Deflate(opts){if(!(this instanceof Deflate))return new Deflate(opts);Zlib.call(this,opts,binding.DEFLATE)}function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);Zlib.call(this,opts,binding.INFLATE)}function Gzip(opts){if(!(this instanceof Gzip))return new Gzip(opts);Zlib.call(this,opts,binding.GZIP)}function Gunzip(opts){if(!(this instanceof Gunzip))return new Gunzip(opts);Zlib.call(this,opts,binding.GUNZIP)}function DeflateRaw(opts){if(!(this instanceof DeflateRaw))return new DeflateRaw(opts);Zlib.call(this,opts,binding.DEFLATERAW)}function InflateRaw(opts){if(!(this instanceof InflateRaw))return new InflateRaw(opts);Zlib.call(this,opts,binding.INFLATERAW)}function Unzip(opts){if(!(this instanceof Unzip))return new Unzip(opts);Zlib.call(this,opts,binding.UNZIP)}function Zlib(opts,mode){this._opts=opts=opts||{};this._chunkSize=opts.chunkSize||exports.Z_DEFAULT_CHUNK;Transform.call(this,opts);if(opts.flush){if(opts.flush!==binding.Z_NO_FLUSH&&opts.flush!==binding.Z_PARTIAL_FLUSH&&opts.flush!==binding.Z_SYNC_FLUSH&&opts.flush!==binding.Z_FULL_FLUSH&&opts.flush!==binding.Z_FINISH&&opts.flush!==binding.Z_BLOCK){throw new Error("Invalid flush flag: "+opts.flush)}}this._flushFlag=opts.flush||binding.Z_NO_FLUSH;if(opts.chunkSize){if(opts.chunkSize<exports.Z_MIN_CHUNK||opts.chunkSize>exports.Z_MAX_CHUNK){throw new Error("Invalid chunk size: "+opts.chunkSize)}}if(opts.windowBits){if(opts.windowBits<exports.Z_MIN_WINDOWBITS||opts.windowBits>exports.Z_MAX_WINDOWBITS){throw new Error("Invalid windowBits: "+opts.windowBits)}}if(opts.level){if(opts.level<exports.Z_MIN_LEVEL||opts.level>exports.Z_MAX_LEVEL){throw new Error("Invalid compression level: "+opts.level)}}if(opts.memLevel){if(opts.memLevel<exports.Z_MIN_MEMLEVEL||opts.memLevel>exports.Z_MAX_MEMLEVEL){throw new Error("Invalid memLevel: "+opts.memLevel)}}if(opts.strategy){if(opts.strategy!=exports.Z_FILTERED&&opts.strategy!=exports.Z_HUFFMAN_ONLY&&opts.strategy!=exports.Z_RLE&&opts.strategy!=exports.Z_FIXED&&opts.strategy!=exports.Z_DEFAULT_STRATEGY){throw new Error("Invalid strategy: "+opts.strategy)}}if(opts.dictionary){if(!Buffer.isBuffer(opts.dictionary)){throw new Error("Invalid dictionary: it should be a Buffer instance")}}this._binding=new binding.Zlib(mode);var self=this;this._hadError=false;this._binding.onerror=function(message,errno){self._binding=null;self._hadError=true;var error=new Error(message);error.errno=errno;error.code=exports.codes[errno];self.emit("error",error)};var level=exports.Z_DEFAULT_COMPRESSION;if(typeof opts.level==="number")level=opts.level;var strategy=exports.Z_DEFAULT_STRATEGY;if(typeof opts.strategy==="number")strategy=opts.strategy;this._binding.init(opts.windowBits||exports.Z_DEFAULT_WINDOWBITS,level,opts.memLevel||exports.Z_DEFAULT_MEMLEVEL,strategy,opts.dictionary);this._buffer=new Buffer(this._chunkSize);this._offset=0;this._closed=false;this._level=level;this._strategy=strategy;this.once("end",this.close)}util.inherits(Zlib,Transform);Zlib.prototype.params=function(level,strategy,callback){if(level<exports.Z_MIN_LEVEL||level>exports.Z_MAX_LEVEL){throw new RangeError("Invalid compression level: "+level)}if(strategy!=exports.Z_FILTERED&&strategy!=exports.Z_HUFFMAN_ONLY&&strategy!=exports.Z_RLE&&strategy!=exports.Z_FIXED&&strategy!=exports.Z_DEFAULT_STRATEGY){throw new TypeError("Invalid strategy: "+strategy)}if(this._level!==level||this._strategy!==strategy){var self=this;this.flush(binding.Z_SYNC_FLUSH,function(){self._binding.params(level,strategy);if(!self._hadError){self._level=level;self._strategy=strategy;if(callback)callback()}})}else{process.nextTick(callback)}};Zlib.prototype.reset=function(){return this._binding.reset()};Zlib.prototype._flush=function(callback){this._transform(new Buffer(0),"",callback)};Zlib.prototype.flush=function(kind,callback){var ws=this._writableState;if(typeof kind==="function"||kind===void 0&&!callback){callback=kind;kind=binding.Z_FULL_FLUSH}if(ws.ended){if(callback)process.nextTick(callback)}else if(ws.ending){if(callback)this.once("end",callback)}else if(ws.needDrain){var self=this;this.once("drain",function(){self.flush(callback)})}else{this._flushFlag=kind;this.write(new Buffer(0),"",callback)}};Zlib.prototype.close=function(callback){if(callback)process.nextTick(callback);if(this._closed)return;this._closed=true;this._binding.close();var self=this;process.nextTick(function(){self.emit("close")})};Zlib.prototype._transform=function(chunk,encoding,cb){var flushFlag;var ws=this._writableState;var ending=ws.ending||ws.ended;var last=ending&&(!chunk||ws.length===chunk.length);if(!chunk===null&&!Buffer.isBuffer(chunk))return cb(new Error("invalid input"));if(last)flushFlag=binding.Z_FINISH;else{flushFlag=this._flushFlag;if(chunk.length>=ws.length){this._flushFlag=this._opts.flush||binding.Z_NO_FLUSH}}var self=this;this._processChunk(chunk,flushFlag,cb)};Zlib.prototype._processChunk=function(chunk,flushFlag,cb){var availInBefore=chunk&&chunk.length;var availOutBefore=this._chunkSize-this._offset;var inOff=0;var self=this;var async=typeof cb==="function";if(!async){var buffers=[];var nread=0;var error;this.on("error",function(er){error=er});do{var res=this._binding.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore)}while(!this._hadError&&callback(res[0],res[1]));if(this._hadError){throw error}var buf=Buffer.concat(buffers,nread);this.close();return buf}var req=this._binding.write(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);req.buffer=chunk;req.callback=callback;function callback(availInAfter,availOutAfter){if(self._hadError)return;var have=availOutBefore-availOutAfter;assert(have>=0,"have should not go down");if(have>0){var out=self._buffer.slice(self._offset,self._offset+have);self._offset+=have;if(async){self.push(out)}else{buffers.push(out);nread+=out.length}}if(availOutAfter===0||self._offset>=self._chunkSize){availOutBefore=self._chunkSize;self._offset=0;self._buffer=new Buffer(self._chunkSize)}if(availOutAfter===0){inOff+=availInBefore-availInAfter;availInBefore=availInAfter;if(!async)return true;var newReq=self._binding.write(flushFlag,chunk,inOff,availInBefore,self._buffer,self._offset,self._chunkSize);newReq.callback=callback;newReq.buffer=chunk;return}if(!async)return false;cb()}};util.inherits(Deflate,Zlib);util.inherits(Inflate,Zlib);util.inherits(Gzip,Zlib);util.inherits(Gunzip,Zlib);util.inherits(DeflateRaw,Zlib);util.inherits(InflateRaw,Zlib);util.inherits(Unzip,Zlib)}).call(this,require("_process"),require("buffer").Buffer)},{"./binding":17,_process:68,_stream_transform:79,assert:3,buffer:20,util:87}],19:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++i<size){buf[i]=fillBuf[i%flen]}}else{buf.fill(_fill)}return buf};exports.allocUnsafe=function allocUnsafe(size){if(typeof Buffer.allocUnsafe==="function"){return Buffer.allocUnsafe(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:20}],20:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()<length){throw new RangeError("Invalid typed array length")}if(Buffer.TYPED_ARRAY_SUPPORT){that=new Uint8Array(length);that.__proto__=Buffer.prototype}else{if(that===null){that=new Buffer(length)}that.length=length}return that}function Buffer(arg,encodingOrOffset,length){if(!Buffer.TYPED_ARRAY_SUPPORT&&!(this instanceof Buffer)){return new Buffer(arg,encodingOrOffset,length)}if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(this,arg)}return from(this,arg,encodingOrOffset,length)}Buffer.poolSize=8192;Buffer._augment=function(arr){arr.__proto__=Buffer.prototype;return arr};function from(that,value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){return fromArrayBuffer(that,value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(that,value,encodingOrOffset)}return fromObject(that,value)}Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)};if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){

Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true})}}function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(that,size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(that,size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill)}return createBuffer(that,size)}Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)};function allocUnsafe(that,size){assertSize(size);that=createBuffer(that,size<0?0:checked(size)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<size;++i){that[i]=0}}return that}Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)};function fromString(that,string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;that=createBuffer(that,length);var actual=that.write(string,encoding);if(actual!==length){that=that.slice(0,actual)}return that}function fromArrayLike(that,array){var length=array.length<0?0:checked(array.length)|0;that=createBuffer(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255}return that}function fromArrayBuffer(that,array,byteOffset,length){array.byteLength;if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError("'offset' is out of bounds")}if(array.byteLength<byteOffset+(length||0)){throw new RangeError("'length' is out of bounds")}if(byteOffset===undefined&&length===undefined){array=new Uint8Array(array)}else if(length===undefined){array=new Uint8Array(array,byteOffset)}else{array=new Uint8Array(array,byteOffset,length)}if(Buffer.TYPED_ARRAY_SUPPORT){that=array;that.__proto__=Buffer.prototype}else{that=fromArrayLike(that,array)}return that}function fromObject(that,obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;that=createBuffer(that,len);if(that.length===0){return that}obj.copy(that,0,0,len);return that}if(obj){if(typeof ArrayBuffer!=="undefined"&&obj.buffer instanceof ArrayBuffer||"length"in obj){if(typeof obj.length!=="number"||isnan(obj.length)){return createBuffer(that,0)}return fromArrayLike(that,obj)}if(obj.type==="Buffer"&&isArray(obj.data)){return fromArrayLike(that,obj.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(typeof ArrayBuffer!=="undefined"&&typeof ArrayBuffer.isView==="function"&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){string=""+string}var len=string.length;if(len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case undefined:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i<len;++i){if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset|0;if(isFinite(length)){length=length|0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i]&127)}return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;++i){newBuf[i]=this[i+start]}}return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;++i){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;++i){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}var len=end-start;var i;if(this===target&&start<targetStart&&targetStart<end){for(i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i<len;++i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(val.length===1){var code=val.charCodeAt(0);if(code<256){val=code}}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}}else if(typeof val==="number"){val=val&255}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString());var len=bytes.length;for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":4,ieee754:27,isarray:21}],21:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],22:[function(require,module,exports){"use strict";var FLOAT32_VIEW=new Float32Array(1);var UINT32_VIEW=new Uint32Array(FLOAT32_VIEW.buffer);var NINF=4286578688;UINT32_VIEW[0]=NINF;module.exports=FLOAT32_VIEW[0]},{}],23:[function(require,module,exports){"use strict";var FLOAT32_VIEW=new Float32Array(1);var UINT32_VIEW=new Uint32Array(FLOAT32_VIEW.buffer);var PINF=2139095040;UINT32_VIEW[0]=PINF;module.exports=FLOAT32_VIEW[0]},{}],24:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction

function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer
require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":29}],25:[function(require,module,exports){(function(Buffer){(function(root,factory){if(typeof module!=="undefined"&&module.exports){module.exports=factory()}else if(typeof define==="function"&&define.amd){define([],factory)}else{if(typeof cornerstone==="undefined"){dicomParser={};if(typeof Package!=="undefined"){root.dicomParser=dicomParser}}dicomParser=factory()}})(this,function(){var dicomParser=function(dicomParser){if(dicomParser===undefined){dicomParser={}}dicomParser.parseDicom=function(byteArray,options){if(byteArray===undefined){throw"dicomParser.parseDicom: missing required parameter 'byteArray'"}function readTransferSyntax(metaHeaderDataSet){if(metaHeaderDataSet.elements.x00020010===undefined){throw"dicomParser.parseDicom: missing required meta header attribute 0002,0010"}var transferSyntaxElement=metaHeaderDataSet.elements.x00020010;return dicomParser.readFixedString(byteArray,transferSyntaxElement.dataOffset,transferSyntaxElement.length)}function isExplicit(transferSyntax){if(transferSyntax==="1.2.840.10008.1.2"){return false}return true}function getDataSetByteStream(transferSyntax,position){if(transferSyntax==="1.2.840.10008.1.2.1.99"){if(options&&options.inflater){var fullByteArrayCallback=options.inflater(byteArray,position);return new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser,fullByteArrayCallback,0)}else if(typeof module!=="undefined"&&this.module!==module){var zlib=require("zlib");var deflatedBuffer=dicomParser.sharedCopy(byteArray,position,byteArray.length-position);var inflatedBuffer=zlib.inflateRawSync(deflatedBuffer);var fullByteArrayBuffer=dicomParser.alloc(byteArray,inflatedBuffer.length+position);byteArray.copy(fullByteArrayBuffer,0,0,position);inflatedBuffer.copy(fullByteArrayBuffer,position);return new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser,fullByteArrayBuffer,0)}else if(typeof pako!=="undefined"){var deflated=byteArray.slice(position);var inflated=pako.inflateRaw(deflated);var fullByteArray=dicomParser.alloc(byteArray,inflated.length+position);fullByteArray.set(byteArray.slice(0,position),0);fullByteArray.set(inflated,position);return new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser,fullByteArray,0)}else{throw"dicomParser.parseDicom: no inflater available to handle deflate transfer syntax"}}if(transferSyntax==="1.2.840.10008.1.2.2"){return new dicomParser.ByteStream(dicomParser.bigEndianByteArrayParser,byteArray,position)}else{return new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser,byteArray,position)}}function mergeDataSets(metaHeaderDataSet,instanceDataSet){for(var propertyName in metaHeaderDataSet.elements){if(metaHeaderDataSet.elements.hasOwnProperty(propertyName)){instanceDataSet.elements[propertyName]=metaHeaderDataSet.elements[propertyName]}}if(metaHeaderDataSet.warnings!==undefined){instanceDataSet.warnings=metaHeaderDataSet.warnings.concat(instanceDataSet.warnings)}return instanceDataSet}function readDataSet(metaHeaderDataSet){var transferSyntax=readTransferSyntax(metaHeaderDataSet);var explicit=isExplicit(transferSyntax);var dataSetByteStream=getDataSetByteStream(transferSyntax,metaHeaderDataSet.position);var elements={};var dataSet=new dicomParser.DataSet(dataSetByteStream.byteArrayParser,dataSetByteStream.byteArray,elements);dataSet.warnings=dataSetByteStream.warnings;try{if(explicit){dicomParser.parseDicomDataSetExplicit(dataSet,dataSetByteStream,dataSetByteStream.byteArray.length,options)}else{dicomParser.parseDicomDataSetImplicit(dataSet,dataSetByteStream,dataSetByteStream.byteArray.length,options)}}catch(e){var ex={exception:e,dataSet:dataSet};throw ex}return dataSet}function parseTheByteStream(){var metaHeaderDataSet=dicomParser.readPart10Header(byteArray,options);var dataSet=readDataSet(metaHeaderDataSet);return mergeDataSets(metaHeaderDataSet,dataSet)}return parseTheByteStream()};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function isEndOfImageMarker(dataSet,position){return dataSet.byteArray[position]===255&&dataSet.byteArray[position+1]===217}function isFragmentEndOfImage(dataSet,pixelDataElement,fragmentIndex){var fragment=pixelDataElement.fragments[fragmentIndex];if(isEndOfImageMarker(dataSet,fragment.position+fragment.length-2)||isEndOfImageMarker(dataSet,fragment.position+fragment.length-3)){return true}return false}function findLastImageFrameFragmentIndex(dataSet,pixelDataElement,startFragment){for(var fragmentIndex=startFragment;fragmentIndex<pixelDataElement.fragments.length;fragmentIndex++){if(isFragmentEndOfImage(dataSet,pixelDataElement,fragmentIndex)){return fragmentIndex}}}dicomParser.createJPEGBasicOffsetTable=function(dataSet,pixelDataElement,fragments){if(dataSet===undefined){throw"dicomParser.createJPEGBasicOffsetTable: missing required parameter dataSet"}if(pixelDataElement===undefined){throw"dicomParser.createJPEGBasicOffsetTable: missing required parameter pixelDataElement"}if(pixelDataElement.tag!=="x7fe00010"){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to non pixel data tag (expected tag = x7fe00010'"}if(pixelDataElement.encapsulatedPixelData!==true){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.hadUndefinedLength!==true){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.basicOffsetTable===undefined){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.fragments===undefined){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.fragments.length<=0){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(fragments&&fragments.length<=0){throw"dicomParser.createJPEGBasicOffsetTable: parameter 'fragments' must not be zero length"}fragments=fragments||pixelDataElement.fragments;var basicOffsetTable=[];var startFragmentIndex=0;while(true){basicOffsetTable.push(pixelDataElement.fragments[startFragmentIndex].offset);var endFragmentIndex=findLastImageFrameFragmentIndex(dataSet,pixelDataElement,startFragmentIndex);if(endFragmentIndex===undefined||endFragmentIndex===pixelDataElement.fragments.length-1){return basicOffsetTable}startFragmentIndex=endFragmentIndex+1}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.explicitDataSetToJS=function(dataSet,options){if(dataSet===undefined){throw"dicomParser.explicitDataSetToJS: missing required parameter dataSet"}options=options||{omitPrivateAttibutes:true,maxElementLength:128};var result={};for(var tag in dataSet.elements){var element=dataSet.elements[tag];if(options.omitPrivateAttibutes===true&&dicomParser.isPrivateTag(tag)){continue}if(element.items){var sequenceItems=[];for(var i=0;i<element.items.length;i++){sequenceItems.push(dicomParser.explicitDataSetToJS(element.items[i].dataSet,options))}result[tag]=sequenceItems}else{var asString;asString=undefined;if(element.length<options.maxElementLength){asString=dicomParser.explicitElementToString(dataSet,element)}if(asString!==undefined){result[tag]=asString}else{result[tag]={dataOffset:element.dataOffset,length:element.length}}}}return result};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.explicitElementToString=function(dataSet,element){if(dataSet===undefined||element===undefined){throw"dicomParser.explicitElementToString: missing required parameters"}if(element.vr===undefined){throw"dicomParser.explicitElementToString: cannot convert implicit element to string"}var vr=element.vr;var tag=element.tag;var textResult;function multiElementToString(numItems,func){var result="";for(var i=0;i<numItems;i++){if(i!==0){result+="/"}result+=func.call(dataSet,tag,i).toString()}return result}if(dicomParser.isStringVr(vr)===true){textResult=dataSet.string(tag)}else if(vr=="AT"){var num=dataSet.uint32(tag);if(num===undefined){return undefined}if(num<0){num=4294967295+num+1}return"x"+num.toString(16).toUpperCase()}else if(vr=="US"){textResult=multiElementToString(element.length/2,dataSet.uint16)}else if(vr==="SS"){textResult=multiElementToString(element.length/2,dataSet.int16)}else if(vr=="UL"){textResult=multiElementToString(element.length/4,dataSet.uint32)}else if(vr==="SL"){textResult=multiElementToString(element.length/4,dataSet.int32)}else if(vr=="FD"){textResult=multiElementToString(element.length/8,dataSet.double)}else if(vr=="FL"){textResult=multiElementToString(element.length/4,dataSet.float)}return textResult};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function daysInMonth(m,y){switch(m){case 2:return y%4==0&&y%100||y%400==0?29:28;case 9:case 4:case 6:case 11:return 30;default:return 31}}function isValidDate(d,m,y){if(isNaN(y)){return false}return m>0&&m<=12&&d>0&&d<=daysInMonth(m,y)}dicomParser.parseDA=function(date,validate){if(date&&date.length===8){var yyyy=parseInt(date.substring(0,4),10);var mm=parseInt(date.substring(4,6),10);var dd=parseInt(date.substring(6,8),10);if(validate){if(isValidDate(dd,mm,yyyy)!==true){throw"invalid DA '"+date+"'"}}return{year:yyyy,month:mm,day:dd}}if(validate){throw"invalid DA '"+date+"'"}return undefined};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.parseTM=function(time,validate){if(time.length>=2){var hh=parseInt(time.substring(0,2),10);var mm=time.length>=4?parseInt(time.substring(2,4),10):undefined;var ss=time.length>=6?parseInt(time.substring(4,6),10):undefined;var ffffff=time.length>=8?parseInt(time.substring(7,13),10):undefined;if(validate){if(isNaN(hh)||mm!==undefined&&isNaN(mm)||ss!==undefined&&isNaN(ss)||ffffff!==undefined&&isNaN(ffffff)||(hh<0||hh>23)||mm&&(mm<0||mm>59)||ss&&(ss<0||ss>59)||ffffff&&(ffffff<0||ffffff>999999)){throw"invalid TM '"+time+"'"}}return{hours:hh,minutes:mm,seconds:ss,fractionalSeconds:ffffff}}if(validate){throw"invalid TM '"+time+"'"}return undefined};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}var stringVrs={AE:true,AS:true,AT:false,CS:true,DA:true,DS:true,DT:true,FL:false,FD:false,IS:true,LO:true,LT:true,OB:false,OD:false,OF:false,OW:false,PN:true,SH:true,SL:false,SQ:false,SS:false,ST:true,TM:true,UI:true,UL:false,UN:undefined,UR:true,US:false,UT:true};dicomParser.isStringVr=function(vr){return stringVrs[vr]};dicomParser.isPrivateTag=function(tag){var lastGroupDigit=parseInt(tag[4]);var groupIsOdd=lastGroupDigit%2===1;return groupIsOdd};dicomParser.parsePN=function(personName){if(personName===undefined){return undefined}var stringValues=personName.split("^");return{familyName:stringValues[0],givenName:stringValues[1],middleName:stringValues[2],prefix:stringValues[3],suffix:stringValues[4]}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}var deprecatedNoticeLogged=false;dicomParser.readEncapsulatedPixelData=function(dataSet,pixelDataElement,frame){if(!deprecatedNoticeLogged){deprecatedNoticeLogged=true;if(console&&console.log){console.log("WARNING: dicomParser.readEncapsulatedPixelData() has been deprecated")}}if(dataSet===undefined){throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'dataSet'"}if(pixelDataElement===undefined){throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'element'"}if(frame===undefined){throw"dicomParser.readEncapsulatedPixelData: missing required parameter 'frame'"}if(pixelDataElement.tag!=="x7fe00010"){throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to non pixel data tag (expected tag = x7fe00010'"}if(pixelDataElement.encapsulatedPixelData!==true){throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.hadUndefinedLength!==true){throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.basicOffsetTable===undefined){throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.fragments===undefined){throw"dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data"}if(frame<0){throw"dicomParser.readEncapsulatedPixelData: parameter 'frame' must be >= 0"}if(pixelDataElement.basicOffsetTable.length!==0){return dicomParser.readEncapsulatedImageFrame(dataSet,pixelDataElement,frame)}else{return dicomParser.readEncapsulatedPixelDataFromFragments(dataSet,pixelDataElement,0,pixelDataElement.fragments.length)}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.alloc=function(byteArray,length){if(typeof Buffer!=="undefined"&&byteArray instanceof Buffer){return Buffer.alloc(length)}else if(byteArray instanceof Uint8Array){return new Uint8Array(length)}else{throw"dicomParser.alloc: unknown type for byteArray"}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.bigEndianByteArrayParser={readUint16:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readUint16: position cannot be less than 0"}if(position+2>byteArray.length){throw"bigEndianByteArrayParser.readUint16: attempt to read past end of buffer"}return(byteArray[position]<<8)+byteArray[position+1]},readInt16:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readInt16: position cannot be less than 0"}if(position+2>byteArray.length){throw"bigEndianByteArrayParser.readInt16: attempt to read past end of buffer"}var int16=(byteArray[position]<<8)+byteArray[position+1];if(int16&32768){int16=int16-65535-1}return int16},readUint32:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readUint32: position cannot be less than 0"}if(position+4>byteArray.length){throw"bigEndianByteArrayParser.readUint32: attempt to read past end of buffer"}var uint32=256*(256*(256*byteArray[position]+byteArray[position+1])+byteArray[position+2])+byteArray[position+3];return uint32},readInt32:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readInt32: position cannot be less than 0"}if(position+4>byteArray.length){throw"bigEndianByteArrayParser.readInt32: attempt to read past end of buffer"}var int32=(byteArray[position]<<24)+(byteArray[position+1]<<16)+(byteArray[position+2]<<8)+byteArray[position+3];return int32},readFloat:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readFloat: position cannot be less than 0"}if(position+4>byteArray.length){throw"bigEndianByteArrayParser.readFloat: attempt to read past end of buffer"}var byteArrayForParsingFloat=new Uint8Array(4);byteArrayForParsingFloat[3]=byteArray[position];byteArrayForParsingFloat[2]=byteArray[position+1];byteArrayForParsingFloat[1]=byteArray[position+2];byteArrayForParsingFloat[0]=byteArray[position+3];var floatArray=new Float32Array(byteArrayForParsingFloat.buffer);return floatArray[0]},readDouble:function(byteArray,position){if(position<0){throw"bigEndianByteArrayParser.readDouble: position cannot be less than 0"}if(position+8>byteArray.length){throw"bigEndianByteArrayParser.readDouble: attempt to read past end of buffer"}var byteArrayForParsingFloat=new Uint8Array(8);byteArrayForParsingFloat[7]=byteArray[position];byteArrayForParsingFloat[6]=byteArray[position+1];byteArrayForParsingFloat[5]=byteArray[position+2];byteArrayForParsingFloat[4]=byteArray[position+3];byteArrayForParsingFloat[3]=byteArray[position+4];byteArrayForParsingFloat[2]=byteArray[position+5];byteArrayForParsingFloat[1]=byteArray[position+6];byteArrayForParsingFloat[0]=byteArray[position+7];var floatArray=new Float64Array(byteArrayForParsingFloat.buffer);return floatArray[0]}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.readFixedString=function(byteArray,position,length){if(length<0){throw"dicomParser.readFixedString - length cannot be less than 0"}if(position+length>byteArray.length){throw"dicomParser.readFixedString: attempt to read past end of buffer"}var result="";var byte;for(var i=0;i<length;i++){byte=byteArray[position+i];if(byte===0){position+=length;return result}result+=String.fromCharCode(byte)}return result};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.ByteStream=function(byteArrayParser,byteArray,position){if(byteArrayParser===undefined){throw"dicomParser.ByteStream: missing required parameter 'byteArrayParser'"}if(byteArray===undefined){throw"dicomParser.ByteStream: missing required parameter 'byteArray'"}if(byteArray instanceof Uint8Array===false&&byteArray instanceof Buffer===false){throw"dicomParser.ByteStream: parameter byteArray is not of type Uint8Array or Buffer"}if(position<0){throw"dicomParser.ByteStream: parameter 'position' cannot be less than 0"}if(position>=byteArray.length){throw"dicomParser.ByteStream: parameter 'position' cannot be greater than or equal to 'byteArray' length"}this.byteArrayParser=byteArrayParser;this.byteArray=byteArray;this.position=position?position:0;this.warnings=[]};dicomParser.ByteStream.prototype.seek=function(offset){if(this.position+offset<0){throw"dicomParser.ByteStream.prototype.seek: cannot seek to position < 0"}this.position+=offset};dicomParser.ByteStream.prototype.readByteStream=function(numBytes){if(this.position+numBytes>this.byteArray.length){throw"dicomParser.ByteStream.prototype.readByteStream: readByteStream - buffer overread"}var byteArrayView=dicomParser.sharedCopy(this.byteArray,this.position,numBytes);this.position+=numBytes;return new dicomParser.ByteStream(this.byteArrayParser,byteArrayView)};dicomParser.ByteStream.prototype.readUint16=function(){var result=this.byteArrayParser.readUint16(this.byteArray,this.position);this.position+=2;return result};dicomParser.ByteStream.prototype.readUint32=function(){var result=this.byteArrayParser.readUint32(this.byteArray,this.position);this.position+=4;return result};dicomParser.ByteStream.prototype.readFixedString=function(length){var result=dicomParser.readFixedString(this.byteArray,this.position,length);this.position+=length;return result};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function getByteArrayParser(element,defaultParser){return element.parser!==undefined?element.parser:defaultParser}dicomParser.DataSet=function(byteArrayParser,byteArray,elements){this.byteArrayParser=byteArrayParser;this.byteArray=byteArray;this.elements=elements};dicomParser.DataSet.prototype.uint16=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readUint16(this.byteArray,element.dataOffset+index*2)}return undefined};dicomParser.DataSet.prototype.int16=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readInt16(this.byteArray,element.dataOffset+index*2)}return undefined};dicomParser.DataSet.prototype.uint32=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readUint32(this.byteArray,element.dataOffset+index*4)}return undefined};dicomParser.DataSet.prototype.int32=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readInt32(this.byteArray,element.dataOffset+index*4)}return undefined};dicomParser.DataSet.prototype.float=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readFloat(this.byteArray,element.dataOffset+index*4)}return undefined};dicomParser.DataSet.prototype.double=function(tag,index){var element=this.elements[tag];index=index!==undefined?index:0;if(element&&element.length!==0){return getByteArrayParser(element,this.byteArrayParser).readDouble(this.byteArray,element.dataOffset+index*8)}return undefined};dicomParser.DataSet.prototype.numStringValues=function(tag){var element=this.elements[tag];if(element&&element.length>0){var fixedString=dicomParser.readFixedString(this.byteArray,element.dataOffset,element.length);var numMatching=fixedString.match(/\\/g);if(numMatching===null){return 1}return numMatching.length+1}return undefined};dicomParser.DataSet.prototype.string=function(tag,index){var element=this.elements[tag];if(element&&element.length>0){var fixedString=dicomParser.readFixedString(this.byteArray,element.dataOffset,element.length);if(index>=0){var values=fixedString.split("\\");return values[index].trim()}else{return fixedString.trim()}}return undefined};dicomParser.DataSet.prototype.text=function(tag,index){var element=this.elements[tag];if(element&&element.length>0){var fixedString=dicomParser.readFixedString(this.byteArray,element.dataOffset,element.length);if(index>=0){var values=fixedString.split("\\");return values[index].replace(/ +$/,"")}else{return fixedString.replace(/ +$/,"")}}return undefined};dicomParser.DataSet.prototype.floatString=function(tag,index){var element=this.elements[tag];if(element&&element.length>0){index=index!==undefined?index:0;var value=this.string(tag,index);if(value!==undefined){return parseFloat(value)}}return undefined};dicomParser.DataSet.prototype.intString=function(tag,index){var element=this.elements[tag];if(element&&element.length>0){index=index!==undefined?index:0;var value=this.string(tag,index);if(value!==undefined){return parseInt(value)}}return undefined};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.findAndSetUNElementLength=function(byteStream,element){if(byteStream===undefined){throw"dicomParser.findAndSetUNElementLength: missing required parameter 'byteStream'"}var itemDelimitationItemLength=8;var maxPosition=byteStream.byteArray.length-itemDelimitationItemLength;while(byteStream.position<=maxPosition){var groupNumber;groupNumber=byteStream.readUint16();if(groupNumber===65534){var elementNumber;elementNumber=byteStream.readUint16();if(elementNumber===57565){var itemDelimiterLength;itemDelimiterLength=byteStream.readUint32();if(itemDelimiterLength!==0){byteStream.warnings("encountered non zero length following item delimiter at position"+byteStream.position-4+" while reading element of undefined length with tag ' + element.tag")}element.length=byteStream.position-element.dataOffset;return}}}element.length=byteStream.byteArray.length-element.dataOffset;byteStream.seek(byteStream.byteArray.length-byteStream.position)};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.findEndOfEncapsulatedElement=function(byteStream,element,warnings){if(byteStream===undefined){throw"dicomParser.findEndOfEncapsulatedElement: missing required parameter 'byteStream'"}if(element===undefined){throw"dicomParser.findEndOfEncapsulatedElement: missing required parameter 'element'"}element.encapsulatedPixelData=true;element.basicOffsetTable=[];element.fragments=[];var basicOffsetTableItemTag=dicomParser.readTag(byteStream);if(basicOffsetTableItemTag!=="xfffee000"){throw"dicomParser.findEndOfEncapsulatedElement: basic offset table not found"}var basicOffsetTableItemlength=byteStream.readUint32();var numFragments=basicOffsetTableItemlength/4;for(var i=0;i<numFragments;i++){var offset=byteStream.readUint32();element.basicOffsetTable.push(offset)}var baseOffset=byteStream.position;while(byteStream.position<byteStream.byteArray.length){var tag=dicomParser.readTag(byteStream);var length=byteStream.readUint32();if(tag==="xfffee0dd"){byteStream.seek(length);element.length=byteStream.position-element.dataOffset;return}else if(tag==="xfffee000"){element.fragments.push({offset:byteStream.position-baseOffset-8,position:byteStream.position,length:length})}else{if(warnings){warnings.push("unexpected tag "+tag+" while searching for end of pixel data element with undefined length")}if(length>byteStream.byteArray.length-byteStream.position){length=byteStream.byteArray.length-byteStream.position}element.fragments.push({offset:byteStream.position-baseOffset-8,position:byteStream.position,length:length});byteStream.seek(length);element.length=byteStream.position-element.dataOffset;return}byteStream.seek(length)}if(warnings){warnings.push("pixel data element "+element.tag+" missing sequence delimiter tag xfffee0dd")}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.findItemDelimitationItemAndSetElementLength=function(byteStream,element){if(byteStream===undefined){throw"dicomParser.readDicomElementImplicit: missing required parameter 'byteStream'"}var itemDelimitationItemLength=8;var maxPosition=byteStream.byteArray.length-itemDelimitationItemLength;while(byteStream.position<=maxPosition){var groupNumber=byteStream.readUint16();if(groupNumber===65534){var elementNumber=byteStream.readUint16();if(elementNumber===57357){var itemDelimiterLength=byteStream.readUint32();if(itemDelimiterLength!==0){byteStream.warnings("encountered non zero length following item delimiter at position"+byteStream.position-4+" while reading element of undefined length with tag ' + element.tag")}element.length=byteStream.position-element.dataOffset;return}}}element.length=byteStream.byteArray.length-element.dataOffset;byteStream.seek(byteStream.byteArray.length-byteStream.position)};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.littleEndianByteArrayParser={readUint16:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readUint16: position cannot be less than 0"}if(position+2>byteArray.length){throw"littleEndianByteArrayParser.readUint16: attempt to read past end of buffer"}return byteArray[position]+byteArray[position+1]*256},readInt16:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readInt16: position cannot be less than 0"}if(position+2>byteArray.length){throw"littleEndianByteArrayParser.readInt16: attempt to read past end of buffer"}var int16=byteArray[position]+(byteArray[position+1]<<8);if(int16&32768){int16=int16-65535-1}return int16},readUint32:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readUint32: position cannot be less than 0"}if(position+4>byteArray.length){throw"littleEndianByteArrayParser.readUint32: attempt to read past end of buffer"}var uint32=byteArray[position]+byteArray[position+1]*256+byteArray[position+2]*256*256+byteArray[position+3]*256*256*256;return uint32},readInt32:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readInt32: position cannot be less than 0"}if(position+4>byteArray.length){throw"littleEndianByteArrayParser.readInt32: attempt to read past end of buffer"}var int32=byteArray[position]+(byteArray[position+1]<<8)+(byteArray[position+2]<<16)+(byteArray[position+3]<<24);return int32},readFloat:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readFloat: position cannot be less than 0"}if(position+4>byteArray.length){throw"littleEndianByteArrayParser.readFloat: attempt to read past end of buffer"}var byteArrayForParsingFloat=new Uint8Array(4);byteArrayForParsingFloat[0]=byteArray[position];byteArrayForParsingFloat[1]=byteArray[position+1];byteArrayForParsingFloat[2]=byteArray[position+2];byteArrayForParsingFloat[3]=byteArray[position+3];var floatArray=new Float32Array(byteArrayForParsingFloat.buffer);return floatArray[0]},readDouble:function(byteArray,position){if(position<0){throw"littleEndianByteArrayParser.readDouble: position cannot be less than 0"}if(position+8>byteArray.length){throw"littleEndianByteArrayParser.readDouble: attempt to read past end of buffer"}var byteArrayForParsingFloat=new Uint8Array(8);byteArrayForParsingFloat[0]=byteArray[position];byteArrayForParsingFloat[1]=byteArray[position+1];byteArrayForParsingFloat[2]=byteArray[position+2];byteArrayForParsingFloat[3]=byteArray[position+3];byteArrayForParsingFloat[4]=byteArray[position+4];byteArrayForParsingFloat[5]=byteArray[position+5];byteArrayForParsingFloat[6]=byteArray[position+6];byteArrayForParsingFloat[7]=byteArray[position+7];var floatArray=new Float64Array(byteArrayForParsingFloat.buffer);return floatArray[0]}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.parseDicomDataSetExplicit=function(dataSet,byteStream,maxPosition,options){maxPosition=maxPosition===undefined?byteStream.byteArray.length:maxPosition;options=options||{};if(byteStream===undefined){throw"dicomParser.parseDicomDataSetExplicit: missing required parameter 'byteStream'"}if(maxPosition<byteStream.position||maxPosition>byteStream.byteArray.length){throw"dicomParser.parseDicomDataSetExplicit: invalid value for parameter 'maxPosition'"}var elements=dataSet.elements;while(byteStream.position<maxPosition){var element=dicomParser.readDicomElementExplicit(byteStream,dataSet.warnings,options.untilTag);elements[element.tag]=element;if(element.tag===options.untilTag){return}}if(byteStream.position>maxPosition){throw"dicomParser:parseDicomDataSetExplicit: buffer overrun"}};dicomParser.parseDicomDataSetImplicit=function(dataSet,byteStream,maxPosition,options){maxPosition=maxPosition===undefined?dataSet.byteArray.length:maxPosition;options=options||{};if(byteStream===undefined){throw"dicomParser.parseDicomDataSetImplicit: missing required parameter 'byteStream'"}if(maxPosition<byteStream.position||maxPosition>byteStream.byteArray.length){throw"dicomParser.parseDicomDataSetImplicit: invalid value for parameter 'maxPosition'"}var elements=dataSet.elements;while(byteStream.position<maxPosition){var element=dicomParser.readDicomElementImplicit(byteStream,options.untilTag,options.vrCallback);elements[element.tag]=element;if(element.tag===options.untilTag){return}}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function getDataLengthSizeInBytesForVR(vr){if(vr==="OB"||vr==="OW"||vr==="SQ"||vr==="OF"||vr==="UT"||vr==="UN"){return 4}else{return 2}}

dicomParser.readDicomElementExplicit=function(byteStream,warnings,untilTag){if(byteStream===undefined){throw"dicomParser.readDicomElementExplicit: missing required parameter 'byteStream'"}var element={tag:dicomParser.readTag(byteStream),vr:byteStream.readFixedString(2)};var dataLengthSizeBytes=getDataLengthSizeInBytesForVR(element.vr);if(dataLengthSizeBytes===2){element.length=byteStream.readUint16();element.dataOffset=byteStream.position}else{byteStream.seek(2);element.length=byteStream.readUint32();element.dataOffset=byteStream.position}if(element.length===4294967295){element.hadUndefinedLength=true}if(element.tag===untilTag){return element}if(element.vr==="SQ"){dicomParser.readSequenceItemsExplicit(byteStream,element,warnings);return element}if(element.length===4294967295){if(element.tag==="x7fe00010"){dicomParser.findEndOfEncapsulatedElement(byteStream,element,warnings);return element}else if(element.vr==="UN"){dicomParser.findAndSetUNElementLength(byteStream,element);return element}else{dicomParser.readSequenceItemsImplicit(byteStream,element);return element}}byteStream.seek(element.length);return element};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function isSequence(element,byteStream,vrCallback){if(typeof vrCallback!=="undefined"){return vrCallback(element.tag)==="SQ"}if(byteStream.position+4<=byteStream.byteArray.length){var nextTag=dicomParser.readTag(byteStream);byteStream.seek(-4);return nextTag==="xfffee000"||nextTag==="xfffee0dd"}byteStream.warnings.push("eof encountered before finding sequence item tag or sequence delimiter tag in peeking to determine VR");return false}dicomParser.readDicomElementImplicit=function(byteStream,untilTag,vrCallback){if(byteStream===undefined){throw"dicomParser.readDicomElementImplicit: missing required parameter 'byteStream'"}var element={tag:dicomParser.readTag(byteStream),length:byteStream.readUint32(),dataOffset:byteStream.position};if(element.length===4294967295){element.hadUndefinedLength=true}if(element.tag===untilTag){return element}if(isSequence(element,byteStream,vrCallback)){dicomParser.readSequenceItemsImplicit(byteStream,element);return element}if(element.hadUndefinedLength){dicomParser.findItemDelimitationItemAndSetElementLength(byteStream,element);return element}byteStream.seek(element.length);return element};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function findFragmentIndexWithOffset(fragments,offset){for(var i=0;i<fragments.length;i++){if(fragments[i].offset===offset){return i}}}function calculateNumberOfFragmentsForFrame(frameIndex,basicOffsetTable,fragments,startFragmentIndex){if(frameIndex===basicOffsetTable.length-1){return fragments.length-startFragmentIndex}var nextFrameOffset=basicOffsetTable[frameIndex+1];for(var i=startFragmentIndex+1;i<fragments.length;i++){if(fragments[i].offset===nextFrameOffset){return i-startFragmentIndex}}throw"dicomParser.calculateNumberOfFragmentsForFrame: could not find fragment with offset matching basic offset table"}dicomParser.readEncapsulatedImageFrame=function(dataSet,pixelDataElement,frameIndex,basicOffsetTable,fragments){basicOffsetTable=basicOffsetTable||pixelDataElement.basicOffsetTable;fragments=fragments||pixelDataElement.fragments;if(dataSet===undefined){throw"dicomParser.readEncapsulatedImageFrame: missing required parameter 'dataSet'"}if(pixelDataElement===undefined){throw"dicomParser.readEncapsulatedImageFrame: missing required parameter 'pixelDataElement'"}if(frameIndex===undefined){throw"dicomParser.readEncapsulatedImageFrame: missing required parameter 'frameIndex'"}if(basicOffsetTable===undefined){throw"dicomParser.readEncapsulatedImageFrame: parameter 'pixelDataElement' does not have basicOffsetTable"}if(pixelDataElement.tag!=="x7fe00010"){throw"dicomParser.readEncapsulatedImageFrame: parameter 'pixelDataElement' refers to non pixel data tag (expected tag = x7fe00010'"}if(pixelDataElement.encapsulatedPixelData!==true){throw"dicomParser.readEncapsulatedImageFrame: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.hadUndefinedLength!==true){throw"dicomParser.readEncapsulatedImageFrame: parameter 'pixelDataElement' refers to pixel data element that does not have undefined length"}if(pixelDataElement.fragments===undefined){throw"dicomParser.readEncapsulatedImageFrame: parameter 'pixelDataElement' refers to pixel data element that does not have fragments"}if(basicOffsetTable.length===0){throw"dicomParser.readEncapsulatedImageFrame: basicOffsetTable has zero entries"}if(frameIndex<0){throw"dicomParser.readEncapsulatedImageFrame: parameter 'frameIndex' must be >= 0"}if(frameIndex>=basicOffsetTable.length){throw"dicomParser.readEncapsulatedImageFrame: parameter 'frameIndex' must be < basicOffsetTable.length"}var offset=basicOffsetTable[frameIndex];var startFragmentIndex=findFragmentIndexWithOffset(fragments,offset);if(startFragmentIndex===undefined){throw"dicomParser.readEncapsulatedImageFrame: unable to find fragment that matches basic offset table entry"}var numFragments=calculateNumberOfFragmentsForFrame(frameIndex,basicOffsetTable,fragments,startFragmentIndex);return dicomParser.readEncapsulatedPixelDataFromFragments(dataSet,pixelDataElement,startFragmentIndex,numFragments,fragments)};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function calculateBufferSize(fragments,startFragment,numFragments){var bufferSize=0;for(var i=startFragment;i<startFragment+numFragments;i++){bufferSize+=fragments[i].length}return bufferSize}dicomParser.readEncapsulatedPixelDataFromFragments=function(dataSet,pixelDataElement,startFragmentIndex,numFragments,fragments){numFragments=numFragments||1;fragments=fragments||pixelDataElement.fragments;if(dataSet===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: missing required parameter 'dataSet'"}if(pixelDataElement===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: missing required parameter 'pixelDataElement'"}if(startFragmentIndex===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: missing required parameter 'startFragmentIndex'"}if(numFragments===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: missing required parameter 'numFragments'"}if(pixelDataElement.tag!=="x7fe00010"){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to non pixel data tag (expected tag = x7fe00010'"}if(pixelDataElement.encapsulatedPixelData!==true){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.hadUndefinedLength!==true){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.basicOffsetTable===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.fragments===undefined){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(pixelDataElement.fragments.length<=0){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'pixelDataElement' refers to pixel data element that does not have encapsulated pixel data"}if(startFragmentIndex<0){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragmentIndex' must be >= 0"}if(startFragmentIndex>=pixelDataElement.fragments.length){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragmentIndex' must be < number of fragments"}if(numFragments<1){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'numFragments' must be > 0"}if(startFragmentIndex+numFragments>pixelDataElement.fragments.length){throw"dicomParser.readEncapsulatedPixelDataFromFragments: parameter 'startFragment' + 'numFragments' < number of fragments"}var byteStream=new dicomParser.ByteStream(dataSet.byteArrayParser,dataSet.byteArray,pixelDataElement.dataOffset);var basicOffsetTable=dicomParser.readSequenceItem(byteStream);if(basicOffsetTable.tag!=="xfffee000"){throw"dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000"}byteStream.seek(basicOffsetTable.length);var fragmentZeroPosition=byteStream.position;var fragmentHeaderSize=8;if(numFragments===1){return dicomParser.sharedCopy(byteStream.byteArray,fragmentZeroPosition+fragments[startFragmentIndex].offset+fragmentHeaderSize,fragments[startFragmentIndex].length)}var bufferSize=calculateBufferSize(fragments,startFragmentIndex,numFragments);var pixelData=dicomParser.alloc(byteStream.byteArray,bufferSize);var pixelDataIndex=0;for(var i=startFragmentIndex;i<startFragmentIndex+numFragments;i++){var fragmentOffset=fragmentZeroPosition+fragments[i].offset+fragmentHeaderSize;for(var j=0;j<fragments[i].length;j++){pixelData[pixelDataIndex++]=byteStream.byteArray[fragmentOffset++]}}return pixelData};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){if(dicomParser===undefined){dicomParser={}}dicomParser.readPart10Header=function(byteArray,options){if(byteArray===undefined){throw"dicomParser.readPart10Header: missing required parameter 'byteArray'"}var littleEndianByteStream=new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser,byteArray);function readPrefix(){littleEndianByteStream.seek(128);var prefix=littleEndianByteStream.readFixedString(4);if(prefix!=="DICM"){throw"dicomParser.readPart10Header: DICM prefix not found at location 132 - this is not a valid DICOM P10 file."}}function readTheHeader(){readPrefix();var warnings=[];var elements={};while(littleEndianByteStream.position<littleEndianByteStream.byteArray.length){var position=littleEndianByteStream.position;var element=dicomParser.readDicomElementExplicit(littleEndianByteStream,warnings);if(element.tag>"x0002ffff"){littleEndianByteStream.position=position;break}element.parser=dicomParser.littleEndianByteArrayParser;elements[element.tag]=element}var metaHeaderDataSet=new dicomParser.DataSet(littleEndianByteStream.byteArrayParser,littleEndianByteStream.byteArray,elements);metaHeaderDataSet.warnings=littleEndianByteStream.warnings;metaHeaderDataSet.position=littleEndianByteStream.position;return metaHeaderDataSet}return readTheHeader()};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function readDicomDataSetExplicitUndefinedLength(byteStream,warnings){var elements={};while(byteStream.position<byteStream.byteArray.length){var element=dicomParser.readDicomElementExplicit(byteStream,warnings);elements[element.tag]=element;if(element.tag==="xfffee00d"){return new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,elements)}}warnings.push("eof encountered before finding item delimiter tag while reading sequence item of undefined length");return new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,elements)}function readSequenceItemExplicit(byteStream,warnings){var item=dicomParser.readSequenceItem(byteStream);if(item.length===4294967295){item.hadUndefinedLength=true;item.dataSet=readDicomDataSetExplicitUndefinedLength(byteStream,warnings);item.length=byteStream.position-item.dataOffset}else{item.dataSet=new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,{});dicomParser.parseDicomDataSetExplicit(item.dataSet,byteStream,byteStream.position+item.length)}return item}function readSQElementUndefinedLengthExplicit(byteStream,element,warnings){while(byteStream.position+4<=byteStream.byteArray.length){var nextTag=dicomParser.readTag(byteStream);byteStream.seek(-4);if(nextTag==="xfffee0dd"){element.length=byteStream.position-element.dataOffset;byteStream.seek(8);return element}var item=readSequenceItemExplicit(byteStream,warnings);element.items.push(item)}warnings.push("eof encountered before finding sequence delimitation tag while reading sequence of undefined length");element.length=byteStream.position-element.dataOffset}function readSQElementKnownLengthExplicit(byteStream,element,warnings){var maxPosition=element.dataOffset+element.length;while(byteStream.position<maxPosition){var item=readSequenceItemExplicit(byteStream,warnings);element.items.push(item)}}dicomParser.readSequenceItemsExplicit=function(byteStream,element,warnings){if(byteStream===undefined){throw"dicomParser.readSequenceItemsExplicit: missing required parameter 'byteStream'"}if(element===undefined){throw"dicomParser.readSequenceItemsExplicit: missing required parameter 'element'"}element.items=[];if(element.length===4294967295){readSQElementUndefinedLengthExplicit(byteStream,element,warnings)}else{readSQElementKnownLengthExplicit(byteStream,element,warnings)}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}function readDicomDataSetImplicitUndefinedLength(byteStream,vrCallback){var elements={};while(byteStream.position<byteStream.byteArray.length){var element=dicomParser.readDicomElementImplicit(byteStream,undefined,vrCallback);elements[element.tag]=element;if(element.tag==="xfffee00d"){return new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,elements)}}byteStream.warnings.push("eof encountered before finding sequence item delimiter in sequence item of undefined length");return new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,elements)}function readSequenceItemImplicit(byteStream,vrCallback){var item=dicomParser.readSequenceItem(byteStream);if(item.length===4294967295){item.hadUndefinedLength=true;item.dataSet=readDicomDataSetImplicitUndefinedLength(byteStream,vrCallback);item.length=byteStream.position-item.dataOffset}else{item.dataSet=new dicomParser.DataSet(byteStream.byteArrayParser,byteStream.byteArray,{});dicomParser.parseDicomDataSetImplicit(item.dataSet,byteStream,byteStream.position+item.length,{vrCallback:vrCallback})}return item}function readSQElementUndefinedLengthImplicit(byteStream,element,vrCallback){while(byteStream.position+4<=byteStream.byteArray.length){var nextTag=dicomParser.readTag(byteStream);byteStream.seek(-4);if(nextTag==="xfffee0dd"){element.length=byteStream.position-element.dataOffset;byteStream.seek(8);return element}var item=readSequenceItemImplicit(byteStream,vrCallback);element.items.push(item)}byteStream.warnings.push("eof encountered before finding sequence delimiter in sequence of undefined length");element.length=byteStream.byteArray.length-element.dataOffset}function readSQElementKnownLengthImplicit(byteStream,element,vrCallback){var maxPosition=element.dataOffset+element.length;while(byteStream.position<maxPosition){var item=readSequenceItemImplicit(byteStream,vrCallback);element.items.push(item)}}dicomParser.readSequenceItemsImplicit=function(byteStream,element,vrCallback){if(byteStream===undefined){throw"dicomParser.readSequenceItemsImplicit: missing required parameter 'byteStream'"}if(element===undefined){throw"dicomParser.readSequenceItemsImplicit: missing required parameter 'element'"}element.items=[];if(element.length===4294967295){readSQElementUndefinedLengthImplicit(byteStream,element,vrCallback)}else{readSQElementKnownLengthImplicit(byteStream,element,vrCallback)}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.readSequenceItem=function(byteStream){if(byteStream===undefined){throw"dicomParser.readSequenceItem: missing required parameter 'byteStream'"}var element={tag:dicomParser.readTag(byteStream),length:byteStream.readUint32(),dataOffset:byteStream.position};if(element.tag!=="xfffee000"){var startPosition=byteStream.position;throw"dicomParser.readSequenceItem: item tag (FFFE,E000) not found at offset "+startPosition}return element};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.readTag=function(byteStream){if(byteStream===undefined){throw"dicomParser.readTag: missing required parameter 'byteStream'"}var groupNumber=byteStream.readUint16()*256*256;var elementNumber=byteStream.readUint16();var tag="x"+("00000000"+(groupNumber+elementNumber).toString(16)).substr(-8);return tag};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.sharedCopy=function(byteArray,byteOffset,length){if(typeof Buffer!=="undefined"&&byteArray instanceof Buffer){return byteArray.slice(byteOffset,byteOffset+length)}else if(byteArray instanceof Uint8Array){return new Uint8Array(byteArray.buffer,byteArray.byteOffset+byteOffset,length)}else{throw"dicomParser.from: unknown type for byteArray"}};return dicomParser}(dicomParser);var dicomParser=function(dicomParser){"use strict";if(dicomParser===undefined){dicomParser={}}dicomParser.version="1.7.3";return dicomParser}(dicomParser);return dicomParser})}).call(this,require("buffer").Buffer)},{buffer:20,zlib:18}],26:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],27:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],28:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],29:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],30:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.ComponentSpec=jpeg.lossless.ComponentSpec||function(){this.hSamp=0;this.quantTableSel=0;this.vSamp=0};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.ComponentSpec}},{}],31:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.DataStream=jpeg.lossless.DataStream||function(data,offset,length){this.buffer=new DataView(data,offset,length);this.index=0};jpeg.lossless.DataStream.prototype.get16=function(){var value=this.buffer.getUint16(this.index,false);this.index+=2;return value};jpeg.lossless.DataStream.prototype.get8=function(){var value=this.buffer.getUint8(this.index);this.index+=1;return value};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.DataStream}},{}],32:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.HuffmanTable=jpeg.lossless.HuffmanTable||(typeof require!=="undefined"?require("./huffman-table.js"):null);jpeg.lossless.QuantizationTable=jpeg.lossless.QuantizationTable||(typeof require!=="undefined"?require("./quantization-table.js"):null);jpeg.lossless.ScanHeader=jpeg.lossless.ScanHeader||(typeof require!=="undefined"?require("./scan-header.js"):null);jpeg.lossless.FrameHeader=jpeg.lossless.FrameHeader||(typeof require!=="undefined"?require("./frame-header.js"):null);jpeg.lossless.Utils=jpeg.lossless.Utils||(typeof require!=="undefined"?require("./utils.js"):null);jpeg.lossless.Decoder=jpeg.lossless.Decoder||function(buffer,numBytes){this.buffer=buffer;this.frame=new jpeg.lossless.FrameHeader;this.huffTable=new jpeg.lossless.HuffmanTable;this.quantTable=new jpeg.lossless.QuantizationTable;this.scan=new jpeg.lossless.ScanHeader;this.DU=jpeg.lossless.Utils.createArray(10,4,64);this.HuffTab=jpeg.lossless.Utils.createArray(4,2,50*256);this.IDCT_Source=[];this.nBlock=[];this.acTab=jpeg.lossless.Utils.createArray(10,1);this.dcTab=jpeg.lossless.Utils.createArray(10,1);this.qTab=jpeg.lossless.Utils.createArray(10,1);this.marker=0;this.markerIndex=0;this.numComp=0;this.restartInterval=0;this.selection=0;this.xDim=0;this.yDim=0;this.xLoc=0;this.yLoc=0;this.numBytes=0;this.outputData=null;this.restarting=false;this.mask=0;if(typeof numBytes!=="undefined"){this.numBytes=numBytes}};jpeg.lossless.Decoder.IDCT_P=[0,5,40,16,45,2,7,42,21,56,8,61,18,47,1,4,41,23,58,13,32,24,37,10,63,17,44,3,6,43,20,57,15,34,29,48,53,26,39,9,60,19,46,22,59,12,33,31,50,55,25,36,11,62,14,35,28,49,52,27,38,30,51,54];jpeg.lossless.Decoder.TABLE=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63];jpeg.lossless.Decoder.MAX_HUFFMAN_SUBTREE=50;jpeg.lossless.Decoder.MSB=2147483648;jpeg.lossless.Decoder.RESTART_MARKER_BEGIN=65488;jpeg.lossless.Decoder.RESTART_MARKER_END=65495;jpeg.lossless.Decoder.prototype.decompress=function(buffer,offset,length){return this.decode(buffer,offset,length).buffer};jpeg.lossless.Decoder.prototype.decode=function(buffer,offset,length,numBytes){var current,scanNum=0,pred=[],i,compN,temp=[],index=[],mcuNum;if(typeof buffer!=="undefined"){this.buffer=buffer}if(typeof numBytes!=="undefined"){this.numBytes=numBytes}this.stream=new jpeg.lossless.DataStream(this.buffer,offset,length);this.buffer=null;this.xLoc=0;this.yLoc=0;current=this.stream.get16();if(current!==65496){throw new Error("Not a JPEG file")}current=this.stream.get16();while(current>>4!==4092||current===65476){switch(current){case 65476:this.huffTable.read(this.stream,this.HuffTab);break;case 65484:throw new Error("Program doesn't support arithmetic coding. (format throw new IOException)");case 65499:this.quantTable.read(this.stream,jpeg.lossless.Decoder.TABLE);break;case 65501:this.restartInterval=this.readNumber();break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:this.readApp();break;case 65534:this.readComment();break;default:if(current>>8!==255){throw new Error("ERROR: format throw new IOException! (decode)")}}current=this.stream.get16()}if(current<65472||current>65479){throw new Error("ERROR: could not handle arithmetic code!")}this.frame.read(this.stream);current=this.stream.get16();do{while(current!==65498){switch(current){case 65476:this.huffTable.read(this.stream,this.HuffTab);break;case 65484:throw new Error("Program doesn't support arithmetic coding. (format throw new IOException)");case 65499:this.quantTable.read(this.stream,jpeg.lossless.Decoder.TABLE);break;case 65501:this.restartInterval=this.readNumber();break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:this.readApp();break;case 65534:this.readComment();break;default:if(current>>8!==255){throw new Error("ERROR: format throw new IOException! (Parser.decode)")}}current=this.stream.get16()}this.precision=this.frame.precision;this.components=this.frame.components;if(!this.numBytes){this.numBytes=parseInt(Math.ceil(this.precision/8))}if(this.numBytes==1){this.mask=255}else{this.mask=65535}this.scan.read(this.stream);this.numComp=this.scan.numComp;this.selection=this.scan.selection;if(this.numBytes===1){if(this.numComp===3){this.getter=this.getValueRGB;this.setter=this.setValueRGB;this.output=this.outputRGB}else{this.getter=this.getValue8;this.setter=this.setValue8;this.output=this.outputSingle}}else{this.getter=this.getValue16;this.setter=this.setValue16;this.output=this.outputSingle}switch(this.selection){case 2:this.selector=this.select2;break;case 3:this.selector=this.select3;break;case 4:this.selector=this.select4;break;case 5:this.selector=this.select5;break;case 6:this.selector=this.select6;break;case 7:this.selector=this.select7;break;default:this.selector=this.select1;break}this.scanComps=this.scan.components;this.quantTables=this.quantTable.quantTables;for(i=0;i<this.numComp;i+=1){compN=this.scanComps[i].scanCompSel;this.qTab[i]=this.quantTables[this.components[compN].quantTableSel];this.nBlock[i]=this.components[compN].vSamp*this.components[compN].hSamp;this.dcTab[i]=this.HuffTab[this.scanComps[i].dcTabSel][0];this.acTab[i]=this.HuffTab[this.scanComps[i].acTabSel][1]}this.xDim=this.frame.dimX;this.yDim=this.frame.dimY;this.outputData=new DataView(new ArrayBuffer(this.xDim*this.yDim*this.numBytes*this.numComp));scanNum+=1;while(true){temp[0]=0;index[0]=0;for(i=0;i<10;i+=1){pred[i]=1<<this.precision-1}if(this.restartInterval===0){current=this.decodeUnit(pred,temp,index);while(current===0&&(this.xLoc<this.xDim&&this.yLoc<this.yDim)){this.output(pred);current=this.decodeUnit(pred,temp,index)}break}for(mcuNum=0;mcuNum<this.restartInterval;mcuNum+=1){this.restarting=mcuNum==0;current=this.decodeUnit(pred,temp,index);this.output(pred);if(current!==0){break}}if(current===0){if(this.markerIndex!==0){current=65280|this.marker;this.markerIndex=0}else{current=this.stream.get16()}}if(!(current>=jpeg.lossless.Decoder.RESTART_MARKER_BEGIN&&current<=jpeg.lossless.Decoder.RESTART_MARKER_END)){break} }if(current===65500&&scanNum===1){this.readNumber();current=this.stream.get16()}}while(current!==65497&&(this.xLoc<this.xDim&&this.yLoc<this.yDim)&&scanNum===0);return this.outputData};jpeg.lossless.Decoder.prototype.decodeUnit=function(prev,temp,index){if(this.numComp==1){return this.decodeSingle(prev,temp,index)}else if(this.numComp==3){return this.decodeRGB(prev,temp,index)}else{return-1}};jpeg.lossless.Decoder.prototype.select1=function(compOffset){return this.getPreviousX(compOffset)};jpeg.lossless.Decoder.prototype.select2=function(compOffset){return this.getPreviousY(compOffset)};jpeg.lossless.Decoder.prototype.select3=function(compOffset){return this.getPreviousXY(compOffset)};jpeg.lossless.Decoder.prototype.select4=function(compOffset){return this.getPreviousX(compOffset)+this.getPreviousY(compOffset)-this.getPreviousXY(compOffset)};jpeg.lossless.Decoder.prototype.select5=function(compOffset){return this.getPreviousX(compOffset)+(this.getPreviousY(compOffset)-this.getPreviousXY(compOffset)>>1)};jpeg.lossless.Decoder.prototype.select6=function(compOffset){return this.getPreviousY(compOffset)+(this.getPreviousX(compOffset)-this.getPreviousXY(compOffset)>>1)};jpeg.lossless.Decoder.prototype.select7=function(compOffset){return(this.getPreviousX(compOffset)+this.getPreviousY(compOffset))/2};jpeg.lossless.Decoder.prototype.decodeRGB=function(prev,temp,index){var value,actab,dctab,qtab,ctrC,i,k,j;prev[0]=this.selector(0);prev[1]=this.selector(1);prev[2]=this.selector(2);for(ctrC=0;ctrC<this.numComp;ctrC+=1){qtab=this.qTab[ctrC];actab=this.acTab[ctrC];dctab=this.dcTab[ctrC];for(i=0;i<this.nBlock[ctrC];i+=1){for(k=0;k<this.IDCT_Source.length;k+=1){this.IDCT_Source[k]=0}value=this.getHuffmanValue(dctab,temp,index);if(value>=65280){return value}prev[ctrC]=this.IDCT_Source[0]=prev[ctrC]+this.getn(index,value,temp,index);this.IDCT_Source[0]*=qtab[0];for(j=1;j<64;j+=1){value=this.getHuffmanValue(actab,temp,index);if(value>=65280){return value}j+=value>>4;if((value&15)===0){if(value>>4===0){break}}else{this.IDCT_Source[jpeg.lossless.Decoder.IDCT_P[j]]=this.getn(index,value&15,temp,index)*qtab[j]}}}}return 0};jpeg.lossless.Decoder.prototype.decodeSingle=function(prev,temp,index){var value,i,n,nRestart;if(this.restarting){this.restarting=false;prev[0]=1<<this.frame.precision-1}else{prev[0]=this.selector()}for(i=0;i<this.nBlock[0];i+=1){value=this.getHuffmanValue(this.dcTab[0],temp,index);if(value>=65280){return value}n=this.getn(prev,value,temp,index);nRestart=n>>8;if(nRestart>=jpeg.lossless.Decoder.RESTART_MARKER_BEGIN&&nRestart<=jpeg.lossless.Decoder.RESTART_MARKER_END){return nRestart}prev[0]+=n}return 0};jpeg.lossless.Decoder.prototype.getHuffmanValue=function(table,temp,index){var code,input,mask;mask=65535;if(index[0]<8){temp[0]<<=8;input=this.stream.get8();if(input===255){this.marker=this.stream.get8();if(this.marker!==0){this.markerIndex=9}}temp[0]|=input}else{index[0]-=8}code=table[temp[0]>>index[0]];if((code&jpeg.lossless.Decoder.MSB)!==0){if(this.markerIndex!==0){this.markerIndex=0;return 65280|this.marker}temp[0]&=mask>>16-index[0];temp[0]<<=8;input=this.stream.get8();if(input===255){this.marker=this.stream.get8();if(this.marker!==0){this.markerIndex=9}}temp[0]|=input;code=table[(code&255)*256+(temp[0]>>index[0])];index[0]+=8}index[0]+=8-(code>>8);if(index[0]<0){throw new Error("index="+index[0]+" temp="+temp[0]+" code="+code+" in HuffmanValue()")}if(index[0]<this.markerIndex){this.markerIndex=0;return 65280|this.marker}temp[0]&=mask>>16-index[0];return code&255};jpeg.lossless.Decoder.prototype.getn=function(PRED,n,temp,index){var result,one,n_one,mask,input;one=1;n_one=-1;mask=65535;if(n===0){return 0}if(n===16){if(PRED[0]>=0){return-32768}else{return 32768}}index[0]-=n;if(index[0]>=0){if(index[0]<this.markerIndex&&!this.isLastPixel()){this.markerIndex=0;return(65280|this.marker)<<8}result=temp[0]>>index[0];temp[0]&=mask>>16-index[0]}else{temp[0]<<=8;input=this.stream.get8();if(input===255){this.marker=this.stream.get8();if(this.marker!==0){this.markerIndex=9}}temp[0]|=input;index[0]+=8;if(index[0]<0){if(this.markerIndex!==0){this.markerIndex=0;return(65280|this.marker)<<8}temp[0]<<=8;input=this.stream.get8();if(input===255){this.marker=this.stream.get8();if(this.marker!==0){this.markerIndex=9}}temp[0]|=input;index[0]+=8}if(index[0]<0){throw new Error("index="+index[0]+" in getn()")}if(index[0]<this.markerIndex){this.markerIndex=0;return(65280|this.marker)<<8}result=temp[0]>>index[0];temp[0]&=mask>>16-index[0]}if(result<one<<n-1){result+=(n_one<<n)+1}return result};jpeg.lossless.Decoder.prototype.getPreviousX=function(compOffset){if(this.xLoc>0){return this.getter(this.yLoc*this.xDim+this.xLoc-1,compOffset)}else if(this.yLoc>0){return this.getPreviousY(compOffset)}else{return 1<<this.frame.precision-1}};jpeg.lossless.Decoder.prototype.getPreviousXY=function(compOffset){if(this.xLoc>0&&this.yLoc>0){return this.getter((this.yLoc-1)*this.xDim+this.xLoc-1,compOffset)}else{return this.getPreviousY(compOffset)}};jpeg.lossless.Decoder.prototype.getPreviousY=function(compOffset){if(this.yLoc>0){return this.getter((this.yLoc-1)*this.xDim+this.xLoc,compOffset)}else{return this.getPreviousX(compOffset)}};jpeg.lossless.Decoder.prototype.isLastPixel=function(){return this.xLoc===this.xDim-1&&this.yLoc===this.yDim-1};jpeg.lossless.Decoder.prototype.outputSingle=function(PRED){if(this.xLoc<this.xDim&&this.yLoc<this.yDim){this.setter(this.yLoc*this.xDim+this.xLoc,this.mask&PRED[0]);this.xLoc+=1;if(this.xLoc>=this.xDim){this.yLoc+=1;this.xLoc=0}}};jpeg.lossless.Decoder.prototype.outputRGB=function(PRED){var offset=this.yLoc*this.xDim+this.xLoc;if(this.xLoc<this.xDim&&this.yLoc<this.yDim){this.setter(offset,PRED[0],0);this.setter(offset,PRED[1],1);this.setter(offset,PRED[2],2);this.xLoc+=1;if(this.xLoc>=this.xDim){this.yLoc+=1;this.xLoc=0}}};jpeg.lossless.Decoder.prototype.setValue16=function(index,val){this.outputData.setInt16(index*2,val,true)};jpeg.lossless.Decoder.prototype.getValue16=function(index){return this.outputData.getInt16(index*2,true)};jpeg.lossless.Decoder.prototype.setValue8=function(index,val){this.outputData.setInt8(index,val)};jpeg.lossless.Decoder.prototype.getValue8=function(index){return this.outputData.getInt8(index)};jpeg.lossless.Decoder.prototype.setValueRGB=function(index,val,compOffset){this.outputData.setUint8(index*3+compOffset,val)};jpeg.lossless.Decoder.prototype.getValueRGB=function(index,compOffset){return this.outputData.getUint8(index*3+compOffset)};jpeg.lossless.Decoder.prototype.readApp=function(){var count=0,length=this.stream.get16();count+=2;while(count<length){this.stream.get8();count+=1}return length};jpeg.lossless.Decoder.prototype.readComment=function(){var sb="",count=0,length;length=this.stream.get16();count+=2;while(count<length){sb+=this.stream.get8();count+=1}return sb};jpeg.lossless.Decoder.prototype.readNumber=function(){var Ld=this.stream.get16();if(Ld!==4){throw new Error("ERROR: Define number format throw new IOException [Ld!=4]")}return this.stream.get16()};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.Decoder}},{"./data-stream.js":31,"./frame-header.js":33,"./huffman-table.js":34,"./quantization-table.js":36,"./scan-header.js":38,"./utils.js":39}],33:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.ComponentSpec=jpeg.lossless.ComponentSpec||(typeof require!=="undefined"?require("./component-spec.js"):null);jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.FrameHeader=jpeg.lossless.FrameHeader||function(){this.components=[];this.dimX=0;this.dimY=0;this.numComp=0;this.precision=0};jpeg.lossless.FrameHeader.prototype.read=function(data){var count=0,length,i,c,temp;length=data.get16();count+=2;this.precision=data.get8();count+=1;this.dimY=data.get16();count+=2;this.dimX=data.get16();count+=2;this.numComp=data.get8();count+=1;for(i=1;i<=this.numComp;i+=1){if(count>length){throw new Error("ERROR: frame format error")}c=data.get8();count+=1;if(count>=length){throw new Error("ERROR: frame format error [c>=Lf]")}temp=data.get8();count+=1;if(!this.components[c]){this.components[c]=new jpeg.lossless.ComponentSpec}this.components[c].hSamp=temp>>4;this.components[c].vSamp=temp&15;this.components[c].quantTableSel=data.get8();count+=1}if(count!==length){throw new Error("ERROR: frame format error [Lf!=count]")}return 1};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.FrameHeader}},{"./component-spec.js":30,"./data-stream.js":31}],34:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.Utils=jpeg.lossless.Utils||(typeof require!=="undefined"?require("./utils.js"):null);jpeg.lossless.HuffmanTable=jpeg.lossless.HuffmanTable||function(){this.l=jpeg.lossless.Utils.createArray(4,2,16);this.th=[];this.v=jpeg.lossless.Utils.createArray(4,2,16,200);this.tc=jpeg.lossless.Utils.createArray(4,2);this.tc[0][0]=0;this.tc[1][0]=0;this.tc[2][0]=0;this.tc[3][0]=0;this.tc[0][1]=0;this.tc[1][1]=0;this.tc[2][1]=0;this.tc[3][1]=0;this.th[0]=0;this.th[1]=0;this.th[2]=0;this.th[3]=0};jpeg.lossless.HuffmanTable.MSB=2147483648;jpeg.lossless.HuffmanTable.prototype.read=function(data,HuffTab){var count=0,length,temp,t,c,i,j;length=data.get16();count+=2;while(count<length){temp=data.get8();count+=1;t=temp&15;if(t>3){throw new Error("ERROR: Huffman table ID > 3")}c=temp>>4;if(c>2){throw new Error("ERROR: Huffman table [Table class > 2 ]")}this.th[t]=1;this.tc[t][c]=1;for(i=0;i<16;i+=1){this.l[t][c][i]=data.get8();count+=1}for(i=0;i<16;i+=1){for(j=0;j<this.l[t][c][i];j+=1){if(count>length){throw new Error("ERROR: Huffman table format error [count>Lh]")}this.v[t][c][i][j]=data.get8();count+=1}}}if(count!==length){throw new Error("ERROR: Huffman table format error [count!=Lf]")}for(i=0;i<4;i+=1){for(j=0;j<2;j+=1){if(this.tc[i][j]!==0){this.buildHuffTable(HuffTab[i][j],this.l[i][j],this.v[i][j])}}}return 1};jpeg.lossless.HuffmanTable.prototype.buildHuffTable=function(tab,L,V){var currentTable,temp,k,i,j,n;temp=256;k=0;for(i=0;i<8;i+=1){for(j=0;j<L[i];j+=1){for(n=0;n<temp>>i+1;n+=1){tab[k]=V[i][j]|i+1<<8;k+=1}}}for(i=1;k<256;i+=1,k+=1){tab[k]=i|jpeg.lossless.HuffmanTable.MSB}currentTable=1;k=0;for(i=8;i<16;i+=1){for(j=0;j<L[i];j+=1){for(n=0;n<temp>>i-7;n+=1){tab[currentTable*256+k]=V[i][j]|i+1<<8;k+=1}if(k>=256){if(k>256){throw new Error("ERROR: Huffman table error(1)!")}k=0;currentTable+=1}}}};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.HuffmanTable}},{"./data-stream.js":31,"./utils.js":39}],35:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.ComponentSpec=jpeg.lossless.ComponentSpec||(typeof require!=="undefined"?require("./component-spec.js"):null);jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.Decoder=jpeg.lossless.Decoder||(typeof require!=="undefined"?require("./decoder.js"):null);jpeg.lossless.FrameHeader=jpeg.lossless.FrameHeader||(typeof require!=="undefined"?require("./frame-header.js"):null);jpeg.lossless.HuffmanTable=jpeg.lossless.HuffmanTable||(typeof require!=="undefined"?require("./huffman-table.js"):null);jpeg.lossless.QuantizationTable=jpeg.lossless.QuantizationTable||(typeof require!=="undefined"?require("./quantization-table.js"):null);jpeg.lossless.ScanComponent=jpeg.lossless.ScanComponent||(typeof require!=="undefined"?require("./scan-component.js"):null);jpeg.lossless.ScanHeader=jpeg.lossless.ScanHeader||(typeof require!=="undefined"?require("./scan-header.js"):null);jpeg.lossless.Utils=jpeg.lossless.Utils||(typeof require!=="undefined"?require("./utils.js"):null);var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg}},{"./component-spec.js":30,"./data-stream.js":31,"./decoder.js":32,"./frame-header.js":33,"./huffman-table.js":34,"./quantization-table.js":36,"./scan-component.js":37,"./scan-header.js":38,"./utils.js":39}],36:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.Utils=jpeg.lossless.Utils||(typeof require!=="undefined"?require("./utils.js"):null);jpeg.lossless.QuantizationTable=jpeg.lossless.QuantizationTable||function(){this.precision=[];this.tq=[];this.quantTables=jpeg.lossless.Utils.createArray(4,64);this.tq[0]=0;this.tq[1]=0;this.tq[2]=0;this.tq[3]=0};jpeg.lossless.QuantizationTable.enhanceQuantizationTable=function(qtab,table){var i;for(i=0;i<8;i+=1){qtab[table[0*8+i]]*=90;qtab[table[4*8+i]]*=90;qtab[table[2*8+i]]*=118;qtab[table[6*8+i]]*=49;qtab[table[5*8+i]]*=71;qtab[table[1*8+i]]*=126;qtab[table[7*8+i]]*=25;qtab[table[3*8+i]]*=106}for(i=0;i<8;i+=1){qtab[table[0+8*i]]*=90;qtab[table[4+8*i]]*=90;qtab[table[2+8*i]]*=118;qtab[table[6+8*i]]*=49;qtab[table[5+8*i]]*=71;qtab[table[1+8*i]]*=126;qtab[table[7+8*i]]*=25;qtab[table[3+8*i]]*=106}for(i=0;i<64;i+=1){qtab[i]>>=6}};jpeg.lossless.QuantizationTable.prototype.read=function(data,table){var count=0,length,temp,t,i;length=data.get16();count+=2;while(count<length){temp=data.get8();count+=1;t=temp&15;if(t>3){throw new Error("ERROR: Quantization table ID > 3")}this.precision[t]=temp>>4;if(this.precision[t]===0){this.precision[t]=8}else if(this.precision[t]===1){this.precision[t]=16}else{throw new Error("ERROR: Quantization table precision error")}this.tq[t]=1;if(this.precision[t]===8){for(i=0;i<64;i+=1){if(count>length){throw new Error("ERROR: Quantization table format error")}this.quantTables[t][i]=data.get8();count+=1}jpeg.lossless.QuantizationTable.enhanceQuantizationTable(this.quantTables[t],table)}else{for(i=0;i<64;i+=1){if(count>length){throw new Error("ERROR: Quantization table format error")}this.quantTables[t][i]=data.get16();count+=2}jpeg.lossless.QuantizationTable.enhanceQuantizationTable(this.quantTables[t],table)}}if(count!==length){throw new Error("ERROR: Quantization table error [count!=Lq]")}return 1};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.QuantizationTable}},{"./data-stream.js":31,"./utils.js":39}],37:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.ScanComponent=jpeg.lossless.ScanComponent||function(){this.acTabSel=0;this.dcTabSel=0;this.scanCompSel=0};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.ScanComponent}},{}],38:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.DataStream=jpeg.lossless.DataStream||(typeof require!=="undefined"?require("./data-stream.js"):null);jpeg.lossless.ScanComponent=jpeg.lossless.ScanComponent||(typeof require!=="undefined"?require("./scan-component.js"):null);jpeg.lossless.ScanHeader=jpeg.lossless.ScanHeader||function(){this.ah=0;this.al=0;this.numComp=0;this.selection=0;this.spectralEnd=0;this.components=[]};jpeg.lossless.ScanHeader.prototype.read=function(data){var count=0,length,i,temp;length=data.get16();count+=2;this.numComp=data.get8();count+=1;for(i=0;i<this.numComp;i+=1){this.components[i]=new jpeg.lossless.ScanComponent;if(count>length){throw new Error("ERROR: scan header format error")}this.components[i].scanCompSel=data.get8();count+=1;temp=data.get8();count+=1;this.components[i].dcTabSel=temp>>4;this.components[i].acTabSel=temp&15}this.selection=data.get8();count+=1;this.spectralEnd=data.get8();count+=1;temp=data.get8();this.ah=temp>>4;this.al=temp&15;count+=1;if(count!==length){throw new Error("ERROR: scan header format error [count!=Ns]")}return 1};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.ScanHeader}},{"./data-stream.js":31,"./scan-component.js":37}],39:[function(require,module,exports){"use strict";var jpeg=jpeg||{};jpeg.lossless=jpeg.lossless||{};jpeg.lossless.Utils=jpeg.lossless.Utils||{};jpeg.lossless.Utils.createArray=function(length){var arr=new Array(length||0),i=length;if(arguments.length>1){var args=Array.prototype.slice.call(arguments,1);while(i--)arr[length-1-i]=jpeg.lossless.Utils.createArray.apply(this,args)}return arr};jpeg.lossless.Utils.makeCRCTable=function(){var c;var crcTable=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}crcTable[n]=c}return crcTable};jpeg.lossless.Utils.crc32=function(dataView){var crcTable=jpeg.lossless.Utils.crcTable||(jpeg.lossless.Utils.crcTable=jpeg.lossless.Utils.makeCRCTable());var crc=0^-1;for(var i=0;i<dataView.byteLength;i++){crc=crc>>>8^crcTable[(crc^dataView.getUint8(i))&255]}return(crc^-1)>>>0};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=jpeg.lossless.Utils}},{}],40:[function(require,module,exports){"use strict";function abs(x){if(x<0){return-x}if(x===0){return 0}return x}module.exports=abs},{}],41:[function(require,module,exports){"use strict";module.exports=Math.ceil},{}],42:[function(require,module,exports){"use strict";var floor=require("math-floor");function div2(x){var str="";var y;while(x>0){y=x/2;x=floor(y);if(y===x){str="0"+str}else{str="1"+str}}return str}module.exports=div2},{"math-floor":45}],43:[function(require,module,exports){"use strict";var pinf=require("const-pinf-float32");var ninf=require("const-ninf-float32");var abs=require("math-abs");var floor=require("math-floor");var rpad=require("utils-right-pad-string");var lpad=require("utils-left-pad-string");var repeat=require("utils-repeat-string");var div2=require("./div2.js");var mult2=require("./mult2.js");var BIAS=127;function binaryString(x){var nbits;var sign;var str;var exp;var n;var f;var i;if(x<0||1/x===ninf){sign="1"}else{sign="0"}if(x===pinf||x===ninf){exp=repeat("1",8);str=repeat("0",23);return sign+exp+str}if(x!==x){exp=repeat("1",8);str="1"+repeat("0",22);return sign+exp+str}if(x===0){exp=repeat("0",8);str=repeat("0",23);return sign+exp+str}x=abs(x);n=floor(x);f=x-n;n=div2(n);f=mult2(f);if(n){exp=n.length-1}else{for(i=0;i<f.length;i++){if(f[i]==="1"){nbits=i+1;break}}exp=-nbits}str=n+f;if(exp<0){if(exp<=-BIAS){nbits=BIAS-1}str=str.substring(nbits)}else{str=str.substring(1)}exp=div2(exp+BIAS);exp=lpad(exp,8,"0");str=rpad(str,23,"0").substring(0,23);return sign+exp+str}module.exports=binaryString},{"./div2.js":42,"./mult2.js":44,"const-ninf-float32":22,"const-pinf-float32":23,"math-abs":40,"math-floor":45,"utils-left-pad-string":88,"utils-repeat-string":89,"utils-right-pad-string":90}],44:[function(require,module,exports){"use strict";var MAX_ITER=149;var MAX_BITS=24;function mult2(x){var str;var y;var i;var j;str="";if(x===0){return str}j=MAX_ITER;for(i=0;i<MAX_ITER;i++){y=x*2;if(y>=1){x=y-1;str+="1";if(j===MAX_ITER){j=i}}else{x=y;str+="0"}if(y===1||i-j>MAX_BITS){break}}return str}module.exports=mult2},{}],45:[function(require,module,exports){"use strict";module.exports=Math.floor},{}],46:[function(require,module,exports){"use strict";var nifti=nifti||{};nifti.NIFTI1=nifti.NIFTI1||(typeof require!=="undefined"?require("./nifti1.js"):null);nifti.NIFTI2=nifti.NIFTI2||(typeof require!=="undefined"?require("./nifti2.js"):null);nifti.Utils=nifti.Utils||(typeof require!=="undefined"?require("./utilities.js"):null);var pako=pako||(typeof require!=="undefined"?require("pako"):null);nifti.isNIFTI1=function(data){var buf,mag1,mag2,mag3;buf=new DataView(data);mag1=buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION);mag2=buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION+1);mag3=buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION+2);return!!(mag1===nifti.NIFTI1.MAGIC_NUMBER[0]&&mag2===nifti.NIFTI1.MAGIC_NUMBER[1]&&mag3===nifti.NIFTI1.MAGIC_NUMBER[2])};nifti.isNIFTI2=function(data){var buf,mag1,mag2,mag3;buf=new DataView(data);mag1=buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION);mag2=buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION+1);mag3=buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION+2);return!!(mag1===nifti.NIFTI2.MAGIC_NUMBER[0]&&mag2===nifti.NIFTI2.MAGIC_NUMBER[1]&&mag3===nifti.NIFTI2.MAGIC_NUMBER[2])};nifti.isNIFTI=function(data){return nifti.isNIFTI1(data)||nifti.isNIFTI2(data)};nifti.isCompressed=function(data){var buf,magicCookie1,magicCookie2;if(data){buf=new DataView(data);magicCookie1=buf.getUint8(0);magicCookie2=buf.getUint8(1);if(magicCookie1===nifti.Utils.GUNZIP_MAGIC_COOKIE1){return true}if(magicCookie2===nifti.Utils.GUNZIP_MAGIC_COOKIE2){return true}}return false};nifti.decompress=function(data){return pako.inflate(data).buffer};nifti.readHeader=function(data){var header=null;if(nifti.isCompressed(data)){data=nifti.decompress(data)}if(nifti.isNIFTI1(data)){header=new nifti.NIFTI1}else if(nifti.isNIFTI2(data)){header=new nifti.NIFTI2}if(header){header.readHeader(data)}else{console.error("That file does not appear to be NIFTI!")}return header};nifti.hasExtension=function(header){return header.extensionFlag[0]!=0};nifti.readImage=function(header,data){var imageOffset=header.vox_offset,timeDim=1,statDim=1;if(header.dims[4]){timeDim=header.dims[4]}if(header.dims[5]){statDim=header.dims[5]}var imageSize=header.dims[1]*header.dims[2]*header.dims[3]*timeDim*statDim*(header.numBitsPerVoxel/8);return data.slice(imageOffset,imageOffset+imageSize)};nifti.readExtension=function(header,data){var loc=header.getExtensionLocation(),size=header.extensionSize;return data.slice(loc,loc+size)};nifti.readExtensionData=function(header,data){var loc=header.getExtensionLocation(),size=header.extensionSize;return data.slice(loc+8,loc+size-8)};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=nifti}},{"./nifti1.js":47,"./nifti2.js":48,"./utilities.js":49,pako:51}],47:[function(require,module,exports){"use strict";var nifti=nifti||{};nifti.Utils=nifti.Utils||(typeof require!=="undefined"?require("./utilities.js"):null);nifti.NIFTI1=nifti.NIFTI1||function(){this.littleEndian=false;this.dim_info=0;this.dims=[];this.intent_p1=0;this.intent_p2=0;this.intent_p3=0;this.intent_code=0;this.datatypeCode=0;this.numBitsPerVoxel=0;this.slice_start=0;this.slice_end=0;this.slice_code=0;this.pixDims=[];this.vox_offset=0;this.scl_slope=1;this.scl_inter=0;this.xyzt_units=0;this.cal_max=0;this.cal_min=0;this.slice_duration=0;this.toffset=0;this.description="";this.aux_file="";this.intent_name="";this.qform_code=0;this.sform_code=0;this.quatern_b=0;this.quatern_c=0;this.quatern_d=0;this.qoffset_x=0;this.qoffset_y=0;this.qoffset_z=0;this.affine=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];this.magic=0;this.isHDR=false;this.extensionFlag=[0,0,0,0];this.extensionSize=0;this.extensionCode=0};nifti.NIFTI1.TYPE_NONE=0;nifti.NIFTI1.TYPE_BINARY=1;nifti.NIFTI1.TYPE_UINT8=2;nifti.NIFTI1.TYPE_INT16=4;nifti.NIFTI1.TYPE_INT32=8;nifti.NIFTI1.TYPE_FLOAT32=16;nifti.NIFTI1.TYPE_COMPLEX64=32;nifti.NIFTI1.TYPE_FLOAT64=64;nifti.NIFTI1.TYPE_RGB24=128;nifti.NIFTI1.TYPE_INT8=256;nifti.NIFTI1.TYPE_UINT16=512;nifti.NIFTI1.TYPE_UINT32=768;nifti.NIFTI1.TYPE_INT64=1024;nifti.NIFTI1.TYPE_UINT64=1280;nifti.NIFTI1.TYPE_FLOAT128=1536;nifti.NIFTI1.TYPE_COMPLEX128=1792;nifti.NIFTI1.TYPE_COMPLEX256=2048;nifti.NIFTI1.XFORM_UNKNOWN=0;nifti.NIFTI1.XFORM_SCANNER_ANAT=1;nifti.NIFTI1.XFORM_ALIGNED_ANAT=2;nifti.NIFTI1.XFORM_TALAIRACH=3;nifti.NIFTI1.XFORM_MNI_152=4;nifti.NIFTI1.SPATIAL_UNITS_MASK=7;nifti.NIFTI1.TEMPORAL_UNITS_MASK=56;nifti.NIFTI1.UNITS_UNKNOWN=0;nifti.NIFTI1.UNITS_METER=1;nifti.NIFTI1.UNITS_MM=2;nifti.NIFTI1.UNITS_MICRON=3;nifti.NIFTI1.UNITS_SEC=8;nifti.NIFTI1.UNITS_MSEC=16;nifti.NIFTI1.UNITS_USEC=24;nifti.NIFTI1.UNITS_HZ=32;nifti.NIFTI1.UNITS_PPM=40;nifti.NIFTI1.UNITS_RADS=48;nifti.NIFTI1.MAGIC_COOKIE=348;nifti.NIFTI1.MAGIC_NUMBER_LOCATION=344;nifti.NIFTI1.MAGIC_NUMBER=[110,43,49];nifti.NIFTI1.MAGIC_NUMBER2=[110,105,49];nifti.NIFTI1.EXTENSION_HEADER_SIZE=8;nifti.NIFTI1.prototype.readHeader=function(data){var rawData=new DataView(data),magicCookieVal=nifti.Utils.getIntAt(rawData,0,this.littleEndian),ctr,ctrOut,ctrIn,index;if(magicCookieVal!==nifti.NIFTI1.MAGIC_COOKIE){this.littleEndian=true;magicCookieVal=nifti.Utils.getIntAt(rawData,0,this.littleEndian)}if(magicCookieVal!==nifti.NIFTI1.MAGIC_COOKIE){throw new Error("This does not appear to be a NIFTI file!")}this.dim_info=nifti.Utils.getByteAt(rawData,39);for(ctr=0;ctr<8;ctr+=1){index=40+ctr*2;this.dims[ctr]=nifti.Utils.getShortAt(rawData,index,this.littleEndian)}this.intent_p1=nifti.Utils.getFloatAt(rawData,56,this.littleEndian);this.intent_p2=nifti.Utils.getFloatAt(rawData,60,this.littleEndian);this.intent_p3=nifti.Utils.getFloatAt(rawData,64,this.littleEndian);this.intent_code=nifti.Utils.getShortAt(rawData,68,this.littleEndian);this.datatypeCode=nifti.Utils.getShortAt(rawData,70,this.littleEndian);this.numBitsPerVoxel=nifti.Utils.getShortAt(rawData,72,this.littleEndian);this.slice_start=nifti.Utils.getShortAt(rawData,74,this.littleEndian);for(ctr=0;ctr<8;ctr+=1){index=76+ctr*4;this.pixDims[ctr]=nifti.Utils.getFloatAt(rawData,index,this.littleEndian)}this.vox_offset=nifti.Utils.getFloatAt(rawData,108,this.littleEndian);this.scl_slope=nifti.Utils.getFloatAt(rawData,112,this.littleEndian);this.scl_inter=nifti.Utils.getFloatAt(rawData,116,this.littleEndian);this.slice_end=nifti.Utils.getShortAt(rawData,120,this.littleEndian);this.slice_code=nifti.Utils.getByteAt(rawData,122);this.xyzt_units=nifti.Utils.getByteAt(rawData,123);this.cal_max=nifti.Utils.getFloatAt(rawData,124,this.littleEndian);this.cal_min=nifti.Utils.getFloatAt(rawData,128,this.littleEndian);this.slice_duration=nifti.Utils.getFloatAt(rawData,132,this.littleEndian);this.toffset=nifti.Utils.getFloatAt(rawData,136,this.littleEndian);this.description=nifti.Utils.getStringAt(rawData,148,228);this.aux_file=nifti.Utils.getStringAt(rawData,228,252);this.qform_code=nifti.Utils.getShortAt(rawData,252,this.littleEndian);this.sform_code=nifti.Utils.getShortAt(rawData,254,this.littleEndian);this.quatern_b=nifti.Utils.getFloatAt(rawData,256,this.littleEndian);this.quatern_c=nifti.Utils.getFloatAt(rawData,260,this.littleEndian);this.quatern_d=nifti.Utils.getFloatAt(rawData,264,this.littleEndian);this.qoffset_x=nifti.Utils.getFloatAt(rawData,268,this.littleEndian);this.qoffset_y=nifti.Utils.getFloatAt(rawData,272,this.littleEndian);this.qoffset_z=nifti.Utils.getFloatAt(rawData,276,this.littleEndian);for(ctrOut=0;ctrOut<3;ctrOut+=1){for(ctrIn=0;ctrIn<4;ctrIn+=1){index=280+(ctrOut*4+ctrIn)*4;this.affine[ctrOut][ctrIn]=nifti.Utils.getFloatAt(rawData,index,this.littleEndian)}}this.affine[3][0]=0;this.affine[3][1]=0;this.affine[3][2]=0;this.affine[3][3]=1;this.intent_name=nifti.Utils.getStringAt(rawData,328,344);this.magic=nifti.Utils.getStringAt(rawData,344,348);this.isHDR=this.magic===nifti.NIFTI1.MAGIC_NUMBER2;if(rawData.byteLength>nifti.NIFTI1.MAGIC_COOKIE){this.extensionFlag[0]=nifti.Utils.getByteAt(rawData,348);this.extensionFlag[1]=nifti.Utils.getByteAt(rawData,348+1);this.extensionFlag[2]=nifti.Utils.getByteAt(rawData,348+2);this.extensionFlag[3]=nifti.Utils.getByteAt(rawData,348+3);if(this.extensionFlag[0]){this.extensionSize=this.getExtensionSize(rawData);this.extensionCode=this.getExtensionCode(rawData)}}};nifti.NIFTI1.prototype.toFormattedString=function(){var fmt=nifti.Utils.formatNumber,string="";string+="Dim Info = "+this.dim_info+"\n";string+="Image Dimensions (1-8): "+this.dims[0]+", "+this.dims[1]+", "+this.dims[2]+", "+this.dims[3]+", "+this.dims[4]+", "+this.dims[5]+", "+this.dims[6]+", "+this.dims[7]+"\n";string+="Intent Parameters (1-3): "+this.intent_p1+", "+this.intent_p2+", "+this.intent_p3+"\n";string+="Intent Code = "+this.intent_code+"\n";string+="Datatype = "+this.datatypeCode+" ("+this.getDatatypeCodeString(this.datatypeCode)+")\n";string+="Bits Per Voxel = "+this.numBitsPerVoxel+"\n";string+="Slice Start = "+this.slice_start+"\n";string+="Voxel Dimensions (1-8): "+fmt(this.pixDims[0])+", "+fmt(this.pixDims[1])+", "+fmt(this.pixDims[2])+", "+fmt(this.pixDims[3])+", "+fmt(this.pixDims[4])+", "+fmt(this.pixDims[5])+", "+fmt(this.pixDims[6])+", "+fmt(this.pixDims[7])+"\n";string+="Image Offset = "+this.vox_offset+"\n";string+="Data Scale: Slope = "+fmt(this.scl_slope)+" Intercept = "+fmt(this.scl_inter)+"\n";string+="Slice End = "+this.slice_end+"\n";string+="Slice Code = "+this.slice_code+"\n";string+="Units Code = "+this.xyzt_units+" ("+this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK&this.xyzt_units)+", "+this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK&this.xyzt_units)+")\n";string+="Display Range: Max = "+fmt(this.cal_max)+" Min = "+fmt(this.cal_min)+"\n";string+="Slice Duration = "+this.slice_duration+"\n";string+="Time Axis Shift = "+this.toffset+"\n";string+='Description: "'+this.description+'"\n';string+='Auxiliary File: "'+this.aux_file+'"\n';string+="Q-Form Code = "+this.qform_code+" ("+this.getTransformCodeString(this.qform_code)+")\n";string+="S-Form Code = "+this.sform_code+" ("+this.getTransformCodeString(this.sform_code)+")\n";string+="Quaternion Parameters: "+"b = "+fmt(this.quatern_b)+" "+"c = "+fmt(this.quatern_c)+" "+"d = "+fmt(this.quatern_d)+"\n";string+="Quaternion Offsets: "+"x = "+this.qoffset_x+" "+"y = "+this.qoffset_y+" "+"z = "+this.qoffset_z+"\n";string+="S-Form Parameters X: "+fmt(this.affine[0][0])+", "+fmt(this.affine[0][1])+", "+fmt(this.affine[0][2])+", "+fmt(this.affine[0][3])+"\n";string+="S-Form Parameters Y: "+fmt(this.affine[1][0])+", "+fmt(this.affine[1][1])+", "+fmt(this.affine[1][2])+", "+fmt(this.affine[1][3])+"\n";string+="S-Form Parameters Z: "+fmt(this.affine[2][0])+", "+fmt(this.affine[2][1])+", "+fmt(this.affine[2][2])+", "+fmt(this.affine[2][3])+"\n";string+='Intent Name: "'+this.intent_name+'"\n';if(this.extensionFlag[0]){string+="Extension: Size = "+this.extensionSize+" Code = "+this.extensionCode+"\n"}return string};nifti.NIFTI1.prototype.getDatatypeCodeString=function(code){if(code===nifti.NIFTI1.TYPE_UINT8){return"1-Byte Unsigned Integer"}else if(code===nifti.NIFTI1.TYPE_INT16){return"2-Byte Signed Integer"}else if(code===nifti.NIFTI1.TYPE_INT32){return"4-Byte Signed Integer"}else if(code===nifti.NIFTI1.TYPE_FLOAT32){return"4-Byte Float"}else if(code===nifti.NIFTI1.TYPE_FLOAT64){return"8-Byte Float"}else if(code===nifti.NIFTI1.TYPE_RGB24){return"RGB"}else if(code===nifti.NIFTI1.TYPE_INT8){return"1-Byte Signed Integer"}else if(code===nifti.NIFTI1.TYPE_UINT16){return"2-Byte Unsigned Integer"}else if(code===nifti.NIFTI1.TYPE_UINT32){return"4-Byte Unsigned Integer"}else if(code===nifti.NIFTI1.TYPE_INT64){return"8-Byte Signed Integer"}else if(code===nifti.NIFTI1.TYPE_UINT64){return"8-Byte Unsigned Integer"}else{return"Unknown"}};nifti.NIFTI1.prototype.getTransformCodeString=function(code){if(code===nifti.NIFTI1.XFORM_SCANNER_ANAT){return"Scanner"}else if(code===nifti.NIFTI1.XFORM_ALIGNED_ANAT){return"Aligned"}else if(code===nifti.NIFTI1.XFORM_TALAIRACH){return"Talairach"}else if(code===nifti.NIFTI1.XFORM_MNI_152){return"MNI"}else{return"Unknown"}};nifti.NIFTI1.prototype.getUnitsCodeString=function(code){if(code===nifti.NIFTI1.UNITS_METER){return"Meters"}else if(code===nifti.NIFTI1.UNITS_MM){return"Millimeters"}else if(code===nifti.NIFTI1.UNITS_MICRON){return"Microns"}else if(code===nifti.NIFTI1.UNITS_SEC){return"Seconds"}else if(code===nifti.NIFTI1.UNITS_MSEC){return"Milliseconds"}else if(code===nifti.NIFTI1.UNITS_USEC){return"Microseconds"}else if(code===nifti.NIFTI1.UNITS_HZ){return"Hz"}else if(code===nifti.NIFTI1.UNITS_PPM){return"PPM"}else if(code===nifti.NIFTI1.UNITS_RADS){return"Rads"}else{return"Unknown"}};nifti.NIFTI1.prototype.getQformMat=function(){ return this.convertNiftiQFormToNiftiSForm(this.quatern_b,this.quatern_c,this.quatern_d,this.qoffset_x,this.qoffset_y,this.qoffset_z,this.pixDims[1],this.pixDims[2],this.pixDims[3],this.pixDims[0])};nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm=function(qb,qc,qd,qx,qy,qz,dx,dy,dz,qfac){var R=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],a,b=qb,c=qc,d=qd,xd,yd,zd;R[3][0]=R[3][1]=R[3][2]=0;R[3][3]=1;a=1-(b*b+c*c+d*d);if(a<1e-7){a=1/Math.sqrt(b*b+c*c+d*d);b*=a;c*=a;d*=a;a=0}else{a=Math.sqrt(a)}xd=dx>0?dx:1;yd=dy>0?dy:1;zd=dz>0?dz:1;if(qfac<0){zd=-zd}R[0][0]=(a*a+b*b-c*c-d*d)*xd;R[0][1]=2*(b*c-a*d)*yd;R[0][2]=2*(b*d+a*c)*zd;R[1][0]=2*(b*c+a*d)*xd;R[1][1]=(a*a+c*c-b*b-d*d)*yd;R[1][2]=2*(c*d-a*b)*zd;R[2][0]=2*(b*d-a*c)*xd;R[2][1]=2*(c*d+a*b)*yd;R[2][2]=(a*a+d*d-c*c-b*b)*zd;R[0][3]=qx;R[1][3]=qy;R[2][3]=qz;return R};nifti.NIFTI1.prototype.convertNiftiSFormToNEMA=function(R){var xi,xj,xk,yi,yj,yk,zi,zj,zk,val,detQ,detP,i,j,k,p,q,r,ibest,jbest,kbest,pbest,qbest,rbest,M,vbest,Q,P,iChar,jChar,kChar,iSense,jSense,kSense;k=0;Q=[[0,0,0],[0,0,0],[0,0,0]];P=[[0,0,0],[0,0,0],[0,0,0]];xi=R[0][0];xj=R[0][1];xk=R[0][2];yi=R[1][0];yj=R[1][1];yk=R[1][2];zi=R[2][0];zj=R[2][1];zk=R[2][2];val=Math.sqrt(xi*xi+yi*yi+zi*zi);if(val===0){return null}xi/=val;yi/=val;zi/=val;val=Math.sqrt(xj*xj+yj*yj+zj*zj);if(val===0){return null}xj/=val;yj/=val;zj/=val;val=xi*xj+yi*yj+zi*zj;if(Math.abs(val)>1e-4){xj-=val*xi;yj-=val*yi;zj-=val*zi;val=Math.sqrt(xj*xj+yj*yj+zj*zj);if(val===0){return null}xj/=val;yj/=val;zj/=val}val=Math.sqrt(xk*xk+yk*yk+zk*zk);if(val===0){xk=yi*zj-zi*yj;yk=zi*xj-zj*xi;zk=xi*yj-yi*xj}else{xk/=val;yk/=val;zk/=val}val=xi*xk+yi*yk+zi*zk;if(Math.abs(val)>1e-4){xk-=val*xi;yk-=val*yi;zk-=val*zi;val=Math.sqrt(xk*xk+yk*yk+zk*zk);if(val===0){return null}xk/=val;yk/=val;zk/=val}val=xj*xk+yj*yk+zj*zk;if(Math.abs(val)>1e-4){xk-=val*xj;yk-=val*yj;zk-=val*zj;val=Math.sqrt(xk*xk+yk*yk+zk*zk);if(val===0){return null}xk/=val;yk/=val;zk/=val}Q[0][0]=xi;Q[0][1]=xj;Q[0][2]=xk;Q[1][0]=yi;Q[1][1]=yj;Q[1][2]=yk;Q[2][0]=zi;Q[2][1]=zj;Q[2][2]=zk;detQ=this.nifti_mat33_determ(Q);if(detQ===0){return null}vbest=-666;ibest=pbest=qbest=rbest=1;jbest=2;kbest=3;for(i=1;i<=3;i+=1){for(j=1;j<=3;j+=1){if(i!==j){for(k=1;k<=3;k+=1){if(!(i===k||j===k)){P[0][0]=P[0][1]=P[0][2]=P[1][0]=P[1][1]=P[1][2]=P[2][0]=P[2][1]=P[2][2]=0;for(p=-1;p<=1;p+=2){for(q=-1;q<=1;q+=2){for(r=-1;r<=1;r+=2){P[0][i-1]=p;P[1][j-1]=q;P[2][k-1]=r;detP=this.nifti_mat33_determ(P);if(detP*detQ>0){M=this.nifti_mat33_mul(P,Q);val=M[0][0]+M[1][1]+M[2][2];if(val>vbest){vbest=val;ibest=i;jbest=j;kbest=k;pbest=p;qbest=q;rbest=r}}}}}}}}}}iChar=jChar=kChar=iSense=jSense=kSense=0;switch(ibest*pbest){case 1:iChar="X";iSense="+";break;case-1:iChar="X";iSense="-";break;case 2:iChar="Y";iSense="+";break;case-2:iChar="Y";iSense="-";break;case 3:iChar="Z";iSense="+";break;case-3:iChar="Z";iSense="-";break}switch(jbest*qbest){case 1:jChar="X";jSense="+";break;case-1:jChar="X";jSense="-";break;case 2:jChar="Y";jSense="+";break;case-2:jChar="Y";jSense="-";break;case 3:jChar="Z";jSense="+";break;case-3:jChar="Z";jSense="-";break}switch(kbest*rbest){case 1:kChar="X";kSense="+";break;case-1:kChar="X";kSense="-";break;case 2:kChar="Y";kSense="+";break;case-2:kChar="Y";kSense="-";break;case 3:kChar="Z";kSense="+";break;case-3:kChar="Z";kSense="-";break}return iChar+jChar+kChar+iSense+jSense+kSense};nifti.NIFTI1.prototype.nifti_mat33_mul=function(A,B){var C=[[0,0,0],[0,0,0],[0,0,0]],i,j;for(i=0;i<3;i+=1){for(j=0;j<3;j+=1){C[i][j]=A[i][0]*B[0][j]+A[i][1]*B[1][j]+A[i][2]*B[2][j]}}return C};nifti.NIFTI1.prototype.nifti_mat33_determ=function(R){var r11,r12,r13,r21,r22,r23,r31,r32,r33;r11=R[0][0];r12=R[0][1];r13=R[0][2];r21=R[1][0];r22=R[1][1];r23=R[1][2];r31=R[2][0];r32=R[2][1];r33=R[2][2];return r11*r22*r33-r11*r32*r23-r21*r12*r33+r21*r32*r13+r31*r12*r23-r31*r22*r13};nifti.NIFTI1.prototype.getExtensionLocation=function(){return nifti.NIFTI1.MAGIC_COOKIE+4};nifti.NIFTI1.prototype.getExtensionSize=function(data){return nifti.Utils.getIntAt(data,this.getExtensionLocation(),this.littleEndian)};nifti.NIFTI1.prototype.getExtensionCode=function(data){return nifti.Utils.getIntAt(data,this.getExtensionLocation()+4,this.littleEndian)};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=nifti.NIFTI1}},{"./utilities.js":49}],48:[function(require,module,exports){"use strict";var nifti=nifti||{};nifti.Utils=nifti.Utils||(typeof require!=="undefined"?require("./utilities.js"):null);nifti.NIFTI1=nifti.NIFTI1||(typeof require!=="undefined"?require("./nifti1.js"):null);nifti.NIFTI2=nifti.NIFTI2||function(){this.littleEndian=false;this.dim_info=0;this.dims=[];this.intent_p1=0;this.intent_p2=0;this.intent_p3=0;this.intent_code=0;this.datatypeCode=0;this.numBitsPerVoxel=0;this.slice_start=0;this.slice_end=0;this.slice_code=0;this.pixDims=[];this.vox_offset=0;this.scl_slope=1;this.scl_inter=0;this.xyzt_units=0;this.cal_max=0;this.cal_min=0;this.slice_duration=0;this.toffset=0;this.description="";this.aux_file="";this.intent_name="";this.qform_code=0;this.sform_code=0;this.quatern_b=0;this.quatern_c=0;this.quatern_d=0;this.qoffset_x=0;this.qoffset_y=0;this.qoffset_z=0;this.affine=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];this.magic=0;this.extensionFlag=[0,0,0,0]};nifti.NIFTI2.MAGIC_COOKIE=540;nifti.NIFTI2.MAGIC_NUMBER_LOCATION=4;nifti.NIFTI2.MAGIC_NUMBER=[110,43,50,0,13,10,26,10];nifti.NIFTI2.prototype.readHeader=function(data){var rawData=new DataView(data),magicCookieVal=nifti.Utils.getIntAt(rawData,0,this.littleEndian),ctr,ctrOut,ctrIn,index,array;if(magicCookieVal!==nifti.NIFTI2.MAGIC_COOKIE){this.littleEndian=true;magicCookieVal=nifti.Utils.getIntAt(rawData,0,this.littleEndian)}if(magicCookieVal!==nifti.NIFTI2.MAGIC_COOKIE){throw new Error("This does not appear to be a NIFTI file!")}this.datatypeCode=nifti.Utils.getShortAt(rawData,12,this.littleEndian);this.numBitsPerVoxel=nifti.Utils.getShortAt(rawData,14,this.littleEndian);for(ctr=0;ctr<8;ctr+=1){index=16+ctr*8;this.dims[ctr]=nifti.Utils.getLongAt(rawData,index,this.littleEndian)}this.intent_p1=nifti.Utils.getDoubleAt(rawData,80,this.littleEndian);this.intent_p2=nifti.Utils.getDoubleAt(rawData,88,this.littleEndian);this.intent_p3=nifti.Utils.getDoubleAt(rawData,96,this.littleEndian);for(ctr=0;ctr<8;ctr+=1){index=104+ctr*8;this.pixDims[ctr]=nifti.Utils.getDoubleAt(rawData,index,this.littleEndian)}this.vox_offset=nifti.Utils.getLongAt(rawData,168,this.littleEndian);this.scl_slope=nifti.Utils.getDoubleAt(rawData,176,this.littleEndian);this.scl_inter=nifti.Utils.getDoubleAt(rawData,184,this.littleEndian);this.cal_max=nifti.Utils.getDoubleAt(rawData,192,this.littleEndian);this.cal_min=nifti.Utils.getDoubleAt(rawData,200,this.littleEndian);this.slice_duration=nifti.Utils.getDoubleAt(rawData,208,this.littleEndian);this.toffset=nifti.Utils.getDoubleAt(rawData,216,this.littleEndian);this.slice_start=nifti.Utils.getLongAt(rawData,224,this.littleEndian);this.slice_end=nifti.Utils.getLongAt(rawData,232,this.littleEndian);this.description=nifti.Utils.getStringAt(rawData,240,240+80);this.aux_file=nifti.Utils.getStringAt(rawData,320,320+24);this.qform_code=nifti.Utils.getIntAt(rawData,344,this.littleEndian);this.sform_code=nifti.Utils.getIntAt(rawData,348,this.littleEndian);this.quatern_b=nifti.Utils.getDoubleAt(rawData,352,this.littleEndian);this.quatern_c=nifti.Utils.getDoubleAt(rawData,360,this.littleEndian);this.quatern_d=nifti.Utils.getDoubleAt(rawData,368,this.littleEndian);this.qoffset_x=nifti.Utils.getDoubleAt(rawData,376,this.littleEndian);this.qoffset_y=nifti.Utils.getDoubleAt(rawData,384,this.littleEndian);this.qoffset_z=nifti.Utils.getDoubleAt(rawData,392,this.littleEndian);for(ctrOut=0;ctrOut<3;ctrOut+=1){for(ctrIn=0;ctrIn<4;ctrIn+=1){index=400+(ctrOut*4+ctrIn)*8;this.affine[ctrOut][ctrIn]=nifti.Utils.getDoubleAt(rawData,index,this.littleEndian)}}this.affine[3][0]=0;this.affine[3][1]=0;this.affine[3][2]=0;this.affine[3][3]=1;this.slice_code=nifti.Utils.getIntAt(rawData,496,this.littleEndian);this.xyzt_units=nifti.Utils.getIntAt(rawData,500,this.littleEndian);this.intent_code=nifti.Utils.getIntAt(rawData,504,this.littleEndian);this.intent_name=nifti.Utils.getStringAt(rawData,508,508+16);this.dim_info=nifti.Utils.getByteAt(rawData,524);if(rawData.byteLength>nifti.NIFTI2.MAGIC_COOKIE){this.extensionFlag[0]=nifti.Utils.getByteAt(rawData,540);this.extensionFlag[1]=nifti.Utils.getByteAt(rawData,540+1);this.extensionFlag[2]=nifti.Utils.getByteAt(rawData,540+2);this.extensionFlag[3]=nifti.Utils.getByteAt(rawData,540+3);if(this.extensionFlag[0]){this.extensionSize=this.getExtensionSize(rawData);this.extensionCode=this.getExtensionCode(rawData)}}};nifti.NIFTI2.prototype.toFormattedString=function(){var fmt=nifti.Utils.formatNumber,string="";string+="Datatype = "+ +this.datatypeCode+" ("+this.getDatatypeCodeString(this.datatypeCode)+")\n";string+="Bits Per Voxel = "+" = "+this.numBitsPerVoxel+"\n";string+="Image Dimensions"+" (1-8): "+this.dims[0]+", "+this.dims[1]+", "+this.dims[2]+", "+this.dims[3]+", "+this.dims[4]+", "+this.dims[5]+", "+this.dims[6]+", "+this.dims[7]+"\n";string+="Intent Parameters (1-3): "+this.intent_p1+", "+this.intent_p2+", "+this.intent_p3+"\n";string+="Voxel Dimensions (1-8): "+fmt(this.pixDims[0])+", "+fmt(this.pixDims[1])+", "+fmt(this.pixDims[2])+", "+fmt(this.pixDims[3])+", "+fmt(this.pixDims[4])+", "+fmt(this.pixDims[5])+", "+fmt(this.pixDims[6])+", "+fmt(this.pixDims[7])+"\n";string+="Image Offset = "+this.vox_offset+"\n";string+="Data Scale: Slope = "+fmt(this.scl_slope)+" Intercept = "+fmt(this.scl_inter)+"\n";string+="Display Range: Max = "+fmt(this.cal_max)+" Min = "+fmt(this.cal_min)+"\n";string+="Slice Duration = "+this.slice_duration+"\n";string+="Time Axis Shift = "+this.toffset+"\n";string+="Slice Start = "+this.slice_start+"\n";string+="Slice End = "+this.slice_end+"\n";string+='Description: "'+this.description+'"\n';string+='Auxiliary File: "'+this.aux_file+'"\n';string+="Q-Form Code = "+this.qform_code+" ("+this.getTransformCodeString(this.qform_code)+")\n";string+="S-Form Code = "+this.sform_code+" ("+this.getTransformCodeString(this.sform_code)+")\n";string+="Quaternion Parameters: "+"b = "+fmt(this.quatern_b)+" "+"c = "+fmt(this.quatern_c)+" "+"d = "+fmt(this.quatern_d)+"\n";string+="Quaternion Offsets: "+"x = "+this.qoffset_x+" "+"y = "+this.qoffset_y+" "+"z = "+this.qoffset_z+"\n";string+="S-Form Parameters X: "+fmt(this.affine[0][0])+", "+fmt(this.affine[0][1])+", "+fmt(this.affine[0][2])+", "+fmt(this.affine[0][3])+"\n";string+="S-Form Parameters Y: "+fmt(this.affine[1][0])+", "+fmt(this.affine[1][1])+", "+fmt(this.affine[1][2])+", "+fmt(this.affine[1][3])+"\n";string+="S-Form Parameters Z: "+fmt(this.affine[2][0])+", "+fmt(this.affine[2][1])+", "+fmt(this.affine[2][2])+", "+fmt(this.affine[2][3])+"\n";string+="Slice Code = "+this.slice_code+"\n";string+="Units Code = "+this.xyzt_units+" ("+this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK&this.xyzt_units)+", "+this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK&this.xyzt_units)+")\n";string+="Intent Code = "+this.intent_code+"\n";string+='Intent Name: "'+this.intent_name+'"\n';string+="Dim Info = "+this.dim_info+"\n";return string};nifti.NIFTI2.prototype.getExtensionLocation=function(){return nifti.NIFTI2.MAGIC_COOKIE+4};nifti.NIFTI2.prototype.getExtensionSize=nifti.NIFTI1.prototype.getExtensionSize;nifti.NIFTI2.prototype.getExtensionCode=nifti.NIFTI1.prototype.getExtensionCode;nifti.NIFTI2.prototype.getDatatypeCodeString=nifti.NIFTI1.prototype.getDatatypeCodeString;nifti.NIFTI2.prototype.getTransformCodeString=nifti.NIFTI1.prototype.getTransformCodeString;nifti.NIFTI2.prototype.getUnitsCodeString=nifti.NIFTI1.prototype.getUnitsCodeString;nifti.NIFTI2.prototype.getQformMat=nifti.NIFTI1.prototype.getQformMat;nifti.NIFTI2.prototype.convertNiftiQFormToNiftiSForm=nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm;nifti.NIFTI2.prototype.convertNiftiSFormToNEMA=nifti.NIFTI1.prototype.convertNiftiSFormToNEMA;nifti.NIFTI2.prototype.nifti_mat33_mul=nifti.NIFTI1.prototype.nifti_mat33_mul;nifti.NIFTI2.prototype.nifti_mat33_determ=nifti.NIFTI1.prototype.nifti_mat33_determ;var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=nifti.NIFTI2}},{"./nifti1.js":47,"./utilities.js":49}],49:[function(require,module,exports){"use strict";var nifti=nifti||{};nifti.Utils=nifti.Utils||{};nifti.Utils.crcTable=null;nifti.Utils.GUNZIP_MAGIC_COOKIE1=31;nifti.Utils.GUNZIP_MAGIC_COOKIE2=139;nifti.Utils.getStringAt=function(data,start,end){var str="",ctr,ch;for(ctr=start;ctr<end;ctr+=1){ch=data.getUint8(ctr);if(ch!==0){str+=String.fromCharCode(ch)}}return str};nifti.Utils.getByteAt=function(data,start){return data.getInt8(start)};nifti.Utils.getShortAt=function(data,start,littleEndian){return data.getInt16(start,littleEndian)};nifti.Utils.getIntAt=function(data,start,littleEndian){return data.getInt32(start,littleEndian)};nifti.Utils.getFloatAt=function(data,start,littleEndian){return data.getFloat32(start,littleEndian)};nifti.Utils.getDoubleAt=function(data,start,littleEndian){return data.getFloat64(start,littleEndian)};nifti.Utils.getLongAt=function(data,start,littleEndian){var ctr,array=[],value=0;for(ctr=0;ctr<8;ctr+=1){array[ctr]=nifti.Utils.getByteAt(data,start+ctr,littleEndian)}for(ctr=array.length-1;ctr>=0;ctr--){value=value*256+array[ctr]}return value};nifti.Utils.toArrayBuffer=function(buffer){var ab,view,i;ab=new ArrayBuffer(buffer.length);view=new Uint8Array(ab);for(i=0;i<buffer.length;i+=1){view[i]=buffer[i]}return ab};nifti.Utils.isString=function(obj){return typeof obj==="string"||obj instanceof String};nifti.Utils.formatNumber=function(num,shortFormat){var val=0;if(nifti.Utils.isString(num)){val=Number(num)}else{val=num}if(shortFormat){val=val.toPrecision(5)}else{val=val.toPrecision(7)}return parseFloat(val)};nifti.Utils.makeCRCTable=function(){var c;var crcTable=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}crcTable[n]=c}return crcTable};nifti.Utils.crc32=function(dataView){var crcTable=nifti.Utils.crcTable||(nifti.Utils.crcTable=nifti.Utils.makeCRCTable());var crc=0^-1;for(var i=0;i<dataView.byteLength;i++){crc=crc>>>8^crcTable[(crc^dataView.getUint8(i))&255]}return(crc^-1)>>>0};var moduleType=typeof module;if(moduleType!=="undefined"&&module.exports){module.exports=nifti.Utils}},{}],50:[function(require,module,exports){"use strict";var assert=require("assert");var lineSeparatorRE=/[ \f\t\v]*\r?\n/;var NRRDMagicRE=/^NRRD\d{4}$/;var lineRE=/^([^:]*)(:[ =])(.*)$/;var dataFileListRE=/^LIST(?: (\d+))?$/;module.exports.serialize=function(nrrdOrg){var i,buffer,arr,totalLen=1,nrrd={},prop,nativeType,nativeSize,bufferData,arrData,line,lines=[],header;for(prop in nrrdOrg){nrrd[prop]=nrrdOrg[prop]}if(nrrd.sizes===undefined){throw new Error("Sizes missing from NRRD file!")}else if(nrrd.dimension===undefined){nrrd.dimension=nrrd.sizes.length}if(nrrd.data instanceof Int8Array){nativeType="int8"}else if(nrrd.data instanceof Uint8Array){nativeType="uint8"}else if(nrrd.data instanceof Int16Array){nativeType="int16"}else if(nrrd.data instanceof Uint16Array){nativeType="uint16"}else if(nrrd.data instanceof Int32Array){nativeType="int32"}else if(nrrd.data instanceof Uint32Array){nativeType="uint32"}else if(nrrd.data instanceof Float32Array){nativeType="float"}else if(nrrd.data instanceof Float64Array){nativeType="double"}if(nrrd.type===undefined&&nativeType!==undefined){nrrd.type=nativeType}else if(nrrd.type===undefined){throw new Error("Type of data is not given and cannot be inferred!")}else if(typeof nrrd.type=="string"||nrrd.type instanceof String){nrrd.type=parseNRRDType(nrrd.type)}if(nrrd.encoding===undefined){nrrd.encoding="raw"}else if(typeof nrrd.encoding=="string"||nrrd.encoding instanceof String){nrrd.encoding=parseNRRDEncoding(nrrd.encoding)}if(nrrd.data&&nrrd.type!="block"&&nrrd.type!="int8"&&nrrd.type!="uint8"&&nrrd.encoding!="ascii"){nrrd.endian=systemEndianness}else if(nrrd.type=="block"||nrrd.type=="int8"||nrrd.type=="uint8"||nrrd.encoding=="ascii"){nrrd.endian=undefined}else if(typeof nrrd.endian=="string"||nrrd.endian instanceof String){nrrd.endian=parseNRRDEndian(nrrd.endian)}var spaceDimension=undefined;if(nrrd.spaceDimension!==undefined){spaceDimension=nrrd.spaceDimension}else if(nrrd.space!==undefined){switch(nrrd.space){case"right-anterior-superior":case"RAS":spaceDimension=3;break;case"left-anterior-superior":case"LAS":spaceDimension=3;break;case"left-posterior-superior":case"LPS":spaceDimension=3;break;case"right-anterior-superior-time":case"RAST":spaceDimension=4;break;case"left-anterior-superior-time":case"LAST":spaceDimension=4;break;case"left-posterior-superior-time":case"LPST":spaceDimension=4;break;case"scanner-xyz":spaceDimension=3;break;case"scanner-xyz-time":spaceDimension=4;break;case"3D-right-handed":spaceDimension=3;break;case"3D-left-handed":spaceDimension=3;break;case"3D-right-handed-time":spaceDimension=4;break;case"3D-left-handed-time":spaceDimension=4;break;default:console.warn("Unrecognized space: "+nrrd.space)}}checkNRRD(nrrd);for(i=0;i<nrrd.sizes.length;i++){if(nrrd.sizes[i]<=0)throw new Error("Sizes should be a list of positive (>0) integers!");totalLen*=nrrd.sizes[i]}if(nrrd.data){if(nrrd.data.length<totalLen){throw new Error("Missing data to serialize!")}}else if(nrrd.buffer){if(nrrd.encoding=="raw"){if(nrrd.type=="block"&&nrrd.blockSize!==undefined){nativeSize=nrrd.blockSize}else{nativeSize=getNRRDTypeSize(nrrd.type)}if(nrrd.buffer.byteLength<totalLen*nativeSize){throw new Error("Missing data to serialize!")}}}else if(nrrd.dataFile){}else{throw new Error("Will not serialize an empty NRRD file!")}if(nrrd.data){switch(nrrd.encoding){case"raw":if(nrrd.type==nativeType&&nrrd.endian==systemEndianness){bufferData=nrrd.data.buffer.slice(nrrd.data.byteOffset,nrrd.data.byteOffset+nrrd.data.byteLength)}else if(nrrd.endian==systemEndianness){bufferData=castTypedArray(nrrd.data,nrrd.type);bufferData=bufferData.buffer.slice(bufferData.byteOffset,bufferData.byteOffset+bufferData.byteLength)}else{bufferData=serializeToBuffer(nrrd.data,nrrd.type,nrrd.endian)}break;case"ascii":if(nrrd.type==nativeType){bufferData=serializeToTextBuffer(nrrd.data)}else{bufferData=serializeToTextBuffer(castTypedArray(nrrd.data,nrrd.type))}break;default:throw new Error("Unsupported NRRD encoding: "+nrrd.encoding)}}else if(nrrd.buffer){bufferData=nrrd.buffer}lines.push("NRRD0005");lines.push("# Generated by nrrd-js");var firstProps=["dimension","spaceDimension","space"];for(i=0;i<firstProps.length;i++){prop=firstProps[i];if(nrrd[prop]===undefined)continue;line=serializeField(prop,nrrd[prop],nrrd.dimension,spaceDimension);if(line!==undefined)lines.push(line)}for(prop in nrrd){if(nrrd[prop]===undefined)continue;if(firstProps.indexOf(prop)>=0)continue;line=serializeField(prop,nrrd[prop],nrrd.dimension,spaceDimension);if(line!==undefined)lines.push(line)}if(nrrd.keys)for(prop in nrrd.keys){if(prop.indexOf(":=")>=0)throw new Error("The combination ':=' is not allowed in an NRRD key!");lines.push(prop+":="+escapeValue(nrrd[prop]))}if(nrrd.dataFile&&nrrd.dataFile.length){lines.push("data file: LIST");Array.prototype.push.apply(lines,nrrd.dataFile)}else if(nrrd.dataFile&&nrrd.dataFile.files&&"subdim"in nrrd.dataFile){lines.push("data file: LIST "+nrrd.dataFile.subdim);Array.prototype.push.apply(lines,nrrd.dataFile.files)}if(bufferData&&!("dataFile"in nrrd)){lines.push("");lines.push("");header=lines.join("\n");buffer=new ArrayBuffer(header.length+bufferData.byteLength);arr=new Uint8Array(buffer);for(i=0;i<header.length;i++){arr[i]=header.charCodeAt(i)}arrData=new Uint8Array(bufferData);arr.set(arrData,header.length)}else{lines.push("");header=lines.join("\n");buffer=new ArrayBuffer(header.length);arr=new Uint8Array(buffer);for(i=0;i<header.length;i++){arr[i]=header.charCodeAt(i)}}return buffer};module.exports.parse=function(buffer){var i,header,dataStart,ret={data:undefined,buffer:undefined,keys:{},version:undefined},lines,match,match2,buf8=new Uint8Array(buffer);if(buf8.buffer!==buffer)buffer=buf8.buffer;i=2;while(i<buf8.length){if(buf8[i]==10){if(buf8[i-1]==10||buf8[i-1]==13&&buf8[i-2]==10){dataStart=i+1;break}else{i++}}else if(buf8[i]==13){i++}else{i+=2}}if(dataStart===undefined){header=String.fromCharCode.apply(null,buf8)}else{header=String.fromCharCode.apply(null,buf8.subarray(0,dataStart));ret.buffer=buffer.slice(dataStart)}lines=header.split(lineSeparatorRE);lines=lines.filter(function(l){return l.length>0&&l[0]!="#"});if(!NRRDMagicRE.test(lines[0])){throw new Error("File is not an NRRD file!")}ret.version=parseInt(lines[0].substring(4,8),10);if(ret.version>5){console.warn("Reading an unsupported version of the NRRD format; things may go haywire.")}for(i=1;i<lines.length;i++){match=lineRE.exec(lines[i]);if(!match){console.warn("Unrecognized line in NRRD header: "+lines[i]);continue}if(match[2]==": "){match[1]=mapNRRDToJavascript(match[1]);if(match[1]=="dataFile"&&(match2=dataFileListRE.exec(match[3]))){if(match2.length==2&&match2[1]){ret[match[1]]={files:lines.slice(i+1),subdim:parseNRRDInteger(match2[1])}}else{ret[match[1]]=lines.slice(i+1)}lines.length=i}else{ret[match[1]]=parseField(match[1],match[3])}}else if(match[2]==":="){ret.keys[match[1]]=unescapeValue(match[3])}else{throw new Error("Logic error in NRRD parser.")}}checkNRRD(ret);if("dataFile"in ret){console.warn("No support for external data yet!")}else{switch(ret.encoding){case"raw":ret.data=parseNRRDRawData(ret.buffer,ret.type,ret.sizes,{endian:ret.endian,blockSize:ret.blockSize});break;case"ascii":ret.data=parseNRRDTextData(ret.buffer,ret.type,ret.sizes);break;default:console.warn("Unsupported NRRD encoding: "+ret.encoding)}}return ret};function escapeValue(val){return val.replace("\\","\\\\").replace("\n","\\n")}function unescapeValue(val){return val.split("\\\\").map(function(s){return s.replace("\\n","\n")}).join("\\")}function serializeField(prop,value,dimension,spaceDimension){var line;var propNRRD=mapJavascriptToNRRD(prop);switch(prop){case"data":case"buffer":case"keys":case"version":break;case"content":case"number":case"sampleUnits":case"space":line=propNRRD+": "+value;break;case"blockSize":case"lineSkip":case"byteSkip":case"dimension":case"spaceDimension":assert(typeof value=="number"||value instanceof Number,"Field "+prop+" should at least contain a number!");line=propNRRD+": "+value;break;case"min":case"max":case"oldMin":case"oldMax":assert(typeof value=="number"||value instanceof Number,"Field "+prop+" should contain a number!");line=propNRRD+": "+value;break;case"spaceOrigin":assert(value.length===spaceDimension,"Field "+prop+" should be a list with length equal to the space dimension!");value.forEach(function(val){assert(typeof val=="number"||val instanceof Number,"Field "+prop+" should be a list of numbers!")});line=propNRRD+": ("+value.join(",")+")";break;case"labels":case"units":case"spaceUnits":assert(value.length!==undefined&&value.length==dimension,"Field "+prop+" should be a list with length equal to the dimension!");value.forEach(function(val){assert(typeof val=="string"||val instanceof String,"Field "+prop+" should be a list of numbers!")});line=propNRRD+": "+value.map(serializeNRRDQuotedString).join(" ");break;case"sizes":assert(value.length!==undefined&&value.length==dimension,"Field "+prop+" should be a list with length equal to the dimension!");value.forEach(function(val){assert(typeof val=="number"||val instanceof Number,"Field "+prop+" should be a list of numbers!")});line=propNRRD+": "+value.join(" ");break;case"spacings":case"thicknesses":case"axisMins":case"axisMaxs":assert(value.length!==undefined&&value.length==dimension,"Field "+prop+" should be a list with length equal to the dimension!");value.forEach(function(val){assert(typeof val=="number"||val instanceof Number,"Field "+prop+" should be a list of numbers!")});line=propNRRD+": "+value.join(" ");break;case"spaceDirections":assert(value.length!==undefined&&value.length===dimension,"Field "+prop+" should be a list with length equal to the dimension!");value.forEach(function(vec){assert(vec===null||vec.length!==undefined&&vec.length===spaceDimension,"The elements of field "+prop+" should be lists with length equal to the space dimension!");if(vec!==null)vec.forEach(function(val){assert(typeof val=="number"||val instanceof Number,"The elements of field "+prop+" should be lists of numbers!")})});line=propNRRD+": "+value.map(function(vec){return vec===null?"none":"("+vec.join(",")+")"}).join(" ");break;case"measurementFrame":assert(value.length!==undefined&&value.length===spaceDimension,"Field "+prop+" should be a list with length equal to the space dimension!");value.forEach(function(vec){assert(vec===null||vec.length!==undefined&&vec.length===spaceDimension,"The elements of field "+prop+" should be lists with length equal to the space dimension!");if(vec!==null)vec.forEach(function(val){assert(typeof val=="number"||val instanceof Number,"The elements of field "+prop+" should be lists of numbers!")})});line=propNRRD+": "+value.map(function(vec){return vec===null?"none":"("+vec.join(",")+")"}).join(" ");break;case"type":assert(typeof value=="string"||value instanceof String,"Field "+prop+" should contain a string!");line=propNRRD+": "+value;break;case"encoding":assert(typeof value=="string"||value instanceof String,"Field "+prop+" should contain a string!");line=propNRRD+": "+value;break;case"endian":assert(typeof value=="string"||value instanceof String,"Field "+prop+" should contain a string!");line=propNRRD+": "+value;break;case"dataFile":if(value.length||value.files&&"subdim"in value){}else{line=propNRRD+": "+serializeNRRDDataFile(value)}break;case"centers":assert(value.length!==undefined&&value.length==dimension,"Field "+prop+" should be a list with length equal to the dimension!");line=propNRRD+": "+value.map(serializeNRRDOptional).join(" ");break;case"kinds":assert(value.length!==undefined&&value.length==dimension,"Field "+prop+" should be a list with length equal to the dimension!");line=propNRRD+": "+value.map(serializeNRRDOptional).join(" ");break;default:console.warn("Unrecognized NRRD field: "+prop+", skipping.")}return line}function parseField(identifier,descriptor){switch(identifier){case"content":case"number":case"sampleUnits":break;case"dimension":case"blockSize":case"lineSkip":case"byteSkip":case"spaceDimension":descriptor=parseNRRDInteger(descriptor);break;case"min":case"max":case"oldMin":case"oldMax":descriptor=parseNRRDFloat(descriptor);break;case"spaceOrigin":descriptor=parseNRRDVector(descriptor);break;case"labels":case"units":case"spaceUnits":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDQuotedString);break;case"sizes":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDInteger);break;case"spacings":case"thicknesses":case"axisMins":case"axisMaxs":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDFloat);break;case"spaceDirections":case"measurementFrame":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDVector);break;case"type":descriptor=parseNRRDType(descriptor);break;case"encoding":descriptor=parseNRRDEncoding(descriptor);break;case"endian":descriptor=parseNRRDEndian(descriptor);break;case"dataFile":descriptor=parseNRRDDataFile(descriptor);break;case"centers":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDCenter);break;case"kinds":descriptor=parseNRRDWhitespaceSeparatedList(descriptor,parseNRRDKind);break;case"space":descriptor=parseNRRDSpace(descriptor);break;default:console.warn("Unrecognized NRRD field: "+identifier)}return descriptor}var mapNRRDToJavascriptStatic={"block size":"blockSize",blocksize:"blockSize","old min":"oldMin",oldmin:"oldMin","old max":"oldMax",oldmax:"oldMax","data file":"dataFile",datafile:"dataFile","line skip":"lineSkip",lineskip:"lineSkip","byte skip":"byteSkip",byteskip:"byteSkip","sample units":"sampleUnits",sampleunits:"sampleUnits","axis mins":"axisMins","axis maxs":"axisMaxs",centers:"centers",centerings:"centers","space dimension":"spaceDimension","space units":"spaceUnits","space origin":"spaceOrigin","space directions":"spaceDirections","measurement frame":"measurementFrame"};var mapJavascriptToNRRDStatic=function(){var id,m={};for(id in mapNRRDToJavascriptStatic){m[mapNRRDToJavascriptStatic[id]]=id}return m}();function mapNRRDToJavascript(id){id=id.toLowerCase();if(id in mapNRRDToJavascriptStatic)return mapNRRDToJavascriptStatic[id];return id}function mapJavascriptToNRRD(id){if(id in mapJavascriptToNRRDStatic)return mapJavascriptToNRRDStatic[id];return id}function parseNRRDInteger(str){var val=parseInt(str,10);if(Number.isNaN(val))throw new Error("Malformed NRRD integer: "+str);return val}function parseNRRDFloat(str){str=str.toLowerCase();if(str.indexOf("nan")>=0)return NaN;if(str.indexOf("-inf")>=0)return-Infinity;if(str.indexOf("inf")>=0)return Infinity;var val=parseFloat(str);if(Number.isNaN(val))throw new Error("Malformed NRRD float: "+str);return val}function parseNRRDVector(str){if(str=="none")return null;if(str.length<2||str[0]!=="("||str[str.length-1]!==")")throw new Error("Malformed NRRD vector: "+str);return str.slice(1,-1).split(",").map(parseNRRDFloat)}function parseNRRDQuotedString(str){if(length<2||str[0]!='"'||str[str.length-1]!='"'){throw new Error("Invalid NRRD quoted string: "+str)}return str.slice(1,-1).replace('\\"','"')}function serializeNRRDQuotedString(str){return'"'+str.replace('"','\\"')+'"'}var whitespaceListSeparator=/[ \t]+/;function parseNRRDWhitespaceSeparatedList(str,parseElement){return str.split(whitespaceListSeparator).map(parseElement)}function parseNRRDType(descriptor){switch(descriptor.toLowerCase()){case"signed char":case"int8":case"int8_t":return"int8";case"uchar":case"unsigned char":case"uint8":case"uint8_t":return"uint8";case"short":case"short int":case"signed short":case"signed short int":case"int16":case"int16_t":return"int16";case"ushort":case"unsigned short":case"unsigned short int":case"uint16":case"uint16_t":return"uint16";case"int":case"signed int":case"int32":case"int32_t":return"int32";case"uint":case"unsigned int":case"uint32":case"uint32_t":return"uint32";case"longlong":case"long long":case"long long int":case"signed long long":case"signed long long int":case"int64":case"int64_t":return"int64";case"ulonglong":case"unsigned long long":case"unsigned long long int":case"uint64":case"uint64_t":return"uint64";case"float":return"float";case"double":return"double";case"block":return"block";default:console.warn("Unrecognized NRRD type: "+descriptor);return descriptor}}function parseNRRDEncoding(encoding){switch(encoding.toLowerCase()){case"raw":return"raw";case"txt":case"text":case"ascii":return"ascii";case"hex":return"hex";case"gz":case"gzip":return"gzip";case"bz2":case"bzip2":return"bzip2";default:console.warn("Unrecognized NRRD encoding: "+encoding);return encoding}}function parseNRRDSpace(space){switch(space.toLowerCase()){case"right-anterior-superior":case"ras":return"right-anterior-superior";case"left-anterior-superior":case"las":return"left-anterior-superior";case"left-posterior-superior":case"lps":return"left-posterior-superior";case"right-anterior-superior-time":case"rast":return"right-anterior-superior-time";case"left-anterior-superior-time":case"last":return"left-anterior-superior-time";case"left-posterior-superior-time":case"lpst":return"left-posterior-superior-time";case"scanner-xyz":return"scanner-xyz";case"scanner-xyz-time":return"scanner-xyz-time";case"3d-right-handed":return"3D-right-handed";case"3d-left-handed":return"3D-left-handed";case"3d-right-handed-time":return"3D-right-handed-time";case"3d-left-handed-time":return"3D-left-handed-time";default:console.warn("Unrecognized space: "+space);return space}}function parseNRRDEndian(endian){switch(endian.toLowerCase()){case"little":return"little";case"big":return"big";default:console.warn("Unrecognized NRRD endianness: "+endian);return endian}} var dataFileFormatRE=/ (-?\d+) (-?\d+) (-?\d+)(?: (\d+))?$/;function parseNRRDDataFile(dataFile){var match=dataFileFormatRE.exec(dataFile);if(match){if(match.length==5&&match[4]){return{format:dataFile.substring(0,match.index),min:parseNRRDInteger(match[1]),max:parseNRRDInteger(match[2]),step:parseNRRDInteger(match[3]),subdim:parseNRRDInteger(match[4])}}else{return{format:dataFile.substring(0,match.index),min:parseNRRDInteger(match[1]),max:parseNRRDInteger(match[2]),step:parseNRRDInteger(match[3])}}}else{return dataFile}}function serializeNRRDDataFile(dataFile){if(typeof dataFile=="string"||dataFile instanceof String){return dataFile}else if("format"in dataFile&&"min"in dataFile&&"max"in dataFile&&"step"in dataFile){if("subdim"in dataFile){return dataFile.format+" "+dataFile.min+" "+dataFile.max+" "+dataFile.step+" "+dataFile.subdim}else{return dataFile.format+" "+dataFile.min+" "+dataFile.max+" "+dataFile.step}}else{throw new Error("Unrecognized data file format!")}}function parseNRRDCenter(center){switch(center.toLowerCase()){case"cell":return"cell";case"node":return"node";case"???":case"none":return null;default:console.warn("Unrecognized NRRD center: "+center);return center}}var NRRDKinds={domain:"domain",space:"space",time:"time",list:"list",point:"point",vector:"vector","covariant-vector":"covariant-vector",normal:"normal",stub:"stub",scalar:"scalar",complex:"complex","2-vector":"2-vector","3-color":"3-color","rgb-color":"RGB-color","hsv-color":"HSV-color","xyz-color":"XYZ-color","4-color":"4-color","rgba-color":"RGBA-color","3-vector":"3-vector","3-gradient":"3-gradient","3-normal":"3-normal","4-vector":"4-vector",quaternion:"quaternion","2d-symmetric-matrix":"2D-symmetric-matrix","2d-masked-symmetric-matrix":"2D-masked-symmetric-matrix","2d-matrix":"2D-matrix","2d-masked-matrix":"2D-masked-matrix","3d-symmetric-matrix":"3D-symmetric-matrix","3d-masked-symmetric-matrix":"3D-masked-symmetric-matrix","3d-matrix":"3D-matrix","3d-masked-matrix":"3D-masked-matrix","???":null,none:null};function parseNRRDKind(kind){var kindLC=kind.toLowerCase();if(kindLC in NRRDKinds)return NRRDKinds[kindLC];console.warn("Unrecognized NRRD kind: "+kind);return kind}function serializeNRRDOptional(a){return a===null?"???":a}var systemEndianness=function(){var buf=new ArrayBuffer(4),intArr=new Uint32Array(buf),byteArr=new Uint8Array(buf);intArr[0]=16909060;if(byteArr[0]==1&&byteArr[1]==2&&byteArr[2]==3&&byteArr[3]==4){return"big"}else if(byteArr[0]==4&&byteArr[1]==3&&byteArr[2]==2&&byteArr[3]==1){return"little"}console.warn("Unrecognized system endianness!");return undefined}();function parseNRRDRawData(buffer,type,sizes,options){var i,arr,view,totalLen=1,endianFlag;for(i=0;i<sizes.length;i++){if(sizes[i]<=0)throw new Error("Sizes should be a list of positive (>0) integers!");totalLen*=sizes[i]}if(type=="block"){return buffer.slice(0,totalLen*options.blockSize)}else if(type=="int8"||type=="uint8"||options.endian==systemEndianness){switch(type){case"int8":checkSize(1);return new Int8Array(buffer.slice(0,totalLen));case"uint8":checkSize(1);return new Uint8Array(buffer.slice(0,totalLen));case"int16":checkSize(2);return new Int16Array(buffer.slice(0,totalLen*2));case"uint16":checkSize(2);return new Uint16Array(buffer.slice(0,totalLen*2));case"int32":checkSize(4);return new Int32Array(buffer.slice(0,totalLen*4));case"uint32":checkSize(4);return new Uint32Array(buffer.slice(0,totalLen*4));case"float":checkSize(4);return new Float32Array(buffer.slice(0,totalLen*4));case"double":checkSize(8);return new Float64Array(buffer.slice(0,totalLen*8));default:console.warn("Unsupported NRRD type: "+type+", returning raw buffer.");return undefined}}else{switch(options.endian){case"big":endianFlag=false;break;case"little":endianFlag=true;break;default:console.warn("Unsupported endianness in NRRD file: "+options.endian);return undefined}view=new DataView(buffer);switch(type){case"int8":arr=new Int8Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getInt8(i)}return arr;case"uint8":arr=new Uint8Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getUint8(i)}return arr;case"int16":arr=new Int16Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getInt16(i*2)}return arr;case"uint16":arr=new Uint16Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getUint16(i*2)}return arr;case"int32":arr=new Int32Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getInt32(i*4)}return arr;case"uint32":arr=new Uint32Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getUint32(i*4)}return arr;case"float":arr=new Float32Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getFloat32(i*4)}return arr;case"double":arr=new Float64Array(totalLen);for(i=0;i<totalLen;i++){arr[i]=view.getFloat64(i*8)}return arr;default:console.warn("Unsupported NRRD type: "+type+", returning raw buffer.");return undefined}}function checkSize(sizeOfType){if(buffer.byteLength<totalLen*sizeOfType)throw new Error("NRRD file does not contain enough data!")}}var whitespaceDataValueListSeparatorRE=/[ \t\n\r\v\f]+/;function parseNRRDTextData(buffer,type,sizes){var i,buf8,str,strList,totalLen=1;for(i=0;i<sizes.length;i++){if(sizes[i]<=0)throw new Error("Sizes should be a list of positive (>0) integers!");totalLen*=sizes[i]}buf8=new Uint8Array(buffer);str=String.fromCharCode.apply(null,buf8);strList=str.split(whitespaceDataValueListSeparatorRE);if(strList.length<totalLen){throw new Error("Not enough data in NRRD file!")}else if(strList.length>totalLen){if(strList[0]==="")strList=strList.slice(1);strList=strList.slice(0,totalLen)}switch(type){case"int8":return new Int8Array(strList.map(parseNRRDInteger));case"uint8":return new Uint8Array(strList.map(parseNRRDInteger));case"int16":return new Int16Array(strList.map(parseNRRDInteger));case"uint16":return new Uint16Array(strList.map(parseNRRDInteger));case"int32":return new Int32Array(strList.map(parseNRRDInteger));case"uint32":return new Uint32Array(strList.map(parseNRRDInteger));case"float":return new Float32Array(strList.map(parseNRRDFloat));case"double":return new Float64Array(strList.map(parseNRRDFloat));default:console.warn("Unsupported NRRD type: "+type+".");return undefined}}function getNRRDTypeSize(type){switch(type){case"int8":return 1;case"uint8":return 1;case"int16":return 2;case"uint16":return 2;case"int32":return 4;case"uint32":return 4;case"int64":return 8;case"uint64":return 8;case"float":return 4;case"double":return 8;default:throw new Error("Do not know the size of NRRD type: "+type)}}function checkNRRD(ret){if(ret.dimension===undefined){throw new Error("Dimension missing from NRRD file!")}else if(ret.type===undefined){throw new Error("Type missing from NRRD file!")}else if(ret.encoding===undefined){throw new Error("Encoding missing from NRRD file!")}else if(ret.sizes===undefined){throw new Error("Sizes missing from NRRD file!")}if(ret.type!="block"&&ret.type!="int8"&&ret.type!="uint8"&&ret.encoding!="ascii"&&ret.endian===undefined){throw new Error("Endianness missing from NRRD file!")}else if(ret.type=="block"&&ret.blockSize===undefined){throw new Error("Missing block size in NRRD file!")}if(ret.dimension===0){throw new Error("Zero-dimensional NRRD file?")}else if(ret.dimension!=ret.sizes.length){throw new Error("Length of 'sizes' is different from 'dimension' in an NRRD file!")}else if(ret.spacings&&ret.dimension!=ret.spacings.length){throw new Error("Length of 'spacings' is different from 'dimension' in an NRRD file!")}else if(ret.thicknesses&&ret.dimension!=ret.thicknesses.length){throw new Error("Length of 'thicknesses' is different from 'dimension' in an NRRD file!")}else if(ret.axisMins&&ret.dimension!=ret.axisMins.length){throw new Error("Length of 'axis mins' is different from 'dimension' in an NRRD file!")}else if(ret.axisMaxs&&ret.dimension!=ret.axisMaxs.length){throw new Error("Length of 'axis maxs' is different from 'dimension' in an NRRD file!")}else if(ret.centers&&ret.dimension!=ret.centers.length){throw new Error("Length of 'centers' is different from 'dimension' in an NRRD file!")}else if(ret.labels&&ret.dimension!=ret.labels.length){throw new Error("Length of 'labels' is different from 'dimension' in an NRRD file!")}else if(ret.units&&ret.dimension!=ret.units.length){throw new Error("Length of 'units' is different from 'dimension' in an NRRD file!")}else if(ret.kinds&&ret.dimension!=ret.kinds.length){throw new Error("Length of 'kinds' is different from 'dimension' in an NRRD file!")}if((ret.data===undefined||ret.data.length===0)&&(ret.buffer===undefined||ret.buffer.byteLength===0)&&ret.dataFile===undefined){throw new Error("NRRD file has neither inline or external data!")}}function castTypedArray(data,type){switch(type){case"int8":return new Int8Array(data);case"uint8":return new Uint8Array(data);case"int16":return new Int16Array(data);case"uint16":return new Uint16Array(data);case"int32":return new Int32Array(data);case"uint32":return new Uint32Array(data);case"float":return new Float32Array(data);case"double":return new Float64Array(data);default:throw new Error("Cannot cast to NRRD type: "+type)}}function serializeToBuffer(data,type,endian){var i,endianFlag,view,nativeSize=getNRRDTypeSize(type),buffer=new ArrayBuffer(data.length*nativeSize);switch(endian){case"big":endianFlag=false;break;case"little":endianFlag=true;break;default:console.warn("Unsupported endianness in NRRD file: "+endian);return undefined}view=new DataView(buffer);switch(type){case"int8":for(i=0;i<data.length;i++){view.setInt8(i,data[i],endianFlag)}return buffer;case"uint8":for(i=0;i<data.length;i++){view.setUint8(i,data[i],endianFlag)}return buffer;case"int16":for(i=0;i<data.length;i++){view.setInt16(i*2,data[i],endianFlag)}return buffer;case"uint16":for(i=0;i<data.length;i++){view.setUint16(i*2,data[i],endianFlag)}return buffer;case"int32":for(i=0;i<data.length;i++){view.setInt32(i*4,data[i],endianFlag)}return buffer;case"uint32":for(i=0;i<data.length;i++){view.setUint32(i*4,data[i],endianFlag)}return buffer;case"float":for(i=0;i<data.length;i++){view.setFloat32(i*4,data[i],endianFlag)}return buffer;case"double":for(i=0;i<data.length;i++){view.setFloat64(i*8,data[i],endianFlag)}return buffer;default:console.warn("Cannot serialize NRRD type: "+type+".");return undefined}}function serializeToTextBuffer(data){var i,strs=new Array(data.length),str,buffer,arr;for(i=0;i<data.length;i++){strs[i]=""+data[i]}str=strs.join(" ");buffer=new ArrayBuffer(str.length);arr=new Uint8Array(buffer);for(i=0;i<arr.length;i++){arr[i]=str.charCodeAt(i)}return buffer}},{assert:3}],51:[function(require,module,exports){"use strict";var assign=require("./lib/utils/common").assign;var deflate=require("./lib/deflate");var inflate=require("./lib/inflate");var constants=require("./lib/zlib/constants");var pako={};assign(pako,deflate,inflate,constants);module.exports=pako},{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){"use strict";var zlib_deflate=require("./zlib/deflate");var utils=require("./utils/common");var strings=require("./utils/strings");var msg=require("./zlib/messages");var ZStream=require("./zlib/zstream");var toString=Object.prototype.toString;var Z_NO_FLUSH=0;var Z_FINISH=4;var Z_OK=0;var Z_STREAM_END=1;var Z_SYNC_FLUSH=2;var Z_DEFAULT_COMPRESSION=-1;var Z_DEFAULT_STRATEGY=0;var Z_DEFLATED=8;function Deflate(options){if(!(this instanceof Deflate))return new Deflate(options);this.options=utils.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY,to:""},options||{});var opt=this.options;if(opt.raw&&opt.windowBits>0){opt.windowBits=-opt.windowBits}else if(opt.gzip&&opt.windowBits>0&&opt.windowBits<16){opt.windowBits+=16}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_deflate.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy);if(status!==Z_OK){throw new Error(msg[status])}if(opt.header){zlib_deflate.deflateSetHeader(this.strm,opt.header)}if(opt.dictionary){var dict;if(typeof opt.dictionary==="string"){dict=strings.string2buf(opt.dictionary)}else if(toString.call(opt.dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(opt.dictionary)}else{dict=opt.dictionary}status=zlib_deflate.deflateSetDictionary(this.strm,dict);if(status!==Z_OK){throw new Error(msg[status])}this._dict_set=true}}Deflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var status,_mode;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?Z_FINISH:Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.string2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_deflate.deflate(strm,_mode);if(status!==Z_STREAM_END&&status!==Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.avail_out===0||strm.avail_in===0&&(_mode===Z_FINISH||_mode===Z_SYNC_FLUSH)){if(this.options.to==="string"){this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output,strm.next_out)))}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}while((strm.avail_in>0||strm.avail_out===0)&&status!==Z_STREAM_END);if(_mode===Z_FINISH){status=zlib_deflate.deflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===Z_OK}if(_mode===Z_SYNC_FLUSH){this.onEnd(Z_OK);strm.avail_out=0;return true}return true};Deflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Deflate.prototype.onEnd=function(status){if(status===Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function deflate(input,options){var deflator=new Deflate(options);deflator.push(input,true);if(deflator.err){throw deflator.msg}return deflator.result}function deflateRaw(input,options){options=options||{};options.raw=true;return deflate(input,options)}function gzip(input,options){options=options||{};options.gzip=true;return deflate(input,options)}exports.Deflate=Deflate;exports.deflate=deflate;exports.deflateRaw=deflateRaw;exports.gzip=gzip},{"./utils/common":54,"./utils/strings":55,"./zlib/deflate":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){"use strict";var zlib_inflate=require("./zlib/inflate");var utils=require("./utils/common");var strings=require("./utils/strings");var c=require("./zlib/constants");var msg=require("./zlib/messages");var ZStream=require("./zlib/zstream");var GZheader=require("./zlib/gzheader");var toString=Object.prototype.toString;function Inflate(options){if(!(this instanceof Inflate))return new Inflate(options);this.options=utils.assign({chunkSize:16384,windowBits:0,to:""},options||{});var opt=this.options;if(opt.raw&&opt.windowBits>=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports.Inflate=Inflate;exports.inflate=inflate;exports.inflateRaw=inflateRaw;exports.ungzip=inflate},{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){arguments[4][6][0].apply(exports,arguments)},{dup:6}],55:[function(require,module,exports){"use strict";var utils=require("./common");var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c2=str.charCodeAt(m_pos+1);if((c2&64512)===56320){c=65536+(c-55296<<10)+(c2-56320);m_pos++}}buf_len+=c<128?1:c<2048?2:c<65536?3:4}buf=new utils.Buf8(buf_len);for(i=0,m_pos=0;i<buf_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c2=str.charCodeAt(m_pos+1);if((c2&64512)===56320){c=65536+(c-55296<<10)+(c2-56320);m_pos++}}if(c<128){buf[i++]=c}else if(c<2048){buf[i++]=192|c>>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i<len;i++){result+=String.fromCharCode(buf[i])}return result}exports.buf2binstring=function(buf){return buf2binstring(buf,buf.length)};exports.binstring2buf=function(str){var buf=new utils.Buf8(str.length);for(var i=0,len=buf.length;i<len;i++){buf[i]=str.charCodeAt(i)}return buf};exports.buf2string=function(buf,max){var i,out,c,c_len;var len=max||buf.length;var utf16buf=new Array(len*2);for(out=0,i=0;i<len;){c=buf[i++];if(c<128){utf16buf[out++]=c;continue}c_len=_utf8len[c];if(c_len>4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i<len){c=c<<6|buf[i++]&63;c_len--}if(c_len>1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},{"./common":54}],56:[function(require,module,exports){arguments[4][7][0].apply(exports,arguments)},{dup:7}],57:[function(require,module,exports){arguments[4][8][0].apply(exports,arguments)},{dup:8}],58:[function(require,module,exports){arguments[4][9][0].apply(exports,arguments)},{dup:9}],59:[function(require,module,exports){"use strict";var utils=require("../utils/common");var trees=require("./trees");var adler32=require("./adler32");var crc32=require("./crc32");var msg=require("./messages");var Z_NO_FLUSH=0;var Z_PARTIAL_FLUSH=1;var Z_FULL_FLUSH=3;var Z_FINISH=4;var Z_BLOCK=5;var Z_OK=0;var Z_STREAM_END=1;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_BUF_ERROR=-5;var Z_DEFAULT_COMPRESSION=-1;var Z_FILTERED=1;var Z_HUFFMAN_ONLY=2;var Z_RLE=3;var Z_FIXED=4;var Z_DEFAULT_STRATEGY=0;var Z_UNKNOWN=2;var Z_DEFLATED=8;var MAX_MEM_LEVEL=9;var MAX_WBITS=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;function err(strm,errorCode){strm.msg=msg[errorCode];return errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}function flush_pending(strm){var s=strm.state;var len=s.pending;if(len>strm.avail_out){len=strm.avail_out}if(len===0){return}utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out);strm.next_out+=len;s.pending_out+=len;strm.total_out+=len;strm.avail_out-=len;s.pending-=len;if(s.pending===0){s.pending_out=0}}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last);s.block_start=s.strstart;flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255;s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size){len=size}if(len===0){return 0}strm.avail_in-=len;utils.arraySet(buf,strm.input,strm.next_in,len,start);if(strm.state.wrap===1){strm.adler=adler32(strm.adler,buf,len,start)}else if(strm.state.wrap===2){strm.adler=crc32(strm.adler,buf,len,start)}strm.next_in+=len;strm.total_in+=len;return len}function longest_match(s,cur_match){var chain_length=s.max_chain_length;var scan=s.strstart;var match;var len;var best_len=s.prev_length;var nice_match=s.nice_match;var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0;var _win=s.window;var wmask=s.w_mask;var prev=s.prev;var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match){chain_length>>=2}if(nice_match>s.lookahead){nice_match=s.lookahead}do{match=cur_match;if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue}scan+=2;match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len}return s.lookahead}function fill_window(s){var _w_size=s.w_size;var p,n,m,more,str;do{more=s.window_size-s.lookahead-s.strstart;if(s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0);s.match_start-=_w_size;s.strstart-=_w_size;s.block_start-=_w_size;n=s.hash_size;p=n;do{m=s.head[--p];s.head[p]=m>=_w_size?m-_w_size:0}while(--n);n=_w_size;p=n;do{m=s.prev[--p];s.prev[p]=m>=_w_size?m-_w_size:0}while(--n);more+=_w_size}if(s.strm.avail_in===0){break}n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more);s.lookahead+=n;if(s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert;s.ins_h=s.window[str];s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;while(s.insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;s.insert--;if(s.lookahead+s.insert<MIN_MATCH){break}}}}while(s.lookahead<MIN_LOOKAHEAD&&s.strm.avail_in!==0)}function deflate_stored(s,flush){var max_block_size=65535;if(max_block_size>s.pending_buf_size-5){max_block_size=s.pending_buf_size-5}for(;;){if(s.lookahead<=1){fill_window(s);if(s.lookahead===0&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.strstart+=s.lookahead;s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){s.lookahead=s.strstart-max_start;s.strstart=max_start;flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.strstart>s.block_start){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head;var bflush;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}if(hash_head!==0&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head)}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;if(s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do{s.strstart++;s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}while(--s.match_length!==0);s.strstart++}else{s.strstart+=s.match_length;s.match_length=0;s.ins_h=s.window[s.strstart];s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_slow(s,flush){var hash_head;var bflush;var max_insert;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}s.prev_length=s.match_length;s.prev_match=s.match_start;s.match_length=MIN_MATCH-1;if(hash_head!==0&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);if(s.match_length<=5&&(s.strategy===Z_FILTERED||s.match_length===MIN_MATCH&&s.strstart-s.match_start>4096)){s.match_length=MIN_MATCH-1}}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH;bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH);s.lookahead-=s.prev_length-1;s.prev_length-=2;do{if(++s.strstart<=max_insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}}while(--s.prev_length!==0);s.match_available=0;s.match_length=MIN_MATCH-1;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}else if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);if(bflush){flush_block_only(s,false)}s.strstart++;s.lookahead--;if(s.strm.avail_out===0){return BS_NEED_MORE}}else{s.match_available=1;s.strstart++;s.lookahead--}}if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);s.match_available=0}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_rle(s,flush){var bflush;var prev;var scan,strend;var _win=s.window;for(;;){if(s.lookahead<=MAX_MATCH){fill_window(s);if(s.lookahead<=MAX_MATCH&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.match_length=0;if(s.lookahead>=MIN_MATCH&&s.strstart>0){scan=s.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=MAX_MATCH-(strend-scan);if(s.match_length>s.lookahead){s.match_length=s.lookahead}}}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;s.strstart+=s.match_length;s.match_length=0}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){fill_window(s);if(s.lookahead===0){if(flush===Z_NO_FLUSH){return BS_NEED_MORE}break}}s.match_length=0;bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length

this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table;configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size;zero(s.head);s.max_lazy_match=configuration_table[s.level].max_lazy;s.good_match=configuration_table[s.level].good_length;s.nice_match=configuration_table[s.level].nice_length;s.max_chain_length=configuration_table[s.level].max_chain;s.strstart=0;s.block_start=0;s.lookahead=0;s.insert=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;s.ins_h=0}function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2);this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2);this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new utils.Buf16(MAX_BITS+1);this.heap=new utils.Buf16(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new utils.Buf16(2*L_CODES+1);zero(this.depth);this.l_buf=0;this.lit_bufsize=0;this.last_lit=0;this.d_buf=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state){return err(strm,Z_STREAM_ERROR)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;s=strm.state;s.pending=0;s.pending_out=0;if(s.wrap<0){s.wrap=-s.wrap}s.status=s.wrap?INIT_STATE
BUSY_STATE;strm.adler=s.wrap===2?0:1;s.last_flush=Z_NO_FLUSH;trees._tr_init(s);return Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK){lm_init(strm.state)}return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR}if(strm.state.wrap!==2){return Z_STREAM_ERROR}strm.state.gzhead=head;return Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm){return Z_STREAM_ERROR}var wrap=1;if(level===Z_DEFAULT_COMPRESSION){level=6}if(windowBits<0){wrap=0;windowBits=-windowBits}else if(windowBits>15){wrap=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED){return err(strm,Z_STREAM_ERROR)}if(windowBits===8){windowBits=9}var s=new DeflateState;strm.state=s;s.strm=strm;s.wrap=wrap;s.gzhead=null;s.w_bits=windowBits;s.w_size=1<<s.w_bits;s.w_mask=s.w_size-1;s.hash_bits=memLevel+7;s.hash_size=1<<s.hash_bits;s.hash_mask=s.hash_size-1;s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH);s.window=new utils.Buf8(s.w_size*2);s.head=new utils.Buf16(s.hash_size);s.prev=new utils.Buf16(s.w_size);s.lit_bufsize=1<<memLevel+6;s.pending_buf_size=s.lit_bufsize*4;s.pending_buf=new utils.Buf8(s.pending_buf_size);s.d_buf=s.lit_bufsize>>1;s.l_buf=(1+2)*s.lit_bufsize;s.level=level;s.strategy=strategy;s.method=method;return deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,Z_DEFLATED,MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY)}function deflate(strm,flush){var old_flush,s;var beg,val;if(!strm||!strm.state||flush>Z_BLOCK||flush<0){return strm?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR}s=strm.state;if(!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH){return err(strm,strm.avail_out===0?Z_BUF_ERROR:Z_STREAM_ERROR)}s.strm=strm;old_flush=s.last_flush;s.last_flush=flush;if(s.status===INIT_STATE){if(s.wrap===2){strm.adler=0;put_byte(s,31);put_byte(s,139);put_byte(s,8);if(!s.gzhead){put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,OS_CODE);s.status=BUSY_STATE}else{put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(!s.gzhead.extra?0:4)+(!s.gzhead.name?0:8)+(!s.gzhead.comment?0:16));put_byte(s,s.gzhead.time&255);put_byte(s,s.gzhead.time>>8&255);put_byte(s,s.gzhead.time>>16&255);put_byte(s,s.gzhead.time>>24&255);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,s.gzhead.os&255);if(s.gzhead.extra&&s.gzhead.extra.length){put_byte(s,s.gzhead.extra.length&255);put_byte(s,s.gzhead.extra.length>>8&255)}if(s.gzhead.hcrc){strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)}s.gzindex=0;s.status=EXTRA_STATE}}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8;var level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2){level_flags=0}else if(s.level<6){level_flags=1}else if(s.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s.strstart!==0){header|=PRESET_DICT}header+=31-header%31;s.status=BUSY_STATE;putShortMSB(s,header);if(s.strstart!==0){putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}strm.adler=1}}if(s.status===EXTRA_STATE){if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){break}}put_byte(s,s.gzhead.extra[s.gzindex]&255);s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(s.gzindex===s.gzhead.extra.length){s.gzindex=0;s.status=NAME_STATE}}else{s.status=NAME_STATE}}if(s.status===NAME_STATE){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.name.length){val=s.gzhead.name.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.gzindex=0;s.status=COMMENT_STATE}}else{s.status=COMMENT_STATE}}if(s.status===COMMENT_STATE){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.comment.length){val=s.gzhead.comment.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.status=HCRC_STATE}}else{s.status=HCRC_STATE}}if(s.status===HCRC_STATE){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size){flush_pending(strm)}if(s.pending+2<=s.pending_buf_size){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);strm.adler=0;s.status=BUSY_STATE}}else{s.status=BUSY_STATE}}if(s.pending!==0){flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH){return err(strm,Z_BUF_ERROR)}if(s.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR)}if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY?deflate_huff(s,flush):s.strategy===Z_RLE?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s.last_flush=-1}return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH){trees._tr_align(s)}else if(flush!==Z_BLOCK){trees._tr_stored_block(s,0,0,false);if(flush===Z_FULL_FLUSH){zero(s.head);if(s.lookahead===0){s.strstart=0;s.block_start=0;s.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}}if(flush!==Z_FINISH){return Z_OK}if(s.wrap<=0){return Z_STREAM_END}if(s.wrap===2){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);put_byte(s,strm.adler>>16&255);put_byte(s,strm.adler>>24&255);put_byte(s,strm.total_in&255);put_byte(s,strm.total_in>>8&255);put_byte(s,strm.total_in>>16&255);put_byte(s,strm.total_in>>24&255)}else{putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}flush_pending(strm);if(s.wrap>0){s.wrap=-s.wrap}return s.pending!==0?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state){return Z_STREAM_ERROR}status=strm.state.status;if(status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE){return err(strm,Z_STREAM_ERROR)}strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var s;var str,n;var wrap;var avail;var next;var input;var tmpDict;if(!strm||!strm.state){return Z_STREAM_ERROR}s=strm.state;wrap=s.wrap;if(wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead){return Z_STREAM_ERROR}if(wrap===1){strm.adler=adler32(strm.adler,dictionary,dictLength,0)}s.wrap=0;if(dictLength>=s.w_size){if(wrap===0){zero(s.head);s.strstart=0;s.block_start=0;s.insert=0}tmpDict=new utils.Buf8(s.w_size);utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0);dictionary=tmpDict;dictLength=s.w_size}avail=strm.avail_in;next=strm.next_in;input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary;fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart;n=s.lookahead-(MIN_MATCH-1);do{s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++}while(--n);s.strstart=str;s.lookahead=MIN_MATCH-1;fill_window(s)}s.strstart+=s.lookahead;s.block_start=s.strstart;s.insert=s.lookahead;s.lookahead=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;strm.next_in=next;strm.input=input;strm.avail_in=avail;s.wrap=wrap;return Z_OK}exports.deflateInit=deflateInit;exports.deflateInit2=deflateInit2;exports.deflateReset=deflateReset;exports.deflateResetKeep=deflateResetKeep;exports.deflateSetHeader=deflateSetHeader;exports.deflate=deflate;exports.deflateEnd=deflateEnd;exports.deflateSetDictionary=deflateSetDictionary;exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module.exports=GZheader},{}],61:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{dup:11}],62:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63,dup:12}],63:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{"../utils/common":54,dup:13}],64:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{dup:14}],65:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{"../utils/common":54,dup:15}],66:[function(require,module,exports){arguments[4][16][0].apply(exports,arguments)},{dup:16}],67:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i<args.length){args[i++]=arguments[i]}return process.nextTick(function afterTick(){fn.apply(null,args)})}}}).call(this,require("_process"))},{_process:68}],68:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],69:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports&&!exports.nodeType&&exports;var freeModule=typeof module=="object"&&module&&!module.nodeType&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;k+=base){if(index>=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&&currentValue<m){m=currentValue}}handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount}}++delta;++n}return output.join("")}function toUnicode(input){return mapDomain(input,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(input){return mapDomain(input,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define("punycode",function(){return punycode})}else if(freeExports&&freeModule){if(module.exports==freeExports){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],70:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],71:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],72:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":70,"./encode":71}],73:[function(require,module,exports){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args");var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v<keys.length;v++){var method=keys[v];if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;processNextTick(onEndNT,this)}function onEndNT(self){self.end()}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}},{"./_stream_readable":74,"./_stream_writable":76,"core-util-is":24,inherits:28,"process-nextick-args":67}],74:[function(require,module,exports){(function(process){"use strict";module.exports=Readable;var processNextTick=require("process-nextick-args");var isArray=require("isarray");var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");var util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util");var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=require("./internal/streams/BufferList");var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc;return this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}if(state.ended||state.reading){doRead=false;debug("reading or ended",doRead)}else if(doRead){debug("do read");state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false;if(!state.reading)n=howMuchToRead(nOrig,state)}var ret;if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){debug("maybeReadMore read 0");stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:

state.pipes.push(dest);break}state.pipesCount+=1;debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)processNextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){debug("onunpipe");if(readable===src){cleanup()}}function onend(){debug("onend");dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=false;function cleanup(){debug("cleanup");dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);src.removeListener("data",ondata);cleanedUp=true;if(state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain))ondrain()}var increasedAwaitDrain=false;src.on("data",ondata);function ondata(chunk){debug("ondata");increasedAwaitDrain=false;var ret=dest.write(chunk);if(false===ret&&!increasedAwaitDrain){if((state.pipesCount===1&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i<len;i++){dests[i].emit("unpipe",this)}return this}var index=indexOf(state.pipes,dest);if(index===-1)return this;state.pipes.splice(index,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"){if(this._readableState.flowing!==false)this.resume()}else if(ev==="readable"){var state=this._readableState;if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.emittedReadable=false;if(!state.reading){processNextTick(nReadingNextTick,this)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){var state=this._readableState;if(!state.flowing){debug("resume");state.flowing=true;resume(this,state)}return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;processNextTick(resume_,stream,state)}}function resume_(stream,state){if(!state.reading){debug("resume read 0");stream.read(0)}state.resumeScheduled=false;state.awaitDrain=0;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(false!==this._readableState.flowing){debug("pause");this._readableState.flowing=false;this.emit("pause")}return this};function flow(stream){var state=stream._readableState;debug("flow",state.flowing);while(state.flowing&&stream.read()!==null){}}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){debug("wrapped data");if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){debug("wrapped _read",n);if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;var ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(n<list.head.data.length){ret=list.head.data.slice(0,n);list.head.data=list.head.data.slice(n)}else if(n===list.head.data.length){ret=list.shift()}else{ret=hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list)}return ret}function copyFromBufferString(n,list){var p=list.head;var c=1;var ret=p.data;n-=ret.length;while(p=p.next){var str=p.data;var nb=n>str.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{"./_stream_duplex":73,"./internal/streams/BufferList":77,_process:68,buffer:20,"buffer-shims":19,"core-util-is":24,events:26,inherits:28,isarray:78,"process-nextick-args":67,"string_decoder/":80,util:5}],75:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);this._transformState=new TransformState(this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}this.once("prefinish",function(){if(typeof this._flush==="function")this._flush(function(er,data){done(stream,er,data)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("_transform() is not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!==null&&data!==undefined)stream.push(data);var ws=stream._writableState;var ts=stream._transformState;if(ws.length)throw new Error("Calling transform done when ws.length != 0");if(ts.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":73,"core-util-is":24,inherits:28}],76:[function(require,module,exports){(function(process){"use strict";module.exports=Writable;var processNextTick=require("process-nextick-args");var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest=new WriteReq(chunk,encoding,cb);if(last){last.next=state.lastBufferedRequest}else{state.bufferedRequest=state.lastBufferedRequest}state.bufferedRequestCount+=1}else{doWrite(stream,state,false,len,chunk,encoding,cb)}return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;if(writev)stream._writev(chunk,state.onwrite);else stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){--state.pendingcb;if(sync)processNextTick(cb,er);else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);if(!finished&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest){clearBuffer(stream,state)}if(sync){asyncWrite(afterWrite,stream,state,finished,cb)}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);state.pendingcb--;cb();finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount;var buffer=new Array(l);var holder=state.corkedRequestsFree;holder.entry=entry;var count=0;while(entry){buffer[count]=entry;entry=entry.next;count+=1}doWrite(stream,state,true,state.length,buffer,"",holder.finish);state.pendingcb++;state.lastBufferedRequest=null;if(holder.next){state.corkedRequestsFree=holder.next;holder.next=null}else{state.corkedRequestsFree=new CorkedRequest(state)}}else{while(entry){var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,false,len,chunk,encoding,cb);entry=entry.next;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}state.bufferedRequestCount=0;state.bufferedRequest=entry;state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(chunk!==null&&chunk!==undefined)this.write(chunk,encoding);if(state.corked){state.corked=1;this.uncork()}if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(state){return state.ending&&state.length===0&&state.bufferedRequest===null&&!state.finished&&!state.writing}function prefinish(stream,state){if(!state.prefinished){state.prefinished=true;stream.emit("prefinish")}}function finishMaybe(stream,state){var need=needFinish(state);if(need){if(state.pendingcb===0){prefinish(stream,state);state.finished=true;stream.emit("finish")}else{prefinish(stream,state)}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)processNextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(err){var entry=_this.entry;_this.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=_this}else{state.corkedRequestsFree=_this}}}}).call(this,require("_process"))},{"./_stream_duplex":73,_process:68,buffer:20,"buffer-shims":19,"core-util-is":24,events:26,inherits:28,"process-nextick-args":67,"util-deprecate":84}],77:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");module.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:20,"buffer-shims":19}],78:[function(require,module,exports){arguments[4][21][0].apply(exports,arguments)},{dup:21}],79:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":75}],80:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:20}],81:[function(require,module,exports){(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):factory(global.THREE=global.THREE||{})})(this,function(exports){"use strict";if(Number.EPSILON===undefined){Number.EPSILON=Math.pow(2,-52)}if(Number.isInteger===undefined){Number.isInteger=function(value){return typeof value==="number"&&isFinite(value)&&Math.floor(value)===value}}if(Math.sign===undefined){Math.sign=function(x){return x<0?-1:x>0?1:+x}}if(Function.prototype.name===undefined){Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}})}if(Object.assign===undefined){(function(){Object.assign=function(target){"use strict";if(target===undefined||target===null){throw new TypeError("Cannot convert undefined or null to object")}var output=Object(target);for(var index=1;index<arguments.length;index++){var source=arguments[index];if(source!==undefined&&source!==null){for(var nextKey in source){if(Object.prototype.hasOwnProperty.call(source,nextKey)){output[nextKey]=source[nextKey]}}}}return output}})()}function EventDispatcher(){}Object.assign(EventDispatcher.prototype,{addEventListener:function(type,listener){if(this._listeners===undefined)this._listeners={};var listeners=this._listeners;if(listeners[type]===undefined){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}},hasEventListener:function(type,listener){if(this._listeners===undefined)return false;var listeners=this._listeners;return listeners[type]!==undefined&&listeners[type].indexOf(listener)!==-1},removeEventListener:function(type,listener){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[type];if(listenerArray!==undefined){var index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}},dispatchEvent:function(event){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[event.type];if(listenerArray!==undefined){event.target=this;var array=listenerArray.slice(0);for(var i=0,l=array.length;i<l;i++){array[i].call(this,event)}}}});var REVISION="87";var MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var CullFaceFrontBack=3;var FrontFaceDirectionCW=0;var FrontFaceDirectionCCW=1;var BasicShadowMap=0;var PCFShadowMap=1;var PCFSoftShadowMap=2;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading=1;var SmoothShading=2;var NoColors=0;var FaceColors=1;var VertexColors=2;var NoBlending=0;var NormalBlending=1;var AdditiveBlending=2;var SubtractiveBlending=3;var MultiplyBlending=4;var CustomBlending=5;var AddEquation=100;var SubtractEquation=101;var ReverseSubtractEquation=102;var MinEquation=103;var MaxEquation=104;var ZeroFactor=200;var OneFactor=201;var SrcColorFactor=202;var OneMinusSrcColorFactor=203;var SrcAlphaFactor=204;var OneMinusSrcAlphaFactor=205;var DstAlphaFactor=206;var OneMinusDstAlphaFactor=207;var DstColorFactor=208;var OneMinusDstColorFactor=209;var SrcAlphaSaturateFactor=210;var NeverDepth=0;var AlwaysDepth=1;var LessDepth=2;var LessEqualDepth=3;var EqualDepth=4;var GreaterEqualDepth=5;var GreaterDepth=6;var NotEqualDepth=7;var MultiplyOperation=0;var MixOperation=1;var AddOperation=2;var NoToneMapping=0;var LinearToneMapping=1;var ReinhardToneMapping=2;var Uncharted2ToneMapping=3;var CineonToneMapping=4;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var SphericalReflectionMapping=305;var CubeUVReflectionMapping=306;var CubeUVRefractionMapping=307;var RepeatWrapping=1e3;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipMapNearestFilter=1004;var NearestMipMapLinearFilter=1005;var LinearFilter=1006;var LinearMipMapNearestFilter=1007;var LinearMipMapLinearFilter=1008;var UnsignedByteType=1009;var ByteType=1010;var ShortType=1011;var UnsignedShortType=1012;var IntType=1013;var UnsignedIntType=1014;var FloatType=1015;var HalfFloatType=1016;var UnsignedShort4444Type=1017;var UnsignedShort5551Type=1018;var UnsignedShort565Type=1019;var UnsignedInt248Type=1020;var AlphaFormat=1021;var RGBFormat=1022;var RGBAFormat=1023;var LuminanceFormat=1024;var LuminanceAlphaFormat=1025;var RGBEFormat=RGBAFormat;var DepthFormat=1026;var DepthStencilFormat=1027;var RGB_S3TC_DXT1_Format=2001;var RGBA_S3TC_DXT1_Format=2002;var RGBA_S3TC_DXT3_Format=2003;var RGBA_S3TC_DXT5_Format=2004;var RGB_PVRTC_4BPPV1_Format=2100;var RGB_PVRTC_2BPPV1_Format=2101;var RGBA_PVRTC_4BPPV1_Format=2102;var RGBA_PVRTC_2BPPV1_Format=2103;var RGB_ETC1_Format=2151;var LoopOnce=2200;var LoopRepeat=2201;var LoopPingPong=2202;var InterpolateDiscrete=2300;var InterpolateLinear=2301;var InterpolateSmooth=2302;var ZeroCurvatureEnding=2400;var ZeroSlopeEnding=2401;var WrapAroundEnding=2402;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3e3;var sRGBEncoding=3001;var GammaEncoding=3007;var RGBEEncoding=3002;var LogLuvEncoding=3003;var RGBM7Encoding=3004;var RGBM16Encoding=3005;var RGBDEncoding=3006;var BasicDepthPacking=3200;var RGBADepthPacking=3201;var _Math={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");var uuid=new Array(36);var rnd=0,r;return function generateUUID(){for(var i=0;i<36;i++){if(i===8||i===13||i===18||i===23){uuid[i]="-"}else if(i===14){uuid[i]="4"}else{if(rnd<=2)rnd=33554432+Math.random()*16777216|0;r=rnd&15;rnd=rnd>>4;uuid[i]=chars[i===19?r&3|8:r]}}return uuid.join("")}}(),clamp:function(value,min,max){return Math.max(min,Math.min(max,value))},euclideanModulo:function(n,m){return(n%m+m)%m},mapLinear:function(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1)},lerp:function(x,y,t){return(1-t)*x+t*y},smoothstep:function(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*(3-2*x)},smootherstep:function(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*x*(x*(x*6-15)+10)},randInt:function(low,high){return low+Math.floor(Math.random()*(high-low+1))},randFloat:function(low,high){return low+Math.random()*(high-low)},randFloatSpread:function(range){return range*(.5-Math.random())},degToRad:function(degrees){return degrees*_Math.DEG2RAD},radToDeg:function(radians){return radians*_Math.RAD2DEG},isPowerOfTwo:function(value){return(value&value-1)===0&&value!==0},nearestPowerOfTwo:function(value){return Math.pow(2,Math.round(Math.log(value)/Math.LN2))},nextPowerOfTwo:function(value){value--;value|=value>>1;value|=value>>2;value|=value>>4;value|=value>>8;value|=value>>16;value++;return value}};function Vector2(x,y){this.x=x||0;this.y=y||0}Object.defineProperties(Vector2.prototype,{width:{get:function(){return this.x},set:function(value){this.x=value}},height:{get:function(){return this.y},set:function(value){this.y=value}}});Object.assign(Vector2.prototype,{isVector2:true,set:function(x,y){this.x=x;this.y=y;return this},setScalar:function(scalar){this.x=scalar;this.y=scalar;return this},setX:function(x){this.x=x;return this},setY:function(y){this.y=y;return this},setComponent:function(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;default:throw new Error("index is out of range: "+index)}return this},getComponent:function(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+index)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(v){this.x=v.x;this.y=v.y;return this},add:function(v,w){if(w!==undefined){console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.");return this.addVectors(v,w)}this.x+=v.x;this.y+=v.y;return this},addScalar:function(s){this.x+=s;this.y+=s;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(v,s){this.x+=v.x*s;this.y+=v.y*s;return this},sub:function(v,w){if(w!==undefined){console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.")

return this.subVectors(v,w)}this.x-=v.x;this.y-=v.y;return this},subScalar
function(s){this.x-=s;this.y-=s;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(v){this.x*=v.x;this.y*=v.y;return this},multiplyScalar:function(scalar){this.x*=scalar;this.y*=scalar;return this},divide:function(v){this.x/=v.x;this.y/=v.y;return this},divideScalar:function(scalar){return this.multiplyScalar(1/scalar)},min:function(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this},max:function(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this},clamp:function(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));return this},clampScalar:function(){var min=new Vector2;var max=new Vector2;return function clampScalar(minVal,maxVal){min.set(minVal,minVal);max.set(maxVal,maxVal);return this.clamp(min,max)}}(),clampLength:function(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(v){return this.x*v.x+this.y*v.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var angle=Math.atan2(this.y,this.x);if(angle<0)angle+=2*Math.PI;return angle},distanceTo:function(v){return Math.sqrt(this.distanceToSquared(v))},distanceToSquared:function(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy},distanceToManhattan:function(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)},setLength:function(length){return this.normalize().multiplyScalar(length)},lerp:function(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this},lerpVectors:function(v1,v2,alpha){return this.subVectors(v2,v1).multiplyScalar(alpha).add(v1)},equals:function(v){return v.x===this.x&&v.y===this.y},fromArray:function(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;return array},fromBufferAttribute:function(attribute,index,offset){if(offset!==undefined){console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().")}this.x=attribute.getX(index);this.y=attribute.getY(index);return this},rotateAround:function(center,angle){var c=Math.cos(angle),s=Math.sin(angle);var x=this.x-center.x;var y=this.y-center.y;this.x=x*c-y*s+center.x;this.y=x*s+y*c+center.y;return this}});var textureId=0;function Texture(image,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){Object.defineProperty(this,"id",{value:textureId++});this.uuid=_Math.generateUUID();this.name="";this.image=image!==undefined?image:Texture.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=mapping!==undefined?mapping:Texture.DEFAULT_MAPPING;this.wrapS=wrapS!==undefined?wrapS:ClampToEdgeWrapping;this.wrapT=wrapT!==undefined?wrapT:ClampToEdgeWrapping;this.magFilter=magFilter!==undefined?magFilter:LinearFilter;this.minFilter=minFilter!==undefined?minFilter:LinearMipMapLinearFilter;this.anisotropy=anisotropy!==undefined?anisotropy:1;this.format=format!==undefined?format:RGBAFormat;this.type=type!==undefined?type:UnsignedByteType;this.offset=new Vector2(0,0);this.repeat=new Vector2(1,1);this.generateMipmaps=true;this.premultiplyAlpha=false;this.flipY=true;this.unpackAlignment=4;this.encoding=encoding!==undefined?encoding:LinearEncoding;this.version=0;this.onUpdate=null}Texture.DEFAULT_IMAGE=undefined;Texture.DEFAULT_MAPPING=UVMapping;Object.defineProperty(Texture.prototype,"needsUpdate",{set:function(value){if(value===true)this.version++}});Object.assign(Texture.prototype,EventDispatcher.prototype,{constructor:Texture,isTexture:true,clone:function(){return(new this.constructor).copy(this)},copy:function(source){this.name=source.name;this.image=source.image;this.mipmaps=source.mipmaps.slice(0);this.mapping=source.mapping;this.wrapS=source.wrapS;this.wrapT=source.wrapT;this.magFilter=source.magFilter;this.minFilter=source.minFilter;this.anisotropy=source.anisotropy;this.format=source.format;this.type=source.type;this.offset.copy(source.offset);this.repeat.copy(source.repeat);this.generateMipmaps=source.generateMipmaps;this.premultiplyAlpha=source.premultiplyAlpha;this.flipY=source.flipY;this.unpackAlignment=source.unpackAlignment;this.encoding=source.encoding;return this},toJSON:function(meta){if(meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid]}function getDataURL(image){var canvas;if(image instanceof HTMLCanvasElement){canvas=image}else{canvas=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");canvas.width=image.width;canvas.height=image.height;var context=canvas.getContext("2d");if(image instanceof ImageData){context.putImageData(image,0,0)}else{context.drawImage(image,0,0,image.width,image.height)}}if(canvas.width>2048||canvas.height>2048){return canvas.toDataURL("image/jpeg",.6)}else{return canvas.toDataURL("image/png")}}var output={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(this.image!==undefined){var image=this.image;if(image.uuid===undefined){image.uuid=_Math.generateUUID()}if(meta.images[image.uuid]===undefined){meta.images[image.uuid]={uuid:image.uuid,url:getDataURL(image)}}output.image=image.uuid}meta.textures[this.uuid]=output;return output},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(uv){if(this.mapping!==UVMapping)return;uv.multiply(this.repeat);uv.add(this.offset);if(uv.x<0||uv.x>1){switch(this.wrapS){case RepeatWrapping:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.x)%2)===1){uv.x=Math.ceil(uv.x)-uv.x}else{uv.x=uv.x-Math.floor(uv.x)}break}}if(uv.y<0||uv.y>1){switch(this.wrapT){case RepeatWrapping:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.y)%2)===1){uv.y=Math.ceil(uv.y)-uv.y}else{uv.y=uv.y-Math.floor(uv.y)}break}}if(this.flipY){uv.y=1-uv.y}}});function Vector4(x,y,z,w){this.x=x||0;this.y=y||0;this.z=z||0;this.w=w!==undefined?w:1}Object.assign(Vector4.prototype,{isVector4:true,set:function(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this},setScalar:function(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this},setX:function(x){this.x=x;return this},setY:function(y){this.y=y;return this},setZ:function(z){this.z=z;return this},setW:function(w){this.w=w;return this},setComponent:function(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;case 3:this.w=value;break;default:throw new Error("index is out of range: "+index)}return this},getComponent:function(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+index)}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==undefined?v.w:1;return this},add:function(v,w){if(w!==undefined){console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.");return this.addVectors(v,w)}this.x+=v.x;this.y+=v.y;this.z+=v.z;this.w+=v.w;return this},addScalar:function(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;this.w+=v.w*s;return this},sub:function(v,w){if(w!==undefined){console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.");return this.subVectors(v,w)}this.x-=v.x;this.y-=v.y;this.z-=v.z;this.w-=v.w;return this},subScalar:function(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this},applyMatrix4:function(m){var x=this.x,y=this.y,z=this.z,w=this.w;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z+e[12]*w;this.y=e[1]*x+e[5]*y+e[9]*z+e[13]*w;this.z=e[2]*x+e[6]*y+e[10]*z+e[14]*w;this.w=e[3]*x+e[7]*y+e[11]*z+e[15]*w;return this},divideScalar:function(scalar){return this.multiplyScalar(1/scalar)},setAxisAngleFromQuaternion:function(q){this.w=2*Math.acos(q.w);var s=Math.sqrt(1-q.w*q.w);if(s<1e-4){this.x=1;this.y=0;this.z=0}else{this.x=q.x/s;this.y=q.y/s;this.z=q.z/s}return this},setAxisAngleFromRotationMatrix:function(m){var angle,x,y,z,epsilon=.01,epsilon2=.1,te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10];if(Math.abs(m12-m21)<epsilon&&Math.abs(m13-m31)<epsilon&&Math.abs(m23-m32)<epsilon){if(Math.abs(m12+m21)<epsilon2&&Math.abs(m13+m31)<epsilon2&&Math.abs(m23+m32)<epsilon2&&Math.abs(m11+m22+m33-3)<epsilon2){this.set(1,0,0,0);return this}angle=Math.PI;var xx=(m11+1)/2;var yy=(m22+1)/2;var zz=(m33+1)/2;var xy=(m12+m21)/4;var xz=(m13+m31)/4;var yz=(m23+m32)/4;if(xx>yy&&xx>zz){if(xx<epsilon){x=0;y=.707106781;z=.707106781}else{x=Math.sqrt(xx);y=xy/x;z=xz/x}}else if(yy>zz){if(yy<epsilon){x=.707106781;y=0;z=.707106781}else{y=Math.sqrt(yy);x=xy/y;z=yz/y}}else{if(zz<epsilon){x=.707106781;y=.707106781;z=0}else{z=Math.sqrt(zz);x=xz/z;y=yz/z}}this.set(x,y,z,angle);return this}var s=Math.sqrt((m32-m23)*(m32-m23)+(m13-m31)*(m13-m31)+(m21-m12)*(m21-m12));if(Math.abs(s)<.001)s=1;this.x=(m32-m23)/s;this.y=(m13-m31)/s;this.z=(m21-m12)/s;this.w=Math.acos((m11+m22+m33-1)/2);return this},min:function(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);this.w=Math.min(this.w,v.w);return this},max:function(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);this.w=Math.max(this.w,v.w);return this},clamp:function(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));this.w=Math.max(min.w,Math.min(max.w,this.w));return this},clampScalar:function(){var min,max;return function clampScalar(minVal,maxVal){if(min===undefined){min=new Vector4;max=new Vector4}min.set(minVal,minVal,minVal,minVal);max.set(maxVal,maxVal,maxVal,maxVal);return this.clamp(min,max)}}(),clampLength:function(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(v){return this.x*v.x+this.y*v.y+this.z*v.z+this.w*v.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(length){return this.normalize().multiplyScalar(length)},lerp:function(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;this.w+=(v.w-this.w)*alpha;return this},lerpVectors:function(v1,v2,alpha){return this.subVectors(v2,v1).multiplyScalar(alpha).add(v1)},equals:function(v){return v.x===this.x&&v.y===this.y&&v.z===this.z&&v.w===this.w},fromArray:function(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];this.w=array[offset+3];return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;array[offset+3]=this.w;return array},fromBufferAttribute:function(attribute,index,offset){if(offset!==undefined){console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().")}this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);this.w=attribute.getW(index);return this}});function WebGLRenderTarget(width,height,options){this.uuid=_Math.generateUUID();this.width=width;this.height=height;this.scissor=new Vector4(0,0,width,height);this.scissorTest=false;this.viewport=new Vector4(0,0,width,height);options=options||{};if(options.minFilter===undefined)options.minFilter=LinearFilter;this.texture=new Texture(undefined,undefined,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.depthBuffer=options.depthBuffer!==undefined?options.depthBuffer:true;this.stencilBuffer=options.stencilBuffer!==undefined?options.stencilBuffer:true;this.depthTexture=options.depthTexture!==undefined?options.depthTexture:null}Object.assign(WebGLRenderTarget.prototype,EventDispatcher.prototype,{isWebGLRenderTarget:true,setSize:function(width,height){if(this.width!==width||this.height!==height){this.width=width;this.height=height;this.dispose()}this.viewport.set(0,0,width,height);this.scissor.set(0,0,width,height)},clone:function(){return(new this.constructor).copy(this)},copy:function(source){this.width=source.width;this.height=source.height;this.viewport.copy(source.viewport);this.texture=source.texture.clone();this.depthBuffer=source.depthBuffer;this.stencilBuffer=source.stencilBuffer;this.depthTexture=source.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});function WebGLRenderTargetCube(width,height,options){WebGLRenderTarget.call(this,width,height,options);this.activeCubeFace=0;this.activeMipMapLevel=0}WebGLRenderTargetCube.prototype=Object.create(WebGLRenderTarget.prototype);WebGLRenderTargetCube.prototype.constructor=WebGLRenderTargetCube;WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube=true;function Quaternion(x,y,z,w){this._x=x||0;this._y=y||0;this._z=z||0;this._w=w!==undefined?w:1}Object.assign(Quaternion,{slerp:function(qa,qb,qm,t){return qm.copy(qa).slerp(qb,t)},slerpFlat:function(dst,dstOffset,src0,srcOffset0,src1,srcOffset1,t){var x0=src0[srcOffset0+0],y0=src0[srcOffset0+1],z0=src0[srcOffset0+2],w0=src0[srcOffset0+3],x1=src1[srcOffset1+0],y1=src1[srcOffset1+1],z1=src1[srcOffset1+2],w1=src1[srcOffset1+3];if(w0!==w1||x0!==x1||y0!==y1||z0!==z1){var s=1-t,cos=x0*x1+y0*y1+z0*z1+w0*w1,dir=cos>=0?1:-1,sqrSin=1-cos*cos;if(sqrSin>Number.EPSILON){var sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin}var tDir=t*dir;x0=x0*s+x1*tDir;y0=y0*s+y1*tDir;z0=z0*s+z1*tDir;w0=w0*s+w1*tDir;if(s===1-t){var f=1/Math.sqrt(x0*x0+y0*y0+z0*z0+w0*w0);x0*=f;y0*=f;z0*=f;w0*=f}}dst[dstOffset]=x0;dst[dstOffset+1]=y0;dst[dstOffset+2]=z0;dst[dstOffset+3]=w0}});Object.defineProperties(Quaternion.prototype,{x:{get:function(){return this._x},set:function(value){this._x=value;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(value){this._y=value;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(value){this._z=value;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(value){this._w=value;this.onChangeCallback()}}});Object.assign(Quaternion.prototype,{set:function(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this.onChangeCallback();return this},setFromEuler:function(euler,update){if(!(euler&&euler.isEuler)){throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.")}var x=euler._x,y=euler._y,z=euler._z,order=euler.order;var cos=Math.cos;var sin=Math.sin;var c1=cos(x/2);var c2=cos(y/2);var c3=cos(z/2);var s1=sin(x/2);var s2=sin(y/2);var s3=sin(z/2);if(order==="XYZ"){this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3}else if(order==="YXZ"){this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3}else if(order==="ZXY"){this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3}else if(order==="ZYX"){this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3}else if(order==="YZX"){this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3}else if(order==="XZY"){this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3}if(update!==false)this.onChangeCallback();return this},setFromAxisAngle:function(axis,angle){var halfAngle=angle/2,s=Math.sin(halfAngle);this._x=axis.x*s;this._y=axis.y*s;this._z=axis.z*s;this._w=Math.cos(halfAngle);this.onChangeCallback();return this},setFromRotationMatrix:function(m){var te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10],trace=m11+m22+m33,s;if(trace>0){s=.5/Math.sqrt(trace+1);this._w=.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s}else if(m11>m22&&m11>m33){s=2*Math.sqrt(1+m11-m22-m33);this._w=(m32-m23)/s;this._x=.25*s;this._y=(m12+m21)/s;this._z=(m13+m31)/s}else if(m22>m33){s=2*Math.sqrt(1+m22-m11-m33);this._w=(m13-m31)/s;this._x=(m12+m21)/s;this._y=.25*s;this._z=(m23+m32)/s}else{s=2*Math.sqrt(1+m33-m11-m22);this._w=(m21-m12)/s;this._x=(m13+m31)/s;this._y=(m23+m32)/s;this._z=.25*s}this.onChangeCallback();return this},setFromUnitVectors:function(){var v1=new Vector3;var r;var EPS=1e-6;return function setFromUnitVectors(vFrom,vTo){if(v1===undefined)v1=new Vector3;r=vFrom.dot(vTo)+1;if(r<EPS){r=0;if(Math.abs(vFrom.x)>Math.abs(vFrom.z)){v1.set(-vFrom.y,vFrom.x,0)}else{v1.set(0,-vFrom.z,vFrom.y)}}else{v1.crossVectors(vFrom,vTo)}this._x=v1.x;this._y=v1.y;this._z=v1.z;this._w=r;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var l=this.length();if(l===0){this._x=0;this._y=0;this._z=0;this._w=1}else{l=1/l;this._x=this._x*l;this._y=this._y*l;this._z=this._z*l;this._w=this._w*l}this.onChangeCallback();return this},multiply:function(q,p){if(p!==undefined){console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.");return this.multiplyQuaternions(q,p)}return this.multiplyQuaternions(this,q)},premultiply:function(q){return this.multiplyQuaternions(q,this)},multiplyQuaternions:function(a,b){var qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;var qbx=b._x,qby=b._y,qbz=b._z,qbw=b._w;this._x=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;this._y=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;this._z=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;this._w=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;this.onChangeCallback();return this},slerp:function(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);var x=this._x,y=this._y,z=this._z,w=this._w;var cosHalfTheta=w*qb._w+x*qb._x+y*qb._y+z*qb._z;if(cosHalfTheta<0){this._w=-qb._w;this._x=-qb._x;this._y=-qb._y;this._z=-qb._z;cosHalfTheta=-cosHalfTheta}else{this.copy(qb)}if(cosHalfTheta>=1){this._w=w;this._x=x;this._y=y;this._z=z;return this}var sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001){this._w=.5*(w+this._w);this._x=.5*(x+this._x);this._y=.5*(y+this._y);this._z=.5*(z+this._z);return this}var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);var ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;this._w=w*ratioA+this._w*ratioB;this._x=x*ratioA+this._x*ratioB;this._y=y*ratioA+this._y*ratioB;this._z=z*ratioA+this._z*ratioB;this.onChangeCallback();return this},equals:function(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w},fromArray:function(array,offset){if(offset===undefined)offset=0;this._x=array[offset];this._y=array[offset+1];this._z=array[offset+2];this._w=array[offset+3];this.onChangeCallback();return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array},onChange:function(callback){this.onChangeCallback=callback;return this},onChangeCallback:function(){}});function Vector3(x,y,z){this.x=x||0;this.y=y||0;this.z=z||0}Object.assign(Vector3.prototype,{isVector3:true,set:function(x,y,z){this.x=x;this.y=y;this.z=z;return this},setScalar:function(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this},setX:function(x){this.x=x;return this},setY:function(y){this.y=y;return this},setZ:function(z){this.z=z;return this},setComponent:function(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;default:throw new Error("index is out of range: "+index)}return this},getComponent:function(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+index)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(v){this.x=v.x;this.y=v.y;this.z=v.z;return this},add:function(v,w){if(w!==undefined){console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.");return this.addVectors(v,w)}this.x+=v.x;this.y+=v.y;this.z+=v.z;return this},addScalar:function(s){this.x+=s;this.y+=s;this.z+=s;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this},sub:function(v,w){if(w!==undefined){console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.");return this.subVectors(v,w)}this.x-=v.x;this.y-=v.y;this.z-=v.z;return this},subScalar:function(s){this.x-=s;this.y-=s;this.z-=s;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(v,w){if(w!==undefined){console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.");return this.multiplyVectors(v,w)}this.x*=v.x;this.y*=v.y;this.z*=v.z;return this},multiplyScalar:function(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var quaternion=new Quaternion;return function applyEuler(euler){if(!(euler&&euler.isEuler)){console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.")}return this.applyQuaternion(quaternion.setFromEuler(euler))}}(),applyAxisAngle:function(){var quaternion=new Quaternion;return function applyAxisAngle(axis,angle){return this.applyQuaternion(quaternion.setFromAxisAngle(axis,angle))}}(),applyMatrix3:function(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6]*z;this.y=e[1]*x+e[4]*y+e[7]*z;this.z=e[2]*x+e[5]*y+e[8]*z;return this},applyMatrix4:function(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;var w=1/(e[3]*x+e[7]*y+e[11]*z+e[15]);this.x=(e[0]*x+e[4]*y+e[8]*z+e[12])*w;this.y=(e[1]*x+e[5]*y+e[9]*z+e[13])*w;this.z=(e[2]*x+e[6]*y+e[10]*z+e[14])*w;return this},applyQuaternion:function(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;this.x=ix*qw+iw*-qx+iy*-qz-iz*-qy;this.y=iy*qw+iw*-qy+iz*-qx-ix*-qz;this.z=iz*qw+iw*-qz+ix*-qy-iy*-qx;return this},project:function(){var matrix=new Matrix4;return function project(camera){matrix.multiplyMatrices(camera.projectionMatrix,matrix.getInverse(camera.matrixWorld));return this.applyMatrix4(matrix)}}(),unproject:function(){var matrix=new Matrix4;return function unproject(camera){matrix.multiplyMatrices(camera.matrixWorld,matrix.getInverse(camera.projectionMatrix));return this.applyMatrix4(matrix)}}(),transformDirection:function(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z;this.y=e[1]*x+e[5]*y+e[9]*z;this.z=e[2]*x+e[6]*y+e[10]*z;return this.normalize()},divide:function(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this},divideScalar:function(scalar){return this.multiplyScalar(1/scalar)},min:function(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);return this},max:function(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);return this},clamp:function(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));return this},clampScalar:function(){var min=new Vector3;var max=new Vector3;return function clampScalar(minVal,maxVal){min.set(minVal,minVal,minVal);max.set(maxVal,maxVal,maxVal);return this.clamp(min,max)}}(),clampLength:function(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(v){return this.x*v.x+this.y*v.y+this.z*v.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(length){return this.normalize().multiplyScalar(length)},lerp:function(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;return this},lerpVectors:function(v1,v2,alpha){return this.subVectors(v2,v1).multiplyScalar(alpha).add(v1)},cross:function(v,w){if(w!==undefined){console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.");return this.crossVectors(v,w)}var x=this.x,y=this.y,z=this.z;this.x=y*v.z-z*v.y;this.y=z*v.x-x*v.z;this.z=x*v.y-y*v.x;return this},crossVectors:function(a,b){var ax=a.x,ay=a.y,az=a.z;var bx=b.x,by=b.y,bz=b.z;this.x=ay*bz-az*by;this.y=az*bx-ax*bz;this.z=ax*by-ay*bx;return this},projectOnVector:function(vector){var scalar=vector.dot(this)/vector.lengthSq();return this.copy(vector).multiplyScalar(scalar)},projectOnPlane:function(){var v1=new Vector3;return function projectOnPlane(planeNormal){v1.copy(this).projectOnVector(planeNormal);return this.sub(v1)}}(),reflect:function(){var v1=new Vector3;return function reflect(normal){return this.sub(v1.copy(normal).multiplyScalar(2*this.dot(normal)))}}(),angleTo:function(v){var theta=this.dot(v)/Math.sqrt(this.lengthSq()*v.lengthSq());return Math.acos(_Math.clamp(theta,-1,1))},distanceTo:function(v){return Math.sqrt(this.distanceToSquared(v))},distanceToSquared:function(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz},distanceToManhattan:function(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z)},setFromSpherical:function(s){var sinPhiRadius=Math.sin(s.phi)*s.radius;this.x=sinPhiRadius*Math.sin(s.theta);this.y=Math.cos(s.phi)*s.radius;this.z=sinPhiRadius*Math.cos(s.theta);return this},setFromCylindrical:function(c){this.x=c.radius*Math.sin(c.theta);this.y=c.y;this.z=c.radius*Math.cos(c.theta);return this},setFromMatrixPosition:function(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this},setFromMatrixScale:function(m){var sx=this.setFromMatrixColumn(m,0).length();var sy=this.setFromMatrixColumn(m,1).length();var sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this},setFromMatrixColumn:function(m,index){return this.fromArray(m.elements,index*4)},equals:function(v){return v.x===this.x&&v.y===this.y&&v.z===this.z},fromArray:function(array,offset){if(offset===undefined)offset=0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array},fromBufferAttribute:function(attribute,index,offset){if(offset!==undefined){console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().")}this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);return this}});function Matrix4(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];if(arguments.length>0){console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}}Object.assign(Matrix4.prototype,{isMatrix4:true,set:function(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){var te=this.elements;te[0]=n11;te[4]=n12;te[8]=n13;te[12]=n14;te[1]=n21;te[5]=n22;te[9]=n23;te[13]=n24;te[2]=n31;te[6]=n32;te[10]=n33;te[14]=n34;te[3]=n41;te[7]=n42;te[11]=n43;te[15]=n44;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new Matrix4).fromArray(this.elements)},copy:function(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];te[9]=me[9];te[10]=me[10];te[11]=me[11];te[12]=me[12];te[13]=me[13];te[14]=me[14];te[15]=me[15];return this},copyPosition:function(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this},extractBasis:function(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2)
return this},makeBasis
function(xAxis,yAxis,zAxis){this.set(xAxis.x,yAxis.x,zAxis.x,0,xAxis.y,yAxis.y,zAxis.y,0,xAxis.z,yAxis.z,zAxis.z,0,0,0,0,1);return this},extractRotation:function(){var v1=new Vector3;return function extractRotation(m){var te=this.elements;var me=m.elements;var scaleX=1/v1.setFromMatrixColumn(m,0).length();var scaleY=1/v1.setFromMatrixColumn(m,1).length();var scaleZ=1/v1.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;return this}}(),makeRotationFromEuler:function(euler){if(!(euler&&euler.isEuler)){console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.")}var te=this.elements;var x=euler.x,y=euler.y,z=euler.z;var a=Math.cos(x),b=Math.sin(x);var c=Math.cos(y),d=Math.sin(y);var e=Math.cos(z),f=Math.sin(z);if(euler.order==="XYZ"){var ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=-c*f;te[8]=d;te[1]=af+be*d;te[5]=ae-bf*d;te[9]=-b*c;te[2]=bf-ae*d;te[6]=be+af*d;te[10]=a*c}else if(euler.order==="YXZ"){var ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce+df*b;te[4]=de*b-cf;te[8]=a*d;te[1]=a*f;te[5]=a*e;te[9]=-b;te[2]=cf*b-de;te[6]=df+ce*b;te[10]=a*c}else if(euler.order==="ZXY"){var ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce-df*b;te[4]=-a*f;te[8]=de+cf*b;te[1]=cf+de*b;te[5]=a*e;te[9]=df-ce*b;te[2]=-a*d;te[6]=b;te[10]=a*c}else if(euler.order==="ZYX"){var ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=be*d-af;te[8]=ae*d+bf;te[1]=c*f;te[5]=bf*d+ae;te[9]=af*d-be;te[2]=-d;te[6]=b*c;te[10]=a*c}else if(euler.order==="YZX"){var ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=bd-ac*f;te[8]=bc*f+ad;te[1]=f;te[5]=a*e;te[9]=-b*e;te[2]=-d*e;te[6]=ad*f+bc;te[10]=ac-bd*f}else if(euler.order==="XZY"){var ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=-f;te[8]=d*e;te[1]=ac*f+bd;te[5]=a*e;te[9]=ad*f-bc;te[2]=bc*f-ad;te[6]=b*e;te[10]=bd*f+ac}te[3]=0;te[7]=0;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this},makeRotationFromQuaternion:function(q){var te=this.elements;var x=q._x,y=q._y,z=q._z,w=q._w;var x2=x+x,y2=y+y,z2=z+z;var xx=x*x2,xy=x*y2,xz=x*z2;var yy=y*y2,yz=y*z2,zz=z*z2;var wx=w*x2,wy=w*y2,wz=w*z2;te[0]=1-(yy+zz);te[4]=xy-wz;te[8]=xz+wy;te[1]=xy+wz;te[5]=1-(xx+zz);te[9]=yz-wx;te[2]=xz-wy;te[6]=yz+wx;te[10]=1-(xx+yy);te[3]=0;te[7]=0;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this},lookAt:function(){var x=new Vector3;var y=new Vector3;var z=new Vector3;return function lookAt(eye,target,up){var te=this.elements;z.subVectors(eye,target);if(z.lengthSq()===0){z.z=1}z.normalize();x.crossVectors(up,z);if(x.lengthSq()===0){if(Math.abs(up.z)===1){z.x+=1e-4}else{z.z+=1e-4}z.normalize();x.crossVectors(up,z)}x.normalize();y.crossVectors(z,x);te[0]=x.x;te[4]=y.x;te[8]=z.x;te[1]=x.y;te[5]=y.y;te[9]=z.y;te[2]=x.z;te[6]=y.z;te[10]=z.z;return this}}(),multiply:function(m,n){if(n!==undefined){console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.");return this.multiplyMatrices(m,n)}return this.multiplyMatrices(this,m)},premultiply:function(m){return this.multiplyMatrices(m,this)},multiplyMatrices:function(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];var a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];var a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];var a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];var b11=be[0],b12=be[4],b13=be[8],b14=be[12];var b21=be[1],b22=be[5],b23=be[9],b24=be[13];var b31=be[2],b32=be[6],b33=be[10],b34=be[14];var b41=be[3],b42=be[7],b43=be[11],b44=be[15];te[0]=a11*b11+a12*b21+a13*b31+a14*b41;te[4]=a11*b12+a12*b22+a13*b32+a14*b42;te[8]=a11*b13+a12*b23+a13*b33+a14*b43;te[12]=a11*b14+a12*b24+a13*b34+a14*b44;te[1]=a21*b11+a22*b21+a23*b31+a24*b41;te[5]=a21*b12+a22*b22+a23*b32+a24*b42;te[9]=a21*b13+a22*b23+a23*b33+a24*b43;te[13]=a21*b14+a22*b24+a23*b34+a24*b44;te[2]=a31*b11+a32*b21+a33*b31+a34*b41;te[6]=a31*b12+a32*b22+a33*b32+a34*b42;te[10]=a31*b13+a32*b23+a33*b33+a34*b43;te[14]=a31*b14+a32*b24+a33*b34+a34*b44;te[3]=a41*b11+a42*b21+a43*b31+a44*b41;te[7]=a41*b12+a42*b22+a43*b32+a44*b42;te[11]=a41*b13+a42*b23+a43*b33+a44*b43;te[15]=a41*b14+a42*b24+a43*b34+a44*b44;return this},multiplyScalar:function(s){var te=this.elements;te[0]*=s;te[4]*=s;te[8]*=s;te[12]*=s;te[1]*=s;te[5]*=s;te[9]*=s;te[13]*=s;te[2]*=s;te[6]*=s;te[10]*=s;te[14]*=s;te[3]*=s;te[7]*=s;te[11]*=s;te[15]*=s;return this},applyToBufferAttribute:function(){var v1=new Vector3;return function applyToBufferAttribute(attribute){for(var i=0,l=attribute.count;i<l;i++){v1.x=attribute.getX(i);v1.y=attribute.getY(i);v1.z=attribute.getZ(i);v1.applyMatrix4(this);attribute.setXYZ(i,v1.x,v1.y,v1.z)}return attribute}}(),determinant:function(){var te=this.elements;var n11=te[0],n12=te[4],n13=te[8],n14=te[12];var n21=te[1],n22=te[5],n23=te[9],n24=te[13];var n31=te[2],n32=te[6],n33=te[10],n34=te[14];var n41=te[3],n42=te[7],n43=te[11],n44=te[15];return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34)+n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31)+n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31)+n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31)},transpose:function(){var te=this.elements;var tmp;tmp=te[1];te[1]=te[4];te[4]=tmp;tmp=te[2];te[2]=te[8];te[8]=tmp;tmp=te[6];te[6]=te[9];te[9]=tmp;tmp=te[3];te[3]=te[12];te[12]=tmp;tmp=te[7];te[7]=te[13];te[13]=tmp;tmp=te[11];te[11]=te[14];te[14]=tmp;return this},setPosition:function(v){var te=this.elements;te[12]=v.x;te[13]=v.y;te[14]=v.z;return this},getInverse:function(m,throwOnDegenerate){var te=this.elements,me=m.elements,n11=me[0],n21=me[1],n31=me[2],n41=me[3],n12=me[4],n22=me[5],n32=me[6],n42=me[7],n13=me[8],n23=me[9],n33=me[10],n43=me[11],n14=me[12],n24=me[13],n34=me[14],n44=me[15],t11=n23*n34*n42-n24*n33*n42+n24*n32*n43-n22*n34*n43-n23*n32*n44+n22*n33*n44,t12=n14*n33*n42-n13*n34*n42-n14*n32*n43+n12*n34*n43+n13*n32*n44-n12*n33*n44,t13=n13*n24*n42-n14*n23*n42+n14*n22*n43-n12*n24*n43-n13*n22*n44+n12*n23*n44,t14=n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34;var det=n11*t11+n21*t12+n31*t13+n41*t14;if(det===0){var msg="THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";if(throwOnDegenerate===true){throw new Error(msg)}else{console.warn(msg)}return this.identity()}var detInv=1/det;te[0]=t11*detInv;te[1]=(n24*n33*n41-n23*n34*n41-n24*n31*n43+n21*n34*n43+n23*n31*n44-n21*n33*n44)*detInv;te[2]=(n22*n34*n41-n24*n32*n41+n24*n31*n42-n21*n34*n42-n22*n31*n44+n21*n32*n44)*detInv;te[3]=(n23*n32*n41-n22*n33*n41-n23*n31*n42+n21*n33*n42+n22*n31*n43-n21*n32*n43)*detInv;te[4]=t12*detInv;te[5]=(n13*n34*n41-n14*n33*n41+n14*n31*n43-n11*n34*n43-n13*n31*n44+n11*n33*n44)*detInv;te[6]=(n14*n32*n41-n12*n34*n41-n14*n31*n42+n11*n34*n42+n12*n31*n44-n11*n32*n44)*detInv;te[7]=(n12*n33*n41-n13*n32*n41+n13*n31*n42-n11*n33*n42-n12*n31*n43+n11*n32*n43)*detInv;te[8]=t13*detInv;te[9]=(n14*n23*n41-n13*n24*n41-n14*n21*n43+n11*n24*n43+n13*n21*n44-n11*n23*n44)*detInv;te[10]=(n12*n24*n41-n14*n22*n41+n14*n21*n42-n11*n24*n42-n12*n21*n44+n11*n22*n44)*detInv;te[11]=(n13*n22*n41-n12*n23*n41-n13*n21*n42+n11*n23*n42+n12*n21*n43-n11*n22*n43)*detInv;te[12]=t14*detInv;te[13]=(n13*n24*n31-n14*n23*n31+n14*n21*n33-n11*n24*n33-n13*n21*n34+n11*n23*n34)*detInv;te[14]=(n14*n22*n31-n12*n24*n31-n14*n21*n32+n11*n24*n32+n12*n21*n34-n11*n22*n34)*detInv;te[15]=(n12*n23*n31-n13*n22*n31+n13*n21*n32-n11*n23*n32-n12*n21*n33+n11*n22*n33)*detInv;return this},scale:function(v){var te=this.elements;var x=v.x,y=v.y,z=v.z;te[0]*=x;te[4]*=y;te[8]*=z;te[1]*=x;te[5]*=y;te[9]*=z;te[2]*=x;te[6]*=y;te[10]*=z;te[3]*=x;te[7]*=y;te[11]*=z;return this},getMaxScaleOnAxis:function(){var te=this.elements;var scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];var scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];var scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq))},makeTranslation:function(x,y,z){this.set(1,0,0,x,0,1,0,y,0,0,1,z,0,0,0,1);return this},makeRotationX:function(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);return this},makeRotationY:function(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);return this},makeRotationZ:function(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(axis,angle){var c=Math.cos(angle);var s=Math.sin(angle);var t=1-c;var x=axis.x,y=axis.y,z=axis.z;var tx=t*x,ty=t*y;this.set(tx*x+c,tx*y-s*z,tx*z+s*y,0,tx*y+s*z,ty*y+c,ty*z-s*x,0,tx*z-s*y,ty*z+s*x,t*z*z+c,0,0,0,0,1);return this},makeScale:function(x,y,z){this.set(x,0,0,0,0,y,0,0,0,0,z,0,0,0,0,1);return this},makeShear:function(x,y,z){this.set(1,y,z,0,x,1,z,0,x,y,1,0,0,0,0,1);return this},compose:function(position,quaternion,scale){this.makeRotationFromQuaternion(quaternion);this.scale(scale);this.setPosition(position);return this},decompose:function(){var vector=new Vector3;var matrix=new Matrix4;return function decompose(position,quaternion,scale){var te=this.elements;var sx=vector.set(te[0],te[1],te[2]).length();var sy=vector.set(te[4],te[5],te[6]).length();var sz=vector.set(te[8],te[9],te[10]).length();var det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];matrix.copy(this);var invSX=1/sx;var invSY=1/sy;var invSZ=1/sz;matrix.elements[0]*=invSX;matrix.elements[1]*=invSX;matrix.elements[2]*=invSX;matrix.elements[4]*=invSY;matrix.elements[5]*=invSY;matrix.elements[6]*=invSY;matrix.elements[8]*=invSZ;matrix.elements[9]*=invSZ;matrix.elements[10]*=invSZ;quaternion.setFromRotationMatrix(matrix);scale.x=sx;scale.y=sy;scale.z=sz;return this}}(),makePerspective:function(left,right,top,bottom,near,far){if(far===undefined){console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.")}var te=this.elements;var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var d=-2*far*near/(far-near);te[0]=x;te[4]=0;te[8]=a;te[12]=0;te[1]=0;te[5]=y;te[9]=b;te[13]=0;te[2]=0;te[6]=0;te[10]=c;te[14]=d;te[3]=0;te[7]=0;te[11]=-1;te[15]=0;return this},makeOrthographic:function(left,right,top,bottom,near,far){var te=this.elements;var w=1/(right-left);var h=1/(top-bottom);var p=1/(far-near);var x=(right+left)*w;var y=(top+bottom)*h;var z=(far+near)*p;te[0]=2*w;te[4]=0;te[8]=0;te[12]=-x;te[1]=0;te[5]=2*h;te[9]=0;te[13]=-y;te[2]=0;te[6]=0;te[10]=-2*p;te[14]=-z;te[3]=0;te[7]=0;te[11]=0;te[15]=1;return this},equals:function(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<16;i++){if(te[i]!==me[i])return false}return true},fromArray:function(array,offset){if(offset===undefined)offset=0;for(var i=0;i<16;i++){this.elements[i]=array[i+offset]}return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];array[offset+9]=te[9];array[offset+10]=te[10];array[offset+11]=te[11];array[offset+12]=te[12];array[offset+13]=te[13];array[offset+14]=te[14];array[offset+15]=te[15];return array}});function DataTexture(data,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={data:data,width:width,height:height};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.generateMipmaps=false;this.flipY=false;this.unpackAlignment=1}DataTexture.prototype=Object.create(Texture.prototype);DataTexture.prototype.constructor=DataTexture;DataTexture.prototype.isDataTexture=true;function CubeTexture(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==undefined?images:[];mapping=mapping!==undefined?mapping:CubeReflectionMapping;Texture.call(this,images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.flipY=false}CubeTexture.prototype=Object.create(Texture.prototype);CubeTexture.prototype.constructor=CubeTexture;CubeTexture.prototype.isCubeTexture=true;Object.defineProperty(CubeTexture.prototype,"images",{get:function(){return this.image},set:function(value){this.image=value}});var emptyTexture=new Texture;var emptyCubeTexture=new CubeTexture;function UniformContainer(){this.seq=[];this.map={}}var arrayCacheF32=[];var arrayCacheI32=[];var mat4array=new Float32Array(16);var mat3array=new Float32Array(9);function flatten(array,nBlocks,blockSize){var firstElem=array[0];if(firstElem<=0||firstElem>0)return array;var n=nBlocks*blockSize,r=arrayCacheF32[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32[n]=r}if(nBlocks!==0){firstElem.toArray(r,0);for(var i=1,offset=0;i!==nBlocks;++i){offset+=blockSize;array[i].toArray(r,offset)}}return r}function allocTexUnits(renderer,n){var r=arrayCacheI32[n];if(r===undefined){r=new Int32Array(n);arrayCacheI32[n]=r}for(var i=0;i!==n;++i)r[i]=renderer.allocTextureUnit();return r}function setValue1f(gl,v){gl.uniform1f(this.addr,v)}function setValue1i(gl,v){gl.uniform1i(this.addr,v)}function setValue2fv(gl,v){if(v.x===undefined)gl.uniform2fv(this.addr,v);else gl.uniform2f(this.addr,v.x,v.y)}function setValue3fv(gl,v){if(v.x!==undefined)gl.uniform3f(this.addr,v.x,v.y,v.z);else if(v.r!==undefined)gl.uniform3f(this.addr,v.r,v.g,v.b);else gl.uniform3fv(this.addr,v)}function setValue4fv(gl,v){if(v.x===undefined)gl.uniform4fv(this.addr,v);else gl.uniform4f(this.addr,v.x,v.y,v.z,v.w)}function setValue2fm(gl,v){gl.uniformMatrix2fv(this.addr,false,v.elements||v)}function setValue3fm(gl,v){if(v.elements===undefined){gl.uniformMatrix3fv(this.addr,false,v)}else{mat3array.set(v.elements);gl.uniformMatrix3fv(this.addr,false,mat3array)}}function setValue4fm(gl,v){if(v.elements===undefined){gl.uniformMatrix4fv(this.addr,false,v)}else{mat4array.set(v.elements);gl.uniformMatrix4fv(this.addr,false,mat4array)}}function setValueT1(gl,v,renderer){var unit=renderer.allocTextureUnit();gl.uniform1i(this.addr,unit);renderer.setTexture2D(v||emptyTexture,unit)}function setValueT6(gl,v,renderer){var unit=renderer.allocTextureUnit();gl.uniform1i(this.addr,unit);renderer.setTextureCube(v||emptyCubeTexture,unit)}function setValue2iv(gl,v){gl.uniform2iv(this.addr,v)}function setValue3iv(gl,v){gl.uniform3iv(this.addr,v)}function setValue4iv(gl,v){gl.uniform4iv(this.addr,v)}function getSingularSetter(type){switch(type){case 5126:return setValue1f;case 35664:return setValue2fv;case 35665:return setValue3fv;case 35666:return setValue4fv;case 35674:return setValue2fm;case 35675:return setValue3fm;case 35676:return setValue4fm;case 35678:case 36198:return setValueT1;case 35680:return setValueT6;case 5124:case 35670:return setValue1i;case 35667:case 35671:return setValue2iv;case 35668:case 35672:return setValue3iv;case 35669:case 35673:return setValue4iv}}function setValue1fv(gl,v){gl.uniform1fv(this.addr,v)}function setValue1iv(gl,v){gl.uniform1iv(this.addr,v)}function setValueV2a(gl,v){gl.uniform2fv(this.addr,flatten(v,this.size,2))}function setValueV3a(gl,v){gl.uniform3fv(this.addr,flatten(v,this.size,3))}function setValueV4a(gl,v){gl.uniform4fv(this.addr,flatten(v,this.size,4))}function setValueM2a(gl,v){gl.uniformMatrix2fv(this.addr,false,flatten(v,this.size,4))}function setValueM3a(gl,v){gl.uniformMatrix3fv(this.addr,false,flatten(v,this.size,9))}function setValueM4a(gl,v){gl.uniformMatrix4fv(this.addr,false,flatten(v,this.size,16))}function setValueT1a(gl,v,renderer){var n=v.length,units=allocTexUnits(renderer,n);gl.uniform1iv(this.addr,units);for(var i=0;i!==n;++i){renderer.setTexture2D(v[i]||emptyTexture,units[i])}}function setValueT6a(gl,v,renderer){var n=v.length,units=allocTexUnits(renderer,n);gl.uniform1iv(this.addr,units);for(var i=0;i!==n;++i){renderer.setTextureCube(v[i]||emptyCubeTexture,units[i])}}function getPureArraySetter(type){switch(type){case 5126:return setValue1fv;case 35664:return setValueV2a;case 35665:return setValueV3a;case 35666:return setValueV4a;case 35674:return setValueM2a;case 35675:return setValueM3a;case 35676:return setValueM4a;case 35678:return setValueT1a;case 35680:return setValueT6a;case 5124:case 35670:return setValue1iv;case 35667:case 35671:return setValue2iv;case 35668:case 35672:return setValue3iv;case 35669:case 35673:return setValue4iv}}function SingleUniform(id,activeInfo,addr){this.id=id;this.addr=addr;this.setValue=getSingularSetter(activeInfo.type)}function PureArrayUniform(id,activeInfo,addr){this.id=id;this.addr=addr;this.size=activeInfo.size;this.setValue=getPureArraySetter(activeInfo.type)}function StructuredUniform(id){this.id=id;UniformContainer.call(this)}StructuredUniform.prototype.setValue=function(gl,value){var seq=this.seq;for(var i=0,n=seq.length;i!==n;++i){var u=seq[i];u.setValue(gl,value[u.id])}};var RePathPart=/([\w\d_]+)(\])?(\[|\.)?/g;function addUniform(container,uniformObject){container.seq.push(uniformObject);container.map[uniformObject.id]=uniformObject}function parseUniform(activeInfo,addr,container){var path=activeInfo.name,pathLength=path.length;RePathPart.lastIndex=0;for(;;){var match=RePathPart.exec(path),matchEnd=RePathPart.lastIndex,id=match[1],idIsIndex=match[2]==="]",subscript=match[3];if(idIsIndex)id=id|0;if(subscript===undefined||subscript==="["&&matchEnd+2===pathLength){addUniform(container,subscript===undefined?new SingleUniform(id,activeInfo,addr):new PureArrayUniform(id,activeInfo,addr));break}else{var map=container.map,next=map[id];if(next===undefined){next=new StructuredUniform(id);addUniform(container,next)}container=next}}}function WebGLUniforms(gl,program,renderer){UniformContainer.call(this);this.renderer=renderer;var n=gl.getProgramParameter(program,gl.ACTIVE_UNIFORMS);for(var i=0;i<n;++i){var info=gl.getActiveUniform(program,i),path=info.name,addr=gl.getUniformLocation(program,path);parseUniform(info,addr,this)}}WebGLUniforms.prototype.setValue=function(gl,name,value){var u=this.map[name];if(u!==undefined)u.setValue(gl,value,this.renderer)};WebGLUniforms.prototype.setOptional=function(gl,object,name){var v=object[name];if(v!==undefined)this.setValue(gl,name,v)};WebGLUniforms.upload=function(gl,seq,values,renderer){for(var i=0,n=seq.length;i!==n;++i){var u=seq[i],v=values[u.id];if(v.needsUpdate!==false){u.setValue(gl,v.value,renderer)}}};WebGLUniforms.seqWithValue=function(seq,values){var r=[];for(var i=0,n=seq.length;i!==n;++i){var u=seq[i];if(u.id in values)r.push(u)}return r};var ColorKeywords={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(r,g,b){if(g===undefined&&b===undefined){return this.set(r)}return this.setRGB(r,g,b)}Object.assign(Color.prototype,{isColor:true,r:1,g:1,b:1,set:function(value){if(value&&value.isColor){this.copy(value)}else if(typeof value==="number"){this.setHex(value)}else if(typeof value==="string"){this.setStyle(value)}return this},setScalar:function(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this},setHex:function(hex){hex=Math.floor(hex);this.r=(hex>>16&255)/255;this.g=(hex>>8&255)/255;this.b=(hex&255)/255;return this},setRGB:function(r,g,b){this.r=r;this.g=g;this.b=b;return this},setHSL:function(){function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*6*(2/3-t);return p}return function setHSL(h,s,l){h=_Math.euclideanModulo(h,1);s=_Math.clamp(s,0,1);l=_Math.clamp(l,0,1);if(s===0){this.r=this.g=this.b=l}else{var p=l<=.5?l*(1+s):l+s-l*s;var q=2*l-p;this.r=hue2rgb(q,p,h+1/3);this.g=hue2rgb(q,p,h);this.b=hue2rgb(q,p,h-1/3)}return this}}(),setStyle:function(style){function handleAlpha(string){if(string===undefined)return;if(parseFloat(string)<1){console.warn("THREE.Color: Alpha component of "+style+" will be ignored.")}}var m;if(m=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)){var color;var name=m[1];var components=m[2];switch(name){case"rgb":case"rgba":if(color=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){this.r=Math.min(255,parseInt(color[1],10))/255;this.g=Math.min(255,parseInt(color[2],10))/255;this.b=Math.min(255,parseInt(color[3],10))/255;handleAlpha(color[5]);return this}if(color=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){this.r=Math.min(100,parseInt(color[1],10))/100;this.g=Math.min(100,parseInt(color[2],10))/100;this.b=Math.min(100,parseInt(color[3],10))/100;handleAlpha(color[5]);return this}break;case"hsl":case"hsla":if(color=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)){var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var l=parseInt(color[3],10)/100;handleAlpha(color[5]);return this.setHSL(h,s,l)}break}}else if(m=/^\#([A-Fa-f0-9]+)$/.exec(style)){var hex=m[1];var size=hex.length;if(size===3){this.r=parseInt(hex.charAt(0)+hex.charAt(0),16)/255;this.g=parseInt(hex.charAt(1)+hex.charAt(1),16)/255;this.b=parseInt(hex.charAt(2)+hex.charAt(2),16)/255;return this}else if(size===6){this.r=parseInt(hex.charAt(0)+hex.charAt(1),16)/255;this.g=parseInt(hex.charAt(2)+hex.charAt(3),16)/255;this.b=parseInt(hex.charAt(4)+hex.charAt(5),16)/255;return this}}if(style&&style.length>0){var hex=ColorKeywords[style];if(hex!==undefined){this.setHex(hex)}else{console.warn("THREE.Color: Unknown color "+style)}}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(color){this.r=color.r;this.g=color.g;this.b=color.b;return this},copyGammaToLinear:function(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2;this.r=Math.pow(color.r,gammaFactor);this.g=Math.pow(color.g,gammaFactor);this.b=Math.pow(color.b,gammaFactor);return this},copyLinearToGamma:function(color,gammaFactor){if(gammaFactor===undefined)gammaFactor=2;var safeInverse=gammaFactor>0?1/gammaFactor:1;this.r=Math.pow(color.r,safeInverse);this.g=Math.pow(color.g,safeInverse);this.b=Math.pow(color.b,safeInverse);return this},convertGammaToLinear:function(){var r=this.r,g=this.g,b=this.b;this.r=r*r;this.g=g*g;this.b=b*b;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return this.r*255<<16^this.g*255<<8^this.b*255<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(optionalTarget){var hsl=optionalTarget||{h:0,s:0,l:0};var r=this.r,g=this.g,b=this.b;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var hue,saturation;var lightness=(min+max)/2;if(min===max){hue=0;saturation=0}else{var delta=max-min;saturation=lightness<=.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g<b?6:0);break;case g:hue=(b-r)/delta+2;break;case b:hue=(r-g)/delta+4;break}hue/=6}hsl.h=hue;hsl.s=saturation;hsl.l=lightness;return hsl},getStyle:function(){return"rgb("+(this.r*255|0)+","+(this.g*255|0)+","+(this.b*255|0)+")"},offsetHSL:function(h,s,l){var hsl=this.getHSL();hsl.h+=h;hsl.s+=s;hsl.l+=l;this.setHSL(hsl.h,hsl.s,hsl.l);return this},add:function(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;return this},addColors:function(color1,color2){this.r=color1.r+color2.r;this.g=color1.g+color2.g;this.b=color1.b+color2.b;return this},addScalar:function(s){this.r+=s;this.g+=s;this.b+=s;return this},sub:function(color){this.r=Math.max(0,this.r-color.r);this.g=Math.max(0,this.g-color.g);this.b=Math.max(0,this.b-color.b);return this},multiply:function(color){this.r*=color.r;this.g*=color.g;this.b*=color.b;return this},multiplyScalar:function(s){this.r*=s;this.g*=s;this.b*=s;return this},lerp:function(color,alpha){this.r+=(color.r-this.r)*alpha;this.g+=(color.g-this.g)*alpha;this.b+=(color.b-this.b)*alpha;return this},equals:function(c){return c.r===this.r&&c.g===this.g&&c.b===this.b},fromArray:function(array,offset){if(offset===undefined)offset=0;this.r=array[offset];this.g=array[offset+1];this.b=array[offset+2];return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this.r;array[offset+1]=this.g;array[offset+2]=this.b;return array},toJSON:function(){return this.getHex()}});var UniformsLib={common:{diffuse:{value:new Color(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new Vector4(0,0,1,1)},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new Vector2(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Color(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new Color(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new Vector4(0,0,1,1)}}};var UniformsUtils={merge:function(uniforms){var merged={};for(var u=0;u<uniforms.length;u++){var tmp=this.clone(uniforms[u]);for(var p in tmp){merged[p]=tmp[p]}}return merged},clone:function(uniforms_src){var uniforms_dst={};for(var u in uniforms_src){uniforms_dst[u]={};for(var p in uniforms_src[u]){var parameter_src=uniforms_src[u][p];if(parameter_src&&(parameter_src.isColor||parameter_src.isMatrix3||parameter_src.isMatrix4||parameter_src.isVector2||parameter_src.isVector3||parameter_src.isVector4||parameter_src.isTexture)){uniforms_dst[u][p]=parameter_src.clone()}else if(Array.isArray(parameter_src)){uniforms_dst[u][p]=parameter_src.slice()}else{uniforms_dst[u][p]=parameter_src}}}return uniforms_dst}};var alphamap_fragment="#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";var alphamap_pars_fragment="#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";var alphatest_fragment="#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";var aomap_fragment="#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";var aomap_pars_fragment="#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";var begin_vertex="\nvec3 transformed = vec3( position );\n";var beginnormal_vertex="\nvec3 objectNormal = vec3( normal );\n"
var bsdfs="float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v 
0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";var bumpmap_pars_fragment="#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";var clipping_planes_fragment="#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";var clipping_planes_pars_fragment="#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";var clipping_planes_pars_vertex="#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";var clipping_planes_vertex="#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";var color_fragment="#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";var color_pars_fragment="#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";var color_pars_vertex="#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";var color_vertex="#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";var common="#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";var cube_uv_reflection_fragment="#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";var defaultnormal_vertex="vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";var displacementmap_pars_vertex="#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";var displacementmap_vertex="#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";var emissivemap_fragment="#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";var emissivemap_pars_fragment="#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";var encodings_fragment=" gl_FragColor = linearToOutputTexel( gl_FragColor );\n";var encodings_pars_fragment="\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";var envmap_fragment="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";var envmap_pars_fragment="#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";var envmap_pars_vertex="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";var envmap_vertex="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";var fog_vertex="\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";var fog_pars_vertex="#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";var fog_fragment="#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";var fog_pars_fragment="#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n";var gradientmap_pars_fragment="#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";var lightmap_fragment="#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";var lightmap_pars_fragment="#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";var lights_lambert_vertex="vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n"
var lights_pars="uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";var lights_phong_fragment="BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";var lights_phong_pars_fragment="varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";var lights_physical_fragment="PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";var lights_physical_pars_fragment="struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";var lights_template="\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) 
1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";var logdepthbuf_fragment="#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";var logdepthbuf_pars_fragment="#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";var logdepthbuf_pars_vertex="#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";var logdepthbuf_vertex="#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";var map_fragment="#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";var map_pars_fragment="#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";var map_particle_fragment="#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";var map_particle_pars_fragment="#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";var metalnessmap_fragment="float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";var metalnessmap_pars_fragment="#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";var morphnormal_vertex="#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";var morphtarget_pars_vertex="#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";var morphtarget_vertex="#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";var normal_fragment="#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";var normalmap_pars_fragment="#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";var packing="vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";var premultiplied_alpha_fragment="#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";var project_vertex="vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";var dithering_fragment="#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";var dithering_pars_fragment="#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n";var roughnessmap_fragment="float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";var roughnessmap_pars_fragment="#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";var shadowmap_pars_fragment="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";var shadowmap_pars_vertex="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"
var shadowmap_vertex="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";var shadowmask_pars_fragment="float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) 
1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";var skinbase_vertex="#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";var skinning_pars_vertex="#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";var skinning_vertex="#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";var skinnormal_vertex="#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";var specularmap_fragment="float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";var specularmap_pars_fragment="#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";var tonemapping_fragment="#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";var tonemapping_pars_fragment="#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";var uv_pars_fragment="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";var uv_pars_vertex="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";var uv_vertex="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";var uv2_pars_fragment="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";var uv2_pars_vertex="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";var uv2_vertex="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";var worldpos_vertex="#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";var cube_frag="uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";var cube_vert="varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";var depth_frag="#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";var depth_vert="#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";var distanceRGBA_frag="#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n";var distanceRGBA_vert="#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n";var equirect_frag="uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";var equirect_vert="varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";var linedashed_frag="uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";var linedashed_vert="uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n";var meshbasic_frag="uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";var meshbasic_vert="#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n";var meshlambert_frag="uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";var meshlambert_vert="#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";var meshphong_frag="#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";var meshphong_vert="#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";var meshphysical_frag="#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";var meshphysical_vert="#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";var normal_frag="#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";var normal_vert="#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";var points_frag="uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";var points_vert="uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";var shadow_frag="uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n}\n";var shadow_vert="#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";var ShaderChunk={alphamap_fragment:alphamap_fragment,alphamap_pars_fragment:alphamap_pars_fragment,alphatest_fragment:alphatest_fragment,aomap_fragment:aomap_fragment,aomap_pars_fragment:aomap_pars_fragment,begin_vertex:begin_vertex,beginnormal_vertex:beginnormal_vertex,bsdfs:bsdfs,bumpmap_pars_fragment:bumpmap_pars_fragment,clipping_planes_fragment:clipping_planes_fragment,clipping_planes_pars_fragment:clipping_planes_pars_fragment,clipping_planes_pars_vertex:clipping_planes_pars_vertex,clipping_planes_vertex:clipping_planes_vertex,color_fragment:color_fragment,color_pars_fragment:color_pars_fragment,color_pars_vertex:color_pars_vertex,color_vertex:color_vertex,common:common,cube_uv_reflection_fragment:cube_uv_reflection_fragment,defaultnormal_vertex:defaultnormal_vertex,displacementmap_pars_vertex:displacementmap_pars_vertex,displacementmap_vertex:displacementmap_vertex,emissivemap_fragment:emissivemap_fragment,emissivemap_pars_fragment:emissivemap_pars_fragment,encodings_fragment:encodings_fragment,encodings_pars_fragment:encodings_pars_fragment,envmap_fragment:envmap_fragment,envmap_pars_fragment:envmap_pars_fragment,envmap_pars_vertex:envmap_pars_vertex,envmap_vertex:envmap_vertex,fog_vertex:fog_vertex,fog_pars_vertex:fog_pars_vertex,fog_fragment:fog_fragment,fog_pars_fragment:fog_pars_fragment,gradientmap_pars_fragment:gradientmap_pars_fragment,lightmap_fragment:lightmap_fragment,lightmap_pars_fragment:lightmap_pars_fragment,lights_lambert_vertex:lights_lambert_vertex,lights_pars:lights_pars,lights_phong_fragment:lights_phong_fragment,lights_phong_pars_fragment:lights_phong_pars_fragment,lights_physical_fragment:lights_physical_fragment,lights_physical_pars_fragment:lights_physical_pars_fragment,lights_template:lights_template,logdepthbuf_fragment:logdepthbuf_fragment,logdepthbuf_pars_fragment:logdepthbuf_pars_fragment,logdepthbuf_pars_vertex:logdepthbuf_pars_vertex,logdepthbuf_vertex:logdepthbuf_vertex,map_fragment:map_fragment,map_pars_fragment:map_pars_fragment,map_particle_fragment:map_particle_fragment,map_particle_pars_fragment:map_particle_pars_fragment,metalnessmap_fragment:metalnessmap_fragment,metalnessmap_pars_fragment:metalnessmap_pars_fragment,morphnormal_vertex:morphnormal_vertex,morphtarget_pars_vertex:morphtarget_pars_vertex,morphtarget_vertex:morphtarget_vertex,normal_fragment:normal_fragment,normalmap_pars_fragment:normalmap_pars_fragment,packing:packing,premultiplied_alpha_fragment:premultiplied_alpha_fragment,project_vertex:project_vertex,dithering_fragment:dithering_fragment,dithering_pars_fragment:dithering_pars_fragment,roughnessmap_fragment:roughnessmap_fragment,roughnessmap_pars_fragment:roughnessmap_pars_fragment,shadowmap_pars_fragment:shadowmap_pars_fragment,shadowmap_pars_vertex:shadowmap_pars_vertex,shadowmap_vertex:shadowmap_vertex,shadowmask_pars_fragment:shadowmask_pars_fragment,skinbase_vertex:skinbase_vertex,skinning_pars_vertex:skinning_pars_vertex,skinning_vertex:skinning_vertex,skinnormal_vertex:skinnormal_vertex,specularmap_fragment:specularmap_fragment,specularmap_pars_fragment:specularmap_pars_fragment,tonemapping_fragment:tonemapping_fragment,tonemapping_pars_fragment:tonemapping_pars_fragment,uv_pars_fragment:uv_pars_fragment,uv_pars_vertex:uv_pars_vertex,uv_vertex:uv_vertex,uv2_pars_fragment:uv2_pars_fragment,uv2_pars_vertex:uv2_pars_vertex,uv2_vertex:uv2_vertex,worldpos_vertex:worldpos_vertex,cube_frag:cube_frag,cube_vert:cube_vert,depth_frag:depth_frag,depth_vert:depth_vert,distanceRGBA_frag:distanceRGBA_frag,distanceRGBA_vert:distanceRGBA_vert,equirect_frag:equirect_frag,equirect_vert:equirect_vert,linedashed_frag:linedashed_frag,linedashed_vert:linedashed_vert,meshbasic_frag:meshbasic_frag,meshbasic_vert:meshbasic_vert,meshlambert_frag:meshlambert_frag,meshlambert_vert:meshlambert_vert,meshphong_frag:meshphong_frag,meshphong_vert:meshphong_vert,meshphysical_frag:meshphysical_frag,meshphysical_vert:meshphysical_vert,normal_frag:normal_frag,normal_vert:normal_vert,points_frag:points_frag,points_vert:points_vert,shadow_frag:shadow_frag,shadow_vert:shadow_vert};var ShaderLib={basic:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.fog]),vertexShader:ShaderChunk.meshbasic_vert,

fragmentShader:ShaderChunk.meshbasic_frag},lambert:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0)}}]),vertexShader:ShaderChunk.meshlambert_vert,fragmentShader:ShaderChunk.meshlambert_frag},phong:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.gradientmap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0)},specular:{value:new Color(1118481)},shininess:{value:30}}]),vertexShader:ShaderChunk.meshphong_vert,fragmentShader:ShaderChunk.meshphong_frag},standard:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.roughnessmap,UniformsLib.metalnessmap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:ShaderChunk.meshphysical_vert,fragmentShader:ShaderChunk.meshphysical_frag},points:{uniforms:UniformsUtils.merge([UniformsLib.points,UniformsLib.fog]),vertexShader:ShaderChunk.points_vert,fragmentShader:ShaderChunk.points_frag},dashed:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ShaderChunk.linedashed_vert,fragmentShader:ShaderChunk.linedashed_frag},depth:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.displacementmap]),vertexShader:ShaderChunk.depth_vert,fragmentShader:ShaderChunk.depth_frag},normal:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,{opacity:{value:1}}]),vertexShader:ShaderChunk.normal_vert,fragmentShader:ShaderChunk.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ShaderChunk.cube_vert,fragmentShader:ShaderChunk.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ShaderChunk.equirect_vert,fragmentShader:ShaderChunk.equirect_frag},distanceRGBA:{uniforms:UniformsUtils.merge([UniformsLib.common,UniformsLib.displacementmap,{referencePosition:{value:new Vector3},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ShaderChunk.distanceRGBA_vert,fragmentShader:ShaderChunk.distanceRGBA_frag},shadow:{uniforms:UniformsUtils.merge([UniformsLib.lights,{color:{value:new Color(0)},opacity:{value:1}}]),vertexShader:ShaderChunk.shadow_vert,fragmentShader:ShaderChunk.shadow_frag}};ShaderLib.physical={uniforms:UniformsUtils.merge([ShaderLib.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:ShaderChunk.meshphysical_vert,fragmentShader:ShaderChunk.meshphysical_frag};function Box2(min,max){this.min=min!==undefined?min:new Vector2(+Infinity,+Infinity);this.max=max!==undefined?max:new Vector2(-Infinity,-Infinity)}Object.assign(Box2.prototype,{set:function(min,max){this.min.copy(min);this.max.copy(max);return this},setFromPoints:function(points){this.makeEmpty();for(var i=0,il=points.length;i<il;i++){this.expandByPoint(points[i])}return this},setFromCenterAndSize:function(){var v1=new Vector2;return function setFromCenterAndSize(center,size){var halfSize=v1.copy(size).multiplyScalar(.5);this.min.copy(center).sub(halfSize);this.max.copy(center).add(halfSize);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(box){this.min.copy(box.min);this.max.copy(box.max);return this},makeEmpty:function(){this.min.x=this.min.y=+Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(optionalTarget){var result=optionalTarget||new Vector2;return this.isEmpty()?result.set(0,0):result.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(optionalTarget){var result=optionalTarget||new Vector2;return this.isEmpty()?result.set(0,0):result.subVectors(this.max,this.min)},expandByPoint:function(point){this.min.min(point);this.max.max(point);return this},expandByVector:function(vector){this.min.sub(vector);this.max.add(vector);return this},expandByScalar:function(scalar){this.min.addScalar(-scalar);this.max.addScalar(scalar);return this},containsPoint:function(point){return point.x<this.min.x||point.x>this.max.x||point.y<this.min.y||point.y>this.max.y?false:true},containsBox:function(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y},getParameter:function(point,optionalTarget){var result=optionalTarget||new Vector2;return result.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(box){return box.max.x<this.min.x||box.min.x>this.max.x||box.max.y<this.min.y||box.min.y>this.max.y?false:true},clampPoint:function(point,optionalTarget){var result=optionalTarget||new Vector2;return result.copy(point).clamp(this.min,this.max)},distanceToPoint:function(){var v1=new Vector2;return function distanceToPoint(point){var clampedPoint=v1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}}(),intersect:function(box){this.min.max(box.min);this.max.min(box.max);return this},union:function(box){this.min.min(box.min);this.max.max(box.max);return this},translate:function(offset){this.min.add(offset);this.max.add(offset);return this},equals:function(box){return box.min.equals(this.min)&&box.max.equals(this.max)}});function WebGLFlareRenderer(renderer,gl,state,textures,capabilities){var vertexBuffer,elementBuffer;var shader,program,attributes,uniforms;var tempTexture,occlusionTexture;function init(){var vertices=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]);var faces=new Uint16Array([0,1,2,0,2,3]);vertexBuffer=gl.createBuffer();elementBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,elementBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,faces,gl.STATIC_DRAW);tempTexture=gl.createTexture();occlusionTexture=gl.createTexture();state.bindTexture(gl.TEXTURE_2D,tempTexture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,16,16,0,gl.RGB,gl.UNSIGNED_BYTE,null);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);state.bindTexture(gl.TEXTURE_2D,occlusionTexture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,16,16,0,gl.RGBA,gl.UNSIGNED_BYTE,null);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);shader={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","vUV = uv;","vec2 pos = position;","if ( renderType == 2 ) {","vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","vVisibility = visibility.r / 9.0;","vVisibility *= 1.0 - visibility.g / 9.0;","vVisibility *= visibility.b / 9.0;","vVisibility *= 1.0 - visibility.a / 9.0;","pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","}","gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","if ( renderType == 0 ) {","gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","} else if ( renderType == 1 ) {","gl_FragColor = texture2D( map, vUV );","} else {","vec4 texture = texture2D( map, vUV );","texture.a *= opacity * vVisibility;","gl_FragColor = texture;","gl_FragColor.rgb *= color;","}","}"].join("\n")};program=createProgram(shader);attributes={vertex:gl.getAttribLocation(program,"position"),uv:gl.getAttribLocation(program,"uv")};uniforms={renderType:gl.getUniformLocation(program,"renderType"),map:gl.getUniformLocation(program,"map"),occlusionMap:gl.getUniformLocation(program,"occlusionMap"),opacity:gl.getUniformLocation(program,"opacity"),color:gl.getUniformLocation(program,"color"),scale:gl.getUniformLocation(program,"scale"),rotation:gl.getUniformLocation(program,"rotation"),screenPosition:gl.getUniformLocation(program,"screenPosition")}}this.render=function(flares,scene,camera,viewport){if(flares.length===0)return;var tempPosition=new Vector3;var invAspect=viewport.w/viewport.z,halfViewportWidth=viewport.z*.5,halfViewportHeight=viewport.w*.5;var size=16/viewport.w,scale=new Vector2(size*invAspect,size);var screenPosition=new Vector3(1,1,0),screenPositionPixels=new Vector2(1,1);var validArea=new Box2;validArea.min.set(viewport.x,viewport.y);validArea.max.set(viewport.x+(viewport.z-16),viewport.y+(viewport.w-16));if(program===undefined){init()}state.useProgram(program);state.initAttributes();state.enableAttribute(attributes.vertex);state.enableAttribute(attributes.uv);state.disableUnusedAttributes();gl.uniform1i(uniforms.occlusionMap,0);gl.uniform1i(uniforms.map,1);gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);gl.vertexAttribPointer(attributes.vertex,2,gl.FLOAT,false,2*8,0);gl.vertexAttribPointer(attributes.uv,2,gl.FLOAT,false,2*8,8);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,elementBuffer);state.disable(gl.CULL_FACE);state.buffers.depth.setMask(false);for(var i=0,l=flares.length;i<l;i++){size=16/viewport.w;scale.set(size*invAspect,size);var flare=flares[i];tempPosition.set(flare.matrixWorld.elements[12],flare.matrixWorld.elements[13],flare.matrixWorld.elements[14]);tempPosition.applyMatrix4(camera.matrixWorldInverse);tempPosition.applyMatrix4(camera.projectionMatrix);screenPosition.copy(tempPosition);screenPositionPixels.x=viewport.x+screenPosition.x*halfViewportWidth+halfViewportWidth-8;screenPositionPixels.y=viewport.y+screenPosition.y*halfViewportHeight+halfViewportHeight-8;if(validArea.containsPoint(screenPositionPixels)===true){state.activeTexture(gl.TEXTURE0);state.bindTexture(gl.TEXTURE_2D,null);state.activeTexture(gl.TEXTURE1);state.bindTexture(gl.TEXTURE_2D,tempTexture);gl.copyTexImage2D(gl.TEXTURE_2D,0,gl.RGB,screenPositionPixels.x,screenPositionPixels.y,16,16,0);gl.uniform1i(uniforms.renderType,0);gl.uniform2f(uniforms.scale,scale.x,scale.y);gl.uniform3f(uniforms.screenPosition,screenPosition.x,screenPosition.y,screenPosition.z);state.disable(gl.BLEND);state.enable(gl.DEPTH_TEST);gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);state.activeTexture(gl.TEXTURE0);state.bindTexture(gl.TEXTURE_2D,occlusionTexture);gl.copyTexImage2D(gl.TEXTURE_2D,0,gl.RGBA,screenPositionPixels.x,screenPositionPixels.y,16,16,0);gl.uniform1i(uniforms.renderType,1);state.disable(gl.DEPTH_TEST);state.activeTexture(gl.TEXTURE1);state.bindTexture(gl.TEXTURE_2D,tempTexture);gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);flare.positionScreen.copy(screenPosition);if(flare.customUpdateCallback){flare.customUpdateCallback(flare)}else{flare.updateLensFlares()}gl.uniform1i(uniforms.renderType,2);state.enable(gl.BLEND);for(var j=0,jl=flare.lensFlares.length;j<jl;j++){var sprite=flare.lensFlares[j];if(sprite.opacity>.001&&sprite.scale>.001){screenPosition.x=sprite.x;screenPosition.y=sprite.y;screenPosition.z=sprite.z;size=sprite.size*sprite.scale/viewport.w;scale.x=size*invAspect;scale.y=size;gl.uniform3f(uniforms.screenPosition,screenPosition.x,screenPosition.y,screenPosition.z);gl.uniform2f(uniforms.scale,scale.x,scale.y);gl.uniform1f(uniforms.rotation,sprite.rotation);gl.uniform1f(uniforms.opacity,sprite.opacity);gl.uniform3f(uniforms.color,sprite.color.r,sprite.color.g,sprite.color.b);state.setBlending(sprite.blending,sprite.blendEquation,sprite.blendSrc,sprite.blendDst);textures.setTexture2D(sprite.texture,1);gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0)}}}}state.enable(gl.CULL_FACE);state.enable(gl.DEPTH_TEST);state.buffers.depth.setMask(true);state.reset()};function createProgram(shader){var program=gl.createProgram();var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);var vertexShader=gl.createShader(gl.VERTEX_SHADER);var prefix="precision "+capabilities.precision+" float;\n";gl.shaderSource(fragmentShader,prefix+shader.fragmentShader);gl.shaderSource(vertexShader,prefix+shader.vertexShader);gl.compileShader(fragmentShader);gl.compileShader(vertexShader);gl.attachShader(program,fragmentShader);gl.attachShader(program,vertexShader);gl.linkProgram(program);return program}}function CanvasTexture(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.needsUpdate=true}CanvasTexture.prototype=Object.create(Texture.prototype);CanvasTexture.prototype.constructor=CanvasTexture;function WebGLSpriteRenderer(renderer,gl,state,textures,capabilities){var vertexBuffer,elementBuffer;var program,attributes,uniforms;var texture;var spritePosition=new Vector3;var spriteRotation=new Quaternion;var spriteScale=new Vector3;function init(){var vertices=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]);var faces=new Uint16Array([0,1,2,0,2,3]);vertexBuffer=gl.createBuffer();elementBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,elementBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,faces,gl.STATIC_DRAW);program=createProgram();attributes={position:gl.getAttribLocation(program,"position"),uv:gl.getAttribLocation(program,"uv")};uniforms={uvOffset:gl.getUniformLocation(program,"uvOffset"),uvScale:gl.getUniformLocation(program,"uvScale"),rotation:gl.getUniformLocation(program,"rotation"),scale:gl.getUniformLocation(program,"scale"),color:gl.getUniformLocation(program,"color"),map:gl.getUniformLocation(program,"map"),opacity:gl.getUniformLocation(program,"opacity"),modelViewMatrix:gl.getUniformLocation(program,"modelViewMatrix"),projectionMatrix:gl.getUniformLocation(program,"projectionMatrix"),fogType:gl.getUniformLocation(program,"fogType"),fogDensity:gl.getUniformLocation(program,"fogDensity"),fogNear:gl.getUniformLocation(program,"fogNear"),fogFar:gl.getUniformLocation(program,"fogFar"),fogColor:gl.getUniformLocation(program,"fogColor"),alphaTest:gl.getUniformLocation(program,"alphaTest")};var canvas=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");canvas.width=8;canvas.height=8;var context=canvas.getContext("2d");context.fillStyle="white";context.fillRect(0,0,8,8);texture=new CanvasTexture(canvas)}this.render=function(sprites,scene,camera){if(sprites.length===0)return;if(program===undefined){init()}state.useProgram(program);state.initAttributes();state.enableAttribute(attributes.position);state.enableAttribute(attributes.uv);state.disableUnusedAttributes();state.disable(gl.CULL_FACE);state.enable(gl.BLEND);gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);gl.vertexAttribPointer(attributes.position,2,gl.FLOAT,false,2*8,0);gl.vertexAttribPointer(attributes.uv,2,gl.FLOAT,false,2*8,8);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,elementBuffer);gl.uniformMatrix4fv(uniforms.projectionMatrix,false,camera.projectionMatrix.elements);state.activeTexture(gl.TEXTURE0);gl.uniform1i(uniforms.map,0);var oldFogType=0;var sceneFogType=0;var fog=scene.fog;if(fog){gl.uniform3f(uniforms.fogColor,fog.color.r,fog.color.g,fog.color.b);if(fog.isFog){gl.uniform1f(uniforms.fogNear,fog.near);gl.uniform1f(uniforms.fogFar,fog.far);gl.uniform1i(uniforms.fogType,1);oldFogType=1;sceneFogType=1}else if(fog.isFogExp2){gl.uniform1f(uniforms.fogDensity,fog.density);gl.uniform1i(uniforms.fogType,2);oldFogType=2;sceneFogType=2}}else{gl.uniform1i(uniforms.fogType,0);oldFogType=0;sceneFogType=0}for(var i=0,l=sprites.length;i<l;i++){var sprite=sprites[i];sprite.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse,sprite.matrixWorld);sprite.z=-sprite.modelViewMatrix.elements[14]}sprites.sort(painterSortStable);var scale=[];for(var i=0,l=sprites.length;i<l;i++){var sprite=sprites[i];var material=sprite.material;if(material.visible===false)continue;sprite.onBeforeRender(renderer,scene,camera,undefined,material,undefined);gl.uniform1f(uniforms.alphaTest,material.alphaTest);gl.uniformMatrix4fv(uniforms.modelViewMatrix,false,sprite.modelViewMatrix.elements);sprite.matrixWorld.decompose(spritePosition,spriteRotation,spriteScale);scale[0]=spriteScale.x;scale[1]=spriteScale.y;var fogType=0;if(scene.fog&&material.fog){fogType=sceneFogType}if(oldFogType!==fogType){gl.uniform1i(uniforms.fogType,fogType);oldFogType=fogType}if(material.map!==null){gl.uniform2f(uniforms.uvOffset,material.map.offset.x,material.map.offset.y);gl.uniform2f(uniforms.uvScale,material.map.repeat.x,material.map.repeat.y)}else{gl.uniform2f(uniforms.uvOffset,0,0);gl.uniform2f(uniforms.uvScale,1,1)}gl.uniform1f(uniforms.opacity,material.opacity);gl.uniform3f(uniforms.color,material.color.r,material.color.g,material.color.b);gl.uniform1f(uniforms.rotation,material.rotation);gl.uniform2fv(uniforms.scale,scale);state.setBlending(material.blending,material.blendEquation,material.blendSrc,material.blendDst,material.blendEquationAlpha,material.blendSrcAlpha,material.blendDstAlpha,material.premultipliedAlpha);state.buffers.depth.setTest(material.depthTest);state.buffers.depth.setMask(material.depthWrite);textures.setTexture2D(material.map||texture,0);gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);sprite.onAfterRender(renderer,scene,camera,undefined,material,undefined)}state.enable(gl.CULL_FACE);state.reset()};function createProgram(){var program=gl.createProgram();var vertexShader=gl.createShader(gl.VERTEX_SHADER);var fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(vertexShader,["precision "+capabilities.precision+" float;","#define SHADER_NAME "+"SpriteMaterial","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","void main() {","vUV = uvOffset + uv * uvScale;","vec2 alignedPosition = position * scale;","vec2 rotatedPosition;","rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","vec4 finalPosition;","finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","finalPosition.xy += rotatedPosition;","finalPosition = projectionMatrix * finalPosition;","gl_Position = finalPosition;","}"].join("\n"));gl.shaderSource(fragmentShader,["precision "+capabilities.precision+" float;","#define SHADER_NAME "+"SpriteMaterial","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","void main() {","vec4 texture = texture2D( map, vUV );","if ( texture.a < alphaTest ) discard;","gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","if ( fogType > 0 ) {","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","if ( fogType == 1 ) {","fogFactor = smoothstep( fogNear, fogFar, depth );","} else {","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","}","gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );","}","}"].join("\n"));gl.compileShader(vertexShader);gl.compileShader(fragmentShader);gl.attachShader(program,vertexShader);gl.attachShader(program,fragmentShader);gl.linkProgram(program);return program}function painterSortStable(a,b){if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder}else if(a.z!==b.z){return b.z-a.z}else{return b.id-a.id}}}var materialId=0;function Material(){Object.defineProperty(this,"id",{value:materialId++});this.uuid=_Math.generateUUID();this.name="";this.type="Material";this.fog=true;this.lights=true;this.blending=NormalBlending;this.side=FrontSide;this.flatShading=false;this.vertexColors=NoColors;this.opacity=1;this.transparent=false;this.blendSrc=SrcAlphaFactor;this.blendDst=OneMinusSrcAlphaFactor;this.blendEquation=AddEquation;this.blendSrcAlpha=null;this.blendDstAlpha=null;this.blendEquationAlpha=null;this.depthFunc=LessEqualDepth;this.depthTest=true;this.depthWrite=true;this.clippingPlanes=null;this.clipIntersection=false;this.clipShadows=false;this.colorWrite=true;this.precision=null;this.polygonOffset=false;this.polygonOffsetFactor=0;this.polygonOffsetUnits=0;this.dithering=false;this.alphaTest=0;this.premultipliedAlpha=false;this.overdraw=0;this.visible=true;this.userData={};this.needsUpdate=true}Object.assign(Material.prototype,EventDispatcher.prototype,{isMaterial:true,onBeforeCompile:function(){},setValues:function(values){if(values===undefined)return;for(var key in values){var newValue=values[key];if(newValue===undefined){console.warn("THREE.Material: '"+key+"' parameter is undefined.");continue}if(key==="shading"){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");this.flatShading=newValue===FlatShading?true:false;continue}var currentValue=this[key];if(currentValue===undefined){console.warn("THREE."+this.type+": '"+key+"' is not a property of this material.");continue}if(currentValue&&currentValue.isColor){currentValue.set(newValue)}else if(currentValue&&currentValue.isVector3&&(newValue&&newValue.isVector3)){currentValue.copy(newValue)}else if(key==="overdraw"){this[key]=Number(newValue)}else{this[key]=newValue}}},toJSON:function(meta){var isRoot=meta===undefined;if(isRoot){meta={textures:{},images:{}}}var data={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};data.uuid=this.uuid;data.type=this.type;if(this.name!=="")data.name=this.name;if(this.color&&this.color.isColor)data.color=this.color.getHex();if(this.roughness!==undefined)data.roughness=this.roughness;if(this.metalness!==undefined)data.metalness=this.metalness;if(this.emissive&&this.emissive.isColor)data.emissive=this.emissive.getHex();if(this.specular&&this.specular.isColor)data.specular=this.specular.getHex();if(this.shininess!==undefined)data.shininess=this.shininess;if(this.clearCoat!==undefined)data.clearCoat=this.clearCoat;if(this.clearCoatRoughness!==undefined)data.clearCoatRoughness=this.clearCoatRoughness;if(this.map&&this.map.isTexture)data.map=this.map.toJSON(meta).uuid;if(this.alphaMap&&this.alphaMap.isTexture)data.alphaMap=this.alphaMap.toJSON(meta).uuid;if(this.lightMap&&this.lightMap.isTexture)data.lightMap=this.lightMap.toJSON(meta).uuid;if(this.bumpMap&&this.bumpMap.isTexture){data.bumpMap=this.bumpMap.toJSON(meta).uuid;data.bumpScale=this.bumpScale}if(this.normalMap&&this.normalMap.isTexture){data.normalMap=this.normalMap.toJSON(meta).uuid;data.normalScale=this.normalScale.toArray()}if(this.displacementMap&&this.displacementMap.isTexture){data.displacementMap=this.displacementMap.toJSON(meta).uuid;data.displacementScale=this.displacementScale;data.displacementBias=this.displacementBias}if(this.roughnessMap&&this.roughnessMap.isTexture)data.roughnessMap=this.roughnessMap.toJSON(meta).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)data.metalnessMap=this.metalnessMap.toJSON(meta).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)data.emissiveMap=this.emissiveMap.toJSON(meta).uuid;if(this.specularMap&&this.specularMap.isTexture)data.specularMap=this.specularMap.toJSON(meta).uuid;if(this.envMap&&this.envMap.isTexture){data.envMap=this.envMap.toJSON(meta).uuid;data.reflectivity=this.reflectivity}if(this.gradientMap&&this.gradientMap.isTexture){data.gradientMap=this.gradientMap.toJSON(meta).uuid}if(this.size!==undefined)data.size=this.size;if(this.sizeAttenuation!==undefined)data.sizeAttenuation=this.sizeAttenuation;if(this.blending!==NormalBlending)data.blending=this.blending;if(this.flatShading===true)data.flatShading=this.flatShading;if(this.side!==FrontSide)data.side=this.side;if(this.vertexColors!==NoColors)data.vertexColors=this.vertexColors;if(this.opacity<1)data.opacity=this.opacity;if(this.transparent===true)data.transparent=this.transparent;data.depthFunc=this.depthFunc;data.depthTest=this.depthTest;data.depthWrite=this.depthWrite;if(this.dithering===true)data.dithering=true;if(this.alphaTest>0)data.alphaTest=this.alphaTest;if(this.premultipliedAlpha===true)data.premultipliedAlpha=this.premultipliedAlpha;if(this.wireframe===true)data.wireframe=this.wireframe;if(this.wireframeLinewidth>1)data.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")data.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")data.wireframeLinejoin=this.wireframeLinejoin;if(this.morphTargets===true)data.morphTargets=true;if(this.skinning===true)data.skinning=true;if(this.visible===false)data.visible=false;if(JSON.stringify(this.userData)!=="{}")data.userData=this.userData;function extractFromCache(cache){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data)}return values}if(isRoot){var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images}return data},clone:function(){return(new this.constructor).copy(this)},copy:function(source){this.name=source.name;this.fog=source.fog;this.lights=source.lights;this.blending=source.blending;this.side=source.side;this.flatShading=source.flatShading;this.vertexColors=source.vertexColors;this.opacity=source.opacity;this.transparent=source.transparent;this.blendSrc=source.blendSrc;this.blendDst=source.blendDst;this.blendEquation=source.blendEquation;this.blendSrcAlpha=source.blendSrcAlpha;this.blendDstAlpha=source.blendDstAlpha;this.blendEquationAlpha=source.blendEquationAlpha;this.depthFunc=source.depthFunc;this.depthTest=source.depthTest;this.depthWrite=source.depthWrite;this.colorWrite=source.colorWrite;this.precision=source.precision;this.polygonOffset=source.polygonOffset;this.polygonOffsetFactor=source.polygonOffsetFactor;this.polygonOffsetUnits=source.polygonOffsetUnits;this.dithering=source.dithering;this.alphaTest=source.alphaTest;this.premultipliedAlpha=source.premultipliedAlpha;this.overdraw=source.overdraw;this.visible=source.visible;this.userData=JSON.parse(JSON.stringify(source.userData));this.clipShadows=source.clipShadows;this.clipIntersection=source.clipIntersection;var srcPlanes=source.clippingPlanes,dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var i=0;i!==n;++i)dstPlanes[i]=srcPlanes[i].clone()}this.clippingPlanes=dstPlanes;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});function ShaderMaterial(parameters){Material.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.lights=false;this.clipping=false;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.extensions={derivatives:false,fragDepth:false,drawBuffers:false,shaderTextureLOD:false};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=undefined;if(parameters!==undefined){if(parameters.attributes!==undefined){console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.")}this.setValues(parameters)}}ShaderMaterial.prototype=Object.create(Material.prototype);ShaderMaterial.prototype.constructor=ShaderMaterial;ShaderMaterial.prototype.isShaderMaterial=true;ShaderMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.fragmentShader=source.fragmentShader;this.vertexShader=source.vertexShader;this.uniforms=UniformsUtils.clone(source.uniforms);this.defines=source.defines;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.lights=source.lights;this.clipping=source.clipping;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;this.extensions=source.extensions;return this};ShaderMaterial.prototype.toJSON=function(meta){var data=Material.prototype.toJSON.call(this,meta);data.uniforms=this.uniforms;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;return data};function MeshDepthMaterial(parameters){Material.call(this);this.type="MeshDepthMaterial";this.depthPacking=BasicDepthPacking;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.lights=false;this.setValues(parameters)}MeshDepthMaterial.prototype=Object.create(Material.prototype);MeshDepthMaterial.prototype.constructor=MeshDepthMaterial;MeshDepthMaterial.prototype.isMeshDepthMaterial=true;MeshDepthMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.depthPacking=source.depthPacking;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;return this};function MeshDistanceMaterial(parameters){Material.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new Vector3;this.nearDistance=1;this.farDistance=1e3;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.fog=false;this.lights=false;this.setValues(parameters)}MeshDistanceMaterial.prototype=Object.create(Material.prototype);MeshDistanceMaterial.prototype.constructor=MeshDistanceMaterial;MeshDistanceMaterial.prototype.isMeshDistanceMaterial=true;MeshDistanceMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.referencePosition.copy(source.referencePosition);this.nearDistance=source.nearDistance;this.farDistance=source.farDistance;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;return this};function Box3(min,max){this.min=min!==undefined?min:new Vector3(+Infinity,+Infinity,+Infinity)

this.max=max!==undefined?max
new Vector3(-Infinity,-Infinity,-Infinity)}Object.assign(Box3.prototype,{isBox3:true,set:function(min,max){this.min.copy(min);this.max.copy(max);return this},setFromArray:function(array){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var i=0,l=array.length;i<l;i+=3){var x=array[i];var y=array[i+1];var z=array[i+2];if(x<minX)minX=x;if(y<minY)minY=y;if(z<minZ)minZ=z;if(x>maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this},setFromBufferAttribute:function(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var i=0,l=attribute.count;i<l;i++){var x=attribute.getX(i);var y=attribute.getY(i);var z=attribute.getZ(i);if(x<minX)minX=x;if(y<minY)minY=y;if(z<minZ)minZ=z;if(x>maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this},setFromPoints:function(points){this.makeEmpty();for(var i=0,il=points.length;i<il;i++){this.expandByPoint(points[i])}return this},setFromCenterAndSize:function(){var v1=new Vector3;return function setFromCenterAndSize(center,size){var halfSize=v1.copy(size).multiplyScalar(.5);this.min.copy(center).sub(halfSize);this.max.copy(center).add(halfSize);return this}}(),setFromObject:function(object){this.makeEmpty();return this.expandByObject(object)},clone:function(){return(new this.constructor).copy(this)},copy:function(box){this.min.copy(box.min);this.max.copy(box.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=+Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(optionalTarget){var result=optionalTarget||new Vector3;return this.isEmpty()?result.set(0,0,0):result.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(optionalTarget){var result=optionalTarget||new Vector3;return this.isEmpty()?result.set(0,0,0):result.subVectors(this.max,this.min)},expandByPoint:function(point){this.min.min(point);this.max.max(point);return this},expandByVector:function(vector){this.min.sub(vector);this.max.add(vector);return this},expandByScalar:function(scalar){this.min.addScalar(-scalar);this.max.addScalar(scalar);return this},expandByObject:function(){var v1=new Vector3;return function expandByObject(object){var scope=this;object.updateMatrixWorld(true);object.traverse(function(node){var i,l;var geometry=node.geometry;if(geometry!==undefined){if(geometry.isGeometry){var vertices=geometry.vertices;for(i=0,l=vertices.length;i<l;i++){v1.copy(vertices[i]);v1.applyMatrix4(node.matrixWorld);scope.expandByPoint(v1)}}else if(geometry.isBufferGeometry){var attribute=geometry.attributes.position;if(attribute!==undefined){for(i=0,l=attribute.count;i<l;i++){v1.fromBufferAttribute(attribute,i).applyMatrix4(node.matrixWorld);scope.expandByPoint(v1)}}}}});return this}}(),containsPoint:function(point){return point.x<this.min.x||point.x>this.max.x||point.y<this.min.y||point.y>this.max.y||point.z<this.min.z||point.z>this.max.z?false:true},containsBox:function(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y&&this.min.z<=box.min.z&&box.max.z<=this.max.z},getParameter:function(point,optionalTarget){var result=optionalTarget||new Vector3;return result.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y),(point.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(box){return box.max.x<this.min.x||box.min.x>this.max.x||box.max.y<this.min.y||box.min.y>this.max.y||box.max.z<this.min.z||box.min.z>this.max.z?false:true},intersectsSphere:function(){var closestPoint=new Vector3;return function intersectsSphere(sphere){this.clampPoint(sphere.center,closestPoint);return closestPoint.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius}}(),intersectsPlane:function(plane){var min,max;if(plane.normal.x>0){min=plane.normal.x*this.min.x;max=plane.normal.x*this.max.x}else{min=plane.normal.x*this.max.x;max=plane.normal.x*this.min.x}if(plane.normal.y>0){min+=plane.normal.y*this.min.y;max+=plane.normal.y*this.max.y}else{min+=plane.normal.y*this.max.y;max+=plane.normal.y*this.min.y}if(plane.normal.z>0){min+=plane.normal.z*this.min.z;max+=plane.normal.z*this.max.z}else{min+=plane.normal.z*this.max.z;max+=plane.normal.z*this.min.z}return min<=plane.constant&&max>=plane.constant},clampPoint:function(point,optionalTarget){var result=optionalTarget||new Vector3;return result.copy(point).clamp(this.min,this.max)},distanceToPoint:function(){var v1=new Vector3;return function distanceToPoint(point){var clampedPoint=v1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}}(),getBoundingSphere:function(){var v1=new Vector3;return function getBoundingSphere(optionalTarget){var result=optionalTarget||new Sphere;this.getCenter(result.center);result.radius=this.getSize(v1).length()*.5;return result}}(),intersect:function(box){this.min.max(box.min);this.max.min(box.max);if(this.isEmpty())this.makeEmpty();return this},union:function(box){this.min.min(box.min);this.max.max(box.max);return this},applyMatrix4:function(){var points=[new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3];return function applyMatrix4(matrix){if(this.isEmpty())return this;points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);this.setFromPoints(points);return this}}(),translate:function(offset){this.min.add(offset);this.max.add(offset);return this},equals:function(box){return box.min.equals(this.min)&&box.max.equals(this.max)}});function Sphere(center,radius){this.center=center!==undefined?center:new Vector3;this.radius=radius!==undefined?radius:0}Object.assign(Sphere.prototype,{set:function(center,radius){this.center.copy(center);this.radius=radius;return this},setFromPoints:function(){var box=new Box3;return function setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter)}else{box.setFromPoints(points).getCenter(center)}var maxRadiusSq=0;for(var i=0,il=points.length;i<il;i++){maxRadiusSq=Math.max(maxRadiusSq,center.distanceToSquared(points[i]))}this.radius=Math.sqrt(maxRadiusSq);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(sphere){this.center.copy(sphere.center);this.radius=sphere.radius;return this},empty:function(){return this.radius<=0},containsPoint:function(point){return point.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(point){return point.distanceTo(this.center)-this.radius},intersectsSphere:function(sphere){var radiusSum=this.radius+sphere.radius;return sphere.center.distanceToSquared(this.center)<=radiusSum*radiusSum},intersectsBox:function(box){return box.intersectsSphere(this)},intersectsPlane:function(plane){return Math.abs(plane.distanceToPoint(this.center))<=this.radius},clampPoint:function(point,optionalTarget){var deltaLengthSq=this.center.distanceToSquared(point);var result=optionalTarget||new Vector3;result.copy(point);if(deltaLengthSq>this.radius*this.radius){result.sub(this.center).normalize();result.multiplyScalar(this.radius).add(this.center)}return result},getBoundingBox:function(optionalTarget){var box=optionalTarget||new Box3;box.set(this.center,this.center);box.expandByScalar(this.radius);return box},applyMatrix4:function(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this},translate:function(offset){this.center.add(offset);return this},equals:function(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius}});function Matrix3(){this.elements=[1,0,0,0,1,0,0,0,1];if(arguments.length>0){console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}}Object.assign(Matrix3.prototype,{isMatrix3:true,set:function(n11,n12,n13,n21,n22,n23,n31,n32,n33){var te=this.elements;te[0]=n11;te[1]=n21;te[2]=n31;te[3]=n12;te[4]=n22;te[5]=n32;te[6]=n13;te[7]=n23;te[8]=n33;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];return this},setFromMatrix4:function(m){var me=m.elements;this.set(me[0],me[4],me[8],me[1],me[5],me[9],me[2],me[6],me[10]);return this},applyToBufferAttribute:function(){var v1=new Vector3;return function applyToBufferAttribute(attribute){for(var i=0,l=attribute.count;i<l;i++){v1.x=attribute.getX(i);v1.y=attribute.getY(i);v1.z=attribute.getZ(i);v1.applyMatrix3(this);attribute.setXYZ(i,v1.x,v1.y,v1.z)}return attribute}}(),multiply:function(m){return this.multiplyMatrices(this,m)},premultiply:function(m){return this.multiplyMatrices(m,this)},multiplyMatrices:function(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[3],a13=ae[6];var a21=ae[1],a22=ae[4],a23=ae[7];var a31=ae[2],a32=ae[5],a33=ae[8];var b11=be[0],b12=be[3],b13=be[6];var b21=be[1],b22=be[4],b23=be[7];var b31=be[2],b32=be[5],b33=be[8];te[0]=a11*b11+a12*b21+a13*b31;te[3]=a11*b12+a12*b22+a13*b32;te[6]=a11*b13+a12*b23+a13*b33;te[1]=a21*b11+a22*b21+a23*b31;te[4]=a21*b12+a22*b22+a23*b32;te[7]=a21*b13+a22*b23+a23*b33;te[2]=a31*b11+a32*b21+a33*b31;te[5]=a31*b12+a32*b22+a33*b32;te[8]=a31*b13+a32*b23+a33*b33;return this},multiplyScalar:function(s){var te=this.elements;te[0]*=s;te[3]*=s;te[6]*=s;te[1]*=s;te[4]*=s;te[7]*=s;te[2]*=s;te[5]*=s;te[8]*=s;return this},determinant:function(){var te=this.elements;var a=te[0],b=te[1],c=te[2],d=te[3],e=te[4],f=te[5],g=te[6],h=te[7],i=te[8];return a*e*i-a*f*h-b*d*i+b*f*g+c*d*h-c*e*g},getInverse:function(matrix,throwOnDegenerate){if(matrix&&matrix.isMatrix4){console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.")}var me=matrix.elements,te=this.elements,n11=me[0],n21=me[1],n31=me[2],n12=me[3],n22=me[4],n32=me[5],n13=me[6],n23=me[7],n33=me[8],t11=n33*n22-n32*n23,t12=n32*n13-n33*n12,t13=n23*n12-n22*n13,det=n11*t11+n21*t12+n31*t13;if(det===0){var msg="THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";if(throwOnDegenerate===true){throw new Error(msg)}else{console.warn(msg)}return this.identity()}var detInv=1/det;te[0]=t11*detInv;te[1]=(n31*n23-n33*n21)*detInv;te[2]=(n32*n21-n31*n22)*detInv;te[3]=t12*detInv;te[4]=(n33*n11-n31*n13)*detInv;te[5]=(n31*n12-n32*n11)*detInv;te[6]=t13*detInv;te[7]=(n21*n13-n23*n11)*detInv;te[8]=(n22*n11-n21*n12)*detInv;return this},transpose:function(){var tmp,m=this.elements;tmp=m[1];m[1]=m[3];m[3]=tmp;tmp=m[2];m[2]=m[6];m[6]=tmp;tmp=m[5];m[5]=m[7];m[7]=tmp;return this},getNormalMatrix:function(matrix4){return this.setFromMatrix4(matrix4).getInverse(this).transpose()},transposeIntoArray:function(r){var m=this.elements;r[0]=m[0];r[1]=m[3];r[2]=m[6];r[3]=m[1];r[4]=m[4];r[5]=m[7];r[6]=m[2];r[7]=m[5];r[8]=m[8];return this},equals:function(matrix){var te=this.elements;var me=matrix.elements;for(var i=0;i<9;i++){if(te[i]!==me[i])return false}return true},fromArray:function(array,offset){if(offset===undefined)offset=0;for(var i=0;i<9;i++){this.elements[i]=array[i+offset]}return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];return array}});function Plane(normal,constant){this.normal=normal!==undefined?normal:new Vector3(1,0,0);this.constant=constant!==undefined?constant:0}Object.assign(Plane.prototype,{set:function(normal,constant){this.normal.copy(normal);this.constant=constant;return this},setComponents:function(x,y,z,w){this.normal.set(x,y,z);this.constant=w;return this},setFromNormalAndCoplanarPoint:function(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this},setFromCoplanarPoints:function(){var v1=new Vector3;var v2=new Vector3;return function setFromCoplanarPoints(a,b,c){var normal=v1.subVectors(c,b).cross(v2.subVectors(a,b)).normalize();this.setFromNormalAndCoplanarPoint(normal,a);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this},normalize:function(){var inverseNormalLength=1/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(point){return this.normal.dot(point)+this.constant},distanceToSphere:function(sphere){return this.distanceToPoint(sphere.center)-sphere.radius},projectPoint:function(point,optionalTarget){var result=optionalTarget||new Vector3;return result.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point)},intersectLine:function(){var v1=new Vector3;return function intersectLine(line,optionalTarget){var result=optionalTarget||new Vector3;var direction=line.delta(v1);var denominator=this.normal.dot(direction);if(denominator===0){if(this.distanceToPoint(line.start)===0){return result.copy(line.start)}return undefined}var t=-(line.start.dot(this.normal)+this.constant)/denominator;if(t<0||t>1){return undefined}return result.copy(direction).multiplyScalar(t).add(line.start)}}(),intersectsLine:function(line){var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0},intersectsBox:function(box){return box.intersectsPlane(this)},intersectsSphere:function(sphere){return sphere.intersectsPlane(this)},coplanarPoint:function(optionalTarget){var result=optionalTarget||new Vector3;return result.copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var v1=new Vector3;var m1=new Matrix3;return function applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||m1.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(v1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this}}(),translate:function(offset){this.constant-=offset.dot(this.normal);return this},equals:function(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant}});function Frustum(p0,p1,p2,p3,p4,p5){this.planes=[p0!==undefined?p0:new Plane,p1!==undefined?p1:new Plane,p2!==undefined?p2:new Plane,p3!==undefined?p3:new Plane,p4!==undefined?p4:new Plane,p5!==undefined?p5:new Plane]}Object.assign(Frustum.prototype,{set:function(p0,p1,p2,p3,p4,p5){var planes=this.planes;planes[0].copy(p0);planes[1].copy(p1);planes[2].copy(p2);planes[3].copy(p3);planes[4].copy(p4);planes[5].copy(p5);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(frustum){var planes=this.planes;for(var i=0;i<6;i++){planes[i].copy(frustum.planes[i])}return this},setFromMatrix:function(m){var planes=this.planes;var me=m.elements;var me0=me[0],me1=me[1],me2=me[2],me3=me[3];var me4=me[4],me5=me[5],me6=me[6],me7=me[7];var me8=me[8],me9=me[9],me10=me[10],me11=me[11];var me12=me[12],me13=me[13],me14=me[14],me15=me[15];planes[0].setComponents(me3-me0,me7-me4,me11-me8,me15-me12).normalize();planes[1].setComponents(me3+me0,me7+me4,me11+me8,me15+me12).normalize();planes[2].setComponents(me3+me1,me7+me5,me11+me9,me15+me13).normalize();planes[3].setComponents(me3-me1,me7-me5,me11-me9,me15-me13).normalize();planes[4].setComponents(me3-me2,me7-me6,me11-me10,me15-me14).normalize();planes[5].setComponents(me3+me2,me7+me6,me11+me10,me15+me14).normalize();return this},intersectsObject:function(){var sphere=new Sphere;return function intersectsObject(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();sphere.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(sphere)}}(),intersectsSprite:function(){var sphere=new Sphere;return function intersectsSprite(sprite){sphere.center.set(0,0,0);sphere.radius=.7071067811865476;sphere.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(sphere)}}(),intersectsSphere:function(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var i=0;i<6;i++){var distance=planes[i].distanceToPoint(center);if(distance<negRadius){return false}}return true},intersectsBox:function(){var p1=new Vector3,p2=new Vector3;return function intersectsBox(box){var planes=this.planes;for(var i=0;i<6;i++){var plane=planes[i];p1.x=plane.normal.x>0?box.min.x:box.max.x;p2.x=plane.normal.x>0?box.max.x:box.min.x;p1.y=plane.normal.y>0?box.min.y:box.max.y;p2.y=plane.normal.y>0?box.max.y:box.min.y;p1.z=plane.normal.z>0?box.min.z:box.max.z;p2.z=plane.normal.z>0?box.max.z:box.min.z;var d1=plane.distanceToPoint(p1);var d2=plane.distanceToPoint(p2);if(d1<0&&d2<0){return false}}return true}}(),containsPoint:function(point){var planes=this.planes;for(var i=0;i<6;i++){if(planes[i].distanceToPoint(point)<0){return false}}return true}});function WebGLShadowMap(_renderer,_objects,maxTextureSize){var _frustum=new Frustum,_projScreenMatrix=new Matrix4,_shadowMapSize=new Vector2,_maxShadowMapSize=new Vector2(maxTextureSize,maxTextureSize),_lookTarget=new Vector3,_lightPositionWorld=new Vector3,_MorphingFlag=1,_SkinningFlag=2,_NumberOfMaterialVariants=(_MorphingFlag|_SkinningFlag)+1,_depthMaterials=new Array(_NumberOfMaterialVariants),_distanceMaterials=new Array(_NumberOfMaterialVariants),_materialCache={};var cubeDirections=[new Vector3(1,0,0),new Vector3(-1,0,0),new Vector3(0,0,1),new Vector3(0,0,-1),new Vector3(0,1,0),new Vector3(0,-1,0)];var cubeUps=[new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,0,1),new Vector3(0,0,-1)];var cube2DViewPorts=[new Vector4,new Vector4,new Vector4,new Vector4,new Vector4,new Vector4];for(var i=0;i!==_NumberOfMaterialVariants;++i){var useMorphing=(i&_MorphingFlag)!==0;var useSkinning=(i&_SkinningFlag)!==0;var depthMaterial=new MeshDepthMaterial({depthPacking:RGBADepthPacking,morphTargets:useMorphing,skinning:useSkinning});_depthMaterials[i]=depthMaterial;var distanceMaterial=new MeshDistanceMaterial({morphTargets:useMorphing,skinning:useSkinning});_distanceMaterials[i]=distanceMaterial}var scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;this.renderReverseSided=true;this.renderSingleSided=true;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;var _gl=_renderer.context;var _state=_renderer.state;_state.disable(_gl.BLEND);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);var faceCount;for(var i=0,il=lights.length;i<il;i++){var light=lights[i];var shadow=light.shadow;var isPointLight=light&&light.isPointLight;if(shadow===undefined){console.warn("THREE.WebGLShadowMap:",light,"has no shadow.");continue}var shadowCamera=shadow.camera;_shadowMapSize.copy(shadow.mapSize);_shadowMapSize.min(_maxShadowMapSize);if(isPointLight){var vpWidth=_shadowMapSize.x;var vpHeight=_shadowMapSize.y;cube2DViewPorts[0].set(vpWidth*2,vpHeight,vpWidth,vpHeight);cube2DViewPorts[1].set(0,vpHeight,vpWidth,vpHeight);cube2DViewPorts[2].set(vpWidth*3,vpHeight,vpWidth,vpHeight);cube2DViewPorts[3].set(vpWidth,vpHeight,vpWidth,vpHeight);cube2DViewPorts[4].set(vpWidth*3,0,vpWidth,vpHeight);cube2DViewPorts[5].set(vpWidth,0,vpWidth,vpHeight);_shadowMapSize.x*=4;_shadowMapSize.y*=2}if(shadow.map===null){var pars={minFilter:NearestFilter,magFilter:NearestFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadowCamera.updateProjectionMatrix()}if(shadow.isSpotLightShadow){shadow.update(light)}var shadowMap=shadow.map;var shadowMatrix=shadow.matrix;_lightPositionWorld.setFromMatrixPosition(light.matrixWorld);shadowCamera.position.copy(_lightPositionWorld);if(isPointLight){faceCount=6;shadowMatrix.makeTranslation(-_lightPositionWorld.x,-_lightPositionWorld.y,-_lightPositionWorld.z)}else{faceCount=1;_lookTarget.setFromMatrixPosition(light.target.matrixWorld);shadowCamera.lookAt(_lookTarget);shadowCamera.updateMatrixWorld();shadowMatrix.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);shadowMatrix.multiply(shadowCamera.projectionMatrix);shadowMatrix.multiply(shadowCamera.matrixWorldInverse)}_renderer.setRenderTarget(shadowMap);_renderer.clear();for(var face=0;face<faceCount;face++){if(isPointLight){_lookTarget.copy(shadowCamera.position);_lookTarget.add(cubeDirections[face]);shadowCamera.up.copy(cubeUps[face]);shadowCamera.lookAt(_lookTarget);shadowCamera.updateMatrixWorld();var vpDimensions=cube2DViewPorts[face];_state.viewport(vpDimensions)}_projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix,shadowCamera.matrixWorldInverse);_frustum.setFromMatrix(_projScreenMatrix);renderObject(scene,camera,shadowCamera,isPointLight)}}scope.needsUpdate=false};function getDepthMaterial(object,material,isPointLight,lightPositionWorld,shadowCameraNear,shadowCameraFar){var geometry=object.geometry;var result=null;var materialVariants=_depthMaterials;var customMaterial=object.customDepthMaterial;if(isPointLight){materialVariants=_distanceMaterials;customMaterial=object.customDistanceMaterial}if(!customMaterial){var useMorphing=false;if(material.morphTargets){if(geometry&&geometry.isBufferGeometry){useMorphing=geometry.morphAttributes&&geometry.morphAttributes.position&&geometry.morphAttributes.position.length>0}else if(geometry&&geometry.isGeometry){useMorphing=geometry.morphTargets&&geometry.morphTargets.length>0}}if(object.isSkinnedMesh&&material.skinning===false){console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",object)}var useSkinning=object.isSkinnedMesh&&material.skinning;var variantIndex=0;if(useMorphing)variantIndex|=_MorphingFlag;if(useSkinning)variantIndex|=_SkinningFlag;result=materialVariants[variantIndex]}else{result=customMaterial}if(_renderer.localClippingEnabled&&material.clipShadows===true&&material.clippingPlanes.length!==0){var keyA=result.uuid,keyB=material.uuid;var materialsForVariant=_materialCache[keyA];if(materialsForVariant===undefined){materialsForVariant={};_materialCache[keyA]=materialsForVariant}var cachedMaterial=materialsForVariant[keyB];if(cachedMaterial===undefined){cachedMaterial=result.clone();materialsForVariant[keyB]=cachedMaterial}result=cachedMaterial}result.visible=material.visible;result.wireframe=material.wireframe;var side=material.side;if(scope.renderSingleSided&&side==DoubleSide){side=FrontSide}if(scope.renderReverseSided){if(side===FrontSide)side=BackSide;else if(side===BackSide)side=FrontSide}result.side=side;result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(isPointLight&&result.isMeshDistanceMaterial){result.referencePosition.copy(lightPositionWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar}return result}function renderObject(object,camera,shadowCamera,isPointLight){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if(object.castShadow&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);var geometry=_objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var k=0,kl=groups.length;k<kl;k++){var group=groups[k];var groupMaterial=material[group.materialIndex];if(groupMaterial&&groupMaterial.visible){var depthMaterial=getDepthMaterial(object,groupMaterial,isPointLight,_lightPositionWorld,shadowCamera.near,shadowCamera.far);_renderer.renderBufferDirect(shadowCamera,null,geometry,depthMaterial,object,group)}}}else if(material.visible){var depthMaterial=getDepthMaterial(object,material,isPointLight,_lightPositionWorld,shadowCamera.near,shadowCamera.far);_renderer.renderBufferDirect(shadowCamera,null,geometry,depthMaterial,object,null)}}}var children=object.children;for(var i=0,l=children.length;i<l;i++){renderObject(children[i],camera,shadowCamera,isPointLight)}}}function WebGLAttributes(gl){var buffers={};function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.dynamic?gl.DYNAMIC_DRAW:gl.STATIC_DRAW;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=gl.FLOAT;if(array instanceof Float32Array){type=gl.FLOAT}else if(array instanceof Float64Array){console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.")}else if(array instanceof Uint16Array){type=gl.UNSIGNED_SHORT}else if(array instanceof Int16Array){type=gl.SHORT}else if(array instanceof Uint32Array){type=gl.UNSIGNED_INT}else if(array instanceof Int32Array){type=gl.INT}else if(array instanceof Int8Array){type=gl.BYTE}else if(array instanceof Uint8Array){type=gl.UNSIGNED_BYTE}return{buffer:buffer,type:type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version}}function updateBuffer(buffer,attribute,bufferType){var array=attribute.array;var updateRange=attribute.updateRange;gl.bindBuffer(bufferType,buffer);if(attribute.dynamic===false){gl.bufferData(bufferType,array,gl.STATIC_DRAW)}else if(updateRange.count===-1){gl.bufferSubData(bufferType,0,array)}else if(updateRange.count===0){console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.")}else{gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count));updateRange.count=-1}}function get(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers[attribute.uuid]}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers[attribute.uuid];if(data){gl.deleteBuffer(data.buffer);delete buffers[attribute.uuid]}}function update(attribute,bufferType){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers[attribute.uuid];if(data===undefined){buffers[attribute.uuid]=createBuffer(attribute,bufferType)}else if(data.version<attribute.version){updateBuffer(data.buffer,attribute,bufferType);data.version=attribute.version}}return{get:get,remove:remove,update:update}}function Euler(x,y,z,order){this._x=x||0;this._y=y||0;this._z=z||0;this._order=order||Euler.DefaultOrder}Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];Euler.DefaultOrder="XYZ";Object.defineProperties(Euler.prototype,{x:{get:function(){return this._x},set:function(value){this._x=value;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(value){this._y=value;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(value){this._z=value;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(value){this._order=value;this.onChangeCallback()}}});Object.assign(Euler.prototype,{isEuler:true,set:function(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this.onChangeCallback();return this},setFromRotationMatrix:function(m,order,update){var clamp=_Math.clamp;var te=m.elements;var m11=te[0],m12=te[4],m13=te[8];var m21=te[1],m22=te[5],m23=te[9];var m31=te[2],m32=te[6],m33=te[10];order=order||this._order;if(order==="XYZ"){this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<.99999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11)}else{this._x=Math.atan2(m32,m22);this._z=0}}else if(order==="YXZ"){this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<.99999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22)}else{this._y=Math.atan2(-m31,m11);this._z=0}}else if(order==="ZXY"){this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<.99999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22)}else{this._y=0;this._z=Math.atan2(m21,m11)}}else if(order==="ZYX"){this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<.99999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11)}else{this._x=0;this._z=Math.atan2(-m12,m22)}}else if(order==="YZX"){this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<.99999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11)}else{this._x=0;this._y=Math.atan2(m13,m33)}}else if(order==="XZY"){this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<.99999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11)}else{this._x=Math.atan2(-m23,m33);this._y=0}}else{console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+order)}this._order=order;if(update!==false)this.onChangeCallback();return this},setFromQuaternion:function(){var matrix=new Matrix4;return function setFromQuaternion(q,order,update){matrix.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(matrix,order,update)}}(),setFromVector3:function(v,order){return this.set(v.x,v.y,v.z,order||this._order)},reorder:function(){var q=new Quaternion;return function reorder(newOrder){q.setFromEuler(this);return this.setFromQuaternion(q,newOrder)}}(),equals:function(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order},fromArray:function(array){this._x=array[0];this._y=array[1];this._z=array[2];if(array[3]!==undefined)this._order=array[3];this.onChangeCallback();return this},toArray:function(array,offset){if(array===undefined)array=[];if(offset===undefined)offset=0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array},toVector3:function(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z)}else{return new Vector3(this._x,this._y,this._z)}},onChange:function(callback){this.onChangeCallback=callback;return this},onChangeCallback:function(){}});function Layers(){this.mask=1|0}Object.assign(Layers.prototype,{set:function(channel){this.mask=1<<channel|0},enable:function(channel){this.mask|=1<<channel|0},toggle:function(channel){this.mask^=1<<channel|0},disable:function(channel){this.mask&=~(1<<channel|0)},test:function(layers){return(this.mask&layers.mask)!==0}});var object3DId=0;function Object3D(){Object.defineProperty(this,"id",{value:object3DId++});this.uuid=_Math.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=Object3D.DefaultUp.clone();var position=new Vector3;var rotation=new Euler;var quaternion=new Quaternion;var scale=new Vector3(1,1,1);function onRotationChange(){

quaternion.setFromEuler(rotation,false)}function onQuaternionChange(){rotation.setFromQuaternion(quaternion,undefined,false)}rotation.onChange(onRotationChange);quaternion.onChange(onQuaternionChange);Object.defineProperties(this,{position:{enumerable:true,value:position},rotation:{enumerable:true,value:rotation},quaternion:{enumerable:true,value:quaternion},scale:{enumerable:true,value:scale},modelViewMatrix:{value:new Matrix4},normalMatrix:{value:new Matrix3}});this.matrix=new Matrix4;this.matrixWorld=new Matrix4;this.matrixAutoUpdate=Object3D.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=false;this.layers=new Layers;this.visible=true;this.castShadow=false;this.receiveShadow=false;this.frustumCulled=true;this.renderOrder=0;this.userData={}}Object3D.DefaultUp=new Vector3(0,1,0);Object3D.DefaultMatrixAutoUpdate=true;Object.assign(Object3D.prototype,EventDispatcher.prototype,{isObject3D:true,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(matrix){this.matrix.multiplyMatrices(matrix,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(q){this.quaternion.premultiply(q);return this},setRotationFromAxisAngle:function(axis,angle){this.quaternion.setFromAxisAngle(axis,angle)},setRotationFromEuler:function(euler){this.quaternion.setFromEuler(euler,true)},setRotationFromMatrix:function(m){this.quaternion.setFromRotationMatrix(m)},setRotationFromQuaternion:function(q){this.quaternion.copy(q)},rotateOnAxis:function(){var q1=new Quaternion;return function rotateOnAxis(axis,angle){q1.setFromAxisAngle(axis,angle);this.quaternion.multiply(q1);return this}}(),rotateX:function(){var v1=new Vector3(1,0,0);return function rotateX(angle){return this.rotateOnAxis(v1,angle)}}(),rotateY:function(){var v1=new Vector3(0,1,0);return function rotateY(angle){return this.rotateOnAxis(v1,angle)}}(),rotateZ:function(){var v1=new Vector3(0,0,1);return function rotateZ(angle){return this.rotateOnAxis(v1,angle)}}(),translateOnAxis:function(){var v1=new Vector3;return function translateOnAxis(axis,distance){v1.copy(axis).applyQuaternion(this.quaternion);this.position.add(v1.multiplyScalar(distance));return this}}(),translateX:function(){var v1=new Vector3(1,0,0);return function translateX(distance){return this.translateOnAxis(v1,distance)}}(),translateY:function(){var v1=new Vector3(0,1,0);return function translateY(distance){return this.translateOnAxis(v1,distance)}}(),translateZ:function(){var v1=new Vector3(0,0,1);return function translateZ(distance){return this.translateOnAxis(v1,distance)}}(),localToWorld:function(vector){return vector.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var m1=new Matrix4;return function worldToLocal(vector){return vector.applyMatrix4(m1.getInverse(this.matrixWorld))}}(),lookAt:function(){var m1=new Matrix4;return function lookAt(vector){if(this.isCamera){m1.lookAt(this.position,vector,this.up)}else{m1.lookAt(vector,this.position,this.up)}this.quaternion.setFromRotationMatrix(m1)}}(),add:function(object){if(arguments.length>1){for(var i=0;i<arguments.length;i++){this.add(arguments[i])}return this}if(object===this){console.error("THREE.Object3D.add: object can't be added as a child of itself.",object);return this}if(object&&object.isObject3D){if(object.parent!==null){object.parent.remove(object)}object.parent=this;object.dispatchEvent({type:"added"});this.children.push(object)}else{console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",object)}return this},remove:function(object){if(arguments.length>1){for(var i=0;i<arguments.length;i++){this.remove(arguments[i])}return this}var index=this.children.indexOf(object);if(index!==-1){object.parent=null;object.dispatchEvent({type:"removed"});this.children.splice(index,1)}return this},getObjectById:function(id){return this.getObjectByProperty("id",id)},getObjectByName:function(name){return this.getObjectByProperty("name",name)},getObjectByProperty:function(name,value){if(this[name]===value)return this;for(var i=0,l=this.children.length;i<l;i++){var child=this.children[i];var object=child.getObjectByProperty(name,value);if(object!==undefined){return object}}return undefined},getWorldPosition:function(optionalTarget){var result=optionalTarget||new Vector3;this.updateMatrixWorld(true);return result.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var position=new Vector3;var scale=new Vector3;return function getWorldQuaternion(optionalTarget){var result=optionalTarget||new Quaternion;this.updateMatrixWorld(true);this.matrixWorld.decompose(position,result,scale);return result}}(),getWorldRotation:function(){var quaternion=new Quaternion;return function getWorldRotation(optionalTarget){var result=optionalTarget||new Euler;this.getWorldQuaternion(quaternion);return result.setFromQuaternion(quaternion,this.rotation.order,false)}}(),getWorldScale:function(){var position=new Vector3;var quaternion=new Quaternion;return function getWorldScale(optionalTarget){var result=optionalTarget||new Vector3;this.updateMatrixWorld(true);this.matrixWorld.decompose(position,quaternion,result);return result}}(),getWorldDirection:function(){var quaternion=new Quaternion;return function getWorldDirection(optionalTarget){var result=optionalTarget||new Vector3;this.getWorldQuaternion(quaternion);return result.set(0,0,1).applyQuaternion(quaternion)}}(),raycast:function(){},traverse:function(callback){callback(this);var children=this.children;for(var i=0,l=children.length;i<l;i++){children[i].traverse(callback)}},traverseVisible:function(callback){if(this.visible===false)return;callback(this);var children=this.children;for(var i=0,l=children.length;i<l;i++){children[i].traverseVisible(callback)}},traverseAncestors:function(callback){var parent=this.parent;if(parent!==null){callback(parent);parent.traverseAncestors(callback)}},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale);this.matrixWorldNeedsUpdate=true},updateMatrixWorld:function(force){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||force){if(this.parent===null){this.matrixWorld.copy(this.matrix)}else{this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)}this.matrixWorldNeedsUpdate=false;force=true}var children=this.children;for(var i=0,l=children.length;i<l;i++){children[i].updateMatrixWorld(force)}},toJSON:function(meta){var isRootObject=meta===undefined||meta==="";var output={};if(isRootObject){meta={geometries:{},materials:{},textures:{},images:{}};output.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"}}var object={};object.uuid=this.uuid;object.type=this.type;if(this.name!=="")object.name=this.name;if(this.castShadow===true)object.castShadow=true;if(this.receiveShadow===true)object.receiveShadow=true;if(this.visible===false)object.visible=false;if(JSON.stringify(this.userData)!=="{}")object.userData=this.userData;object.matrix=this.matrix.toArray();function serialize(library,element){if(library[element.uuid]===undefined){library[element.uuid]=element.toJSON(meta)}return element.uuid}if(this.geometry!==undefined){object.geometry=serialize(meta.geometries,this.geometry)}if(this.material!==undefined){if(Array.isArray(this.material)){var uuids=[];for(var i=0,l=this.material.length;i<l;i++){uuids.push(serialize(meta.materials,this.material[i]))}object.material=uuids}else{object.material=serialize(meta.materials,this.material)}}if(this.children.length>0){object.children=[];for(var i=0;i<this.children.length;i++){object.children.push(this.children[i].toJSON(meta).object)}}if(isRootObject){var geometries=extractFromCache(meta.geometries);var materials=extractFromCache(meta.materials);var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(geometries.length>0)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images}output.object=object;return output;function extractFromCache(cache){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data)}return values}},clone:function(recursive){return(new this.constructor).copy(this,recursive)},copy:function(source,recursive){if(recursive===undefined)recursive=true;this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.quaternion.copy(source.quaternion);this.scale.copy(source.scale);this.matrix.copy(source.matrix);this.matrixWorld.copy(source.matrixWorld);this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrixWorldNeedsUpdate=source.matrixWorldNeedsUpdate;this.layers.mask=source.layers.mask;this.visible=source.visible;this.castShadow=source.castShadow;this.receiveShadow=source.receiveShadow;this.frustumCulled=source.frustumCulled;this.renderOrder=source.renderOrder;this.userData=JSON.parse(JSON.stringify(source.userData));if(recursive===true){for(var i=0;i<source.children.length;i++){var child=source.children[i];this.add(child.clone())}}return this}});function Camera(){Object3D.call(this);this.type="Camera";this.matrixWorldInverse=new Matrix4;this.projectionMatrix=new Matrix4}Camera.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Camera,isCamera:true,copy:function(source,recursive){Object3D.prototype.copy.call(this,source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);return this},getWorldDirection:function(){var quaternion=new Quaternion;return function getWorldDirection(optionalTarget){var result=optionalTarget||new Vector3;this.getWorldQuaternion(quaternion);return result.set(0,0,-1).applyQuaternion(quaternion)}}(),updateMatrixWorld:function(force){Object3D.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});function OrthographicCamera(left,right,top,bottom,near,far){Camera.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=left;this.right=right;this.top=top;this.bottom=bottom;this.near=near!==undefined?near:.1;this.far=far!==undefined?far:2e3;this.updateProjectionMatrix()}OrthographicCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:OrthographicCamera,isOrthographicCamera:true,copy:function(source,recursive){Camera.prototype.copy.call(this,source,recursive);this.left=source.left;this.right=source.right;this.top=source.top;this.bottom=source.bottom;this.near=source.near;this.far=source.far;this.zoom=source.zoom;this.view=source.view===null?null:Object.assign({},source.view);return this},setViewOffset:function(fullWidth,fullHeight,x,y,width,height){this.view={fullWidth:fullWidth,fullHeight:fullHeight,offsetX:x,offsetY:y,width:width,height:height};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var dx=(this.right-this.left)/(2*this.zoom);var dy=(this.top-this.bottom)/(2*this.zoom);var cx=(this.right+this.left)/2;var cy=(this.top+this.bottom)/2;var left=cx-dx;var right=cx+dx;var top=cy+dy;var bottom=cy-dy;if(this.view!==null){var zoomW=this.zoom/(this.view.width/this.view.fullWidth);var zoomH=this.zoom/(this.view.height/this.view.fullHeight);var scaleW=(this.right-this.left)/this.view.width;var scaleH=(this.top-this.bottom)/this.view.height;left+=scaleW*(this.view.offsetX/zoomW);right=left+scaleW*(this.view.width/zoomW);top-=scaleH*(this.view.offsetY/zoomH);bottom=top-scaleH*(this.view.height/zoomH)}this.projectionMatrix.makeOrthographic(left,right,top,bottom,this.near,this.far)},toJSON:function(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.zoom=this.zoom;data.object.left=this.left;data.object.right=this.right;data.object.top=this.top;data.object.bottom=this.bottom;data.object.near=this.near;data.object.far=this.far;if(this.view!==null)data.object.view=Object.assign({},this.view);return data}});function PerspectiveCamera(fov,aspect,near,far){Camera.call(this);this.type="PerspectiveCamera";this.fov=fov!==undefined?fov:50;this.zoom=1;this.near=near!==undefined?near:.1;this.far=far!==undefined?far:2e3;this.focus=10;this.aspect=aspect!==undefined?aspect:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}PerspectiveCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:PerspectiveCamera,isPerspectiveCamera:true,copy:function(source,recursive){Camera.prototype.copy.call(this,source,recursive);this.fov=source.fov;this.zoom=source.zoom;this.near=source.near;this.far=source.far;this.focus=source.focus;this.aspect=source.aspect;this.view=source.view===null?null:Object.assign({},source.view);this.filmGauge=source.filmGauge;this.filmOffset=source.filmOffset;return this},setFocalLength:function(focalLength){var vExtentSlope=.5*this.getFilmHeight()/focalLength;this.fov=_Math.RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix()},getFocalLength:function(){var vExtentSlope=Math.tan(_Math.DEG2RAD*.5*this.fov);return.5*this.getFilmHeight()/vExtentSlope},getEffectiveFOV:function(){return _Math.RAD2DEG*2*Math.atan(Math.tan(_Math.DEG2RAD*.5*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;this.view={fullWidth:fullWidth,fullHeight:fullHeight,offsetX:x,offsetY:y,width:width,height:height};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var near=this.near,top=near*Math.tan(_Math.DEG2RAD*.5*this.fov)/this.zoom,height=2*top,width=this.aspect*height,left=-.5*width,view=this.view;if(view!==null){var fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight}var skew=this.filmOffset;if(skew!==0)left+=near*skew/this.getFilmWidth();this.projectionMatrix.makePerspective(left,left+width,top,top-height,near,this.far)},toJSON:function(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.fov=this.fov;data.object.zoom=this.zoom;data.object.near=this.near;data.object.far=this.far;data.object.focus=this.focus;data.object.aspect=this.aspect;if(this.view!==null)data.object.view=Object.assign({},this.view);data.object.filmGauge=this.filmGauge;data.object.filmOffset=this.filmOffset;return data}});function Face3(a,b,c,normal,color,materialIndex){this.a=a;this.b=b;this.c=c;this.normal=normal&&normal.isVector3?normal:new Vector3;this.vertexNormals=Array.isArray(normal)?normal:[];this.color=color&&color.isColor?color:new Color;this.vertexColors=Array.isArray(color)?color:[];this.materialIndex=materialIndex!==undefined?materialIndex:0}Object.assign(Face3.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(source){this.a=source.a;this.b=source.b;this.c=source.c;this.normal.copy(source.normal);this.color.copy(source.color);this.materialIndex=source.materialIndex;for(var i=0,il=source.vertexNormals.length;i<il;i++){this.vertexNormals[i]=source.vertexNormals[i].clone()}for(var i=0,il=source.vertexColors.length;i<il;i++){this.vertexColors[i]=source.vertexColors[i].clone()}return this}});var count=0;function GeometryIdCount(){return count++}function Geometry(){Object.defineProperty(this,"id",{value:GeometryIdCount()});this.uuid=_Math.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;this.elementsNeedUpdate=false;this.verticesNeedUpdate=false;this.uvsNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.lineDistancesNeedUpdate=false;this.groupsNeedUpdate=false}Object.assign(Geometry.prototype,EventDispatcher.prototype,{isGeometry:true,applyMatrix:function(matrix){var normalMatrix=(new Matrix3).getNormalMatrix(matrix);for(var i=0,il=this.vertices.length;i<il;i++){var vertex=this.vertices[i];vertex.applyMatrix4(matrix)}for(var i=0,il=this.faces.length;i<il;i++){var face=this.faces[i];face.normal.applyMatrix3(normalMatrix).normalize();for(var j=0,jl=face.vertexNormals.length;j<jl;j++){face.vertexNormals[j].applyMatrix3(normalMatrix).normalize()}}if(this.boundingBox!==null){this.computeBoundingBox()}if(this.boundingSphere!==null){this.computeBoundingSphere()}this.verticesNeedUpdate=true;this.normalsNeedUpdate=true;return this},rotateX:function(){var m1=new Matrix4;return function rotateX(angle){m1.makeRotationX(angle);this.applyMatrix(m1);return this}}(),rotateY:function(){var m1=new Matrix4;return function rotateY(angle){m1.makeRotationY(angle);this.applyMatrix(m1);return this}}(),rotateZ:function(){var m1=new Matrix4;return function rotateZ(angle){m1.makeRotationZ(angle);this.applyMatrix(m1);return this}}(),translate:function(){var m1=new Matrix4;return function translate(x,y,z){m1.makeTranslation(x,y,z);this.applyMatrix(m1);return this}}(),scale:function(){var m1=new Matrix4;return function scale(x,y,z){m1.makeScale(x,y,z);this.applyMatrix(m1);return this}}(),lookAt:function(){var obj=new Object3D;return function lookAt(vector){obj.lookAt(vector);obj.updateMatrix();this.applyMatrix(obj.matrix)}}(),fromBufferGeometry:function(geometry){var scope=this;var indices=geometry.index!==null?geometry.index.array:undefined;var attributes=geometry.attributes;var positions=attributes.position.array;var normals=attributes.normal!==undefined?attributes.normal.array:undefined;var colors=attributes.color!==undefined?attributes.color.array:undefined;var uvs=attributes.uv!==undefined?attributes.uv.array:undefined;var uvs2=attributes.uv2!==undefined?attributes.uv2.array:undefined;if(uvs2!==undefined)this.faceVertexUvs[1]=[];var tempNormals=[];var tempUVs=[];var tempUVs2=[];for(var i=0,j=0;i<positions.length;i+=3,j+=2){scope.vertices.push(new Vector3(positions[i],positions[i+1],positions[i+2]));if(normals!==undefined){tempNormals.push(new Vector3(normals[i],normals[i+1],normals[i+2]))}if(colors!==undefined){scope.colors.push(new Color(colors[i],colors[i+1],colors[i+2]))}if(uvs!==undefined){tempUVs.push(new Vector2(uvs[j],uvs[j+1]))}if(uvs2!==undefined){tempUVs2.push(new Vector2(uvs2[j],uvs2[j+1]))}}function addFace(a,b,c,materialIndex){var vertexNormals=normals!==undefined?[tempNormals[a].clone(),tempNormals[b].clone(),tempNormals[c].clone()]:[];var vertexColors=colors!==undefined?[scope.colors[a].clone(),scope.colors[b].clone(),scope.colors[c].clone()]:[];var face=new Face3(a,b,c,vertexNormals,vertexColors,materialIndex);scope.faces.push(face);if(uvs!==undefined){scope.faceVertexUvs[0].push([tempUVs[a].clone(),tempUVs[b].clone(),tempUVs[c].clone()])}if(uvs2!==undefined){scope.faceVertexUvs[1].push([tempUVs2[a].clone(),tempUVs2[b].clone(),tempUVs2[c].clone()])}}var groups=geometry.groups;if(groups.length>0){for(var i=0;i<groups.length;i++){var group=groups[i];var start=group.start;var count=group.count;for(var j=start,jl=start+count;j<jl;j+=3){if(indices!==undefined){addFace(indices[j],indices[j+1],indices[j+2],group.materialIndex)}else{addFace(j,j+1,j+2,group.materialIndex)}}}}else{if(indices!==undefined){for(var i=0;i<indices.length;i+=3){addFace(indices[i],indices[i+1],indices[i+2])}}else{for(var i=0;i<positions.length/3;i+=3){addFace(i,i+1,i+2)}}}this.computeFaceNormals();if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone()}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone()}return this},center:function(){this.computeBoundingBox();var offset=this.boundingBox.getCenter().negate();this.translate(offset.x,offset.y,offset.z);return offset},normalize:function(){this.computeBoundingSphere();var center=this.boundingSphere.center;var radius=this.boundingSphere.radius;var s=radius===0?1:1/radius;var matrix=new Matrix4;matrix.set(s,0,0,-s*center.x,0,s,0,-s*center.y,0,0,s,-s*center.z,0,0,0,1);this.applyMatrix(matrix);return this},computeFaceNormals:function(){var cb=new Vector3,ab=new Vector3;for(var f=0,fl=this.faces.length;f<fl;f++){var face=this.faces[f];var vA=this.vertices[face.a];var vB=this.vertices[face.b];var vC=this.vertices[face.c];cb.subVectors(vC,vB);ab.subVectors(vA,vB);cb.cross(ab);cb.normalize();face.normal.copy(cb)}},computeVertexNormals:function(areaWeighted){if(areaWeighted===undefined)areaWeighted=true;var v,vl,f,fl,face,vertices;vertices=new Array(this.vertices.length);for(v=0,vl=this.vertices.length;v<vl;v++){vertices[v]=new Vector3}if(areaWeighted){var vA,vB,vC;var cb=new Vector3,ab=new Vector3;for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];vA=this.vertices[face.a];vB=this.vertices[face.b];vC=this.vertices[face.c];cb.subVectors(vC,vB);ab.subVectors(vA,vB);cb.cross(ab);vertices[face.a].add(cb);vertices[face.b].add(cb);vertices[face.c].add(cb)}}else{this.computeFaceNormals();for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];vertices[face.a].add(face.normal);vertices[face.b].add(face.normal);vertices[face.c].add(face.normal)}}for(v=0,vl=this.vertices.length;v<vl;v++){vertices[v].normalize()}for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];var vertexNormals=face.vertexNormals;if(vertexNormals.length===3){vertexNormals[0].copy(vertices[face.a]);vertexNormals[1].copy(vertices[face.b]);vertexNormals[2].copy(vertices[face.c])}else{vertexNormals[0]=vertices[face.a].clone();vertexNormals[1]=vertices[face.b].clone();vertexNormals[2]=vertices[face.c].clone()}}if(this.faces.length>0){this.normalsNeedUpdate=true}},computeFlatVertexNormals:function(){var f,fl,face;this.computeFaceNormals();for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];var vertexNormals=face.vertexNormals;if(vertexNormals.length===3){vertexNormals[0].copy(face.normal);vertexNormals[1].copy(face.normal);vertexNormals[2].copy(face.normal)}else{vertexNormals[0]=face.normal.clone();vertexNormals[1]=face.normal.clone();vertexNormals[2]=face.normal.clone()}}if(this.faces.length>0){this.normalsNeedUpdate=true}},computeMorphNormals:function(){var i,il,f,fl,face;for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];if(!face.__originalFaceNormal){face.__originalFaceNormal=face.normal.clone()}else{face.__originalFaceNormal.copy(face.normal)}if(!face.__originalVertexNormals)face.__originalVertexNormals=[];for(i=0,il=face.vertexNormals.length;i<il;i++){if(!face.__originalVertexNormals[i]){face.__originalVertexNormals[i]=face.vertexNormals[i].clone()}else{face.__originalVertexNormals[i].copy(face.vertexNormals[i])}}}var tmpGeo=new Geometry;tmpGeo.faces=this.faces;for(i=0,il=this.morphTargets.length;i<il;i++){if(!this.morphNormals[i]){this.morphNormals[i]={};this.morphNormals[i].faceNormals=[];this.morphNormals[i].vertexNormals=[];var dstNormalsFace=this.morphNormals[i].faceNormals;var dstNormalsVertex=this.morphNormals[i].vertexNormals;var faceNormal,vertexNormals;for(f=0,fl=this.faces.length;f<fl;f++){faceNormal=new Vector3;vertexNormals={a:new Vector3,b:new Vector3,c:new Vector3};dstNormalsFace.push(faceNormal);dstNormalsVertex.push(vertexNormals)}}var morphNormals=this.morphNormals[i];tmpGeo.vertices=this.morphTargets[i].vertices;tmpGeo.computeFaceNormals();tmpGeo.computeVertexNormals();var faceNormal,vertexNormals;for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];faceNormal=morphNormals.faceNormals[f];vertexNormals=morphNormals.vertexNormals[f];faceNormal.copy(face.normal);vertexNormals.a.copy(face.vertexNormals[0]);vertexNormals.b.copy(face.vertexNormals[1]);vertexNormals.c.copy(face.vertexNormals[2])}}for(f=0,fl=this.faces.length;f<fl;f++){face=this.faces[f];face.normal=face.__originalFaceNormal;face.vertexNormals=face.__originalVertexNormals}},computeLineDistances:function(){var d=0;var vertices=this.vertices;for(var i=0,il=vertices.length;i<il;i++){if(i>0){d+=vertices[i].distanceTo(vertices[i-1])}this.lineDistances[i]=d}},computeBoundingBox:function(){if(this.boundingBox===null){this.boundingBox=new Box3}this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){if(this.boundingSphere===null){this.boundingSphere=new Sphere}this.boundingSphere.setFromPoints(this.vertices)},merge:function(geometry,matrix,materialIndexOffset){if(!(geometry&&geometry.isGeometry)){console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",geometry);return}var normalMatrix,vertexOffset=this.vertices.length,vertices1=this.vertices,vertices2=geometry.vertices,faces1=this.faces,faces2=geometry.faces,uvs1=this.faceVertexUvs[0],uvs2=geometry.faceVertexUvs[0],colors1=this.colors,colors2=geometry.colors;if(materialIndexOffset===undefined)materialIndexOffset=0;if(matrix!==undefined){normalMatrix=(new Matrix3).getNormalMatrix(matrix)}for(var i=0,il=vertices2.length;i<il;i++){var vertex=vertices2[i];var vertexCopy=vertex.clone();if(matrix!==undefined)vertexCopy.applyMatrix4(matrix);vertices1.push(vertexCopy)}for(var i=0,il=colors2.length;i<il;i++){colors1.push(colors2[i].clone())}for(i=0,il=faces2.length;i<il;i++){var face=faces2[i],faceCopy,normal,color,faceVertexNormals=face.vertexNormals,faceVertexColors=face.vertexColors;faceCopy=new Face3(face.a+vertexOffset,face.b+vertexOffset,face.c+vertexOffset);faceCopy.normal.copy(face.normal);if(normalMatrix!==undefined){faceCopy.normal.applyMatrix3(normalMatrix).normalize()}for(var j=0,jl=faceVertexNormals.length;j<jl;j++){normal=faceVertexNormals[j].clone();if(normalMatrix!==undefined){normal.applyMatrix3(normalMatrix).normalize()}faceCopy.vertexNormals.push(normal)}faceCopy.color.copy(face.color);for(var j=0,jl=faceVertexColors.length;j<jl;j++){color=faceVertexColors[j];faceCopy.vertexColors.push(color.clone())}faceCopy.materialIndex=face.materialIndex+materialIndexOffset;faces1.push(faceCopy)}for(i=0,il=uvs2.length;i<il;i++){var uv=uvs2[i],uvCopy=[];if(uv===undefined){continue}for(var j=0,jl=uv.length;j<jl;j++){uvCopy.push(uv[j].clone())}uvs1.push(uvCopy)}},mergeMesh:function(mesh){if(!(mesh&&mesh.isMesh)){console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",mesh);return}mesh.matrixAutoUpdate&&mesh.updateMatrix();this.merge(mesh.geometry,mesh.matrix)},mergeVertices:function(){var verticesMap={};var unique=[],changes=[];var v,key;var precisionPoints=4;var precision=Math.pow(10,precisionPoints);var i,il,face;var indices,j,jl;for(i=0,il=this.vertices.length;i<il;i++){v=this.vertices[i];key=Math.round(v.x*precision)+"_"+Math.round(v.y*precision)+"_"+Math.round(v.z*precision);if(verticesMap[key]===undefined){verticesMap[key]=i;unique.push(this.vertices[i]);changes[i]=unique.length-1}else{changes[i]=changes[verticesMap[key]]}}var faceIndicesToRemove=[];for(i=0,il=this.faces.length;i<il;i++){face=this.faces[i];face.a=changes[face.a];face.b=changes[face.b];face.c=changes[face.c];indices=[face.a,face.b,face.c];for(var n=0;n<3;n++){if(indices[n]===indices[(n+1)%3]){faceIndicesToRemove.push(i);break}}}for(i=faceIndicesToRemove.length-1;i>=0;i--){var idx=faceIndicesToRemove[i];this.faces.splice(idx,1);for(j=0,jl=this.faceVertexUvs.length;j<jl;j++){this.faceVertexUvs[j].splice(idx,1)}}var diff=this.vertices.length-unique.length;this.vertices=unique;return diff},sortFacesByMaterialIndex:function(){var faces=this.faces;var length=faces.length;for(var i=0;i<length;i++){faces[i]._id=i}function materialIndexSort(a,b){return a.materialIndex-b.materialIndex}faces.sort(materialIndexSort);var uvs1=this.faceVertexUvs[0];var uvs2=this.faceVertexUvs[1];var newUvs1,newUvs2;if(uvs1&&uvs1.length===length)newUvs1=[];if(uvs2&&uvs2.length===length)newUvs2=[];for(var i=0;i<length;i++){var id=faces[i]._id;if(newUvs1)newUvs1.push(uvs1[id]);if(newUvs2)newUvs2.push(uvs2[id])}if(newUvs1)this.faceVertexUvs[0]=newUvs1;if(newUvs2)this.faceVertexUvs[1]=newUvs2},toJSON:function(){var data={metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};data.uuid=this.uuid;data.type=this.type;if(this.name!=="")data.name=this.name;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key]}return data}var vertices=[];for(var i=0;i<this.vertices.length;i++){var vertex=this.vertices[i];vertices.push(vertex.x,vertex.y,vertex.z)}var faces=[];var normals=[];var normalsHash={};var colors=[];var colorsHash={};var uvs=[];var uvsHash={};for(var i=0;i<this.faces.length;i++){var face=this.faces[i];var hasMaterial=true;var hasFaceUv=false;var hasFaceVertexUv=this.faceVertexUvs[0][i]!==undefined;var hasFaceNormal=face.normal.length()>0;var hasFaceVertexNormal=face.vertexNormals.length>0;var hasFaceColor=face.color.r!==1||face.color.g!==1||face.color.b!==1;var hasFaceVertexColor=face.vertexColors.length>0;var faceType=0;faceType=setBit(faceType,0,0);faceType=setBit(faceType,1,hasMaterial);faceType=setBit(faceType,2,hasFaceUv);faceType=setBit(faceType,3,hasFaceVertexUv);faceType=setBit(faceType,4,hasFaceNormal);faceType=setBit(faceType,5,hasFaceVertexNormal);faceType=setBit(faceType,6,hasFaceColor);faceType=setBit(faceType,7,hasFaceVertexColor);faces.push(faceType);faces.push(face.a,face.b,face.c);faces.push(face.materialIndex);if(hasFaceVertexUv){var faceVertexUvs=this.faceVertexUvs[0][i];faces.push(getUvIndex(faceVertexUvs[0]),getUvIndex(faceVertexUvs[1]),getUvIndex(faceVertexUvs[2]))}if(hasFaceNormal){faces.push(getNormalIndex(face.normal))}if(hasFaceVertexNormal){var vertexNormals=face.vertexNormals;faces.push(getNormalIndex(vertexNormals[0]),getNormalIndex(vertexNormals[1]),getNormalIndex(vertexNormals[2]))}if(hasFaceColor){faces.push(getColorIndex(face.color))}if(hasFaceVertexColor){var vertexColors=face.vertexColors;faces.push(getColorIndex(vertexColors[0]),getColorIndex(vertexColors[1]),getColorIndex(vertexColors[2]))}}function setBit(value,position,enabled){return enabled?value|1<<position:value&~(1<<position)}function getNormalIndex(normal){var hash=normal.x.toString()+normal.y.toString()+normal.z.toString();if(normalsHash[hash]!==undefined){return normalsHash[hash]}normalsHash[hash]=normals.length/3;normals.push(normal.x,normal.y,normal.z);return normalsHash[hash]}function getColorIndex(color){var hash=color.r.toString()+color.g.toString()+color.b.toString();if(colorsHash[hash]!==undefined){return colorsHash[hash]}colorsHash[hash]=colors.length;colors.push(color.getHex());return colorsHash[hash]}function getUvIndex(uv){var hash=uv.x.toString()+uv.y.toString();if(uvsHash[hash]!==undefined){return uvsHash[hash]}uvsHash[hash]=uvs.length/2;uvs.push(uv.x,uv.y);return uvsHash[hash]}data.data={};data.data.vertices=vertices;data.data.normals=normals;if(colors.length>0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];data.data.faces=faces;return data},clone:function(){return(new Geometry).copy(this)},copy:function(source){var i,il,j,jl,k,kl;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;this.name=source.name;var vertices=source.vertices;for(i=0,il=vertices.length;i<il;i++){this.vertices.push(vertices[i].clone())}var colors=source.colors;for(i=0,il=colors.length;i<il;i++){this.colors.push(colors[i].clone())}var faces=source.faces;for(i=0,il=faces.length;i<il;i++){this.faces.push(faces[i].clone())}for(i=0,il=source.faceVertexUvs.length;i<il;i++){var faceVertexUvs=source.faceVertexUvs[i];if(this.faceVertexUvs[i]===undefined){this.faceVertexUvs[i]=[]}for(j=0,jl=faceVertexUvs.length;j<jl;j++){var uvs=faceVertexUvs[j],uvsCopy=[];for(k=0,kl=uvs.length;k<kl;k++){var uv=uvs[k];uvsCopy.push(uv.clone())}this.faceVertexUvs[i].push(uvsCopy)}}var morphTargets=source.morphTargets;for(i=0,il=morphTargets.length;i<il;i++){ var morphTarget={};morphTarget.name=morphTargets[i].name;if(morphTargets[i].vertices!==undefined){morphTarget.vertices=[];for(j=0,jl=morphTargets[i].vertices.length;j<jl;j++){morphTarget.vertices.push(morphTargets[i].vertices[j].clone())}}if(morphTargets[i].normals!==undefined){morphTarget.normals=[];for(j=0,jl=morphTargets[i].normals.length;j<jl;j++){morphTarget.normals.push(morphTargets[i].normals[j].clone())}}this.morphTargets.push(morphTarget)}var morphNormals=source.morphNormals;for(i=0,il=morphNormals.length;i<il;i++){var morphNormal={};if(morphNormals[i].vertexNormals!==undefined){morphNormal.vertexNormals=[];for(j=0,jl=morphNormals[i].vertexNormals.length;j<jl;j++){var srcVertexNormal=morphNormals[i].vertexNormals[j];var destVertexNormal={};destVertexNormal.a=srcVertexNormal.a.clone();destVertexNormal.b=srcVertexNormal.b.clone();destVertexNormal.c=srcVertexNormal.c.clone();morphNormal.vertexNormals.push(destVertexNormal)}}if(morphNormals[i].faceNormals!==undefined){morphNormal.faceNormals=[];for(j=0,jl=morphNormals[i].faceNormals.length;j<jl;j++){morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone())}}this.morphNormals.push(morphNormal)}var skinWeights=source.skinWeights;for(i=0,il=skinWeights.length;i<il;i++){this.skinWeights.push(skinWeights[i].clone())}var skinIndices=source.skinIndices;for(i=0,il=skinIndices.length;i<il;i++){this.skinIndices.push(skinIndices[i].clone())}var lineDistances=source.lineDistances;for(i=0,il=lineDistances.length;i<il;i++){this.lineDistances.push(lineDistances[i])}var boundingBox=source.boundingBox;if(boundingBox!==null){this.boundingBox=boundingBox.clone()}var boundingSphere=source.boundingSphere;if(boundingSphere!==null){this.boundingSphere=boundingSphere.clone()}this.elementsNeedUpdate=source.elementsNeedUpdate;this.verticesNeedUpdate=source.verticesNeedUpdate;this.uvsNeedUpdate=source.uvsNeedUpdate;this.normalsNeedUpdate=source.normalsNeedUpdate;this.colorsNeedUpdate=source.colorsNeedUpdate;this.lineDistancesNeedUpdate=source.lineDistancesNeedUpdate;this.groupsNeedUpdate=source.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});function BufferAttribute(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.")}this.uuid=_Math.generateUUID();this.name="";this.array=array;this.itemSize=itemSize;this.count=array!==undefined?array.length/itemSize:0;this.normalized=normalized===true;this.dynamic=false;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}Object.defineProperty(BufferAttribute.prototype,"needsUpdate",{set:function(value){if(value===true)this.version++}});Object.assign(BufferAttribute.prototype,{isBufferAttribute:true,setArray:function(array){if(Array.isArray(array)){throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.")}this.count=array!==undefined?array.length/this.itemSize:0;this.array=array},setDynamic:function(value){this.dynamic=value;return this},copy:function(source){this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.dynamic=source.dynamic;return this},copyAt:function(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var i=0,l=this.itemSize;i<l;i++){this.array[index1+i]=attribute.array[index2+i]}return this},copyArray:function(array){this.array.set(array);return this},copyColorsArray:function(colors){var array=this.array,offset=0;for(var i=0,l=colors.length;i<l;i++){var color=colors[i];if(color===undefined){console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",i);color=new Color}array[offset++]=color.r;array[offset++]=color.g;array[offset++]=color.b}return this},copyIndicesArray:function(indices){var array=this.array,offset=0;for(var i=0,l=indices.length;i<l;i++){var index=indices[i];array[offset++]=index.a;array[offset++]=index.b;array[offset++]=index.c}return this},copyVector2sArray:function(vectors){var array=this.array,offset=0;for(var i=0,l=vectors.length;i<l;i++){var vector=vectors[i];if(vector===undefined){console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",i);vector=new Vector2}array[offset++]=vector.x;array[offset++]=vector.y}return this},copyVector3sArray:function(vectors){var array=this.array,offset=0;for(var i=0,l=vectors.length;i<l;i++){var vector=vectors[i];if(vector===undefined){console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",i);vector=new Vector3}array[offset++]=vector.x;array[offset++]=vector.y;array[offset++]=vector.z}return this},copyVector4sArray:function(vectors){var array=this.array,offset=0;for(var i=0,l=vectors.length;i<l;i++){var vector=vectors[i];if(vector===undefined){console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",i);vector=new Vector4}array[offset++]=vector.x;array[offset++]=vector.y;array[offset++]=vector.z;array[offset++]=vector.w}return this},set:function(value,offset){if(offset===undefined)offset=0;this.array.set(value,offset);return this},getX:function(index){return this.array[index*this.itemSize]},setX:function(index,x){this.array[index*this.itemSize]=x;return this},getY:function(index){return this.array[index*this.itemSize+1]},setY:function(index,y){this.array[index*this.itemSize+1]=y;return this},getZ:function(index){return this.array[index*this.itemSize+2]},setZ:function(index,z){this.array[index*this.itemSize+2]=z;return this},getW:function(index){return this.array[index*this.itemSize+3]},setW:function(index,w){this.array[index*this.itemSize+3]=w;return this},setXY:function(index,x,y){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;return this},setXYZ:function(index,x,y,z){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;this.array[index+2]=z;return this},setXYZW:function(index,x,y,z,w){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;this.array[index+2]=z;this.array[index+3]=w;return this},onUpload:function(callback){this.onUploadCallback=callback;return this},clone:function(){return new this.constructor(this.array,this.itemSize).copy(this)}});function Int8BufferAttribute(array,itemSize){BufferAttribute.call(this,new Int8Array(array),itemSize)}Int8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int8BufferAttribute.prototype.constructor=Int8BufferAttribute;function Uint8BufferAttribute(array,itemSize){BufferAttribute.call(this,new Uint8Array(array),itemSize)}Uint8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8BufferAttribute.prototype.constructor=Uint8BufferAttribute;function Uint8ClampedBufferAttribute(array,itemSize){BufferAttribute.call(this,new Uint8ClampedArray(array),itemSize)}Uint8ClampedBufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8ClampedBufferAttribute.prototype.constructor=Uint8ClampedBufferAttribute;function Int16BufferAttribute(array,itemSize){BufferAttribute.call(this,new Int16Array(array),itemSize)}Int16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int16BufferAttribute.prototype.constructor=Int16BufferAttribute;function Uint16BufferAttribute(array,itemSize){BufferAttribute.call(this,new Uint16Array(array),itemSize)}Uint16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint16BufferAttribute.prototype.constructor=Uint16BufferAttribute;function Int32BufferAttribute(array,itemSize){BufferAttribute.call(this,new Int32Array(array),itemSize)}Int32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int32BufferAttribute.prototype.constructor=Int32BufferAttribute;function Uint32BufferAttribute(array,itemSize){BufferAttribute.call(this,new Uint32Array(array),itemSize)}Uint32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint32BufferAttribute.prototype.constructor=Uint32BufferAttribute;function Float32BufferAttribute(array,itemSize){BufferAttribute.call(this,new Float32Array(array),itemSize)}Float32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float32BufferAttribute.prototype.constructor=Float32BufferAttribute;function Float64BufferAttribute(array,itemSize){BufferAttribute.call(this,new Float64Array(array),itemSize)}Float64BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float64BufferAttribute.prototype.constructor=Float64BufferAttribute;function DirectGeometry(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingBox=null;this.boundingSphere=null;this.verticesNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.uvsNeedUpdate=false;this.groupsNeedUpdate=false}Object.assign(DirectGeometry.prototype,{computeGroups:function(geometry){var group;var groups=[];var materialIndex=undefined;var faces=geometry.faces;for(var i=0;i<faces.length;i++){var face=faces[i];if(face.materialIndex!==materialIndex){materialIndex=face.materialIndex;if(group!==undefined){group.count=i*3-group.start;groups.push(group)}group={start:i*3,materialIndex:materialIndex}}}if(group!==undefined){group.count=i*3-group.start;groups.push(group)}this.groups=groups},fromGeometry:function(geometry){var faces=geometry.faces;var vertices=geometry.vertices;var faceVertexUvs=geometry.faceVertexUvs;var hasFaceVertexUv=faceVertexUvs[0]&&faceVertexUvs[0].length>0;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var i=0;i<morphTargetsLength;i++){morphTargetsPosition[i]=[]}this.morphTargets.position=morphTargetsPosition}var morphNormals=geometry.morphNormals;var morphNormalsLength=morphNormals.length;var morphTargetsNormal;if(morphNormalsLength>0){morphTargetsNormal=[];for(var i=0;i<morphNormalsLength;i++){morphTargetsNormal[i]=[]}this.morphTargets.normal=morphTargetsNormal}var skinIndices=geometry.skinIndices;var skinWeights=geometry.skinWeights;var hasSkinIndices=skinIndices.length===vertices.length;var hasSkinWeights=skinWeights.length===vertices.length;for(var i=0;i<faces.length;i++){var face=faces[i];this.vertices.push(vertices[face.a],vertices[face.b],vertices[face.c]);var vertexNormals=face.vertexNormals;if(vertexNormals.length===3){this.normals.push(vertexNormals[0],vertexNormals[1],vertexNormals[2])}else{var normal=face.normal;this.normals.push(normal,normal,normal)}var vertexColors=face.vertexColors;if(vertexColors.length===3){this.colors.push(vertexColors[0],vertexColors[1],vertexColors[2])}else{var color=face.color;this.colors.push(color,color,color)}if(hasFaceVertexUv===true){var vertexUvs=faceVertexUvs[0][i];if(vertexUvs!==undefined){this.uvs.push(vertexUvs[0],vertexUvs[1],vertexUvs[2])}else{console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",i);this.uvs.push(new Vector2,new Vector2,new Vector2)}}if(hasFaceVertexUv2===true){var vertexUvs=faceVertexUvs[1][i];if(vertexUvs!==undefined){this.uvs2.push(vertexUvs[0],vertexUvs[1],vertexUvs[2])}else{console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",i);this.uvs2.push(new Vector2,new Vector2,new Vector2)}}for(var j=0;j<morphTargetsLength;j++){var morphTarget=morphTargets[j].vertices;morphTargetsPosition[j].push(morphTarget[face.a],morphTarget[face.b],morphTarget[face.c])}for(var j=0;j<morphNormalsLength;j++){var morphNormal=morphNormals[j].vertexNormals[i];morphTargetsNormal[j].push(morphNormal.a,morphNormal.b,morphNormal.c)}if(hasSkinIndices){this.skinIndices.push(skinIndices[face.a],skinIndices[face.b],skinIndices[face.c])}if(hasSkinWeights){this.skinWeights.push(skinWeights[face.a],skinWeights[face.b],skinWeights[face.c])}}this.computeGroups(geometry);this.verticesNeedUpdate=geometry.verticesNeedUpdate;this.normalsNeedUpdate=geometry.normalsNeedUpdate;this.colorsNeedUpdate=geometry.colorsNeedUpdate;this.uvsNeedUpdate=geometry.uvsNeedUpdate;this.groupsNeedUpdate=geometry.groupsNeedUpdate;return this}});function arrayMax(array){if(array.length===0)return-Infinity;var max=array[0];for(var i=1,l=array.length;i<l;++i){if(array[i]>max)max=array[i]}return max}function BufferGeometry(){Object.defineProperty(this,"id",{value:GeometryIdCount()});this.uuid=_Math.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.drawRange={start:0,count:Infinity}}BufferGeometry.MaxIndex=65535;Object.assign(BufferGeometry.prototype,EventDispatcher.prototype,{isBufferGeometry:true,getIndex:function(){return this.index},setIndex:function(index){if(Array.isArray(index)){this.index=new(arrayMax(index)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(index,1)}else{this.index=index}},addAttribute:function(name,attribute){if(!(attribute&&attribute.isBufferAttribute)&&!(attribute&&attribute.isInterleavedBufferAttribute)){console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).");this.addAttribute(name,new BufferAttribute(arguments[1],arguments[2]));return}if(name==="index"){console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.");this.setIndex(attribute);return}this.attributes[name]=attribute;return this},getAttribute:function(name){return this.attributes[name]},removeAttribute:function(name){delete this.attributes[name];return this},addGroup:function(start,count,materialIndex){this.groups.push({start:start,count:count,materialIndex:materialIndex!==undefined?materialIndex:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(start,count){this.drawRange.start=start;this.drawRange.count=count},applyMatrix:function(matrix){var position=this.attributes.position;if(position!==undefined){matrix.applyToBufferAttribute(position);position.needsUpdate=true}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=(new Matrix3).getNormalMatrix(matrix);normalMatrix.applyToBufferAttribute(normal);normal.needsUpdate=true}if(this.boundingBox!==null){this.computeBoundingBox()}if(this.boundingSphere!==null){this.computeBoundingSphere()}return this},rotateX:function(){var m1=new Matrix4;return function rotateX(angle){m1.makeRotationX(angle);this.applyMatrix(m1);return this}}(),rotateY:function(){var m1=new Matrix4;return function rotateY(angle){m1.makeRotationY(angle);this.applyMatrix(m1);return this}}(),rotateZ:function(){var m1=new Matrix4;return function rotateZ(angle){m1.makeRotationZ(angle);this.applyMatrix(m1);return this}}(),translate:function(){var m1=new Matrix4;return function translate(x,y,z){m1.makeTranslation(x,y,z);this.applyMatrix(m1);return this}}(),scale:function(){var m1=new Matrix4;return function scale(x,y,z){m1.makeScale(x,y,z);this.applyMatrix(m1);return this}}(),lookAt:function(){var obj=new Object3D;return function lookAt(vector){obj.lookAt(vector);obj.updateMatrix();this.applyMatrix(obj.matrix)}}(),center:function(){this.computeBoundingBox();var offset=this.boundingBox.getCenter().negate();this.translate(offset.x,offset.y,offset.z);return offset},setFromObject:function(object){var geometry=object.geometry;if(object.isPoints||object.isLine){var positions=new Float32BufferAttribute(geometry.vertices.length*3,3);var colors=new Float32BufferAttribute(geometry.colors.length*3,3);this.addAttribute("position",positions.copyVector3sArray(geometry.vertices));this.addAttribute("color",colors.copyColorsArray(geometry.colors));if(geometry.lineDistances&&geometry.lineDistances.length===geometry.vertices.length){var lineDistances=new Float32BufferAttribute(geometry.lineDistances.length,1);this.addAttribute("lineDistance",lineDistances.copyArray(geometry.lineDistances))}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone()}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone()}}else if(object.isMesh){if(geometry&&geometry.isGeometry){this.fromGeometry(geometry)}}return this},updateFromObject:function(object){var geometry=object.geometry;if(object.isMesh){var direct=geometry.__directGeometry;if(geometry.elementsNeedUpdate===true){direct=undefined;geometry.elementsNeedUpdate=false}if(direct===undefined){return this.fromGeometry(geometry)}direct.verticesNeedUpdate=geometry.verticesNeedUpdate;direct.normalsNeedUpdate=geometry.normalsNeedUpdate;direct.colorsNeedUpdate=geometry.colorsNeedUpdate;direct.uvsNeedUpdate=geometry.uvsNeedUpdate;direct.groupsNeedUpdate=geometry.groupsNeedUpdate;geometry.verticesNeedUpdate=false;geometry.normalsNeedUpdate=false;geometry.colorsNeedUpdate=false;geometry.uvsNeedUpdate=false;geometry.groupsNeedUpdate=false;geometry=direct}var attribute;if(geometry.verticesNeedUpdate===true){attribute=this.attributes.position;if(attribute!==undefined){attribute.copyVector3sArray(geometry.vertices);attribute.needsUpdate=true}geometry.verticesNeedUpdate=false}if(geometry.normalsNeedUpdate===true){attribute=this.attributes.normal;if(attribute!==undefined){attribute.copyVector3sArray(geometry.normals);attribute.needsUpdate=true}geometry.normalsNeedUpdate=false}if(geometry.colorsNeedUpdate===true){attribute=this.attributes.color;if(attribute!==undefined){attribute.copyColorsArray(geometry.colors);attribute.needsUpdate=true}geometry.colorsNeedUpdate=false}if(geometry.uvsNeedUpdate){attribute=this.attributes.uv;if(attribute!==undefined){attribute.copyVector2sArray(geometry.uvs);attribute.needsUpdate=true}geometry.uvsNeedUpdate=false}if(geometry.lineDistancesNeedUpdate){attribute=this.attributes.lineDistance;if(attribute!==undefined){attribute.copyArray(geometry.lineDistances);attribute.needsUpdate=true}geometry.lineDistancesNeedUpdate=false}if(geometry.groupsNeedUpdate){geometry.computeGroups(object.geometry);this.groups=geometry.groups;geometry.groupsNeedUpdate=false}return this},fromGeometry:function(geometry){geometry.__directGeometry=(new DirectGeometry).fromGeometry(geometry);return this.fromDirectGeometry(geometry.__directGeometry)},fromDirectGeometry:function(geometry){var positions=new Float32Array(geometry.vertices.length*3);this.addAttribute("position",new BufferAttribute(positions,3).copyVector3sArray(geometry.vertices));if(geometry.normals.length>0){var normals=new Float32Array(geometry.normals.length*3);this.addAttribute("normal",new BufferAttribute(normals,3).copyVector3sArray(geometry.normals))}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.addAttribute("color",new BufferAttribute(colors,3).copyColorsArray(geometry.colors))}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.addAttribute("uv",new BufferAttribute(uvs,2).copyVector2sArray(geometry.uvs))}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.addAttribute("uv2",new BufferAttribute(uvs2,2).copyVector2sArray(geometry.uvs2))}if(geometry.indices.length>0){var TypeArray=arrayMax(geometry.indices)>65535?Uint32Array:Uint16Array;var indices=new TypeArray(geometry.indices.length*3);this.setIndex(new BufferAttribute(indices,1).copyIndicesArray(geometry.indices))}this.groups=geometry.groups;for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var i=0,l=morphTargets.length;i<l;i++){var morphTarget=morphTargets[i];var attribute=new Float32BufferAttribute(morphTarget.length*3,3);array.push(attribute.copyVector3sArray(morphTarget))}this.morphAttributes[name]=array}if(geometry.skinIndices.length>0){var skinIndices=new Float32BufferAttribute(geometry.skinIndices.length*4,4);this.addAttribute("skinIndex",skinIndices.copyVector4sArray(geometry.skinIndices))}if(geometry.skinWeights.length>0){var skinWeights=new Float32BufferAttribute(geometry.skinWeights.length*4,4);this.addAttribute("skinWeight",skinWeights.copyVector4sArray(geometry.skinWeights))}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone()}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone()}return this},computeBoundingBox:function(){if(this.boundingBox===null){this.boundingBox=new Box3}var position=this.attributes.position;if(position!==undefined){this.boundingBox.setFromBufferAttribute(position)}else{this.boundingBox.makeEmpty()}if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z)){console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}},computeBoundingSphere:function(){var box=new Box3;var vector=new Vector3;return function computeBoundingSphere(){if(this.boundingSphere===null){this.boundingSphere=new Sphere}var position=this.attributes.position;if(position){var center=this.boundingSphere.center;box.setFromBufferAttribute(position);box.getCenter(center);var maxRadiusSq=0;for(var i=0,il=position.count;i<il;i++){vector.x=position.getX(i);vector.y=position.getY(i);vector.z=position.getZ(i);maxRadiusSq=Math.max(maxRadiusSq,center.distanceToSquared(vector))}this.boundingSphere.radius=Math.sqrt(maxRadiusSq);if(isNaN(this.boundingSphere.radius)){console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var index=this.index;var attributes=this.attributes;var groups=this.groups;if(attributes.position){var positions=attributes.position.array;if(attributes.normal===undefined){this.addAttribute("normal",new BufferAttribute(new Float32Array(positions.length),3))}else{var array=attributes.normal.array;for(var i=0,il=array.length;i<il;i++){array[i]=0}}var normals=attributes.normal.array;var vA,vB,vC;var pA=new Vector3,pB=new Vector3,pC=new Vector3;var cb=new Vector3,ab=new Vector3;if(index){var indices=index.array;if(groups.length===0){this.addGroup(0,indices.length)}for(var j=0,jl=groups.length;j<jl;++j){var group=groups[j];var start=group.start;var count=group.count;for(var i=start,il=start+count;i<il;i+=3){vA=indices[i+0]*3;vB=indices[i+1]*3;vC=indices[i+2]*3;pA.fromArray(positions,vA);pB.fromArray(positions,vB);pC.fromArray(positions,vC);cb.subVectors(pC,pB);ab.subVectors(pA,pB);cb.cross(ab);normals[vA]+=cb.x;normals[vA+1]+=cb.y;normals[vA+2]+=cb.z;normals[vB]+=cb.x;normals[vB+1]+=cb.y;normals[vB+2]+=cb.z;normals[vC]+=cb.x;normals[vC+1]+=cb.y;normals[vC+2]+=cb.z}}}else{for(var i=0,il=positions.length;i<il;i+=9){pA.fromArray(positions,i);pB.fromArray(positions,i+3);pC.fromArray(positions,i+6);cb.subVectors(pC,pB);ab.subVectors(pA,pB);cb.cross(ab);normals[i]=cb.x;normals[i+1]=cb.y;normals[i+2]=cb.z;normals[i+3]=cb.x;normals[i+4]=cb.y;normals[i+5]=cb.z;normals[i+6]=cb.x;normals[i+7]=cb.y;normals[i+8]=cb.z}}this.normalizeNormals();attributes.normal.needsUpdate=true}},merge:function(geometry,offset){if(!(geometry&&geometry.isBufferGeometry)){console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",geometry);return}if(offset===undefined)offset=0;var attributes=this.attributes;for(var key in attributes){if(geometry.attributes[key]===undefined)continue;var attribute1=attributes[key];var attributeArray1=attribute1.array;var attribute2=geometry.attributes[key];var attributeArray2=attribute2.array;var attributeSize=attribute2.itemSize;for(var i=0,j=attributeSize*offset;i<attributeArray2.length;i++,j++){attributeArray1[j]=attributeArray2[i]}}return this},normalizeNormals:function(){var vector=new Vector3;return function normalizeNormals(){var normals=this.attributes.normal;for(var i=0,il=normals.count;i<il;i++){vector.x=normals.getX(i);vector.y=normals.getY(i);vector.z=normals.getZ(i);vector.normalize();normals.setXYZ(i,vector.x,vector.y,vector.z)}}}(),toNonIndexed:function(){if(this.index===null){console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.");return this}var geometry2=new BufferGeometry;var indices=this.index.array;var attributes=this.attributes;for(var name in attributes){var attribute=attributes[name];var array=attribute.array;var itemSize=attribute.itemSize;var array2=new array.constructor(indices.length*itemSize);var index=0,index2=0;for(var i=0,l=indices.length;i<l;i++){index=indices[i]*itemSize;for(var j=0;j<itemSize;j++){array2[index2++]=array[index++]}}geometry2.addAttribute(name,new BufferAttribute(array2,itemSize))}return geometry2},toJSON:function(){var data={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};data.uuid=this.uuid;data.type=this.type;if(this.name!=="")data.name=this.name;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key]}return data}data.data={attributes:{}};var index=this.index;if(index!==null){var array=Array.prototype.slice.call(index.array);data.data.index={type:index.array.constructor.name,array:array}}var attributes=this.attributes;for(var key in attributes){var attribute=attributes[key];var array=Array.prototype.slice.call(attribute.array);data.data.attributes[key]={itemSize:attribute.itemSize,type:attribute.array.constructor.name,array:array,normalized:attribute.normalized}}var groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups))}var boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius}}return data},clone:function(){return(new BufferGeometry).copy(this)},copy:function(source){var name,i,l;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.name=source.name;var index=source.index;if(index!==null){this.setIndex(index.clone())}var attributes=source.attributes;for(name in attributes){var attribute=attributes[name];this.addAttribute(name,attribute.clone())}var morphAttributes=source.morphAttributes;for(name in morphAttributes){var array=[];var morphAttribute=morphAttributes[name];for(i=0,l=morphAttribute.length;i<l;i++){array.push(morphAttribute[i].clone())}this.morphAttributes[name]=array}var groups=source.groups;for(i=0,l=groups.length;i<l;i++){var group=groups[i];this.addGroup(group.start,group.count,group.materialIndex)}var boundingBox=source.boundingBox;if(boundingBox!==null){this.boundingBox=boundingBox.clone()}var boundingSphere=source.boundingSphere;if(boundingSphere!==null){this.boundingSphere=boundingSphere.clone()}this.drawRange.start=source.drawRange.start;this.drawRange.count=source.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});function BoxGeometry(width,height,depth,widthSegments,heightSegments,depthSegments){Geometry.call(this);this.type="BoxGeometry";this.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};this.fromBufferGeometry(new BoxBufferGeometry(width,height,depth,widthSegments,heightSegments,depthSegments));this.mergeVertices()}BoxGeometry.prototype=Object.create(Geometry.prototype);BoxGeometry.prototype.constructor=BoxGeometry;function BoxBufferGeometry(width,height,depth,widthSegments,heightSegments,depthSegments){BufferGeometry.call(this);this.type="BoxBufferGeometry";this.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};var scope=this;widthSegments=Math.floor(widthSegments)||1;heightSegments=Math.floor(heightSegments)||1;depthSegments=Math.floor(depthSegments)||1;var indices=[];var vertices=[];var normals=[];var uvs=[];var numberOfVertices=0;var groupStart=0;buildPlane("z","y","x",-1,-1,depth,height,width,depthSegments,heightSegments,0);buildPlane("z","y","x",1,-1,depth,height,-width,depthSegments,heightSegments,1);buildPlane("x","z","y",1,1,width,depth,height,widthSegments,depthSegments,2);buildPlane("x","z","y",1,-1,width,depth,-height,widthSegments,depthSegments,3);buildPlane("x","y","z",1,-1,width,height,depth,widthSegments,heightSegments,4);buildPlane("x","y","z",-1,-1,width,height,-depth,widthSegments,heightSegments,5);this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));function buildPlane(u,v,w,udir,vdir,width,height,depth,gridX,gridY,materialIndex){var segmentWidth=width/gridX;var segmentHeight=height/gridY;var widthHalf=width/2;var heightHalf=height/2;var depthHalf=depth/2;var gridX1=gridX+1;var gridY1=gridY+1;var vertexCounter=0;var groupCount=0;var ix,iy;var vector=new Vector3;for(iy=0;iy<gridY1;iy++){var y=iy*segmentHeight-heightHalf;for(ix=0;ix<gridX1;ix++){var x=ix*segmentWidth-widthHalf;vector[u]=x*udir;vector[v]=y*vdir;vector[w]=depthHalf;vertices.push(vector.x,vector.y,vector.z);vector[u]=0;vector[v]=0;vector[w]=depth>0?1:-1;normals.push(vector.x,vector.y,vector.z);uvs.push(ix/gridX);uvs.push(1-iy/gridY);vertexCounter+=1}}for(iy=0;iy<gridY;iy++){for(ix=0;ix<gridX;ix++){var a=numberOfVertices+ix+gridX1*iy;var b=numberOfVertices+ix+gridX1*(iy+1);var c=numberOfVertices+(ix+1)+gridX1*(iy+1);var d=numberOfVertices+(ix+1)+gridX1*iy;indices.push(a,b,d);indices.push(b,c,d);groupCount+=6}}scope.addGroup(groupStart,groupCount,materialIndex);groupStart+=groupCount;numberOfVertices+=vertexCounter}}BoxBufferGeometry.prototype=Object.create(BufferGeometry.prototype);BoxBufferGeometry.prototype.constructor=BoxBufferGeometry;function PlaneGeometry(width,height,widthSegments,heightSegments){Geometry.call(this);this.type="PlaneGeometry";this.parameters={width:width,height:height,widthSegments:widthSegments,heightSegments:heightSegments};this.fromBufferGeometry(new PlaneBufferGeometry(width,height,widthSegments,heightSegments));this.mergeVertices()}PlaneGeometry.prototype=Object.create(Geometry.prototype);PlaneGeometry.prototype.constructor=PlaneGeometry;function PlaneBufferGeometry(width,height,widthSegments,heightSegments){BufferGeometry.call(this);this.type="PlaneBufferGeometry";this.parameters={width:width,height:height,widthSegments:widthSegments,heightSegments:heightSegments};var width_half=width/2;var height_half=height/2;var gridX=Math.floor(widthSegments)||1;var gridY=Math.floor(heightSegments)||1;var gridX1=gridX+1;var gridY1=gridY+1;var segment_width=width/gridX;var segment_height=height/gridY;var ix,iy;var indices=[];var vertices=[];var normals=[];var uvs=[];for(iy=0;iy<gridY1;iy++){var y=iy*segment_height-height_half;for(ix=0;ix<gridX1;ix++){var x=ix*segment_width-width_half;vertices.push(x,-y,0);normals.push(0,0,1);uvs.push(ix/gridX);uvs.push(1-iy/gridY)}}for(iy=0;iy<gridY;iy++){for(ix=0;ix<gridX;ix++){var a=ix+gridX1*iy;var b=ix+gridX1*(iy+1);var c=ix+1+gridX1*(iy+1);var d=ix+1+gridX1*iy;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}PlaneBufferGeometry.prototype=Object.create(BufferGeometry.prototype);PlaneBufferGeometry.prototype.constructor=PlaneBufferGeometry;function MeshBasicMaterial(parameters){Material.call(this);this.type="MeshBasicMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.skinning=false;this.morphTargets=false;this.lights=false;this.setValues(parameters)}MeshBasicMaterial.prototype=Object.create(Material.prototype)

MeshBasicMaterial.prototype.constructor=MeshBasicMaterial;MeshBasicMaterial.prototype.isMeshBasicMaterial=true;MeshBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;return this};function Ray(origin,direction){this.origin=origin!==undefined?origin
new Vector3;this.direction=direction!==undefined?direction:new Vector3}Object.assign(Ray.prototype,{set:function(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this},at:function(t,optionalTarget){var result=optionalTarget||new Vector3;return result.copy(this.direction).multiplyScalar(t).add(this.origin)},lookAt:function(v){this.direction.copy(v).sub(this.origin).normalize();return this},recast:function(){var v1=new Vector3;return function recast(t){this.origin.copy(this.at(t,v1));return this}}(),closestPointToPoint:function(point,optionalTarget){var result=optionalTarget||new Vector3;result.subVectors(point,this.origin);var directionDistance=result.dot(this.direction);if(directionDistance<0){return result.copy(this.origin)}return result.copy(this.direction).multiplyScalar(directionDistance).add(this.origin)},distanceToPoint:function(point){return Math.sqrt(this.distanceSqToPoint(point))},distanceSqToPoint:function(){var v1=new Vector3;return function distanceSqToPoint(point){var directionDistance=v1.subVectors(point,this.origin).dot(this.direction);if(directionDistance<0){return this.origin.distanceToSquared(point)}v1.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return v1.distanceToSquared(point)}}(),distanceSqToSegment:function(){var segCenter=new Vector3;var segDir=new Vector3;var diff=new Vector3;return function distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){segCenter.copy(v0).add(v1).multiplyScalar(.5);segDir.copy(v1).sub(v0).normalize();diff.copy(this.origin).sub(segCenter);var segExtent=v0.distanceTo(v1)*.5;var a01=-this.direction.dot(segDir);var b0=diff.dot(this.direction);var b1=-diff.dot(segDir);var c=diff.lengthSq();var det=Math.abs(1-a01*a01);var s0,s1,sqrDist,extDet;if(det>0){s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){var invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c}else{s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{if(s1<=-extDet){s0=Math.max(0,-(-a01*segExtent+b0));s1=s0>0?-segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}else if(s1<=extDet){s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c}else{s0=Math.max(0,-(a01*segExtent+b0));s1=s0>0?segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}}}else{s1=a01>0?-segExtent:segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}if(optionalPointOnRay){optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin)}if(optionalPointOnSegment){optionalPointOnSegment.copy(segDir).multiplyScalar(s1).add(segCenter)}return sqrDist}}(),intersectSphere:function(){var v1=new Vector3;return function intersectSphere(sphere,optionalTarget){v1.subVectors(sphere.center,this.origin);var tca=v1.dot(this.direction);var d2=v1.dot(v1)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);var t0=tca-thc;var t1=tca+thc;if(t0<0&&t1<0)return null;if(t0<0)return this.at(t1,optionalTarget);return this.at(t0,optionalTarget)}}(),intersectsSphere:function(sphere){return this.distanceToPoint(sphere.center)<=sphere.radius},distanceToPlane:function(plane){var denominator=plane.normal.dot(this.direction);if(denominator===0){if(plane.distanceToPoint(this.origin)===0){return 0}return null}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;return t>=0?t:null},intersectPlane:function(plane,optionalTarget){var t=this.distanceToPlane(plane);if(t===null){return null}return this.at(t,optionalTarget)},intersectsPlane:function(plane){var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true}var denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true}return false},intersectBox:function(box,optionalTarget){var tmin,tmax,tymin,tymax,tzmin,tzmax;var invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;var origin=this.origin;if(invdirx>=0){tmin=(box.min.x-origin.x)*invdirx;tmax=(box.max.x-origin.x)*invdirx}else{tmin=(box.max.x-origin.x)*invdirx;tmax=(box.min.x-origin.x)*invdirx}if(invdiry>=0){tymin=(box.min.y-origin.y)*invdiry;tymax=(box.max.y-origin.y)*invdiry}else{tymin=(box.max.y-origin.y)*invdiry;tymax=(box.min.y-origin.y)*invdiry}if(tmin>tymax||tymin>tmax)return null;if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax<tmax||tmax!==tmax)tmax=tymax;if(invdirz>=0){tzmin=(box.min.z-origin.z)*invdirz;tzmax=(box.max.z-origin.z)*invdirz}else{tzmin=(box.max.z-origin.z)*invdirz;tzmax=(box.min.z-origin.z)*invdirz}if(tmin>tzmax||tzmin>tmax)return null;if(tzmin>tmin||tmin!==tmin)tmin=tzmin;if(tzmax<tmax||tmax!==tmax)tmax=tzmax;if(tmax<0)return null;return this.at(tmin>=0?tmin:tmax,optionalTarget)},intersectsBox:function(){var v=new Vector3;return function intersectsBox(box){return this.intersectBox(box,v)!==null}}(),intersectTriangle:function(){var diff=new Vector3;var edge1=new Vector3;var edge2=new Vector3;var normal=new Vector3;return function intersectTriangle(a,b,c,backfaceCulling,optionalTarget){edge1.subVectors(b,a);edge2.subVectors(c,a);normal.crossVectors(edge1,edge2);var DdN=this.direction.dot(normal);var sign;if(DdN>0){if(backfaceCulling)return null;sign=1}else if(DdN<0){sign=-1;DdN=-DdN}else{return null}diff.subVectors(this.origin,a);var DdQxE2=sign*this.direction.dot(edge2.crossVectors(diff,edge2));if(DdQxE2<0){return null}var DdE1xQ=sign*this.direction.dot(edge1.cross(diff));if(DdE1xQ<0){return null}if(DdQxE2+DdE1xQ>DdN){return null}var QdN=-sign*diff.dot(normal);if(QdN<0){return null}return this.at(QdN/DdN,optionalTarget)}}(),applyMatrix4:function(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this},equals:function(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction)}});function Line3(start,end){this.start=start!==undefined?start:new Vector3;this.end=end!==undefined?end:new Vector3}Object.assign(Line3.prototype,{set:function(start,end){this.start.copy(start);this.end.copy(end);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(line){this.start.copy(line.start);this.end.copy(line.end);return this},getCenter:function(optionalTarget){var result=optionalTarget||new Vector3;return result.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(optionalTarget){var result=optionalTarget||new Vector3;return result.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(t,optionalTarget){var result=optionalTarget||new Vector3;return this.delta(result).multiplyScalar(t).add(this.start)},closestPointToPointParameter:function(){var startP=new Vector3;var startEnd=new Vector3;return function closestPointToPointParameter(point,clampToLine){startP.subVectors(point,this.start);startEnd.subVectors(this.end,this.start);var startEnd2=startEnd.dot(startEnd);var startEnd_startP=startEnd.dot(startP);var t=startEnd_startP/startEnd2;if(clampToLine){t=_Math.clamp(t,0,1)}return t}}(),closestPointToPoint:function(point,clampToLine,optionalTarget){var t=this.closestPointToPointParameter(point,clampToLine);var result=optionalTarget||new Vector3;return this.delta(result).multiplyScalar(t).add(this.start)},applyMatrix4:function(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this},equals:function(line){return line.start.equals(this.start)&&line.end.equals(this.end)}});function Triangle(a,b,c){this.a=a!==undefined?a:new Vector3;this.b=b!==undefined?b:new Vector3;this.c=c!==undefined?c:new Vector3}Object.assign(Triangle,{normal:function(){var v0=new Vector3;return function normal(a,b,c,optionalTarget){var result=optionalTarget||new Vector3;result.subVectors(c,b);v0.subVectors(a,b);result.cross(v0);var resultLengthSq=result.lengthSq();if(resultLengthSq>0){return result.multiplyScalar(1/Math.sqrt(resultLengthSq))}return result.set(0,0,0)}}(),barycoordFromPoint:function(){var v0=new Vector3;var v1=new Vector3;var v2=new Vector3;return function barycoordFromPoint(point,a,b,c,optionalTarget){v0.subVectors(c,a);v1.subVectors(b,a);v2.subVectors(point,a);var dot00=v0.dot(v0);var dot01=v0.dot(v1);var dot02=v0.dot(v2);var dot11=v1.dot(v1);var dot12=v1.dot(v2);var denom=dot00*dot11-dot01*dot01;var result=optionalTarget||new Vector3;if(denom===0){return result.set(-2,-1,-1)}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;return result.set(1-u-v,v,u)}}(),containsPoint:function(){var v1=new Vector3;return function containsPoint(point,a,b,c){var result=Triangle.barycoordFromPoint(point,a,b,c,v1);return result.x>=0&&result.y>=0&&result.x+result.y<=1}}()});Object.assign(Triangle.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this},area:function(){var v0=new Vector3;var v1=new Vector3;return function area(){v0.subVectors(this.c,this.b);v1.subVectors(this.a,this.b);return v0.cross(v1).length()*.5}}(),midpoint:function(optionalTarget){var result=optionalTarget||new Vector3;return result.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(optionalTarget){return Triangle.normal(this.a,this.b,this.c,optionalTarget)},plane:function(optionalTarget){var result=optionalTarget||new Plane;return result.setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(point,optionalTarget){return Triangle.barycoordFromPoint(point,this.a,this.b,this.c,optionalTarget)},containsPoint:function(point){return Triangle.containsPoint(point,this.a,this.b,this.c)},closestPointToPoint:function(){var plane=new Plane;var edgeList=[new Line3,new Line3,new Line3];var projectedPoint=new Vector3;var closestPoint=new Vector3;return function closestPointToPoint(point,optionalTarget){var result=optionalTarget||new Vector3;var minDistance=Infinity;plane.setFromCoplanarPoints(this.a,this.b,this.c);plane.projectPoint(point,projectedPoint);if(this.containsPoint(projectedPoint)===true){result.copy(projectedPoint)}else{edgeList[0].set(this.a,this.b);edgeList[1].set(this.b,this.c);edgeList[2].set(this.c,this.a);for(var i=0;i<edgeList.length;i++){edgeList[i].closestPointToPoint(projectedPoint,true,closestPoint);var distance=projectedPoint.distanceToSquared(closestPoint);if(distance<minDistance){minDistance=distance;result.copy(closestPoint)}}}return result}}(),equals:function(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c)}});function Mesh(geometry,material){Object3D.call(this);this.type="Mesh";this.geometry=geometry!==undefined?geometry:new BufferGeometry;this.material=material!==undefined?material:new MeshBasicMaterial({color:Math.random()*16777215});this.drawMode=TrianglesDrawMode;this.updateMorphTargets()}Mesh.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Mesh,isMesh:true,setDrawMode:function(value){this.drawMode=value},copy:function(source){Object3D.prototype.copy.call(this,source);this.drawMode=source.drawMode;return this},updateMorphTargets:function(){var geometry=this.geometry;var m,ml,name;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphAttribute.length;m<ml;m++){name=morphAttribute[m].name||String(m);this.morphTargetInfluences.push(0);this.morphTargetDictionary[name]=m}}}}else{var morphTargets=geometry.morphTargets;if(morphTargets!==undefined&&morphTargets.length>0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(m=0,ml=morphTargets.length;m<ml;m++){name=morphTargets[m].name||String(m);this.morphTargetInfluences.push(0);this.morphTargetDictionary[name]=m}}}},raycast:function(){var inverseMatrix=new Matrix4;var ray=new Ray;var sphere=new Sphere;var vA=new Vector3;var vB=new Vector3;var vC=new Vector3;var tempA=new Vector3;var tempB=new Vector3;var tempC=new Vector3;var uvA=new Vector2;var uvB=new Vector2;var uvC=new Vector2;var barycoord=new Vector3;var intersectionPoint=new Vector3;var intersectionPointWorld=new Vector3;function uvIntersection(point,p1,p2,p3,uv1,uv2,uv3){Triangle.barycoordFromPoint(point,p1,p2,p3,barycoord);uv1.multiplyScalar(barycoord.x);uv2.multiplyScalar(barycoord.y);uv3.multiplyScalar(barycoord.z);uv1.add(uv2).add(uv3);return uv1.clone()}function checkIntersection(object,material,raycaster,ray,pA,pB,pC,point){var intersect;if(material.side===BackSide){intersect=ray.intersectTriangle(pC,pB,pA,true,point)}else{intersect=ray.intersectTriangle(pA,pB,pC,material.side!==DoubleSide,point)}if(intersect===null)return null;intersectionPointWorld.copy(point);intersectionPointWorld.applyMatrix4(object.matrixWorld);var distance=raycaster.ray.origin.distanceTo(intersectionPointWorld);if(distance<raycaster.near||distance>raycaster.far)return null;return{distance:distance,point:intersectionPointWorld.clone(),object:object}}function checkBufferGeometryIntersection(object,raycaster,ray,position,uv,a,b,c){vA.fromBufferAttribute(position,a);vB.fromBufferAttribute(position,b);vC.fromBufferAttribute(position,c);var intersection=checkIntersection(object,object.material,raycaster,ray,vA,vB,vC,intersectionPoint);if(intersection){if(uv){uvA.fromBufferAttribute(uv,a);uvB.fromBufferAttribute(uv,b);uvC.fromBufferAttribute(uv,c);intersection.uv=uvIntersection(intersectionPoint,vA,vB,vC,uvA,uvB,uvC)}intersection.face=new Face3(a,b,c,Triangle.normal(vA,vB,vC));intersection.faceIndex=a}return intersection}return function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var matrixWorld=this.matrixWorld;if(material===undefined)return;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();sphere.copy(geometry.boundingSphere);sphere.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(sphere)===false)return;inverseMatrix.getInverse(matrixWorld);ray.copy(raycaster.ray).applyMatrix4(inverseMatrix);if(geometry.boundingBox!==null){if(ray.intersectsBox(geometry.boundingBox)===false)return}var intersection;if(geometry.isBufferGeometry){var a,b,c;var index=geometry.index;var position=geometry.attributes.position;var uv=geometry.attributes.uv;var i,l;if(index!==null){for(i=0,l=index.count;i<l;i+=3){a=index.getX(i);b=index.getX(i+1);c=index.getX(i+2);intersection=checkBufferGeometryIntersection(this,raycaster,ray,position,uv,a,b,c);if(intersection){intersection.faceIndex=Math.floor(i/3);intersects.push(intersection)}}}else{for(i=0,l=position.count;i<l;i+=3){a=i;b=i+1;c=i+2;intersection=checkBufferGeometryIntersection(this,raycaster,ray,position,uv,a,b,c);if(intersection){intersection.index=a;intersects.push(intersection)}}}}else if(geometry.isGeometry){var fvA,fvB,fvC;var isMultiMaterial=Array.isArray(material);var vertices=geometry.vertices;var faces=geometry.faces;var uvs;var faceVertexUvs=geometry.faceVertexUvs[0];if(faceVertexUvs.length>0)uvs=faceVertexUvs;for(var f=0,fl=faces.length;f<fl;f++){var face=faces[f];var faceMaterial=isMultiMaterial?material[face.materialIndex]:material;if(faceMaterial===undefined)continue;fvA=vertices[face.a];fvB=vertices[face.b];fvC=vertices[face.c];if(faceMaterial.morphTargets===true){var morphTargets=geometry.morphTargets;var morphInfluences=this.morphTargetInfluences;vA.set(0,0,0);vB.set(0,0,0);vC.set(0,0,0);for(var t=0,tl=morphTargets.length;t<tl;t++){var influence=morphInfluences[t];if(influence===0)continue;var targets=morphTargets[t].vertices;vA.addScaledVector(tempA.subVectors(targets[face.a],fvA),influence);vB.addScaledVector(tempB.subVectors(targets[face.b],fvB),influence);vC.addScaledVector(tempC.subVectors(targets[face.c],fvC),influence)}vA.add(fvA);vB.add(fvB);vC.add(fvC);fvA=vA;fvB=vB;fvC=vC}intersection=checkIntersection(this,faceMaterial,raycaster,ray,fvA,fvB,fvC,intersectionPoint);if(intersection){if(uvs&&uvs[f]){var uvs_f=uvs[f];uvA.copy(uvs_f[0]);uvB.copy(uvs_f[1]);uvC.copy(uvs_f[2]);intersection.uv=uvIntersection(intersectionPoint,fvA,fvB,fvC,uvA,uvB,uvC)}intersection.face=face;intersection.faceIndex=f;intersects.push(intersection)}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});function WebGLBackground(renderer,state,geometries,premultipliedAlpha){var clearColor=new Color(0);var clearAlpha=0;var planeCamera,planeMesh;var boxMesh;function render(renderList,scene,camera,forceClear){var background=scene.background;if(background===null){setClear(clearColor,clearAlpha)}else if(background&&background.isColor){setClear(background,1);forceClear=true}if(renderer.autoClear||forceClear){renderer.clear(renderer.autoClearColor,renderer.autoClearDepth,renderer.autoClearStencil)}if(background&&background.isCubeTexture){if(boxMesh===undefined){boxMesh=new Mesh(new BoxBufferGeometry(1,1,1),new ShaderMaterial({uniforms:ShaderLib.cube.uniforms,vertexShader:ShaderLib.cube.vertexShader,fragmentShader:ShaderLib.cube.fragmentShader,side:BackSide,depthTest:true,depthWrite:false,polygonOffset:true,fog:false}));boxMesh.geometry.removeAttribute("normal");boxMesh.geometry.removeAttribute("uv");boxMesh.onBeforeRender=function(renderer,scene,camera){var scale=camera.far;this.matrixWorld.makeScale(scale,scale,scale);this.matrixWorld.copyPosition(camera.matrixWorld);this.material.polygonOffsetUnits=scale*10};geometries.update(boxMesh.geometry)}boxMesh.material.uniforms.tCube.value=background;renderList.push(boxMesh,boxMesh.geometry,boxMesh.material,0,null)}else if(background&&background.isTexture){if(planeCamera===undefined){planeCamera=new OrthographicCamera(-1,1,1,-1,0,1);planeMesh=new Mesh(new PlaneBufferGeometry(2,2),new MeshBasicMaterial({depthTest:false,depthWrite:false,fog:false}));geometries.update(planeMesh.geometry)}planeMesh.material.map=background;renderer.renderBufferDirect(planeCamera,null,planeMesh.geometry,planeMesh.material,planeMesh,null)}}function setClear(color,alpha){state.buffers.color.setClear(color.r,color.g,color.b,alpha,premultipliedAlpha)}return{getClearColor:function(){return clearColor},setClearColor:function(color,alpha){clearColor.set(color);clearAlpha=alpha!==undefined?alpha:1;setClear(clearColor,clearAlpha)},getClearAlpha:function(){return clearAlpha},setClearAlpha:function(alpha){clearAlpha=alpha;setClear(clearColor,clearAlpha)},render:render}}function painterSortStable(a,b){if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder}else if(a.program&&b.program&&a.program!==b.program){return a.program.id-b.program.id}else if(a.material.id!==b.material.id){return a.material.id-b.material.id}else if(a.z!==b.z){return a.z-b.z}else{return a.id-b.id}}function reversePainterSortStable(a,b){if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder}if(a.z!==b.z){return b.z-a.z}else{return a.id-b.id}}function WebGLRenderList(){var renderItems=[];var renderItemsIndex=0;var opaque=[];var transparent=[];function init(){renderItemsIndex=0;opaque.length=0;transparent.length=0}function push(object,geometry,material,z,group){var renderItem=renderItems[renderItemsIndex];if(renderItem===undefined){renderItem={id:object.id,object:object,geometry:geometry,material:material,program:material.program,renderOrder:object.renderOrder,z:z,group:group};renderItems[renderItemsIndex]=renderItem}else{renderItem.id=object.id;renderItem.object=object;renderItem.geometry=geometry;renderItem.material=material;renderItem.program=material.program;renderItem.renderOrder=object.renderOrder;renderItem.z=z;renderItem.group=group}(material.transparent===true?transparent:opaque).push(renderItem);renderItemsIndex++}function sort(){if(opaque.length>1)opaque.sort(painterSortStable);if(transparent.length>1)transparent.sort(reversePainterSortStable)}return{opaque:opaque,transparent:transparent,init:init,push:push,sort:sort}}function WebGLRenderLists(){var lists={};function get(scene,camera){var hash=scene.id+","+camera.id;var list=lists[hash];if(list===undefined){list=new WebGLRenderList;lists[hash]=list}return list}function dispose(){lists={}}return{get:get,dispose:dispose}}function absNumericalSort(a,b){return Math.abs(b[1])-Math.abs(a[1])}function WebGLMorphtargets(gl){var influencesList={};var morphInfluences=new Float32Array(8);function update(object,geometry,material,program){var objectInfluences=object.morphTargetInfluences;var length=objectInfluences.length;var influences=influencesList[geometry.id];if(influences===undefined){influences=[];for(var i=0;i<length;i++){influences[i]=[i,0]}influencesList[geometry.id]=influences}var morphTargets=material.morphTargets&&geometry.morphAttributes.position;var morphNormals=material.morphNormals&&geometry.morphAttributes.normal;for(var i=0;i<length;i++){var influence=influences[i];if(influence[1]!==0){if(morphTargets)geometry.removeAttribute("morphTarget"+i);if(morphNormals)geometry.removeAttribute("morphNormal"+i)}}for(var i=0;i<length;i++){var influence=influences[i];influence[0]=i;influence[1]=objectInfluences[i]}influences.sort(absNumericalSort);for(var i=0;i<8;i++){var influence=influences[i];if(influence){var index=influence[0];var value=influence[1];if(value){if(morphTargets)geometry.addAttribute("morphTarget"+i,morphTargets[index]);if(morphNormals)geometry.addAttribute("morphNormal"+i,morphNormals[index]);morphInfluences[i]=value;continue}}morphInfluences[i]=0}program.getUniforms().setValue(gl,"morphTargetInfluences",morphInfluences)}return{update:update}}function WebGLIndexedBufferRenderer(gl,extensions,infoRender){var mode;function setMode(value){mode=value}var type,bytesPerElement;function setIndex(value){type=value.type;bytesPerElement=value.bytesPerElement}function render(start,count){gl.drawElements(mode,count,type,start*bytesPerElement);infoRender.calls++;infoRender.vertices+=count;if(mode===gl.TRIANGLES)infoRender.faces+=count/3;else if(mode===gl.POINTS)infoRender.points+=count}function renderInstances(geometry,start,count){var extension=extensions.get("ANGLE_instanced_arrays");if(extension===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}extension.drawElementsInstancedANGLE(mode,count,type,start*bytesPerElement,geometry.maxInstancedCount);infoRender.calls++;infoRender.vertices+=count*geometry.maxInstancedCount;if(mode===gl.TRIANGLES)infoRender.faces+=geometry.maxInstancedCount*count/3;else if(mode===gl.POINTS)infoRender.points+=geometry.maxInstancedCount*count}this.setMode=setMode;this.setIndex=setIndex;this.render=render;this.renderInstances=renderInstances}function WebGLBufferRenderer(gl,extensions,infoRender){var mode;function setMode(value){mode=value}function render(start,count){gl.drawArrays(mode,start,count);infoRender.calls++;infoRender.vertices+=count;if(mode===gl.TRIANGLES)infoRender.faces+=count/3;else if(mode===gl.POINTS)infoRender.points+=count}function renderInstances(geometry,start,count){var extension=extensions.get("ANGLE_instanced_arrays");if(extension===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}var position=geometry.attributes.position;if(position.isInterleavedBufferAttribute){count=position.data.count;extension.drawArraysInstancedANGLE(mode,0,count,geometry.maxInstancedCount)}else{extension.drawArraysInstancedANGLE(mode,start,count,geometry.maxInstancedCount)}infoRender.calls++;infoRender.vertices+=count*geometry.maxInstancedCount;if(mode===gl.TRIANGLES)infoRender.faces+=geometry.maxInstancedCount*count/3;else if(mode===gl.POINTS)infoRender.points+=geometry.maxInstancedCount*count}this.setMode=setMode;this.render=render;this.renderInstances=renderInstances}function WebGLGeometries(gl,attributes,infoMemory){var geometries={};var wireframeAttributes={};function onGeometryDispose(event){var geometry=event.target;var buffergeometry=geometries[geometry.id];if(buffergeometry.index!==null){attributes.remove(buffergeometry.index)}for(var name in buffergeometry.attributes){attributes.remove(buffergeometry.attributes[name])}geometry.removeEventListener("dispose",onGeometryDispose);delete geometries[geometry.id];var attribute=wireframeAttributes[geometry.id];if(attribute){attributes.remove(attribute);delete wireframeAttributes[geometry.id]}attribute=wireframeAttributes[buffergeometry.id];if(attribute){attributes.remove(attribute);delete wireframeAttributes[buffergeometry.id]}infoMemory.geometries--}function get(object,geometry){var buffergeometry=geometries[geometry.id];if(buffergeometry)return buffergeometry;geometry.addEventListener("dispose",onGeometryDispose);if(geometry.isBufferGeometry){buffergeometry=geometry}else if(geometry.isGeometry){if(geometry._bufferGeometry===undefined){geometry._bufferGeometry=(new BufferGeometry).setFromObject(object)}buffergeometry=geometry._bufferGeometry}geometries[geometry.id]=buffergeometry;infoMemory.geometries++;return buffergeometry}function update(geometry){var index=geometry.index;var geometryAttributes=geometry.attributes;if(index!==null){attributes.update(index,gl.ELEMENT_ARRAY_BUFFER)}for(var name in geometryAttributes){attributes.update(geometryAttributes[name],gl.ARRAY_BUFFER)}var morphAttributes=geometry.morphAttributes;for(var name in morphAttributes){var array=morphAttributes[name];for(var i=0,l=array.length;i<l;i++){attributes.update(array[i],gl.ARRAY_BUFFER)}}}function getWireframeAttribute(geometry){var attribute=wireframeAttributes[geometry.id];if(attribute)return attribute;var indices=[];var geometryIndex=geometry.index;var geometryAttributes=geometry.attributes;if(geometryIndex!==null){var array=geometryIndex.array;for(var i=0,l=array.length;i<l;i+=3){var a=array[i+0];var b=array[i+1];var c=array[i+2];indices.push(a,b,b,c,c,a)}}else{var array=geometryAttributes.position.array;for(var i=0,l=array.length/3-1;i<l;i+=3){var a=i+0;var b=i+1;var c=i+2;indices.push(a,b,b,c,c,a)}}attribute=new(arrayMax(indices)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(indices,1);attributes.update(attribute,gl.ELEMENT_ARRAY_BUFFER);wireframeAttributes[geometry.id]=attribute;return attribute}return{get:get,update:update,getWireframeAttribute:getWireframeAttribute}}function UniformsCache(){var lights={};return{get:function(light){if(lights[light.id]!==undefined){return lights[light.id]}var uniforms;switch(light.type){case"DirectionalLight":uniforms={direction:new Vector3,color:new Color,shadow:false,shadowBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"SpotLight":uniforms={position:new Vector3,direction:new Vector3,color:new Color,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:false,shadowBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"PointLight":uniforms={position:new Vector3,color:new Color,distance:0,decay:0,shadow:false,shadowBias:0,shadowRadius:1,shadowMapSize:new Vector2,shadowCameraNear:1,shadowCameraFar:1e3};break;case"HemisphereLight":uniforms={direction:new Vector3,skyColor:new Color,groundColor:new Color};break;case"RectAreaLight":uniforms={color:new Color,position:new Vector3,halfWidth:new Vector3,halfHeight:new Vector3};break}lights[light.id]=uniforms;return uniforms}}}function WebGLLights(){var cache=new UniformsCache;var state={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};var vector3=new Vector3;var matrix4=new Matrix4;var matrix42=new Matrix4;function setup(lights,shadows,camera){var r=0,g=0,b=0;var directionalLength=0;var pointLength=0;var spotLength=0;var rectAreaLength=0;var hemiLength=0;var viewMatrix=camera.matrixWorldInverse;for(var i=0,l=lights.length;i<l;i++){var light=lights[i];var color=light.color;var intensity=light.intensity;var distance=light.distance;var shadowMap=light.shadow&&light.shadow.map?light.shadow.map.texture:null;if(light.isAmbientLight){r+=color.r*intensity;g+=color.g*intensity;b+=color.b*intensity}else if(light.isDirectionalLight){var uniforms=cache.get(light);uniforms.color.copy(light.color).multiplyScalar(light.intensity);uniforms.direction.setFromMatrixPosition(light.matrixWorld);vector3.setFromMatrixPosition(light.target.matrixWorld);uniforms.direction.sub(vector3);uniforms.direction.transformDirection(viewMatrix);uniforms.shadow=light.castShadow;if(light.castShadow){var shadow=light.shadow;uniforms.shadowBias=shadow.bias;uniforms.shadowRadius=shadow.radius;uniforms.shadowMapSize=shadow.mapSize}state.directionalShadowMap[directionalLength]=shadowMap;state.directionalShadowMatrix[directionalLength]=light.shadow.matrix;state.directional[directionalLength]=uniforms;directionalLength++}else if(light.isSpotLight){var uniforms=cache.get(light);uniforms.position.setFromMatrixPosition(light.matrixWorld);uniforms.position.applyMatrix4(viewMatrix);uniforms.color.copy(color).multiplyScalar(intensity);uniforms.distance=distance;uniforms.direction.setFromMatrixPosition(light.matrixWorld);vector3.setFromMatrixPosition(light.target.matrixWorld);uniforms.direction.sub(vector3);uniforms.direction.transformDirection(viewMatrix);uniforms.coneCos=Math.cos(light.angle);uniforms.penumbraCos=Math.cos(light.angle*(1-light.penumbra));uniforms.decay=light.distance===0?0:light.decay;uniforms.shadow=light.castShadow;if(light.castShadow){var shadow=light.shadow;uniforms.shadowBias=shadow.bias;uniforms.shadowRadius=shadow.radius;uniforms.shadowMapSize=shadow.mapSize}state.spotShadowMap[spotLength]=shadowMap;state.spotShadowMatrix[spotLength]=light.shadow.matrix;state.spot[spotLength]=uniforms;spotLength++}else if(light.isRectAreaLight){var uniforms=cache.get(light);uniforms.color.copy(color).multiplyScalar(intensity/(light.width*light.height));uniforms.position.setFromMatrixPosition(light.matrixWorld);uniforms.position.applyMatrix4(viewMatrix);matrix42.identity();matrix4.copy(light.matrixWorld);matrix4.premultiply(viewMatrix);matrix42.extractRotation(matrix4);uniforms.halfWidth.set(light.width*.5,0,0);uniforms.halfHeight.set(0,light.height*.5,0);uniforms.halfWidth.applyMatrix4(matrix42);uniforms.halfHeight.applyMatrix4(matrix42);state.rectArea[rectAreaLength]=uniforms;rectAreaLength++}else if(light.isPointLight){var uniforms=cache.get(light);uniforms.position.setFromMatrixPosition(light.matrixWorld)
uniforms.position.applyMatrix4(viewMatrix);uniforms.color.copy(light.color).multiplyScalar(light.intensity);uniforms.distance=light.distance;uniforms.decay=light.distance===0?0
light.decay;uniforms.shadow=light.castShadow;if(light.castShadow){var shadow=light.shadow;uniforms.shadowBias=shadow.bias;uniforms.shadowRadius=shadow.radius;uniforms.shadowMapSize=shadow.mapSize;uniforms.shadowCameraNear=shadow.camera.near;uniforms.shadowCameraFar=shadow.camera.far}state.pointShadowMap[pointLength]=shadowMap;state.pointShadowMatrix[pointLength]=light.shadow.matrix;state.point[pointLength]=uniforms;pointLength++}else if(light.isHemisphereLight){var uniforms=cache.get(light);uniforms.direction.setFromMatrixPosition(light.matrixWorld);uniforms.direction.transformDirection(viewMatrix);uniforms.direction.normalize();uniforms.skyColor.copy(light.color).multiplyScalar(intensity);uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);state.hemi[hemiLength]=uniforms;hemiLength++}}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.hash=directionalLength+","+pointLength+","+spotLength+","+rectAreaLength+","+hemiLength+","+shadows.length}return{setup:setup,state:state}}function WebGLObjects(geometries,infoRender){var updateList={};function update(object){var frame=infoRender.frame;var geometry=object.geometry;var buffergeometry=geometries.get(object,geometry);if(updateList[buffergeometry.id]!==frame){if(geometry.isGeometry){buffergeometry.updateFromObject(object)}geometries.update(buffergeometry);updateList[buffergeometry.id]=frame}return buffergeometry}function clear(){updateList={}}return{update:update,clear:clear}}function addLineNumbers(string){var lines=string.split("\n");for(var i=0;i<lines.length;i++){lines[i]=i+1+": "+lines[i]}return lines.join("\n")}function WebGLShader(gl,type,string){var shader=gl.createShader(type);gl.shaderSource(shader,string);gl.compileShader(shader);if(gl.getShaderParameter(shader,gl.COMPILE_STATUS)===false){console.error("THREE.WebGLShader: Shader couldn't compile.")}if(gl.getShaderInfoLog(shader)!==""){console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",type===gl.VERTEX_SHADER?"vertex":"fragment",gl.getShaderInfoLog(shader),addLineNumbers(string))}return shader}var programIdCount=0;function getEncodingComponents(encoding){switch(encoding){case LinearEncoding:return["Linear","( value )"];case sRGBEncoding:return["sRGB","( value )"];case RGBEEncoding:return["RGBE","( value )"];case RGBM7Encoding:return["RGBM","( value, 7.0 )"];case RGBM16Encoding:return["RGBM","( value, 16.0 )"];case RGBDEncoding:return["RGBD","( value, 256.0 )"];case GammaEncoding:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+encoding)}}function getTexelDecodingFunction(functionName,encoding){var components=getEncodingComponents(encoding);return"vec4 "+functionName+"( vec4 value ) { return "+components[0]+"ToLinear"+components[1]+"; }"}function getTexelEncodingFunction(functionName,encoding){var components=getEncodingComponents(encoding);return"vec4 "+functionName+"( vec4 value ) { return LinearTo"+components[0]+components[1]+"; }"}function getToneMappingFunction(functionName,toneMapping){var toneMappingName;switch(toneMapping){case LinearToneMapping:toneMappingName="Linear";break;case ReinhardToneMapping:toneMappingName="Reinhard";break;case Uncharted2ToneMapping:toneMappingName="Uncharted2";break;case CineonToneMapping:toneMappingName="OptimizedCineon";break;default:throw new Error("unsupported toneMapping: "+toneMapping)}return"vec3 "+functionName+"( vec3 color ) { return "+toneMappingName+"ToneMapping( color ); }"}function generateExtensions(extensions,parameters,rendererExtensions){extensions=extensions||{};var chunks=[extensions.derivatives||parameters.envMapCubeUV||parameters.bumpMap||parameters.normalMap||parameters.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(extensions.fragDepth||parameters.logarithmicDepthBuffer)&&rendererExtensions.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",extensions.drawBuffers&&rendererExtensions.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(extensions.shaderTextureLOD||parameters.envMap)&&rendererExtensions.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""];return chunks.filter(filterEmptyLine).join("\n")}function generateDefines(defines){var chunks=[];for(var name in defines){var value=defines[name];if(value===false)continue;chunks.push("#define "+name+" "+value)}return chunks.join("\n")}function fetchAttributeLocations(gl,program,identifiers){var attributes={};var n=gl.getProgramParameter(program,gl.ACTIVE_ATTRIBUTES);for(var i=0;i<n;i++){var info=gl.getActiveAttrib(program,i);var name=info.name;attributes[name]=gl.getAttribLocation(program,name)}return attributes}function filterEmptyLine(string){return string!==""}function replaceLightNums(string,parameters){return string.replace(/NUM_DIR_LIGHTS/g,parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g,parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g,parameters.numHemiLights)}function parseIncludes(string){var pattern=/^[ \t]*#include +<([\w\d.]+)>/gm;function replace(match,include){var replace=ShaderChunk[include];if(replace===undefined){throw new Error("Can not resolve #include <"+include+">")}return parseIncludes(replace)}return string.replace(pattern,replace)}function unrollLoops(string){var pattern=/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;function replace(match,start,end,snippet){var unroll="";for(var i=parseInt(start);i<parseInt(end);i++){unroll+=snippet.replace(/\[ i \]/g,"[ "+i+" ]")}return unroll}return string.replace(pattern,replace)}function WebGLProgram(renderer,extensions,code,material,shader,parameters){var gl=renderer.context;var defines=material.defines;var vertexShader=shader.vertexShader;var fragmentShader=shader.fragmentShader;var shadowMapTypeDefine="SHADOWMAP_TYPE_BASIC";if(parameters.shadowMapType===PCFShadowMap){shadowMapTypeDefine="SHADOWMAP_TYPE_PCF"}else if(parameters.shadowMapType===PCFSoftShadowMap){shadowMapTypeDefine="SHADOWMAP_TYPE_PCF_SOFT"}var envMapTypeDefine="ENVMAP_TYPE_CUBE";var envMapModeDefine="ENVMAP_MODE_REFLECTION";var envMapBlendingDefine="ENVMAP_BLENDING_MULTIPLY";if(parameters.envMap){switch(material.envMap.mapping){case CubeReflectionMapping:case CubeRefractionMapping:envMapTypeDefine="ENVMAP_TYPE_CUBE";break;case CubeUVReflectionMapping:case CubeUVRefractionMapping:envMapTypeDefine="ENVMAP_TYPE_CUBE_UV";break;case EquirectangularReflectionMapping:case EquirectangularRefractionMapping:envMapTypeDefine="ENVMAP_TYPE_EQUIREC";break;case SphericalReflectionMapping:envMapTypeDefine="ENVMAP_TYPE_SPHERE";break}switch(material.envMap.mapping){case CubeRefractionMapping:case EquirectangularRefractionMapping:envMapModeDefine="ENVMAP_MODE_REFRACTION";break}switch(material.combine){case MultiplyOperation:envMapBlendingDefine="ENVMAP_BLENDING_MULTIPLY";break;case MixOperation:envMapBlendingDefine="ENVMAP_BLENDING_MIX";break;case AddOperation:envMapBlendingDefine="ENVMAP_BLENDING_ADD";break}}var gammaFactorDefine=renderer.gammaFactor>0?renderer.gammaFactor:1;var customExtensions=generateExtensions(material.extensions,parameters,extensions);var customDefines=generateDefines(defines);var program=gl.createProgram();var prefixVertex,prefixFragment;if(material.isRawShaderMaterial){prefixVertex=[customDefines,"\n"].filter(filterEmptyLine).join("\n");prefixFragment=[customExtensions,customDefines,"\n"].filter(filterEmptyLine).join("\n")}else{prefixVertex=["precision "+parameters.precision+" float;","precision "+parameters.precision+" int;","#define SHADER_NAME "+shader.name,customDefines,parameters.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+gammaFactorDefine,"#define MAX_BONES "+parameters.maxBones,parameters.useFog&&parameters.fog?"#define USE_FOG":"",parameters.useFog&&parameters.fogExp?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.displacementMap&&parameters.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.vertexColors?"#define USE_COLOR":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.skinning?"#define USE_SKINNING":"",parameters.useVertexTexture?"#define BONE_TEXTURE":"",parameters.morphTargets?"#define USE_MORPHTARGETS":"",parameters.morphNormals&&parameters.flatShading===false?"#define USE_MORPHNORMALS":"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+parameters.numClippingPlanes,parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.sizeAttenuation?"#define USE_SIZEATTENUATION":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&&extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(filterEmptyLine).join("\n");prefixFragment=[customExtensions,"precision "+parameters.precision+" float;","precision "+parameters.precision+" int;","#define SHADER_NAME "+shader.name,customDefines,parameters.alphaTest?"#define ALPHATEST "+parameters.alphaTest:"","#define GAMMA_FACTOR "+gammaFactorDefine,parameters.useFog&&parameters.fog?"#define USE_FOG":"",parameters.useFog&&parameters.fogExp?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapTypeDefine:"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.envMap?"#define "+envMapBlendingDefine:"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.vertexColors?"#define USE_COLOR":"",parameters.gradientMap?"#define USE_GRADIENTMAP":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+parameters.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(parameters.numClippingPlanes-parameters.numClipIntersection),parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",parameters.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&&extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",parameters.envMap&&extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",parameters.toneMapping!==NoToneMapping?"#define TONE_MAPPING":"",parameters.toneMapping!==NoToneMapping?ShaderChunk["tonemapping_pars_fragment"]:"",parameters.toneMapping!==NoToneMapping?getToneMappingFunction("toneMapping",parameters.toneMapping):"",parameters.dithering?"#define DITHERING":"",parameters.outputEncoding||parameters.mapEncoding||parameters.envMapEncoding||parameters.emissiveMapEncoding?ShaderChunk["encodings_pars_fragment"]:"",parameters.mapEncoding?getTexelDecodingFunction("mapTexelToLinear",parameters.mapEncoding):"",parameters.envMapEncoding?getTexelDecodingFunction("envMapTexelToLinear",parameters.envMapEncoding):"",parameters.emissiveMapEncoding?getTexelDecodingFunction("emissiveMapTexelToLinear",parameters.emissiveMapEncoding):"",parameters.outputEncoding?getTexelEncodingFunction("linearToOutputTexel",parameters.outputEncoding):"",parameters.depthPacking?"#define DEPTH_PACKING "+material.depthPacking:"","\n"].filter(filterEmptyLine).join("\n")}vertexShader=parseIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);fragmentShader=parseIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);if(!material.isShaderMaterial){vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader)}var vertexGlsl=prefixVertex+vertexShader;var fragmentGlsl=prefixFragment+fragmentShader;var glVertexShader=WebGLShader(gl,gl.VERTEX_SHADER,vertexGlsl);var glFragmentShader=WebGLShader(gl,gl.FRAGMENT_SHADER,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);if(material.index0AttributeName!==undefined){gl.bindAttribLocation(program,0,material.index0AttributeName)}else if(parameters.morphTargets===true){gl.bindAttribLocation(program,0,"position")}gl.linkProgram(program);var programLog=gl.getProgramInfoLog(program);var vertexLog=gl.getShaderInfoLog(glVertexShader);var fragmentLog=gl.getShaderInfoLog(glFragmentShader);var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,gl.LINK_STATUS)===false){runnable=false;console.error("THREE.WebGLProgram: shader error: ",gl.getError(),"gl.VALIDATE_STATUS",gl.getProgramParameter(program,gl.VALIDATE_STATUS),"gl.getProgramInfoLog",programLog,vertexLog,fragmentLog)}else if(programLog!==""){console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",programLog)}else if(vertexLog===""||fragmentLog===""){haveDiagnostics=false}if(haveDiagnostics){this.diagnostics={runnable:runnable,material:material,programLog:programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}}}gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms(gl,program,renderer)}return cachedUniforms};var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations(gl,program)}return cachedAttributes};this.destroy=function(){gl.deleteProgram(program);this.program=undefined};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=programIdCount++;this.code=code;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this}function WebGLPrograms(renderer,extensions,capabilities){var programs=[];var shaderIDs={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow"};var parameterNames=["precision","supportsVertexTextures","map","mapEncoding","envMap","envMapMode","envMapEncoding","lightMap","aoMap","emissiveMap","emissiveMapEncoding","bumpMap","normalMap","displacementMap","specularMap","roughnessMap","metalnessMap","gradientMap","alphaMap","combine","vertexColors","fog","useFog","fogExp","flatShading","sizeAttenuation","logarithmicDepthBuffer","skinning","maxBones","useVertexTexture","morphTargets","morphNormals","maxMorphTargets","maxMorphNormals","premultipliedAlpha","numDirLights","numPointLights","numSpotLights","numHemiLights","numRectAreaLights","shadowMapEnabled","shadowMapType","toneMapping","physicallyCorrectLights","alphaTest","doubleSided","flipSided","numClippingPlanes","numClipIntersection","depthPacking","dithering"];function allocateBones(object){var skeleton=object.skeleton;var bones=skeleton.bones;if(capabilities.floatVertexTextures){return 1024}else{var nVertexUniforms=capabilities.maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones<bones.length){console.warn("THREE.WebGLRenderer: Skeleton has "+bones.length+" bones. This GPU supports "+maxBones+".");return 0}return maxBones}}function getTextureEncodingFromMap(map,gammaOverrideLinear){var encoding;if(!map){encoding=LinearEncoding}else if(map.isTexture){encoding=map.encoding}else if(map.isWebGLRenderTarget){console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");encoding=map.texture.encoding}if(encoding===LinearEncoding&&gammaOverrideLinear){encoding=GammaEncoding}return encoding}this.getParameters=function(material,lights,shadows,fog,nClipPlanes,nClipIntersection,object){var shaderID=shaderIDs[material.type];var maxBones=object.isSkinnedMesh?allocateBones(object):0;var precision=capabilities.precision;if(material.precision!==null){precision=capabilities.getMaxPrecision(material.precision);if(precision!==material.precision){console.warn("THREE.WebGLProgram.getParameters:",material.precision,"not supported, using",precision,"instead.")}}var currentRenderTarget=renderer.getRenderTarget();var parameters={shaderID:shaderID,precision:precision,supportsVertexTextures:capabilities.vertexTextures,outputEncoding:getTextureEncodingFromMap(!currentRenderTarget?null:currentRenderTarget.texture,renderer.gammaOutput),map:!!material.map,mapEncoding:getTextureEncodingFromMap(material.map,renderer.gammaInput),envMap:!!material.envMap,envMapMode:material.envMap&&material.envMap.mapping,envMapEncoding:getTextureEncodingFromMap(material.envMap,renderer.gammaInput),envMapCubeUV:!!material.envMap&&(material.envMap.mapping===CubeUVReflectionMapping||material.envMap.mapping===CubeUVRefractionMapping),lightMap:!!material.lightMap,aoMap:!!material.aoMap,emissiveMap:!!material.emissiveMap,emissiveMapEncoding:getTextureEncodingFromMap(material.emissiveMap,renderer.gammaInput),bumpMap:!!material.bumpMap,normalMap:!!material.normalMap,displacementMap:!!material.displacementMap,roughnessMap:!!material.roughnessMap,metalnessMap:!!material.metalnessMap,specularMap:!!material.specularMap,alphaMap:!!material.alphaMap,gradientMap:!!material.gradientMap,combine:material.combine,vertexColors:material.vertexColors,fog:!!fog,useFog:material.fog,fogExp:fog&&fog.isFogExp2,flatShading:material.flatShading,sizeAttenuation:material.sizeAttenuation,logarithmicDepthBuffer:capabilities.logarithmicDepthBuffer,skinning:material.skinning&&maxBones>0,maxBones:maxBones,useVertexTexture:capabilities.floatVertexTextures,morphTargets:material.morphTargets,morphNormals:material.morphNormals,maxMorphTargets:renderer.maxMorphTargets,maxMorphNormals:renderer.maxMorphNormals,numDirLights:lights.directional.length,numPointLights:lights.point.length,numSpotLights:lights.spot.length,numRectAreaLights:lights.rectArea.length,numHemiLights:lights.hemi.length,numClippingPlanes:nClipPlanes,numClipIntersection:nClipIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&object.receiveShadow&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:renderer.toneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,alphaTest:material.alphaTest,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,depthPacking:material.depthPacking!==undefined?material.depthPacking:false};return parameters};this.getProgramCode=function(material,parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID)}else{array.push(material.fragmentShader);array.push(material.vertexShader)}if(material.defines!==undefined){for(var name in material.defines){array.push(name);array.push(material.defines[name])}}for(var i=0;i<parameterNames.length;i++){array.push(parameters[parameterNames[i]])}array.push(material.onBeforeCompile.toString());array.push(renderer.gammaOutput);return array.join()};this.acquireProgram=function(material,shader,parameters,code){var program;for(var p=0,pl=programs.length;p<pl;p++){var programInfo=programs[p];if(programInfo.code===code){program=programInfo;++program.usedTimes;break}}if(program===undefined){program=new WebGLProgram(renderer,extensions,code,material,shader,parameters);programs.push(program)}return program};this.releaseProgram=function(program){if(--program.usedTimes===0){var i=programs.indexOf(program);programs[i]=programs[programs.length-1];programs.pop();program.destroy()}};this.programs=programs}function WebGLTextures(_gl,extensions,state,properties,capabilities,utils,infoMemory){var _isWebGL2=typeof WebGL2RenderingContext!=="undefined"&&_gl instanceof WebGL2RenderingContext;function clampToMaxSize(image,maxSize){if(image.width>maxSize||image.height>maxSize){var scale=maxSize/Math.max(image.width,image.height);var canvas=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");canvas.width=Math.floor(image.width*scale);canvas.height=Math.floor(image.height*scale);var context=canvas.getContext("2d");context.drawImage(image,0,0,image.width,image.height,0,0,canvas.width,canvas.height);console.warn("THREE.WebGLRenderer: image is too big ("+image.width+"x"+image.height+"). Resized to "+canvas.width+"x"+canvas.height,image);return canvas}return image}function isPowerOfTwo(image){return _Math.isPowerOfTwo(image.width)&&_Math.isPowerOfTwo(image.height)}function makePowerOfTwo(image){if(image instanceof HTMLImageElement||image instanceof HTMLCanvasElement){var canvas=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");canvas.width=_Math.nearestPowerOfTwo(image.width);canvas.height=_Math.nearestPowerOfTwo(image.height);var context=canvas.getContext("2d");context.drawImage(image,0,0,canvas.width,canvas.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+image.width+"x"+image.height+"). Resized to "+canvas.width+"x"+canvas.height,image);return canvas}return image}function textureNeedsPowerOfTwo(texture){return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function textureNeedsGenerateMipmaps(texture,isPowerOfTwo){return texture.generateMipmaps&&isPowerOfTwo&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function filterFallback(f){if(f===NearestFilter||f===NearestMipMapNearestFilter||f===NearestMipMapLinearFilter){return _gl.NEAREST}return _gl.LINEAR}function onTextureDispose(event){var texture=event.target;texture.removeEventListener("dispose",onTextureDispose);deallocateTexture(texture);infoMemory.textures--}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener("dispose",onRenderTargetDispose);deallocateRenderTarget(renderTarget);infoMemory.textures--}function deallocateTexture(texture){var textureProperties=properties.get(texture);if(texture.image&&textureProperties.__image__webglTextureCube){_gl.deleteTexture(textureProperties.__image__webglTextureCube)}else{if(textureProperties.__webglInit===undefined)return;_gl.deleteTexture(textureProperties.__webglTexture)}properties.remove(texture)}function deallocateRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var textureProperties=properties.get(renderTarget.texture);if(!renderTarget)return;if(textureProperties.__webglTexture!==undefined){_gl.deleteTexture(textureProperties.__webglTexture)}if(renderTarget.depthTexture){renderTarget.depthTexture.dispose()}if(renderTarget.isWebGLRenderTargetCube){for(var i=0;i<6;i++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i])}}else{_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer)}properties.remove(renderTarget.texture);properties.remove(renderTarget)}function setTexture2D(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){var image=texture.image;if(image===undefined){console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",texture)}else if(image.complete===false){console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",texture)}else{uploadTexture(textureProperties,texture,slot);return}}state.activeTexture(_gl.TEXTURE0+slot);state.bindTexture(_gl.TEXTURE_2D,textureProperties.__webglTexture)}function setTextureCube(texture,slot){var textureProperties=properties.get(texture);if(texture.image.length===6){if(texture.version>0&&textureProperties.__version!==texture.version){if(!textureProperties.__image__webglTextureCube){texture.addEventListener("dispose",onTextureDispose);textureProperties.__image__webglTextureCube=_gl.createTexture();infoMemory.textures++}state.activeTexture(_gl.TEXTURE0+slot);state.bindTexture(_gl.TEXTURE_CUBE_MAP,textureProperties.__image__webglTextureCube);_gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL,texture.flipY);var isCompressed=texture&&texture.isCompressedTexture;var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var i=0;i<6;i++){if(!isCompressed&&!isDataTexture){cubeImage[i]=clampToMaxSize(texture.image[i],capabilities.maxCubemapSize)}else{cubeImage[i]=isDataTexture?texture.image[i].image:texture.image[i]}}var image=cubeImage[0],isPowerOfTwoImage=isPowerOfTwo(image),glFormat=utils.convert(texture.format),glType=utils.convert(texture.type);setTextureParameters(_gl.TEXTURE_CUBE_MAP,texture,isPowerOfTwoImage);for(var i=0;i<6;i++){if(!isCompressed){if(isDataTexture){state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X+i,0,glFormat,cubeImage[i].width,cubeImage[i].height,0,glFormat,glType,cubeImage[i].data)}else{state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X+i,0,glFormat,glFormat,glType,cubeImage[i])}}else{var mipmap,mipmaps=cubeImage[i].mipmaps;for(var j=0,jl=mipmaps.length;j<jl;j++){mipmap=mipmaps[j];if(texture.format!==RGBAFormat&&texture.format!==RGBFormat){if(state.getCompressedTextureFormats().indexOf(glFormat)>-1){state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X+i,j,glFormat,mipmap.width,mipmap.height,0,mipmap.data)}else{console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()")}}else{state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X+i,j,glFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data)}}}}if(textureNeedsGenerateMipmaps(texture,isPowerOfTwoImage)){_gl.generateMipmap(_gl.TEXTURE_CUBE_MAP)}textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture)}else{state.activeTexture(_gl.TEXTURE0+slot);state.bindTexture(_gl.TEXTURE_CUBE_MAP,textureProperties.__image__webglTextureCube)}}}function setTextureCubeDynamic(texture,slot){state.activeTexture(_gl.TEXTURE0+slot);state.bindTexture(_gl.TEXTURE_CUBE_MAP,properties.get(texture).__webglTexture)}function setTextureParameters(textureType,texture,isPowerOfTwoImage){var extension;if(isPowerOfTwoImage){_gl.texParameteri(textureType,_gl.TEXTURE_WRAP_S,utils.convert(texture.wrapS));_gl.texParameteri(textureType,_gl.TEXTURE_WRAP_T,utils.convert(texture.wrapT));_gl.texParameteri(textureType,_gl.TEXTURE_MAG_FILTER,utils.convert(texture.magFilter));_gl.texParameteri(textureType,_gl.TEXTURE_MIN_FILTER,utils.convert(texture.minFilter))}else{_gl.texParameteri(textureType,_gl.TEXTURE_WRAP_S,_gl.CLAMP_TO_EDGE);_gl.texParameteri(textureType,_gl.TEXTURE_WRAP_T,_gl.CLAMP_TO_EDGE);if(texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",texture)}_gl.texParameteri(textureType,_gl.TEXTURE_MAG_FILTER,filterFallback(texture.magFilter));_gl.texParameteri(textureType,_gl.TEXTURE_MIN_FILTER,filterFallback(texture.minFilter));if(texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",texture)}}extension=extensions.get("EXT_texture_filter_anisotropic");if(extension){if(texture.type===FloatType&&extensions.get("OES_texture_float_linear")===null)return;if(texture.type===HalfFloatType&&extensions.get("OES_texture_half_float_linear")===null)return;if(texture.anisotropy>1||properties.get(texture).__currentAnisotropy){_gl.texParameterf(textureType,extension.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(texture.anisotropy,capabilities.getMaxAnisotropy()));properties.get(texture).__currentAnisotropy=texture.anisotropy}}}function uploadTexture(textureProperties,texture,slot){if(textureProperties.__webglInit===undefined){textureProperties.__webglInit=true;texture.addEventListener("dispose",onTextureDispose);textureProperties.__webglTexture=_gl.createTexture();infoMemory.textures++}state.activeTexture(_gl.TEXTURE0+slot);state.bindTexture(_gl.TEXTURE_2D,textureProperties.__webglTexture);_gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL,texture.flipY);_gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,texture.premultiplyAlpha);_gl.pixelStorei(_gl.UNPACK_ALIGNMENT,texture.unpackAlignment);var image=clampToMaxSize(texture.image,capabilities.maxTextureSize);if(textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(image)===false){image=makePowerOfTwo(image)}var isPowerOfTwoImage=isPowerOfTwo(image),glFormat=utils.convert(texture.format),glType=utils.convert(texture.type);setTextureParameters(_gl.TEXTURE_2D,texture,isPowerOfTwoImage);var mipmap,mipmaps=texture.mipmaps;if(texture.isDepthTexture){var internalFormat=_gl.DEPTH_COMPONENT;if(texture.type===FloatType){if(!_isWebGL2)throw new Error("Float Depth Texture only supported in WebGL2.0");internalFormat=_gl.DEPTH_COMPONENT32F}else if(_isWebGL2){internalFormat=_gl.DEPTH_COMPONENT16}if(texture.format===DepthFormat&&internalFormat===_gl.DEPTH_COMPONENT){if(texture.type!==UnsignedShortType&&texture.type!==UnsignedIntType){console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.");texture.type=UnsignedShortType
glType=utils.convert(texture.type)}}if(texture.format===DepthStencilFormat){internalFormat=_gl.DEPTH_STENCIL;if(texture.type!==UnsignedInt248Type){console.warn("THREE.WebGLRenderer
Use UnsignedInt248Type for DepthStencilFormat DepthTexture.");texture.type=UnsignedInt248Type;glType=utils.convert(texture.type)}}state.texImage2D(_gl.TEXTURE_2D,0,internalFormat,image.width,image.height,0,glFormat,glType,null)}else if(texture.isDataTexture){if(mipmaps.length>0&&isPowerOfTwoImage){for(var i=0,il=mipmaps.length;i<il;i++){mipmap=mipmaps[i];state.texImage2D(_gl.TEXTURE_2D,i,glFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data)}texture.generateMipmaps=false}else{state.texImage2D(_gl.TEXTURE_2D,0,glFormat,image.width,image.height,0,glFormat,glType,image.data)}}else if(texture.isCompressedTexture){for(var i=0,il=mipmaps.length;i<il;i++){mipmap=mipmaps[i];if(texture.format!==RGBAFormat&&texture.format!==RGBFormat){if(state.getCompressedTextureFormats().indexOf(glFormat)>-1){state.compressedTexImage2D(_gl.TEXTURE_2D,i,glFormat,mipmap.width,mipmap.height,0,mipmap.data)}else{console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()")}}else{state.texImage2D(_gl.TEXTURE_2D,i,glFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data)}}}else{if(mipmaps.length>0&&isPowerOfTwoImage){for(var i=0,il=mipmaps.length;i<il;i++){mipmap=mipmaps[i];state.texImage2D(_gl.TEXTURE_2D,i,glFormat,glFormat,glType,mipmap)}texture.generateMipmaps=false}else{state.texImage2D(_gl.TEXTURE_2D,0,glFormat,glFormat,glType,image)}}if(textureNeedsGenerateMipmaps(texture,isPowerOfTwoImage))_gl.generateMipmap(_gl.TEXTURE_2D);textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture)}function setupFrameBufferTexture(framebuffer,renderTarget,attachment,textureTarget){var glFormat=utils.convert(renderTarget.texture.format);var glType=utils.convert(renderTarget.texture.type);state.texImage2D(textureTarget,0,glFormat,renderTarget.width,renderTarget.height,0,glFormat,glType,null);_gl.bindFramebuffer(_gl.FRAMEBUFFER,framebuffer);_gl.framebufferTexture2D(_gl.FRAMEBUFFER,attachment,textureTarget,properties.get(renderTarget.texture).__webglTexture,0);_gl.bindFramebuffer(_gl.FRAMEBUFFER,null)}function setupRenderBufferStorage(renderbuffer,renderTarget){_gl.bindRenderbuffer(_gl.RENDERBUFFER,renderbuffer);if(renderTarget.depthBuffer&&!renderTarget.stencilBuffer){_gl.renderbufferStorage(_gl.RENDERBUFFER,_gl.DEPTH_COMPONENT16,renderTarget.width,renderTarget.height);_gl.framebufferRenderbuffer(_gl.FRAMEBUFFER,_gl.DEPTH_ATTACHMENT,_gl.RENDERBUFFER,renderbuffer)}else if(renderTarget.depthBuffer&&renderTarget.stencilBuffer){_gl.renderbufferStorage(_gl.RENDERBUFFER,_gl.DEPTH_STENCIL,renderTarget.width,renderTarget.height);_gl.framebufferRenderbuffer(_gl.FRAMEBUFFER,_gl.DEPTH_STENCIL_ATTACHMENT,_gl.RENDERBUFFER,renderbuffer)}else{_gl.renderbufferStorage(_gl.RENDERBUFFER,_gl.RGBA4,renderTarget.width,renderTarget.height)}_gl.bindRenderbuffer(_gl.RENDERBUFFER,null)}function setupDepthTexture(framebuffer,renderTarget){var isCube=renderTarget&&renderTarget.isWebGLRenderTargetCube;if(isCube)throw new Error("Depth Texture with cube render targets is not supported");_gl.bindFramebuffer(_gl.FRAMEBUFFER,framebuffer);if(!(renderTarget.depthTexture&&renderTarget.depthTexture.isDepthTexture)){throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture")}if(!properties.get(renderTarget.depthTexture).__webglTexture||renderTarget.depthTexture.image.width!==renderTarget.width||renderTarget.depthTexture.image.height!==renderTarget.height){renderTarget.depthTexture.image.width=renderTarget.width;renderTarget.depthTexture.image.height=renderTarget.height;renderTarget.depthTexture.needsUpdate=true}setTexture2D(renderTarget.depthTexture,0);var webglDepthTexture=properties.get(renderTarget.depthTexture).__webglTexture;if(renderTarget.depthTexture.format===DepthFormat){_gl.framebufferTexture2D(_gl.FRAMEBUFFER,_gl.DEPTH_ATTACHMENT,_gl.TEXTURE_2D,webglDepthTexture,0)}else if(renderTarget.depthTexture.format===DepthStencilFormat){_gl.framebufferTexture2D(_gl.FRAMEBUFFER,_gl.DEPTH_STENCIL_ATTACHMENT,_gl.TEXTURE_2D,webglDepthTexture,0)}else{throw new Error("Unknown depthTexture format")}}function setupDepthRenderbuffer(renderTarget){var renderTargetProperties=properties.get(renderTarget);var isCube=renderTarget.isWebGLRenderTargetCube===true;if(renderTarget.depthTexture){if(isCube)throw new Error("target.depthTexture not supported in Cube render targets");setupDepthTexture(renderTargetProperties.__webglFramebuffer,renderTarget)}else{if(isCube){renderTargetProperties.__webglDepthbuffer=[];for(var i=0;i<6;i++){_gl.bindFramebuffer(_gl.FRAMEBUFFER,renderTargetProperties.__webglFramebuffer[i]);renderTargetProperties.__webglDepthbuffer[i]=_gl.createRenderbuffer();setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i],renderTarget)}}else{_gl.bindFramebuffer(_gl.FRAMEBUFFER,renderTargetProperties.__webglFramebuffer);renderTargetProperties.__webglDepthbuffer=_gl.createRenderbuffer();setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer,renderTarget)}}_gl.bindFramebuffer(_gl.FRAMEBUFFER,null)}function setupRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var textureProperties=properties.get(renderTarget.texture);renderTarget.addEventListener("dispose",onRenderTargetDispose);textureProperties.__webglTexture=_gl.createTexture();infoMemory.textures++;var isCube=renderTarget.isWebGLRenderTargetCube===true;var isTargetPowerOfTwo=isPowerOfTwo(renderTarget);if(isCube){renderTargetProperties.__webglFramebuffer=[];for(var i=0;i<6;i++){renderTargetProperties.__webglFramebuffer[i]=_gl.createFramebuffer()}}else{renderTargetProperties.__webglFramebuffer=_gl.createFramebuffer()}if(isCube){state.bindTexture(_gl.TEXTURE_CUBE_MAP,textureProperties.__webglTexture);setTextureParameters(_gl.TEXTURE_CUBE_MAP,renderTarget.texture,isTargetPowerOfTwo);for(var i=0;i<6;i++){setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i],renderTarget,_gl.COLOR_ATTACHMENT0,_gl.TEXTURE_CUBE_MAP_POSITIVE_X+i)}if(textureNeedsGenerateMipmaps(renderTarget.texture,isTargetPowerOfTwo))_gl.generateMipmap(_gl.TEXTURE_CUBE_MAP);state.bindTexture(_gl.TEXTURE_CUBE_MAP,null)}else{state.bindTexture(_gl.TEXTURE_2D,textureProperties.__webglTexture);setTextureParameters(_gl.TEXTURE_2D,renderTarget.texture,isTargetPowerOfTwo);setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer,renderTarget,_gl.COLOR_ATTACHMENT0,_gl.TEXTURE_2D);if(textureNeedsGenerateMipmaps(renderTarget.texture,isTargetPowerOfTwo))_gl.generateMipmap(_gl.TEXTURE_2D);state.bindTexture(_gl.TEXTURE_2D,null)}if(renderTarget.depthBuffer){setupDepthRenderbuffer(renderTarget)}}function updateRenderTargetMipmap(renderTarget){var texture=renderTarget.texture;var isTargetPowerOfTwo=isPowerOfTwo(renderTarget);if(textureNeedsGenerateMipmaps(texture,isTargetPowerOfTwo)){var target=renderTarget.isWebGLRenderTargetCube?_gl.TEXTURE_CUBE_MAP:_gl.TEXTURE_2D;var webglTexture=properties.get(texture).__webglTexture;state.bindTexture(target,webglTexture);_gl.generateMipmap(target);state.bindTexture(target,null)}}this.setTexture2D=setTexture2D;this.setTextureCube=setTextureCube;this.setTextureCubeDynamic=setTextureCubeDynamic;this.setupRenderTarget=setupRenderTarget;this.updateRenderTargetMipmap=updateRenderTargetMipmap}function WebGLProperties(){var properties={};function get(object){var uuid=object.uuid;var map=properties[uuid];if(map===undefined){map={};properties[uuid]=map}return map}function remove(object){delete properties[object.uuid]}function clear(){properties={}}return{get:get,remove:remove,clear:clear}}function WebGLState(gl,extensions,utils){function ColorBuffer(){var locked=false;var color=new Vector4;var currentColorMask=null;var currentColorClear=new Vector4(0,0,0,0);return{setMask:function(colorMask){if(currentColorMask!==colorMask&&!locked){gl.colorMask(colorMask,colorMask,colorMask,colorMask);currentColorMask=colorMask}},setLocked:function(lock){locked=lock},setClear:function(r,g,b,a,premultipliedAlpha){if(premultipliedAlpha===true){r*=a;g*=a;b*=a}color.set(r,g,b,a);if(currentColorClear.equals(color)===false){gl.clearColor(r,g,b,a);currentColorClear.copy(color)}},reset:function(){locked=false;currentColorMask=null;currentColorClear.set(-1,0,0,0)}}}function DepthBuffer(){var locked=false;var currentDepthMask=null;var currentDepthFunc=null;var currentDepthClear=null;return{setTest:function(depthTest){if(depthTest){enable(gl.DEPTH_TEST)}else{disable(gl.DEPTH_TEST)}},setMask:function(depthMask){if(currentDepthMask!==depthMask&&!locked){gl.depthMask(depthMask);currentDepthMask=depthMask}},setFunc:function(depthFunc){if(currentDepthFunc!==depthFunc){if(depthFunc){switch(depthFunc){case NeverDepth:gl.depthFunc(gl.NEVER);break;case AlwaysDepth:gl.depthFunc(gl.ALWAYS);break;case LessDepth:gl.depthFunc(gl.LESS);break;case LessEqualDepth:gl.depthFunc(gl.LEQUAL);break;case EqualDepth:gl.depthFunc(gl.EQUAL);break;case GreaterEqualDepth:gl.depthFunc(gl.GEQUAL);break;case GreaterDepth:gl.depthFunc(gl.GREATER);break;case NotEqualDepth:gl.depthFunc(gl.NOTEQUAL);break;default:gl.depthFunc(gl.LEQUAL)}}else{gl.depthFunc(gl.LEQUAL)}currentDepthFunc=depthFunc}},setLocked:function(lock){locked=lock},setClear:function(depth){if(currentDepthClear!==depth){gl.clearDepth(depth);currentDepthClear=depth}},reset:function(){locked=false;currentDepthMask=null;currentDepthFunc=null;currentDepthClear=null}}}function StencilBuffer(){var locked=false;var currentStencilMask=null;var currentStencilFunc=null;var currentStencilRef=null;var currentStencilFuncMask=null;var currentStencilFail=null;var currentStencilZFail=null;var currentStencilZPass=null;var currentStencilClear=null;return{setTest:function(stencilTest){if(stencilTest){enable(gl.STENCIL_TEST)}else{disable(gl.STENCIL_TEST)}},setMask:function(stencilMask){if(currentStencilMask!==stencilMask&&!locked){gl.stencilMask(stencilMask);currentStencilMask=stencilMask}},setFunc:function(stencilFunc,stencilRef,stencilMask){if(currentStencilFunc!==stencilFunc||currentStencilRef!==stencilRef||currentStencilFuncMask!==stencilMask){gl.stencilFunc(stencilFunc,stencilRef,stencilMask);currentStencilFunc=stencilFunc;currentStencilRef=stencilRef;currentStencilFuncMask=stencilMask}},setOp:function(stencilFail,stencilZFail,stencilZPass){if(currentStencilFail!==stencilFail||currentStencilZFail!==stencilZFail||currentStencilZPass!==stencilZPass){gl.stencilOp(stencilFail,stencilZFail,stencilZPass);currentStencilFail=stencilFail;currentStencilZFail=stencilZFail;currentStencilZPass=stencilZPass}},setLocked:function(lock){locked=lock},setClear:function(stencil){if(currentStencilClear!==stencil){gl.clearStencil(stencil);currentStencilClear=stencil}},reset:function(){locked=false;currentStencilMask=null;currentStencilFunc=null;currentStencilRef=null;currentStencilFuncMask=null;currentStencilFail=null;currentStencilZFail=null;currentStencilZPass=null;currentStencilClear=null}}}var colorBuffer=new ColorBuffer;var depthBuffer=new DepthBuffer;var stencilBuffer=new StencilBuffer;var maxVertexAttributes=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);var newAttributes=new Uint8Array(maxVertexAttributes);var enabledAttributes=new Uint8Array(maxVertexAttributes);var attributeDivisors=new Uint8Array(maxVertexAttributes);var capabilities={};var compressedTextureFormats=null;var currentProgram=null;var currentBlending=null;var currentBlendEquation=null;var currentBlendSrc=null;var currentBlendDst=null;var currentBlendEquationAlpha=null;var currentBlendSrcAlpha=null;var currentBlendDstAlpha=null;var currentPremultipledAlpha=false;var currentFlipSided=null;var currentCullFace=null;var currentLineWidth=null;var currentPolygonOffsetFactor=null;var currentPolygonOffsetUnits=null;var maxTextures=gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);var version=parseFloat(/^WebGL\ ([0-9])/.exec(gl.getParameter(gl.VERSION))[1]);var lineWidthAvailable=parseFloat(version)>=1;var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4;var currentViewport=new Vector4;function createTexture(type,target,count){var data=new Uint8Array(4);var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(type,gl.TEXTURE_MAG_FILTER,gl.NEAREST);for(var i=0;i<count;i++){gl.texImage2D(target+i,0,gl.RGBA,1,1,0,gl.RGBA,gl.UNSIGNED_BYTE,data)}return texture}var emptyTextures={};emptyTextures[gl.TEXTURE_2D]=createTexture(gl.TEXTURE_2D,gl.TEXTURE_2D,1);emptyTextures[gl.TEXTURE_CUBE_MAP]=createTexture(gl.TEXTURE_CUBE_MAP,gl.TEXTURE_CUBE_MAP_POSITIVE_X,6);colorBuffer.setClear(0,0,0,1);depthBuffer.setClear(1);stencilBuffer.setClear(0);enable(gl.DEPTH_TEST);depthBuffer.setFunc(LessEqualDepth);setFlipSided(false);setCullFace(CullFaceBack);enable(gl.CULL_FACE);enable(gl.BLEND);setBlending(NormalBlending);function initAttributes(){for(var i=0,l=newAttributes.length;i<l;i++){newAttributes[i]=0}}function enableAttribute(attribute){newAttributes[attribute]=1;if(enabledAttributes[attribute]===0){gl.enableVertexAttribArray(attribute);enabledAttributes[attribute]=1}if(attributeDivisors[attribute]!==0){var extension=extensions.get("ANGLE_instanced_arrays");extension.vertexAttribDivisorANGLE(attribute,0);attributeDivisors[attribute]=0}}function enableAttributeAndDivisor(attribute,meshPerAttribute){newAttributes[attribute]=1;if(enabledAttributes[attribute]===0){gl.enableVertexAttribArray(attribute);enabledAttributes[attribute]=1}if(attributeDivisors[attribute]!==meshPerAttribute){var extension=extensions.get("ANGLE_instanced_arrays");extension.vertexAttribDivisorANGLE(attribute,meshPerAttribute);attributeDivisors[attribute]=meshPerAttribute}}function disableUnusedAttributes(){for(var i=0,l=enabledAttributes.length;i!==l;++i){if(enabledAttributes[i]!==newAttributes[i]){gl.disableVertexAttribArray(i);enabledAttributes[i]=0}}}function enable(id){if(capabilities[id]!==true){gl.enable(id);capabilities[id]=true}}function disable(id){if(capabilities[id]!==false){gl.disable(id);capabilities[id]=false}}function getCompressedTextureFormats(){if(compressedTextureFormats===null){compressedTextureFormats=[];if(extensions.get("WEBGL_compressed_texture_pvrtc")||extensions.get("WEBGL_compressed_texture_s3tc")||extensions.get("WEBGL_compressed_texture_etc1")){var formats=gl.getParameter(gl.COMPRESSED_TEXTURE_FORMATS);for(var i=0;i<formats.length;i++){compressedTextureFormats.push(formats[i])}}}return compressedTextureFormats}function useProgram(program){if(currentProgram!==program){gl.useProgram(program);currentProgram=program;return true}return false}function setBlending(blending,blendEquation,blendSrc,blendDst,blendEquationAlpha,blendSrcAlpha,blendDstAlpha,premultipliedAlpha){if(blending!==NoBlending){enable(gl.BLEND)}else{disable(gl.BLEND)}if(blending!==CustomBlending){if(blending!==currentBlending||premultipliedAlpha!==currentPremultipledAlpha){switch(blending){case AdditiveBlending:if(premultipliedAlpha){gl.blendEquationSeparate(gl.FUNC_ADD,gl.FUNC_ADD);gl.blendFuncSeparate(gl.ONE,gl.ONE,gl.ONE,gl.ONE)}else{gl.blendEquation(gl.FUNC_ADD);gl.blendFunc(gl.SRC_ALPHA,gl.ONE)}break;case SubtractiveBlending:if(premultipliedAlpha){gl.blendEquationSeparate(gl.FUNC_ADD,gl.FUNC_ADD);gl.blendFuncSeparate(gl.ZERO,gl.ZERO,gl.ONE_MINUS_SRC_COLOR,gl.ONE_MINUS_SRC_ALPHA)}else{gl.blendEquation(gl.FUNC_ADD);gl.blendFunc(gl.ZERO,gl.ONE_MINUS_SRC_COLOR)}break;case MultiplyBlending:if(premultipliedAlpha){gl.blendEquationSeparate(gl.FUNC_ADD,gl.FUNC_ADD);gl.blendFuncSeparate(gl.ZERO,gl.SRC_COLOR,gl.ZERO,gl.SRC_ALPHA)}else{gl.blendEquation(gl.FUNC_ADD);gl.blendFunc(gl.ZERO,gl.SRC_COLOR)}break;default:if(premultipliedAlpha){gl.blendEquationSeparate(gl.FUNC_ADD,gl.FUNC_ADD);gl.blendFuncSeparate(gl.ONE,gl.ONE_MINUS_SRC_ALPHA,gl.ONE,gl.ONE_MINUS_SRC_ALPHA)}else{gl.blendEquationSeparate(gl.FUNC_ADD,gl.FUNC_ADD);gl.blendFuncSeparate(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA,gl.ONE,gl.ONE_MINUS_SRC_ALPHA)}}}currentBlendEquation=null;currentBlendSrc=null;currentBlendDst=null;currentBlendEquationAlpha=null;currentBlendSrcAlpha=null;currentBlendDstAlpha=null}else{blendEquationAlpha=blendEquationAlpha||blendEquation;blendSrcAlpha=blendSrcAlpha||blendSrc;blendDstAlpha=blendDstAlpha||blendDst;if(blendEquation!==currentBlendEquation||blendEquationAlpha!==currentBlendEquationAlpha){gl.blendEquationSeparate(utils.convert(blendEquation),utils.convert(blendEquationAlpha));currentBlendEquation=blendEquation;currentBlendEquationAlpha=blendEquationAlpha}if(blendSrc!==currentBlendSrc||blendDst!==currentBlendDst||blendSrcAlpha!==currentBlendSrcAlpha||blendDstAlpha!==currentBlendDstAlpha){gl.blendFuncSeparate(utils.convert(blendSrc),utils.convert(blendDst),utils.convert(blendSrcAlpha),utils.convert(blendDstAlpha));currentBlendSrc=blendSrc;currentBlendDst=blendDst;currentBlendSrcAlpha=blendSrcAlpha;currentBlendDstAlpha=blendDstAlpha}}currentBlending=blending;currentPremultipledAlpha=premultipliedAlpha}function setMaterial(material){material.side===DoubleSide?disable(gl.CULL_FACE):enable(gl.CULL_FACE);setFlipSided(material.side===BackSide);material.transparent===true?setBlending(material.blending,material.blendEquation,material.blendSrc,material.blendDst,material.blendEquationAlpha,material.blendSrcAlpha,material.blendDstAlpha,material.premultipliedAlpha):setBlending(NoBlending);depthBuffer.setFunc(material.depthFunc);depthBuffer.setTest(material.depthTest);depthBuffer.setMask(material.depthWrite);colorBuffer.setMask(material.colorWrite);setPolygonOffset(material.polygonOffset,material.polygonOffsetFactor,material.polygonOffsetUnits)}function setFlipSided(flipSided){if(currentFlipSided!==flipSided){if(flipSided){gl.frontFace(gl.CW)}else{gl.frontFace(gl.CCW)}currentFlipSided=flipSided}}function setCullFace(cullFace){if(cullFace!==CullFaceNone){enable(gl.CULL_FACE);if(cullFace!==currentCullFace){if(cullFace===CullFaceBack){gl.cullFace(gl.BACK)}else if(cullFace===CullFaceFront){gl.cullFace(gl.FRONT)}else{gl.cullFace(gl.FRONT_AND_BACK)}}}else{disable(gl.CULL_FACE)}currentCullFace=cullFace}function setLineWidth(width){if(width!==currentLineWidth){if(lineWidthAvailable)gl.lineWidth(width);currentLineWidth=width}}function setPolygonOffset(polygonOffset,factor,units){if(polygonOffset){enable(gl.POLYGON_OFFSET_FILL);if(currentPolygonOffsetFactor!==factor||currentPolygonOffsetUnits!==units){gl.polygonOffset(factor,units);currentPolygonOffsetFactor=factor;currentPolygonOffsetUnits=units}}else{disable(gl.POLYGON_OFFSET_FILL)}}function setScissorTest(scissorTest){if(scissorTest){enable(gl.SCISSOR_TEST)}else{disable(gl.SCISSOR_TEST)}}function activeTexture(webglSlot){if(webglSlot===undefined)webglSlot=gl.TEXTURE0+maxTextures-1;if(currentTextureSlot!==webglSlot){gl.activeTexture(webglSlot);currentTextureSlot=webglSlot}}function bindTexture(webglType,webglTexture){if(currentTextureSlot===null){activeTexture()}var boundTexture=currentBoundTextures[currentTextureSlot];if(boundTexture===undefined){boundTexture={type:undefined,texture:undefined};currentBoundTextures[currentTextureSlot]=boundTexture}if(boundTexture.type!==webglType||boundTexture.texture!==webglTexture){gl.bindTexture(webglType,webglTexture||emptyTextures[webglType]);boundTexture.type=webglType;boundTexture.texture=webglTexture}}function compressedTexImage2D(){try{gl.compressedTexImage2D.apply(gl,arguments)}catch(error){console.error("THREE.WebGLState:",error)}}function texImage2D(){try{gl.texImage2D.apply(gl,arguments)}catch(error){console.error("THREE.WebGLState:",error)}}function scissor(scissor){if(currentScissor.equals(scissor)===false){gl.scissor(scissor.x,scissor.y,scissor.z,scissor.w);currentScissor.copy(scissor)}}function viewport(viewport){if(currentViewport.equals(viewport)===false){gl.viewport(viewport.x,viewport.y,viewport.z,viewport.w);currentViewport.copy(viewport)}}function reset(){for(var i=0;i<enabledAttributes.length;i++){if(enabledAttributes[i]===1){gl.disableVertexAttribArray(i);enabledAttributes[i]=0}}capabilities={};compressedTextureFormats=null;currentTextureSlot=null;currentBoundTextures={};currentProgram=null;currentBlending=null;currentFlipSided=null;currentCullFace=null;colorBuffer.reset();depthBuffer.reset();stencilBuffer.reset()}return{buffers:{color:colorBuffer,depth:depthBuffer,stencil:stencilBuffer},initAttributes:initAttributes,enableAttribute:enableAttribute,enableAttributeAndDivisor:enableAttributeAndDivisor,disableUnusedAttributes:disableUnusedAttributes,enable:enable,disable:disable,getCompressedTextureFormats:getCompressedTextureFormats,useProgram:useProgram,setBlending:setBlending,setMaterial:setMaterial,setFlipSided:setFlipSided,setCullFace:setCullFace,setLineWidth:setLineWidth,setPolygonOffset:setPolygonOffset,setScissorTest:setScissorTest,activeTexture:activeTexture,bindTexture:bindTexture,compressedTexImage2D:compressedTexImage2D,texImage2D:texImage2D,scissor:scissor,viewport:viewport,reset:reset}}function WebGLCapabilities(gl,extensions,parameters){var maxAnisotropy;function getMaxAnisotropy(){if(maxAnisotropy!==undefined)return maxAnisotropy;var extension=extensions.get("EXT_texture_filter_anisotropic");if(extension!==null){maxAnisotropy=gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else{maxAnisotropy=0}return maxAnisotropy}function getMaxPrecision(precision){if(precision==="highp"){if(gl.getShaderPrecisionFormat(gl.VERTEX_SHADER,gl.HIGH_FLOAT).precision>0&&gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER,gl.HIGH_FLOAT).precision>0){return"highp"}precision="mediump"}if(precision==="mediump"){if(gl.getShaderPrecisionFormat(gl.VERTEX_SHADER,gl.MEDIUM_FLOAT).precision>0&&gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER,gl.MEDIUM_FLOAT).precision>0){return"mediump"}}return"lowp"}var precision=parameters.precision!==undefined?parameters.precision:"highp";var maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn("THREE.WebGLRenderer:",precision,"not supported, using",maxPrecision,"instead.");precision=maxPrecision}var logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true&&!!extensions.get("EXT_frag_depth");var maxTextures=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);var maxVertexTextures=gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);var maxTextureSize=gl.getParameter(gl.MAX_TEXTURE_SIZE);var maxCubemapSize=gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);var maxAttributes=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);var maxVertexUniforms=gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);var maxVaryings=gl.getParameter(gl.MAX_VARYING_VECTORS);var maxFragmentUniforms=gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=!!extensions.get("OES_texture_float");var floatVertexTextures=vertexTextures&&floatFragmentTextures;return{getMaxAnisotropy:getMaxAnisotropy,getMaxPrecision:getMaxPrecision,precision:precision,logarithmicDepthBuffer:logarithmicDepthBuffer,maxTextures:maxTextures,maxVertexTextures:maxVertexTextures,maxTextureSize:maxTextureSize,maxCubemapSize:maxCubemapSize,maxAttributes:maxAttributes,maxVertexUniforms:maxVertexUniforms,maxVaryings:maxVaryings,maxFragmentUniforms:maxFragmentUniforms,vertexTextures:vertexTextures,floatFragmentTextures:floatFragmentTextures,floatVertexTextures:floatVertexTextures}}function ArrayCamera(array){PerspectiveCamera.call(this);this.cameras=array||[]}ArrayCamera.prototype=Object.assign(Object.create(PerspectiveCamera.prototype),{constructor:ArrayCamera,isArrayCamera:true});function WebVRManager(renderer){var scope=this;var device=null;var frameData=null;if("VRFrameData"in window){frameData=new window.VRFrameData}var matrixWorldInverse=new Matrix4;var standingMatrix=new Matrix4;var standingMatrixInverse=new Matrix4;var cameraL=new PerspectiveCamera;cameraL.bounds=new Vector4(0,0,.5,1);cameraL.layers.enable(1);var cameraR=new PerspectiveCamera;cameraR.bounds=new Vector4(.5,0,.5,1);cameraR.layers.enable(2);var cameraVR=new ArrayCamera([cameraL,cameraR]);cameraVR.layers.enable(1);cameraVR.layers.enable(2);var currentSize,currentPixelRatio;function onVRDisplayPresentChange(){if(device!==null&&device.isPresenting){var eyeParameters=device.getEyeParameters("left");var renderWidth=eyeParameters.renderWidth;var renderHeight=eyeParameters.renderHeight;currentPixelRatio=renderer.getPixelRatio();currentSize=renderer.getSize();renderer.setDrawingBufferSize(renderWidth*2,renderHeight,1)}else if(scope.enabled){renderer.setDrawingBufferSize(currentSize.width,currentSize.height,currentPixelRatio)}}window.addEventListener("vrdisplaypresentchange",onVRDisplayPresentChange,false);this.enabled=false;this.standing=false;this.getDevice=function(){return device};this.setDevice=function(value){if(value!==undefined)device=value};this.getCamera=function(camera){if(device===null)return camera;device.depthNear=camera.near;device.depthFar=camera.far;device.getFrameData(frameData);var pose=frameData.pose;if(pose.position!==null){camera.position.fromArray(pose.position)}else{camera.position.set(0,0,0)}if(pose.orientation!==null){camera.quaternion.fromArray(pose.orientation)}camera.updateMatrixWorld();var stageParameters=device.stageParameters;if(this.standing&&stageParameters){standingMatrix.fromArray(stageParameters.sittingToStandingTransform);standingMatrixInverse.getInverse(standingMatrix);camera.matrixWorld.multiply(standingMatrix);camera.matrixWorldInverse.multiply(standingMatrixInverse)}if(device.isPresenting===false)return camera;cameraL.near=camera.near;cameraR.near=camera.near;cameraL.far=camera.far;cameraR.far=camera.far;cameraVR.matrixWorld.copy(camera.matrixWorld);cameraVR.matrixWorldInverse.copy(camera.matrixWorldInverse);cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix);if(this.standing&&stageParameters){cameraL.matrixWorldInverse.multiply(standingMatrixInverse);cameraR.matrixWorldInverse.multiply(standingMatrixInverse)}var parent=camera.parent;if(parent!==null){matrixWorldInverse.getInverse(parent.matrixWorld);cameraL.matrixWorldInverse.multiply(matrixWorldInverse);cameraR.matrixWorldInverse.multiply(matrixWorldInverse)}cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);var layers=device.getLayers();if(layers.length){var layer=layers[0];if(layer.leftBounds!==null&&layer.leftBounds.length===4){cameraL.bounds.fromArray(layer.leftBounds)}if(layer.rightBounds!==null&&layer.rightBounds.length===4){cameraR.bounds.fromArray(layer.rightBounds)}}return cameraVR};this.getStandingMatrix=function(){return standingMatrix};this.submitFrame=function(){if(device&&device.isPresenting)device.submitFrame()};this.dispose=function(){window.removeEventListener("vrdisplaypresentchange",onVRDisplayPresentChange)}}function WebGLExtensions(gl){var extensions={};return{get:function(name){if(extensions[name]!==undefined){return extensions[name]}var extension;switch(name){case"WEBGL_depth_texture":extension=gl.getExtension("WEBGL_depth_texture")||gl.getExtension("MOZ_WEBGL_depth_texture")||gl.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":extension=gl.getExtension("EXT_texture_filter_anisotropic")||gl.getExtension("MOZ_EXT_texture_filter_anisotropic")||gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":extension=gl.getExtension("WEBGL_compressed_texture_s3tc")||gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":extension=gl.getExtension("WEBGL_compressed_texture_pvrtc")||gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":extension=gl.getExtension("WEBGL_compressed_texture_etc1");break;default:extension=gl.getExtension(name)}if(extension===null){console.warn("THREE.WebGLRenderer: "+name+" extension not supported.")}extensions[name]=extension;return extension}}}function WebGLClipping(){var scope=this,globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false,plane=new Plane,viewNormalMatrix=new Matrix3,uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){var enabled=planes.length!==0||enableLocalClipping||numGlobalPlanes!==0||localClippingEnabled;localClippingEnabled=enableLocalClipping;globalState=projectPlanes(planes,camera,0);numGlobalPlanes=planes.length;return enabled};this.beginShadows=function(){renderingShadows=true;projectPlanes(null)};this.endShadows=function(){renderingShadows=false;resetGlobalState()};this.setState=function(planes,clipIntersection,clipShadows,camera,cache,fromCache){if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){if(renderingShadows){projectPlanes(null)}else{resetGlobalState()}}else{var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4,dstArray=cache.clippingState||null;uniform.value=dstArray;dstArray=projectPlanes(planes,camera,lGlobal,fromCache);for(var i=0;i!==lGlobal;++i){dstArray[i]=globalState[i]}cache.clippingState=dstArray;this.numIntersection=clipIntersection?this.numPlanes:0;this.numPlanes+=nGlobal}};function resetGlobalState(){if(uniform.value!==globalState){uniform.value=globalState;uniform.needsUpdate=numGlobalPlanes>0}scope.numPlanes=numGlobalPlanes;scope.numIntersection=0}function projectPlanes(planes,camera,dstOffset,skipTransform){var nPlanes=planes!==null?planes.length:0,dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){var flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length<flatSize){dstArray=new Float32Array(flatSize)}for(var i=0,i4=dstOffset;i!==nPlanes;++i,i4+=4){plane.copy(planes[i]).applyMatrix4(viewMatrix,viewNormalMatrix);plane.normal.toArray(dstArray,i4);dstArray[i4+3]=plane.constant}}uniform.value=dstArray;uniform.needsUpdate=true}scope.numPlanes=nPlanes;return dstArray}}function WebGLUtils(gl,extensions){function convert(p){var extension;if(p===RepeatWrapping)return gl.REPEAT;if(p===ClampToEdgeWrapping)return gl.CLAMP_TO_EDGE;if(p===MirroredRepeatWrapping)return gl.MIRRORED_REPEAT;if(p===NearestFilter)return gl.NEAREST;if(p===NearestMipMapNearestFilter)return gl.NEAREST_MIPMAP_NEAREST;if(p===NearestMipMapLinearFilter)return gl.NEAREST_MIPMAP_LINEAR;if(p===LinearFilter)return gl.LINEAR;if(p===LinearMipMapNearestFilter)return gl.LINEAR_MIPMAP_NEAREST;if(p===LinearMipMapLinearFilter)return gl.LINEAR_MIPMAP_LINEAR;if(p===UnsignedByteType)return gl.UNSIGNED_BYTE;if(p===UnsignedShort4444Type)return gl.UNSIGNED_SHORT_4_4_4_4;if(p===UnsignedShort5551Type)return gl.UNSIGNED_SHORT_5_5_5_1;if(p===UnsignedShort565Type)return gl.UNSIGNED_SHORT_5_6_5;if(p===ByteType)return gl.BYTE;if(p===ShortType)return gl.SHORT;if(p===UnsignedShortType)return gl.UNSIGNED_SHORT;if(p===IntType)return gl.INT;if(p===UnsignedIntType)return gl.UNSIGNED_INT;if(p===FloatType)return gl.FLOAT;if(p===HalfFloatType){extension=extensions.get("OES_texture_half_float");if(extension!==null)return extension.HALF_FLOAT_OES}if(p===AlphaFormat)return gl.ALPHA;if(p===RGBFormat)return gl.RGB;if(p===RGBAFormat)return gl.RGBA;if(p===LuminanceFormat)return gl.LUMINANCE;if(p===LuminanceAlphaFormat)return gl.LUMINANCE_ALPHA;if(p===DepthFormat)return gl.DEPTH_COMPONENT;if(p===DepthStencilFormat)return gl.DEPTH_STENCIL;if(p===AddEquation)return gl.FUNC_ADD;if(p===SubtractEquation)return gl.FUNC_SUBTRACT
if(p===ReverseSubtractEquation)return gl.FUNC_REVERSE_SUBTRACT;if(p===ZeroFactor)return gl.ZERO;if(p===OneFactor)return gl.ONE;if(p===SrcColorFactor)return gl.SRC_COLOR;if(p===OneMinusSrcColorFactor)return gl.ONE_MINUS_SRC_COLOR;if(p===SrcAlphaFactor)return gl.SRC_ALPHA;if(p===OneMinusSrcAlphaFactor)return gl.ONE_MINUS_SRC_ALPHA;if(p===DstAlphaFactor)return gl.DST_ALPHA;if(p===OneMinusDstAlphaFactor)return gl.ONE_MINUS_DST_ALPHA;if(p===DstColorFactor)return gl.DST_COLOR;if(p===OneMinusDstColorFactor)return gl.ONE_MINUS_DST_COLOR;if(p===SrcAlphaSaturateFactor)return gl.SRC_ALPHA_SATURATE;if(p===RGB_S3TC_DXT1_Format||p===RGBA_S3TC_DXT1_Format||p===RGBA_S3TC_DXT3_Format||p===RGBA_S3TC_DXT5_Format){extension=extensions.get("WEBGL_compressed_texture_s3tc");if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format)return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format)return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT}}if(p===RGB_PVRTC_4BPPV1_Format||p===RGB_PVRTC_2BPPV1_Format||p===RGBA_PVRTC_4BPPV1_Format||p===RGBA_PVRTC_2BPPV1_Format){extension=extensions.get("WEBGL_compressed_texture_pvrtc");if(extension!==null){if(p===RGB_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(p===RGB_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(p===RGBA_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(p===RGBA_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}}if(p===RGB_ETC1_Format){extension=extensions.get("WEBGL_compressed_texture_etc1");if(extension!==null)return extension.COMPRESSED_RGB_ETC1_WEBGL}if(p===MinEquation||p===MaxEquation){extension=extensions.get("EXT_blend_minmax");if(extension!==null){if(p===MinEquation)return extension.MIN_EXT;if(p===MaxEquation)return extension.MAX_EXT}}if(p===UnsignedInt248Type){extension=extensions.get("WEBGL_depth_texture");if(extension!==null)return extension.UNSIGNED_INT_24_8_WEBGL}return 0}return{convert
convert}}function WebGLRenderer(parameters){console.log("THREE.WebGLRenderer",REVISION);parameters=parameters||{};var _canvas=parameters.canvas!==undefined?parameters.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),_context=parameters.context!==undefined?parameters.context:null,_alpha=parameters.alpha!==undefined?parameters.alpha:false,_depth=parameters.depth!==undefined?parameters.depth:true,_stencil=parameters.stencil!==undefined?parameters.stencil:true,_antialias=parameters.antialias!==undefined?parameters.antialias:false,_premultipliedAlpha=parameters.premultipliedAlpha!==undefined?parameters.premultipliedAlpha:true,_preserveDrawingBuffer=parameters.preserveDrawingBuffer!==undefined?parameters.preserveDrawingBuffer:false;var lightsArray=[];var shadowsArray=[];var currentRenderList=null;var spritesArray=[];var flaresArray=[];this.domElement=_canvas;this.context=null;this.autoClear=true;this.autoClearColor=true;this.autoClearDepth=true;this.autoClearStencil=true;this.sortObjects=true;this.clippingPlanes=[];this.localClippingEnabled=false;this.gammaFactor=2;this.gammaInput=false;this.gammaOutput=false;this.physicallyCorrectLights=false;this.toneMapping=LinearToneMapping;this.toneMappingExposure=1;this.toneMappingWhitePoint=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var _this=this,_isContextLost=false,_currentRenderTarget=null,_currentFramebuffer=null,_currentMaterialId=-1,_currentGeometryProgram="",_currentCamera=null,_currentArrayCamera=null,_currentViewport=new Vector4,_currentScissor=new Vector4,_currentScissorTest=null,_usedTextureUnits=0,_width=_canvas.width,_height=_canvas.height,_pixelRatio=1,_viewport=new Vector4(0,0,_width,_height),_scissor=new Vector4(0,0,_width,_height),_scissorTest=false,_frustum=new Frustum,_clipping=new WebGLClipping,_clippingEnabled=false,_localClippingEnabled=false,_projScreenMatrix=new Matrix4,_vector3=new Vector3,_infoMemory={geometries:0,textures:0},_infoRender={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:_infoRender,memory:_infoMemory,programs:null};function getTargetPixelRatio(){return _currentRenderTarget===null?_pixelRatio:1}var _gl;try{var contextAttributes={alpha:_alpha,depth:_depth,stencil:_stencil,antialias:_antialias,premultipliedAlpha:_premultipliedAlpha,preserveDrawingBuffer:_preserveDrawingBuffer};_gl=_context||_canvas.getContext("webgl",contextAttributes)||_canvas.getContext("experimental-webgl",contextAttributes);if(_gl===null){if(_canvas.getContext("webgl")!==null){throw"Error creating WebGL context with your selected attributes."}else{throw"Error creating WebGL context."}}if(_gl.getShaderPrecisionFormat===undefined){_gl.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}}}_canvas.addEventListener("webglcontextlost",onContextLost,false);_canvas.addEventListener("webglcontextrestored",onContextRestore,false)}catch(error){console.error("THREE.WebGLRenderer: "+error)}var extensions,capabilities,state;var properties,textures,attributes,geometries,objects,lights;var programCache,renderLists;var background,morphtargets,bufferRenderer,indexedBufferRenderer;var flareRenderer,spriteRenderer;var utils;function initGLContext(){extensions=new WebGLExtensions(_gl);extensions.get("WEBGL_depth_texture");extensions.get("OES_texture_float");extensions.get("OES_texture_float_linear");extensions.get("OES_texture_half_float");extensions.get("OES_texture_half_float_linear");extensions.get("OES_standard_derivatives");extensions.get("ANGLE_instanced_arrays");if(extensions.get("OES_element_index_uint")){BufferGeometry.MaxIndex=4294967296}utils=new WebGLUtils(_gl,extensions);capabilities=new WebGLCapabilities(_gl,extensions,parameters);state=new WebGLState(_gl,extensions,utils);state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio));state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio));properties=new WebGLProperties;textures=new WebGLTextures(_gl,extensions,state,properties,capabilities,utils,_infoMemory);attributes=new WebGLAttributes(_gl);geometries=new WebGLGeometries(_gl,attributes,_infoMemory);objects=new WebGLObjects(geometries,_infoRender);morphtargets=new WebGLMorphtargets(_gl);programCache=new WebGLPrograms(_this,extensions,capabilities);lights=new WebGLLights;renderLists=new WebGLRenderLists;background=new WebGLBackground(_this,state,geometries,_premultipliedAlpha);bufferRenderer=new WebGLBufferRenderer(_gl,extensions,_infoRender);indexedBufferRenderer=new WebGLIndexedBufferRenderer(_gl,extensions,_infoRender);flareRenderer=new WebGLFlareRenderer(_this,_gl,state,textures,capabilities);spriteRenderer=new WebGLSpriteRenderer(_this,_gl,state,textures,capabilities);_this.info.programs=programCache.programs;_this.context=_gl;_this.capabilities=capabilities;_this.extensions=extensions;_this.properties=properties;_this.renderLists=renderLists;_this.state=state}initGLContext();var vr=new WebVRManager(_this);this.vr=vr;var shadowMap=new WebGLShadowMap(_this,objects,capabilities.maxTextureSize);this.shadowMap=shadowMap;this.getContext=function(){return _gl};this.getContextAttributes=function(){return _gl.getContextAttributes()};this.forceContextLoss=function(){var extension=extensions.get("WEBGL_lose_context");if(extension)extension.loseContext()};this.forceContextRestore=function(){var extension=extensions.get("WEBGL_lose_context");if(extension)extension.restoreContext()};this.getPixelRatio=function(){return _pixelRatio};this.setPixelRatio=function(value){if(value===undefined)return;_pixelRatio=value;this.setSize(_width,_height,false)};this.getSize=function(){return{width:_width,height:_height}};this.setSize=function(width,height,updateStyle){var device=vr.getDevice();if(device&&device.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}_width=width;_height=height;_canvas.width=width*_pixelRatio;_canvas.height=height*_pixelRatio;if(updateStyle!==false){_canvas.style.width=width+"px";_canvas.style.height=height+"px"}this.setViewport(0,0,width,height)};this.getDrawingBufferSize=function(){return{width:_width*_pixelRatio,height:_height*_pixelRatio}};this.setDrawingBufferSize=function(width,height,pixelRatio){_width=width;_height=height;_pixelRatio=pixelRatio;_canvas.width=width*pixelRatio;_canvas.height=height*pixelRatio;this.setViewport(0,0,width,height)};this.setViewport=function(x,y,width,height){_viewport.set(x,_height-y-height,width,height);state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio))};this.setScissor=function(x,y,width,height){_scissor.set(x,_height-y-height,width,height);state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio))};this.setScissorTest=function(boolean){state.setScissorTest(_scissorTest=boolean)};this.getClearColor=background.getClearColor;this.setClearColor=background.setClearColor;this.getClearAlpha=background.getClearAlpha;this.setClearAlpha=background.setClearAlpha;this.clear=function(color,depth,stencil){var bits=0;if(color===undefined||color)bits|=_gl.COLOR_BUFFER_BIT;if(depth===undefined||depth)bits|=_gl.DEPTH_BUFFER_BIT;if(stencil===undefined||stencil)bits|=_gl.STENCIL_BUFFER_BIT;_gl.clear(bits)};this.clearColor=function(){this.clear(true,false,false)};this.clearDepth=function(){this.clear(false,true,false)};this.clearStencil=function(){this.clear(false,false,true)};this.clearTarget=function(renderTarget,color,depth,stencil){this.setRenderTarget(renderTarget);this.clear(color,depth,stencil)};this.dispose=function(){_canvas.removeEventListener("webglcontextlost",onContextLost,false);_canvas.removeEventListener("webglcontextrestored",onContextRestore,false);renderLists.dispose();vr.dispose()};function onContextLost(event){event.preventDefault();console.log("THREE.WebGLRenderer: Context Lost.");_isContextLost=true}function onContextRestore(event){console.log("THREE.WebGLRenderer: Context Restored.");_isContextLost=false;initGLContext()}function onMaterialDispose(event){var material=event.target;material.removeEventListener("dispose",onMaterialDispose);deallocateMaterial(material)}function deallocateMaterial(material){releaseMaterialProgramReference(material);properties.remove(material)}function releaseMaterialProgramReference(material){var programInfo=properties.get(material).program;material.program=undefined;if(programInfo!==undefined){programCache.releaseProgram(programInfo)}}function renderObjectImmediate(object,program,material){object.render(function(object){_this.renderBufferImmediate(object,program,material)})}this.renderBufferImmediate=function(object,program,material){state.initAttributes();var buffers=properties.get(object);if(object.hasPositions&&!buffers.position)buffers.position=_gl.createBuffer();if(object.hasNormals&&!buffers.normal)buffers.normal=_gl.createBuffer();if(object.hasUvs&&!buffers.uv)buffers.uv=_gl.createBuffer();if(object.hasColors&&!buffers.color)buffers.color=_gl.createBuffer();var programAttributes=program.getAttributes();if(object.hasPositions){_gl.bindBuffer(_gl.ARRAY_BUFFER,buffers.position);_gl.bufferData(_gl.ARRAY_BUFFER,object.positionArray,_gl.DYNAMIC_DRAW);state.enableAttribute(programAttributes.position);_gl.vertexAttribPointer(programAttributes.position,3,_gl.FLOAT,false,0,0)}if(object.hasNormals){_gl.bindBuffer(_gl.ARRAY_BUFFER,buffers.normal);if(!material.isMeshPhongMaterial&&!material.isMeshStandardMaterial&&!material.isMeshNormalMaterial&&material.flatShading===true){for(var i=0,l=object.count*3;i<l;i+=9){var array=object.normalArray;var nx=(array[i+0]+array[i+3]+array[i+6])/3;var ny=(array[i+1]+array[i+4]+array[i+7])/3;var nz=(array[i+2]+array[i+5]+array[i+8])/3;array[i+0]=nx;array[i+1]=ny;array[i+2]=nz;array[i+3]=nx;array[i+4]=ny;array[i+5]=nz;array[i+6]=nx;array[i+7]=ny;array[i+8]=nz}}_gl.bufferData(_gl.ARRAY_BUFFER,object.normalArray,_gl.DYNAMIC_DRAW);state.enableAttribute(programAttributes.normal);_gl.vertexAttribPointer(programAttributes.normal,3,_gl.FLOAT,false,0,0)}if(object.hasUvs&&material.map){_gl.bindBuffer(_gl.ARRAY_BUFFER,buffers.uv);_gl.bufferData(_gl.ARRAY_BUFFER,object.uvArray,_gl.DYNAMIC_DRAW);state.enableAttribute(programAttributes.uv);_gl.vertexAttribPointer(programAttributes.uv,2,_gl.FLOAT,false,0,0)}if(object.hasColors&&material.vertexColors!==NoColors){_gl.bindBuffer(_gl.ARRAY_BUFFER,buffers.color);_gl.bufferData(_gl.ARRAY_BUFFER,object.colorArray,_gl.DYNAMIC_DRAW);state.enableAttribute(programAttributes.color);_gl.vertexAttribPointer(programAttributes.color,3,_gl.FLOAT,false,0,0)}state.disableUnusedAttributes();_gl.drawArrays(_gl.TRIANGLES,0,object.count);object.count=0};this.renderBufferDirect=function(camera,fog,geometry,material,object,group){state.setMaterial(material);var program=setProgram(camera,fog,material,object);var geometryProgram=geometry.id+"_"+program.id+"_"+(material.wireframe===true);var updateBuffers=false;if(geometryProgram!==_currentGeometryProgram){_currentGeometryProgram=geometryProgram;updateBuffers=true}if(object.morphTargetInfluences){morphtargets.update(object,geometry,material,program);updateBuffers=true}var index=geometry.index;var position=geometry.attributes.position;var rangeFactor=1;if(material.wireframe===true){index=geometries.getWireframeAttribute(geometry);rangeFactor=2}var attribute;var renderer=bufferRenderer;if(index!==null){attribute=attributes.get(index);renderer=indexedBufferRenderer;renderer.setIndex(attribute)}if(updateBuffers){setupVertexAttributes(material,program,geometry);if(index!==null){_gl.bindBuffer(_gl.ELEMENT_ARRAY_BUFFER,attribute.buffer)}}var dataCount=0;if(index!==null){dataCount=index.count}else if(position!==undefined){dataCount=position.count}var rangeStart=geometry.drawRange.start*rangeFactor;var rangeCount=geometry.drawRange.count*rangeFactor;var groupStart=group!==null?group.start*rangeFactor:0;var groupCount=group!==null?group.count*rangeFactor:Infinity;var drawStart=Math.max(rangeStart,groupStart);var drawEnd=Math.min(dataCount,rangeStart+rangeCount,groupStart+groupCount)-1;var drawCount=Math.max(0,drawEnd-drawStart+1);if(drawCount===0)return;if(object.isMesh){if(material.wireframe===true){state.setLineWidth(material.wireframeLinewidth*getTargetPixelRatio());renderer.setMode(_gl.LINES)}else{switch(object.drawMode){case TrianglesDrawMode:renderer.setMode(_gl.TRIANGLES);break;case TriangleStripDrawMode:renderer.setMode(_gl.TRIANGLE_STRIP);break;case TriangleFanDrawMode:renderer.setMode(_gl.TRIANGLE_FAN);break}}}else if(object.isLine){var lineWidth=material.linewidth;if(lineWidth===undefined)lineWidth=1;state.setLineWidth(lineWidth*getTargetPixelRatio());if(object.isLineSegments){renderer.setMode(_gl.LINES)}else if(object.isLineLoop){renderer.setMode(_gl.LINE_LOOP)}else{renderer.setMode(_gl.LINE_STRIP)}}else if(object.isPoints){renderer.setMode(_gl.POINTS)}if(geometry&&geometry.isInstancedBufferGeometry){if(geometry.maxInstancedCount>0){renderer.renderInstances(geometry,drawStart,drawCount)}}else{renderer.render(drawStart,drawCount)}};function setupVertexAttributes(material,program,geometry,startIndex){if(geometry&&geometry.isInstancedBufferGeometry){if(extensions.get("ANGLE_instanced_arrays")===null){console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}}if(startIndex===undefined)startIndex=0;state.initAttributes();var geometryAttributes=geometry.attributes;var programAttributes=program.getAttributes();var materialDefaultAttributeValues=material.defaultAttributeValues;for(var name in programAttributes){var programAttribute=programAttributes[name];if(programAttribute>=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;var bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){var data=geometryAttribute.data;var stride=data.stride;var offset=geometryAttribute.offset;if(data&&data.isInstancedInterleavedBuffer){state.enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry.maxInstancedCount===undefined){geometry.maxInstancedCount=data.meshPerAttribute*data.count}}else{state.enableAttribute(programAttribute)}_gl.bindBuffer(_gl.ARRAY_BUFFER,buffer);_gl.vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,(startIndex*stride+offset)*bytesPerElement)}else{if(geometryAttribute.isInstancedBufferAttribute){state.enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry.maxInstancedCount===undefined){geometry.maxInstancedCount=geometryAttribute.meshPerAttribute*geometryAttribute.count}}else{state.enableAttribute(programAttribute)}_gl.bindBuffer(_gl.ARRAY_BUFFER,buffer);_gl.vertexAttribPointer(programAttribute,size,type,normalized,0,startIndex*size*bytesPerElement)}}else if(materialDefaultAttributeValues!==undefined){var value=materialDefaultAttributeValues[name];if(value!==undefined){switch(value.length){case 2:_gl.vertexAttrib2fv(programAttribute,value);break;case 3:_gl.vertexAttrib3fv(programAttribute,value);break;case 4:_gl.vertexAttrib4fv(programAttribute,value);break;default:_gl.vertexAttrib1fv(programAttribute,value)}}}}}state.disableUnusedAttributes()}this.compile=function(scene,camera){lightsArray.length=0;shadowsArray.length=0;scene.traverse(function(object){if(object.isLight){lightsArray.push(object);if(object.castShadow){shadowsArray.push(object)}}});lights.setup(lightsArray,shadowsArray,camera);scene.traverse(function(object){if(object.material){if(Array.isArray(object.material)){for(var i=0;i<object.material.length;i++){initMaterial(object.material[i],scene.fog,object)}}else{initMaterial(object.material,scene.fog,object)}}})};var isAnimating=false;var onAnimationFrame=null;function start(){if(isAnimating)return;(vr.getDevice()||window).requestAnimationFrame(loop)}function loop(time){if(onAnimationFrame!==null)onAnimationFrame(time);(vr.getDevice()||window).requestAnimationFrame(loop)}this.animate=function(callback){onAnimationFrame=callback;start()};this.render=function(scene,camera,renderTarget,forceClear){if(!(camera&&camera.isCamera)){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(_isContextLost)return;_currentGeometryProgram="";_currentMaterialId=-1;_currentCamera=null;if(scene.autoUpdate===true)scene.updateMatrixWorld();if(camera.parent===null)camera.updateMatrixWorld();if(vr.enabled){camera=vr.getCamera(camera)}_projScreenMatrix.multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse);_frustum.setFromMatrix(_projScreenMatrix);lightsArray.length=0;shadowsArray.length=0;spritesArray.length=0;flaresArray.length=0;_localClippingEnabled=this.localClippingEnabled;_clippingEnabled=_clipping.init(this.clippingPlanes,_localClippingEnabled,camera);currentRenderList=renderLists.get(scene,camera);currentRenderList.init();projectObject(scene,camera,_this.sortObjects);if(_this.sortObjects===true){currentRenderList.sort()}if(_clippingEnabled)_clipping.beginShadows();shadowMap.render(shadowsArray,scene,camera);lights.setup(lightsArray,shadowsArray,camera);if(_clippingEnabled)_clipping.endShadows();_infoRender.frame++;_infoRender.calls=0;_infoRender.vertices=0;_infoRender.faces=0;_infoRender.points=0;if(renderTarget===undefined){renderTarget=null}this.setRenderTarget(renderTarget);background.render(currentRenderList,scene,camera,forceClear);var opaqueObjects=currentRenderList.opaque;var transparentObjects=currentRenderList.transparent;if(scene.overrideMaterial){var overrideMaterial=scene.overrideMaterial;if(opaqueObjects.length)renderObjects(opaqueObjects,scene,camera,overrideMaterial);if(transparentObjects.length)renderObjects(transparentObjects,scene,camera,overrideMaterial)}else{if(opaqueObjects.length)renderObjects(opaqueObjects,scene,camera);if(transparentObjects.length)renderObjects(transparentObjects,scene,camera)}spriteRenderer.render(spritesArray,scene,camera);flareRenderer.render(flaresArray,scene,camera,_currentViewport);if(renderTarget){textures.updateRenderTargetMipmap(renderTarget)}state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false);if(vr.enabled){vr.submitFrame()}};function projectObject(object,camera,sortObjects){if(!object.visible)return;var visible=object.layers.test(camera.layers);if(visible){if(object.isLight){lightsArray.push(object);if(object.castShadow){shadowsArray.push(object)}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){spritesArray.push(object)}}else if(object.isLensFlare){flaresArray.push(object)}else if(object.isImmediateRenderObject){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix)}currentRenderList.push(object,null,object.material,_vector3.z,null)}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){object.skeleton.update()}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix)}var geometry=objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var i=0,l=groups.length;i<l;i++){var group=groups[i];var groupMaterial=material[group.materialIndex];if(groupMaterial&&groupMaterial.visible){currentRenderList.push(object,geometry,groupMaterial,_vector3.z,group)}}}else if(material.visible){currentRenderList.push(object,geometry,material,_vector3.z,null)}}}}var children=object.children;for(var i=0,l=children.length;i<l;i++){projectObject(children[i],camera,sortObjects)}}function renderObjects(renderList,scene,camera,overrideMaterial){for(var i=0,l=renderList.length;i<l;i++){var renderItem=renderList[i];var object=renderItem.object;var geometry=renderItem.geometry;var material=overrideMaterial===undefined?renderItem.material:overrideMaterial;var group=renderItem.group;if(camera.isArrayCamera){_currentArrayCamera=camera;var cameras=camera.cameras;for(var j=0,jl=cameras.length;j<jl;j++){var camera2=cameras[j];if(object.layers.test(camera2.layers)){var bounds=camera2.bounds;var x=bounds.x*_width;var y=bounds.y*_height;var width=bounds.z*_width;var height=bounds.w*_height;state.viewport(_currentViewport.set(x,y,width,height).multiplyScalar(_pixelRatio));renderObject(object,scene,camera2,geometry,material,group)}}}else{_currentArrayCamera=null;renderObject(object,scene,camera,geometry,material,group)}}}function renderObject(object,scene,camera,geometry,material,group){object.onBeforeRender(_this,scene,camera,geometry,material,group);object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse,object.matrixWorld);object.normalMatrix.getNormalMatrix(object.modelViewMatrix);if(object.isImmediateRenderObject){state.setMaterial(material);var program=setProgram(camera,scene.fog,material,object);_currentGeometryProgram="";renderObjectImmediate(object,program,material)}else{_this.renderBufferDirect(camera,scene.fog,geometry,material,object,group)}object.onAfterRender(_this,scene,camera,geometry,material,group)}function initMaterial(material,fog,object){var materialProperties=properties.get(material);var parameters=programCache.getParameters(material,lights.state,shadowsArray,fog,_clipping.numPlanes,_clipping.numIntersection,object);var code=programCache.getProgramCode(material,parameters);var program=materialProperties.program;var programChange=true;if(program===undefined){material.addEventListener("dispose",onMaterialDispose)}else if(program.code!==code){releaseMaterialProgramReference(material)}else if(parameters.shaderID!==undefined){return}else{programChange=false}if(programChange){if(parameters.shaderID){var shader=ShaderLib[parameters.shaderID];materialProperties.shader={name:material.type,uniforms:UniformsUtils.clone(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader}}else{materialProperties.shader={name:material.type,uniforms:material.uniforms,vertexShader:material.vertexShader,fragmentShader:material.fragmentShader}}material.onBeforeCompile(materialProperties.shader);program=programCache.acquireProgram(material,materialProperties.shader,parameters,code);materialProperties.program=program;material.program=program}var programAttributes=program.getAttributes();if(material.morphTargets){material.numSupportedMorphTargets=0;for(var i=0;i<_this.maxMorphTargets;i++){if(programAttributes["morphTarget"+i]>=0){material.numSupportedMorphTargets++}}}if(material.morphNormals){material.numSupportedMorphNormals=0;for(var i=0;i<_this.maxMorphNormals;i++){if(programAttributes["morphNormal"+i]>=0){material.numSupportedMorphNormals++}}}var uniforms=materialProperties.shader.uniforms;if(!material.isShaderMaterial&&!material.isRawShaderMaterial||material.clipping===true){materialProperties.numClippingPlanes=_clipping.numPlanes;materialProperties.numIntersection=_clipping.numIntersection;uniforms.clippingPlanes=_clipping.uniform}materialProperties.fog=fog;materialProperties.lightsHash=lights.state.hash;if(material.lights){uniforms.ambientLightColor.value=lights.state.ambient;uniforms.directionalLights.value=lights.state.directional;uniforms.spotLights.value=lights.state.spot;uniforms.rectAreaLights.value=lights.state.rectArea;uniforms.pointLights.value=lights.state.point;uniforms.hemisphereLights.value=lights.state.hemi;uniforms.directionalShadowMap.value=lights.state.directionalShadowMap;uniforms.directionalShadowMatrix.value=lights.state.directionalShadowMatrix;uniforms.spotShadowMap.value=lights.state.spotShadowMap;uniforms.spotShadowMatrix.value=lights.state.spotShadowMatrix;uniforms.pointShadowMap.value=lights.state.pointShadowMap;uniforms.pointShadowMatrix.value=lights.state.pointShadowMatrix}var progUniforms=materialProperties.program.getUniforms(),uniformsList=WebGLUniforms.seqWithValue(progUniforms.seq,uniforms);materialProperties.uniformsList=uniformsList}function setProgram(camera,fog,material,object){_usedTextureUnits=0;var materialProperties=properties.get(material);if(_clippingEnabled){if(_localClippingEnabled||camera!==_currentCamera){var useCache=camera===_currentCamera&&material.id===_currentMaterialId;_clipping.setState(material.clippingPlanes,material.clipIntersection,material.clipShadows,camera,materialProperties,useCache)}}if(material.needsUpdate===false){if(materialProperties.program===undefined){material.needsUpdate=true}else if(material.fog&&materialProperties.fog!==fog){material.needsUpdate=true}else if(material.lights&&materialProperties.lightsHash!==lights.state.hash){material.needsUpdate=true}else if(materialProperties.numClippingPlanes!==undefined&&(materialProperties.numClippingPlanes!==_clipping.numPlanes||materialProperties.numIntersection!==_clipping.numIntersection)){material.needsUpdate=true}}if(material.needsUpdate){initMaterial(material,fog,object);material.needsUpdate=false}var refreshProgram=false;var refreshMaterial=false;var refreshLights=false;var program=materialProperties.program,p_uniforms=program.getUniforms(),m_uniforms=materialProperties.shader.uniforms;if(state.useProgram(program.program)){refreshProgram=true;refreshMaterial=true;refreshLights=true}if(material.id!==_currentMaterialId){_currentMaterialId=material.id;refreshMaterial=true}if(refreshProgram||camera!==_currentCamera){p_uniforms.setValue(_gl,"projectionMatrix",camera.projectionMatrix);if(capabilities.logarithmicDepthBuffer){p_uniforms.setValue(_gl,"logDepthBufFC",2/(Math.log(camera.far+1)/Math.LN2))}if(_currentCamera!==(_currentArrayCamera||camera)){_currentCamera=_currentArrayCamera||camera;refreshMaterial=true;refreshLights=true}if(material.isShaderMaterial||material.isMeshPhongMaterial||material.isMeshStandardMaterial||material.envMap){var uCamPos=p_uniforms.map.cameraPosition;if(uCamPos!==undefined){uCamPos.setValue(_gl,_vector3.setFromMatrixPosition(camera.matrixWorld))}}if(material.isMeshPhongMaterial||material.isMeshLambertMaterial||material.isMeshBasicMaterial||material.isMeshStandardMaterial||material.isShaderMaterial||material.skinning){p_uniforms.setValue(_gl,"viewMatrix",camera.matrixWorldInverse)}}if(material.skinning){p_uniforms.setOptional(_gl,object,"bindMatrix");p_uniforms.setOptional(_gl,object,"bindMatrixInverse");var skeleton=object.skeleton;if(skeleton){var bones=skeleton.bones;if(capabilities.floatVertexTextures){if(skeleton.boneTexture===undefined){var size=Math.sqrt(bones.length*4);size=_Math.nextPowerOfTwo(Math.ceil(size));size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);boneMatrices.set(skeleton.boneMatrices);var boneTexture=new DataTexture(boneMatrices,size,size,RGBAFormat,FloatType);skeleton.boneMatrices=boneMatrices;skeleton.boneTexture=boneTexture;skeleton.boneTextureSize=size}p_uniforms.setValue(_gl,"boneTexture",skeleton.boneTexture);p_uniforms.setValue(_gl,"boneTextureSize",skeleton.boneTextureSize)}else{p_uniforms.setOptional(_gl,skeleton,"boneMatrices")}}}if(refreshMaterial){p_uniforms.setValue(_gl,"toneMappingExposure",_this.toneMappingExposure);p_uniforms.setValue(_gl,"toneMappingWhitePoint",_this.toneMappingWhitePoint);if(material.lights){markUniformsLightsNeedsUpdate(m_uniforms,refreshLights)}if(fog&&material.fog){refreshUniformsFog(m_uniforms,fog)}if(material.isMeshBasicMaterial){refreshUniformsCommon(m_uniforms,material)}else if(material.isMeshLambertMaterial){refreshUniformsCommon(m_uniforms,material);refreshUniformsLambert(m_uniforms,material)}else if(material.isMeshPhongMaterial){refreshUniformsCommon(m_uniforms,material);if(material.isMeshToonMaterial){refreshUniformsToon(m_uniforms,material)}else{refreshUniformsPhong(m_uniforms,material)}}else if(material.isMeshStandardMaterial){refreshUniformsCommon(m_uniforms,material);if(material.isMeshPhysicalMaterial){refreshUniformsPhysical(m_uniforms,material)}else{refreshUniformsStandard(m_uniforms,material)}}else if(material.isMeshDepthMaterial){refreshUniformsCommon(m_uniforms,material);refreshUniformsDepth(m_uniforms,material)}else if(material.isMeshDistanceMaterial){refreshUniformsCommon(m_uniforms,material);refreshUniformsDistance(m_uniforms,material)}else if(material.isMeshNormalMaterial){refreshUniformsCommon(m_uniforms,material);refreshUniformsNormal(m_uniforms,material)}else if(material.isLineBasicMaterial){refreshUniformsLine(m_uniforms,material);if(material.isLineDashedMaterial){refreshUniformsDash(m_uniforms,material)}}else if(material.isPointsMaterial){refreshUniformsPoints(m_uniforms,material)}else if(material.isShadowMaterial){m_uniforms.color.value=material.color;m_uniforms.opacity.value=material.opacity}if(m_uniforms.ltcMat!==undefined)m_uniforms.ltcMat.value=UniformsLib.LTC_MAT_TEXTURE;if(m_uniforms.ltcMag!==undefined)m_uniforms.ltcMag.value=UniformsLib.LTC_MAG_TEXTURE;WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,_this)}p_uniforms.setValue(_gl,"modelViewMatrix",object.modelViewMatrix);p_uniforms.setValue(_gl,"normalMatrix",object.normalMatrix);p_uniforms.setValue(_gl,"modelMatrix",object.matrixWorld);return program}function refreshUniformsCommon(uniforms,material){uniforms.opacity.value=material.opacity;if(material.color){uniforms.diffuse.value=material.color}if(material.emissive){uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity)}if(material.map){uniforms.map.value=material.map}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap}if(material.specularMap){uniforms.specularMap.value=material.specularMap}if(material.envMap){uniforms.envMap.value=material.envMap;uniforms.flipEnvMap.value=!(material.envMap&&material.envMap.isCubeTexture)?1:-1;uniforms.reflectivity.value=material.reflectivity
uniforms.refractionRatio.value=material.refractionRatio}if(material.lightMap){uniforms.lightMap.value=material.lightMap;uniforms.lightMapIntensity.value=material.lightMapIntensity}if(material.aoMap){uniforms.aoMap.value=material.aoMap;uniforms.aoMapIntensity.value=material.aoMapIntensity}var uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.specularMap){uvScaleMap=material.specularMap}else if(material.displacementMap){uvScaleMap=material.displacementMap}else if(material.normalMap){uvScaleMap=material.normalMap}else if(material.bumpMap){uvScaleMap=material.bumpMap}else if(material.roughnessMap){uvScaleMap=material.roughnessMap}else if(material.metalnessMap){uvScaleMap=material.metalnessMap}else if(material.alphaMap){uvScaleMap=material.alphaMap}else if(material.emissiveMap){uvScaleMap=material.emissiveMap}if(uvScaleMap!==undefined){if(uvScaleMap.isWebGLRenderTarget){uvScaleMap=uvScaleMap.texture}var offset=uvScaleMap.offset;var repeat=uvScaleMap.repeat;uniforms.offsetRepeat.value.set(offset.x,offset.y,repeat.x,repeat.y)}}function refreshUniformsLine(uniforms,material){uniforms.diffuse.value=material.color;uniforms.opacity.value=material.opacity}function refreshUniformsDash(uniforms,material){uniforms.dashSize.value=material.dashSize;uniforms.totalSize.value=material.dashSize+material.gapSize;uniforms.scale.value=material.scale}function refreshUniformsPoints(uniforms,material){uniforms.diffuse.value=material.color;uniforms.opacity.value=material.opacity;uniforms.size.value=material.size*_pixelRatio;uniforms.scale.value=_height*.5;uniforms.map.value=material.map;if(material.map!==null){var offset=material.map.offset;var repeat=material.map.repeat;uniforms.offsetRepeat.value.set(offset.x,offset.y,repeat.x,repeat.y)}}function refreshUniformsFog(uniforms,fog){uniforms.fogColor.value=fog.color;if(fog.isFog){uniforms.fogNear.value=fog.near;uniforms.fogFar.value=fog.far}else if(fog.isFogExp2){uniforms.fogDensity.value=fog.density}}function refreshUniformsLambert(uniforms,material){if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap}}function refreshUniformsPhong(uniforms,material){uniforms.specular.value=material.specular;uniforms.shininess.value=Math.max(material.shininess,1e-4);if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale)}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias}}function refreshUniformsToon(uniforms,material){refreshUniformsPhong(uniforms,material);if(material.gradientMap){uniforms.gradientMap.value=material.gradientMap}}function refreshUniformsStandard(uniforms,material){uniforms.roughness.value=material.roughness;uniforms.metalness.value=material.metalness;if(material.roughnessMap){uniforms.roughnessMap.value=material.roughnessMap}if(material.metalnessMap){uniforms.metalnessMap.value=material.metalnessMap}if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale)}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias}if(material.envMap){uniforms.envMapIntensity.value=material.envMapIntensity}}function refreshUniformsPhysical(uniforms,material){uniforms.clearCoat.value=material.clearCoat;uniforms.clearCoatRoughness.value=material.clearCoatRoughness;refreshUniformsStandard(uniforms,material)}function refreshUniformsDepth(uniforms,material){if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias}}function refreshUniformsDistance(uniforms,material){if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias}uniforms.referencePosition.value.copy(material.referencePosition);uniforms.nearDistance.value=material.nearDistance;uniforms.farDistance.value=material.farDistance}function refreshUniformsNormal(uniforms,material){if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale)}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias}}function markUniformsLightsNeedsUpdate(uniforms,value){uniforms.ambientLightColor.needsUpdate=value;uniforms.directionalLights.needsUpdate=value;uniforms.pointLights.needsUpdate=value;uniforms.spotLights.needsUpdate=value;uniforms.rectAreaLights.needsUpdate=value;uniforms.hemisphereLights.needsUpdate=value}this.setFaceCulling=function(cullFace,frontFaceDirection){state.setCullFace(cullFace);state.setFlipSided(frontFaceDirection===FrontFaceDirectionCW)};function allocTextureUnit(){var textureUnit=_usedTextureUnits;if(textureUnit>=capabilities.maxTextures){console.warn("THREE.WebGLRenderer
Trying to use "+textureUnit+" texture units while this GPU supports only "+capabilities.maxTextures)}_usedTextureUnits+=1;return textureUnit}this.allocTextureUnit=allocTextureUnit;this.setTexture2D=function(){var warned=false;return function setTexture2D(texture,slot){if(texture&&texture.isWebGLRenderTarget){if(!warned){console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead.");warned=true}texture=texture.texture}textures.setTexture2D(texture,slot)}}();this.setTexture=function(){var warned=false;return function setTexture(texture,slot){if(!warned){console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead.");warned=true}textures.setTexture2D(texture,slot)}}();this.setTextureCube=function(){var warned=false;return function setTextureCube(texture,slot){if(texture&&texture.isWebGLRenderTargetCube){if(!warned){console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead.");warned=true}texture=texture.texture}if(texture&&texture.isCubeTexture||Array.isArray(texture.image)&&texture.image.length===6){textures.setTextureCube(texture,slot)}else{textures.setTextureCubeDynamic(texture,slot)}}}();this.getRenderTarget=function(){return _currentRenderTarget};this.setRenderTarget=function(renderTarget){_currentRenderTarget=renderTarget;if(renderTarget&&properties.get(renderTarget).__webglFramebuffer===undefined){textures.setupRenderTarget(renderTarget)}var framebuffer=null;var isCube=false;if(renderTarget){var __webglFramebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLRenderTargetCube){framebuffer=__webglFramebuffer[renderTarget.activeCubeFace];isCube=true}else{framebuffer=__webglFramebuffer}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest}else{_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio);_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio);_currentScissorTest=_scissorTest}if(_currentFramebuffer!==framebuffer){_gl.bindFramebuffer(_gl.FRAMEBUFFER,framebuffer);_currentFramebuffer=framebuffer}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){var textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(_gl.FRAMEBUFFER,_gl.COLOR_ATTACHMENT0,_gl.TEXTURE_CUBE_MAP_POSITIVE_X+renderTarget.activeCubeFace,textureProperties.__webglTexture,renderTarget.activeMipMapLevel)}};this.readRenderTargetPixels=function(renderTarget,x,y,width,height,buffer){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(_gl.FRAMEBUFFER,framebuffer);restore=true}try{var texture=renderTarget.texture;var textureFormat=texture.format;var textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE)&&!(textureType===FloatType&&(extensions.get("OES_texture_float")||extensions.get("WEBGL_color_buffer_float")))&&!(textureType===HalfFloatType&&extensions.get("EXT_color_buffer_half_float"))){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(_gl.checkFramebufferStatus(_gl.FRAMEBUFFER)===_gl.FRAMEBUFFER_COMPLETE){if(x>=0&&x<=renderTarget.width-width&&(y>=0&&y<=renderTarget.height-height)){_gl.readPixels(x,y,width,height,utils.convert(textureFormat),utils.convert(textureType),buffer)}}else{console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}}finally{if(restore){_gl.bindFramebuffer(_gl.FRAMEBUFFER,_currentFramebuffer)}}}}}function FogExp2(color,density){this.name="";this.color=new Color(color);this.density=density!==undefined?density:25e-5}FogExp2.prototype.isFogExp2=true;FogExp2.prototype.clone=function(){return new FogExp2(this.color.getHex(),this.density)};FogExp2.prototype.toJSON=function(meta){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};function Fog(color,near,far){this.name="";this.color=new Color(color);this.near=near!==undefined?near:1;this.far=far!==undefined?far:1e3}Fog.prototype.isFog=true;Fog.prototype.clone=function(){return new Fog(this.color.getHex(),this.near,this.far)};Fog.prototype.toJSON=function(meta){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};function Scene(){Object3D.call(this);this.type="Scene";this.background=null;this.fog=null;this.overrideMaterial=null;this.autoUpdate=true}Scene.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Scene,copy:function(source,recursive){Object3D.prototype.copy.call(this,source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.fog!==null)this.fog=source.fog.clone();if(source.overrideMaterial!==null)this.overrideMaterial=source.overrideMaterial.clone();this.autoUpdate=source.autoUpdate;this.matrixAutoUpdate=source.matrixAutoUpdate;return this},toJSON:function(meta){var data=Object3D.prototype.toJSON.call(this,meta);if(this.background!==null)data.object.background=this.background.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data}});function LensFlare(texture,size,distance,blending,color){Object3D.call(this);this.lensFlares=[];this.positionScreen=new Vector3;this.customUpdateCallback=undefined;if(texture!==undefined){this.add(texture,size,distance,blending,color)}}LensFlare.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:LensFlare,isLensFlare:true,copy:function(source){Object3D.prototype.copy.call(this,source);this.positionScreen.copy(source.positionScreen);this.customUpdateCallback=source.customUpdateCallback;for(var i=0,l=source.lensFlares.length;i<l;i++){this.lensFlares.push(source.lensFlares[i])}return this},add:function(texture,size,distance,blending,color,opacity){if(size===undefined)size=-1;if(distance===undefined)distance=0;if(opacity===undefined)opacity=1;if(color===undefined)color=new Color(16777215);if(blending===undefined)blending=NormalBlending;distance=Math.min(distance,Math.max(0,distance));this.lensFlares.push({texture:texture,size:size,distance:distance,x:0,y:0,z:0,scale:1,rotation:0,opacity:opacity,color:color,blending:blending})},updateLensFlares:function(){var f,fl=this.lensFlares.length;var flare;var vecX=-this.positionScreen.x*2;var vecY=-this.positionScreen.y*2;for(f=0;f<fl;f++){flare=this.lensFlares[f];flare.x=this.positionScreen.x+vecX*flare.distance;flare.y=this.positionScreen.y+vecY*flare.distance;flare.wantedRotation=flare.x*Math.PI*.25;flare.rotation+=(flare.wantedRotation-flare.rotation)*.25}}});function SpriteMaterial(parameters){Material.call(this);this.type="SpriteMaterial";this.color=new Color(16777215);this.map=null;this.rotation=0;this.fog=false;this.lights=false;this.setValues(parameters)}SpriteMaterial.prototype=Object.create(Material.prototype);SpriteMaterial.prototype.constructor=SpriteMaterial;SpriteMaterial.prototype.isSpriteMaterial=true;SpriteMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.rotation=source.rotation;return this};function Sprite(material){Object3D.call(this);this.type="Sprite";this.material=material!==undefined?material:new SpriteMaterial}Sprite.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Sprite,isSprite:true,raycast:function(){var intersectPoint=new Vector3;var worldPosition=new Vector3;var worldScale=new Vector3;return function raycast(raycaster,intersects){worldPosition.setFromMatrixPosition(this.matrixWorld);raycaster.ray.closestPointToPoint(worldPosition,intersectPoint);worldScale.setFromMatrixScale(this.matrixWorld);var guessSizeSq=worldScale.x*worldScale.y/4;if(worldPosition.distanceToSquared(intersectPoint)>guessSizeSq)return;var distance=raycaster.ray.origin.distanceTo(intersectPoint);if(distance<raycaster.near||distance>raycaster.far)return;intersects.push({distance:distance,point:intersectPoint.clone(),face:null,object:this})}}(),clone:function(){return new this.constructor(this.material).copy(this)}});function LOD(){Object3D.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:true,value:[]}})}LOD.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:LOD,copy:function(source){Object3D.prototype.copy.call(this,source,false);var levels=source.levels;for(var i=0,l=levels.length;i<l;i++){var level=levels[i];this.addLevel(level.object.clone(),level.distance)}return this},addLevel:function(object,distance){if(distance===undefined)distance=0;distance=Math.abs(distance);var levels=this.levels;for(var l=0;l<levels.length;l++){if(distance<levels[l].distance){break}}levels.splice(l,0,{distance:distance,object:object});this.add(object)},getObjectForDistance:function(distance){var levels=this.levels;for(var i=1,l=levels.length;i<l;i++){if(distance<levels[i].distance){break}}return levels[i-1].object},raycast:function(){var matrixPosition=new Vector3;return function raycast(raycaster,intersects){matrixPosition.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(matrixPosition);this.getObjectForDistance(distance).raycast(raycaster,intersects)}}(),update:function(){var v1=new Vector3;var v2=new Vector3;return function update(camera){var levels=this.levels;if(levels.length>1){v1.setFromMatrixPosition(camera.matrixWorld);v2.setFromMatrixPosition(this.matrixWorld);var distance=v1.distanceTo(v2);levels[0].object.visible=true;for(var i=1,l=levels.length;i<l;i++){if(distance>=levels[i].distance){levels[i-1].object.visible=false;levels[i].object.visible=true}else{break}}for(;i<l;i++){levels[i].object.visible=false}}}}(),toJSON:function(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.levels=[];var levels=this.levels;for(var i=0,l=levels.length;i<l;i++){var level=levels[i];data.object.levels.push({object:level.object.uuid,distance:level.distance})}return data}});function Skeleton(bones,boneInverses){bones=bones||[];this.bones=bones.slice(0);this.boneMatrices=new Float32Array(this.bones.length*16);if(boneInverses===undefined){this.calculateInverses()}else{if(this.bones.length===boneInverses.length){this.boneInverses=boneInverses.slice(0)}else{console.warn("THREE.Skeleton boneInverses is the wrong length.");this.boneInverses=[];for(var i=0,il=this.bones.length;i<il;i++){this.boneInverses.push(new Matrix4)}}}}Object.assign(Skeleton.prototype,{calculateInverses:function(){this.boneInverses=[];for(var i=0,il=this.bones.length;i<il;i++){var inverse=new Matrix4;if(this.bones[i]){inverse.getInverse(this.bones[i].matrixWorld)}this.boneInverses.push(inverse)}},pose:function(){var bone,i,il;for(i=0,il=this.bones.length;i<il;i++){bone=this.bones[i];if(bone){bone.matrixWorld.getInverse(this.boneInverses[i])}}for(i=0,il=this.bones.length;i<il;i++){bone=this.bones[i];if(bone){if(bone.parent&&bone.parent.isBone){bone.matrix.getInverse(bone.parent.matrixWorld);bone.matrix.multiply(bone.matrixWorld)}else{bone.matrix.copy(bone.matrixWorld)}bone.matrix.decompose(bone.position,bone.quaternion,bone.scale)}}},update:function(){var offsetMatrix=new Matrix4;var identityMatrix=new Matrix4;return function update(){var bones=this.bones;var boneInverses=this.boneInverses;var boneMatrices=this.boneMatrices;var boneTexture=this.boneTexture;for(var i=0,il=bones.length;i<il;i++){var matrix=bones[i]?bones[i].matrixWorld:identityMatrix;offsetMatrix.multiplyMatrices(matrix,boneInverses[i]);offsetMatrix.toArray(boneMatrices,i*16)}if(boneTexture!==undefined){boneTexture.needsUpdate=true}}}(),clone:function(){return new Skeleton(this.bones,this.boneInverses)}});function Bone(){Object3D.call(this);this.type="Bone"}Bone.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Bone,isBone:true});function SkinnedMesh(geometry,material){Mesh.call(this,geometry,material);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new Matrix4;this.bindMatrixInverse=new Matrix4;var bones=this.initBones();var skeleton=new Skeleton(bones);this.bind(skeleton,this.matrixWorld);this.normalizeSkinWeights()}SkinnedMesh.prototype=Object.assign(Object.create(Mesh.prototype),{constructor:SkinnedMesh,isSkinnedMesh:true,initBones:function(){var bones=[],bone,gbone;var i,il;if(this.geometry&&this.geometry.bones!==undefined){for(i=0,il=this.geometry.bones.length;i<il;i++){gbone=this.geometry.bones[i];bone=new Bone;bones.push(bone);bone.name=gbone.name;bone.position.fromArray(gbone.pos);bone.quaternion.fromArray(gbone.rotq);if(gbone.scl!==undefined)bone.scale.fromArray(gbone.scl)}for(i=0,il=this.geometry.bones.length;i<il;i++){gbone=this.geometry.bones[i];if(gbone.parent!==-1&&gbone.parent!==null&&bones[gbone.parent]!==undefined){bones[gbone.parent].add(bones[i])}else{this.add(bones[i])}}}this.updateMatrixWorld(true);return bones},bind:function(skeleton,bindMatrix){this.skeleton=skeleton;if(bindMatrix===undefined){this.updateMatrixWorld(true);this.skeleton.calculateInverses();bindMatrix=this.matrixWorld}this.bindMatrix.copy(bindMatrix);this.bindMatrixInverse.getInverse(bindMatrix)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var scale,i;if(this.geometry&&this.geometry.isGeometry){for(i=0;i<this.geometry.skinWeights.length;i++){var sw=this.geometry.skinWeights[i];scale=1/sw.lengthManhattan();if(scale!==Infinity){sw.multiplyScalar(scale)}else{sw.set(1,0,0,0)}}}else if(this.geometry&&this.geometry.isBufferGeometry){var vec=new Vector4;var skinWeight=this.geometry.attributes.skinWeight;for(i=0;i<skinWeight.count;i++){vec.x=skinWeight.getX(i);vec.y=skinWeight.getY(i);vec.z=skinWeight.getZ(i);vec.w=skinWeight.getW(i);scale=1/vec.lengthManhattan();if(scale!==Infinity){vec.multiplyScalar(scale)}else{vec.set(1,0,0,0)}skinWeight.setXYZW(i,vec.x,vec.y,vec.z,vec.w)}}},updateMatrixWorld:function(force){Mesh.prototype.updateMatrixWorld.call(this,force);if(this.bindMode==="attached"){this.bindMatrixInverse.getInverse(this.matrixWorld)}else if(this.bindMode==="detached"){this.bindMatrixInverse.getInverse(this.bindMatrix)}else{console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}},clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});function LineBasicMaterial(parameters){Material.call(this);this.type="LineBasicMaterial";this.color=new Color(16777215);this.linewidth=1;this.linecap="round";this.linejoin="round";this.lights=false;this.setValues(parameters)}LineBasicMaterial.prototype=Object.create(Material.prototype);LineBasicMaterial.prototype.constructor=LineBasicMaterial;LineBasicMaterial.prototype.isLineBasicMaterial=true;LineBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.linewidth=source.linewidth;this.linecap=source.linecap;this.linejoin=source.linejoin;return this};function Line(geometry,material,mode){if(mode===1){console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.");return new LineSegments(geometry,material)}Object3D.call(this);this.type="Line";this.geometry=geometry!==undefined?geometry:new BufferGeometry;this.material=material!==undefined?material:new LineBasicMaterial({color:Math.random()*16777215})}Line.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Line,isLine:true,raycast:function(){var inverseMatrix=new Matrix4;var ray=new Ray;var sphere=new Sphere;return function raycast(raycaster,intersects){var precision=raycaster.linePrecision;var precisionSq=precision*precision;var geometry=this.geometry;var matrixWorld=this.matrixWorld;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();sphere.copy(geometry.boundingSphere);sphere.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(sphere)===false)return;inverseMatrix.getInverse(matrixWorld);ray.copy(raycaster.ray).applyMatrix4(inverseMatrix);var vStart=new Vector3;var vEnd=new Vector3;var interSegment=new Vector3;var interRay=new Vector3;var step=this&&this.isLineSegments?2:1;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positions=attributes.position.array;if(index!==null){var indices=index.array;for(var i=0,l=indices.length-1;i<l;i+=step){var a=indices[i];var b=indices[i+1];vStart.fromArray(positions,a*3);vEnd.fromArray(positions,b*3);var distSq=ray.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(distSq>precisionSq)continue;interRay.applyMatrix4(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(interRay);if(distance<raycaster.near||distance>raycaster.far)continue;intersects.push({distance:distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}else{for(var i=0,l=positions.length/3-1;i<l;i+=step){vStart.fromArray(positions,3*i);vEnd.fromArray(positions,3*i+3);var distSq=ray.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(distSq>precisionSq)continue;interRay.applyMatrix4(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(interRay);if(distance<raycaster.near||distance>raycaster.far)continue;intersects.push({distance:distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}}else if(geometry.isGeometry){var vertices=geometry.vertices;var nbVertices=vertices.length;for(var i=0;i<nbVertices-1;i+=step){var distSq=ray.distanceSqToSegment(vertices[i],vertices[i+1],interRay,interSegment);if(distSq>precisionSq)continue;interRay.applyMatrix4(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(interRay);if(distance<raycaster.near||distance>raycaster.far)continue;intersects.push({distance:distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});function LineSegments(geometry,material){Line.call(this,geometry,material);this.type="LineSegments"}LineSegments.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineSegments,isLineSegments:true});function LineLoop(geometry,material){Line.call(this,geometry,material);this.type="LineLoop"}LineLoop.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineLoop,isLineLoop:true});function PointsMaterial(parameters){Material.call(this);this.type="PointsMaterial";this.color=new Color(16777215);this.map=null;this.size=1;this.sizeAttenuation=true;this.lights=false;this.setValues(parameters)}PointsMaterial.prototype=Object.create(Material.prototype);PointsMaterial.prototype.constructor=PointsMaterial;PointsMaterial.prototype.isPointsMaterial=true;PointsMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.size=source.size;this.sizeAttenuation=source.sizeAttenuation;return this};function Points(geometry,material){Object3D.call(this);this.type="Points";this.geometry=geometry!==undefined?geometry:new BufferGeometry;this.material=material!==undefined?material:new PointsMaterial({color:Math.random()*16777215})}Points.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Points,isPoints:true,raycast:function(){var inverseMatrix=new Matrix4;var ray=new Ray;var sphere=new Sphere;return function raycast(raycaster,intersects){var object=this;var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Points.threshold;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();sphere.copy(geometry.boundingSphere);sphere.applyMatrix4(matrixWorld);sphere.radius+=threshold;if(raycaster.ray.intersectsSphere(sphere)===false)return;inverseMatrix.getInverse(matrixWorld);ray.copy(raycaster.ray).applyMatrix4(inverseMatrix);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;var position=new Vector3;function testPoint(point,index){var rayPointDistanceSq=ray.distanceSqToPoint(point);if(rayPointDistanceSq<localThresholdSq){var intersectPoint=ray.closestPointToPoint(point);intersectPoint.applyMatrix4(matrixWorld);var distance=raycaster.ray.origin.distanceTo(intersectPoint);if(distance<raycaster.near||distance>raycaster.far)return;intersects.push({distance:distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint.clone(),index:index,face:null,object:object})}}if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positions=attributes.position.array;if(index!==null){var indices=index.array;for(var i=0,il=indices.length;i<il;i++){var a=indices[i];position.fromArray(positions,a*3);testPoint(position,a)}}else{for(var i=0,l=positions.length/3;i<l;i++){position.fromArray(positions,i*3);testPoint(position,i)}}}else{var vertices=geometry.vertices;for(var i=0,l=vertices.length;i<l;i++){testPoint(vertices[i],i)}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});function Group(){Object3D.call(this);this.type="Group"}Group.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Group});function VideoTexture(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.generateMipmaps=false;var scope=this;function update(){requestAnimationFrame(update);if(video.readyState>=video.HAVE_CURRENT_DATA){scope.needsUpdate=true}}update()}VideoTexture.prototype=Object.create(Texture.prototype);VideoTexture.prototype.constructor=VideoTexture;function CompressedTexture(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={width:width,height:height};this.mipmaps=mipmaps;this.flipY=false;this.generateMipmaps=false}CompressedTexture.prototype=Object.create(Texture.prototype);CompressedTexture.prototype.constructor=CompressedTexture;CompressedTexture.prototype.isCompressedTexture=true;function DepthTexture(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==undefined?format:DepthFormat;if(format!==DepthFormat&&format!==DepthStencilFormat){throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat")}if(type===undefined&&format===DepthFormat)type=UnsignedShortType;if(type===undefined&&format===DepthStencilFormat)type=UnsignedInt248Type;Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.image={width:width,height:height};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.flipY=false;this.generateMipmaps=false}DepthTexture.prototype=Object.create(Texture.prototype);DepthTexture.prototype.constructor=DepthTexture;DepthTexture.prototype.isDepthTexture=true;function WireframeGeometry(geometry){BufferGeometry.call(this);this.type="WireframeGeometry";var vertices=[];var i,j,l,o,ol;var edge=[0,0],edges={},e,edge1,edge2;var key,keys=["a","b","c"];var vertex;if(geometry&&geometry.isGeometry){var faces=geometry.faces;for(i=0,l=faces.length;i<l;i++){var face=faces[i];for(j=0;j<3;j++){edge1=face[keys[j]];edge2=face[keys[(j+1)%3]];edge[0]=Math.min(edge1,edge2);edge[1]=Math.max(edge1,edge2);key=edge[0]+","+edge[1];if(edges[key]===undefined){edges[key]={index1:edge[0],index2:edge[1]}}}}for(key in edges){e=edges[key];vertex=geometry.vertices[e.index1];vertices.push(vertex.x,vertex.y,vertex.z);vertex=geometry.vertices[e.index2];vertices.push(vertex.x,vertex.y,vertex.z)}}else if(geometry&&geometry.isBufferGeometry){var position,indices,groups;var group,start,count;var index1,index2;vertex=new Vector3;if(geometry.index!==null){position=geometry.attributes.position;indices=geometry.index;groups=geometry.groups;if(groups.length===0){groups=[{start:0,count:indices.count,materialIndex:0}]}for(o=0,ol=groups.length;o<ol;++o){group=groups[o];start=group.start;count=group.count;for(i=start,l=start+count;i<l;i+=3){for(j=0;j<3;j++){edge1=indices.getX(i+j);edge2=indices.getX(i+(j+1)%3);edge[0]=Math.min(edge1,edge2);edge[1]=Math.max(edge1,edge2);key=edge[0]+","+edge[1];if(edges[key]===undefined){edges[key]={index1:edge[0],index2:edge[1]}}}}}for(key in edges){e=edges[key];vertex.fromBufferAttribute(position,e.index1);vertices.push(vertex.x,vertex.y,vertex.z);vertex.fromBufferAttribute(position,e.index2);vertices.push(vertex.x,vertex.y,vertex.z)}}else{position=geometry.attributes.position;for(i=0,l=position.count/3;i<l;i++){for(j=0;j<3;j++){index1=3*i+j;vertex.fromBufferAttribute(position,index1);vertices.push(vertex.x,vertex.y,vertex.z);index2=3*i+(j+1)%3;vertex.fromBufferAttribute(position,index2);vertices.push(vertex.x,vertex.y,vertex.z)}}}}this.addAttribute("position",new Float32BufferAttribute(vertices,3))}WireframeGeometry.prototype=Object.create(BufferGeometry.prototype);WireframeGeometry.prototype.constructor=WireframeGeometry;function ParametricGeometry(func,slices,stacks){Geometry.call(this);this.type="ParametricGeometry";this.parameters={func:func,slices:slices,stacks:stacks};this.fromBufferGeometry(new ParametricBufferGeometry(func,slices,stacks));this.mergeVertices()}ParametricGeometry.prototype=Object.create(Geometry.prototype);ParametricGeometry.prototype.constructor=ParametricGeometry;function ParametricBufferGeometry(func,slices,stacks){BufferGeometry.call(this);this.type="ParametricBufferGeometry";this.parameters={func:func,slices:slices,stacks:stacks};var indices=[]
var vertices=[];var normals=[];var uvs=[];var EPS=1e-5;var normal=new Vector3;var p0=new Vector3,p1=new Vector3;var pu=new Vector3,pv=new Vector3;var i,j;var sliceCount=slices+1;for(i=0;i<=stacks;i++){var v=i/stacks;for(j=0;j<=slices;j++){var u=j/slices;p0=func(u,v,p0);vertices.push(p0.x,p0.y,p0.z);if(u-EPS>=0){p1=func(u-EPS,v,p1);pu.subVectors(p0,p1)}else{p1=func(u+EPS,v,p1);pu.subVectors(p1,p0)}if(v-EPS>=0){p1=func(u,v-EPS,p1);pv.subVectors(p0,p1)}else{p1=func(u,v+EPS,p1);pv.subVectors(p1,p0)}normal.crossVectors(pu,pv).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(u,v)}}for(i=0;i<stacks;i++){for(j=0;j<slices;j++){var a=i*sliceCount+j;var b=i*sliceCount+j+1;var c=(i+1)*sliceCount+j+1;var d=(i+1)*sliceCount+j;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}ParametricBufferGeometry.prototype=Object.create(BufferGeometry.prototype);ParametricBufferGeometry.prototype.constructor=ParametricBufferGeometry;function PolyhedronGeometry(vertices,indices,radius,detail){Geometry.call(this);this.type="PolyhedronGeometry";this.parameters={vertices
vertices,indices:indices,radius:radius,detail:detail};this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices,indices,radius,detail));this.mergeVertices()}PolyhedronGeometry.prototype=Object.create(Geometry.prototype);PolyhedronGeometry.prototype.constructor=PolyhedronGeometry;function PolyhedronBufferGeometry(vertices,indices,radius,detail){BufferGeometry.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:vertices,indices:indices,radius:radius,detail:detail};radius=radius||1;detail=detail||0;var vertexBuffer=[];var uvBuffer=[];subdivide(detail);appplyRadius(radius);generateUVs();this.addAttribute("position",new Float32BufferAttribute(vertexBuffer,3));this.addAttribute("normal",new Float32BufferAttribute(vertexBuffer.slice(),3));this.addAttribute("uv",new Float32BufferAttribute(uvBuffer,2));if(detail===0){this.computeVertexNormals()}else{this.normalizeNormals()}function subdivide(detail){var a=new Vector3;var b=new Vector3;var c=new Vector3;for(var i=0;i<indices.length;i+=3){getVertexByIndex(indices[i+0],a);getVertexByIndex(indices[i+1],b);getVertexByIndex(indices[i+2],c);subdivideFace(a,b,c,detail)}}function subdivideFace(a,b,c,detail){var cols=Math.pow(2,detail);var v=[];var i,j;for(i=0;i<=cols;i++){v[i]=[];var aj=a.clone().lerp(c,i/cols);var bj=b.clone().lerp(c,i/cols);var rows=cols-i;for(j=0;j<=rows;j++){if(j===0&&i===cols){v[i][j]=aj}else{v[i][j]=aj.clone().lerp(bj,j/rows)}}}for(i=0;i<cols;i++){for(j=0;j<2*(cols-i)-1;j++){var k=Math.floor(j/2);if(j%2===0){pushVertex(v[i][k+1]);pushVertex(v[i+1][k]);pushVertex(v[i][k])}else{pushVertex(v[i][k+1]);pushVertex(v[i+1][k+1]);pushVertex(v[i+1][k])}}}}function appplyRadius(radius){var vertex=new Vector3;for(var i=0;i<vertexBuffer.length;i+=3){vertex.x=vertexBuffer[i+0];vertex.y=vertexBuffer[i+1];vertex.z=vertexBuffer[i+2];vertex.normalize().multiplyScalar(radius);vertexBuffer[i+0]=vertex.x;vertexBuffer[i+1]=vertex.y;vertexBuffer[i+2]=vertex.z}}function generateUVs(){var vertex=new Vector3;for(var i=0;i<vertexBuffer.length;i+=3){vertex.x=vertexBuffer[i+0];vertex.y=vertexBuffer[i+1];vertex.z=vertexBuffer[i+2];var u=azimuth(vertex)/2/Math.PI+.5;var v=inclination(vertex)/Math.PI+.5;uvBuffer.push(u,1-v)}correctUVs();correctSeam()}function correctSeam(){for(var i=0;i<uvBuffer.length;i+=6){var x0=uvBuffer[i+0];var x1=uvBuffer[i+2];var x2=uvBuffer[i+4];var max=Math.max(x0,x1,x2);var min=Math.min(x0,x1,x2);if(max>.9&&min<.1){if(x0<.2)uvBuffer[i+0]+=1;if(x1<.2)uvBuffer[i+2]+=1;if(x2<.2)uvBuffer[i+4]+=1}}}function pushVertex(vertex){vertexBuffer.push(vertex.x,vertex.y,vertex.z)}function getVertexByIndex(index,vertex){var stride=index*3;vertex.x=vertices[stride+0];vertex.y=vertices[stride+1];vertex.z=vertices[stride+2]}function correctUVs(){var a=new Vector3;var b=new Vector3;var c=new Vector3;var centroid=new Vector3;var uvA=new Vector2;var uvB=new Vector2;var uvC=new Vector2;for(var i=0,j=0;i<vertexBuffer.length;i+=9,j+=6){a.set(vertexBuffer[i+0],vertexBuffer[i+1],vertexBuffer[i+2]);b.set(vertexBuffer[i+3],vertexBuffer[i+4],vertexBuffer[i+5]);c.set(vertexBuffer[i+6],vertexBuffer[i+7],vertexBuffer[i+8]);uvA.set(uvBuffer[j+0],uvBuffer[j+1]);uvB.set(uvBuffer[j+2],uvBuffer[j+3]);uvC.set(uvBuffer[j+4],uvBuffer[j+5]);centroid.copy(a).add(b).add(c).divideScalar(3);var azi=azimuth(centroid);correctUV(uvA,j+0,a,azi);correctUV(uvB,j+2,b,azi);correctUV(uvC,j+4,c,azi)}}function correctUV(uv,stride,vector,azimuth){if(azimuth<0&&uv.x===1){uvBuffer[stride]=uv.x-1}if(vector.x===0&&vector.z===0){uvBuffer[stride]=azimuth/2/Math.PI+.5}}function azimuth(vector){return Math.atan2(vector.z,-vector.x)}function inclination(vector){return Math.atan2(-vector.y,Math.sqrt(vector.x*vector.x+vector.z*vector.z))}}PolyhedronBufferGeometry.prototype=Object.create(BufferGeometry.prototype);PolyhedronBufferGeometry.prototype.constructor=PolyhedronBufferGeometry;function TetrahedronGeometry(radius,detail){Geometry.call(this);this.type="TetrahedronGeometry";this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new TetrahedronBufferGeometry(radius,detail));this.mergeVertices()}TetrahedronGeometry.prototype=Object.create(Geometry.prototype);TetrahedronGeometry.prototype.constructor=TetrahedronGeometry;function TetrahedronBufferGeometry(radius,detail){var vertices=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1];var indices=[2,1,0,0,3,2,1,3,0,2,3,1];PolyhedronBufferGeometry.call(this,vertices,indices,radius,detail);this.type="TetrahedronBufferGeometry";this.parameters={radius:radius,detail:detail}}TetrahedronBufferGeometry.prototype=Object.create(PolyhedronBufferGeometry.prototype);TetrahedronBufferGeometry.prototype.constructor=TetrahedronBufferGeometry;function OctahedronGeometry(radius,detail){Geometry.call(this);this.type="OctahedronGeometry";this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new OctahedronBufferGeometry(radius,detail));this.mergeVertices()}OctahedronGeometry.prototype=Object.create(Geometry.prototype);OctahedronGeometry.prototype.constructor=OctahedronGeometry;function OctahedronBufferGeometry(radius,detail){var vertices=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1];var indices=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];PolyhedronBufferGeometry.call(this,vertices,indices,radius,detail);this.type="OctahedronBufferGeometry";this.parameters={radius:radius,detail:detail}}OctahedronBufferGeometry.prototype=Object.create(PolyhedronBufferGeometry.prototype);OctahedronBufferGeometry.prototype.constructor=OctahedronBufferGeometry;function IcosahedronGeometry(radius,detail){Geometry.call(this);this.type="IcosahedronGeometry";this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new IcosahedronBufferGeometry(radius,detail));this.mergeVertices()}IcosahedronGeometry.prototype=Object.create(Geometry.prototype);IcosahedronGeometry.prototype.constructor=IcosahedronGeometry;function IcosahedronBufferGeometry(radius,detail){var t=(1+Math.sqrt(5))/2;var vertices=[-1,t,0,1,t,0,-1,-t,0,1,-t,0,0,-1,t,0,1,t,0,-1,-t,0,1,-t,t,0,-1,t,0,1,-t,0,-1,-t,0,1];var indices=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];PolyhedronBufferGeometry.call(this,vertices,indices,radius,detail);this.type="IcosahedronBufferGeometry";this.parameters={radius:radius,detail:detail}}IcosahedronBufferGeometry.prototype=Object.create(PolyhedronBufferGeometry.prototype);IcosahedronBufferGeometry.prototype.constructor=IcosahedronBufferGeometry;function DodecahedronGeometry(radius,detail){Geometry.call(this);this.type="DodecahedronGeometry";this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new DodecahedronBufferGeometry(radius,detail));this.mergeVertices()}DodecahedronGeometry.prototype=Object.create(Geometry.prototype);DodecahedronGeometry.prototype.constructor=DodecahedronGeometry;function DodecahedronBufferGeometry(radius,detail){var t=(1+Math.sqrt(5))/2;var r=1/t;var vertices=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-r,-t,0,-r,t,0,r,-t,0,r,t,-r,-t,0,-r,t,0,r,-t,0,r,t,0,-t,0,-r,t,0,-r,-t,0,r,t,0,r];var indices=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];PolyhedronBufferGeometry.call(this,vertices,indices,radius,detail);this.type="DodecahedronBufferGeometry";this.parameters={radius:radius,detail:detail}}DodecahedronBufferGeometry.prototype=Object.create(PolyhedronBufferGeometry.prototype);DodecahedronBufferGeometry.prototype.constructor=DodecahedronBufferGeometry;function TubeGeometry(path,tubularSegments,radius,radialSegments,closed,taper){Geometry.call(this);this.type="TubeGeometry";this.parameters={path:path,tubularSegments:tubularSegments,radius:radius,radialSegments:radialSegments,closed:closed};if(taper!==undefined)console.warn("THREE.TubeGeometry: taper has been removed.");var bufferGeometry=new TubeBufferGeometry(path,tubularSegments,radius,radialSegments,closed);this.tangents=bufferGeometry.tangents;this.normals=bufferGeometry.normals;this.binormals=bufferGeometry.binormals;this.fromBufferGeometry(bufferGeometry);this.mergeVertices()}TubeGeometry.prototype=Object.create(Geometry.prototype);TubeGeometry.prototype.constructor=TubeGeometry;function TubeBufferGeometry(path,tubularSegments,radius,radialSegments,closed){BufferGeometry.call(this);this.type="TubeBufferGeometry";this.parameters={path:path,tubularSegments:tubularSegments,radius:radius,radialSegments:radialSegments,closed:closed};tubularSegments=tubularSegments||64;radius=radius||1;radialSegments=radialSegments||8;closed=closed||false;var frames=path.computeFrenetFrames(tubularSegments,closed);this.tangents=frames.tangents;this.normals=frames.normals;this.binormals=frames.binormals;var vertex=new Vector3;var normal=new Vector3;var uv=new Vector2;var i,j;var vertices=[];var normals=[];var uvs=[];var indices=[];generateBufferData();this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));function generateBufferData(){for(i=0;i<tubularSegments;i++){generateSegment(i)}generateSegment(closed===false?tubularSegments:0);generateUVs();generateIndices()}function generateSegment(i){var P=path.getPointAt(i/tubularSegments);var N=frames.normals[i];var B=frames.binormals[i];for(j=0;j<=radialSegments;j++){var v=j/radialSegments*Math.PI*2;var sin=Math.sin(v);var cos=-Math.cos(v);normal.x=cos*N.x+sin*B.x;normal.y=cos*N.y+sin*B.y;normal.z=cos*N.z+sin*B.z;normal.normalize();normals.push(normal.x,normal.y,normal.z);vertex.x=P.x+radius*normal.x;vertex.y=P.y+radius*normal.y;vertex.z=P.z+radius*normal.z;vertices.push(vertex.x,vertex.y,vertex.z)}}function generateIndices(){for(j=1;j<=tubularSegments;j++){for(i=1;i<=radialSegments;i++){var a=(radialSegments+1)*(j-1)+(i-1);var b=(radialSegments+1)*j+(i-1);var c=(radialSegments+1)*j+i;var d=(radialSegments+1)*(j-1)+i;indices.push(a,b,d);indices.push(b,c,d)}}}function generateUVs(){for(i=0;i<=tubularSegments;i++){for(j=0;j<=radialSegments;j++){uv.x=i/tubularSegments;uv.y=j/radialSegments;uvs.push(uv.x,uv.y)}}}}TubeBufferGeometry.prototype=Object.create(BufferGeometry.prototype);TubeBufferGeometry.prototype.constructor=TubeBufferGeometry;function TorusKnotGeometry(radius,tube,tubularSegments,radialSegments,p,q,heightScale){Geometry.call(this);this.type="TorusKnotGeometry";this.parameters={radius:radius,tube:tube,tubularSegments:tubularSegments,radialSegments:radialSegments,p:p,q:q};if(heightScale!==undefined)console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");this.fromBufferGeometry(new TorusKnotBufferGeometry(radius,tube,tubularSegments,radialSegments,p,q));this.mergeVertices()}TorusKnotGeometry.prototype=Object.create(Geometry.prototype);TorusKnotGeometry.prototype.constructor=TorusKnotGeometry;function TorusKnotBufferGeometry(radius,tube,tubularSegments,radialSegments,p,q){BufferGeometry.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:radius,tube:tube,tubularSegments:tubularSegments,radialSegments:radialSegments,p:p,q:q};radius=radius||100;tube=tube||40;tubularSegments=Math.floor(tubularSegments)||64;radialSegments=Math.floor(radialSegments)||8;p=p||2;q=q||3;var indices=[];var vertices=[];var normals=[];var uvs=[];var i,j;var vertex=new Vector3;var normal=new Vector3;var P1=new Vector3;var P2=new Vector3;var B=new Vector3;var T=new Vector3;var N=new Vector3;for(i=0;i<=tubularSegments;++i){var u=i/tubularSegments*p*Math.PI*2;calculatePositionOnCurve(u,p,q,radius,P1);calculatePositionOnCurve(u+.01,p,q,radius,P2);T.subVectors(P2,P1);N.addVectors(P2,P1);B.crossVectors(T,N);N.crossVectors(B,T);B.normalize();N.normalize();for(j=0;j<=radialSegments;++j){var v=j/radialSegments*Math.PI*2;var cx=-tube*Math.cos(v);var cy=tube*Math.sin(v);vertex.x=P1.x+(cx*N.x+cy*B.x);vertex.y=P1.y+(cx*N.y+cy*B.y);vertex.z=P1.z+(cx*N.z+cy*B.z);vertices.push(vertex.x,vertex.y,vertex.z);normal.subVectors(vertex,P1).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(i/tubularSegments);uvs.push(j/radialSegments)}}for(j=1;j<=tubularSegments;j++){for(i=1;i<=radialSegments;i++){var a=(radialSegments+1)*(j-1)+(i-1);var b=(radialSegments+1)*j+(i-1);var c=(radialSegments+1)*j+i;var d=(radialSegments+1)*(j-1)+i;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));function calculatePositionOnCurve(u,p,q,radius,position){var cu=Math.cos(u);var su=Math.sin(u);var quOverP=q/p*u;var cs=Math.cos(quOverP);position.x=radius*(2+cs)*.5*cu;position.y=radius*(2+cs)*su*.5;position.z=radius*Math.sin(quOverP)*.5}}TorusKnotBufferGeometry.prototype=Object.create(BufferGeometry.prototype);TorusKnotBufferGeometry.prototype.constructor=TorusKnotBufferGeometry;function TorusGeometry(radius,tube,radialSegments,tubularSegments,arc){Geometry.call(this);this.type="TorusGeometry";this.parameters={radius:radius,tube:tube,radialSegments:radialSegments,tubularSegments:tubularSegments,arc:arc};this.fromBufferGeometry(new TorusBufferGeometry(radius,tube,radialSegments,tubularSegments,arc));this.mergeVertices()}TorusGeometry.prototype=Object.create(Geometry.prototype);TorusGeometry.prototype.constructor=TorusGeometry;function TorusBufferGeometry(radius,tube,radialSegments,tubularSegments,arc){BufferGeometry.call(this);this.type="TorusBufferGeometry";this.parameters={radius:radius,tube:tube,radialSegments:radialSegments,tubularSegments:tubularSegments,arc:arc};radius=radius||100;tube=tube||40;radialSegments=Math.floor(radialSegments)||8;tubularSegments=Math.floor(tubularSegments)||6;arc=arc||Math.PI*2;var indices=[];var vertices=[];var normals=[];var uvs=[];var center=new Vector3;var vertex=new Vector3;var normal=new Vector3;var j,i;for(j=0;j<=radialSegments;j++){for(i=0;i<=tubularSegments;i++){var u=i/tubularSegments*arc;var v=j/radialSegments*Math.PI*2;vertex.x=(radius+tube*Math.cos(v))*Math.cos(u);vertex.y=(radius+tube*Math.cos(v))*Math.sin(u);vertex.z=tube*Math.sin(v);vertices.push(vertex.x,vertex.y,vertex.z);center.x=radius*Math.cos(u);center.y=radius*Math.sin(u);normal.subVectors(vertex,center).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(i/tubularSegments);uvs.push(j/radialSegments)}}for(j=1;j<=radialSegments;j++){for(i=1;i<=tubularSegments;i++){var a=(tubularSegments+1)*j+i-1;var b=(tubularSegments+1)*(j-1)+i-1;var c=(tubularSegments+1)*(j-1)+i;var d=(tubularSegments+1)*j+i;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}TorusBufferGeometry.prototype=Object.create(BufferGeometry.prototype);TorusBufferGeometry.prototype.constructor=TorusBufferGeometry;var ShapeUtils={area:function(contour){var n=contour.length;var a=0;for(var p=n-1,q=0;q<n;p=q++){a+=contour[p].x*contour[q].y-contour[q].x*contour[p].y}return a*.5},triangulate:function(){function snip(contour,u,v,w,n,verts){var p;var ax,ay,bx,by;var cx,cy,px,py;ax=contour[verts[u]].x;ay=contour[verts[u]].y;bx=contour[verts[v]].x;by=contour[verts[v]].y;cx=contour[verts[w]].x;cy=contour[verts[w]].y;if((bx-ax)*(cy-ay)-(by-ay)*(cx-ax)<=0)return false;var aX,aY,bX,bY,cX,cY;var apx,apy,bpx,bpy,cpx,cpy;var cCROSSap,bCROSScp,aCROSSbp;aX=cx-bx;aY=cy-by;bX=ax-cx;bY=ay-cy;cX=bx-ax;cY=by-ay;for(p=0;p<n;p++){px=contour[verts[p]].x;py=contour[verts[p]].y;if(px===ax&&py===ay||px===bx&&py===by||px===cx&&py===cy)continue;apx=px-ax;apy=py-ay;bpx=px-bx;bpy=py-by;cpx=px-cx;cpy=py-cy;aCROSSbp=aX*bpy-aY*bpx;cCROSSap=cX*apy-cY*apx;bCROSScp=bX*cpy-bY*cpx;if(aCROSSbp>=-Number.EPSILON&&bCROSScp>=-Number.EPSILON&&cCROSSap>=-Number.EPSILON)return false}return true}return function triangulate(contour,indices){var n=contour.length;if(n<3)return null;var result=[],verts=[],vertIndices=[];var u,v,w;if(ShapeUtils.area(contour)>0){for(v=0;v<n;v++)verts[v]=v}else{for(v=0;v<n;v++)verts[v]=n-1-v}var nv=n;var count=2*nv;for(v=nv-1;nv>2;){if(count--<=0){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");if(indices)return vertIndices;return result}u=v;if(nv<=u)u=0;v=u+1;if(nv<=v)v=0;w=v+1;if(nv<=w)w=0;if(snip(contour,u,v,w,nv,verts)){var a,b,c,s,t;a=verts[u];b=verts[v];c=verts[w];result.push([contour[a],contour[b],contour[c]]);vertIndices.push([verts[u],verts[v],verts[w]]);for(s=v,t=v+1;t<nv;s++,t++){verts[s]=verts[t]}nv--;count=2*nv}}if(indices)return vertIndices;return result}}(),triangulateShape:function(contour,holes){function removeDupEndPts(points){var l=points.length;if(l>2&&points[l-1].equals(points[0])){points.pop()}}removeDupEndPts(contour);holes.forEach(removeDupEndPts);function point_in_segment_2D_colin(inSegPt1,inSegPt2,inOtherPt){if(inSegPt1.x!==inSegPt2.x){if(inSegPt1.x<inSegPt2.x){return inSegPt1.x<=inOtherPt.x&&inOtherPt.x<=inSegPt2.x}else{return inSegPt2.x<=inOtherPt.x&&inOtherPt.x<=inSegPt1.x}}else{if(inSegPt1.y<inSegPt2.y){return inSegPt1.y<=inOtherPt.y&&inOtherPt.y<=inSegPt2.y}else{return inSegPt2.y<=inOtherPt.y&&inOtherPt.y<=inSegPt1.y}}}function intersect_segments_2D(inSeg1Pt1,inSeg1Pt2,inSeg2Pt1,inSeg2Pt2,inExcludeAdjacentSegs){var seg1dx=inSeg1Pt2.x-inSeg1Pt1.x,seg1dy=inSeg1Pt2.y-inSeg1Pt1.y;var seg2dx=inSeg2Pt2.x-inSeg2Pt1.x,seg2dy=inSeg2Pt2.y-inSeg2Pt1.y;var seg1seg2dx=inSeg1Pt1.x-inSeg2Pt1.x;var seg1seg2dy=inSeg1Pt1.y-inSeg2Pt1.y;var limit=seg1dy*seg2dx-seg1dx*seg2dy;var perpSeg1=seg1dy*seg1seg2dx-seg1dx*seg1seg2dy;if(Math.abs(limit)>Number.EPSILON){var perpSeg2;if(limit>0){if(perpSeg1<0||perpSeg1>limit)return[];perpSeg2=seg2dy*seg1seg2dx-seg2dx*seg1seg2dy;if(perpSeg2<0||perpSeg2>limit)return[]}else{if(perpSeg1>0||perpSeg1<limit)return[];perpSeg2=seg2dy*seg1seg2dx-seg2dx*seg1seg2dy;if(perpSeg2>0||perpSeg2<limit)return[]}if(perpSeg2===0){if(inExcludeAdjacentSegs&&(perpSeg1===0||perpSeg1===limit))return[];return[inSeg1Pt1]}if(perpSeg2===limit){if(inExcludeAdjacentSegs&&(perpSeg1===0||perpSeg1===limit))return[];return[inSeg1Pt2]}if(perpSeg1===0)return[inSeg2Pt1];if(perpSeg1===limit)return[inSeg2Pt2];var factorSeg1=perpSeg2/limit;return[{x:inSeg1Pt1.x+factorSeg1*seg1dx,y:inSeg1Pt1.y+factorSeg1*seg1dy}]}else{if(perpSeg1!==0||seg2dy*seg1seg2dx!==seg2dx*seg1seg2dy)return[];var seg1Pt=seg1dx===0&&seg1dy===0;var seg2Pt=seg2dx===0&&seg2dy===0;if(seg1Pt&&seg2Pt){if(inSeg1Pt1.x!==inSeg2Pt1.x||inSeg1Pt1.y!==inSeg2Pt1.y)return[];return[inSeg1Pt1]}if(seg1Pt){if(!point_in_segment_2D_colin(inSeg2Pt1,inSeg2Pt2,inSeg1Pt1))return[];return[inSeg1Pt1]}if(seg2Pt){if(!point_in_segment_2D_colin(inSeg1Pt1,inSeg1Pt2,inSeg2Pt1))return[];return[inSeg2Pt1]}var seg1min,seg1max,seg1minVal,seg1maxVal;var seg2min,seg2max,seg2minVal,seg2maxVal;if(seg1dx!==0){if(inSeg1Pt1.x<inSeg1Pt2.x){seg1min=inSeg1Pt1;seg1minVal=inSeg1Pt1.x;seg1max=inSeg1Pt2;seg1maxVal=inSeg1Pt2.x}else{seg1min=inSeg1Pt2;seg1minVal=inSeg1Pt2.x;seg1max=inSeg1Pt1;seg1maxVal=inSeg1Pt1.x}if(inSeg2Pt1.x<inSeg2Pt2.x){seg2min=inSeg2Pt1;seg2minVal=inSeg2Pt1.x;seg2max=inSeg2Pt2;seg2maxVal=inSeg2Pt2.x}else{seg2min=inSeg2Pt2;seg2minVal=inSeg2Pt2.x;seg2max=inSeg2Pt1;seg2maxVal=inSeg2Pt1.x}}else{if(inSeg1Pt1.y<inSeg1Pt2.y){seg1min=inSeg1Pt1;seg1minVal=inSeg1Pt1.y;seg1max=inSeg1Pt2;seg1maxVal=inSeg1Pt2.y}else{seg1min=inSeg1Pt2;seg1minVal=inSeg1Pt2.y;seg1max=inSeg1Pt1;seg1maxVal=inSeg1Pt1.y}if(inSeg2Pt1.y<inSeg2Pt2.y){seg2min=inSeg2Pt1;seg2minVal=inSeg2Pt1.y;seg2max=inSeg2Pt2;seg2maxVal=inSeg2Pt2.y}else{seg2min=inSeg2Pt2;seg2minVal=inSeg2Pt2.y;seg2max=inSeg2Pt1;seg2maxVal=inSeg2Pt1.y}}if(seg1minVal<=seg2minVal){if(seg1maxVal<seg2minVal)return[];if(seg1maxVal===seg2minVal){if(inExcludeAdjacentSegs)return[];return[seg2min]}if(seg1maxVal<=seg2maxVal)return[seg2min,seg1max];return[seg2min,seg2max]}else{if(seg1minVal>seg2maxVal)return[];if(seg1minVal===seg2maxVal){if(inExcludeAdjacentSegs)return[];return[seg1min]}if(seg1maxVal<=seg2maxVal)return[seg1min,seg1max];return[seg1min,seg2max]}}}function isPointInsideAngle(inVertex,inLegFromPt,inLegToPt,inOtherPt){var legFromPtX=inLegFromPt.x-inVertex.x,legFromPtY=inLegFromPt.y-inVertex.y;var legToPtX=inLegToPt.x-inVertex.x,legToPtY=inLegToPt.y-inVertex.y;var otherPtX=inOtherPt.x-inVertex.x,otherPtY=inOtherPt.y-inVertex.y;var from2toAngle=legFromPtX*legToPtY-legFromPtY*legToPtX;var from2otherAngle=legFromPtX*otherPtY-legFromPtY*otherPtX;if(Math.abs(from2toAngle)>Number.EPSILON){var other2toAngle=otherPtX*legToPtY-otherPtY*legToPtX;if(from2toAngle>0){return from2otherAngle>=0&&other2toAngle>=0}else{return from2otherAngle>=0||other2toAngle>=0}}else{return from2otherAngle>0}}function removeHoles(contour,holes){var shape=contour.concat();var hole;function isCutLineInsideAngles(inShapeIdx,inHoleIdx){var lastShapeIdx=shape.length-1;var prevShapeIdx=inShapeIdx-1;if(prevShapeIdx<0)prevShapeIdx=lastShapeIdx;var nextShapeIdx=inShapeIdx+1;if(nextShapeIdx>lastShapeIdx)nextShapeIdx=0;var insideAngle=isPointInsideAngle(shape[inShapeIdx],shape[prevShapeIdx],shape[nextShapeIdx],hole[inHoleIdx]);if(!insideAngle){return false}var lastHoleIdx=hole.length-1;var prevHoleIdx=inHoleIdx-1;if(prevHoleIdx<0)prevHoleIdx=lastHoleIdx;var nextHoleIdx=inHoleIdx+1;if(nextHoleIdx>lastHoleIdx)nextHoleIdx=0;insideAngle=isPointInsideAngle(hole[inHoleIdx],hole[prevHoleIdx],hole[nextHoleIdx],shape[inShapeIdx]);if(!insideAngle){return false}return true}function intersectsShapeEdge(inShapePt,inHolePt){var sIdx,nextIdx,intersection;for(sIdx=0;sIdx<shape.length;sIdx++){nextIdx=sIdx+1;nextIdx%=shape.length;intersection=intersect_segments_2D(inShapePt,inHolePt,shape[sIdx],shape[nextIdx],true);if(intersection.length>0)return true}return false}var indepHoles=[];function intersectsHoleEdge(inShapePt,inHolePt){var ihIdx,chkHole,hIdx,nextIdx,intersection;for(ihIdx=0;ihIdx<indepHoles.length;ihIdx++){chkHole=holes[indepHoles[ihIdx]];for(hIdx=0;hIdx<chkHole.length;hIdx++){nextIdx=hIdx+1;nextIdx%=chkHole.length;intersection=intersect_segments_2D(inShapePt,inHolePt,chkHole[hIdx],chkHole[nextIdx],true);if(intersection.length>0)return true}}return false}var holeIndex,shapeIndex,shapePt,holePt,holeIdx,cutKey,failedCuts=[],tmpShape1,tmpShape2,tmpHole1,tmpHole2;for(var h=0,hl=holes.length;h<hl;h++){indepHoles.push(h)}var minShapeIndex=0;var counter=indepHoles.length*2;while(indepHoles.length>0){counter--;if(counter<0){console.log('THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!');break}for(shapeIndex=minShapeIndex;shapeIndex<shape.length;shapeIndex++){shapePt=shape[shapeIndex];holeIndex=-1;for(var h=0;h<indepHoles.length;h++){holeIdx=indepHoles[h];cutKey=shapePt.x+":"+shapePt.y+":"+holeIdx;if(failedCuts[cutKey]!==undefined)continue;hole=holes[holeIdx];for(var h2=0;h2<hole.length;h2++){holePt=hole[h2];if(!isCutLineInsideAngles(shapeIndex,h2))continue;if(intersectsShapeEdge(shapePt,holePt))continue;if(intersectsHoleEdge(shapePt,holePt))continue;holeIndex=h2;indepHoles.splice(h,1);tmpShape1=shape.slice(0,shapeIndex+1);tmpShape2=shape.slice(shapeIndex);tmpHole1=hole.slice(holeIndex);tmpHole2=hole.slice(0,holeIndex+1);shape=tmpShape1.concat(tmpHole1).concat(tmpHole2).concat(tmpShape2);minShapeIndex=shapeIndex;break}if(holeIndex>=0)break;failedCuts[cutKey]=true}if(holeIndex>=0)break}}return shape}var i,il,f,face,key,index,allPointsMap={};var allpoints=contour.concat();for(var h=0,hl=holes.length;h<hl;h++){Array.prototype.push.apply(allpoints,holes[h])}for(i=0,il=allpoints.length;i<il;i++){key=allpoints[i].x+":"+allpoints[i].y;if(allPointsMap[key]!==undefined){console.warn("THREE.ShapeUtils: Duplicate point",key,i)}allPointsMap[key]=i}var shapeWithoutHoles=removeHoles(contour,holes);var triangles=ShapeUtils.triangulate(shapeWithoutHoles,false);for(i=0,il=triangles.length;i<il;i++){face=triangles[i];for(f=0;f<3;f++){key=face[f].x+":"+face[f].y;index=allPointsMap[key];if(index!==undefined){face[f]=index}}}return triangles.concat()},isClockWise:function(pts){return ShapeUtils.area(pts)<0}};function ExtrudeGeometry(shapes,options){Geometry.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:shapes,options:options};this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes,options));this.mergeVertices()}ExtrudeGeometry.prototype=Object.create(Geometry.prototype);ExtrudeGeometry.prototype.constructor=ExtrudeGeometry;function ExtrudeBufferGeometry(shapes,options){if(typeof shapes==="undefined"){return}BufferGeometry.call(this);this.type="ExtrudeBufferGeometry";shapes=Array.isArray(shapes)?shapes:[shapes];this.addShapeList(shapes,options);this.computeVertexNormals()}ExtrudeBufferGeometry.prototype=Object.create(BufferGeometry.prototype);ExtrudeBufferGeometry.prototype.constructor=ExtrudeBufferGeometry;ExtrudeBufferGeometry.prototype.getArrays=function(){var positionAttribute=this.getAttribute("position");var verticesArray=positionAttribute?Array.prototype.slice.call(positionAttribute.array):[];var uvAttribute=this.getAttribute("uv");var uvArray=uvAttribute?Array.prototype.slice.call(uvAttribute.array):[];var IndexAttribute=this.index;var indicesArray=IndexAttribute?Array.prototype.slice.call(IndexAttribute.array):[];return{position:verticesArray,uv:uvArray,index:indicesArray}};ExtrudeBufferGeometry.prototype.addShapeList=function(shapes,options){var sl=shapes.length;options.arrays=this.getArrays();for(var s=0;s<sl;s++){var shape=shapes[s];this.addShape(shape,options)}this.setIndex(options.arrays.index);this.addAttribute("position",new Float32BufferAttribute(options.arrays.position,3));this.addAttribute("uv",new Float32BufferAttribute(options.arrays.uv,2))};ExtrudeBufferGeometry.prototype.addShape=function(shape,options){var arrays=options.arrays?options.arrays:this.getArrays();var verticesArray=arrays.position;var indicesArray=arrays.index;var uvArray=arrays.uv;var placeholder=[];var amount=options.amount!==undefined?options.amount:100;var bevelThickness=options.bevelThickness!==undefined?options.bevelThickness:6;var bevelSize=options.bevelSize!==undefined?options.bevelSize:bevelThickness-2;var bevelSegments=options.bevelSegments!==undefined?options.bevelSegments:3;var bevelEnabled=options.bevelEnabled!==undefined?options.bevelEnabled:true;var curveSegments=options.curveSegments!==undefined?options.curveSegments:12;var steps=options.steps!==undefined?options.steps:1;var extrudePath=options.extrudePath;var extrudePts,extrudeByPath=false;var uvgen=options.UVGenerator!==undefined?options.UVGenerator:ExtrudeGeometry.WorldUVGenerator;var splineTube,binormal,normal,position2;if(extrudePath){extrudePts=extrudePath.getSpacedPoints(steps);extrudeByPath=true;bevelEnabled=false;splineTube=options.frames!==undefined?options.frames:extrudePath.computeFrenetFrames(steps,false);binormal=new Vector3;normal=new Vector3;position2=new Vector3}if(!bevelEnabled){bevelSegments=0;bevelThickness=0;bevelSize=0}var ahole,h,hl;var scope=this;var shapePoints=shape.extractPoints(curveSegments);var vertices=shapePoints.shape;var holes=shapePoints.holes;var reverse=!ShapeUtils.isClockWise(vertices);if(reverse){vertices=vertices.reverse();for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];if(ShapeUtils.isClockWise(ahole)){holes[h]=ahole.reverse()}}}var faces=ShapeUtils.triangulateShape(vertices,holes);var contour=vertices;for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];vertices=vertices.concat(ahole)}function scalePt2(pt,vec,size){if(!vec)console.error("THREE.ExtrudeGeometry: vec does not exist");return vec.clone().multiplyScalar(size).add(pt)}var b,bs,t,z,vert,vlen=vertices.length,face,flen=faces.length;function getBevelVec(inPt,inPrev,inNext){var v_trans_x,v_trans_y,shrink_by;var v_prev_x=inPt.x-inPrev.x,v_prev_y=inPt.y-inPrev.y;var v_next_x=inNext.x-inPt.x,v_next_y=inNext.y-inPt.y;var v_prev_lensq=v_prev_x*v_prev_x+v_prev_y*v_prev_y;var collinear0=v_prev_x*v_next_y-v_prev_y*v_next_x;if(Math.abs(collinear0)>Number.EPSILON){var v_prev_len=Math.sqrt(v_prev_lensq);var v_next_len=Math.sqrt(v_next_x*v_next_x+v_next_y*v_next_y);var ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;var ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;var ptNextShift_x=inNext.x-v_next_y/v_next_len;var ptNextShift_y=inNext.y+v_next_x/v_next_len;var sf=((ptNextShift_x-ptPrevShift_x)*v_next_y-(ptNextShift_y-ptPrevShift_y)*v_next_x)/(v_prev_x*v_next_y-v_prev_y*v_next_x);v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;var v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2(v_trans_x,v_trans_y)}else{shrink_by=Math.sqrt(v_trans_lensq/2)}}else{var direction_eq=false;if(v_prev_x>Number.EPSILON){if(v_next_x>Number.EPSILON){direction_eq=true}}else{if(v_prev_x<-Number.EPSILON){if(v_next_x<-Number.EPSILON){direction_eq=true}}else{if(Math.sign(v_prev_y)===Math.sign(v_next_y)){direction_eq=true}}}if(direction_eq){v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq)}else{v_trans_x=v_prev_x;v_trans_y=v_prev_y;shrink_by=Math.sqrt(v_prev_lensq/2)}}return new Vector2(v_trans_x/shrink_by,v_trans_y/shrink_by)}var contourMovements=[];for(var i=0,il=contour.length,j=il-1,k=i+1;i<il;i++,j++,k++){if(j===il)j=0;if(k===il)k=0;contourMovements[i]=getBevelVec(contour[i],contour[j],contour[k])}var holesMovements=[],oneHoleMovements,verticesMovements=contourMovements.concat();for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];oneHoleMovements=[];for(i=0,il=ahole.length,j=il-1,k=i+1;i<il;i++,j++,k++){if(j===il)j=0;if(k===il)k=0;oneHoleMovements[i]=getBevelVec(ahole[i],ahole[j],ahole[k])}holesMovements.push(oneHoleMovements);verticesMovements=verticesMovements.concat(oneHoleMovements)}for(b=0;b<bevelSegments;b++){t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2);for(i=0,il=contour.length;i<il;i++){vert=scalePt2(contour[i],contourMovements[i],bs);v(vert.x,vert.y,-z)}for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];oneHoleMovements=holesMovements[h];for(i=0,il=ahole.length;i<il;i++){vert=scalePt2(ahole[i],oneHoleMovements[i],bs);v(vert.x,vert.y,-z)}}}bs=bevelSize;for(i=0;i<vlen;i++){vert=bevelEnabled?scalePt2(vertices[i],verticesMovements[i],bs):vertices[i];if(!extrudeByPath){v(vert.x,vert.y,0)}else{normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);position2.copy(extrudePts[0]).add(normal).add(binormal);v(position2.x,position2.y,position2.z)}}var s
for(s=1;s<=steps;s++){for(i=0;i<vlen;i++){vert=bevelEnabled?scalePt2(vertices[i],verticesMovements[i],bs)
vertices[i];if(!extrudeByPath){v(vert.x,vert.y,amount/steps*s)}else{normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);position2.copy(extrudePts[s]).add(normal).add(binormal);v(position2.x,position2.y,position2.z)}}}for(b=bevelSegments-1;b>=0;b--){t=b/bevelSegments;z=bevelThickness*Math.cos(t*Math.PI/2);bs=bevelSize*Math.sin(t*Math.PI/2);for(i=0,il=contour.length;i<il;i++){vert=scalePt2(contour[i],contourMovements[i],bs);v(vert.x,vert.y,amount+z)}for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];oneHoleMovements=holesMovements[h];for(i=0,il=ahole.length;i<il;i++){vert=scalePt2(ahole[i],oneHoleMovements[i],bs);if(!extrudeByPath){v(vert.x,vert.y,amount+z)}else{v(vert.x,vert.y+extrudePts[steps-1].y,extrudePts[steps-1].x+z)}}}}buildLidFaces();buildSideFaces();function buildLidFaces(){var start=verticesArray.length/3;if(bevelEnabled){var layer=0;var offset=vlen*layer;for(i=0;i<flen;i++){face=faces[i];f3(face[2]+offset,face[1]+offset,face[0]+offset)}layer=steps+bevelSegments*2;offset=vlen*layer;for(i=0;i<flen;i++){face=faces[i];f3(face[0]+offset,face[1]+offset,face[2]+offset)}}else{for(i=0;i<flen;i++){face=faces[i];f3(face[2],face[1],face[0])}for(i=0;i<flen;i++){face=faces[i];f3(face[0]+vlen*steps,face[1]+vlen*steps,face[2]+vlen*steps)}}scope.addGroup(start,verticesArray.length/3-start,options.material!==undefined?options.material:0)}function buildSideFaces(){var start=verticesArray.length/3;var layeroffset=0;sidewalls(contour,layeroffset);layeroffset+=contour.length;for(h=0,hl=holes.length;h<hl;h++){ahole=holes[h];sidewalls(ahole,layeroffset);layeroffset+=ahole.length}scope.addGroup(start,verticesArray.length/3-start,options.extrudeMaterial!==undefined?options.extrudeMaterial:1)}function sidewalls(contour,layeroffset){var j,k;i=contour.length;while(--i>=0){j=i;k=i-1;if(k<0)k=contour.length-1;var s=0,sl=steps+bevelSegments*2;for(s=0;s<sl;s++){var slen1=vlen*s;var slen2=vlen*(s+1);var a=layeroffset+j+slen1,b=layeroffset+k+slen1,c=layeroffset+k+slen2,d=layeroffset+j+slen2;f4(a,b,c,d,contour,s,sl,j,k)}}}function v(x,y,z){placeholder.push(x);placeholder.push(y);placeholder.push(z)}function f3(a,b,c){addVertex(a);addVertex(b);addVertex(c);var nextIndex=verticesArray.length/3;var uvs=uvgen.generateTopUV(scope,verticesArray,nextIndex-3,nextIndex-2,nextIndex-1);addUV(uvs[0]);addUV(uvs[1]);addUV(uvs[2])}function f4(a,b,c,d,wallContour,stepIndex,stepsLength,contourIndex1,contourIndex2){addVertex(a);addVertex(b);addVertex(d);addVertex(b);addVertex(c);addVertex(d);var nextIndex=verticesArray.length/3;var uvs=uvgen.generateSideWallUV(scope,verticesArray,nextIndex-6,nextIndex-3,nextIndex-2,nextIndex-1);addUV(uvs[0]);addUV(uvs[1]);addUV(uvs[3]);addUV(uvs[1]);addUV(uvs[2]);addUV(uvs[3])}function addVertex(index){indicesArray.push(verticesArray.length/3);verticesArray.push(placeholder[index*3+0]);verticesArray.push(placeholder[index*3+1]);verticesArray.push(placeholder[index*3+2])}function addUV(vector2){uvArray.push(vector2.x);uvArray.push(vector2.y)}if(!options.arrays){this.setIndex(indicesArray);this.addAttribute("position",new Float32BufferAttribute(verticesArray,3));this.addAttribute("uv",new Float32BufferAttribute(options.arrays.uv,2))}};ExtrudeGeometry.WorldUVGenerator={generateTopUV:function(geometry,vertices,indexA,indexB,indexC){var a_x=vertices[indexA*3];var a_y=vertices[indexA*3+1];var b_x=vertices[indexB*3];var b_y=vertices[indexB*3+1];var c_x=vertices[indexC*3];var c_y=vertices[indexC*3+1];return[new Vector2(a_x,a_y),new Vector2(b_x,b_y),new Vector2(c_x,c_y)]},generateSideWallUV:function(geometry,vertices,indexA,indexB,indexC,indexD){var a_x=vertices[indexA*3];var a_y=vertices[indexA*3+1];var a_z=vertices[indexA*3+2];var b_x=vertices[indexB*3];var b_y=vertices[indexB*3+1];var b_z=vertices[indexB*3+2];var c_x=vertices[indexC*3];var c_y=vertices[indexC*3+1];var c_z=vertices[indexC*3+2];var d_x=vertices[indexD*3];var d_y=vertices[indexD*3+1];var d_z=vertices[indexD*3+2];if(Math.abs(a_y-b_y)<.01){return[new Vector2(a_x,1-a_z),new Vector2(b_x,1-b_z),new Vector2(c_x,1-c_z),new Vector2(d_x,1-d_z)]}else{return[new Vector2(a_y,1-a_z),new Vector2(b_y,1-b_z),new Vector2(c_y,1-c_z),new Vector2(d_y,1-d_z)]}}};function TextGeometry(text,parameters){Geometry.call(this);this.type="TextGeometry";this.parameters={text:text,parameters:parameters};this.fromBufferGeometry(new TextBufferGeometry(text,parameters));this.mergeVertices()}TextGeometry.prototype=Object.create(Geometry.prototype);TextGeometry.prototype.constructor=TextGeometry;function TextBufferGeometry(text,parameters){parameters=parameters||{};var font=parameters.font;if(!(font&&font.isFont)){console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font.");return new Geometry}var shapes=font.generateShapes(text,parameters.size,parameters.curveSegments);parameters.amount=parameters.height!==undefined?parameters.height:50;if(parameters.bevelThickness===undefined)parameters.bevelThickness=10;if(parameters.bevelSize===undefined)parameters.bevelSize=8;if(parameters.bevelEnabled===undefined)parameters.bevelEnabled=false;ExtrudeBufferGeometry.call(this,shapes,parameters);this.type="TextBufferGeometry"}TextBufferGeometry.prototype=Object.create(ExtrudeBufferGeometry.prototype);TextBufferGeometry.prototype.constructor=TextBufferGeometry;function SphereGeometry(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength){Geometry.call(this);this.type="SphereGeometry";this.parameters={radius:radius,widthSegments:widthSegments,heightSegments:heightSegments,phiStart:phiStart,phiLength:phiLength,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new SphereBufferGeometry(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength));this.mergeVertices()}SphereGeometry.prototype=Object.create(Geometry.prototype);SphereGeometry.prototype.constructor=SphereGeometry;function SphereBufferGeometry(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength){BufferGeometry.call(this);this.type="SphereBufferGeometry";this.parameters={radius:radius,widthSegments:widthSegments,heightSegments:heightSegments,phiStart:phiStart,phiLength:phiLength,thetaStart:thetaStart,thetaLength:thetaLength};radius=radius||50;widthSegments=Math.max(3,Math.floor(widthSegments)||8);heightSegments=Math.max(2,Math.floor(heightSegments)||6);phiStart=phiStart!==undefined?phiStart:0;phiLength=phiLength!==undefined?phiLength:Math.PI*2;thetaStart=thetaStart!==undefined?thetaStart:0;thetaLength=thetaLength!==undefined?thetaLength:Math.PI;var thetaEnd=thetaStart+thetaLength;var ix,iy;var index=0;var grid=[];var vertex=new Vector3;var normal=new Vector3;var indices=[];var vertices=[];var normals=[];var uvs=[];for(iy=0;iy<=heightSegments;iy++){var verticesRow=[];var v=iy/heightSegments;for(ix=0;ix<=widthSegments;ix++){var u=ix/widthSegments;vertex.x=-radius*Math.cos(phiStart+u*phiLength)*Math.sin(thetaStart+v*thetaLength);vertex.y=radius*Math.cos(thetaStart+v*thetaLength);vertex.z=radius*Math.sin(phiStart+u*phiLength)*Math.sin(thetaStart+v*thetaLength);vertices.push(vertex.x,vertex.y,vertex.z);normal.set(vertex.x,vertex.y,vertex.z).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(u,1-v);verticesRow.push(index++)}grid.push(verticesRow)}for(iy=0;iy<heightSegments;iy++){for(ix=0;ix<widthSegments;ix++){var a=grid[iy][ix+1];var b=grid[iy][ix];var c=grid[iy+1][ix];var d=grid[iy+1][ix+1];if(iy!==0||thetaStart>0)indices.push(a,b,d);if(iy!==heightSegments-1||thetaEnd<Math.PI)indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}SphereBufferGeometry.prototype=Object.create(BufferGeometry.prototype);SphereBufferGeometry.prototype.constructor=SphereBufferGeometry;function RingGeometry(innerRadius,outerRadius,thetaSegments,phiSegments,thetaStart,thetaLength){Geometry.call(this);this.type="RingGeometry";this.parameters={innerRadius:innerRadius,outerRadius:outerRadius,thetaSegments:thetaSegments,phiSegments:phiSegments,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new RingBufferGeometry(innerRadius,outerRadius,thetaSegments,phiSegments,thetaStart,thetaLength));this.mergeVertices()}RingGeometry.prototype=Object.create(Geometry.prototype);RingGeometry.prototype.constructor=RingGeometry;function RingBufferGeometry(innerRadius,outerRadius,thetaSegments,phiSegments,thetaStart,thetaLength){BufferGeometry.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:innerRadius,outerRadius:outerRadius,thetaSegments:thetaSegments,phiSegments:phiSegments,thetaStart:thetaStart,thetaLength:thetaLength};innerRadius=innerRadius||20;outerRadius=outerRadius||50;thetaStart=thetaStart!==undefined?thetaStart:0;thetaLength=thetaLength!==undefined?thetaLength:Math.PI*2;thetaSegments=thetaSegments!==undefined?Math.max(3,thetaSegments):8;phiSegments=phiSegments!==undefined?Math.max(1,phiSegments):1;var indices=[];var vertices=[];var normals=[];var uvs=[];var segment;var radius=innerRadius;var radiusStep=(outerRadius-innerRadius)/phiSegments;var vertex=new Vector3;var uv=new Vector2;var j,i;for(j=0;j<=phiSegments;j++){for(i=0;i<=thetaSegments;i++){segment=thetaStart+i/thetaSegments*thetaLength;vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);normals.push(0,0,1);uv.x=(vertex.x/outerRadius+1)/2;uv.y=(vertex.y/outerRadius+1)/2;uvs.push(uv.x,uv.y)}radius+=radiusStep}for(j=0;j<phiSegments;j++){var thetaSegmentLevel=j*(thetaSegments+1);for(i=0;i<thetaSegments;i++){segment=i+thetaSegmentLevel;var a=segment;var b=segment+thetaSegments+1;var c=segment+thetaSegments+2;var d=segment+1;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}RingBufferGeometry.prototype=Object.create(BufferGeometry.prototype);RingBufferGeometry.prototype.constructor=RingBufferGeometry;function LatheGeometry(points,segments,phiStart,phiLength){Geometry.call(this);this.type="LatheGeometry";this.parameters={points:points,segments:segments,phiStart:phiStart,phiLength:phiLength};this.fromBufferGeometry(new LatheBufferGeometry(points,segments,phiStart,phiLength));this.mergeVertices()}LatheGeometry.prototype=Object.create(Geometry.prototype);LatheGeometry.prototype.constructor=LatheGeometry;function LatheBufferGeometry(points,segments,phiStart,phiLength){BufferGeometry.call(this);this.type="LatheBufferGeometry";this.parameters={points:points,segments:segments,phiStart:phiStart,phiLength:phiLength};segments=Math.floor(segments)||12;phiStart=phiStart||0;phiLength=phiLength||Math.PI*2;phiLength=_Math.clamp(phiLength,0,Math.PI*2);var indices=[];var vertices=[];var uvs=[];var base;var inverseSegments=1/segments;var vertex=new Vector3;var uv=new Vector2;var i,j;for(i=0;i<=segments;i++){var phi=phiStart+i*inverseSegments*phiLength;var sin=Math.sin(phi);var cos=Math.cos(phi);for(j=0;j<=points.length-1;j++){vertex.x=points[j].x*sin;vertex.y=points[j].y;vertex.z=points[j].x*cos;vertices.push(vertex.x,vertex.y,vertex.z);uv.x=i/segments;uv.y=j/(points.length-1);uvs.push(uv.x,uv.y)}}for(i=0;i<segments;i++){for(j=0;j<points.length-1;j++){base=j+i*points.length;var a=base;var b=base+points.length;var c=base+points.length+1;var d=base+1;indices.push(a,b,d);indices.push(b,c,d)}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));this.computeVertexNormals();if(phiLength===Math.PI*2){var normals=this.attributes.normal.array;var n1=new Vector3;var n2=new Vector3;var n=new Vector3;base=segments*points.length*3;for(i=0,j=0;i<points.length;i++,j+=3){n1.x=normals[j+0];n1.y=normals[j+1];n1.z=normals[j+2];n2.x=normals[base+j+0];n2.y=normals[base+j+1];n2.z=normals[base+j+2];n.addVectors(n1,n2).normalize();normals[j+0]=normals[base+j+0]=n.x;normals[j+1]=normals[base+j+1]=n.y;normals[j+2]=normals[base+j+2]=n.z}}}LatheBufferGeometry.prototype=Object.create(BufferGeometry.prototype);LatheBufferGeometry.prototype.constructor=LatheBufferGeometry;function ShapeGeometry(shapes,curveSegments){Geometry.call(this);this.type="ShapeGeometry";if(typeof curveSegments==="object"){console.warn("THREE.ShapeGeometry: Options parameter has been removed.");curveSegments=curveSegments.curveSegments}this.parameters={shapes:shapes,curveSegments:curveSegments};this.fromBufferGeometry(new ShapeBufferGeometry(shapes,curveSegments));this.mergeVertices()}ShapeGeometry.prototype=Object.create(Geometry.prototype);ShapeGeometry.prototype.constructor=ShapeGeometry;function ShapeBufferGeometry(shapes,curveSegments){BufferGeometry.call(this);this.type="ShapeBufferGeometry";this.parameters={shapes:shapes,curveSegments:curveSegments};curveSegments=curveSegments||12;var indices=[];var vertices=[];var normals=[];var uvs=[];var groupStart=0;var groupCount=0;if(Array.isArray(shapes)===false){addShape(shapes)}else{for(var i=0;i<shapes.length;i++){addShape(shapes[i]);this.addGroup(groupStart,groupCount,i);groupStart+=groupCount;groupCount=0}}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));function addShape(shape){var i,l,shapeHole;var indexOffset=vertices.length/3;var points=shape.extractPoints(curveSegments);var shapeVertices=points.shape;var shapeHoles=points.holes;if(ShapeUtils.isClockWise(shapeVertices)===false){shapeVertices=shapeVertices.reverse();for(i=0,l=shapeHoles.length;i<l;i++){shapeHole=shapeHoles[i];if(ShapeUtils.isClockWise(shapeHole)===true){shapeHoles[i]=shapeHole.reverse()}}}var faces=ShapeUtils.triangulateShape(shapeVertices,shapeHoles);for(i=0,l=shapeHoles.length;i<l;i++){shapeHole=shapeHoles[i];shapeVertices=shapeVertices.concat(shapeHole)}for(i=0,l=shapeVertices.length;i<l;i++){var vertex=shapeVertices[i];vertices.push(vertex.x,vertex.y,0);normals.push(0,0,1);uvs.push(vertex.x,vertex.y)}for(i=0,l=faces.length;i<l;i++){var face=faces[i];var a=face[0]+indexOffset;var b=face[1]+indexOffset;var c=face[2]+indexOffset;indices.push(a,b,c);groupCount+=3}}}ShapeBufferGeometry.prototype=Object.create(BufferGeometry.prototype);ShapeBufferGeometry.prototype.constructor=ShapeBufferGeometry;function EdgesGeometry(geometry,thresholdAngle){BufferGeometry.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:thresholdAngle};thresholdAngle=thresholdAngle!==undefined?thresholdAngle:1;var vertices=[];var thresholdDot=Math.cos(_Math.DEG2RAD*thresholdAngle);var edge=[0,0],edges={},edge1,edge2;var key,keys=["a","b","c"];var geometry2;if(geometry.isBufferGeometry){geometry2=new Geometry;geometry2.fromBufferGeometry(geometry)}else{geometry2=geometry.clone()}geometry2.mergeVertices();geometry2.computeFaceNormals();var sourceVertices=geometry2.vertices;var faces=geometry2.faces;for(var i=0,l=faces.length;i<l;i++){var face=faces[i];for(var j=0;j<3;j++){edge1=face[keys[j]];edge2=face[keys[(j+1)%3]];edge[0]=Math.min(edge1,edge2);edge[1]=Math.max(edge1,edge2);key=edge[0]+","+edge[1];if(edges[key]===undefined){edges[key]={index1:edge[0],index2:edge[1],face1:i,face2:undefined}}else{edges[key].face2=i}}}for(key in edges){var e=edges[key];if(e.face2===undefined||faces[e.face1].normal.dot(faces[e.face2].normal)<=thresholdDot){var vertex=sourceVertices[e.index1];vertices.push(vertex.x,vertex.y,vertex.z);vertex=sourceVertices[e.index2];vertices.push(vertex.x,vertex.y,vertex.z)}}this.addAttribute("position",new Float32BufferAttribute(vertices,3))}EdgesGeometry.prototype=Object.create(BufferGeometry.prototype);EdgesGeometry.prototype.constructor=EdgesGeometry;function CylinderGeometry(radiusTop,radiusBottom,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){Geometry.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:radiusTop,radiusBottom:radiusBottom,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop,radiusBottom,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength));this.mergeVertices()}CylinderGeometry.prototype=Object.create(Geometry.prototype);CylinderGeometry.prototype.constructor=CylinderGeometry;function CylinderBufferGeometry(radiusTop,radiusBottom,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){BufferGeometry.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:radiusTop,radiusBottom:radiusBottom,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};var scope=this;radiusTop=radiusTop!==undefined?radiusTop:20;radiusBottom=radiusBottom!==undefined?radiusBottom:20;height=height!==undefined?height:100;radialSegments=Math.floor(radialSegments)||8;heightSegments=Math.floor(heightSegments)||1;openEnded=openEnded!==undefined?openEnded:false;thetaStart=thetaStart!==undefined?thetaStart:0;thetaLength=thetaLength!==undefined?thetaLength:2*Math.PI;var indices=[];var vertices=[];var normals=[];var uvs=[];var index=0;var indexArray=[];var halfHeight=height/2;var groupStart=0;generateTorso();if(openEnded===false){if(radiusTop>0)generateCap(true);if(radiusBottom>0)generateCap(false)}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2));function generateTorso(){var x,y;var normal=new Vector3;var vertex=new Vector3;var groupCount=0;var slope=(radiusBottom-radiusTop)/height;for(y=0;y<=heightSegments;y++){var indexRow=[];var v=y/heightSegments;var radius=v*(radiusBottom-radiusTop)+radiusTop;for(x=0;x<=radialSegments;x++){var u=x/radialSegments;var theta=u*thetaLength+thetaStart;var sinTheta=Math.sin(theta);var cosTheta=Math.cos(theta);vertex.x=radius*sinTheta;vertex.y=-v*height+halfHeight;vertex.z=radius*cosTheta;vertices.push(vertex.x,vertex.y,vertex.z);normal.set(sinTheta,slope,cosTheta).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(u,1-v);indexRow.push(index++)}indexArray.push(indexRow)}for(x=0;x<radialSegments;x++){for(y=0;y<heightSegments;y++){var a=indexArray[y][x];var b=indexArray[y+1][x];var c=indexArray[y+1][x+1];var d=indexArray[y][x+1];indices.push(a,b,d);indices.push(b,c,d);groupCount+=6}}scope.addGroup(groupStart,groupCount,0);groupStart+=groupCount}function generateCap(top){var x,centerIndexStart,centerIndexEnd;var uv=new Vector2;var vertex=new Vector3;var groupCount=0;var radius=top===true?radiusTop:radiusBottom;var sign=top===true?1:-1;centerIndexStart=index;for(x=1;x<=radialSegments;x++){vertices.push(0,halfHeight*sign,0);normals.push(0,sign,0);uvs.push(.5,.5);index++}centerIndexEnd=index;for(x=0;x<=radialSegments;x++){var u=x/radialSegments;var theta=u*thetaLength+thetaStart;var cosTheta=Math.cos(theta);var sinTheta=Math.sin(theta);vertex.x=radius*sinTheta;vertex.y=halfHeight*sign;vertex.z=radius*cosTheta;vertices.push(vertex.x,vertex.y,vertex.z);normals.push(0,sign,0);uv.x=cosTheta*.5+.5;uv.y=sinTheta*.5*sign+.5;uvs.push(uv.x,uv.y);index++}for(x=0;x<radialSegments;x++){var c=centerIndexStart+x;var i=centerIndexEnd+x;if(top===true){indices.push(i,i+1,c)}else{indices.push(i+1,i,c)}groupCount+=3}scope.addGroup(groupStart,groupCount,top===true?1:2);groupStart+=groupCount}}CylinderBufferGeometry.prototype=Object.create(BufferGeometry.prototype);CylinderBufferGeometry.prototype.constructor=CylinderBufferGeometry;function ConeGeometry(radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){CylinderGeometry.call(this,0,radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength);this.type="ConeGeometry";this.parameters={radius:radius,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength}}ConeGeometry.prototype=Object.create(CylinderGeometry.prototype);ConeGeometry.prototype.constructor=ConeGeometry;function ConeBufferGeometry(radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){CylinderBufferGeometry.call(this,0,radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength);this.type="ConeBufferGeometry";this.parameters={radius:radius,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength}}ConeBufferGeometry.prototype=Object.create(CylinderBufferGeometry.prototype);ConeBufferGeometry.prototype.constructor=ConeBufferGeometry;function CircleGeometry(radius,segments,thetaStart,thetaLength){Geometry.call(this);this.type="CircleGeometry";this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new CircleBufferGeometry(radius,segments,thetaStart,thetaLength));this.mergeVertices()}CircleGeometry.prototype=Object.create(Geometry.prototype);CircleGeometry.prototype.constructor=CircleGeometry;function CircleBufferGeometry(radius,segments,thetaStart,thetaLength){BufferGeometry.call(this);this.type="CircleBufferGeometry";this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};radius=radius||50;segments=segments!==undefined?Math.max(3,segments):8;thetaStart=thetaStart!==undefined?thetaStart:0;thetaLength=thetaLength!==undefined?thetaLength:Math.PI*2;var indices=[];var vertices=[];var normals=[];var uvs=[];var i,s;var vertex=new Vector3;var uv=new Vector2;vertices.push(0,0,0);normals.push(0,0,1);uvs.push(.5,.5);for(s=0,i=3;s<=segments;s++,i+=3){var segment=thetaStart+s/segments*thetaLength;vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);normals.push(0,0,1);uv.x=(vertices[i]/radius+1)/2;uv.y=(vertices[i+1]/radius+1)/2;uvs.push(uv.x,uv.y)}for(i=1;i<=segments;i++){indices.push(i,i+1,0)}this.setIndex(indices);this.addAttribute("position",new Float32BufferAttribute(vertices,3));this.addAttribute("normal",new Float32BufferAttribute(normals,3));this.addAttribute("uv",new Float32BufferAttribute(uvs,2))}CircleBufferGeometry.prototype=Object.create(BufferGeometry.prototype);CircleBufferGeometry.prototype.constructor=CircleBufferGeometry;var Geometries=Object.freeze({WireframeGeometry:WireframeGeometry,ParametricGeometry:ParametricGeometry,ParametricBufferGeometry:ParametricBufferGeometry,TetrahedronGeometry:TetrahedronGeometry,TetrahedronBufferGeometry:TetrahedronBufferGeometry,OctahedronGeometry:OctahedronGeometry,OctahedronBufferGeometry:OctahedronBufferGeometry,IcosahedronGeometry:IcosahedronGeometry,IcosahedronBufferGeometry:IcosahedronBufferGeometry,DodecahedronGeometry:DodecahedronGeometry,DodecahedronBufferGeometry:DodecahedronBufferGeometry,PolyhedronGeometry:PolyhedronGeometry,PolyhedronBufferGeometry:PolyhedronBufferGeometry,TubeGeometry:TubeGeometry,TubeBufferGeometry:TubeBufferGeometry,TorusKnotGeometry:TorusKnotGeometry,TorusKnotBufferGeometry:TorusKnotBufferGeometry,TorusGeometry:TorusGeometry,TorusBufferGeometry:TorusBufferGeometry,TextGeometry:TextGeometry,TextBufferGeometry:TextBufferGeometry,SphereGeometry:SphereGeometry,SphereBufferGeometry:SphereBufferGeometry,RingGeometry:RingGeometry,RingBufferGeometry:RingBufferGeometry,PlaneGeometry:PlaneGeometry,PlaneBufferGeometry:PlaneBufferGeometry,LatheGeometry:LatheGeometry,LatheBufferGeometry:LatheBufferGeometry,ShapeGeometry:ShapeGeometry,ShapeBufferGeometry:ShapeBufferGeometry,ExtrudeGeometry:ExtrudeGeometry,ExtrudeBufferGeometry:ExtrudeBufferGeometry,EdgesGeometry:EdgesGeometry,ConeGeometry:ConeGeometry,ConeBufferGeometry:ConeBufferGeometry,CylinderGeometry:CylinderGeometry,CylinderBufferGeometry:CylinderBufferGeometry,CircleGeometry:CircleGeometry,CircleBufferGeometry:CircleBufferGeometry,BoxGeometry:BoxGeometry,BoxBufferGeometry:BoxBufferGeometry});function ShadowMaterial(parameters){Material.call(this);this.type="ShadowMaterial";this.color=new Color(0);this.opacity=1;this.lights=true;this.transparent=true;this.setValues(parameters)}ShadowMaterial.prototype=Object.create(Material.prototype);ShadowMaterial.prototype.constructor=ShadowMaterial;ShadowMaterial.prototype.isShadowMaterial=true;function RawShaderMaterial(parameters){ShaderMaterial.call(this,parameters);this.type="RawShaderMaterial"}RawShaderMaterial.prototype=Object.create(ShaderMaterial.prototype);RawShaderMaterial.prototype.constructor=RawShaderMaterial;RawShaderMaterial.prototype.isRawShaderMaterial=true;function MeshStandardMaterial(parameters){Material.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new Color(16777215);this.roughness=.5;this.metalness=.5;this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.roughnessMap=null;this.metalnessMap=null;this.alphaMap=null;this.envMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters)}MeshStandardMaterial.prototype=Object.create(Material.prototype);MeshStandardMaterial.prototype.constructor=MeshStandardMaterial;MeshStandardMaterial.prototype.isMeshStandardMaterial=true;MeshStandardMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={STANDARD:""};this.color.copy(source.color);this.roughness=source.roughness;this.metalness=source.metalness;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.roughnessMap=source.roughnessMap;this.metalnessMap=source.metalnessMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.envMapIntensity=source.envMapIntensity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this};function MeshPhysicalMaterial(parameters){MeshStandardMaterial.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoat=0;this.clearCoatRoughness=0;this.setValues(parameters)}MeshPhysicalMaterial.prototype=Object.create(MeshStandardMaterial.prototype);MeshPhysicalMaterial.prototype.constructor=MeshPhysicalMaterial;MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial=true;MeshPhysicalMaterial.prototype.copy=function(source){MeshStandardMaterial.prototype.copy.call(this,source);this.defines={PHYSICAL:""};this.reflectivity=source.reflectivity;this.clearCoat=source.clearCoat;this.clearCoatRoughness=source.clearCoatRoughness;return this};function MeshPhongMaterial(parameters){Material.call(this);this.type="MeshPhongMaterial";this.color=new Color(16777215);this.specular=new Color(1118481);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters)}MeshPhongMaterial.prototype=Object.create(Material.prototype);MeshPhongMaterial.prototype.constructor=MeshPhongMaterial;MeshPhongMaterial.prototype.isMeshPhongMaterial=true;MeshPhongMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this};function MeshToonMaterial(parameters){MeshPhongMaterial.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(parameters)}MeshToonMaterial.prototype=Object.create(MeshPhongMaterial.prototype);MeshToonMaterial.prototype.constructor=MeshToonMaterial;MeshToonMaterial.prototype.isMeshToonMaterial=true;MeshToonMaterial.prototype.copy=function(source){MeshPhongMaterial.prototype.copy.call(this,source);this.gradientMap=source.gradientMap;return this};function MeshNormalMaterial(parameters){Material.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.lights=false;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters)}MeshNormalMaterial.prototype=Object.create(Material.prototype);MeshNormalMaterial.prototype.constructor=MeshNormalMaterial;MeshNormalMaterial.prototype.isMeshNormalMaterial=true;MeshNormalMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this}
function MeshLambertMaterial(parameters){Material.call(this);this.type="MeshLambertMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters)}MeshLambertMaterial.prototype=Object.create(Material.prototype);MeshLambertMaterial.prototype.constructor=MeshLambertMaterial;MeshLambertMaterial.prototype.isMeshLambertMaterial=true;MeshLambertMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this};function LineDashedMaterial(parameters){LineBasicMaterial.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters)}LineDashedMaterial.prototype=Object.create(LineBasicMaterial.prototype);LineDashedMaterial.prototype.constructor=LineDashedMaterial;LineDashedMaterial.prototype.isLineDashedMaterial=true;LineDashedMaterial.prototype.copy=function(source){LineBasicMaterial.prototype.copy.call(this,source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this};var Materials=Object.freeze({ShadowMaterial
ShadowMaterial,SpriteMaterial:SpriteMaterial,RawShaderMaterial:RawShaderMaterial,ShaderMaterial:ShaderMaterial,PointsMaterial:PointsMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshToonMaterial:MeshToonMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshBasicMaterial:MeshBasicMaterial,LineDashedMaterial:LineDashedMaterial,LineBasicMaterial:LineBasicMaterial,Material:Material});var Cache={enabled:false,files:{},add:function(key,file){if(this.enabled===false)return;this.files[key]=file},get:function(key){if(this.enabled===false)return;return this.files[key]},remove:function(key){delete this.files[key]},clear:function(){this.files={}}};function LoadingManager(onLoad,onProgress,onError){var scope=this;var isLoading=false,itemsLoaded=0,itemsTotal=0;this.onStart=undefined;this.onLoad=onLoad;this.onProgress=onProgress;this.onError=onError;this.itemStart=function(url){itemsTotal++;if(isLoading===false){if(scope.onStart!==undefined){scope.onStart(url,itemsLoaded,itemsTotal)}}isLoading=true};this.itemEnd=function(url){itemsLoaded++;if(scope.onProgress!==undefined){scope.onProgress(url,itemsLoaded,itemsTotal)}if(itemsLoaded===itemsTotal){isLoading=false;if(scope.onLoad!==undefined){scope.onLoad()}}};this.itemError=function(url){if(scope.onError!==undefined){scope.onError(url)}}}var DefaultLoadingManager=new LoadingManager;function FileLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(FileLoader.prototype,{load:function(url,onLoad,onProgress,onError){if(url===undefined)url="";if(this.path!==undefined)url=this.path+url;var scope=this;var cached=Cache.get(url);if(cached!==undefined){scope.manager.itemStart(url);setTimeout(function(){if(onLoad)onLoad(cached);scope.manager.itemEnd(url)},0);return cached}var dataUriRegex=/^data:(.*?)(;base64)?,(.*)$/;var dataUriRegexResult=url.match(dataUriRegex);if(dataUriRegexResult){var mimeType=dataUriRegexResult[1];var isBase64=!!dataUriRegexResult[2];var data=dataUriRegexResult[3];data=window.decodeURIComponent(data);if(isBase64)data=window.atob(data);try{var response;var responseType=(this.responseType||"").toLowerCase();switch(responseType){case"arraybuffer":case"blob":response=new ArrayBuffer(data.length);var view=new Uint8Array(response);for(var i=0;i<data.length;i++){view[i]=data.charCodeAt(i)}if(responseType==="blob"){response=new Blob([response],{type:mimeType})}break;case"document":var parser=new DOMParser;response=parser.parseFromString(data,mimeType);break;case"json":response=JSON.parse(data);break;default:response=data;break}window.setTimeout(function(){if(onLoad)onLoad(response);scope.manager.itemEnd(url)},0)}catch(error){window.setTimeout(function(){if(onError)onError(error);scope.manager.itemEnd(url);scope.manager.itemError(url)},0)}}else{var request=new XMLHttpRequest;request.open("GET",url,true);request.addEventListener("load",function(event){var response=event.target.response;Cache.add(url,response);if(this.status===200){if(onLoad)onLoad(response);scope.manager.itemEnd(url)}else if(this.status===0){console.warn("THREE.FileLoader: HTTP Status 0 received.");if(onLoad)onLoad(response);scope.manager.itemEnd(url)}else{if(onError)onError(event);scope.manager.itemEnd(url);scope.manager.itemError(url)}},false);if(onProgress!==undefined){request.addEventListener("progress",function(event){onProgress(event)},false)}request.addEventListener("error",function(event){if(onError)onError(event);scope.manager.itemEnd(url);scope.manager.itemError(url)},false);if(this.responseType!==undefined)request.responseType=this.responseType;if(this.withCredentials!==undefined)request.withCredentials=this.withCredentials;if(request.overrideMimeType)request.overrideMimeType(this.mimeType!==undefined?this.mimeType:"text/plain");for(var header in this.requestHeader){request.setRequestHeader(header,this.requestHeader[header])}request.send(null)}scope.manager.itemStart(url);return request},setPath:function(value){this.path=value;return this},setResponseType:function(value){this.responseType=value;return this},setWithCredentials:function(value){this.withCredentials=value;return this},setMimeType:function(value){this.mimeType=value;return this},setRequestHeader:function(value){this.requestHeader=value;return this}});function CompressedTextureLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager;this._parser=null}Object.assign(CompressedTextureLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var images=[];var texture=new CompressedTexture;texture.image=images;var loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setResponseType("arraybuffer");function loadTexture(i){loader.load(url[i],function(buffer){var texDatas=scope._parser(buffer,true);images[i]={width:texDatas.width,height:texDatas.height,format:texDatas.format,mipmaps:texDatas.mipmaps};loaded+=1;if(loaded===6){if(texDatas.mipmapCount===1)texture.minFilter=LinearFilter;texture.format=texDatas.format;texture.needsUpdate=true;if(onLoad)onLoad(texture)}},onProgress,onError)}if(Array.isArray(url)){var loaded=0;for(var i=0,il=url.length;i<il;++i){loadTexture(i)}}else{loader.load(url,function(buffer){var texDatas=scope._parser(buffer,true);if(texDatas.isCubemap){var faces=texDatas.mipmaps.length/texDatas.mipmapCount;for(var f=0;f<faces;f++){images[f]={mipmaps:[]};for(var i=0;i<texDatas.mipmapCount;i++){images[f].mipmaps.push(texDatas.mipmaps[f*texDatas.mipmapCount+i]);images[f].format=texDatas.format;images[f].width=texDatas.width;images[f].height=texDatas.height}}}else{texture.image.width=texDatas.width;texture.image.height=texDatas.height;texture.mipmaps=texDatas.mipmaps}if(texDatas.mipmapCount===1){texture.minFilter=LinearFilter}texture.format=texDatas.format;texture.needsUpdate=true;if(onLoad)onLoad(texture)},onProgress,onError)}return texture},setPath:function(value){this.path=value;return this}});function DataTextureLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager;this._parser=null}Object.assign(DataTextureLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var texture=new DataTexture;var loader=new FileLoader(this.manager);loader.setResponseType("arraybuffer");loader.load(url,function(buffer){var texData=scope._parser(buffer);if(!texData)return;if(undefined!==texData.image){texture.image=texData.image}else if(undefined!==texData.data){texture.image.width=texData.width;texture.image.height=texData.height;texture.image.data=texData.data}texture.wrapS=undefined!==texData.wrapS?texData.wrapS:ClampToEdgeWrapping;texture.wrapT=undefined!==texData.wrapT?texData.wrapT:ClampToEdgeWrapping;texture.magFilter=undefined!==texData.magFilter?texData.magFilter:LinearFilter;texture.minFilter=undefined!==texData.minFilter?texData.minFilter:LinearMipMapLinearFilter;texture.anisotropy=undefined!==texData.anisotropy?texData.anisotropy:1;if(undefined!==texData.format){texture.format=texData.format}if(undefined!==texData.type){texture.type=texData.type}if(undefined!==texData.mipmaps){texture.mipmaps=texData.mipmaps}if(1===texData.mipmapCount){texture.minFilter=LinearFilter}texture.needsUpdate=true;if(onLoad)onLoad(texture,texData)},onProgress,onError);return texture}});function ImageLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(ImageLoader.prototype,{crossOrigin:"Anonymous",load:function(url,onLoad,onProgress,onError){if(url===undefined)url="";if(this.path!==undefined)url=this.path+url;var scope=this;var cached=Cache.get(url);if(cached!==undefined){scope.manager.itemStart(url);setTimeout(function(){if(onLoad)onLoad(cached);scope.manager.itemEnd(url)},0);return cached}var image=document.createElementNS("http://www.w3.org/1999/xhtml","img");image.addEventListener("load",function(){Cache.add(url,this);if(onLoad)onLoad(this);scope.manager.itemEnd(url)},false);image.addEventListener("error",function(event){if(onError)onError(event);scope.manager.itemEnd(url);scope.manager.itemError(url)},false);if(url.substr(0,5)!=="data:"){if(this.crossOrigin!==undefined)image.crossOrigin=this.crossOrigin}scope.manager.itemStart(url);image.src=url;return image},setCrossOrigin:function(value){this.crossOrigin=value;return this},setPath:function(value){this.path=value;return this}});function CubeTextureLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(CubeTextureLoader.prototype,{crossOrigin:"Anonymous",load:function(urls,onLoad,onProgress,onError){var texture=new CubeTexture;var loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);loader.setPath(this.path);var loaded=0;function loadTexture(i){loader.load(urls[i],function(image){texture.images[i]=image;loaded++;if(loaded===6){texture.needsUpdate=true;if(onLoad)onLoad(texture)}},undefined,onError)}for(var i=0;i<urls.length;++i){loadTexture(i)}return texture},setCrossOrigin:function(value){this.crossOrigin=value;return this},setPath:function(value){this.path=value;return this}});function TextureLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(TextureLoader.prototype,{crossOrigin:"Anonymous",load:function(url,onLoad,onProgress,onError){var loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);loader.setPath(this.path);var texture=new Texture;texture.image=loader.load(url,function(){var isJPEG=url.search(/\.(jpg|jpeg)$/)>0||url.search(/^data\:image\/jpeg/)===0;texture.format=isJPEG?RGBFormat:RGBAFormat;texture.needsUpdate=true;if(onLoad!==undefined){onLoad(texture)}},onProgress,onError);return texture},setCrossOrigin:function(value){this.crossOrigin=value;return this},setPath:function(value){this.path=value;return this}});function Light(color,intensity){Object3D.call(this);this.type="Light";this.color=new Color(color);this.intensity=intensity!==undefined?intensity:1;this.receiveShadow=undefined}Light.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Light,isLight:true,copy:function(source){Object3D.prototype.copy.call(this,source);this.color.copy(source.color);this.intensity=source.intensity;return this},toJSON:function(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.color=this.color.getHex();data.object.intensity=this.intensity;if(this.groundColor!==undefined)data.object.groundColor=this.groundColor.getHex();if(this.distance!==undefined)data.object.distance=this.distance;if(this.angle!==undefined)data.object.angle=this.angle;if(this.decay!==undefined)data.object.decay=this.decay;if(this.penumbra!==undefined)data.object.penumbra=this.penumbra;if(this.shadow!==undefined)data.object.shadow=this.shadow.toJSON();return data}});function HemisphereLight(skyColor,groundColor,intensity){Light.call(this,skyColor,intensity);this.type="HemisphereLight";this.castShadow=undefined;this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.groundColor=new Color(groundColor)}HemisphereLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:HemisphereLight,isHemisphereLight:true,copy:function(source){Light.prototype.copy.call(this,source);this.groundColor.copy(source.groundColor);return this}});function LightShadow(camera){this.camera=camera;this.bias=0;this.radius=1;this.mapSize=new Vector2(512,512);this.map=null;this.matrix=new Matrix4}Object.assign(LightShadow.prototype,{copy:function(source){this.camera=source.camera.clone();this.bias=source.bias;this.radius=source.radius;this.mapSize.copy(source.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var object={};if(this.bias!==0)object.bias=this.bias;if(this.radius!==1)object.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)object.mapSize=this.mapSize.toArray();object.camera=this.camera.toJSON(false).object;delete object.camera.matrix;return object}});function SpotLightShadow(){LightShadow.call(this,new PerspectiveCamera(50,1,.5,500))}SpotLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:SpotLightShadow,isSpotLightShadow:true,update:function(light){var camera=this.camera;var fov=_Math.RAD2DEG*2*light.angle;var aspect=this.mapSize.width/this.mapSize.height;var far=light.distance||camera.far;if(fov!==camera.fov||aspect!==camera.aspect||far!==camera.far){camera.fov=fov;camera.aspect=aspect;camera.far=far;camera.updateProjectionMatrix()}}});function SpotLight(color,intensity,distance,angle,penumbra,decay){Light.call(this,color,intensity);this.type="SpotLight";this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.target=new Object3D;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(power){this.intensity=power/Math.PI}});this.distance=distance!==undefined?distance:0;this.angle=angle!==undefined?angle:Math.PI/3;this.penumbra=penumbra!==undefined?penumbra:0;this.decay=decay!==undefined?decay:1;this.shadow=new SpotLightShadow}SpotLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:SpotLight,isSpotLight:true,copy:function(source){Light.prototype.copy.call(this,source);this.distance=source.distance;this.angle=source.angle;this.penumbra=source.penumbra;this.decay=source.decay;this.target=source.target.clone();this.shadow=source.shadow.clone();return this}});function PointLight(color,intensity,distance,decay){Light.call(this,color,intensity);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return this.intensity*4*Math.PI},set:function(power){this.intensity=power/(4*Math.PI)}});this.distance=distance!==undefined?distance:0;this.decay=decay!==undefined?decay:1;this.shadow=new LightShadow(new PerspectiveCamera(90,1,.5,500))}PointLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:PointLight,isPointLight:true,copy:function(source){Light.prototype.copy.call(this,source);this.distance=source.distance;this.decay=source.decay;this.shadow=source.shadow.clone();return this}});function DirectionalLightShadow(){LightShadow.call(this,new OrthographicCamera(-5,5,5,-5,.5,500))}DirectionalLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:DirectionalLightShadow});function DirectionalLight(color,intensity){Light.call(this,color,intensity);this.type="DirectionalLight";this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.target=new Object3D;this.shadow=new DirectionalLightShadow}DirectionalLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:DirectionalLight,isDirectionalLight:true,copy:function(source){Light.prototype.copy.call(this,source);this.target=source.target.clone();this.shadow=source.shadow.clone();return this}});function AmbientLight(color,intensity){Light.call(this,color,intensity);this.type="AmbientLight";this.castShadow=undefined}AmbientLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:AmbientLight,isAmbientLight:true});function RectAreaLight(color,intensity,width,height){Light.call(this,color,intensity);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=width!==undefined?width:10;this.height=height!==undefined?height:10}RectAreaLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:RectAreaLight,isRectAreaLight:true,copy:function(source){Light.prototype.copy.call(this,source);this.width=source.width;this.height=source.height;return this},toJSON:function(meta){var data=Light.prototype.toJSON.call(this,meta);data.object.width=this.width;data.object.height=this.height;return data}});var AnimationUtils={arraySlice:function(array,from,to){if(AnimationUtils.isTypedArray(array)){return new array.constructor(array.subarray(from,to!==undefined?to:array.length))}return array.slice(from,to)},convertArray:function(array,type,forceClone){if(!array||!forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==="number"){return new type(array)}return Array.prototype.slice.call(array)},isTypedArray:function(object){return ArrayBuffer.isView(object)&&!(object instanceof DataView)},getKeyframeOrder:function(times){function compareTime(i,j){return times[i]-times[j]}var n=times.length;var result=new Array(n);for(var i=0;i!==n;++i)result[i]=i;result.sort(compareTime);return result},sortedArray:function(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var i=0,dstOffset=0;dstOffset!==nValues;++i){var srcOffset=order[i]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j]}}return result},flattenJSON:function(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++]}if(key===undefined)return;var value=key[valuePropertyName];if(value===undefined)return;if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push.apply(values,value)}key=jsonKeys[i++]}while(key!==undefined)}else if(value.toArray!==undefined){do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);value.toArray(values,values.length)}key=jsonKeys[i++]}while(key!==undefined)}else{do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push(value)}key=jsonKeys[i++]}while(key!==undefined)}}};function Interpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){this.parameterPositions=parameterPositions;this._cachedIndex=0;this.resultBuffer=resultBuffer!==undefined?resultBuffer:new sampleValues.constructor(sampleSize);this.sampleValues=sampleValues;this.valueSize=sampleSize}Object.assign(Interpolant.prototype,{evaluate:function(t){var pp=this.parameterPositions,i1=this._cachedIndex,t1=pp[i1],t0=pp[i1-1];validate_interval:{seek:{var right;linear_scan:{forward_scan:if(!(t<t1)){for(var giveUpAt=i1+2;;){if(t1===undefined){if(t<t0)break forward_scan;i1=pp.length;this._cachedIndex=i1;return this.afterEnd_(i1-1,t,t0)}if(i1===giveUpAt)break;t0=t1;t1=pp[++i1];if(t<t1){break seek}}right=pp.length;break linear_scan}if(!(t>=t0)){var t1global=pp[1];if(t<t1global){i1=2;t0=t1global}for(var giveUpAt=i1-2;;){if(t0===undefined){this._cachedIndex=0;return this.beforeStart_(0,t,t1)}if(i1===giveUpAt)break;t1=t0;t0=pp[--i1-1];if(t>=t0){break seek}}right=i1;i1=0;break linear_scan}break validate_interval}while(i1<right){var mid=i1+right>>>1;if(t<pp[mid]){right=mid}else{i1=mid+1}}t1=pp[i1];t0=pp[i1-1];if(t0===undefined){this._cachedIndex=0;return this.beforeStart_(0,t,t1)}if(t1===undefined){i1=pp.length;this._cachedIndex=i1;return this.afterEnd_(i1-1,t0,t)}}this._cachedIndex=i1;this.intervalChanged_(i1,t0,t1)}return this.interpolate_(i1,t0,t,t1)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||this.DefaultSettings_},copySampleValue_:function(index){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset=index*stride;for(var i=0;i!==stride;++i){result[i]=values[offset+i]}return result},interpolate_:function(i1,t0,t,t1){throw new Error("call to abstract method")},intervalChanged_:function(i1,t0,t1){}});Object.assign(Interpolant.prototype,{beforeStart_:Interpolant.prototype.copySampleValue_,afterEnd_:Interpolant.prototype.copySampleValue_});function CubicInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);this._weightPrev=-0;this._offsetPrev=-0;this._weightNext=-0;this._offsetNext=-0}CubicInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:CubicInterpolant,DefaultSettings_:{endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding},intervalChanged_:function(i1,t0,t1){var pp=this.parameterPositions,iPrev=i1-2,iNext=i1+1,tPrev=pp[iPrev],tNext=pp[iNext];if(tPrev===undefined){switch(this.getSettings_().endingStart){case ZeroSlopeEnding:iPrev=i1;tPrev=2*t0-t1;break;case WrapAroundEnding:iPrev=pp.length-2;tPrev=t0+pp[iPrev]-pp[iPrev+1];break;default:iPrev=i1;tPrev=t1}}if(tNext===undefined){switch(this.getSettings_().endingEnd){case ZeroSlopeEnding:iNext=i1;tNext=2*t1-t0;break;case WrapAroundEnding:iNext=1;tNext=t1+pp[1]-pp[0];break;default:iNext=i1-1;tNext=t0}}var halfDt=(t1-t0)*.5,stride=this.valueSize;this._weightPrev=halfDt/(t0-tPrev);this._weightNext=halfDt/(tNext-t1);this._offsetPrev=iPrev*stride;this._offsetNext=iNext*stride},interpolate_:function(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,o1=i1*stride,o0=o1-stride,oP=this._offsetPrev,oN=this._offsetNext,wP=this._weightPrev,wN=this._weightNext,p=(t-t0)/(t1-t0),pp=p*p,ppp=pp*p;var sP=-wP*ppp+2*wP*pp-wP*p;var s0=(1+wP)*ppp+(-1.5-2*wP)*pp+(-.5+wP)*p+1;var s1=(-1-wN)*ppp+(1.5+wN)*pp+.5*p;var sN=wN*ppp-wN*pp;for(var i=0;i!==stride;++i){result[i]=sP*values[oP+i]+s0*values[o0+i]+s1*values[o1+i]+sN*values[oN+i]}return result}});function LinearInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer)}LinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:LinearInterpolant,interpolate_:function(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset1=i1*stride,offset0=offset1-stride,weight1=(t-t0)/(t1-t0),weight0=1-weight1;for(var i=0;i!==stride;++i){result[i]=values[offset0+i]*weight0+values[offset1+i]*weight1}return result}});function DiscreteInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer)}DiscreteInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:DiscreteInterpolant,interpolate_:function(i1,t0,t,t1){return this.copySampleValue_(i1-1)}});var KeyframeTrackPrototype;KeyframeTrackPrototype={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodDiscrete:function(result){return new DiscreteInterpolant(this.times,this.values,this.getValueSize(),result)},InterpolantFactoryMethodLinear:function(result){return new LinearInterpolant(this.times,this.values,this.getValueSize(),result)},InterpolantFactoryMethodSmooth:function(result){return new CubicInterpolant(this.times,this.values,this.getValueSize(),result)},setInterpolation:function(interpolation){var factoryMethod;switch(interpolation){case InterpolateDiscrete:factoryMethod=this.InterpolantFactoryMethodDiscrete;break;case InterpolateLinear:factoryMethod=this.InterpolantFactoryMethodLinear;break;case InterpolateSmooth:factoryMethod=this.InterpolantFactoryMethodSmooth;break}if(factoryMethod===undefined){var message="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===undefined){if(interpolation!==this.DefaultInterpolation){this.setInterpolation(this.DefaultInterpolation)}else{throw new Error(message)}}console.warn("THREE.KeyframeTrackPrototype:",message);return}this.createInterpolant=factoryMethod},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return InterpolateDiscrete;case this.InterpolantFactoryMethodLinear:return InterpolateLinear;case this.InterpolantFactoryMethodSmooth:return InterpolateSmooth}},getValueSize:function(){return this.values.length/this.times.length},shift:function(timeOffset){if(timeOffset!==0){var times=this.times;for(var i=0,n=times.length;i!==n;++i){times[i]+=timeOffset}}return this},scale:function(timeScale){if(timeScale!==1){var times=this.times;for(var i=0,n=times.length;i!==n;++i){times[i]*=timeScale}}return this},trim:function(startTime,endTime){var times=this.times,nKeys=times.length,from=0,to=nKeys-1;while(from!==nKeys&&times[from]<startTime)++from;while(to!==-1&&times[to]>endTime)--to;++to;if(from!==0||to!==nKeys){if(from>=to)to=Math.max(to,1),from=to-1;var stride=this.getValueSize();this.times=AnimationUtils.arraySlice(times,from,to);this.values=AnimationUtils.arraySlice(this.values,from*stride,to*stride)}return this},validate:function(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this);valid=false}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error("THREE.KeyframeTrackPrototype: Track is empty.",this);valid=false}var prevTime=null;for(var i=0;i!==nKeys;i++){var currTime=times[i];if(typeof currTime==="number"&&isNaN(currTime)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",this,i,currTime);valid=false;break}if(prevTime!==null&&prevTime>currTime){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,i,currTime,prevTime);valid=false;break}prevTime=currTime}if(values!==undefined){if(AnimationUtils.isTypedArray(values)){for(var i=0,n=values.length;i!==n;++i){var value=values[i];if(isNaN(value)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,i,value);valid=false;break}}}}return valid},optimize:function(){var times=this.times,values=this.values,stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,writeIndex=1,lastIndex=times.length-1;for(var i=1;i<lastIndex;++i){var keep=false;var time=times[i];var timeNext=times[i+1];if(time!==timeNext&&(i!==1||time!==time[0])){if(!smoothInterpolation){var offset=i*stride,offsetP=offset-stride,offsetN=offset+stride;for(var j=0;j!==stride;++j){var value=values[offset+j];if(value!==values[offsetP+j]||value!==values[offsetN+j]){keep=true;break}}}else keep=true}if(keep){if(i!==writeIndex){times[writeIndex]=times[i];var readOffset=i*stride,writeOffset=writeIndex*stride;for(var j=0;j!==stride;++j)values[writeOffset+j]=values[readOffset+j]}++writeIndex}}if(lastIndex>0){times[writeIndex]=times[lastIndex];for(var readOffset=lastIndex*stride,writeOffset=writeIndex*stride,j=0;j!==stride;++j)values[writeOffset+j]=values[readOffset+j];++writeIndex}if(writeIndex!==times.length){this.times=AnimationUtils.arraySlice(times,0,writeIndex);this.values=AnimationUtils.arraySlice(values,0,writeIndex*stride)}return this}};function KeyframeTrackConstructor(name,times,values,interpolation){if(name===undefined)throw new Error("track name is undefined");if(times===undefined||times.length===0){throw new Error("no keyframes in track named "+name)}this.name=name;this.times=AnimationUtils.convertArray(times,this.TimeBufferType);this.values=AnimationUtils.convertArray(values,this.ValueBufferType);this.setInterpolation(interpolation||this.DefaultInterpolation);this.validate();this.optimize()}function VectorKeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.call(this,name,times,values,interpolation)}VectorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:VectorKeyframeTrack,ValueTypeName:"vector"});function QuaternionLinearInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer)}QuaternionLinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:QuaternionLinearInterpolant,interpolate_:function(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset=i1*stride,alpha=(t-t0)/(t1-t0);for(var end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha)}return result}});function QuaternionKeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.call(this,name,times,values,interpolation)}QuaternionKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:QuaternionKeyframeTrack,ValueTypeName:"quaternion",DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodLinear:function(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result)},InterpolantFactoryMethodSmooth:undefined});function NumberKeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.call(this,name,times,values,interpolation)}NumberKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:NumberKeyframeTrack,ValueTypeName:"number"});function StringKeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.call(this,name,times,values,interpolation)}StringKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:StringKeyframeTrack,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined});function BooleanKeyframeTrack(name,times,values){KeyframeTrackConstructor.call(this,name,times,values)}BooleanKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:BooleanKeyframeTrack,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined});function ColorKeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.call(this,name,times,values,interpolation)}ColorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrackPrototype),{constructor:ColorKeyframeTrack,ValueTypeName:"color"});function KeyframeTrack(name,times,values,interpolation){KeyframeTrackConstructor.apply(this,arguments)}KeyframeTrack.prototype=KeyframeTrackPrototype
KeyframeTrackPrototype.constructor=KeyframeTrack;Object.assign(KeyframeTrack,{parse
function(json){if(json.type===undefined){throw new Error("track type undefined, can not parse")}var trackType=KeyframeTrack._getTrackTypeForValueTypeName(json.type);if(json.times===undefined){var times=[],values=[];AnimationUtils.flattenJSON(json.keys,times,values,"value");json.times=times;json.values=values}if(trackType.parse!==undefined){return trackType.parse(json)}else{return new trackType(json.name,json.times,json.values,json.interpolation)}},toJSON:function(track){var trackType=track.constructor;var json;if(trackType.toJSON!==undefined){json=trackType.toJSON(track)}else{json={name:track.name,times:AnimationUtils.convertArray(track.times,Array),values:AnimationUtils.convertArray(track.values,Array)};var interpolation=track.getInterpolation();if(interpolation!==track.DefaultInterpolation){json.interpolation=interpolation}}json.type=track.ValueTypeName;return json},_getTrackTypeForValueTypeName:function(typeName){switch(typeName.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return NumberKeyframeTrack;case"vector":case"vector2":case"vector3":case"vector4":return VectorKeyframeTrack;case"color":return ColorKeyframeTrack;case"quaternion":return QuaternionKeyframeTrack;case"bool":case"boolean":return BooleanKeyframeTrack;case"string":return StringKeyframeTrack}throw new Error("Unsupported typeName: "+typeName)}});function AnimationClip(name,duration,tracks){this.name=name;this.tracks=tracks;this.duration=duration!==undefined?duration:-1;this.uuid=_Math.generateUUID();if(this.duration<0){this.resetDuration()}this.optimize()}Object.assign(AnimationClip,{parse:function(json){var tracks=[],jsonTracks=json.tracks,frameTime=1/(json.fps||1);for(var i=0,n=jsonTracks.length;i!==n;++i){tracks.push(KeyframeTrack.parse(jsonTracks[i]).scale(frameTime))}return new AnimationClip(json.name,json.duration,tracks)},toJSON:function(clip){var tracks=[],clipTracks=clip.tracks;var json={name:clip.name,duration:clip.duration,tracks:tracks};for(var i=0,n=clipTracks.length;i!==n;++i){tracks.push(KeyframeTrack.toJSON(clipTracks[i]))}return json},CreateFromMorphTargetSequence:function(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var i=0;i<numMorphTargets;i++){var times=[];var values=[];times.push((i+numMorphTargets-1)%numMorphTargets,i,(i+1)%numMorphTargets);values.push(0,1,0);var order=AnimationUtils.getKeyframeOrder(times);times=AnimationUtils.sortedArray(times,1,order);values=AnimationUtils.sortedArray(values,1,order);if(!noLoop&&times[0]===0){times.push(numMorphTargets);values.push(values[0])}tracks.push(new NumberKeyframeTrack(".morphTargetInfluences["+morphTargetSequence[i].name+"]",times,values).scale(1/fps))}return new AnimationClip(name,-1,tracks)},findByName:function(objectOrClipArray,name){var clipArray=objectOrClipArray;if(!Array.isArray(objectOrClipArray)){var o=objectOrClipArray;clipArray=o.geometry&&o.geometry.animations||o.animations}for(var i=0;i<clipArray.length;i++){if(clipArray[i].name===name){return clipArray[i]}}return null},CreateClipsFromMorphTargetSequences:function(morphTargets,fps,noLoop){var animationToMorphTargets={};var pattern=/^([\w-]*?)([\d]+)$/;for(var i=0,il=morphTargets.length;i<il;i++){var morphTarget=morphTargets[i];var parts=morphTarget.name.match(pattern);if(parts&&parts.length>1){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[]}animationMorphTargets.push(morphTarget)}}var clips=[];for(var name in animationToMorphTargets){clips.push(AnimationClip.CreateFromMorphTargetSequence(name,animationToMorphTargets[name],fps,noLoop))}return clips},parseAnimation:function(animation,bones){if(!animation){console.error("THREE.AnimationClip: No animation in JSONLoader data.");return null}var addNonemptyTrack=function(trackType,trackName,animationKeys,propertyName,destTracks){if(animationKeys.length!==0){var times=[];var values=[];AnimationUtils.flattenJSON(animationKeys,times,values,propertyName);if(times.length!==0){destTracks.push(new trackType(trackName,times,values))}}};var tracks=[];var clipName=animation.name||"default";var duration=animation.length||-1;var fps=animation.fps||30;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h<hierarchyTracks.length;h++){var animationKeys=hierarchyTracks[h].keys;if(!animationKeys||animationKeys.length===0)continue;if(animationKeys[0].morphTargets){var morphTargetNames={};for(var k=0;k<animationKeys.length;k++){if(animationKeys[k].morphTargets){for(var m=0;m<animationKeys[k].morphTargets.length;m++){morphTargetNames[animationKeys[k].morphTargets[m]]=-1}}}for(var morphTargetName in morphTargetNames){var times=[];var values=[];for(var m=0;m!==animationKeys[k].morphTargets.length;++m){var animationKey=animationKeys[k];times.push(animationKey.time);values.push(animationKey.morphTarget===morphTargetName?1:0)}tracks.push(new NumberKeyframeTrack(".morphTargetInfluence["+morphTargetName+"]",times,values))}duration=morphTargetNames.length*(fps||1)}else{var boneName=".bones["+bones[h].name+"]";addNonemptyTrack(VectorKeyframeTrack,boneName+".position",animationKeys,"pos",tracks);addNonemptyTrack(QuaternionKeyframeTrack,boneName+".quaternion",animationKeys,"rot",tracks);addNonemptyTrack(VectorKeyframeTrack,boneName+".scale",animationKeys,"scl",tracks)}}if(tracks.length===0){return null}var clip=new AnimationClip(clipName,duration,tracks);return clip}});Object.assign(AnimationClip.prototype,{resetDuration:function(){var tracks=this.tracks,duration=0;for(var i=0,n=tracks.length;i!==n;++i){var track=this.tracks[i];duration=Math.max(duration,track.times[track.times.length-1])}this.duration=duration},trim:function(){for(var i=0;i<this.tracks.length;i++){this.tracks[i].trim(0,this.duration)}return this},optimize:function(){for(var i=0;i<this.tracks.length;i++){this.tracks[i].optimize()}return this}});function MaterialLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager;this.textures={}}Object.assign(MaterialLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.load(url,function(text){onLoad(scope.parse(JSON.parse(text)))},onProgress,onError)},setTextures:function(value){this.textures=value},parse:function(json){var textures=this.textures;function getTexture(name){if(textures[name]===undefined){console.warn("THREE.MaterialLoader: Undefined texture",name)}return textures[name]}var material=new Materials[json.type];if(json.uuid!==undefined)material.uuid=json.uuid;if(json.name!==undefined)material.name=json.name;if(json.color!==undefined)material.color.setHex(json.color);if(json.roughness!==undefined)material.roughness=json.roughness;if(json.metalness!==undefined)material.metalness=json.metalness;if(json.emissive!==undefined)material.emissive.setHex(json.emissive);if(json.specular!==undefined)material.specular.setHex(json.specular);if(json.shininess!==undefined)material.shininess=json.shininess;if(json.clearCoat!==undefined)material.clearCoat=json.clearCoat;if(json.clearCoatRoughness!==undefined)material.clearCoatRoughness=json.clearCoatRoughness;if(json.uniforms!==undefined)material.uniforms=json.uniforms;if(json.vertexShader!==undefined)material.vertexShader=json.vertexShader;if(json.fragmentShader!==undefined)material.fragmentShader=json.fragmentShader;if(json.vertexColors!==undefined)material.vertexColors=json.vertexColors;if(json.fog!==undefined)material.fog=json.fog;if(json.flatShading!==undefined)material.flatShading=json.flatShading;if(json.blending!==undefined)material.blending=json.blending;if(json.side!==undefined)material.side=json.side;if(json.opacity!==undefined)material.opacity=json.opacity;if(json.transparent!==undefined)material.transparent=json.transparent;if(json.alphaTest!==undefined)material.alphaTest=json.alphaTest;if(json.depthTest!==undefined)material.depthTest=json.depthTest;if(json.depthWrite!==undefined)material.depthWrite=json.depthWrite;if(json.colorWrite!==undefined)material.colorWrite=json.colorWrite;if(json.wireframe!==undefined)material.wireframe=json.wireframe;if(json.wireframeLinewidth!==undefined)material.wireframeLinewidth=json.wireframeLinewidth;if(json.wireframeLinecap!==undefined)material.wireframeLinecap=json.wireframeLinecap;if(json.wireframeLinejoin!==undefined)material.wireframeLinejoin=json.wireframeLinejoin;if(json.skinning!==undefined)material.skinning=json.skinning;if(json.morphTargets!==undefined)material.morphTargets=json.morphTargets;if(json.dithering!==undefined)material.dithering=json.dithering;if(json.visible!==undefined)material.visible=json.visible;if(json.userData!==undefined)material.userData=json.userData;if(json.shading!==undefined)material.flatShading=json.shading===1;if(json.size!==undefined)material.size=json.size;if(json.sizeAttenuation!==undefined)material.sizeAttenuation=json.sizeAttenuation;if(json.map!==undefined)material.map=getTexture(json.map);if(json.alphaMap!==undefined){material.alphaMap=getTexture(json.alphaMap);material.transparent=true}if(json.bumpMap!==undefined)material.bumpMap=getTexture(json.bumpMap);if(json.bumpScale!==undefined)material.bumpScale=json.bumpScale;if(json.normalMap!==undefined)material.normalMap=getTexture(json.normalMap);if(json.normalScale!==undefined){var normalScale=json.normalScale;if(Array.isArray(normalScale)===false){normalScale=[normalScale,normalScale]}material.normalScale=(new Vector2).fromArray(normalScale)}if(json.displacementMap!==undefined)material.displacementMap=getTexture(json.displacementMap);if(json.displacementScale!==undefined)material.displacementScale=json.displacementScale;if(json.displacementBias!==undefined)material.displacementBias=json.displacementBias;if(json.roughnessMap!==undefined)material.roughnessMap=getTexture(json.roughnessMap);if(json.metalnessMap!==undefined)material.metalnessMap=getTexture(json.metalnessMap);if(json.emissiveMap!==undefined)material.emissiveMap=getTexture(json.emissiveMap);if(json.emissiveIntensity!==undefined)material.emissiveIntensity=json.emissiveIntensity;if(json.specularMap!==undefined)material.specularMap=getTexture(json.specularMap);if(json.envMap!==undefined)material.envMap=getTexture(json.envMap);if(json.reflectivity!==undefined)material.reflectivity=json.reflectivity;if(json.lightMap!==undefined)material.lightMap=getTexture(json.lightMap);if(json.lightMapIntensity!==undefined)material.lightMapIntensity=json.lightMapIntensity;if(json.aoMap!==undefined)material.aoMap=getTexture(json.aoMap);if(json.aoMapIntensity!==undefined)material.aoMapIntensity=json.aoMapIntensity;if(json.gradientMap!==undefined)material.gradientMap=getTexture(json.gradientMap);return material}});function BufferGeometryLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(BufferGeometryLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.load(url,function(text){onLoad(scope.parse(JSON.parse(text)))},onProgress,onError)},parse:function(json){var geometry=new BufferGeometry;var index=json.data.index;if(index!==undefined){var typedArray=new TYPED_ARRAYS[index.type](index.array);geometry.setIndex(new BufferAttribute(typedArray,1))}var attributes=json.data.attributes;for(var key in attributes){var attribute=attributes[key];var typedArray=new TYPED_ARRAYS[attribute.type](attribute.array);geometry.addAttribute(key,new BufferAttribute(typedArray,attribute.itemSize,attribute.normalized))}var groups=json.data.groups||json.data.drawcalls||json.data.offsets;if(groups!==undefined){for(var i=0,n=groups.length;i!==n;++i){var group=groups[i];geometry.addGroup(group.start,group.count,group.materialIndex)}}var boundingSphere=json.data.boundingSphere;if(boundingSphere!==undefined){var center=new Vector3;if(boundingSphere.center!==undefined){center.fromArray(boundingSphere.center)}geometry.boundingSphere=new Sphere(center,boundingSphere.radius)}return geometry}});var TYPED_ARRAYS={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:typeof Uint8ClampedArray!=="undefined"?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Loader(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}Loader.Handlers={handlers:[],add:function(regex,loader){this.handlers.push(regex,loader)},get:function(file){var handlers=this.handlers;for(var i=0,l=handlers.length;i<l;i+=2){var regex=handlers[i];var loader=handlers[i+1];if(regex.test(file)){return loader}}return null}};Object.assign(Loader.prototype,{crossOrigin:undefined,extractUrlBase:function(url){var parts=url.split("/");if(parts.length===1)return"./";parts.pop();return parts.join("/")+"/"},initMaterials:function(materials,texturePath,crossOrigin){var array=[];for(var i=0;i<materials.length;++i){array[i]=this.createMaterial(materials[i],texturePath,crossOrigin)}return array},createMaterial:function(){var BlendingMode={NoBlending:NoBlending,NormalBlending:NormalBlending,AdditiveBlending:AdditiveBlending,SubtractiveBlending:SubtractiveBlending,MultiplyBlending:MultiplyBlending,CustomBlending:CustomBlending};var color=new Color;var textureLoader=new TextureLoader;var materialLoader=new MaterialLoader;return function createMaterial(m,texturePath,crossOrigin){var textures={};function loadTexture(path,repeat,offset,wrap,anisotropy){var fullPath=texturePath+path;var loader=Loader.Handlers.get(fullPath);var texture;if(loader!==null){texture=loader.load(fullPath)}else{textureLoader.setCrossOrigin(crossOrigin);texture=textureLoader.load(fullPath)}if(repeat!==undefined){texture.repeat.fromArray(repeat);if(repeat[0]!==1)texture.wrapS=RepeatWrapping;if(repeat[1]!==1)texture.wrapT=RepeatWrapping}if(offset!==undefined){texture.offset.fromArray(offset)}if(wrap!==undefined){if(wrap[0]==="repeat")texture.wrapS=RepeatWrapping;if(wrap[0]==="mirror")texture.wrapS=MirroredRepeatWrapping;if(wrap[1]==="repeat")texture.wrapT=RepeatWrapping;if(wrap[1]==="mirror")texture.wrapT=MirroredRepeatWrapping}if(anisotropy!==undefined){texture.anisotropy=anisotropy}var uuid=_Math.generateUUID();textures[uuid]=texture;return uuid}var json={uuid:_Math.generateUUID(),type:"MeshLambertMaterial"};for(var name in m){var value=m[name];switch(name){case"DbgColor":case"DbgIndex":case"opticalDensity":case"illumination":break;case"DbgName":json.name=value;break;case"blending":json.blending=BlendingMode[value];break;case"colorAmbient":case"mapAmbient":console.warn("THREE.Loader.createMaterial:",name,"is no longer supported.");break;case"colorDiffuse":json.color=color.fromArray(value).getHex();break;case"colorSpecular":json.specular=color.fromArray(value).getHex();break;case"colorEmissive":json.emissive=color.fromArray(value).getHex();break;case"specularCoef":json.shininess=value;break;case"shading":if(value.toLowerCase()==="basic")json.type="MeshBasicMaterial";if(value.toLowerCase()==="phong")json.type="MeshPhongMaterial";if(value.toLowerCase()==="standard")json.type="MeshStandardMaterial";break;case"mapDiffuse":json.map=loadTexture(value,m.mapDiffuseRepeat,m.mapDiffuseOffset,m.mapDiffuseWrap,m.mapDiffuseAnisotropy);break;case"mapDiffuseRepeat":case"mapDiffuseOffset":case"mapDiffuseWrap":case"mapDiffuseAnisotropy":break;case"mapEmissive":json.emissiveMap=loadTexture(value,m.mapEmissiveRepeat,m.mapEmissiveOffset,m.mapEmissiveWrap,m.mapEmissiveAnisotropy);break;case"mapEmissiveRepeat":case"mapEmissiveOffset":case"mapEmissiveWrap":case"mapEmissiveAnisotropy":break;case"mapLight":json.lightMap=loadTexture(value,m.mapLightRepeat,m.mapLightOffset,m.mapLightWrap,m.mapLightAnisotropy);break;case"mapLightRepeat":case"mapLightOffset":case"mapLightWrap":case"mapLightAnisotropy":break;case"mapAO":json.aoMap=loadTexture(value,m.mapAORepeat,m.mapAOOffset,m.mapAOWrap,m.mapAOAnisotropy);break;case"mapAORepeat":case"mapAOOffset":case"mapAOWrap":case"mapAOAnisotropy":break;case"mapBump":json.bumpMap=loadTexture(value,m.mapBumpRepeat,m.mapBumpOffset,m.mapBumpWrap,m.mapBumpAnisotropy);break;case"mapBumpScale":json.bumpScale=value;break;case"mapBumpRepeat":case"mapBumpOffset":case"mapBumpWrap":case"mapBumpAnisotropy":break;case"mapNormal":json.normalMap=loadTexture(value,m.mapNormalRepeat,m.mapNormalOffset,m.mapNormalWrap,m.mapNormalAnisotropy);break;case"mapNormalFactor":json.normalScale=[value,value];break;case"mapNormalRepeat":case"mapNormalOffset":case"mapNormalWrap":case"mapNormalAnisotropy":break;case"mapSpecular":json.specularMap=loadTexture(value,m.mapSpecularRepeat,m.mapSpecularOffset,m.mapSpecularWrap,m.mapSpecularAnisotropy);break;case"mapSpecularRepeat":case"mapSpecularOffset":case"mapSpecularWrap":case"mapSpecularAnisotropy":break;case"mapMetalness":json.metalnessMap=loadTexture(value,m.mapMetalnessRepeat,m.mapMetalnessOffset,m.mapMetalnessWrap,m.mapMetalnessAnisotropy);break;case"mapMetalnessRepeat":case"mapMetalnessOffset":case"mapMetalnessWrap":case"mapMetalnessAnisotropy":break;case"mapRoughness":json.roughnessMap=loadTexture(value,m.mapRoughnessRepeat,m.mapRoughnessOffset,m.mapRoughnessWrap,m.mapRoughnessAnisotropy);break;case"mapRoughnessRepeat":case"mapRoughnessOffset":case"mapRoughnessWrap":case"mapRoughnessAnisotropy":break;case"mapAlpha":json.alphaMap=loadTexture(value,m.mapAlphaRepeat,m.mapAlphaOffset,m.mapAlphaWrap,m.mapAlphaAnisotropy);break;case"mapAlphaRepeat":case"mapAlphaOffset":case"mapAlphaWrap":case"mapAlphaAnisotropy":break;case"flipSided":json.side=BackSide;break;case"doubleSided":json.side=DoubleSide;break;case"transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");json.opacity=value;break;case"depthTest":case"depthWrite":case"colorWrite":case"opacity":case"reflectivity":case"transparent":case"visible":case"wireframe":json[name]=value;break;case"vertexColors":if(value===true)json.vertexColors=VertexColors;if(value==="face")json.vertexColors=FaceColors;break;default:console.error("THREE.Loader.createMaterial: Unsupported",name,value);break}}if(json.type==="MeshBasicMaterial")delete json.emissive;if(json.type!=="MeshPhongMaterial")delete json.specular;if(json.opacity<1)json.transparent=true;materialLoader.setTextures(textures);return materialLoader.parse(json)}}()});function JSONLoader(manager){if(typeof manager==="boolean"){console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor.");manager=undefined}this.manager=manager!==undefined?manager:DefaultLoadingManager;this.withCredentials=false}Object.assign(JSONLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var texturePath=this.texturePath&&typeof this.texturePath==="string"?this.texturePath:Loader.prototype.extractUrlBase(url);var loader=new FileLoader(this.manager);loader.setWithCredentials(this.withCredentials);loader.load(url,function(text){var json=JSON.parse(text);var metadata=json.metadata;if(metadata!==undefined){var type=metadata.type;if(type!==undefined){if(type.toLowerCase()==="object"){console.error("THREE.JSONLoader: "+url+" should be loaded with THREE.ObjectLoader instead.");return}if(type.toLowerCase()==="scene"){console.error("THREE.JSONLoader: "+url+" should be loaded with THREE.SceneLoader instead.");return}}}var object=scope.parse(json,texturePath);onLoad(object.geometry,object.materials)},onProgress,onError)},setTexturePath:function(value){this.texturePath=value},parse:function(){function parseModel(json,geometry){function isBitSet(value,position){return value&1<<position}var i,j,fi,offset,zLength,colorIndex,normalIndex,uvIndex,materialIndex,type,isQuad,hasMaterial,hasFaceVertexUv,hasFaceNormal,hasFaceVertexNormal,hasFaceColor,hasFaceVertexColor,vertex,face,faceA,faceB,hex,normal,uvLayer,uv,u,v,faces=json.faces,vertices=json.vertices,normals=json.normals,colors=json.colors,scale=json.scale,nUvLayers=0;if(json.uvs!==undefined){for(i=0;i<json.uvs.length;i++){if(json.uvs[i].length)nUvLayers++}for(i=0;i<nUvLayers;i++){geometry.faceVertexUvs[i]=[]}}offset=0;zLength=vertices.length;while(offset<zLength){vertex=new Vector3;vertex.x=vertices[offset++]*scale;vertex.y=vertices[offset++]*scale;vertex.z=vertices[offset++]*scale;geometry.vertices.push(vertex)}offset=0;zLength=faces.length;while(offset<zLength){type=faces[offset++];isQuad=isBitSet(type,0);hasMaterial=isBitSet(type,1);hasFaceVertexUv=isBitSet(type,3);hasFaceNormal=isBitSet(type,4);hasFaceVertexNormal=isBitSet(type,5);hasFaceColor=isBitSet(type,6);hasFaceVertexColor=isBitSet(type,7);if(isQuad){faceA=new Face3;faceA.a=faces[offset];faceA.b=faces[offset+1];faceA.c=faces[offset+3];faceB=new Face3;faceB.a=faces[offset+1];faceB.b=faces[offset+2];faceB.c=faces[offset+3];offset+=4;if(hasMaterial){materialIndex=faces[offset++];faceA.materialIndex=materialIndex;faceB.materialIndex=materialIndex}fi=geometry.faces.length;if(hasFaceVertexUv){for(i=0;i<nUvLayers;i++){uvLayer=json.uvs[i];geometry.faceVertexUvs[i][fi]=[];geometry.faceVertexUvs[i][fi+1]=[];for(j=0;j<4;j++){uvIndex=faces[offset++];u=uvLayer[uvIndex*2];v=uvLayer[uvIndex*2+1];uv=new Vector2(u,v);if(j!==2)geometry.faceVertexUvs[i][fi].push(uv);if(j!==0)geometry.faceVertexUvs[i][fi+1].push(uv)}}}if(hasFaceNormal){normalIndex=faces[offset++]*3;faceA.normal.set(normals[normalIndex++],normals[normalIndex++],normals[normalIndex]);faceB.normal.copy(faceA.normal)}if(hasFaceVertexNormal){for(i=0;i<4;i++){normalIndex=faces[offset++]*3;normal=new Vector3(normals[normalIndex++],normals[normalIndex++],normals[normalIndex]);if(i!==2)faceA.vertexNormals.push(normal);if(i!==0)faceB.vertexNormals.push(normal)}}if(hasFaceColor){colorIndex=faces[offset++];hex=colors[colorIndex];faceA.color.setHex(hex);faceB.color.setHex(hex)}if(hasFaceVertexColor){for(i=0;i<4;i++){colorIndex=faces[offset++];hex=colors[colorIndex];if(i!==2)faceA.vertexColors.push(new Color(hex));if(i!==0)faceB.vertexColors.push(new Color(hex))}}geometry.faces.push(faceA);geometry.faces.push(faceB)}else{face=new Face3;face.a=faces[offset++];face.b=faces[offset++];face.c=faces[offset++];if(hasMaterial){materialIndex=faces[offset++];face.materialIndex=materialIndex}fi=geometry.faces.length;if(hasFaceVertexUv){for(i=0;i<nUvLayers;i++){uvLayer=json.uvs[i];geometry.faceVertexUvs[i][fi]=[];for(j=0;j<3;j++){uvIndex=faces[offset++];u=uvLayer[uvIndex*2];v=uvLayer[uvIndex*2+1];uv=new Vector2(u,v);geometry.faceVertexUvs[i][fi].push(uv)}}}if(hasFaceNormal){normalIndex=faces[offset++]*3;face.normal.set(normals[normalIndex++],normals[normalIndex++],normals[normalIndex])}if(hasFaceVertexNormal){for(i=0;i<3;i++){normalIndex=faces[offset++]*3;normal=new Vector3(normals[normalIndex++],normals[normalIndex++],normals[normalIndex]);face.vertexNormals.push(normal)}}if(hasFaceColor){colorIndex=faces[offset++];face.color.setHex(colors[colorIndex])}if(hasFaceVertexColor){for(i=0;i<3;i++){colorIndex=faces[offset++];face.vertexColors.push(new Color(colors[colorIndex]))}}geometry.faces.push(face)}}}function parseSkin(json,geometry){var influencesPerVertex=json.influencesPerVertex!==undefined?json.influencesPerVertex:2;if(json.skinWeights){for(var i=0,l=json.skinWeights.length;i<l;i+=influencesPerVertex){var x=json.skinWeights[i];var y=influencesPerVertex>1?json.skinWeights[i+1]:0;var z=influencesPerVertex>2?json.skinWeights[i+2]:0;var w=influencesPerVertex>3?json.skinWeights[i+3]:0;geometry.skinWeights.push(new Vector4(x,y,z,w))}}if(json.skinIndices){for(var i=0,l=json.skinIndices.length;i<l;i+=influencesPerVertex){var a=json.skinIndices[i];var b=influencesPerVertex>1?json.skinIndices[i+1]:0;var c=influencesPerVertex>2?json.skinIndices[i+2]:0;var d=influencesPerVertex>3?json.skinIndices[i+3]:0;geometry.skinIndices.push(new Vector4(a,b,c,d))}}geometry.bones=json.bones;if(geometry.bones&&geometry.bones.length>0&&(geometry.skinWeights.length!==geometry.skinIndices.length||geometry.skinIndices.length!==geometry.vertices.length)){console.warn("When skinning, number of vertices ("+geometry.vertices.length+"), skinIndices ("+geometry.skinIndices.length+"), and skinWeights ("+geometry.skinWeights.length+") should match.")}}function parseMorphing(json,geometry){var scale=json.scale;if(json.morphTargets!==undefined){for(var i=0,l=json.morphTargets.length;i<l;i++){geometry.morphTargets[i]={};geometry.morphTargets[i].name=json.morphTargets[i].name;geometry.morphTargets[i].vertices=[];var dstVertices=geometry.morphTargets[i].vertices;var srcVertices=json.morphTargets[i].vertices;for(var v=0,vl=srcVertices.length;v<vl;v+=3){var vertex=new Vector3;vertex.x=srcVertices[v]*scale;vertex.y=srcVertices[v+1]*scale;vertex.z=srcVertices[v+2]*scale;dstVertices.push(vertex)}}}if(json.morphColors!==undefined&&json.morphColors.length>0){console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.');var faces=geometry.faces;var morphColors=json.morphColors[0].colors;for(var i=0,l=faces.length;i<l;i++){faces[i].color.fromArray(morphColors,i*3)}}}function parseAnimations(json,geometry){var outputAnimations=[];var animations=[];if(json.animation!==undefined){animations.push(json.animation)}if(json.animations!==undefined){if(json.animations.length){animations=animations.concat(json.animations)}else{animations.push(json.animations)}}for(var i=0;i<animations.length;i++){var clip=AnimationClip.parseAnimation(animations[i],geometry.bones);if(clip)outputAnimations.push(clip)}if(geometry.morphTargets){var morphAnimationClips=AnimationClip.CreateClipsFromMorphTargetSequences(geometry.morphTargets,10);outputAnimations=outputAnimations.concat(morphAnimationClips)}if(outputAnimations.length>0)geometry.animations=outputAnimations}return function(json,texturePath){if(json.data!==undefined){json=json.data}if(json.scale!==undefined){json.scale=1/json.scale}else{json.scale=1}var geometry=new Geometry;parseModel(json,geometry);parseSkin(json,geometry);parseMorphing(json,geometry);parseAnimations(json,geometry);geometry.computeFaceNormals();geometry.computeBoundingSphere();if(json.materials===undefined||json.materials.length===0){return{geometry:geometry}}else{var materials=Loader.prototype.initMaterials(json.materials,texturePath,this.crossOrigin);return{geometry:geometry,materials:materials}}}}()});function ObjectLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager;this.texturePath=""}Object.assign(ObjectLoader.prototype,{load:function(url,onLoad,onProgress,onError){if(this.texturePath===""){this.texturePath=url.substring(0,url.lastIndexOf("/")+1)}var scope=this;var loader=new FileLoader(scope.manager);loader.load(url,function(text){var json=null;try{json=JSON.parse(text)}catch(error){if(onError!==undefined)onError(error);console.error("THREE:ObjectLoader: Can't parse "+url+".",error.message);return}var metadata=json.metadata;if(metadata===undefined||metadata.type===undefined||metadata.type.toLowerCase()==="geometry"){console.error("THREE.ObjectLoader: Can't load "+url+". Use THREE.JSONLoader instead.");return}scope.parse(json,onLoad)},onProgress,onError)},setTexturePath:function(value){this.texturePath=value},setCrossOrigin:function(value){this.crossOrigin=value},parse:function(json,onLoad){var geometries=this.parseGeometries(json.geometries);var images=this.parseImages(json.images,function(){if(onLoad!==undefined)onLoad(object)});var textures=this.parseTextures(json.textures,images);var materials=this.parseMaterials(json.materials,textures);var object=this.parseObject(json.object,geometries,materials);if(json.animations){object.animations=this.parseAnimations(json.animations)}if(json.images===undefined||json.images.length===0){if(onLoad!==undefined)onLoad(object)}return object},parseGeometries:function(json){var geometries={};if(json!==undefined){var geometryLoader=new JSONLoader;var bufferGeometryLoader=new BufferGeometryLoader;for(var i=0,l=json.length;i<l;i++){var geometry;var data=json[i];switch(data.type){case"PlaneGeometry":case"PlaneBufferGeometry":geometry=new Geometries[data.type](data.width,data.height,data.widthSegments,data.heightSegments);break;case"BoxGeometry":case"BoxBufferGeometry":case"CubeGeometry":geometry=new Geometries[data.type](data.width,data.height,data.depth,data.widthSegments,data.heightSegments,data.depthSegments);break;case"CircleGeometry":case"CircleBufferGeometry":geometry=new Geometries[data.type](data.radius,data.segments,data.thetaStart,data.thetaLength);break;case"CylinderGeometry":case"CylinderBufferGeometry":geometry=new Geometries[data.type](data.radiusTop,data.radiusBottom,data.height,data.radialSegments,data.heightSegments,data.openEnded,data.thetaStart,data.thetaLength);break;case"ConeGeometry":case"ConeBufferGeometry":geometry=new Geometries[data.type](data.radius,data.height,data.radialSegments,data.heightSegments,data.openEnded,data.thetaStart,data.thetaLength);break;case"SphereGeometry":case"SphereBufferGeometry":geometry=new Geometries[data.type](data.radius,data.widthSegments,data.heightSegments,data.phiStart,data.phiLength,data.thetaStart,data.thetaLength);break;case"DodecahedronGeometry":case"IcosahedronGeometry":case"OctahedronGeometry":case"TetrahedronGeometry":geometry=new Geometries[data.type](data.radius,data.detail);break;case"RingGeometry":case"RingBufferGeometry":geometry=new Geometries[data.type](data.innerRadius,data.outerRadius,data.thetaSegments,data.phiSegments,data.thetaStart,data.thetaLength);break;case"TorusGeometry":case"TorusBufferGeometry":geometry=new Geometries[data.type](data.radius,data.tube,data.radialSegments,data.tubularSegments,data.arc);break;case"TorusKnotGeometry":case"TorusKnotBufferGeometry":geometry=new Geometries[data.type](data.radius,data.tube,data.tubularSegments,data.radialSegments,data.p,data.q);break;case"LatheGeometry":case"LatheBufferGeometry":geometry=new Geometries[data.type](data.points,data.segments,data.phiStart,data.phiLength);break;case"BufferGeometry":geometry=bufferGeometryLoader.parse(data);break;case"Geometry":geometry=geometryLoader.parse(data,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+data.type+'"');continue}geometry.uuid=data.uuid;if(data.name!==undefined)geometry.name=data.name;geometries[data.uuid]=geometry}}return geometries},parseMaterials:function(json,textures){var materials={};if(json!==undefined){var loader=new MaterialLoader;loader.setTextures(textures);for(var i=0,l=json.length;i<l;i++){var data=json[i];if(data.type==="MultiMaterial"){var array=[];for(var j=0;j<data.materials.length;j++){array.push(loader.parse(data.materials[j]))}materials[data.uuid]=array}else{materials[data.uuid]=loader.parse(data)}}}return materials},parseAnimations:function(json){var animations=[];for(var i=0;i<json.length;i++){var clip=AnimationClip.parse(json[i]);animations.push(clip)}return animations},parseImages:function(json,onLoad){var scope=this;var images={};function loadImage(url){scope.manager.itemStart(url);return loader.load(url,function(){scope.manager.itemEnd(url)},undefined,function(){scope.manager.itemEnd(url);scope.manager.itemError(url)})}if(json!==undefined&&json.length>0){var manager=new LoadingManager(onLoad);var loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(var i=0,l=json.length;i<l;i++){var image=json[i];var path=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url)?image.url:scope.texturePath+image.url;images[image.uuid]=loadImage(path)}}return images},parseTextures:function(json,images){function parseConstant(value,type){if(typeof value==="number")return value;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",value);return type[value]}var textures={};if(json!==undefined){for(var i=0,l=json.length;i<l;i++){var data=json[i];if(data.image===undefined){console.warn('THREE.ObjectLoader: No "image" specified for',data.uuid)}if(images[data.image]===undefined){

console.warn("THREE.ObjectLoader: Undefined image",data.image)}var texture=new Texture(images[data.image]);texture.needsUpdate=true;texture.uuid=data.uuid;if(data.name!==undefined)texture.name=data.name;if(data.mapping!==undefined)texture.mapping=parseConstant(data.mapping,TEXTURE_MAPPING);if(data.offset!==undefined)texture.offset.fromArray(data.offset);if(data.repeat!==undefined)texture.repeat.fromArray(data.repeat);if(data.wrap!==undefined){texture.wrapS=parseConstant(data.wrap[0],TEXTURE_WRAPPING);texture.wrapT=parseConstant(data.wrap[1],TEXTURE_WRAPPING)}if(data.minFilter!==undefined)texture.minFilter=parseConstant(data.minFilter,TEXTURE_FILTER);if(data.magFilter!==undefined)texture.magFilter=parseConstant(data.magFilter,TEXTURE_FILTER);if(data.anisotropy!==undefined)texture.anisotropy=data.anisotropy;if(data.flipY!==undefined)texture.flipY=data.flipY;textures[data.uuid]=texture}}return textures},parseObject:function(){var matrix=new Matrix4;return function parseObject(data,geometries,materials){var object;function getGeometry(name){if(geometries[name]===undefined){console.warn("THREE.ObjectLoader: Undefined geometry",name)}return geometries[name]}function getMaterial(name){if(name===undefined)return undefined;if(Array.isArray(name)){var array=[];for(var i=0,l=name.length;i<l;i++){var uuid=name[i];if(materials[uuid]===undefined){console.warn("THREE.ObjectLoader: Undefined material",uuid)}array.push(materials[uuid])}return array}if(materials[name]===undefined){console.warn("THREE.ObjectLoader: Undefined material",name)}return materials[name]}switch(data.type){case"Scene":object=new Scene;if(data.background!==undefined){if(Number.isInteger(data.background)){object.background=new Color(data.background)}}if(data.fog!==undefined){if(data.fog.type==="Fog"){object.fog=new Fog(data.fog.color,data.fog.near,data.fog.far)}else if(data.fog.type==="FogExp2"){object.fog=new FogExp2(data.fog.color,data.fog.density)}}break;case"PerspectiveCamera":object=new PerspectiveCamera(data.fov,data.aspect,data.near,data.far);if(data.focus!==undefined)object.focus=data.focus;if(data.zoom!==undefined)object.zoom=data.zoom;if(data.filmGauge!==undefined)object.filmGauge=data.filmGauge;if(data.filmOffset!==undefined)object.filmOffset=data.filmOffset;if(data.view!==undefined)object.view=Object.assign({},data.view);break;case"OrthographicCamera":object=new OrthographicCamera(data.left,data.right,data.top,data.bottom,data.near,data.far);break;case"AmbientLight":object=new AmbientLight(data.color,data.intensity);break;case"DirectionalLight":object=new DirectionalLight(data.color,data.intensity);break;case"PointLight":object=new PointLight(data.color,data.intensity,data.distance,data.decay);break;case"RectAreaLight":object=new RectAreaLight(data.color,data.intensity,data.width,data.height);break;case"SpotLight":object=new SpotLight(data.color,data.intensity,data.distance,data.angle,data.penumbra,data.decay);break;case"HemisphereLight":object=new HemisphereLight(data.color,data.groundColor,data.intensity);break;case"SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");case"Mesh":var geometry=getGeometry(data.geometry);var material=getMaterial(data.material);if(geometry.bones&&geometry.bones.length>0){object=new SkinnedMesh(geometry,material)}else{object=new Mesh(geometry,material)}break;case"LOD":object=new LOD;break;case"Line":object=new Line(getGeometry(data.geometry),getMaterial(data.material),data.mode);break;case"LineLoop":object=new LineLoop(getGeometry(data.geometry),getMaterial(data.material));break;case"LineSegments":object=new LineSegments(getGeometry(data.geometry),getMaterial(data.material));break;case"PointCloud":case"Points":object=new Points(getGeometry(data.geometry),getMaterial(data.material));break;case"Sprite":object=new Sprite(getMaterial(data.material));break;case"Group":object=new Group;break;default:object=new Object3D}object.uuid=data.uuid;if(data.name!==undefined)object.name=data.name;if(data.matrix!==undefined){matrix.fromArray(data.matrix);matrix.decompose(object.position,object.quaternion,object.scale)}else{if(data.position!==undefined)object.position.fromArray(data.position);if(data.rotation!==undefined)object.rotation.fromArray(data.rotation);if(data.quaternion!==undefined)object.quaternion.fromArray(data.quaternion);if(data.scale!==undefined)object.scale.fromArray(data.scale)}if(data.castShadow!==undefined)object.castShadow=data.castShadow;if(data.receiveShadow!==undefined)object.receiveShadow=data.receiveShadow;if(data.shadow){if(data.shadow.bias!==undefined)object.shadow.bias=data.shadow.bias;if(data.shadow.radius!==undefined)object.shadow.radius=data.shadow.radius;if(data.shadow.mapSize!==undefined)object.shadow.mapSize.fromArray(data.shadow.mapSize);if(data.shadow.camera!==undefined)object.shadow.camera=this.parseObject(data.shadow.camera)}if(data.visible!==undefined)object.visible=data.visible;if(data.userData!==undefined)object.userData=data.userData;if(data.children!==undefined){var children=data.children;for(var i=0;i<children.length;i++){object.add(this.parseObject(children[i],geometries,materials))}}if(data.type==="LOD"){var levels=data.levels;for(var l=0;l<levels.length;l++){var level=levels[l];var child=object.getObjectByProperty("uuid",level.object);if(child!==undefined){object.addLevel(child,level.distance)}}}return object}}()});var TEXTURE_MAPPING={UVMapping:UVMapping,CubeReflectionMapping:CubeReflectionMapping,CubeRefractionMapping:CubeRefractionMapping,EquirectangularReflectionMapping:EquirectangularReflectionMapping,EquirectangularRefractionMapping:EquirectangularRefractionMapping,SphericalReflectionMapping:SphericalReflectionMapping,CubeUVReflectionMapping:CubeUVReflectionMapping,CubeUVRefractionMapping:CubeUVRefractionMapping};var TEXTURE_WRAPPING={RepeatWrapping:RepeatWrapping,ClampToEdgeWrapping:ClampToEdgeWrapping,MirroredRepeatWrapping:MirroredRepeatWrapping};var TEXTURE_FILTER={NearestFilter:NearestFilter,NearestMipMapNearestFilter:NearestMipMapNearestFilter,NearestMipMapLinearFilter:NearestMipMapLinearFilter,LinearFilter:LinearFilter,LinearMipMapNearestFilter:LinearMipMapNearestFilter,LinearMipMapLinearFilter:LinearMipMapLinearFilter};function CatmullRom(t,p0,p1,p2,p3){var v0=(p2-p0)*.5;var v1=(p3-p1)*.5;var t2=t*t;var t3=t*t2;return(2*p1-2*p2+v0+v1)*t3+(-3*p1+3*p2-2*v0-v1)*t2+v0*t+p1}function QuadraticBezierP0(t,p){var k=1-t;return k*k*p}function QuadraticBezierP1(t,p){return 2*(1-t)*t*p}function QuadraticBezierP2(t,p){return t*t*p}function QuadraticBezier(t,p0,p1,p2){return QuadraticBezierP0(t,p0)+QuadraticBezierP1(t,p1)+QuadraticBezierP2(t,p2)}function CubicBezierP0(t,p){var k=1-t;return k*k*k*p}function CubicBezierP1(t,p){var k=1-t;return 3*k*k*t*p}function CubicBezierP2(t,p){return 3*(1-t)*t*t*p}function CubicBezierP3(t,p){return t*t*t*p}function CubicBezier(t,p0,p1,p2,p3){return CubicBezierP0(t,p0)+CubicBezierP1(t,p1)+CubicBezierP2(t,p2)+CubicBezierP3(t,p3)}function Curve(){this.arcLengthDivisions=200}Object.assign(Curve.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(u){var t=this.getUtoTmapping(u);return this.getPoint(t)},getPoints:function(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions))}return points},getSpacedPoints:function(divisions){if(divisions===undefined)divisions=5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions))}return points},getLength:function(){var lengths=this.getLengths();return lengths[lengths.length-1]},getLengths:function(divisions){if(divisions===undefined)divisions=this.arcLengthDivisions;if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths}this.needsUpdate=false;var cache=[];var current,last=this.getPoint(0);var p,sum=0;cache.push(0);for(p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current}this.cacheArcLengths=cache;return cache},updateArcLengths:function(){this.needsUpdate=true;this.getLengths()},getUtoTmapping:function(u,distance){var arcLengths=this.getLengths();var i=0,il=arcLengths.length;var targetArcLength;if(distance){targetArcLength=distance}else{targetArcLength=u*arcLengths[il-1]}var low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1}else if(comparison>0){high=i-1}else{high=i;break}}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1)}var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;var t=(i+segmentFraction)/(il-1);return t},getTangent:function(t){var delta=1e-4;var t1=t-delta;var t2=t+delta;if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var vec=pt2.clone().sub(pt1);return vec.normalize()},getTangentAt:function(u){var t=this.getUtoTmapping(u);return this.getTangent(t)},computeFrenetFrames:function(segments,closed){var normal=new Vector3;var tangents=[];var normals=[];var binormals=[];var vec=new Vector3;var mat=new Matrix4;var i,u,theta;for(i=0;i<=segments;i++){u=i/segments;tangents[i]=this.getTangentAt(u);tangents[i].normalize()}normals[0]=new Vector3;binormals[0]=new Vector3;var min=Number.MAX_VALUE;var tx=Math.abs(tangents[0].x);var ty=Math.abs(tangents[0].y);var tz=Math.abs(tangents[0].z);if(tx<=min){min=tx;normal.set(1,0,0)}if(ty<=min){min=ty;normal.set(0,1,0)}if(tz<=min){normal.set(0,0,1)}vec.crossVectors(tangents[0],normal).normalize();normals[0].crossVectors(tangents[0],vec);binormals[0].crossVectors(tangents[0],normals[0]);for(i=1;i<=segments;i++){normals[i]=normals[i-1].clone();binormals[i]=binormals[i-1].clone();vec.crossVectors(tangents[i-1],tangents[i]);if(vec.length()>Number.EPSILON){vec.normalize();theta=Math.acos(_Math.clamp(tangents[i-1].dot(tangents[i]),-1,1));normals[i].applyMatrix4(mat.makeRotationAxis(vec,theta))}binormals[i].crossVectors(tangents[i],normals[i])}if(closed===true){theta=Math.acos(_Math.clamp(normals[0].dot(normals[segments]),-1,1));theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){theta=-theta}for(i=1;i<=segments;i++){normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i],theta*i));binormals[i].crossVectors(tangents[i],normals[i])}}return{tangents:tangents,normals:normals,binormals:binormals}}});function LineCurve(v1,v2){Curve.call(this);this.v1=v1;this.v2=v2}LineCurve.prototype=Object.create(Curve.prototype);LineCurve.prototype.constructor=LineCurve;LineCurve.prototype.isLineCurve=true;LineCurve.prototype.getPoint=function(t){if(t===1){return this.v2.clone()}var point=this.v2.clone().sub(this.v1);point.multiplyScalar(t).add(this.v1);return point};LineCurve.prototype.getPointAt=function(u){return this.getPoint(u)};LineCurve.prototype.getTangent=function(t){var tangent=this.v2.clone().sub(this.v1);return tangent.normalize()};function CurvePath(){Curve.call(this);this.curves=[];this.autoClose=false}CurvePath.prototype=Object.assign(Object.create(Curve.prototype),{constructor:CurvePath,add:function(curve){this.curves.push(curve)},closePath:function(){var startPoint=this.curves[0].getPoint(0);var endPoint=this.curves[this.curves.length-1].getPoint(1);if(!startPoint.equals(endPoint)){this.curves.push(new LineCurve(endPoint,startPoint))}},getPoint:function(t){var d=t*this.getLength();var curveLengths=this.getCurveLengths();var i=0;while(i<curveLengths.length){if(curveLengths[i]>=d){var diff=curveLengths[i]-d;var curve=this.curves[i];var segmentLength=curve.getLength();var u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u)}i++}return null},getLength:function(){var lens=this.getCurveLengths();return lens[lens.length-1]},updateArcLengths:function(){this.needsUpdate=true;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length){return this.cacheLengths}var lengths=[],sums=0;for(var i=0,l=this.curves.length;i<l;i++){sums+=this.curves[i].getLength();lengths.push(sums)}this.cacheLengths=lengths;return lengths},getSpacedPoints:function(divisions){if(divisions===undefined)divisions=40;var points=[];for(var i=0;i<=divisions;i++){points.push(this.getPoint(i/divisions))}if(this.autoClose){points.push(points[0])}return points},getPoints:function(divisions){divisions=divisions||12;var points=[],last;for(var i=0,curves=this.curves;i<curves.length;i++){var curve=curves[i];var resolution=curve&&curve.isEllipseCurve?divisions*2:curve&&curve.isLineCurve?1:curve&&curve.isSplineCurve?divisions*curve.points.length:divisions;var pts=curve.getPoints(resolution);for(var j=0;j<pts.length;j++){var point=pts[j];if(last&&last.equals(point))continue;points.push(point);last=point}}if(this.autoClose&&points.length>1&&!points[points.length-1].equals(points[0])){points.push(points[0])}return points},createPointsGeometry:function(divisions){var pts=this.getPoints(divisions);return this.createGeometry(pts)},createSpacedPointsGeometry:function(divisions){var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts)},createGeometry:function(points){var geometry=new Geometry;for(var i=0,l=points.length;i<l;i++){var point=points[i];geometry.vertices.push(new Vector3(point.x,point.y,point.z||0))}return geometry}});function EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){Curve.call(this);this.aX=aX;this.aY=aY;this.xRadius=xRadius;this.yRadius=yRadius;this.aStartAngle=aStartAngle;this.aEndAngle=aEndAngle;this.aClockwise=aClockwise;this.aRotation=aRotation||0}EllipseCurve.prototype=Object.create(Curve.prototype);EllipseCurve.prototype.constructor=EllipseCurve;EllipseCurve.prototype.isEllipseCurve=true;EllipseCurve.prototype.getPoint=function(t){var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)<Number.EPSILON;while(deltaAngle<0)deltaAngle+=twoPi;while(deltaAngle>twoPi)deltaAngle-=twoPi;if(deltaAngle<Number.EPSILON){if(samePoints){deltaAngle=0}else{deltaAngle=twoPi}}if(this.aClockwise===true&&!samePoints){if(deltaAngle===twoPi){deltaAngle=-twoPi}else{deltaAngle=deltaAngle-twoPi}}var angle=this.aStartAngle+t*deltaAngle;var x=this.aX+this.xRadius*Math.cos(angle);var y=this.aY+this.yRadius*Math.sin(angle);if(this.aRotation!==0){var cos=Math.cos(this.aRotation);var sin=Math.sin(this.aRotation);var tx=x-this.aX;var ty=y-this.aY;x=tx*cos-ty*sin+this.aX;y=tx*sin+ty*cos+this.aY}return new Vector2(x,y)};function SplineCurve(points){Curve.call(this);this.points=points===undefined?[]:points}SplineCurve.prototype=Object.create(Curve.prototype);SplineCurve.prototype.constructor=SplineCurve;SplineCurve.prototype.isSplineCurve=true;SplineCurve.prototype.getPoint=function(t){var points=this.points;var point=(points.length-1)*t;var intPoint=Math.floor(point);var weight=point-intPoint;var point0=points[intPoint===0?intPoint:intPoint-1];var point1=points[intPoint];var point2=points[intPoint>points.length-2?points.length-1:intPoint+1];var point3=points[intPoint>points.length-3?points.length-1:intPoint+2];return new Vector2(CatmullRom(weight,point0.x,point1.x,point2.x,point3.x),CatmullRom(weight,point0.y,point1.y,point2.y,point3.y))};function CubicBezierCurve(v0,v1,v2,v3){Curve.call(this);this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3}CubicBezierCurve.prototype=Object.create(Curve.prototype);CubicBezierCurve.prototype.constructor=CubicBezierCurve;CubicBezierCurve.prototype.getPoint=function(t){var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;return new Vector2(CubicBezier(t,v0.x,v1.x,v2.x,v3.x),CubicBezier(t,v0.y,v1.y,v2.y,v3.y))};function QuadraticBezierCurve(v0,v1,v2){Curve.call(this);this.v0=v0;this.v1=v1;this.v2=v2}QuadraticBezierCurve.prototype=Object.create(Curve.prototype);QuadraticBezierCurve.prototype.constructor=QuadraticBezierCurve;QuadraticBezierCurve.prototype.getPoint=function(t){var v0=this.v0,v1=this.v1,v2=this.v2;return new Vector2(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y))};var PathPrototype=Object.assign(Object.create(CurvePath.prototype),{fromPoints:function(vectors){this.moveTo(vectors[0].x,vectors[0].y);for(var i=1,l=vectors.length;i<l;i++){this.lineTo(vectors[i].x,vectors[i].y)}},moveTo:function(x,y){this.currentPoint.set(x,y)},lineTo:function(x,y){var curve=new LineCurve(this.currentPoint.clone(),new Vector2(x,y));this.curves.push(curve);this.currentPoint.set(x,y)},quadraticCurveTo:function(aCPx,aCPy,aX,aY){var curve=new QuadraticBezierCurve(this.currentPoint.clone(),new Vector2(aCPx,aCPy),new Vector2(aX,aY));this.curves.push(curve);this.currentPoint.set(aX,aY)},bezierCurveTo:function(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){var curve=new CubicBezierCurve(this.currentPoint.clone(),new Vector2(aCP1x,aCP1y),new Vector2(aCP2x,aCP2y),new Vector2(aX,aY));this.curves.push(curve);this.currentPoint.set(aX,aY)},splineThru:function(pts){var npts=[this.currentPoint.clone()].concat(pts);var curve=new SplineCurve(npts);this.curves.push(curve);this.currentPoint.copy(pts[pts.length-1])},arc:function(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){var x0=this.currentPoint.x;var y0=this.currentPoint.y;this.absarc(aX+x0,aY+y0,aRadius,aStartAngle,aEndAngle,aClockwise)},absarc:function(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){this.absellipse(aX,aY,aRadius,aRadius,aStartAngle,aEndAngle,aClockwise)},ellipse:function(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){var x0=this.currentPoint.x;var y0=this.currentPoint.y;this.absellipse(aX+x0,aY+y0,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation)},absellipse:function(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){var curve=new EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation);if(this.curves.length>0){var firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y)}}this.curves.push(curve);var lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint)}});function Path(points){CurvePath.call(this);this.currentPoint=new Vector2;if(points){this.fromPoints(points)}}Path.prototype=PathPrototype;PathPrototype.constructor=Path;function Shape(){Path.apply(this,arguments);this.holes=[]}Shape.prototype=Object.assign(Object.create(PathPrototype),{constructor:Shape,getPointsHoles:function(divisions){var holesPts=[];for(var i=0,l=this.holes.length;i<l;i++){holesPts[i]=this.holes[i].getPoints(divisions)}return holesPts},extractAllPoints:function(divisions){return{shape:this.getPoints(divisions),holes:this.getPointsHoles(divisions)}},extractPoints:function(divisions){return this.extractAllPoints(divisions)}});function ShapePath(){this.subPaths=[];this.currentPath=null}Object.assign(ShapePath.prototype,{moveTo:function(x,y){this.currentPath=new Path;this.subPaths.push(this.currentPath);this.currentPath.moveTo(x,y)},lineTo:function(x,y){this.currentPath.lineTo(x,y)},quadraticCurveTo:function(aCPx,aCPy,aX,aY){this.currentPath.quadraticCurveTo(aCPx,aCPy,aX,aY)},bezierCurveTo:function(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){this.currentPath.bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY)},splineThru:function(pts){this.currentPath.splineThru(pts)},toShapes:function(isCCW,noHoles){function toShapesNoHoles(inSubpaths){var shapes=[];for(var i=0,l=inSubpaths.length;i<l;i++){var tmpPath=inSubpaths[i];var tmpShape=new Shape;tmpShape.curves=tmpPath.curves;shapes.push(tmpShape)}return shapes}function isPointInsidePolygon(inPt,inPolygon){var polyLen=inPolygon.length;var inside=false;for(var p=polyLen-1,q=0;q<polyLen;p=q++){var edgeLowPt=inPolygon[p];var edgeHighPt=inPolygon[q];var edgeDx=edgeHighPt.x-edgeLowPt.x;var edgeDy=edgeHighPt.y-edgeLowPt.y;if(Math.abs(edgeDy)>Number.EPSILON){if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy}if(inPt.y<edgeLowPt.y||inPt.y>edgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true}else{var perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;if(perpEdge<0)continue;inside=!inside}}else{if(inPt.y!==edgeLowPt.y)continue;if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true}}return inside}var isClockWise=ShapeUtils.isClockWise;var subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);var solid,tmpPath,tmpShape,shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape;tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes}var holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var i=0,l=subPaths.length;i<l;i++){tmpPath=subPaths[i];tmpPoints=tmpPath.getPoints();solid=isClockWise(tmpPoints);solid=isCCW?!solid:solid;if(solid){if(!holesFirst&&newShapes[mainIdx])mainIdx++;newShapes[mainIdx]={s:new Shape,p:tmpPoints};newShapes[mainIdx].s.curves=tmpPath.curves;if(holesFirst)mainIdx++;newShapeHoles[mainIdx]=[]}else{newShapeHoles[mainIdx].push({h:tmpPath,p:tmpPoints[0]})}}if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx<sLen;sIdx++){betterShapeHoles[sIdx]=[]}for(var sIdx=0,sLen=newShapes.length;sIdx<sLen;sIdx++){var sho=newShapeHoles[sIdx];for(var hIdx=0;hIdx<sho.length;hIdx++){var ho=sho[hIdx];var hole_unassigned=true;for(var s2Idx=0;s2Idx<newShapes.length;s2Idx++){if(isPointInsidePolygon(ho.p,newShapes[s2Idx].p)){if(sIdx!==s2Idx)toChange.push({froms:sIdx,tos:s2Idx,hole:hIdx});if(hole_unassigned){hole_unassigned=false;betterShapeHoles[s2Idx].push(ho)}else{ambiguous=true}}}if(hole_unassigned){betterShapeHoles[sIdx].push(ho)}}}if(toChange.length>0){if(!ambiguous)newShapeHoles=betterShapeHoles}}var tmpHoles;for(var i=0,il=newShapes.length;i<il;i++){tmpShape=newShapes[i].s;shapes.push(tmpShape);tmpHoles=newShapeHoles[i];for(var j=0,jl=tmpHoles.length;j<jl;j++){tmpShape.holes.push(tmpHoles[j].h)}}return shapes}});function Font(data){this.data=data}Object.assign(Font.prototype,{isFont:true,generateShapes:function(text,size,divisions){function createPaths(text){var chars=String(text).split("");var scale=size/data.resolution;var line_height=(data.boundingBox.yMax-data.boundingBox.yMin+data.underlineThickness)*scale;var offsetX=0,offsetY=0;var paths=[];for(var i=0;i<chars.length;i++){var char=chars[i];if(char==="\n"){offsetX=0;offsetY-=line_height}else{var ret=createPath(char,scale,offsetX,offsetY);offsetX+=ret.offsetX;paths.push(ret.path)}}return paths}function createPath(c,scale,offsetX,offsetY){var glyph=data.glyphs[c]||data.glyphs["?"];if(!glyph)return;var path=new ShapePath;var pts=[];var x,y,cpx,cpy,cpx0,cpy0,cpx1,cpy1,cpx2,cpy2,laste;if(glyph.o){var outline=glyph._cachedOutline||(glyph._cachedOutline=glyph.o.split(" "));for(var i=0,l=outline.length;i<l;){var action=outline[i++];switch(action){case"m":x=outline[i++]*scale+offsetX;y=outline[i++]*scale+offsetY;path.moveTo(x,y);break;case"l":x=outline[i++]*scale+offsetX;y=outline[i++]*scale+offsetY;path.lineTo(x,y);break;case"q":cpx=outline[i++]*scale+offsetX;cpy=outline[i++]*scale+offsetY;cpx1=outline[i++]*scale+offsetX;cpy1=outline[i++]*scale+offsetY;path.quadraticCurveTo(cpx1,cpy1,cpx,cpy);laste=pts[pts.length-1];if(laste){cpx0=laste.x;cpy0=laste.y;for(var i2=1;i2<=divisions;i2++){var t=i2/divisions;QuadraticBezier(t,cpx0,cpx1,cpx);QuadraticBezier(t,cpy0,cpy1,cpy)}}break;case"b":cpx=outline[i++]*scale+offsetX;cpy=outline[i++]*scale+offsetY;cpx1=outline[i++]*scale+offsetX;cpy1=outline[i++]*scale+offsetY;cpx2=outline[i++]*scale+offsetX;cpy2=outline[i++]*scale+offsetY;path.bezierCurveTo(cpx1,cpy1,cpx2,cpy2,cpx,cpy);laste=pts[pts.length-1];if(laste){cpx0=laste.x;cpy0=laste.y;for(var i2=1;i2<=divisions;i2++){var t=i2/divisions;CubicBezier(t,cpx0,cpx1,cpx2,cpx);CubicBezier(t,cpy0,cpy1,cpy2,cpy)}}break}}}return{offsetX:glyph.ha*scale,path:path}}if(size===undefined)size=100;if(divisions===undefined)divisions=4;var data=this.data;var paths=createPaths(text);var shapes=[];for(var p=0,pl=paths.length;p<pl;p++){Array.prototype.push.apply(shapes,paths[p].toShapes())}return shapes}});function FontLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(FontLoader.prototype,{load:function(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(this.manager);loader.load(url,function(text){var json;try{json=JSON.parse(text)}catch(e){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.");json=JSON.parse(text.substring(65,text.length-2))}var font=scope.parse(json);if(onLoad)onLoad(font)},onProgress,onError)},parse:function(json){return new Font(json)}});var context;var AudioContext={getContext:function(){if(context===undefined){context=new(window.AudioContext||window.webkitAudioContext)}return context},setContext:function(value){context=value}};function AudioLoader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager}Object.assign(AudioLoader.prototype,{load:function(url,onLoad,onProgress,onError){var loader=new FileLoader(this.manager);loader.setResponseType("arraybuffer");loader.load(url,function(buffer){var context=AudioContext.getContext();context.decodeAudioData(buffer,function(audioBuffer){onLoad(audioBuffer)})},onProgress,onError)}});function StereoCamera(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new PerspectiveCamera;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=false;this.cameraR=new PerspectiveCamera;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=false}Object.assign(StereoCamera.prototype,{update:function(){var instance,focus,fov,aspect,near,far,zoom,eyeSep;var eyeRight=new Matrix4;var eyeLeft=new Matrix4;return function update(camera){var needsUpdate=instance!==this||focus!==camera.focus||fov!==camera.fov||aspect!==camera.aspect*this.aspect||near!==camera.near||far!==camera.far||zoom!==camera.zoom||eyeSep!==this.eyeSep;if(needsUpdate){instance=this;focus=camera.focus;fov=camera.fov;aspect=camera.aspect*this.aspect;near=camera.near;far=camera.far;zoom=camera.zoom;var projectionMatrix=camera.projectionMatrix.clone();eyeSep=this.eyeSep/2;var eyeSepOnProjection=eyeSep*near/focus;var ymax=near*Math.tan(_Math.DEG2RAD*fov*.5)/zoom;var xmin,xmax;eyeLeft.elements[12]=-eyeSep;eyeRight.elements[12]=eyeSep;xmin=-ymax*aspect+eyeSepOnProjection;xmax=ymax*aspect+eyeSepOnProjection;projectionMatrix.elements[0]=2*near/(xmax-xmin);projectionMatrix.elements[8]=(xmax+xmin)/(xmax-xmin);this.cameraL.projectionMatrix.copy(projectionMatrix);xmin=-ymax*aspect-eyeSepOnProjection;xmax=ymax*aspect-eyeSepOnProjection;projectionMatrix.elements[0]=2*near/(xmax-xmin);projectionMatrix.elements[8]=(xmax+xmin)/(xmax-xmin);this.cameraR.projectionMatrix.copy(projectionMatrix)}this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(eyeLeft);this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(eyeRight)}}()});function CubeCamera(near,far,cubeResolution){Object3D.call(this);this.type="CubeCamera";var fov=90,aspect=1;var cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3(1,0,0));this.add(cameraPX);var cameraNX=new PerspectiveCamera(fov,aspect,near,far);cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3(-1,0,0));this.add(cameraNX);var cameraPY=new PerspectiveCamera(fov,aspect,near,far);cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3(0,1,0));this.add(cameraPY);var cameraNY=new PerspectiveCamera(fov,aspect,near,far);cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3(0,-1,0));this.add(cameraNY);var cameraPZ=new PerspectiveCamera(fov,aspect,near,far);cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3(0,0,1));this.add(cameraPZ);var cameraNZ=new PerspectiveCamera(fov,aspect,near,far);cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ);var options={format:RGBFormat,magFilter:LinearFilter,minFilter:LinearFilter};this.renderTarget=new WebGLRenderTargetCube(cubeResolution,cubeResolution,options);this.renderTarget.texture.name="CubeCamera";this.update=function(renderer,scene){if(this.parent===null)this.updateMatrixWorld();var renderTarget=this.renderTarget;var generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderTarget.activeCubeFace=0;renderer.render(scene,cameraPX,renderTarget);renderTarget.activeCubeFace=1;renderer.render(scene,cameraNX,renderTarget);renderTarget.activeCubeFace=2;renderer.render(scene,cameraPY,renderTarget);renderTarget.activeCubeFace=3;renderer.render(scene,cameraNY,renderTarget);renderTarget.activeCubeFace=4;renderer.render(scene,cameraPZ,renderTarget);renderTarget.texture.generateMipmaps=generateMipmaps;renderTarget.activeCubeFace=5;renderer.render(scene,cameraNZ,renderTarget);renderer.setRenderTarget(null)};this.clear=function(renderer,color,depth,stencil){var renderTarget=this.renderTarget;for(var i=0;i<6;i++){renderTarget.activeCubeFace=i;renderer.setRenderTarget(renderTarget);renderer.clear(color,depth,stencil)}renderer.setRenderTarget(null)}}CubeCamera.prototype=Object.create(Object3D.prototype);CubeCamera.prototype.constructor=CubeCamera;function AudioListener(){Object3D.call(this);this.type="AudioListener";this.context=AudioContext.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}AudioListener.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:AudioListener,getInput:function(){return this.gain},removeFilter:function(){if(this.filter!==null){this.gain.disconnect(this.filter);this.filter.disconnect(this.context.destination);this.gain.connect(this.context.destination);this.filter=null}},getFilter:function(){return this.filter},setFilter:function(value){if(this.filter!==null){this.gain.disconnect(this.filter);this.filter.disconnect(this.context.destination)}else{this.gain.disconnect(this.context.destination)}this.filter=value;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(value){this.gain.gain.value=value},updateMatrixWorld:function(){var position=new Vector3;var quaternion=new Quaternion;var scale=new Vector3;var orientation=new Vector3;return function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);var listener=this.context.listener;var up=this.up;this.matrixWorld.decompose(position,quaternion,scale);orientation.set(0,0,-1).applyQuaternion(quaternion);if(listener.positionX){listener.positionX.setValueAtTime(position.x,this.context.currentTime);listener.positionY.setValueAtTime(position.y,this.context.currentTime);listener.positionZ.setValueAtTime(position.z,this.context.currentTime);listener.forwardX.setValueAtTime(orientation.x,this.context.currentTime);listener.forwardY.setValueAtTime(orientation.y,this.context.currentTime);listener.forwardZ.setValueAtTime(orientation.z,this.context.currentTime);listener.upX.setValueAtTime(up.x,this.context.currentTime);listener.upY.setValueAtTime(up.y,this.context.currentTime);listener.upZ.setValueAtTime(up.z,this.context.currentTime)}else{listener.setPosition(position.x,position.y,position.z);listener.setOrientation(orientation.x,orientation.y,orientation.z,up.x,up.y,up.z)}}}()});function Audio(listener){Object3D.call(this);this.type="Audio";this.context=listener.context;this.gain=this.context.createGain();this.gain.connect(listener.getInput());this.autoplay=false;this.buffer=null;this.loop=false;this.startTime=0;this.playbackRate=1;this.isPlaying=false;this.hasPlaybackControl=true;this.sourceType="empty";this.filters=[]} Audio.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Audio,getOutput:function(){return this.gain},setNodeSource:function(audioNode){this.hasPlaybackControl=false;this.sourceType="audioNode";this.source=audioNode;this.connect();return this},setBuffer:function(audioBuffer){this.buffer=audioBuffer;this.sourceType="buffer";if(this.autoplay)this.play();return this},play:function(){if(this.isPlaying===true){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return}var source=this.context.createBufferSource();source.buffer=this.buffer;source.loop=this.loop;source.onended=this.onEnded.bind(this);source.playbackRate.setValueAtTime(this.playbackRate,this.startTime);source.start(0,this.startTime);this.isPlaying=true;this.source=source;return this.connect()},pause:function(){if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return}this.source.stop();this.startTime=this.context.currentTime;this.isPlaying=false;return this},stop:function(){if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return}this.source.stop();this.startTime=0;this.isPlaying=false;return this},connect:function(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(var i=1,l=this.filters.length;i<l;i++){this.filters[i-1].connect(this.filters[i])}this.filters[this.filters.length-1].connect(this.getOutput())}else{this.source.connect(this.getOutput())}return this},disconnect:function(){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(var i=1,l=this.filters.length;i<l;i++){this.filters[i-1].disconnect(this.filters[i])}this.filters[this.filters.length-1].disconnect(this.getOutput())}else{this.source.disconnect(this.getOutput())}return this},getFilters:function(){return this.filters},setFilters:function(value){if(!value)value=[];if(this.isPlaying===true){this.disconnect();this.filters=value;this.connect()}else{this.filters=value}return this},getFilter:function(){return this.getFilters()[0]},setFilter:function(filter){return this.setFilters(filter?[filter]:[])},setPlaybackRate:function(value){if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return}this.playbackRate=value;if(this.isPlaying===true){this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime)}return this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=false},getLoop:function(){if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return false}return this.loop},setLoop:function(value){if(this.hasPlaybackControl===false){console.warn("THREE.Audio: this Audio has no playback control.");return}this.loop=value;if(this.isPlaying===true){this.source.loop=this.loop}return this},getVolume:function(){return this.gain.gain.value},setVolume:function(value){this.gain.gain.value=value;return this}});function PositionalAudio(listener){Audio.call(this,listener);this.panner=this.context.createPanner();this.panner.connect(this.gain)}PositionalAudio.prototype=Object.assign(Object.create(Audio.prototype),{constructor:PositionalAudio,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(value){this.panner.refDistance=value},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(value){this.panner.rolloffFactor=value},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(value){this.panner.distanceModel=value},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(value){this.panner.maxDistance=value},updateMatrixWorld:function(){var position=new Vector3;return function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);position.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(position.x,position.y,position.z)}}()});function AudioAnalyser(audio,fftSize){this.analyser=audio.context.createAnalyser();this.analyser.fftSize=fftSize!==undefined?fftSize:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);audio.getOutput().connect(this.analyser)}Object.assign(AudioAnalyser.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){var value=0,data=this.getFrequencyData();for(var i=0;i<data.length;i++){value+=data[i]}return value/data.length}});function PropertyMixer(binding,typeName,valueSize){this.binding=binding;this.valueSize=valueSize;var bufferType=Float64Array,mixFunction;switch(typeName){case"quaternion":mixFunction=this._slerp;break;case"string":case"bool":bufferType=Array;mixFunction=this._select;break;default:mixFunction=this._lerp}this.buffer=new bufferType(valueSize*4);this._mixBufferRegion=mixFunction;this.cumulativeWeight=0;this.useCount=0;this.referenceCount=0}Object.assign(PropertyMixer.prototype,{accumulate:function(accuIndex,weight){var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride,currentWeight=this.cumulativeWeight;if(currentWeight===0){for(var i=0;i!==stride;++i){buffer[offset+i]=buffer[i]}currentWeight=weight}else{currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride)}this.cumulativeWeight=currentWeight},apply:function(accuIndex){var stride=this.valueSize,buffer=this.buffer,offset=accuIndex*stride+stride,weight=this.cumulativeWeight,binding=this.binding;this.cumulativeWeight=0;if(weight<1){var originalValueOffset=stride*3;this._mixBufferRegion(buffer,offset,originalValueOffset,1-weight,stride)}for(var i=stride,e=stride+stride;i!==e;++i){if(buffer[i]!==buffer[i+stride]){binding.setValue(buffer,offset);break}}},saveOriginalState:function(){var binding=this.binding;var buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*3;binding.getValue(buffer,originalValueOffset);for(var i=stride,e=originalValueOffset;i!==e;++i){buffer[i]=buffer[originalValueOffset+i%stride]}this.cumulativeWeight=0},restoreOriginalState:function(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset)},_select:function(buffer,dstOffset,srcOffset,t,stride){if(t>=.5){for(var i=0;i!==stride;++i){buffer[dstOffset+i]=buffer[srcOffset+i]}}},_slerp:function(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t)},_lerp:function(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var i=0;i!==stride;++i){var j=dstOffset+i;buffer[j]=buffer[j]*s+buffer[srcOffset+i]*t}}});function Composite(targetGroup,path,optionalParsedPath){var parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath)}Object.assign(Composite.prototype,{getValue:function(array,offset){this.bind();var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];if(binding!==undefined)binding.getValue(array,offset)},setValue:function(array,offset){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].setValue(array,offset)}},bind:function(){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].bind()}},unbind:function(){var bindings=this._bindings;for(var i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].unbind()}}});function PropertyBinding(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding.parseTrackName(path);this.node=PropertyBinding.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode}Object.assign(PropertyBinding,{Composite:Composite,create:function(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath)}else{return new PropertyBinding.Composite(root,path,parsedPath)}},sanitizeNodeName:function(name){return name.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var directoryRe=/((?:[\w-]+[\/:])*)/;var nodeRe=/([\w-\.]+)?/;var objectRe=/(?:\.([\w-]+)(?:\[(.+)\])?)?/;var propertyRe=/\.([\w-]+)(?:\[(.+)\])?/;var trackRe=new RegExp(""+"^"+directoryRe.source+nodeRe.source+objectRe.source+propertyRe.source+"$");var supportedObjectNames=["material","materials","bones"];return function(trackName){var matches=trackRe.exec(trackName);if(!matches){throw new Error("PropertyBinding: Cannot parse trackName: "+trackName)}var results={nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf(".");if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);if(supportedObjectNames.indexOf(objectName)!==-1){results.nodeName=results.nodeName.substring(0,lastDot);results.objectName=objectName}}if(results.propertyName===null||results.propertyName.length===0){throw new Error("PropertyBinding: can not parse propertyName from trackName: "+trackName)}return results}}(),findNode:function(root,nodeName){if(!nodeName||nodeName===""||nodeName==="root"||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root}if(root.skeleton){var searchSkeleton=function(skeleton){for(var i=0;i<skeleton.bones.length;i++){var bone=skeleton.bones[i];if(bone.name===nodeName){return bone}}return null};var bone=searchSkeleton(root.skeleton);if(bone){return bone}}if(root.children){var searchNodeSubtree=function(children){for(var i=0;i<children.length;i++){var childNode=children[i];if(childNode.name===nodeName||childNode.uuid===nodeName){return childNode}var result=searchNodeSubtree(childNode.children);if(result)return result}return null};var subTreeNode=searchNodeSubtree(root.children);if(subTreeNode){return subTreeNode}}return null}});Object.assign(PropertyBinding.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function getValue_direct(buffer,offset){buffer[offset]=this.node[this.propertyName]},function getValue_array(buffer,offset){var source=this.resolvedProperty;for(var i=0,n=source.length;i!==n;++i){buffer[offset++]=source[i]}},function getValue_arrayElement(buffer,offset){buffer[offset]=this.resolvedProperty[this.propertyIndex]},function getValue_toArray(buffer,offset){this.resolvedProperty.toArray(buffer,offset)}],SetterByBindingTypeAndVersioning:[[function setValue_direct(buffer,offset){this.node[this.propertyName]=buffer[offset]},function setValue_direct_setNeedsUpdate(buffer,offset){this.node[this.propertyName]=buffer[offset];this.targetObject.needsUpdate=true},function setValue_direct_setMatrixWorldNeedsUpdate(buffer,offset){this.node[this.propertyName]=buffer[offset];this.targetObject.matrixWorldNeedsUpdate=true}],[function setValue_array(buffer,offset){var dest=this.resolvedProperty;for(var i=0,n=dest.length;i!==n;++i){dest[i]=buffer[offset++]}},function setValue_array_setNeedsUpdate(buffer,offset){var dest=this.resolvedProperty;for(var i=0,n=dest.length;i!==n;++i){dest[i]=buffer[offset++]}this.targetObject.needsUpdate=true},function setValue_array_setMatrixWorldNeedsUpdate(buffer,offset){var dest=this.resolvedProperty;for(var i=0,n=dest.length;i!==n;++i){dest[i]=buffer[offset++]}this.targetObject.matrixWorldNeedsUpdate=true}],[function setValue_arrayElement(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset]},function setValue_arrayElement_setNeedsUpdate(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset];this.targetObject.needsUpdate=true},function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset];this.targetObject.matrixWorldNeedsUpdate=true}],[function setValue_fromArray(buffer,offset){this.resolvedProperty.fromArray(buffer,offset)},function setValue_fromArray_setNeedsUpdate(buffer,offset){this.resolvedProperty.fromArray(buffer,offset);this.targetObject.needsUpdate=true},function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer,offset){this.resolvedProperty.fromArray(buffer,offset);this.targetObject.matrixWorldNeedsUpdate=true}]],getValue:function getValue_unbound(targetArray,offset){this.bind();this.getValue(targetArray,offset)},setValue:function getValue_unbound(sourceArray,offset){this.bind();this.setValue(sourceArray,offset)},bind:function(){var targetObject=this.node,parsedPath=this.parsedPath,objectName=parsedPath.objectName,propertyName=parsedPath.propertyName,propertyIndex=parsedPath.propertyIndex;if(!targetObject){targetObject=PropertyBinding.findNode(this.rootNode,parsedPath.nodeName)||this.rootNode;this.node=targetObject}this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(!targetObject){console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.");return}if(objectName){var objectIndex=parsedPath.objectIndex;switch(objectName){case"materials":if(!targetObject.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!targetObject.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}targetObject=targetObject.material.materials;break;case"bones":if(!targetObject.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}targetObject=targetObject.skeleton.bones;for(var i=0;i<targetObject.length;i++){if(targetObject[i].name===objectIndex){objectIndex=i;break}}break;default:if(targetObject[objectName]===undefined){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}targetObject=targetObject[objectName]}if(objectIndex!==undefined){if(targetObject[objectIndex]===undefined){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,targetObject);return}targetObject=targetObject[objectIndex]}}var nodeProperty=targetObject[propertyName];if(nodeProperty===undefined){var nodeName=parsedPath.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+nodeName+"."+propertyName+" but it wasn't found.",targetObject);return}var versioning=this.Versioning.None;if(targetObject.needsUpdate!==undefined){versioning=this.Versioning.NeedsUpdate;this.targetObject=targetObject}else if(targetObject.matrixWorldNeedsUpdate!==undefined){versioning=this.Versioning.MatrixWorldNeedsUpdate;this.targetObject=targetObject}var bindingType=this.BindingType.Direct;if(propertyIndex!==undefined){if(propertyName==="morphTargetInfluences"){if(!targetObject.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(targetObject.geometry.isBufferGeometry){if(!targetObject.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(var i=0;i<this.node.geometry.morphAttributes.position.length;i++){if(targetObject.geometry.morphAttributes.position[i].name===propertyIndex){propertyIndex=i;break}}}else{if(!targetObject.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",this);return}for(var i=0;i<this.node.geometry.morphTargets.length;i++){if(targetObject.geometry.morphTargets[i].name===propertyIndex){propertyIndex=i;break}}}}bindingType=this.BindingType.ArrayElement;this.resolvedProperty=nodeProperty;this.propertyIndex=propertyIndex}else if(nodeProperty.fromArray!==undefined&&nodeProperty.toArray!==undefined){bindingType=this.BindingType.HasFromToArray;this.resolvedProperty=nodeProperty}else if(Array.isArray(nodeProperty)){bindingType=this.BindingType.EntireArray;this.resolvedProperty=nodeProperty}else{this.propertyName=propertyName}this.getValue=this.GetterByBindingType[bindingType];this.setValue=this.SetterByBindingTypeAndVersioning[bindingType][versioning]},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(PropertyBinding.prototype,{_getValue_unbound:PropertyBinding.prototype.getValue,_setValue_unbound:PropertyBinding.prototype.setValue});function AnimationObjectGroup(var_args){this.uuid=_Math.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var indices={};this._indicesByUUID=indices;for(var i=0,n=arguments.length;i!==n;++i){indices[arguments[i].uuid]=i}this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var scope=this;this.stats={objects:{get total(){return scope._objects.length},get inUse(){return this.total-scope.nCachedObjects_}},get bindingsPerObject(){return scope._bindings.length}}}Object.assign(AnimationObjectGroup.prototype,{isAnimationObjectGroup:true,add:function(var_args){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid],knownObject=undefined;if(index===undefined){index=nObjects++;indicesByUUID[uuid]=index;objects.push(object);for(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding(object,paths[j],parsedPaths[j]))}}else if(index<nCachedObjects){knownObject=objects[index];var firstActiveIndex=--nCachedObjects,lastCachedObject=objects[firstActiveIndex];indicesByUUID[lastCachedObject.uuid]=index;objects[index]=lastCachedObject;indicesByUUID[uuid]=firstActiveIndex;objects[firstActiveIndex]=object;for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],lastCached=bindingsForPath[firstActiveIndex],binding=bindingsForPath[index];bindingsForPath[index]=lastCached;if(binding===undefined){binding=new PropertyBinding(object,paths[j],parsedPaths[j])}bindingsForPath[firstActiveIndex]=binding}}else if(objects[index]!==knownObject){console.error("THREE.AnimationObjectGroup: Different objects with the same UUID "+"detected. Clean the caches or recreate your infrastructure when reloading scenes.")}}this.nCachedObjects_=nCachedObjects},remove:function(var_args){var objects=this._objects,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined&&index>=nCachedObjects){var lastCachedIndex=nCachedObjects++,firstActiveObject=objects[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects[lastCachedIndex]=object;for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding}}}this.nCachedObjects_=nCachedObjects},uncache:function(var_args){var objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;for(var i=0,n=arguments.length;i!==n;++i){var object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index<nCachedObjects){var firstActiveIndex=--nCachedObjects,lastCachedObject=objects[firstActiveIndex],lastIndex=--nObjects,lastObject=objects[lastIndex];indicesByUUID[lastCachedObject.uuid]=index;objects[index]=lastCachedObject;indicesByUUID[lastObject.uuid]=firstActiveIndex;objects[firstActiveIndex]=lastObject;objects.pop();for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],lastCached=bindingsForPath[firstActiveIndex],last=bindingsForPath[lastIndex];bindingsForPath[index]=lastCached;bindingsForPath[firstActiveIndex]=last;bindingsForPath.pop()}}else{var lastIndex=--nObjects,lastObject=objects[lastIndex];indicesByUUID[lastObject.uuid]=index;objects[index]=lastObject;objects.pop();for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j];bindingsForPath[index]=bindingsForPath[lastIndex];bindingsForPath.pop()}}}}this.nCachedObjects_=nCachedObjects},subscribe_:function(path,parsedPath){var indicesByPath=this._bindingsIndicesByPath,index=indicesByPath[path],bindings=this._bindings;if(index!==undefined)return bindings[index];var paths=this._paths,parsedPaths=this._parsedPaths,objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,bindingsForPath=new Array(nObjects);index=bindings.length;indicesByPath[path]=index;paths.push(path);parsedPaths.push(parsedPath);bindings.push(bindingsForPath);for(var i=nCachedObjects,n=objects.length;i!==n;++i){var object=objects[i];bindingsForPath[i]=new PropertyBinding(object,path,parsedPath)}return bindingsForPath},unsubscribe_:function(path){var indicesByPath=this._bindingsIndicesByPath,index=indicesByPath[path];if(index!==undefined){var paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,lastBindingsIndex=bindings.length-1,lastBindings=bindings[lastBindingsIndex],lastBindingsPath=path[lastBindingsIndex];indicesByPath[lastBindingsPath]=index;bindings[index]=lastBindings;bindings.pop();parsedPaths[index]=parsedPaths[lastBindingsIndex];parsedPaths.pop();paths[index]=paths[lastBindingsIndex];paths.pop()}}});function AnimationAction(mixer,clip,localRoot){this._mixer=mixer;this._clip=clip;this._localRoot=localRoot||null;var tracks=clip.tracks,nTracks=tracks.length,interpolants=new Array(nTracks);var interpolantSettings={endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding};for(var i=0;i!==nTracks;++i){var interpolant=tracks[i].createInterpolant(null);interpolants[i]=interpolant;interpolant.settings=interpolantSettings}this._interpolantSettings=interpolantSettings;this._interpolants=interpolants;this._propertyBindings=new Array(nTracks);this._cacheIndex=null;this._byClipCacheIndex=null;this._timeScaleInterpolant=null;this._weightInterpolant=null;this.loop=LoopRepeat;this._loopCount=-1;this._startTime=null;this.time=0;this.timeScale=1;this._effectiveTimeScale=1;this.weight=1;this._effectiveWeight=1;this.repetitions=Infinity;this.paused=false;this.enabled=true;this.clampWhenFinished=false;this.zeroSlopeAtStart=true;this.zeroSlopeAtEnd=true}Object.assign(AnimationAction.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=false;this.enabled=true;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)},isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(time){this._startTime=time;return this},setLoop:function(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this},setEffectiveWeight:function(weight){this.weight=weight;this._effectiveWeight=this.enabled?weight:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(duration){return this._scheduleFading(duration,0,1)},fadeOut:function(duration){return this._scheduleFading(duration,1,0)},crossFadeFrom:function(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){var fadeInDuration=this._clip.duration,fadeOutDuration=fadeOutAction._clip.duration,startEndRatio=fadeOutDuration/fadeInDuration,endStartRatio=fadeInDuration/fadeOutDuration;fadeOutAction.warp(1,startEndRatio,duration);this.warp(endStartRatio,1,duration)}return this},crossFadeTo:function(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp)},stopFading:function(){var weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant)}return this},setEffectiveTimeScale:function(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},setDuration:function(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping()},syncWith:function(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping()},halt:function(duration){return this.warp(this._effectiveTimeScale,0,duration)},warp:function(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,interpolant=this._timeScaleInterpolant,timeScale=this.timeScale;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;times[1]=now+duration;values[0]=startTimeScale/timeScale;values[1]=endTimeScale/timeScale;return this},stopWarping:function(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant)}return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(time,deltaTime,timeDirection,accuIndex){if(!this.enabled){this._updateWeight(time);return}var startTime=this._startTime;if(startTime!==null){var timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return}this._startTime=null;deltaTime=timeDirection*timeRunning}deltaTime*=this._updateTimeScale(time);var clipTime=this._updateTime(deltaTime);var weight=this._updateWeight(time);if(weight>0){var interpolants=this._interpolants;var propertyMixers=this._propertyBindings;for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulate(accuIndex,weight)}}},_updateWeight:function(time){var weight=0;if(this.enabled){weight=this.weight;var interpolant=this._weightInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];weight*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopFading();if(interpolantValue===0){this.enabled=false}}}}this._effectiveWeight=weight;return weight},_updateTimeScale:function(time){var timeScale=0;if(!this.paused){timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];timeScale*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopWarping();if(timeScale===0){this.paused=true}else{this.timeScale=timeScale}}}}this._effectiveTimeScale=timeScale;return timeScale},_updateTime:function(deltaTime){var time=this.time+deltaTime;if(deltaTime===0)return time;var duration=this._clip.duration,loop=this.loop,loopCount=this._loopCount;if(loop===LoopOnce){if(loopCount===-1){this._loopCount=0;this._setEndings(true,true,false)}handle_stop:{if(time>=duration){time=duration}else if(time<0){time=0}else break handle_stop;if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime<0?-1:1})}}else{var pingPong=loop===LoopPingPong;if(loopCount===-1){if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong)}else{this._setEndings(this.repetitions===0,true,pingPong)}}if(time>=duration||time<0){var loopDelta=Math.floor(time/duration);time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var pending=this.repetitions-loopCount;if(pending<0){if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime>0?1:-1})}else{if(pending===0){var atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong)}else{this._setEndings(false,false,pingPong)}this._loopCount=loopCount;this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:loopDelta})}}if(pingPong&&(loopCount&1)===1){this.time=time;return duration-time}}this.time=time;return time},_setEndings:function(atStart,atEnd,pingPong){var settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding}else{if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingStart=WrapAroundEnding}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingEnd=WrapAroundEnding}}},_scheduleFading:function(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time,interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;values[0]=weightNow;times[1]=now+duration;values[1]=weightThen;return this}});function AnimationMixer(root){this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1}Object.assign(AnimationMixer.prototype,EventDispatcher.prototype,{_bindAction:function(action,prototypeAction){var root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName,bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName}for(var i=0;i!==nTracks;++i){var track=tracks[i],trackName=track.name,binding=bindingsByName[trackName];if(binding!==undefined){bindings[i]=binding}else{binding=bindings[i];if(binding!==undefined){if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName)}continue}var path=prototypeAction&&prototypeAction._propertyBindings[i].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[i]=binding}interpolants[i].resultBuffer=binding.buffer}},_activateAction:function(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){var rootUuid=(action._localRoot||this._root).uuid,clipUuid=action._clip.uuid,actionsForClip=this._actionsByClip[clipUuid];this._bindAction(action,actionsForClip&&actionsForClip.knownActions[0]);this._addInactiveAction(action,clipUuid,rootUuid)}var bindings=action._propertyBindings;for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState()}}this._lendAction(action)}},_deactivateAction:function(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding)}}this._takeBackAction(action)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var scope=this;this.stats={actions:{get total(){return scope._actions.length},get inUse(){return scope._nActiveActions}},bindings:{get total(){ return scope._bindings.length},get inUse(){return scope._nActiveBindings}},controlInterpolants:{get total(){return scope._controlInterpolants.length},get inUse(){return scope._nActiveControlInterpolants}}}},_isActiveAction:function(action){var index=action._cacheIndex;return index!==null&&index<this._nActiveActions},_addInactiveAction:function(action,clipUuid,rootUuid){var actions=this._actions,actionsByClip=this._actionsByClip,actionsForClip=actionsByClip[clipUuid];if(actionsForClip===undefined){actionsForClip={knownActions:[action],actionByRoot:{}};action._byClipCacheIndex=0;actionsByClip[clipUuid]=actionsForClip}else{var knownActions=actionsForClip.knownActions;action._byClipCacheIndex=knownActions.length;knownActions.push(action)}action._cacheIndex=actions.length;actions.push(action);actionsForClip.actionByRoot[rootUuid]=action},_removeInactiveAction:function(action){var actions=this._actions,lastInactiveAction=actions[actions.length-1],cacheIndex=action._cacheIndex;lastInactiveAction._cacheIndex=cacheIndex;actions[cacheIndex]=lastInactiveAction;actions.pop();action._cacheIndex=null;var clipUuid=action._clip.uuid,actionsByClip=this._actionsByClip,actionsForClip=actionsByClip[clipUuid],knownActionsForClip=actionsForClip.knownActions,lastKnownAction=knownActionsForClip[knownActionsForClip.length-1],byClipCacheIndex=action._byClipCacheIndex;lastKnownAction._byClipCacheIndex=byClipCacheIndex;knownActionsForClip[byClipCacheIndex]=lastKnownAction;knownActionsForClip.pop();action._byClipCacheIndex=null;var actionByRoot=actionsForClip.actionByRoot,rootUuid=(action._localRoot||this._root).uuid;delete actionByRoot[rootUuid];if(knownActionsForClip.length===0){delete actionsByClip[clipUuid]}this._removeInactiveBindingsForAction(action)},_removeInactiveBindingsForAction:function(action){var bindings=action._propertyBindings;for(var i=0,n=bindings.length;i!==n;++i){var binding=bindings[i];if(--binding.referenceCount===0){this._removeInactiveBinding(binding)}}},_lendAction:function(action){var actions=this._actions,prevIndex=action._cacheIndex,lastActiveIndex=this._nActiveActions++,firstInactiveAction=actions[lastActiveIndex];action._cacheIndex=lastActiveIndex;actions[lastActiveIndex]=action;firstInactiveAction._cacheIndex=prevIndex;actions[prevIndex]=firstInactiveAction},_takeBackAction:function(action){var actions=this._actions,prevIndex=action._cacheIndex,firstInactiveIndex=--this._nActiveActions,lastActiveAction=actions[firstInactiveIndex];action._cacheIndex=firstInactiveIndex;actions[firstInactiveIndex]=action;lastActiveAction._cacheIndex=prevIndex;actions[prevIndex]=lastActiveAction},_addInactiveBinding:function(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],bindings=this._bindings;if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding)},_removeInactiveBinding:function(binding){var bindings=this._bindings,propBinding=binding.binding,rootUuid=propBinding.rootNode.uuid,trackName=propBinding.path,bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],lastInactiveBinding=bindings[bindings.length-1],cacheIndex=binding._cacheIndex;lastInactiveBinding._cacheIndex=cacheIndex;bindings[cacheIndex]=lastInactiveBinding;bindings.pop();delete bindingByName[trackName];remove_empty_map:{for(var _ in bindingByName)break remove_empty_map;delete bindingsByRoot[rootUuid]}},_lendBinding:function(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,lastActiveIndex=this._nActiveBindings++,firstInactiveBinding=bindings[lastActiveIndex];binding._cacheIndex=lastActiveIndex;bindings[lastActiveIndex]=binding;firstInactiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=firstInactiveBinding},_takeBackBinding:function(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,firstInactiveIndex=--this._nActiveBindings,lastActiveBinding=bindings[firstInactiveIndex];binding._cacheIndex=firstInactiveIndex;bindings[firstInactiveIndex]=binding;lastActiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=lastActiveBinding},_lendControlInterpolant:function(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++,interpolant=interpolants[lastActiveIndex];if(interpolant===undefined){interpolant=new LinearInterpolant(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer);interpolant.__cacheIndex=lastActiveIndex;interpolants[lastActiveIndex]=interpolant}return interpolant},_takeBackControlInterpolant:function(interpolant){var interpolants=this._controlInterpolants,prevIndex=interpolant.__cacheIndex,firstInactiveIndex=--this._nActiveControlInterpolants,lastActiveInterpolant=interpolants[firstInactiveIndex];interpolant.__cacheIndex=firstInactiveIndex;interpolants[firstInactiveIndex]=interpolant;lastActiveInterpolant.__cacheIndex=prevIndex;interpolants[prevIndex]=lastActiveInterpolant},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(clip,optionalRoot){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==="string"?AnimationClip.findByName(root,clip):clip,clipUuid=clipObject!==null?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid],prototypeAction=null;if(actionsForClip!==undefined){var existingAction=actionsForClip.actionByRoot[rootUuid];if(existingAction!==undefined){return existingAction}prototypeAction=actionsForClip.knownActions[0];if(clipObject===null)clipObject=prototypeAction._clip}if(clipObject===null)return null;var newAction=new AnimationAction(this,clipObject,optionalRoot);this._bindAction(newAction,prototypeAction);this._addInactiveAction(newAction,clipUuid,rootUuid);return newAction},existingAction:function(clip,optionalRoot){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==="string"?AnimationClip.findByName(root,clip):clip,clipUuid=clipObject?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid];if(actionsForClip!==undefined){return actionsForClip.actionByRoot[rootUuid]||null}return null},stopAllAction:function(){var actions=this._actions,nActions=this._nActiveActions,bindings=this._bindings,nBindings=this._nActiveBindings;this._nActiveActions=0;this._nActiveBindings=0;for(var i=0;i!==nActions;++i){actions[i].reset()}for(var i=0;i!==nBindings;++i){bindings[i].useCount=0}return this},update:function(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;for(var i=0;i!==nActions;++i){var action=actions[i];action._update(time,deltaTime,timeDirection,accuIndex)}var bindings=this._bindings,nBindings=this._nActiveBindings;for(var i=0;i!==nBindings;++i){bindings[i].apply(accuIndex)}return this},getRoot:function(){return this._root},uncacheClip:function(clip){var actions=this._actions,clipUuid=clip.uuid,actionsByClip=this._actionsByClip,actionsForClip=actionsByClip[clipUuid];if(actionsForClip!==undefined){var actionsToRemove=actionsForClip.knownActions;for(var i=0,n=actionsToRemove.length;i!==n;++i){var action=actionsToRemove[i];this._deactivateAction(action);var cacheIndex=action._cacheIndex,lastInactiveAction=actions[actions.length-1];action._cacheIndex=null;action._byClipCacheIndex=null;lastInactiveAction._cacheIndex=cacheIndex;actions[cacheIndex]=lastInactiveAction;actions.pop();this._removeInactiveBindingsForAction(action)}delete actionsByClip[clipUuid]}},uncacheRoot:function(root){var rootUuid=root.uuid,actionsByClip=this._actionsByClip;for(var clipUuid in actionsByClip){var actionByRoot=actionsByClip[clipUuid].actionByRoot,action=actionByRoot[rootUuid];if(action!==undefined){this._deactivateAction(action);this._removeInactiveAction(action)}}var bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid];if(bindingByName!==undefined){for(var trackName in bindingByName){var binding=bindingByName[trackName];binding.restoreOriginalState();this._removeInactiveBinding(binding)}}},uncacheAction:function(clip,optionalRoot){var action=this.existingAction(clip,optionalRoot);if(action!==null){this._deactivateAction(action);this._removeInactiveAction(action)}}});function Uniform(value){if(typeof value==="string"){console.warn("THREE.Uniform: Type parameter is no longer needed.");value=arguments[1]}this.value=value}Uniform.prototype.clone=function(){return new Uniform(this.value.clone===undefined?this.value:this.value.clone())};function InstancedBufferGeometry(){BufferGeometry.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=undefined}InstancedBufferGeometry.prototype=Object.assign(Object.create(BufferGeometry.prototype),{constructor:InstancedBufferGeometry,isInstancedBufferGeometry:true,addGroup:function(start,count,materialIndex){this.groups.push({start:start,count:count,materialIndex:materialIndex})},copy:function(source){var index=source.index;if(index!==null){this.setIndex(index.clone())}var attributes=source.attributes;for(var name in attributes){var attribute=attributes[name];this.addAttribute(name,attribute.clone())}var groups=source.groups;for(var i=0,l=groups.length;i<l;i++){var group=groups[i];this.addGroup(group.start,group.count,group.materialIndex)}return this}});function InterleavedBufferAttribute(interleavedBuffer,itemSize,offset,normalized){this.uuid=_Math.generateUUID();this.data=interleavedBuffer;this.itemSize=itemSize;this.offset=offset;this.normalized=normalized===true}Object.defineProperties(InterleavedBufferAttribute.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(InterleavedBufferAttribute.prototype,{isInterleavedBufferAttribute:true,setX:function(index,x){this.data.array[index*this.data.stride+this.offset]=x;return this},setY:function(index,y){this.data.array[index*this.data.stride+this.offset+1]=y;return this},setZ:function(index,z){this.data.array[index*this.data.stride+this.offset+2]=z;return this},setW:function(index,w){this.data.array[index*this.data.stride+this.offset+3]=w;return this},getX:function(index){return this.data.array[index*this.data.stride+this.offset]},getY:function(index){return this.data.array[index*this.data.stride+this.offset+1]},getZ:function(index){return this.data.array[index*this.data.stride+this.offset+2]},getW:function(index){return this.data.array[index*this.data.stride+this.offset+3]},setXY:function(index,x,y){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;return this},setXYZ:function(index,x,y,z){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;this.data.array[index+2]=z;return this},setXYZW:function(index,x,y,z,w){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;this.data.array[index+2]=z;this.data.array[index+3]=w;return this}});function InterleavedBuffer(array,stride){this.uuid=_Math.generateUUID();this.array=array;this.stride=stride;this.count=array!==undefined?array.length/stride:0;this.dynamic=false;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}Object.defineProperty(InterleavedBuffer.prototype,"needsUpdate",{set:function(value){if(value===true)this.version++}});Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:true,setArray:function(array){if(Array.isArray(array)){throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.")}this.count=array!==undefined?array.length/this.stride:0;this.array=array},setDynamic:function(value){this.dynamic=value;return this},copy:function(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.dynamic=source.dynamic;return this},copyAt:function(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var i=0,l=this.stride;i<l;i++){this.array[index1+i]=attribute.array[index2+i]}return this},set:function(value,offset){if(offset===undefined)offset=0;this.array.set(value,offset);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(callback){this.onUploadCallback=callback;return this}});function InstancedInterleavedBuffer(array,stride,meshPerAttribute){InterleavedBuffer.call(this,array,stride);this.meshPerAttribute=meshPerAttribute||1}InstancedInterleavedBuffer.prototype=Object.assign(Object.create(InterleavedBuffer.prototype),{constructor:InstancedInterleavedBuffer,isInstancedInterleavedBuffer:true,copy:function(source){InterleavedBuffer.prototype.copy.call(this,source);this.meshPerAttribute=source.meshPerAttribute;return this}});function InstancedBufferAttribute(array,itemSize,meshPerAttribute){BufferAttribute.call(this,array,itemSize);this.meshPerAttribute=meshPerAttribute||1}InstancedBufferAttribute.prototype=Object.assign(Object.create(BufferAttribute.prototype),{constructor:InstancedBufferAttribute,isInstancedBufferAttribute:true,copy:function(source){BufferAttribute.prototype.copy.call(this,source);this.meshPerAttribute=source.meshPerAttribute;return this}});function Raycaster(origin,direction,near,far){this.ray=new Ray(origin,direction);this.near=near||0;this.far=far||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function ascSort(a,b){return a.distance-b.distance}function intersectObject(object,raycaster,intersects,recursive){if(object.visible===false)return;object.raycast(raycaster,intersects);if(recursive===true){var children=object.children;for(var i=0,l=children.length;i<l;i++){intersectObject(children[i],raycaster,intersects,true)}}}Object.assign(Raycaster.prototype,{linePrecision:1,set:function(origin,direction){this.ray.set(origin,direction)},setFromCamera:function(coords,camera){if(camera&&camera.isPerspectiveCamera){this.ray.origin.setFromMatrixPosition(camera.matrixWorld);this.ray.direction.set(coords.x,coords.y,.5).unproject(camera).sub(this.ray.origin).normalize()}else if(camera&&camera.isOrthographicCamera){this.ray.origin.set(coords.x,coords.y,(camera.near+camera.far)/(camera.near-camera.far)).unproject(camera);this.ray.direction.set(0,0,-1).transformDirection(camera.matrixWorld)}else{console.error("THREE.Raycaster: Unsupported camera type.")}},intersectObject:function(object,recursive){var intersects=[];intersectObject(object,this,intersects,recursive);intersects.sort(ascSort);return intersects},intersectObjects:function(objects,recursive){var intersects=[];if(Array.isArray(objects)===false){console.warn("THREE.Raycaster.intersectObjects: objects is not an Array.");return intersects}for(var i=0,l=objects.length;i<l;i++){intersectObject(objects[i],this,intersects,recursive)}intersects.sort(ascSort);return intersects}});function Clock(autoStart){this.autoStart=autoStart!==undefined?autoStart:true;this.startTime=0;this.oldTime=0;this.elapsedTime=0;this.running=false}Object.assign(Clock.prototype,{start:function(){this.startTime=(typeof performance==="undefined"?Date:performance).now();this.oldTime=this.startTime;this.elapsedTime=0;this.running=true},stop:function(){this.getElapsedTime();this.running=false;this.autoStart=false},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var diff=0;if(this.autoStart&&!this.running){this.start();return 0}if(this.running){var newTime=(typeof performance==="undefined"?Date:performance).now();diff=(newTime-this.oldTime)/1e3;this.oldTime=newTime;this.elapsedTime+=diff}return diff}});function Spherical(radius,phi,theta){this.radius=radius!==undefined?radius:1;this.phi=phi!==undefined?phi:0;this.theta=theta!==undefined?theta:0;return this}Object.assign(Spherical.prototype,{set:function(radius,phi,theta){this.radius=radius;this.phi=phi;this.theta=theta;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(other){this.radius=other.radius;this.phi=other.phi;this.theta=other.theta;return this},makeSafe:function(){var EPS=1e-6;this.phi=Math.max(EPS,Math.min(Math.PI-EPS,this.phi));return this},setFromVector3:function(vec3){this.radius=vec3.length();if(this.radius===0){this.theta=0;this.phi=0}else{this.theta=Math.atan2(vec3.x,vec3.z);this.phi=Math.acos(_Math.clamp(vec3.y/this.radius,-1,1))}return this}});function Cylindrical(radius,theta,y){this.radius=radius!==undefined?radius:1;this.theta=theta!==undefined?theta:0;this.y=y!==undefined?y:0;return this}Object.assign(Cylindrical.prototype,{set:function(radius,theta,y){this.radius=radius;this.theta=theta;this.y=y;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(other){this.radius=other.radius;this.theta=other.theta;this.y=other.y;return this},setFromVector3:function(vec3){this.radius=Math.sqrt(vec3.x*vec3.x+vec3.z*vec3.z);this.theta=Math.atan2(vec3.x,vec3.z);this.y=vec3.y;return this}});function ImmediateRenderObject(material){Object3D.call(this);this.material=material;this.render=function(renderCallback){}}ImmediateRenderObject.prototype=Object.create(Object3D.prototype);ImmediateRenderObject.prototype.constructor=ImmediateRenderObject;ImmediateRenderObject.prototype.isImmediateRenderObject=true;function VertexNormalsHelper(object,size,hex,linewidth){this.object=object;this.size=size!==undefined?size:1;var color=hex!==undefined?hex:16711680;var width=linewidth!==undefined?linewidth:1;var nNormals=0;var objGeometry=this.object.geometry;if(objGeometry&&objGeometry.isGeometry){nNormals=objGeometry.faces.length*3}else if(objGeometry&&objGeometry.isBufferGeometry){nNormals=objGeometry.attributes.normal.count}var geometry=new BufferGeometry;var positions=new Float32BufferAttribute(nNormals*2*3,3);geometry.addAttribute("position",positions);LineSegments.call(this,geometry,new LineBasicMaterial({color:color,linewidth:width}));this.matrixAutoUpdate=false;this.update()}VertexNormalsHelper.prototype=Object.create(LineSegments.prototype);VertexNormalsHelper.prototype.constructor=VertexNormalsHelper;VertexNormalsHelper.prototype.update=function(){var v1=new Vector3;var v2=new Vector3;var normalMatrix=new Matrix3;return function update(){var keys=["a","b","c"];this.object.updateMatrixWorld(true);normalMatrix.getNormalMatrix(this.object.matrixWorld);var matrixWorld=this.object.matrixWorld;var position=this.geometry.attributes.position;var objGeometry=this.object.geometry;if(objGeometry&&objGeometry.isGeometry){var vertices=objGeometry.vertices;var faces=objGeometry.faces;var idx=0;for(var i=0,l=faces.length;i<l;i++){var face=faces[i];for(var j=0,jl=face.vertexNormals.length;j<jl;j++){var vertex=vertices[face[keys[j]]];var normal=face.vertexNormals[j];v1.copy(vertex).applyMatrix4(matrixWorld);v2.copy(normal).applyMatrix3(normalMatrix).normalize().multiplyScalar(this.size).add(v1);position.setXYZ(idx,v1.x,v1.y,v1.z);idx=idx+1;position.setXYZ(idx,v2.x,v2.y,v2.z);idx=idx+1}}}else if(objGeometry&&objGeometry.isBufferGeometry){var objPos=objGeometry.attributes.position;var objNorm=objGeometry.attributes.normal;var idx=0;for(var j=0,jl=objPos.count;j<jl;j++){v1.set(objPos.getX(j),objPos.getY(j),objPos.getZ(j)).applyMatrix4(matrixWorld);v2.set(objNorm.getX(j),objNorm.getY(j),objNorm.getZ(j));v2.applyMatrix3(normalMatrix).normalize().multiplyScalar(this.size).add(v1);position.setXYZ(idx,v1.x,v1.y,v1.z);idx=idx+1;position.setXYZ(idx,v2.x,v2.y,v2.z);idx=idx+1}}position.needsUpdate=true}}();function SpotLightHelper(light,color){Object3D.call(this);this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var geometry=new BufferGeometry;var positions=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(var i=0,j=1,l=32;i<l;i++,j++){var p1=i/l*Math.PI*2;var p2=j/l*Math.PI*2;positions.push(Math.cos(p1),Math.sin(p1),1,Math.cos(p2),Math.sin(p2),1)}geometry.addAttribute("position",new Float32BufferAttribute(positions,3));var material=new LineBasicMaterial({fog:false});this.cone=new LineSegments(geometry,material);this.add(this.cone);this.update()}SpotLightHelper.prototype=Object.create(Object3D.prototype);SpotLightHelper.prototype.constructor=SpotLightHelper;SpotLightHelper.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};SpotLightHelper.prototype.update=function(){var vector=new Vector3;var vector2=new Vector3;return function update(){this.light.updateMatrixWorld();var coneLength=this.light.distance?this.light.distance:1e3;var coneWidth=coneLength*Math.tan(this.light.angle);this.cone.scale.set(coneWidth,coneWidth,coneLength);vector.setFromMatrixPosition(this.light.matrixWorld);vector2.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(vector2.sub(vector));if(this.color!==undefined){this.cone.material.color.set(this.color)}else{this.cone.material.color.copy(this.light.color)}}}();function getBoneList(object){var boneList=[];if(object&&object.isBone){boneList.push(object)}for(var i=0;i<object.children.length;i++){boneList.push.apply(boneList,getBoneList(object.children[i]))}return boneList}function SkeletonHelper(object){var bones=getBoneList(object);var geometry=new BufferGeometry;var vertices=[];var colors=[];var color1=new Color(0,0,1);var color2=new Color(0,1,0);for(var i=0;i<bones.length;i++){var bone=bones[i];if(bone.parent&&bone.parent.isBone){vertices.push(0,0,0);vertices.push(0,0,0);colors.push(color1.r,color1.g,color1.b);colors.push(color2.r,color2.g,color2.b)}}geometry.addAttribute("position",new Float32BufferAttribute(vertices,3));geometry.addAttribute("color",new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:VertexColors,depthTest:false,depthWrite:false,transparent:true});LineSegments.call(this,geometry,material);this.root=object;this.bones=bones;this.matrix=object.matrixWorld;this.matrixAutoUpdate=false;this.onBeforeRender()}SkeletonHelper.prototype=Object.create(LineSegments.prototype);SkeletonHelper.prototype.constructor=SkeletonHelper;SkeletonHelper.prototype.onBeforeRender=function(){var vector=new Vector3;var boneMatrix=new Matrix4;var matrixWorldInv=new Matrix4;return function onBeforeRender(){var bones=this.bones;var geometry=this.geometry;var position=geometry.getAttribute("position");matrixWorldInv.getInverse(this.root.matrixWorld);for(var i=0,j=0;i<bones.length;i++){var bone=bones[i];if(bone.parent&&bone.parent.isBone){boneMatrix.multiplyMatrices(matrixWorldInv,bone.matrixWorld);vector.setFromMatrixPosition(boneMatrix);position.setXYZ(j,vector.x,vector.y,vector.z);boneMatrix.multiplyMatrices(matrixWorldInv,bone.parent.matrixWorld);vector.setFromMatrixPosition(boneMatrix);position.setXYZ(j+1,vector.x,vector.y,vector.z);j+=2}}geometry.getAttribute("position").needsUpdate=true}}();function PointLightHelper(light,sphereSize,color){this.light=light;this.light.updateMatrixWorld();this.color=color;var geometry=new SphereBufferGeometry(sphereSize,4,2);var material=new MeshBasicMaterial({wireframe:true,fog:false});Mesh.call(this,geometry,material);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=false;this.update()}PointLightHelper.prototype=Object.create(Mesh.prototype);PointLightHelper.prototype.constructor=PointLightHelper;PointLightHelper.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};PointLightHelper.prototype.update=function(){if(this.color!==undefined){this.material.color.set(this.color)}else{this.material.color.copy(this.light.color)}};function RectAreaLightHelper(light,color){Object3D.call(this);this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var material=new LineBasicMaterial({fog:false});var geometry=new BufferGeometry;geometry.addAttribute("position",new BufferAttribute(new Float32Array(5*3),3));this.line=new Line(geometry,material);this.add(this.line);this.update()}RectAreaLightHelper.prototype=Object.create(Object3D.prototype);RectAreaLightHelper.prototype.constructor=RectAreaLightHelper;RectAreaLightHelper.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};RectAreaLightHelper.prototype.update=function(){var hx=this.light.width*.5;var hy=this.light.height*.5;var position=this.line.geometry.attributes.position;var array=position.array;array[0]=hx;array[1]=-hy;array[2]=0;array[3]=hx;array[4]=hy;array[5]=0;array[6]=-hx;array[7]=hy;array[8]=0;array[9]=-hx;array[10]=-hy;array[11]=0;array[12]=hx;array[13]=-hy;array[14]=0;position.needsUpdate=true;if(this.color!==undefined){this.line.material.color.set(this.color)}else{this.line.material.color.copy(this.light.color)}};function HemisphereLightHelper(light,size,color){Object3D.call(this);this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var geometry=new OctahedronBufferGeometry(size);geometry.rotateY(Math.PI*.5);this.material=new MeshBasicMaterial({wireframe:true,fog:false});if(this.color===undefined)this.material.vertexColors=VertexColors;var position=geometry.getAttribute("position");var colors=new Float32Array(position.count*3);geometry.addAttribute("color",new BufferAttribute(colors,3));this.add(new Mesh(geometry,this.material));this.update()}HemisphereLightHelper.prototype=Object.create(Object3D.prototype);HemisphereLightHelper.prototype.constructor=HemisphereLightHelper;HemisphereLightHelper.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};HemisphereLightHelper.prototype.update=function(){var vector=new Vector3;var color1=new Color;var color2=new Color;return function update(){var mesh=this.children[0];if(this.color!==undefined){this.material.color.set(this.color)}else{var colors=mesh.geometry.getAttribute("color");color1.copy(this.light.color);color2.copy(this.light.groundColor);for(var i=0,l=colors.count;i<l;i++){var color=i<l/2?color1:color2;colors.setXYZ(i,color.r,color.g,color.b)}colors.needsUpdate=true}mesh.lookAt(vector.setFromMatrixPosition(this.light.matrixWorld).negate())}}();function GridHelper(size,divisions,color1,color2){size=size||10;divisions=divisions||10;color1=new Color(color1!==undefined?color1:4473924);color2=new Color(color2!==undefined?color2:8947848);var center=divisions/2;var step=size/divisions;var halfSize=size/2;var vertices=[],colors=[];for(var i=0,j=0,k=-halfSize;i<=divisions;i++,k+=step){vertices.push(-halfSize,0,k,halfSize,0,k);vertices.push(k,0,-halfSize,k,0,halfSize);var color=i===center?color1:color2;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3}var geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute(vertices,3));geometry.addAttribute("color",new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:VertexColors});LineSegments.call(this,geometry,material)}GridHelper.prototype=Object.create(LineSegments.prototype);GridHelper.prototype.constructor=GridHelper;function PolarGridHelper(radius,radials,circles,divisions,color1,color2){radius=radius||10;radials=radials||16;circles=circles||8;divisions=divisions||64;color1=new Color(color1!==undefined?color1:4473924);color2=new Color(color2!==undefined?color2:8947848);var vertices=[];var colors=[];var x,z;var v,i,j,r,color;for(i=0;i<=radials;i++){v=i/radials*(Math.PI*2);x=Math.sin(v)*radius;z=Math.cos(v)*radius;vertices.push(0,0,0);vertices.push(x,0,z);color=i&1?color1:color2;colors.push(color.r,color.g,color.b);colors.push(color.r,color.g,color.b)}for(i=0;i<=circles;i++){color=i&1?color1:color2;r=radius-radius/circles*i;for(j=0;j<divisions;j++){v=j/divisions*(Math.PI*2);x=Math.sin(v)*r;z=Math.cos(v)*r;vertices.push(x,0,z);colors.push(color.r,color.g,color.b);v=(j+1)/divisions*(Math.PI*2);x=Math.sin(v)*r;z=Math.cos(v)*r;vertices.push(x,0,z);colors.push(color.r,color.g,color.b)}}var geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute(vertices,3));geometry.addAttribute("color",new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:VertexColors});LineSegments.call(this,geometry,material)}PolarGridHelper.prototype=Object.create(LineSegments.prototype);PolarGridHelper.prototype.constructor=PolarGridHelper;function FaceNormalsHelper(object,size,hex,linewidth){this.object=object;this.size=size!==undefined?size:1;var color=hex!==undefined?hex:16776960;var width=linewidth!==undefined?linewidth:1;var nNormals=0;var objGeometry=this.object.geometry;if(objGeometry&&objGeometry.isGeometry){nNormals=objGeometry.faces.length}else{console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.")}var geometry=new BufferGeometry;var positions=new Float32BufferAttribute(nNormals*2*3,3);geometry.addAttribute("position",positions);LineSegments.call(this,geometry,new LineBasicMaterial({color:color,linewidth:width}));this.matrixAutoUpdate=false;this.update()}FaceNormalsHelper.prototype=Object.create(LineSegments.prototype);FaceNormalsHelper.prototype.constructor=FaceNormalsHelper;FaceNormalsHelper.prototype.update=function(){var v1=new Vector3;var v2=new Vector3;var normalMatrix=new Matrix3;return function update(){this.object.updateMatrixWorld(true);normalMatrix.getNormalMatrix(this.object.matrixWorld);var matrixWorld=this.object.matrixWorld;var position=this.geometry.attributes.position;var objGeometry=this.object.geometry;var vertices=objGeometry.vertices;var faces=objGeometry.faces;var idx=0;for(var i=0,l=faces.length;i<l;i++){var face=faces[i];var normal=face.normal;v1.copy(vertices[face.a]).add(vertices[face.b]).add(vertices[face.c]).divideScalar(3).applyMatrix4(matrixWorld);v2.copy(normal).applyMatrix3(normalMatrix).normalize().multiplyScalar(this.size).add(v1);position.setXYZ(idx,v1.x,v1.y,v1.z);idx=idx+1;position.setXYZ(idx,v2.x,v2.y,v2.z);idx=idx+1}position.needsUpdate=true}}();function DirectionalLightHelper(light,size,color){Object3D.call(this);this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;if(size===undefined)size=1;var geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute([-size,size,0,size,size,0,size,-size,0,-size,-size,0,-size,size,0],3));var material=new LineBasicMaterial({fog:false});this.lightPlane=new Line(geometry,material);this.add(this.lightPlane);geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute([0,0,0,0,0,1],3));this.targetLine=new Line(geometry,material);this.add(this.targetLine);this.update()}DirectionalLightHelper.prototype=Object.create(Object3D.prototype);DirectionalLightHelper.prototype.constructor=DirectionalLightHelper;DirectionalLightHelper.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};DirectionalLightHelper.prototype.update=function(){var v1=new Vector3;var v2=new Vector3;var v3=new Vector3;return function update(){v1.setFromMatrixPosition(this.light.matrixWorld);v2.setFromMatrixPosition(this.light.target.matrixWorld);v3.subVectors(v2,v1);this.lightPlane.lookAt(v3);if(this.color!==undefined){this.lightPlane.material.color.set(this.color);this.targetLine.material.color.set(this.color)}else{this.lightPlane.material.color.copy(this.light.color);this.targetLine.material.color.copy(this.light.color)}this.targetLine.lookAt(v3);this.targetLine.scale.z=v3.length()}}();function CameraHelper(camera){var geometry=new BufferGeometry;var material=new LineBasicMaterial({color:16777215,vertexColors:FaceColors});var vertices=[];var colors=[];var pointMap={};var colorFrustum=new Color(16755200)

var colorCone=new Color(16711680);var colorUp=new Color(43775);var colorTarget=new Color(16777215);var colorCross=new Color(3355443);addLine("n1","n2",colorFrustum);addLine("n2","n4",colorFrustum);addLine("n4","n3",colorFrustum);addLine("n3","n1",colorFrustum);addLine("f1","f2",colorFrustum);addLine("f2","f4",colorFrustum);addLine("f4","f3",colorFrustum);addLine("f3","f1",colorFrustum);addLine("n1","f1",colorFrustum);addLine("n2","f2",colorFrustum);addLine("n3","f3",colorFrustum);addLine("n4","f4",colorFrustum);addLine("p","n1",colorCone);addLine("p","n2",colorCone);addLine("p","n3",colorCone);addLine("p","n4",colorCone);addLine("u1","u2",colorUp);addLine("u2","u3",colorUp);addLine("u3","u1",colorUp);addLine("c","t",colorTarget);addLine("p","c",colorCross);addLine("cn1","cn2",colorCross);addLine("cn3","cn4",colorCross);addLine("cf1","cf2",colorCross);addLine("cf3","cf4",colorCross);function addLine(a,b,color){addPoint(a,color);addPoint(b,color)}function addPoint(id,color){vertices.push(0,0,0);colors.push(color.r,color.g,color.b);if(pointMap[id]===undefined){pointMap[id]=[]}pointMap[id].push(vertices.length/3-1)}geometry.addAttribute("position",new Float32BufferAttribute(vertices,3));geometry.addAttribute("color",new Float32BufferAttribute(colors,3));LineSegments.call(this,geometry,material);this.camera=camera;if(this.camera.updateProjectionMatrix)this.camera.updateProjectionMatrix();this.matrix=camera.matrixWorld;this.matrixAutoUpdate=false;this.pointMap=pointMap;this.update()}CameraHelper.prototype=Object.create(LineSegments.prototype);CameraHelper.prototype.constructor=CameraHelper;CameraHelper.prototype.update=function(){var geometry,pointMap;var vector=new Vector3;var camera=new Camera;function setPoint(point,x,y,z){vector.set(x,y,z).unproject(camera);var points=pointMap[point];if(points!==undefined){var position=geometry.getAttribute("position");for(var i=0,l=points.length;i<l;i++){position.setXYZ(points[i],vector.x,vector.y,vector.z)}}}return function update(){geometry=this.geometry;pointMap=this.pointMap;var w=1,h=1;camera.projectionMatrix.copy(this.camera.projectionMatrix);setPoint("c",0,0,-1);setPoint("t",0,0,1);setPoint("n1",-w,-h,-1);setPoint("n2",w,-h,-1);setPoint("n3",-w,h,-1);setPoint("n4",w,h,-1);setPoint("f1",-w,-h,1);setPoint("f2",w,-h,1);setPoint("f3",-w,h,1);setPoint("f4",w,h,1);setPoint("u1",w*.7,h*1.1,-1);setPoint("u2",-w*.7,h*1.1,-1);setPoint("u3",0,h*2,-1);setPoint("cf1",-w,0,1);setPoint("cf2",w,0,1);setPoint("cf3",0,-h,1);setPoint("cf4",0,h,1);setPoint("cn1",-w,0,-1);setPoint("cn2",w,0,-1);setPoint("cn3",0,-h,-1);setPoint("cn4",0,h,-1);geometry.getAttribute("position").needsUpdate=true}}();function BoxHelper(object,color){this.object=object;if(color===undefined)color=16776960;var indices=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var positions=new Float32Array(8*3);var geometry=new BufferGeometry;geometry.setIndex(new BufferAttribute(indices,1));geometry.addAttribute("position",new BufferAttribute(positions,3));LineSegments.call(this,geometry,new LineBasicMaterial({color
color}));this.matrixAutoUpdate=false;this.update()}BoxHelper.prototype=Object.create(LineSegments.prototype);BoxHelper.prototype.constructor=BoxHelper;BoxHelper.prototype.update=function(){var box=new Box3;return function update(object){if(object!==undefined){console.warn("THREE.BoxHelper: .update() has no longer arguments.")}if(this.object!==undefined){box.setFromObject(this.object)}if(box.isEmpty())return;var min=box.min;var max=box.max;var position=this.geometry.attributes.position;var array=position.array;array[0]=max.x;array[1]=max.y;array[2]=max.z;array[3]=min.x;array[4]=max.y;array[5]=max.z;array[6]=min.x;array[7]=min.y;array[8]=max.z;array[9]=max.x;array[10]=min.y;array[11]=max.z;array[12]=max.x;array[13]=max.y;array[14]=min.z;array[15]=min.x;array[16]=max.y;array[17]=min.z;array[18]=min.x;array[19]=min.y;array[20]=min.z;array[21]=max.x;array[22]=min.y;array[23]=min.z;position.needsUpdate=true;this.geometry.computeBoundingSphere()}}();BoxHelper.prototype.setFromObject=function(object){this.object=object;this.update();return this};function Box3Helper(box,hex){this.type="Box3Helper";this.box=box;var color=hex!==undefined?hex:16776960;var indices=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var positions=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1];var geometry=new BufferGeometry;geometry.setIndex(new BufferAttribute(indices,1));geometry.addAttribute("position",new Float32BufferAttribute(positions,3));LineSegments.call(this,geometry,new LineBasicMaterial({color:color}));this.geometry.computeBoundingSphere();this.onBeforeRender()}Box3Helper.prototype=Object.create(LineSegments.prototype);Box3Helper.prototype.constructor=Box3Helper;Box3Helper.prototype.onBeforeRender=function(){var box=this.box;if(box.isEmpty())return;box.getCenter(this.position);box.getSize(this.scale);this.scale.multiplyScalar(.5)};function PlaneHelper(plane,size,hex){this.type="PlaneHelper";this.plane=plane;this.size=size===undefined?1:size;var color=hex!==undefined?hex:16776960;var positions=[1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0];var geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute(positions,3));geometry.computeBoundingSphere();Line.call(this,geometry,new LineBasicMaterial({color:color}));var positions2=[1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1];var geometry2=new BufferGeometry;geometry2.addAttribute("position",new Float32BufferAttribute(positions2,3));geometry2.computeBoundingSphere();this.add(new Mesh(geometry2,new MeshBasicMaterial({color:color,opacity:.2,transparent:true,depthWrite:false})));this.onBeforeRender()}PlaneHelper.prototype=Object.create(Line.prototype);PlaneHelper.prototype.constructor=PlaneHelper;PlaneHelper.prototype.onBeforeRender=function(){var scale=-this.plane.constant;if(Math.abs(scale)<1e-8)scale=1e-8;this.scale.set(.5*this.size,.5*this.size,scale);this.lookAt(this.plane.normal);this.updateMatrixWorld()};var lineGeometry;var coneGeometry;function ArrowHelper(dir,origin,length,color,headLength,headWidth){Object3D.call(this);if(color===undefined)color=16776960;if(length===undefined)length=1;if(headLength===undefined)headLength=.2*length;if(headWidth===undefined)headWidth=.2*headLength;if(lineGeometry===undefined){lineGeometry=new BufferGeometry;lineGeometry.addAttribute("position",new Float32BufferAttribute([0,0,0,0,1,0],3));coneGeometry=new CylinderBufferGeometry(0,.5,1,5,1);coneGeometry.translate(0,-.5,0)}this.position.copy(origin);this.line=new Line(lineGeometry,new LineBasicMaterial({color:color}));this.line.matrixAutoUpdate=false;this.add(this.line);this.cone=new Mesh(coneGeometry,new MeshBasicMaterial({color:color}));this.cone.matrixAutoUpdate=false;this.add(this.cone);this.setDirection(dir);this.setLength(length,headLength,headWidth)}ArrowHelper.prototype=Object.create(Object3D.prototype);ArrowHelper.prototype.constructor=ArrowHelper;ArrowHelper.prototype.setDirection=function(){var axis=new Vector3;var radians;return function setDirection(dir){if(dir.y>.99999){this.quaternion.set(0,0,0,1)}else if(dir.y<-.99999){this.quaternion.set(1,0,0,0)}else{axis.set(dir.z,0,-dir.x).normalize();radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(axis,radians)}}}();ArrowHelper.prototype.setLength=function(length,headLength,headWidth){if(headLength===undefined)headLength=.2*length;if(headWidth===undefined)headWidth=.2*headLength;this.line.scale.set(1,Math.max(0,length-headLength),1);this.line.updateMatrix();this.cone.scale.set(headWidth,headLength,headWidth);this.cone.position.y=length;this.cone.updateMatrix()};ArrowHelper.prototype.setColor=function(color){this.line.material.color.copy(color);this.cone.material.color.copy(color)};function AxisHelper(size){size=size||1;var vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];var colors=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1];var geometry=new BufferGeometry;geometry.addAttribute("position",new Float32BufferAttribute(vertices,3));geometry.addAttribute("color",new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:VertexColors});LineSegments.call(this,geometry,material)}AxisHelper.prototype=Object.create(LineSegments.prototype);AxisHelper.prototype.constructor=AxisHelper;function CubicPoly(){var c0=0,c1=0,c2=0,c3=0;function init(x0,x1,t0,t1){c0=x0;c1=t0;c2=-3*x0+3*x1-2*t0-t1;c3=2*x0-2*x1+t0+t1}return{initCatmullRom:function(x0,x1,x2,x3,tension){init(x1,x2,tension*(x2-x0),tension*(x3-x1))},initNonuniformCatmullRom:function(x0,x1,x2,x3,dt0,dt1,dt2){var t1=(x1-x0)/dt0-(x2-x0)/(dt0+dt1)+(x2-x1)/dt1;var t2=(x2-x1)/dt1-(x3-x1)/(dt1+dt2)+(x3-x2)/dt2;t1*=dt1;t2*=dt1;init(x1,x2,t1,t2)},calc:function(t){var t2=t*t;var t3=t2*t;return c0+c1*t+c2*t2+c3*t3}}}var tmp=new Vector3;var px=new CubicPoly;var py=new CubicPoly;var pz=new CubicPoly;function CatmullRomCurve3(points){Curve.call(this);if(points.length<2)console.warn("THREE.CatmullRomCurve3: Points array needs at least two entries.");this.points=points||[];this.closed=false}CatmullRomCurve3.prototype=Object.create(Curve.prototype);CatmullRomCurve3.prototype.constructor=CatmullRomCurve3;CatmullRomCurve3.prototype.getPoint=function(t){var points=this.points;var l=points.length;var point=(l-(this.closed?0:1))*t;var intPoint=Math.floor(point);var weight=point-intPoint;if(this.closed){intPoint+=intPoint>0?0:(Math.floor(Math.abs(intPoint)/points.length)+1)*points.length}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1}var p0,p1,p2,p3;if(this.closed||intPoint>0){p0=points[(intPoint-1)%l]}else{tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp}p1=points[intPoint%l];p2=points[(intPoint+1)%l];if(this.closed||intPoint+2<l){p3=points[(intPoint+2)%l]}else{tmp.subVectors(points[l-1],points[l-2]).add(points[l-1]);p3=tmp}if(this.type===undefined||this.type==="centripetal"||this.type==="chordal"){var pow=this.type==="chordal"?.5:.25;var dt0=Math.pow(p0.distanceToSquared(p1),pow);var dt1=Math.pow(p1.distanceToSquared(p2),pow);var dt2=Math.pow(p2.distanceToSquared(p3),pow);if(dt1<1e-4)dt1=1;if(dt0<1e-4)dt0=dt1;if(dt2<1e-4)dt2=dt1;px.initNonuniformCatmullRom(p0.x,p1.x,p2.x,p3.x,dt0,dt1,dt2);py.initNonuniformCatmullRom(p0.y,p1.y,p2.y,p3.y,dt0,dt1,dt2);pz.initNonuniformCatmullRom(p0.z,p1.z,p2.z,p3.z,dt0,dt1,dt2)}else if(this.type==="catmullrom"){var tension=this.tension!==undefined?this.tension:.5;px.initCatmullRom(p0.x,p1.x,p2.x,p3.x,tension);py.initCatmullRom(p0.y,p1.y,p2.y,p3.y,tension);pz.initCatmullRom(p0.z,p1.z,p2.z,p3.z,tension)}return new Vector3(px.calc(weight),py.calc(weight),pz.calc(weight))};function CubicBezierCurve3(v0,v1,v2,v3){Curve.call(this);this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3}CubicBezierCurve3.prototype=Object.create(Curve.prototype);CubicBezierCurve3.prototype.constructor=CubicBezierCurve3;CubicBezierCurve3.prototype.getPoint=function(t){var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;return new Vector3(CubicBezier(t,v0.x,v1.x,v2.x,v3.x),CubicBezier(t,v0.y,v1.y,v2.y,v3.y),CubicBezier(t,v0.z,v1.z,v2.z,v3.z))};function QuadraticBezierCurve3(v0,v1,v2){Curve.call(this);this.v0=v0;this.v1=v1;this.v2=v2}QuadraticBezierCurve3.prototype=Object.create(Curve.prototype);QuadraticBezierCurve3.prototype.constructor=QuadraticBezierCurve3;QuadraticBezierCurve3.prototype.getPoint=function(t){var v0=this.v0,v1=this.v1,v2=this.v2;return new Vector3(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y),QuadraticBezier(t,v0.z,v1.z,v2.z))};function LineCurve3(v1,v2){Curve.call(this);this.v1=v1;this.v2=v2}LineCurve3.prototype=Object.create(Curve.prototype);LineCurve3.prototype.constructor=LineCurve3;LineCurve3.prototype.getPoint=function(t){if(t===1){return this.v2.clone()}var vector=new Vector3;vector.subVectors(this.v2,this.v1);vector.multiplyScalar(t);vector.add(this.v1);return vector};function ArcCurve(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){EllipseCurve.call(this,aX,aY,aRadius,aRadius,aStartAngle,aEndAngle,aClockwise)}ArcCurve.prototype=Object.create(EllipseCurve.prototype);ArcCurve.prototype.constructor=ArcCurve;var SceneUtils={createMultiMaterialObject:function(geometry,materials){var group=new Group;for(var i=0,l=materials.length;i<l;i++){group.add(new Mesh(geometry,materials[i]))}return group},detach:function(child,parent,scene){child.applyMatrix(parent.matrixWorld);parent.remove(child);scene.add(child)},attach:function(child,scene,parent){child.applyMatrix((new Matrix4).getInverse(parent.matrixWorld));scene.remove(child);parent.add(child)}};function Face4(a,b,c,d,normal,color,materialIndex){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Face3(a,b,c,normal,color,materialIndex)}var LineStrip=0;var LinePieces=1;function MeshFaceMaterial(materials){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return materials}function MultiMaterial(materials){if(materials===undefined)materials=[];console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");materials.isMultiMaterial=true;materials.materials=materials;materials.clone=function(){return materials.slice()};return materials}function PointCloud(geometry,material){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Points(geometry,material)}function Particle(material){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Sprite(material)}function ParticleSystem(geometry,material){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Points(geometry,material)}function PointCloudMaterial(parameters){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new PointsMaterial(parameters)}function ParticleBasicMaterial(parameters){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new PointsMaterial(parameters)}function ParticleSystemMaterial(parameters){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new PointsMaterial(parameters)}function Vertex(x,y,z){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new Vector3(x,y,z)}function DynamicBufferAttribute(array,itemSize){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return new BufferAttribute(array,itemSize).setDynamic(true)}function Int8Attribute(array,itemSize){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new Int8BufferAttribute(array,itemSize)}function Uint8Attribute(array,itemSize){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new Uint8BufferAttribute(array,itemSize)}function Uint8ClampedAttribute(array,itemSize){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new Uint8ClampedBufferAttribute(array,itemSize)}function Int16Attribute(array,itemSize){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new Int16BufferAttribute(array,itemSize)}function Uint16Attribute(array,itemSize){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new Uint16BufferAttribute(array,itemSize)}function Int32Attribute(array,itemSize){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new Int32BufferAttribute(array,itemSize)}function Uint32Attribute(array,itemSize){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new Uint32BufferAttribute(array,itemSize)}function Float32Attribute(array,itemSize){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new Float32BufferAttribute(array,itemSize)}function Float64Attribute(array,itemSize){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new Float64BufferAttribute(array,itemSize)}Curve.create=function(construct,getPoint){console.log("THREE.Curve.create() has been deprecated");construct.prototype=Object.create(Curve.prototype);construct.prototype.constructor=construct;construct.prototype.getPoint=getPoint;return construct};function ClosedSplineCurve3(points){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");CatmullRomCurve3.call(this,points);this.type="catmullrom";this.closed=true}ClosedSplineCurve3.prototype=Object.create(CatmullRomCurve3.prototype);function SplineCurve3(points){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");CatmullRomCurve3.call(this,points);this.type="catmullrom"}SplineCurve3.prototype=Object.create(CatmullRomCurve3.prototype);function Spline(points){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");CatmullRomCurve3.call(this,points);this.type="catmullrom"}Spline.prototype=Object.create(CatmullRomCurve3.prototype);Object.assign(Spline.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(optionalTarget){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(samplingCoef){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});function BoundingBoxHelper(object,color){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new BoxHelper(object,color)}function EdgesHelper(object,hex){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new LineSegments(new EdgesGeometry(object.geometry),new LineBasicMaterial({color:hex!==undefined?hex:16777215}))}GridHelper.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};SkeletonHelper.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};function WireframeHelper(object,hex){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new LineSegments(new WireframeGeometry(object.geometry),new LineBasicMaterial({color:hex!==undefined?hex:16777215}))}function XHRLoader(manager){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new FileLoader(manager)}function BinaryTextureLoader(manager){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new DataTextureLoader(manager)}Object.assign(Box2.prototype,{center:function(optionalTarget){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(optionalTarget)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(box){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(box)},size:function(optionalTarget){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(optionalTarget)}});Object.assign(Box3.prototype,{center:function(optionalTarget){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(optionalTarget)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(box){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(box)},isIntersectionSphere:function(sphere){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(sphere)},size:function(optionalTarget){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(optionalTarget)}});Line3.prototype.center=function(optionalTarget){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(optionalTarget)};_Math.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(Matrix3.prototype,{flattenToArrayOffset:function(array,offset){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(array,offset)},multiplyVector3:function(vector){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return vector.applyMatrix3(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(buffer,offset,length){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(buffer)},applyToVector3Array:function(array,offset,length){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(Matrix4.prototype,{extractPosition:function(m){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(m)},flattenToArrayOffset:function(array,offset){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(array,offset)},getPosition:function(){var v1;return function getPosition(){if(v1===undefined)v1=new Vector3;console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return v1.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(q){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(q)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(vector){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");return vector.applyMatrix4(this)},multiplyVector4:function(vector){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return vector.applyMatrix4(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},rotateAxis:function(v){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");v.transformDirection(this)},crossVector:function(vector){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");return vector.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(buffer,offset,length){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(buffer)},applyToVector3Array:function(array,offset,length){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(left,right,bottom,top,near,far){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(left,right,top,bottom,near,far)}});Plane.prototype.isIntersectionLine=function(line){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(line)};Quaternion.prototype.multiplyVector3=function(vector){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return vector.applyQuaternion(this)};Object.assign(Ray.prototype,{isIntersectionBox:function(box){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(box)},isIntersectionPlane:function(plane){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(plane)},isIntersectionSphere:function(sphere){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(sphere)}});Object.assign(Shape.prototype,{extrude:function(options){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new ExtrudeGeometry(this,options)},makeGeometry:function(options){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new ShapeGeometry(this,options)}});Object.assign(Vector2.prototype,{fromAttribute:function(attribute,index,offset){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(attribute,index,offset)}});Object.assign(Vector3.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(m){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(m)},getScaleFromMatrix:function(m){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(m)},getColumnFromMatrix:function(index,matrix){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(matrix,index)},applyProjection:function(m){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(m)},fromAttribute:function(attribute,index,offset){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(attribute,index,offset)}});Object.assign(Vector4.prototype,{fromAttribute:function(attribute,index,offset){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(attribute,index,offset)}});Geometry.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(Object3D.prototype,{getChildByName:function(name){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");return this.getObjectByName(name)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(distance,axis){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(axis,distance)}});Object.defineProperties(Object3D.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(value){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");this.rotation.order=value}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(LOD.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Skeleton.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(Curve.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(value){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=value}});PerspectiveCamera.prototype.setLens=function(focalLength,filmGauge){console.warn("THREE.PerspectiveCamera.setLens is deprecated. "+"Use .setFocalLength and .filmGauge for a photographic setup.");if(filmGauge!==undefined)this.filmGauge=filmGauge;this.setFocalLength(focalLength)};Object.defineProperties(Light.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(value){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=value}},shadowCameraLeft:{set:function(value){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=value}},shadowCameraRight:{set:function(value){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=value}},shadowCameraTop:{set:function(value){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=value}},shadowCameraBottom:{set:function(value){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");this.shadow.camera.bottom=value}},shadowCameraNear:{set:function(value){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=value}},shadowCameraFar:{set:function(value){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");this.shadow.camera.far=value}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(value){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");this.shadow.bias=value}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(value){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");this.shadow.mapSize.width=value}},shadowMapHeight:{set:function(value){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=value}}});Object.defineProperties(BufferAttribute.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(BufferGeometry.prototype,{addIndex:function(index){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(index)},addDrawCall:function(start,count,indexOffset){if(indexOffset!==undefined){console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.")}console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(start,count)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});Object.defineProperties(BufferGeometry.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){

console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});Object.defineProperties(Uniform.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");return this}}});Object.defineProperties(Material.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new Color}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(value){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");this.flatShading=value===THREE.FlatShading?true:false}}});Object.defineProperties(MeshPhongMaterial.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return false},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(ShaderMaterial.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(value){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=value}}});Object.assign(WebGLRenderer.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},getMaxAnisotropy:function(){console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().");return this.capabilities.getMaxAnisotropy()},getPrecision:function(){console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.");return this.capabilities.precision},supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(boolean){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(boolean)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(WebGLRenderer.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(value){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=value}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(value){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");this.shadowMap.type=value}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(value){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=value}}});Object.defineProperties(WebGLShadowMap.prototype,{cullFace:{get:function(){return this.renderReverseSided?CullFaceFront:CullFaceBack},set:function(cullFace){var value=cullFace!==CullFaceBack;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+value+".");this.renderReverseSided=value}}});Object.defineProperties(WebGLRenderTarget.prototype,{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(value){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=value}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(value){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=value}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");return this.texture.magFilter},set:function(value){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=value}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(value){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=value}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");return this.texture.anisotropy},set:function(value){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=value}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(value){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=value}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},set:function(value){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=value}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(value){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=value}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(value){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");this.texture.type=value}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(value){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=value}}});Audio.prototype.load=function(file){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var scope=this;var audioLoader=new AudioLoader;audioLoader.load(file,function(buffer){scope.setBuffer(buffer)});return this};AudioAnalyser.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};CubeCamera.prototype.updateCubeMap=function(renderer,scene){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(renderer,scene)};var GeometryUtils={merge:function(geometry1,geometry2,materialIndexOffset){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var matrix;if(geometry2.isMesh){geometry2.matrixAutoUpdate&&geometry2.updateMatrix();matrix=geometry2.matrix;geometry2=geometry2.geometry}geometry1.merge(geometry2,matrix,materialIndexOffset)},center:function(geometry){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return geometry.center()}};var ImageUtils={crossOrigin:undefined,loadTexture:function(url,mapping,onLoad,onError){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var loader=new TextureLoader;loader.setCrossOrigin(this.crossOrigin);var texture=loader.load(url,onLoad,undefined,onError);if(mapping)texture.mapping=mapping;return texture},loadTextureCube:function(urls,mapping,onLoad,onError){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var loader=new CubeTextureLoader;loader.setCrossOrigin(this.crossOrigin);var texture=loader.load(urls,onLoad,undefined,onError);if(mapping)texture.mapping=mapping;return texture},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};function Projector(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=function(vector,camera){console.warn("THREE.Projector: .projectVector() is now vector.project().");vector.project(camera)};this.unprojectVector=function(vector,camera){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");vector.unproject(camera)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}}function CanvasRenderer(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}}exports.WebGLRenderTargetCube=WebGLRenderTargetCube;exports.WebGLRenderTarget=WebGLRenderTarget;exports.WebGLRenderer=WebGLRenderer;exports.ShaderLib=ShaderLib;exports.UniformsLib=UniformsLib;exports.UniformsUtils=UniformsUtils;exports.ShaderChunk=ShaderChunk;exports.FogExp2=FogExp2;exports.Fog=Fog;exports.Scene=Scene;exports.LensFlare=LensFlare;exports.Sprite=Sprite;exports.LOD=LOD;exports.SkinnedMesh=SkinnedMesh;exports.Skeleton=Skeleton;exports.Bone=Bone;exports.Mesh=Mesh;exports.LineSegments=LineSegments;exports.LineLoop=LineLoop;exports.Line=Line;exports.Points=Points;exports.Group=Group;exports.VideoTexture=VideoTexture;exports.DataTexture=DataTexture;exports.CompressedTexture=CompressedTexture;exports.CubeTexture=CubeTexture;exports.CanvasTexture=CanvasTexture;exports.DepthTexture=DepthTexture;exports.Texture=Texture;exports.CompressedTextureLoader=CompressedTextureLoader;exports.DataTextureLoader=DataTextureLoader;exports.CubeTextureLoader=CubeTextureLoader;exports.TextureLoader=TextureLoader;exports.ObjectLoader=ObjectLoader;exports.MaterialLoader=MaterialLoader;exports.BufferGeometryLoader=BufferGeometryLoader;exports.DefaultLoadingManager=DefaultLoadingManager;exports.LoadingManager=LoadingManager;exports.JSONLoader=JSONLoader;exports.ImageLoader=ImageLoader;exports.FontLoader=FontLoader;exports.FileLoader=FileLoader;exports.Loader=Loader;exports.Cache=Cache;exports.AudioLoader=AudioLoader;exports.SpotLightShadow=SpotLightShadow;exports.SpotLight=SpotLight;exports.PointLight=PointLight;exports.RectAreaLight=RectAreaLight;exports.HemisphereLight=HemisphereLight;exports.DirectionalLightShadow=DirectionalLightShadow;exports.DirectionalLight=DirectionalLight;exports.AmbientLight=AmbientLight;exports.LightShadow=LightShadow;exports.Light=Light;exports.StereoCamera=StereoCamera;exports.PerspectiveCamera=PerspectiveCamera;exports.OrthographicCamera=OrthographicCamera;exports.CubeCamera=CubeCamera;exports.ArrayCamera=ArrayCamera;exports.Camera=Camera;exports.AudioListener=AudioListener;exports.PositionalAudio=PositionalAudio;exports.AudioContext=AudioContext;exports.AudioAnalyser=AudioAnalyser;exports.Audio=Audio;exports.VectorKeyframeTrack=VectorKeyframeTrack;exports.StringKeyframeTrack=StringKeyframeTrack;exports.QuaternionKeyframeTrack=QuaternionKeyframeTrack;exports.NumberKeyframeTrack=NumberKeyframeTrack;exports.ColorKeyframeTrack=ColorKeyframeTrack;exports.BooleanKeyframeTrack=BooleanKeyframeTrack;exports.PropertyMixer=PropertyMixer;exports.PropertyBinding=PropertyBinding;exports.KeyframeTrack=KeyframeTrack;exports.AnimationUtils=AnimationUtils;exports.AnimationObjectGroup=AnimationObjectGroup;exports.AnimationMixer=AnimationMixer;exports.AnimationClip=AnimationClip;exports.Uniform=Uniform;exports.InstancedBufferGeometry=InstancedBufferGeometry;exports.BufferGeometry=BufferGeometry;exports.GeometryIdCount=GeometryIdCount;exports.Geometry=Geometry;exports.InterleavedBufferAttribute=InterleavedBufferAttribute;exports.InstancedInterleavedBuffer=InstancedInterleavedBuffer;exports.InterleavedBuffer=InterleavedBuffer;exports.InstancedBufferAttribute=InstancedBufferAttribute;exports.Face3=Face3;exports.Object3D=Object3D;exports.Raycaster=Raycaster;exports.Layers=Layers;exports.EventDispatcher=EventDispatcher;exports.Clock=Clock;exports.QuaternionLinearInterpolant=QuaternionLinearInterpolant;exports.LinearInterpolant=LinearInterpolant;exports.DiscreteInterpolant=DiscreteInterpolant;exports.CubicInterpolant=CubicInterpolant;exports.Interpolant=Interpolant;exports.Triangle=Triangle;exports.Math=_Math;exports.Spherical=Spherical;exports.Cylindrical=Cylindrical;exports.Plane=Plane;exports.Frustum=Frustum;exports.Sphere=Sphere;exports.Ray=Ray;exports.Matrix4=Matrix4;exports.Matrix3=Matrix3;exports.Box3=Box3;exports.Box2=Box2;exports.Line3=Line3;exports.Euler=Euler;exports.Vector4=Vector4;exports.Vector3=Vector3;exports.Vector2=Vector2;exports.Quaternion=Quaternion;exports.Color=Color;exports.ImmediateRenderObject=ImmediateRenderObject;exports.VertexNormalsHelper=VertexNormalsHelper;exports.SpotLightHelper=SpotLightHelper;exports.SkeletonHelper=SkeletonHelper;exports.PointLightHelper=PointLightHelper;exports.RectAreaLightHelper=RectAreaLightHelper;exports.HemisphereLightHelper=HemisphereLightHelper;exports.GridHelper=GridHelper;exports.PolarGridHelper=PolarGridHelper;exports.FaceNormalsHelper=FaceNormalsHelper;exports.DirectionalLightHelper=DirectionalLightHelper;exports.CameraHelper=CameraHelper;exports.BoxHelper=BoxHelper;exports.Box3Helper=Box3Helper;exports.PlaneHelper=PlaneHelper;exports.ArrowHelper=ArrowHelper;exports.AxisHelper=AxisHelper;exports.CatmullRomCurve3=CatmullRomCurve3;exports.CubicBezierCurve3=CubicBezierCurve3;exports.QuadraticBezierCurve3=QuadraticBezierCurve3;exports.LineCurve3=LineCurve3;exports.ArcCurve=ArcCurve;exports.EllipseCurve=EllipseCurve;exports.SplineCurve=SplineCurve;exports.CubicBezierCurve=CubicBezierCurve;exports.QuadraticBezierCurve=QuadraticBezierCurve;exports.LineCurve=LineCurve;exports.Shape=Shape;exports.Path=Path;exports.ShapePath=ShapePath;exports.Font=Font;exports.CurvePath=CurvePath;exports.Curve=Curve;exports.ShapeUtils=ShapeUtils;exports.SceneUtils=SceneUtils;exports.WebGLUtils=WebGLUtils;exports.WireframeGeometry=WireframeGeometry;exports.ParametricGeometry=ParametricGeometry;exports.ParametricBufferGeometry=ParametricBufferGeometry;exports.TetrahedronGeometry=TetrahedronGeometry;exports.TetrahedronBufferGeometry=TetrahedronBufferGeometry;exports.OctahedronGeometry=OctahedronGeometry;exports.OctahedronBufferGeometry=OctahedronBufferGeometry;exports.IcosahedronGeometry=IcosahedronGeometry;exports.IcosahedronBufferGeometry=IcosahedronBufferGeometry;exports.DodecahedronGeometry=DodecahedronGeometry;exports.DodecahedronBufferGeometry=DodecahedronBufferGeometry;exports.PolyhedronGeometry=PolyhedronGeometry;exports.PolyhedronBufferGeometry=PolyhedronBufferGeometry;exports.TubeGeometry=TubeGeometry;exports.TubeBufferGeometry=TubeBufferGeometry;exports.TorusKnotGeometry=TorusKnotGeometry;exports.TorusKnotBufferGeometry=TorusKnotBufferGeometry;exports.TorusGeometry=TorusGeometry;exports.TorusBufferGeometry=TorusBufferGeometry;exports.TextGeometry=TextGeometry;exports.TextBufferGeometry=TextBufferGeometry;exports.SphereGeometry=SphereGeometry;exports.SphereBufferGeometry=SphereBufferGeometry;exports.RingGeometry=RingGeometry;exports.RingBufferGeometry=RingBufferGeometry;exports.PlaneGeometry=PlaneGeometry;exports.PlaneBufferGeometry=PlaneBufferGeometry;exports.LatheGeometry=LatheGeometry;exports.LatheBufferGeometry=LatheBufferGeometry;exports.ShapeGeometry=ShapeGeometry;exports.ShapeBufferGeometry=ShapeBufferGeometry;exports.ExtrudeGeometry=ExtrudeGeometry;exports.ExtrudeBufferGeometry=ExtrudeBufferGeometry;exports.EdgesGeometry=EdgesGeometry;exports.ConeGeometry=ConeGeometry;exports.ConeBufferGeometry=ConeBufferGeometry;exports.CylinderGeometry=CylinderGeometry;exports.CylinderBufferGeometry=CylinderBufferGeometry;exports.CircleGeometry=CircleGeometry;exports.CircleBufferGeometry=CircleBufferGeometry;exports.BoxGeometry=BoxGeometry;exports.BoxBufferGeometry=BoxBufferGeometry;exports.ShadowMaterial=ShadowMaterial;exports.SpriteMaterial=SpriteMaterial;exports.RawShaderMaterial=RawShaderMaterial;exports.ShaderMaterial=ShaderMaterial;exports.PointsMaterial=PointsMaterial;exports.MeshPhysicalMaterial=MeshPhysicalMaterial;exports.MeshStandardMaterial=MeshStandardMaterial;exports.MeshPhongMaterial=MeshPhongMaterial;exports.MeshToonMaterial=MeshToonMaterial;exports.MeshNormalMaterial=MeshNormalMaterial;exports.MeshLambertMaterial=MeshLambertMaterial;exports.MeshDepthMaterial=MeshDepthMaterial;exports.MeshDistanceMaterial=MeshDistanceMaterial;exports.MeshBasicMaterial=MeshBasicMaterial;exports.LineDashedMaterial=LineDashedMaterial;exports.LineBasicMaterial=LineBasicMaterial;exports.Material=Material;exports.Float64BufferAttribute=Float64BufferAttribute;exports.Float32BufferAttribute=Float32BufferAttribute;exports.Uint32BufferAttribute=Uint32BufferAttribute;exports.Int32BufferAttribute=Int32BufferAttribute;exports.Uint16BufferAttribute=Uint16BufferAttribute;exports.Int16BufferAttribute=Int16BufferAttribute;exports.Uint8ClampedBufferAttribute=Uint8ClampedBufferAttribute;exports.Uint8BufferAttribute=Uint8BufferAttribute;exports.Int8BufferAttribute=Int8BufferAttribute;exports.BufferAttribute=BufferAttribute;exports.REVISION=REVISION;exports.MOUSE=MOUSE;exports.CullFaceNone=CullFaceNone;exports.CullFaceBack=CullFaceBack;exports.CullFaceFront=CullFaceFront;exports.CullFaceFrontBack=CullFaceFrontBack;exports.FrontFaceDirectionCW=FrontFaceDirectionCW;exports.FrontFaceDirectionCCW=FrontFaceDirectionCCW;exports.BasicShadowMap=BasicShadowMap;exports.PCFShadowMap=PCFShadowMap;exports.PCFSoftShadowMap=PCFSoftShadowMap;exports.FrontSide=FrontSide;exports.BackSide=BackSide;exports.DoubleSide=DoubleSide;exports.FlatShading=FlatShading;exports.SmoothShading=SmoothShading;exports.NoColors=NoColors;exports.FaceColors=FaceColors;exports.VertexColors=VertexColors;exports.NoBlending=NoBlending;exports.NormalBlending=NormalBlending;exports.AdditiveBlending=AdditiveBlending;exports.SubtractiveBlending=SubtractiveBlending;exports.MultiplyBlending=MultiplyBlending;exports.CustomBlending=CustomBlending;exports.AddEquation=AddEquation;exports.SubtractEquation=SubtractEquation;exports.ReverseSubtractEquation=ReverseSubtractEquation;exports.MinEquation=MinEquation;exports.MaxEquation=MaxEquation;exports.ZeroFactor=ZeroFactor;exports.OneFactor=OneFactor;exports.SrcColorFactor=SrcColorFactor;exports.OneMinusSrcColorFactor=OneMinusSrcColorFactor;exports.SrcAlphaFactor=SrcAlphaFactor;exports.OneMinusSrcAlphaFactor=OneMinusSrcAlphaFactor;exports.DstAlphaFactor=DstAlphaFactor;exports.OneMinusDstAlphaFactor=OneMinusDstAlphaFactor;exports.DstColorFactor=DstColorFactor;exports.OneMinusDstColorFactor=OneMinusDstColorFactor;exports.SrcAlphaSaturateFactor=SrcAlphaSaturateFactor;exports.NeverDepth=NeverDepth;exports.AlwaysDepth=AlwaysDepth;exports.LessDepth=LessDepth;exports.LessEqualDepth=LessEqualDepth;exports.EqualDepth=EqualDepth;exports.GreaterEqualDepth=GreaterEqualDepth;exports.GreaterDepth=GreaterDepth;exports.NotEqualDepth=NotEqualDepth;exports.MultiplyOperation=MultiplyOperation;exports.MixOperation=MixOperation;exports.AddOperation=AddOperation;exports.NoToneMapping=NoToneMapping;exports.LinearToneMapping=LinearToneMapping;exports.ReinhardToneMapping=ReinhardToneMapping;exports.Uncharted2ToneMapping=Uncharted2ToneMapping;exports.CineonToneMapping=CineonToneMapping;exports.UVMapping=UVMapping;exports.CubeReflectionMapping=CubeReflectionMapping;exports.CubeRefractionMapping=CubeRefractionMapping;exports.EquirectangularReflectionMapping=EquirectangularReflectionMapping;exports.EquirectangularRefractionMapping=EquirectangularRefractionMapping;exports.SphericalReflectionMapping=SphericalReflectionMapping;exports.CubeUVReflectionMapping=CubeUVReflectionMapping;exports.CubeUVRefractionMapping=CubeUVRefractionMapping;exports.RepeatWrapping=RepeatWrapping;exports.ClampToEdgeWrapping=ClampToEdgeWrapping;exports.MirroredRepeatWrapping=MirroredRepeatWrapping;exports.NearestFilter=NearestFilter;exports.NearestMipMapNearestFilter=NearestMipMapNearestFilter;exports.NearestMipMapLinearFilter=NearestMipMapLinearFilter;exports.LinearFilter=LinearFilter;exports.LinearMipMapNearestFilter=LinearMipMapNearestFilter;exports.LinearMipMapLinearFilter=LinearMipMapLinearFilter;exports.UnsignedByteType=UnsignedByteType;exports.ByteType=ByteType;exports.ShortType=ShortType;exports.UnsignedShortType=UnsignedShortType;exports.IntType=IntType;exports.UnsignedIntType=UnsignedIntType;exports.FloatType=FloatType;exports.HalfFloatType=HalfFloatType;exports.UnsignedShort4444Type=UnsignedShort4444Type;exports.UnsignedShort5551Type=UnsignedShort5551Type;exports.UnsignedShort565Type=UnsignedShort565Type;exports.UnsignedInt248Type=UnsignedInt248Type;exports.AlphaFormat=AlphaFormat;exports.RGBFormat=RGBFormat;exports.RGBAFormat=RGBAFormat;exports.LuminanceFormat=LuminanceFormat;exports.LuminanceAlphaFormat=LuminanceAlphaFormat;exports.RGBEFormat=RGBEFormat;exports.DepthFormat=DepthFormat;exports.DepthStencilFormat=DepthStencilFormat;exports.RGB_S3TC_DXT1_Format=RGB_S3TC_DXT1_Format;exports.RGBA_S3TC_DXT1_Format=RGBA_S3TC_DXT1_Format;exports.RGBA_S3TC_DXT3_Format=RGBA_S3TC_DXT3_Format;exports.RGBA_S3TC_DXT5_Format=RGBA_S3TC_DXT5_Format;exports.RGB_PVRTC_4BPPV1_Format=RGB_PVRTC_4BPPV1_Format;exports.RGB_PVRTC_2BPPV1_Format=RGB_PVRTC_2BPPV1_Format;exports.RGBA_PVRTC_4BPPV1_Format=RGBA_PVRTC_4BPPV1_Format;exports.RGBA_PVRTC_2BPPV1_Format=RGBA_PVRTC_2BPPV1_Format;exports.RGB_ETC1_Format=RGB_ETC1_Format;exports.LoopOnce=LoopOnce;exports.LoopRepeat=LoopRepeat;exports.LoopPingPong=LoopPingPong;exports.InterpolateDiscrete=InterpolateDiscrete;exports.InterpolateLinear=InterpolateLinear;exports.InterpolateSmooth=InterpolateSmooth;exports.ZeroCurvatureEnding=ZeroCurvatureEnding;exports.ZeroSlopeEnding=ZeroSlopeEnding;exports.WrapAroundEnding=WrapAroundEnding;exports.TrianglesDrawMode=TrianglesDrawMode;exports.TriangleStripDrawMode=TriangleStripDrawMode;exports.TriangleFanDrawMode=TriangleFanDrawMode;exports.LinearEncoding=LinearEncoding;exports.sRGBEncoding=sRGBEncoding;exports.GammaEncoding=GammaEncoding;exports.RGBEEncoding=RGBEEncoding;exports.LogLuvEncoding=LogLuvEncoding;exports.RGBM7Encoding=RGBM7Encoding;exports.RGBM16Encoding=RGBM16Encoding;exports.RGBDEncoding=RGBDEncoding;exports.BasicDepthPacking=BasicDepthPacking;exports.RGBADepthPacking=RGBADepthPacking;exports.CubeGeometry=BoxGeometry;exports.Face4=Face4;exports.LineStrip=LineStrip;exports.LinePieces=LinePieces;exports.MeshFaceMaterial=MeshFaceMaterial;exports.MultiMaterial=MultiMaterial;exports.PointCloud=PointCloud;exports.Particle=Particle;exports.ParticleSystem=ParticleSystem;exports.PointCloudMaterial=PointCloudMaterial;exports.ParticleBasicMaterial=ParticleBasicMaterial;exports.ParticleSystemMaterial=ParticleSystemMaterial;exports.Vertex=Vertex;exports.DynamicBufferAttribute=DynamicBufferAttribute;exports.Int8Attribute=Int8Attribute;exports.Uint8Attribute=Uint8Attribute;exports.Uint8ClampedAttribute=Uint8ClampedAttribute;exports.Int16Attribute=Int16Attribute;exports.Uint16Attribute=Uint16Attribute;exports.Int32Attribute=Int32Attribute;exports.Uint32Attribute=Uint32Attribute;exports.Float32Attribute=Float32Attribute;exports.Float64Attribute=Float64Attribute;exports.ClosedSplineCurve3=ClosedSplineCurve3;exports.SplineCurve3=SplineCurve3;exports.Spline=Spline;exports.BoundingBoxHelper=BoundingBoxHelper;exports.EdgesHelper=EdgesHelper;exports.WireframeHelper=WireframeHelper;exports.XHRLoader=XHRLoader;exports.BinaryTextureLoader=BinaryTextureLoader;exports.GeometryUtils=GeometryUtils;exports.ImageUtils=ImageUtils;exports.Projector=Projector;exports.CanvasRenderer=CanvasRenderer;Object.defineProperty(exports,"__esModule",{value:true})})},{}],82:[function(require,module,exports){"use strict";var punycode=require("punycode");var util=require("./util");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/");url=uSplit.join(splitter);var rest=url;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1))}else{this.query=this.search.substr(1)}}else if(parseQueryString){this.search="";this.query={}}return this}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,function(match){ return encodeURIComponent(match)});search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":83,punycode:69,querystring:72}],83:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return typeof arg==="string"},isObject:function(arg){return typeof arg==="object"&&arg!==null},isNull:function(arg){return arg===null},isNullOrUndefined:function(arg){return arg==null}}},{}],84:[function(require,module,exports){(function(global){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],85:[function(require,module,exports){arguments[4][28][0].apply(exports,arguments)},{dup:28}],86:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],87:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"�["+inspect.colors[style][0]+"m"+str+"�["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":86,_process:68,inherits:85}],88:[function(require,module,exports){"use strict";var isString=require("validate.io-string-primitive");var isNonNegativeInteger=require("validate.io-nonnegative-integer");var ceil=require("math-ceil");var repeat=require("utils-repeat-string");var MAX_SAFE_INTEGER=9007199254740991;function lpad(str,len,pad){var n;var p;if(!isString(str)){throw new TypeError("invalid input argument. First argument must be a string. Value: `"+str+"`.")}if(!isNonNegativeInteger(len)){throw new TypeError("invalid input argument. Second argument must be a nonnegative integer. Value: `"+len+"`.")}if(arguments.length>2){p=pad;if(!isString(p)){throw new TypeError("invalid input argument. Third argument must be a string. Value: `"+p+"`.")}if(p.length===0){throw new RangeError("invalid input argument. Pad string must not be an empty string.")}}else{p=" "}if(len>MAX_SAFE_INTEGER){throw new RangeError("invalid input argument. Output string length exceeds maximum allowed string length.")}n=(len-str.length)/p.length;if(n<=0){return str}n=ceil(n);return repeat(p,n)+str}module.exports=lpad},{"math-ceil":41,"utils-repeat-string":89,"validate.io-nonnegative-integer":92,"validate.io-string-primitive":94}],89:[function(require,module,exports){"use strict";var isString=require("validate.io-string-primitive");var isNonNegativeInteger=require("validate.io-nonnegative-integer");var MAX_SAFE_INTEGER=9007199254740991;function repeat(str,n){var rpt;var cnt;if(!isString(str)){throw new TypeError("invalid input argument. First argument must be a string. Value: `"+str+"`.")}if(!isNonNegativeInteger(n)){throw new TypeError("invalid input argument. Second argument must be a nonnegative integer. Value: `"+n+"`.")}if(str.length===0||n===0){return""}if(str.length*n>MAX_SAFE_INTEGER){throw new RangeError("invalid input argument. Output string length exceeds maximum allowed string length.")}rpt="";cnt=n;for(;;){if((cnt&1)===1){rpt+=str}cnt>>>=1;if(cnt===0){break}str+=str}return rpt}module.exports=repeat},{"validate.io-nonnegative-integer":92,"validate.io-string-primitive":94}],90:[function(require,module,exports){"use strict";var isString=require("validate.io-string-primitive");var isNonNegativeInteger=require("validate.io-nonnegative-integer");var ceil=require("math-ceil");var repeat=require("utils-repeat-string");var MAX_SAFE_INTEGER=9007199254740991;function rpad(str,len,pad){var n;var p;if(!isString(str)){throw new TypeError("invalid input argument. First argument must be a string. Value: `"+str+"`.")}if(!isNonNegativeInteger(len)){throw new TypeError("invalid input argument. Second argument must be a nonnegative integer. Value: `"+len+"`.")}if(arguments.length>2){p=pad;if(!isString(p)){throw new TypeError("invalid input argument. Third argument must be a string. Value: `"+p+"`.")}if(p.length===0){throw new RangeError("invalid input argument. Pad string must not be an empty string.")}}else{p=" "}if(len>MAX_SAFE_INTEGER){throw new RangeError("invalid input argument. Output string length exceeds maximum allowed string length.")}n=(len-str.length)/p.length;if(n<=0){return str}n=ceil(n);return str+repeat(p,n)}module.exports=rpad},{"math-ceil":41,"utils-repeat-string":89,"validate.io-nonnegative-integer":92,"validate.io-string-primitive":94}],91:[function(require,module,exports){"use strict";var isNumber=require("validate.io-number");function isInteger(value){return isNumber(value)&&value%1===0}module.exports=isInteger},{"validate.io-number":93}],92:[function(require,module,exports){"use strict";var isInteger=require("validate.io-integer");function isNonNegativeInteger(value){return isInteger(value)&&value>=0}module.exports=isNonNegativeInteger},{"validate.io-integer":91}],93:[function(require,module,exports){"use strict";function isNumber(value){return(typeof value==="number"||Object.prototype.toString.call(value)==="[object Number]")&&value.valueOf()===value.valueOf()}module.exports=isNumber},{}],94:[function(require,module,exports){"use strict";function isString(value){return typeof value==="string"}module.exports=isString},{}],95:[function(require,module,exports){module.exports={name:"ami.js",version:"0.0.21-dev",main:"build/ami.js",keywords:["ami","ami.js","three.js","webgl","dicom","nifti","awesome","medical","imaging","xtk","nrrd","vtk","stl","trk"],author:{name:"Nicolas Rannou",email:"nicolas@eunate.ch",url:"https://eunate.ch"},license:"Apache-2.0",repository:{type:"git",url:"https://fnndsc.github.io/ami"},config:{threeVersion:"87",amiCDN:"https://cdnjs.cloudflare.com/ajax/libs/ami.js/",gaKey:"UA-39303022-3",transforms:"-t [babelify --presets [ es2015 ] ]"},dependencies:{"dicom-parser":"1.7.3","image-JPEG2000":"OHIF/image-JPEG2000#master","jpeg-lossless-decoder-js":"1.2.3","math-float32-to-binary-string":"^1.0.0","nifti-reader-js":"v0.5.3","nrrd-js":"^0.2.1",pako:"1.0.1",three:"0.87.0"},scripts:{"dist:prepare":"node ./scripts/$npm_package_config_mode.js --dist","dist:watchAmi":"watchify -d src/ami $npm_package_config_transforms --standalone AMI -o dist/build/ami.js -v","dist:watch":"watchify $npm_package_config_target -d $npm_package_config_transforms -o dist/$npm_package_config_target -v",dist:"npm run dist:prepare --ami.js:mode=$npm_package_config_mode && (live-server dist --open=$npm_package_config_open & npm run dist:watch --ami.js:target=$npm_package_config_target)",example:"npm run clean && node ./scripts/router.js examples ",lesson:"npm run clean && mkdir dist/build && touch dist/build/ami.js && node ./scripts/router.js lessons ",demo:"node ./scripts/lessons.js --demo",lint:"eslint src/**/*.js","build:examples":"npm run dist:prepare --ami.js:mode=examples && find examples -name '*.js' -print0 | xargs -0 -n1 -I{} bash -c \"echo Building {}; browserify {} -d -v $npm_package_config_transforms > dist/{} \"","build:ami":"browserify src/ami.js -d -v $npm_package_config_transforms --standalone AMI > build/ami.js && uglifyjs build/ami.js -o build/ami.min.js",build:"npm run clean && cp index.html dist/index.html && npm run build:examples && npm run doc","build-cjs":"rimraf lib && cross-env BABEL_ENV=cjs babel ./src -d lib",clean:"rimraf -rf dist/*",test:"karma start",doc:"jsdoc -p -r -R README.md -c jsdoc.json -d dist/doc src",ami:"npm run lint && npm run demo && npm run build:ami && npm run test",deploy:"npm run build && gh-pages -d dist"},devDependencies:{"babel-cli":"latest","babel-plugin-add-module-exports":"^0.2.1","babel-polyfill":"^6.13.0","babel-preset-es2015":"^6.13.2",babelify:"7.3.0",browserify:"^13.1.0","cross-env":"^3.2.3",eslint:"latest","eslint-config-google":"latest","gh-pages":"latest",glslify:"5.1.0","jasmine-core":"latest",jsdoc:"jsdoc3/jsdoc#master",karma:"latest","karma-browserify":"latest","karma-jasmine":"latest","karma-phantomjs-launcher":"1.0.4","karma-sinon":"^1.0.5","karma-spec-reporter":"latest","live-server":"^1.1.0","phantomjs-prebuilt":"2.1.14",rimraf:"^2.6.1","rollup-plugin-node-builtins":"^2.1.2",shelljs:"latest",sinon:"^2.0.0","uglify-js":"^2.7.3",watchify:"3.7.0"},engines:{node:">=6.9.0"},browserify:{transform:["babelify"]}}},{}],96:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _cameras=require("./cameras/cameras");var _cameras2=_interopRequireDefault(_cameras);var _controls=require("./controls/controls");var _controls2=_interopRequireDefault(_controls);var _core=require("./core/core");var _core2=_interopRequireDefault(_core);var _geometries=require("./geometries/geometries");var _geometries2=_interopRequireDefault(_geometries);var _helpers=require("./helpers/helpers");var _helpers2=_interopRequireDefault(_helpers);var _loaders=require("./loaders/loaders");var _loaders2=_interopRequireDefault(_loaders);var _models=require("./models/models");var _models2=_interopRequireDefault(_models);var _parsers=require("./parsers/parsers");var _parsers2=_interopRequireDefault(_parsers);var _presets=require("./presets/presets");var _presets2=_interopRequireDefault(_presets);var _shaders=require("./shaders/shaders");var _shaders2=_interopRequireDefault(_shaders);var _widgets=require("./widgets/widgets");var _widgets2=_interopRequireDefault(_widgets);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var pckg=require("../package.json");exports.default={Cameras:_cameras2.default,Controls:_controls2.default,Core:_core2.default,Geometries:_geometries2.default,Helpers:_helpers2.default,Presets:_presets2.default,Loaders:_loaders2.default,Models:_models2.default,Parsers:_parsers2.default,Shaders:_shaders2.default,Widgets:_widgets2.default};window.console.log("AMI "+pckg.version+" ( ThreeJS "+pckg.config.threeVersion+")")},{"../package.json":95,"./cameras/cameras":97,"./controls/controls":99,"./core/core":104,"./geometries/geometries":108,"./helpers/helpers":113,"./loaders/loaders":124,"./models/models":128,"./parsers/parsers":133,"./presets/presets":138,"./shaders/shaders":154,"./widgets/widgets":168}],97:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _cameras=require("./cameras.orthographic");var _cameras2=_interopRequireDefault(_cameras);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Orthographic:_cameras2.default}},{"./cameras.orthographic":98}],98:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("../core/core.intersections");var _core2=_interopRequireDefault(_core);var _core3=require("../core/core.validators");var _core4=_interopRequireDefault(_core3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var CamerasOrthographic=function(_THREE$OrthographicCa){_inherits(CamerasOrthographic,_THREE$OrthographicCa);function CamerasOrthographic(left,right,top,bottom,near,far){_classCallCheck(this,CamerasOrthographic);var _this=_possibleConstructorReturn(this,(CamerasOrthographic.__proto__||Object.getPrototypeOf(CamerasOrthographic)).call(this,left,right,top,bottom,near,far));_this._front=null;_this._back=null;_this._directions=[new _three.Vector3(1,0,0),new _three.Vector3(0,1,0),new _three.Vector3(0,0,1)];_this._directionsLabel=["A","P","L","R","I","S"];_this._orientation="default";_this._convention="radio";_this._stackOrientation=0;_this._right=null;_this._up=null;_this._direction=null;_this._controls=null;_this._box=null;_this._canvas={width:null,height:null};_this._fromFront=true;_this._angle=0;return _this}_createClass(CamerasOrthographic,[{key:"init",value:function init(xCosine,yCosine,zCosine,controls,box,canvas){console.warn("cameras.orthographic.init(...) is deprecated.\n Use .cosines, .controls, .box and .canvas instead.");if(!(_core4.default.vector3(xCosine)&&_core4.default.vector3(yCosine)&&_core4.default.vector3(zCosine)&&_core4.default.box(box)&&controls)){window.console.log("Invalid input provided.");return false}this._right=xCosine;this._up=this._adjustTopDirection(xCosine,yCosine);this._direction=(new _three.Vector3).crossVectors(this._right,this._up);this._controls=controls;this._box=box;this._canvas=canvas;var ray={position:this._box.center,direction:this._direction};var intersections=this._orderIntersections(_core2.default.rayBox(ray,this._box),this._direction);this._front=intersections[0];this._back=intersections[1];this.up.set(this._up.x,this._up.y,this._up.z);this._updateCanvas();this._updatePositionAndTarget(this._front,this._back);this._updateMatrices();this._updateDirections()}},{key:"update",value:function update(){if(this._orientation==="default"){switch(this._getMaxIndex(this._directions[2])){case 0:this._orientation="sagittal";break;case 1:this._orientation="coronal";break;case 2:this._orientation="axial";break;default:this._orientation="free";break}}if(this._orientation==="free"){this._right=this._directions[0];this._up=this._directions[1];this._direction=this._directions[2]}else{var leftIndex=this.leftDirection();var leftDirection=this._directions[leftIndex];var posteriorIndex=this.posteriorDirection();var posteriorDirection=this._directions[posteriorIndex];var superiorIndex=this.superiorDirection();var superiorDirection=this._directions[superiorIndex];if(this._convention==="radio"){switch(this._orientation){case"axial":if(posteriorDirection.y>0){posteriorDirection.negate()}if(superiorDirection.z<0){superiorDirection.negate()}this._right=leftDirection;this._up=posteriorDirection;this._direction=superiorDirection;break;case"coronal":if(superiorDirection.z<0){superiorDirection.negate()}if(posteriorDirection.y<0){posteriorDirection.negate()}this._right=leftDirection;this._up=superiorDirection;this._direction=posteriorDirection;break;case"sagittal":if(superiorDirection.z<0){superiorDirection.negate()}if(leftDirection.x>0){leftDirection.negate()}this._right=posteriorDirection;this._up=superiorDirection;this._direction=leftDirection;break;default:console.warn('"'+this._orientation+'" orientation is not valid.\n (choices: axial, coronal, sagittal)');break}}else if(this._convention==="neuro"){switch(this._orientation){case"axial":if(posteriorDirection.y>0){posteriorDirection.negate()}if(superiorDirection.z>0){superiorDirection.negate()}this._right=leftDirection;this._up=posteriorDirection;this._direction=superiorDirection;break;case"coronal":if(superiorDirection.z<0){superiorDirection.negate()}if(posteriorDirection.y>0){posteriorDirection.negate()}this._right=leftDirection;this._up=superiorDirection;this._direction=posteriorDirection;break;case"sagittal":if(superiorDirection.z<0){superiorDirection.negate()}if(leftDirection.x>0){leftDirection.negate()}this._right=posteriorDirection;this._up=superiorDirection;this._direction=leftDirection;break;default:console.warn('"'+this._orientation+'" orientation is not valid.\n (choices: axial, coronal, sagittal)');break}}else{console.warn(this._convention+" is not valid (choices: radio, neuro)")}}var ray={position:this._box.center,direction:this._direction};var intersections=this._orderIntersections(_core2.default.rayBox(ray,this._box),this._direction);this._front=intersections[0];this._back=intersections[1]

this.up.set(this._up.x,this._up.y,this._up.z);this._updateCanvas();this._updatePositionAndTarget(this._front,this._back);this._updateMatrices();this._updateDirections()}},{key
"leftDirection",value:function leftDirection(){return this._findMaxIndex(this._directions,0)}},{key:"posteriorDirection",value:function posteriorDirection(){return this._findMaxIndex(this._directions,1)}},{key:"superiorDirection",value:function superiorDirection(){return this._findMaxIndex(this._directions,2)}},{key:"invertRows",value:function invertRows(){this.up.multiplyScalar(-1);this.invertColumns();this._updateDirections()}},{key:"invertColumns",value:function invertColumns(){this.center();var oppositePosition=this._oppositePosition(this.position);this._updatePositionAndTarget(oppositePosition,this.position.clone());this._updateMatrices();this._fromFront=!this._fromFront;this._angle%=360;this._angle=360-this._angle;this._updateDirections()}},{key:"center",value:function center(){if(this._fromFront){this._updatePositionAndTarget(this._front,this._back)}else{this._updatePositionAndTarget(this._back,this._front)}this._updateMatrices();this._updateDirections()}},{key:"rotate",value:function rotate(){var angle=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;this.center();var computedAngle=90;var clockwise=1;if(!this._fromFront){clockwise=-1}if(angle===null){computedAngle*=-clockwise;this._angle+=90}else{computedAngle=360-clockwise*(angle-this._angle);this._angle=angle}this._angle%=360;var rotation=(new _three.Matrix4).makeRotationAxis(this._direction,computedAngle*Math.PI/180);this.up.applyMatrix4(rotation);this._updateMatrices();this._updateDirections()}},{key:"fitBox",value:function fitBox(){var direction=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var factor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1.5;var zoom=1;switch(direction){case 0:zoom=factor*this._computeZoom(this._canvas.width,this._right);break;case 1:zoom=factor*this._computeZoom(this._canvas.height,this._up);break;case 2:zoom=factor*Math.min(this._computeZoom(this._canvas.width,this._right),this._computeZoom(this._canvas.height,this._up));break;default:break}if(!zoom){return false}this.zoom=zoom;this.center()}},{key:"_adjustTopDirection",value:function _adjustTopDirection(horizontalDirection,verticalDirection){var vMaxIndex=this._getMaxIndex(verticalDirection);if(vMaxIndex===2&&verticalDirection.getComponent(vMaxIndex)<0||vMaxIndex===1&&verticalDirection.getComponent(vMaxIndex)>0||vMaxIndex===0&&verticalDirection.getComponent(vMaxIndex)>0){verticalDirection.negate()}return verticalDirection}},{key:"_getMaxIndex",value:function _getMaxIndex(vector){var maxValue=Math.abs(vector.x);var index=0;if(Math.abs(vector.y)>maxValue){maxValue=Math.abs(vector.y);index=1}if(Math.abs(vector.z)>maxValue){index=2}return index}},{key:"_findMaxIndex",value:function _findMaxIndex(directions,target){var maxIndices=this._getMaxIndices(directions);for(var i=0;i<maxIndices.length;i++){if(maxIndices[i]===target){return i}}}},{key:"_getMaxIndices",value:function _getMaxIndices(directions){var indices=[];indices.push(this._getMaxIndex(directions[0]));indices.push(this._getMaxIndex(directions[1]));indices.push(this._getMaxIndex(directions[2]));return indices}},{key:"_orderIntersections",value:function _orderIntersections(intersections,direction){var ordered=intersections[0].dot(direction)<intersections[1].dot(direction);if(!ordered){return[intersections[1],intersections[0]]}return intersections}},{key:"_updateCanvas",value:function _updateCanvas(){var camFactor=2;this.left=-this._canvas.width/camFactor;this.right=this._canvas.width/camFactor;this.top=this._canvas.height/camFactor;this.bottom=-this._canvas.height/camFactor;this._updateMatrices();this.controls.handleResize()}},{key:"_oppositePosition",value:function _oppositePosition(position){var oppositePosition=position.clone();oppositePosition.sub(this._box.center);var rotation=(new _three.Matrix4).makeRotationAxis(this.up,Math.PI);oppositePosition.applyMatrix4(rotation);oppositePosition.add(this._box.center);return oppositePosition}},{key:"_computeZoom",value:function _computeZoom(dimension,direction){if(!(dimension&&dimension>0)){window.console.log("Invalid dimension provided.");window.console.log(dimension);return false}var ray={position:this._box.center.clone(),direction:direction};var intersections=_core2.default.rayBox(ray,this._box);if(intersections.length<2){window.console.log("Can not adjust the camera ( < 2 intersections).");window.console.log(ray);window.console.log(this._box);return false}return dimension/intersections[0].distanceTo(intersections[1])}},{key:"_updatePositionAndTarget",value:function _updatePositionAndTarget(position,target){this.position.set(position.x,position.y,position.z);this.lookAt(target.x,target.y,target.z);this._controls.target.set(target.x,target.y,target.z)}},{key:"_updateMatrices",value:function _updateMatrices(){this._controls.update();this.updateProjectionMatrix();this.updateMatrixWorld()}},{key:"_updateLabels",value:function _updateLabels(){this._directionsLabel=[this._vector2Label(this._up),this._vector2Label(this._up.clone().negate()),this._vector2Label(this._right),this._vector2Label(this._right.clone().negate()),this._vector2Label(this._direction),this._vector2Label(this._direction.clone().negate())]}},{key:"_vector2Label",value:function _vector2Label(direction){var index=this._getMaxIndex(direction);var scaledDirection=direction.clone().divideScalar(Math.abs(direction.getComponent(index)));var delta=.2;var label="";for(var i=0;i<3;i++){if(i===0){if(scaledDirection.getComponent(i)+delta>=1){label+="L"}else if(scaledDirection.getComponent(i)-delta<=-1){label+="R"}}if(i===1){if(scaledDirection.getComponent(i)+delta>=1){label+="P"}else if(scaledDirection.getComponent(i)-delta<=-1){label+="A"}}if(i===2){if(scaledDirection.getComponent(i)+delta>=1){label+="S"}else if(scaledDirection.getComponent(i)-delta<=-1){label+="I"}}}return label}},{key:"_updateDirections",value:function _updateDirections(){this._up=this.up.clone();var pLocal=new _three.Vector3(0,0,-1);var pWorld=pLocal.applyMatrix4(this.matrixWorld);this._direction=pWorld.sub(this.position).normalize();this._right=(new _three.Vector3).crossVectors(this._direction,this.up);this._updateLabels()}},{key:"controls",set:function set(controls){this._controls=controls},get:function get(){return this._controls}},{key:"box",set:function set(box){this._box=box},get:function get(){return this._box}},{key:"canvas",set:function set(canvas){this._canvas=canvas;this._updateCanvas()},get:function get(){return this._canvas}},{key:"angle",set:function set(angle){this.rotate(angle)},get:function get(){return this._angle}},{key:"directions",set:function set(directions){this._directions=directions},get:function get(){return this._directions}},{key:"convention",set:function set(convention){this._convention=convention},get:function get(){return this._convention}},{key:"orientation",set:function set(orientation){this._orientation=orientation},get:function get(){return this._orientation}},{key:"directionsLabel",set:function set(directionsLabel){this._directionsLabel=directionsLabel},get:function get(){return this._directionsLabel}},{key:"stackOrientation",set:function set(stackOrientation){this._stackOrientation=stackOrientation;if(this._stackOrientation===0){this._orientation="default"}else{var maxIndex=this._getMaxIndex(this._directions[(this._stackOrientation+2)%3]);if(maxIndex===0){this._orientation="sagittal"}else if(maxIndex===1){this._orientation="coronal"}else if(maxIndex===2){this._orientation="axial"}}},get:function get(){if(this._orientation==="default"){this._stackOrientation=0}else{var maxIndex=this._getMaxIndex(this._direction);if(maxIndex===this._getMaxIndex(this._directions[2])){this._stackOrientation=0}else if(maxIndex===this._getMaxIndex(this._directions[0])){this._stackOrientation=1}else if(maxIndex===this._getMaxIndex(this._directions[1])){this._stackOrientation=2}}return this._stackOrientation}}]);return CamerasOrthographic}(THREE.OrthographicCamera);exports.default=CamerasOrthographic},{"../core/core.intersections":103,"../core/core.validators":107,three:81}],99:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _controls=require("./controls.trackball");var _controls2=_interopRequireDefault(_controls);var _controls3=require("./controls.trackballortho");var _controls4=_interopRequireDefault(_controls3);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Trackball:_controls2.default,TrackballOrtho:_controls4.default}},{"./controls.trackball":100,"./controls.trackballortho":101}],100:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Trackball=function(_EventDispatcher){_inherits(Trackball,_EventDispatcher);function Trackball(object,domElement){_classCallCheck(this,Trackball);var _this2=_possibleConstructorReturn(this,(Trackball.__proto__||Object.getPrototypeOf(Trackball)).call(this));var _this=_this2;var STATE={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM:4,TOUCH_PAN:5,CUSTOM:99};_this2.object=object;_this2.domElement=domElement!==undefined?domElement:document;_this2.enabled=true;_this2.screen={left:0,top:0,width:0,height:0};_this2.rotateSpeed=1;_this2.zoomSpeed=1.2;_this2.panSpeed=.3;_this2.noRotate=false;_this2.noZoom=false;_this2.noPan=false;_this2.noCustom=false;_this2.forceState=-1;_this2.staticMoving=false;_this2.dynamicDampingFactor=.2;_this2.minDistance=0;_this2.maxDistance=Infinity;_this2.keys=[65,83,68];_this2.target=new _three.Vector3;var EPS=1e-6;var lastPosition=new _three.Vector3;var _state=STATE.NONE,_prevState=STATE.NONE,_eye=new _three.Vector3,_movePrev=new _three.Vector2,_moveCurr=new _three.Vector2,_lastAxis=new _three.Vector3,_lastAngle=0,_zoomStart=new _three.Vector2,_zoomEnd=new _three.Vector2,_touchZoomDistanceStart=0,_touchZoomDistanceEnd=0,_panStart=new _three.Vector2,_panEnd=new _three.Vector2,_customStart=new _three.Vector2,_customEnd=new _three.Vector2;_this2.target0=_this2.target.clone();_this2.position0=_this2.object.position.clone();_this2.up0=_this2.object.up.clone();var changeEvent={type:"change"};var startEvent={type:"start"};var endEvent={type:"end"};_this2.handleResize=function(){if(this.domElement===document){this.screen.left=0;this.screen.top=0;this.screen.width=window.innerWidth;this.screen.height=window.innerHeight}else{var box=this.domElement.getBoundingClientRect();var d=this.domElement.ownerDocument.documentElement;this.screen.left=box.left+window.pageXOffset-d.clientLeft;this.screen.top=box.top+window.pageYOffset-d.clientTop;this.screen.width=box.width;this.screen.height=box.height}};_this2.handleEvent=function(event){if(typeof this[event.type]=="function"){this[event.type](event)}};var getMouseOnScreen=function(){var vector=new _three.Vector2;return function(pageX,pageY){vector.set((pageX-_this.screen.left)/_this.screen.width,(pageY-_this.screen.top)/_this.screen.height);return vector}}();var getMouseOnCircle=function(){var vector=new _three.Vector2;return function(pageX,pageY){vector.set((pageX-_this.screen.width*.5-_this.screen.left)/(_this.screen.width*.5),(_this.screen.height+2*(_this.screen.top-pageY))/_this.screen.width);return vector}}();_this2.rotateCamera=function(){var axis=new _three.Vector3,quaternion=new _three.Quaternion,eyeDirection=new _three.Vector3,objectUpDirection=new _three.Vector3,objectSidewaysDirection=new _three.Vector3,moveDirection=new _three.Vector3,angle=void 0;return function(){moveDirection.set(_moveCurr.x-_movePrev.x,_moveCurr.y-_movePrev.y,0);angle=moveDirection.length();if(angle){_eye.copy(_this.object.position).sub(_this.target);eyeDirection.copy(_eye).normalize();objectUpDirection.copy(_this.object.up).normalize();objectSidewaysDirection.crossVectors(objectUpDirection,eyeDirection).normalize();objectUpDirection.setLength(_moveCurr.y-_movePrev.y);objectSidewaysDirection.setLength(_moveCurr.x-_movePrev.x);moveDirection.copy(objectUpDirection.add(objectSidewaysDirection));axis.crossVectors(moveDirection,_eye).normalize();angle*=_this.rotateSpeed;quaternion.setFromAxisAngle(axis,angle);_eye.applyQuaternion(quaternion);_this.object.up.applyQuaternion(quaternion);_lastAxis.copy(axis);_lastAngle=angle}else if(!_this.staticMoving&&_lastAngle){_lastAngle*=Math.sqrt(1-_this.dynamicDampingFactor);_eye.copy(_this.object.position).sub(_this.target);quaternion.setFromAxisAngle(_lastAxis,_lastAngle);_eye.applyQuaternion(quaternion);_this.object.up.applyQuaternion(quaternion)}_movePrev.copy(_moveCurr)}}();_this2.zoomCamera=function(){var factor=void 0;if(_state===STATE.TOUCH_ZOOM){factor=_touchZoomDistanceStart/_touchZoomDistanceEnd;_touchZoomDistanceStart=_touchZoomDistanceEnd;_eye.multiplyScalar(factor)}else{factor=1+(_zoomEnd.y-_zoomStart.y)*_this.zoomSpeed;if(factor!==1&&factor>0){_eye.multiplyScalar(factor);if(_this.staticMoving){_zoomStart.copy(_zoomEnd)}else{_zoomStart.y+=(_zoomEnd.y-_zoomStart.y)*this.dynamicDampingFactor}}}};_this2.panCamera=function(){var mouseChange=new _three.Vector2,objectUp=new _three.Vector3,pan=new _three.Vector3;return function(){mouseChange.copy(_panEnd).sub(_panStart);if(mouseChange.lengthSq()){mouseChange.multiplyScalar(_eye.length()*_this.panSpeed);pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x);pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y));_this.object.position.add(pan);_this.target.add(pan);if(_this.staticMoving){_panStart.copy(_panEnd)}else{_panStart.add(mouseChange.subVectors(_panEnd,_panStart).multiplyScalar(_this.dynamicDampingFactor))}}}}();_this2.checkDistances=function(){if(!_this.noZoom||!_this.noPan){if(_eye.lengthSq()>_this.maxDistance*_this.maxDistance){_this.object.position.addVectors(_this.target,_eye.setLength(_this.maxDistance))}if(_eye.lengthSq()<_this.minDistance*_this.minDistance){_this.object.position.addVectors(_this.target,_eye.setLength(_this.minDistance))}}};_this2.update=function(){_eye.subVectors(_this.object.position,_this.target);if(!_this.noRotate){_this.rotateCamera()}if(!_this.noZoom){_this.zoomCamera()}if(!_this.noPan){_this.panCamera()}if(!_this.noCustom){_this.custom(_customStart,_customEnd)}_this.object.position.addVectors(_this.target,_eye);_this.checkDistances();_this.object.lookAt(_this.target);if(lastPosition.distanceToSquared(_this.object.position)>EPS){_this.dispatchEvent(changeEvent);lastPosition.copy(_this.object.position)}};_this2.reset=function(){_state=STATE.NONE;_prevState=STATE.NONE;_this.target.copy(_this.target0);_this.object.position.copy(_this.position0);_this.object.up.copy(_this.up0);_eye.subVectors(_this.object.position,_this.target);_this.object.lookAt(_this.target);_this.dispatchEvent(changeEvent);lastPosition.copy(_this.object.position)};_this2.setState=function(targetState){_this.forceState=targetState;_prevState=targetState;_state=targetState};_this2.custom=function(customStart,customEnd){};function keydown(event){if(_this.enabled===false)return;window.removeEventListener("keydown",keydown);_prevState=_state;if(_state!==STATE.NONE){return}else if(event.keyCode===_this.keys[STATE.ROTATE]&&!_this.noRotate){_state=STATE.ROTATE}else if(event.keyCode===_this.keys[STATE.ZOOM]&&!_this.noZoom){_state=STATE.ZOOM}else if(event.keyCode===_this.keys[STATE.PAN]&&!_this.noPan){_state=STATE.PAN}}function keyup(event){if(_this.enabled===false)return;_state=_prevState;window.addEventListener("keydown",keydown,false)}function mousedown(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.NONE){_state=event.button}if(_state===STATE.ROTATE&&!_this.noRotate){_moveCurr.copy(getMouseOnCircle(event.pageX,event.pageY));_movePrev.copy(_moveCurr)}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomStart.copy(getMouseOnScreen(event.pageX,event.pageY));_zoomEnd.copy(_zoomStart)}else if(_state===STATE.PAN&&!_this.noPan){_panStart.copy(getMouseOnScreen(event.pageX,event.pageY));_panEnd.copy(_panStart)}else if(_state===STATE.CUSTOM&&!_this.noCustom){_customStart.copy(getMouseOnScreen(event.pageX,event.pageY));_customEnd.copy(_panStart)}document.addEventListener("mousemove",mousemove,false);document.addEventListener("mouseup",mouseup,false);_this.dispatchEvent(startEvent)}function mousemove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.ROTATE&&!_this.noRotate){_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.pageX,event.pageY))}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomEnd.copy(getMouseOnScreen(event.pageX,event.pageY))}else if(_state===STATE.PAN&&!_this.noPan){_panEnd.copy(getMouseOnScreen(event.pageX,event.pageY))}else if(_state===STATE.CUSTOM&&!_this.noCustom){_customEnd.copy(getMouseOnScreen(event.pageX,event.pageY))}}function mouseup(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_this.forceState===-1){_state=STATE.NONE}document.removeEventListener("mousemove",mousemove);document.removeEventListener("mouseup",mouseup);_this.dispatchEvent(endEvent)}function mousewheel(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();var delta=0;if(event.wheelDelta){delta=event.wheelDelta/40}else if(event.detail){delta=-event.detail/3}if(_state!==STATE.CUSTOM){_zoomStart.y+=delta*.01}else if(_state===STATE.CUSTOM){_customStart.y+=delta*.01}_this.dispatchEvent(startEvent);_this.dispatchEvent(endEvent)}function touchstart(event){if(_this.enabled===false)return;if(_this.forceState===-1){switch(event.touches.length){case 1:_state=STATE.TOUCH_ROTATE;_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));_movePrev.copy(_moveCurr);break;case 2:_state=STATE.TOUCH_ZOOM;var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=_touchZoomDistanceStart=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panStart.copy(getMouseOnScreen(x,y));_panEnd.copy(_panStart);break;default:_state=STATE.NONE}}else{switch(_state){case 0:_state=STATE.TOUCH_ROTATE;_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));_movePrev.copy(_moveCurr);break;case 1:case 4:if(event.touches.length>=2){_state=STATE.TOUCH_ZOOM;var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=_touchZoomDistanceStart=Math.sqrt(dx*dx+dy*dy)}else{_state=STATE.ZOOM;_zoomStart.copy(getMouseOnScreen(event.touches[0].pageX,event.touches[0].pageY));_zoomEnd.copy(_zoomStart)}break;case 2:case 5:if(event.touches.length>=2){_state=STATE.TOUCH_PAN;var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panStart.copy(getMouseOnScreen(x,y));_panEnd.copy(_panStart)}else{_state=STATE.PAN;_panStart.copy(getMouseOnScreen(event.touches[0].pageX,event.touches[0].pageY));_panEnd.copy(_panStart)}break;case 99:_state=STATE.CUSTOM;var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_customStart.copy(getMouseOnScreen(x,y));_customEnd.copy(_customStart);break;default:_state=STATE.NONE}}_this.dispatchEvent(startEvent)}function touchmove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_this.forceState===-1){switch(event.touches.length){case 1:_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));break;case 2:var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));break;default:_state=STATE.NONE}}else{switch(_state){case 0:_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));break;case 1:_zoomEnd.copy(getMouseOnScreen(event.touches[0].pageX,event.touches[0].pageY));break;case 2:_panEnd.copy(getMouseOnScreen(event.touches[0].pageX,event.touches[0].pageY));break;case 4:var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=Math.sqrt(dx*dx+dy*dy);break;case 5:var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));break;case 99:var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_customEnd.copy(getMouseOnScreen(x,y));break;default:_state=STATE.NONE}}}function touchend(event){if(_this.enabled===false)return;if(_this.forceState===-1){switch(event.touches.length){case 1:_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));break;case 2:_touchZoomDistanceStart=_touchZoomDistanceEnd=0;var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));_panStart.copy(_panEnd);break}_state=STATE.NONE}else{switch(_state){case 0:_movePrev.copy(_moveCurr);_moveCurr.copy(getMouseOnCircle(event.touches[0].pageX,event.touches[0].pageY));break;case 1:case 2:break;case 4:_touchZoomDistanceStart=_touchZoomDistanceEnd=0;_state=STATE.ZOOM;break;case 5:if(event.touches.length>=2){var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));_panStart.copy(_panEnd)}_state=STATE.PAN;break;case 99:var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_customEnd.copy(getMouseOnScreen(x,y));_customStart.copy(_customEnd);break;default:_state=STATE.NONE}}_this.dispatchEvent(endEvent)}_this2.domElement.addEventListener("contextmenu",function(event){event.preventDefault()},false);_this2.domElement.addEventListener("mousedown",mousedown,false);_this2.domElement.addEventListener("mousewheel",mousewheel,false);_this2.domElement.addEventListener("DOMMouseScroll",mousewheel,false);_this2.domElement.addEventListener("touchstart",touchstart,false);_this2.domElement.addEventListener("touchend",touchend,false);_this2.domElement.addEventListener("touchmove",touchmove,false);window.addEventListener("keydown",keydown,false);window.addEventListener("keyup",keyup,false);_this2.handleResize();_this2.update();return _this2}return Trackball}(_three.EventDispatcher);exports.default=Trackball},{three:81}],101:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Trackballortho=function(_EventDispatcher){_inherits(Trackballortho,_EventDispatcher);function Trackballortho(object,domElement){var state=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{NONE:-1,ROTATE:1,ZOOM:2,PAN:0,SCROLL:4,TOUCH_ROTATE:4,TOUCH_ZOOM_PAN:5};_classCallCheck(this,Trackballortho);var _this2=_possibleConstructorReturn(this,(Trackballortho.__proto__||Object.getPrototypeOf(Trackballortho)).call(this));var _this=_this2;var STATE=state;_this2.object=object;_this2.domElement=domElement!==undefined?domElement:document;_this2.enabled=true;_this2.screen={left:0,top:0,width:0,height:0};_this2.radius=0;_this2.zoomSpeed=1.2;_this2.noZoom=false;_this2.noPan=false;_this2.staticMoving=false;_this2.dynamicDampingFactor=.2;_this2.keys=[65,83,68];_this2.target=new _three.Vector3;var EPS=1e-6;var _changed=true;var _state=STATE.NONE,_prevState=STATE.NONE,_eye=new _three.Vector3,_zoomStart=new _three.Vector2,_zoomEnd=new _three.Vector2,_touchZoomDistanceStart=0,_touchZoomDistanceEnd=0,_panStart=new _three.Vector2,_panEnd=new _three.Vector2;_this2.target0=_this2.target.clone();_this2.position0=_this2.object.position.clone();_this2.up0=_this2.object.up.clone();_this2.left0=_this2.object.left;_this2.right0=_this2.object.right;_this2.top0=_this2.object.top;_this2.bottom0=_this2.object.bottom;var changeEvent={type:"change"};var startEvent={type:"start"};var endEvent={type:"end"};_this2.handleResize=function(){if(this.domElement===document){this.screen.left=0;this.screen.top=0;this.screen.width=window.innerWidth;this.screen.height=window.innerHeight}else{var box=this.domElement.getBoundingClientRect();var d=this.domElement.ownerDocument.documentElement;this.screen.left=box.left+window.pageXOffset-d.clientLeft;this.screen.top=box.top+window.pageYOffset-d.clientTop;this.screen.width=box.width;this.screen.height=box.height}this.radius=.5*Math.min(this.screen.width,this.screen.height);this.left0=this.object.left;this.right0=this.object.right;this.top0=this.object.top;this.bottom0=this.object.bottom};_this2.handleEvent=function(event){if(typeof this[event.type]=="function"){this[event.type](event)}};var getMouseOnScreen=function(){var vector=new _three.Vector2;return function getMouseOnScreen(pageX,pageY){vector.set((pageX-_this.screen.left)/_this.screen.width,(pageY-_this.screen.top)/_this.screen.height);return vector}}();_this2.zoomCamera=function(){if(_state===STATE.TOUCH_ZOOM_PAN){var factor=_touchZoomDistanceEnd/_touchZoomDistanceStart;_touchZoomDistanceStart=_touchZoomDistanceEnd;_this.object.zoom*=factor;_changed=true}else{var factor=1+(_zoomEnd.y-_zoomStart.y)*_this.zoomSpeed;if(Math.abs(factor-1)>EPS&&factor>0){_this.object.zoom/=factor;if(_this.staticMoving){_zoomStart.copy(_zoomEnd)}else{_zoomStart.y+=(_zoomEnd.y-_zoomStart.y)*this.dynamicDampingFactor}_changed=true}}};_this2.panCamera=function(){var mouseChange=new _three.Vector2,objectUp=new _three.Vector3,pan=new _three.Vector3;return function panCamera(){mouseChange.copy(_panEnd).sub(_panStart);if(mouseChange.lengthSq()){var scale_x=(_this.object.right-_this.object.left)/_this.object.zoom;var scale_y=(_this.object.top-_this.object.bottom)/_this.object.zoom;mouseChange.x*=scale_x;mouseChange.y*=scale_y;pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x);pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y));_this.object.position.add(pan);_this.target.add(pan);if(_this.staticMoving){_panStart.copy(_panEnd)}else{_panStart.add(mouseChange.subVectors(_panEnd,_panStart).multiplyScalar(_this.dynamicDampingFactor))}_changed=true}}}();_this2.update=function(){_eye.subVectors(_this.object.position,_this.target);if(!_this.noZoom){_this.zoomCamera();if(_changed){_this.object.updateProjectionMatrix()}}if(!_this.noPan){_this.panCamera()}_this.object.position.addVectors(_this.target,_eye);_this.object.lookAt(_this.target);if(_changed){_this.dispatchEvent(changeEvent);_changed=false}};_this2.reset=function(){_state=STATE.NONE;_prevState=STATE.NONE;_this.target.copy(_this.target0);_this.object.position.copy(_this.position0);_this.object.up.copy(_this.up0);_eye.subVectors(_this.object.position,_this.target);_this.object.left=_this.left0;_this.object.right=_this.right0;_this.object.top=_this.top0;_this.object.bottom=_this.bottom0;_this.object.lookAt(_this.target);_this.dispatchEvent(changeEvent);_changed=false};function keydown(event){if(_this.enabled===false)return;window.removeEventListener("keydown",keydown);_prevState=_state;if(_state!==STATE.NONE){return}else if(event.keyCode===_this.keys[STATE.ROTATE]&&!_this.noRotate){_state=STATE.ROTATE}else if(event.keyCode===_this.keys[STATE.ZOOM]&&!_this.noZoom){_state=STATE.ZOOM}else if(event.keyCode===_this.keys[STATE.PAN]&&!_this.noPan){_state=STATE.PAN}}function keyup(event){if(_this.enabled===false)return;_state=_prevState;window.addEventListener("keydown",keydown,false)}function mousedown(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.NONE){_state=event.button}if(_state===STATE.ROTATE&&!_this.noRotate){}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomStart.copy(getMouseOnScreen(event.pageX,event.pageY));_zoomEnd.copy(_zoomStart)}else if(_state===STATE.PAN&&!_this.noPan){_panStart.copy(getMouseOnScreen(event.pageX,event.pageY));_panEnd.copy(_panStart)}document.addEventListener("mousemove",mousemove,false);document.addEventListener("mouseup",mouseup,false);_this.dispatchEvent(startEvent)}function mousemove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();if(_state===STATE.ROTATE&&!_this.noRotate){}else if(_state===STATE.ZOOM&&!_this.noZoom){_zoomEnd.copy(getMouseOnScreen(event.pageX,event.pageY))}else if(_state===STATE.PAN&&!_this.noPan){_panEnd.copy(getMouseOnScreen(event.pageX,event.pageY))}}function mouseup(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();_state=STATE.NONE;document.removeEventListener("mousemove",mousemove);document.removeEventListener("mouseup",mouseup);_this.dispatchEvent(endEvent)}function mousewheel(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();var delta=0;if(event.wheelDelta){delta=event.wheelDelta/40}else if(event.detail){delta=-event.detail/3}_this.dispatchEvent({type:"OnScroll",delta:delta});_this.dispatchEvent(startEvent);_this.dispatchEvent(endEvent)}function touchstart(event){if(_this.enabled===false)return;switch(event.touches.length){case 1:_state=STATE.TOUCH_ROTATE;break;case 2:_state=STATE.TOUCH_ZOOM_PAN;var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=_touchZoomDistanceStart=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2
var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panStart.copy(getMouseOnScreen(x,y));_panEnd.copy(_panStart);break;default
_state=STATE.NONE}_this.dispatchEvent(startEvent)}function touchmove(event){if(_this.enabled===false)return;event.preventDefault();event.stopPropagation();switch(event.touches.length){case 1:break;case 2:var dx=event.touches[0].pageX-event.touches[1].pageX;var dy=event.touches[0].pageY-event.touches[1].pageY;_touchZoomDistanceEnd=Math.sqrt(dx*dx+dy*dy);var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));break;default:_state=STATE.NONE}}function touchend(event){if(_this.enabled===false)return;switch(event.touches.length){case 1:break;case 2:_touchZoomDistanceStart=_touchZoomDistanceEnd=0;var x=(event.touches[0].pageX+event.touches[1].pageX)/2;var y=(event.touches[0].pageY+event.touches[1].pageY)/2;_panEnd.copy(getMouseOnScreen(x,y));_panStart.copy(_panEnd);break}_state=STATE.NONE;_this.dispatchEvent(endEvent)}function contextmenu(event){event.preventDefault()}_this2.dispose=function(){this.domElement.removeEventListener("contextmenu",contextmenu,false);this.domElement.removeEventListener("mousedown",mousedown,false);this.domElement.removeEventListener("mousewheel",mousewheel,false);this.domElement.removeEventListener("MozMousePixelScroll",mousewheel,false);this.domElement.removeEventListener("touchstart",touchstart,false);this.domElement.removeEventListener("touchend",touchend,false);this.domElement.removeEventListener("touchmove",touchmove,false);document.removeEventListener("mousemove",mousemove,false);document.removeEventListener("mouseup",mouseup,false);window.removeEventListener("keydown",keydown,false);window.removeEventListener("keyup",keyup,false)};_this2.domElement.addEventListener("contextmenu",contextmenu,false);_this2.domElement.addEventListener("mousedown",mousedown,false);_this2.domElement.addEventListener("mousewheel",mousewheel,false);_this2.domElement.addEventListener("MozMousePixelScroll",mousewheel,false);_this2.domElement.addEventListener("touchstart",touchstart,false);_this2.domElement.addEventListener("touchend",touchend,false);_this2.domElement.addEventListener("touchmove",touchmove,false);window.addEventListener("keydown",keydown,false);window.addEventListener("keyup",keyup,false);_this2.handleResize();_this2.update();return _this2}return Trackballortho}(_three.EventDispatcher);exports.default=Trackballortho},{three:81}],102:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i]}return arr2}else{return Array.from(arr)}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Colors=function(){function Colors(){_classCallCheck(this,Colors)}_createClass(Colors,null,[{key:"cielab2XYZ",value:function cielab2XYZ(l,a,b){var refX=95.047;var refY=100;var refZ=108.883;var y=(l+16)/116;var x=a/500+y;var z=y-b/200;if(Math.pow(y,3)>.008856){y=Math.pow(y,3)}else{y=(y-16/116)/7.787}if(Math.pow(x,3)>.008856){x=Math.pow(x,3)}else{x=(x-16/116)/7.787}if(Math.pow(z,3)>.008856){z=Math.pow(z,3)}else{z=(z-16/116)/7.787}return[refX*x,refY*y,refZ*z]}},{key:"xyz2RGB",value:function xyz2RGB(x,y,z){x/=100;y/=100;z/=100;var r=x*3.2406+y*-1.5372+z*-.4986;var g=x*-.9689+y*1.8758+z*.0415;var b=x*.0557+y*-.204+z*1.057;if(r>.0031308){r=1.055*Math.pow(r,1/2.4)-.055}else{r=12.92*r}if(g>.0031308){g=1.055*Math.pow(g,1/2.4)-.055}else{g=12.92*g}if(b>.0031308){b=1.055*Math.pow(b,1/2.4)-.055}else{b=12.92*b}r=r*255;g=g*255;b=b*255;return[r,g,b]}},{key:"cielab2RGB",value:function cielab2RGB(){var l=arguments.length>0&&arguments[0]!==undefined?arguments[0]:50;var a=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var b=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;if(!(l>=0&&l<=100)){return null}var xyz=this.cielab2XYZ(l,a,b);return this.xyz2RGB.apply(this,_toConsumableArray(xyz))}}]);return Colors}();exports.default=Colors},{}],103:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("./core.utils");var _core2=_interopRequireDefault(_core);var _core3=require("./core.validators");var _core4=_interopRequireDefault(_core3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Intersections=function(){function Intersections(){_classCallCheck(this,Intersections)}_createClass(Intersections,null,[{key:"aabbPlane",value:function aabbPlane(aabb,plane){var intersections=[];if(!(this.validateAabb(aabb)&&this.validatePlane(plane))){window.console.log("Invalid aabb or plane provided.");return false}var fromAABB=new _three.Matrix4;fromAABB.getInverse(aabb.toAABB);var t1=plane.direction.clone().applyMatrix4(aabb.toAABB);var t0=new _three.Vector3(0,0,0).applyMatrix4(aabb.toAABB);var planeAABB=this.posdir(plane.position.clone().applyMatrix4(aabb.toAABB),new _three.Vector3(t1.x-t0.x,t1.y-t0.y,t1.z-t0.z).normalize());var bbox=_core2.default.bbox(aabb.center,aabb.halfDimensions);var orientation=new _three.Vector3(new _three.Vector3(1,0,0),new _three.Vector3(0,1,0),new _three.Vector3(0,0,1));var ray=this.posdir(new _three.Vector3(aabb.center.x-aabb.halfDimensions.x,aabb.center.y-aabb.halfDimensions.y,aabb.center.z-aabb.halfDimensions.z),orientation.x);this.rayPlaneInBBox(ray,planeAABB,bbox,intersections);ray.direction=orientation.y;this.rayPlaneInBBox(ray,planeAABB,bbox,intersections);ray.direction=orientation.z;this.rayPlaneInBBox(ray,planeAABB,bbox,intersections);var ray2=this.posdir(new _three.Vector3(aabb.center.x+aabb.halfDimensions.x,aabb.center.y+aabb.halfDimensions.y,aabb.center.z+aabb.halfDimensions.z),orientation.x);this.rayPlaneInBBox(ray2,planeAABB,bbox,intersections);ray2.direction=orientation.y;this.rayPlaneInBBox(ray2,planeAABB,bbox,intersections);ray2.direction=orientation.z;this.rayPlaneInBBox(ray2,planeAABB,bbox,intersections);var ray3=this.posdir(new _three.Vector3(aabb.center.x+aabb.halfDimensions.x,aabb.center.y-aabb.halfDimensions.y,aabb.center.z-aabb.halfDimensions.z),orientation.y);this.rayPlaneInBBox(ray3,planeAABB,bbox,intersections);ray3.direction=orientation.z;this.rayPlaneInBBox(ray3,planeAABB,bbox,intersections);var ray4=this.posdir(new _three.Vector3(aabb.center.x-aabb.halfDimensions.x,aabb.center.y+aabb.halfDimensions.y,aabb.center.z-aabb.halfDimensions.z),orientation.x);this.rayPlaneInBBox(ray4,planeAABB,bbox,intersections);ray4.direction=orientation.z;this.rayPlaneInBBox(ray4,planeAABB,bbox,intersections);var ray5=this.posdir(new _three.Vector3(aabb.center.x-aabb.halfDimensions.x,aabb.center.y-aabb.halfDimensions.y,aabb.center.z+aabb.halfDimensions.z),orientation.x);this.rayPlaneInBBox(ray5,planeAABB,bbox,intersections);ray5.direction=orientation.y;this.rayPlaneInBBox(ray5,planeAABB,bbox,intersections);intersections.map(function(element){return element.applyMatrix4(fromAABB)});return intersections}},{key:"rayPlane",value:function rayPlane(ray,plane){if(ray.direction.dot(plane.direction)!==0){var t=(plane.direction.x*(plane.position.x-ray.position.x)+plane.direction.y*(plane.position.y-ray.position.y)+plane.direction.z*(plane.position.z-ray.position.z))/(plane.direction.x*ray.direction.x+plane.direction.y*ray.direction.y+plane.direction.z*ray.direction.z);var intersection=new _three.Vector3(ray.position.x+t*ray.direction.x,ray.position.y+t*ray.direction.y,ray.position.z+t*ray.direction.z);return intersection}return null}},{key:"rayBox",value:function rayBox(ray,box){var intersections=[];var bbox=_core2.default.bbox(box.center,box.halfDimensions);var plane=this.posdir(new _three.Vector3(bbox.min.x,box.center.y,box.center.z),new _three.Vector3(-1,0,0));this.rayPlaneInBBox(ray,plane,bbox,intersections);plane=this.posdir(new _three.Vector3(bbox.max.x,box.center.y,box.center.z),new _three.Vector3(1,0,0));this.rayPlaneInBBox(ray,plane,bbox,intersections);plane=this.posdir(new _three.Vector3(box.center.x,bbox.min.y,box.center.z),new _three.Vector3(0,-1,0));this.rayPlaneInBBox(ray,plane,bbox,intersections);plane=this.posdir(new _three.Vector3(box.center.x,bbox.max.y,box.center.z),new _three.Vector3(0,1,0));this.rayPlaneInBBox(ray,plane,bbox,intersections);plane=this.posdir(new _three.Vector3(box.center.x,box.center.y,bbox.min.z),new _three.Vector3(0,0,-1));this.rayPlaneInBBox(ray,plane,bbox,intersections);plane=this.posdir(new _three.Vector3(box.center.x,box.center.y,bbox.max.z),new _three.Vector3(0,0,1));this.rayPlaneInBBox(ray,plane,bbox,intersections);return intersections}},{key:"rayPlaneInBBox",value:function rayPlaneInBBox(ray,planeAABB,bbox,intersections){var intersection=this.rayPlane(ray,planeAABB);if(intersection&&this.inBBox(intersection,bbox)){if(!intersections.find(this.findIntersection(intersection))){intersections.push(intersection)}}}},{key:"findIntersection",value:function findIntersection(myintersection){return function found(element,index,array){if(myintersection.x===element.x&&myintersection.y===element.y&&myintersection.z===element.z){return true}return false}}},{key:"inBBox",value:function inBBox(point,bbox){var epsilon=1e-4;if(point&&point.x>=bbox.min.x-epsilon&&point.y>=bbox.min.y-epsilon&&point.z>=bbox.min.z-epsilon&&point.x<=bbox.max.x+epsilon&&point.y<=bbox.max.y+epsilon&&point.z<=bbox.max.z+epsilon){return true}return false}},{key:"posdir",value:function posdir(position,direction){return{position:position,direction:direction}}},{key:"validatePlane",value:function validatePlane(plane){if(plane===null){window.console.log("Invalid plane.");window.console.log(plane);return false}if(!_core4.default.vector3(plane.position)){window.console.log("Invalid plane.position.");window.console.log(plane.position);return false}if(!_core4.default.vector3(plane.direction)){window.console.log("Invalid plane.direction.");window.console.log(plane.direction);return false}return true}},{key:"validateAabb",value:function validateAabb(aabb){if(aabb===null){window.console.log("Invalid aabb.");window.console.log(aabb);return false}if(!_core4.default.matrix4(aabb.toAABB)){window.console.log("Invalid aabb.toAABB: ");window.console.log(aabb.toAABB);return false}if(!_core4.default.vector3(aabb.center)){window.console.log("Invalid aabb.center.");window.console.log(aabb.center);return false}if(!(_core4.default.vector3(aabb.halfDimensions)&&aabb.halfDimensions.x>=0&&aabb.halfDimensions.y>=0&&aabb.halfDimensions.z>=0)){window.console.log("Invalid aabb.halfDimensions.");window.console.log(aabb.halfDimensions);return false}return true}}]);return Intersections}();exports.default=Intersections},{"./core.utils":106,"./core.validators":107,three:81}],104:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _core=require("./core.colors");var _core2=_interopRequireDefault(_core);var _core3=require("./core.intersections");var _core4=_interopRequireDefault(_core3);var _core5=require("./core.pack");var _core6=_interopRequireDefault(_core5);var _core7=require("./core.validators");var _core8=_interopRequireDefault(_core7);var _core9=require("./core.utils");var _core10=_interopRequireDefault(_core9);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Colors:_core2.default,Intersections:_core4.default,Utils:_core10.default,Validators:_core8.default}},{"./core.colors":102,"./core.intersections":103,"./core.pack":105,"./core.utils":106,"./core.validators":107}],105:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Pack=function Pack(){_classCallCheck(this,Pack)};exports.default=Pack},{}],106:[function(require,module,exports){"use strict";var _typeof2=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj)}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj)};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("./core.validators");var _core2=_interopRequireDefault(_core);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var URL=require("url");var CoreUtils=function(){function CoreUtils(){_classCallCheck(this,CoreUtils)}_createClass(CoreUtils,null,[{key:"bbox",value:function bbox(center,halfDimensions){if(!(_core2.default.vector3(center)&&_core2.default.vector3(halfDimensions))){window.console.log("Invalid center or plane halfDimensions.");return false}if(!(halfDimensions.x>=0&&halfDimensions.y>=0&&halfDimensions.z>=0)){window.console.log("halfDimensions must be >= 0.");window.console.log(halfDimensions);return false}var min=center.clone().sub(halfDimensions);var max=center.clone().add(halfDimensions);return{min:min,max:max}}},{key:"minMax",value:function minMax(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var minMax=[65535,-32768];var numPixels=data.length;for(var index=0;index<numPixels;index++){var spv=data[index];minMax[0]=Math.min(minMax[0],spv);minMax[1]=Math.max(minMax[1],spv)}return minMax}},{key:"isElement",value:function isElement(obj){try{return obj instanceof HTMLElement}catch(e){return(typeof obj==="undefined"?"undefined":_typeof(obj))==="object"&&obj.nodeType===1&&_typeof(obj.style)==="object"&&_typeof(obj.ownerDocument)==="object"}}},{key:"isString",value:function isString(str){return typeof str==="string"||str instanceof String}},{key:"parseUrl",value:function parseUrl(url){var data={};data.filename="";data.extension="";data.pathname="";data.query="";var parsedUrl=URL.parse(url);data.pathname=parsedUrl.pathname;data.query=parsedUrl.query;if(data.query){data.filename=data.query.split("&").reduce(function(acc,fieldval){var fvPair=fieldval.split("=");if(fvPair.length>0&&fvPair[0]=="filename"){acc=fvPair[1]}return acc})}if(!data.filename){data.filename=data.pathname.split("/").pop()}var splittedName=data.filename.split(".");if(splittedName.length<=1){data.extension="dicom"}else{data.extension=data.filename.split(".").pop()}if(!isNaN(data.extension)){data.extension="dicom"}if(data.query&&data.query.includes("contentType=application%2Fdicom")){data.extension="dicom"}return data}},{key:"ijk2LPS",value:function ijk2LPS(xCos,yCos,zCos,spacing,origin){var registrationMatrix=arguments.length>5&&arguments[5]!==undefined?arguments[5]:new _three.Matrix4;var ijk2LPS=new _three.Matrix4;ijk2LPS.set(xCos.x*spacing.y,yCos.x*spacing.x,zCos.x*spacing.z,origin.x,xCos.y*spacing.y,yCos.y*spacing.x,zCos.y*spacing.z,origin.y,xCos.z*spacing.y,yCos.z*spacing.x,zCos.z*spacing.z,origin.z,0,0,0,1);ijk2LPS.premultiply(registrationMatrix);return ijk2LPS}},{key:"aabb2LPS",value:function aabb2LPS(xCos,yCos,zCos,origin){var aabb2LPS=new _three.Matrix4;aabb2LPS.set(xCos.x,yCos.x,zCos.x,origin.x,xCos.y,yCos.y,zCos.y,origin.y,xCos.z,yCos.z,zCos.z,origin.z,0,0,0,1);return aabb2LPS}},{key:"worldToData",value:function worldToData(lps2IJK,worldCoordinates){var dataCoordinate=(new _three.Vector3).copy(worldCoordinates).applyMatrix4(lps2IJK);dataCoordinate.addScalar(.5).floor();return dataCoordinate}},{key:"value",value:function value(stack,coordinate){console.warn("value is deprecated, please use getPixelData instead");this.getPixelData(stack,coordinate)}},{key:"getPixelData",value:function getPixelData(stack,coordinate){if(coordinate.z>=0&&coordinate.z<stack._frame.length){return stack._frame[coordinate.z].getPixelData(coordinate.x,coordinate.y)}else{return null}}},{key:"setPixelData",value:function setPixelData(stack,coordinate,value){if(coordinate.z>=0&&coordinate.z<stack._frame.length){stack._frame[coordinate.z].setPixelData(coordinate.x,coordinate.y,value)}else{return null}}},{key:"rescaleSlopeIntercept",value:function rescaleSlopeIntercept(value,slope,intercept){return value*slope+intercept}}]);return CoreUtils}();exports.default=CoreUtils},{"./core.validators":107,three:81,url:82}],107:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Validators=function(){function Validators(){_classCallCheck(this,Validators)}_createClass(Validators,null,[{key:"matrix4",value:function matrix4(objectToTest){if(!(objectToTest!==null&&typeof objectToTest!=="undefined"&&objectToTest.hasOwnProperty("elements")&&objectToTest.elements.length===16&&typeof objectToTest.identity==="function"&&typeof objectToTest.copy==="function"&&typeof objectToTest.determinant==="function")){return false}return true}},{key:"vector3",value:function vector3(objectToTest){if(!(objectToTest!==null&&typeof objectToTest!=="undefined"&&objectToTest.hasOwnProperty("x")&&objectToTest.hasOwnProperty("y")&&objectToTest.hasOwnProperty("z")&&!objectToTest.hasOwnProperty("w"))){return false}return true}},{key:"box",value:function box(objectToTest){if(!(objectToTest!==null&&typeof objectToTest!=="undefined"&&objectToTest.hasOwnProperty("center")&&this.vector3(objectToTest.center)&&objectToTest.hasOwnProperty("halfDimensions")&&this.vector3(objectToTest.halfDimensions)&&objectToTest.halfDimensions.x>=0&&objectToTest.halfDimensions.y>=0&&objectToTest.halfDimensions.z>=0)){return false}return true}},{key:"ray",value:function ray(objectToTest){if(!(objectToTest!==null&&typeof objectToTest!=="undefined"&&objectToTest.hasOwnProperty("position")&&this.vector3(objectToTest.position)&&objectToTest.hasOwnProperty("direction")&&this.vector3(objectToTest.direction))){return false}return true}}]);return Validators}();exports.default=Validators},{}],108:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _geometries=require("./geometries.slice");var _geometries2=_interopRequireDefault(_geometries);var _geometries3=require("./geometries.voxel");var _geometries4=_interopRequireDefault(_geometries3);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Slice:_geometries2.default,Voxel:_geometries4.default}},{"./geometries.slice":109,"./geometries.voxel":110}],109:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("../core/core.intersections");var _core2=_interopRequireDefault(_core);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var GeometriesSlice=function(_THREE$ShapeGeometry){_inherits(GeometriesSlice,_THREE$ShapeGeometry);function GeometriesSlice(halfDimensions,center,position,direction){var toAABB=arguments.length>4&&arguments[4]!==undefined?arguments[4]:new _three.Matrix4;_classCallCheck(this,GeometriesSlice);var aabb={halfDimensions:halfDimensions,center:center,toAABB:toAABB};var plane={position:position,direction:direction};var intersections=_core2.default.aabbPlane(aabb,plane);if(intersections.length<3){window.console.log("WARNING: Less than 3 intersections between AABB and Plane.");window.console.log("AABB");window.console.log(aabb);window.console.log("Plane");window.console.log(plane);window.console.log("exiting...");throw"geometries.slice has less than 3 intersections, can not create a valid geometry."}var orderedIntersections=GeometriesSlice.orderIntersections(intersections,direction);var sliceShape=GeometriesSlice.shape(orderedIntersections);var _this=_possibleConstructorReturn(this,(GeometriesSlice.__proto__||Object.getPrototypeOf(GeometriesSlice)).call(this,sliceShape));_this.type="SliceGeometry";_this.vertices=orderedIntersections;_this.verticesNeedUpdate=true;return _this}_createClass(GeometriesSlice,null,[{key:"shape",value:function shape(points){var shape=new THREE.Shape;shape.moveTo(points[0].xy.x,points[0].xy.y);for(var l=1;l<points.length;l++){shape.lineTo(points[l].xy.x,points[l].xy.y)}shape.lineTo(points[0].xy.x,points[0].xy.y);return shape}},{key:"centerOfMass",value:function centerOfMass(points){var centerOfMass=new _three.Vector3(0,0,0);for(var i=0;i<points.length;i++){centerOfMass.x+=points[i].x;centerOfMass.y+=points[i].y;centerOfMass.z+=points[i].z}centerOfMass.divideScalar(points.length);return centerOfMass}},{key:"orderIntersections",value:function orderIntersections(points,direction){var reference=GeometriesSlice.centerOfMass(points);var referenceDirection=new _three.Vector3(points[0].x-reference.x,points[0].y-reference.y,points[0].z-reference.z).normalize();var base=new _three.Vector3(0,0,0).crossVectors(referenceDirection,direction).normalize();var orderedpoints=[];for(var j=0;j<points.length;j++){var point=new _three.Vector3(points[j].x,points[j].y,points[j].z);point.direction=new _three.Vector3(points[j].x-reference.x,points[j].y-reference.y,points[j].z-reference.z).normalize();var x=referenceDirection.dot(point.direction);var y=base.dot(point.direction);point.xy={x:x,y:y};var theta=Math.atan2(y,x)*(180/Math.PI);point.angle=theta;orderedpoints.push(point)}orderedpoints.sort(function(a,b){return a.angle-b.angle});var noDups=[orderedpoints[0]];var epsilon=1e-4;for(var i=1;i<orderedpoints.length;i++){if(Math.abs(orderedpoints[i-1].angle-orderedpoints[i].angle)>epsilon){noDups.push(orderedpoints[i])}}return noDups}}]);return GeometriesSlice}(THREE.ShapeGeometry);exports.default=GeometriesSlice},{"../core/core.intersections":103,three:81}],110:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var GeometriesVoxel=function(_THREE$BoxGeometry){_inherits(GeometriesVoxel,_THREE$BoxGeometry);function GeometriesVoxel(dataPosition){_classCallCheck(this,GeometriesVoxel);var _this=_possibleConstructorReturn(this,(GeometriesVoxel.__proto__||Object.getPrototypeOf(GeometriesVoxel)).call(this,1,1,1));_this._location=dataPosition;_this.applyMatrix((new _three.Matrix4).makeTranslation(_this._location.x,_this._location.y,_this._location.z));_this.verticesNeedUpdate=true;return _this}_createClass(GeometriesVoxel,[{key:"resetVertices",value:function resetVertices(){this.vertices[0].set(.5,.5,.5);this.vertices[1].set(.5,.5,-.5);this.vertices[2].set(.5,-.5,.5);this.vertices[3].set(.5,-.5,-.5);this.vertices[4].set(-.5,.5,-.5);this.vertices[5].set(-.5,.5,.5);this.vertices[6].set(-.5,-.5,-.5);this.vertices[7].set(-.5,-.5,.5)}},{key:"location",set:function set(location){this._location=location;this.vertices[0].set(+.5,+.5,+.5);this.vertices[1].set(+.5,+.5,-.5);this.vertices[2].set(+.5,-.5,+.5);this.vertices[3].set(+.5,-.5,-.5);this.vertices[4].set(-.5,+.5,-.5);this.vertices[5].set(-.5,+.5,+.5);this.vertices[6].set(-.5,-.5,-.5);this.vertices[7].set(-.5,-.5,+.5);this.applyMatrix((new _three.Matrix4).makeTranslation(this._location.x,this._location.y,this._location.z));this.verticesNeedUpdate=true},get:function get(){return this._location}}]);return GeometriesVoxel}(THREE.BoxGeometry);exports.default=GeometriesVoxel},{three:81}],111:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersBorder=function(_THREE$Object3D){_inherits(HelpersBorder,_THREE$Object3D);function HelpersBorder(helpersSlice){_classCallCheck(this,HelpersBorder);var _this=_possibleConstructorReturn(this,(HelpersBorder.__proto__||Object.getPrototypeOf(HelpersBorder)).call(this));_this._helpersSlice=helpersSlice;_this._visible=true;_this._color=16711680;_this._material=null;_this._geometry=null;_this._mesh=null;_this._create();return _this}_createClass(HelpersBorder,[{key:"_create",value:function _create(){if(!this._material){this._material=new THREE.LineBasicMaterial({color:this._color,linewidth:1})}if(!this._helpersSlice.geometry.vertices){return}this._geometry=new THREE.Geometry;for(var i=0;i<this._helpersSlice.geometry.vertices.length;i++){this._geometry.vertices.push(this._helpersSlice.geometry.vertices[i])}this._geometry.vertices.push(this._helpersSlice.geometry.vertices[0]);this._mesh=new THREE.Line(this._geometry,this._material);if(this._helpersSlice.aabbSpace==="IJK"){this._mesh.applyMatrix(this._helpersSlice.stack.ijk2LPS)}
this._mesh.visible=this._visible;this.add(this._mesh)}},{key:"_update",value:function _update(){if(this._mesh){this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh=null}this._create()}},{key:"dispose",value:function dispose(){this._mesh.material.dispose();this._mesh.material=null;this._geometry.dispose();this._geometry=null;this._material.dispose();this._material=null}},{key:"helpersSlice",set:function set(helpersSlice){this._helpersSlice=helpersSlice;this._update()},get:function get(){return this._helpersSlice}},{key:"visible",set:function set(visible){this._visible=visible;if(this._mesh){this._mesh.visible=this._visible}},get:function get(){return this._visible}},{key:"color",set:function set(color){this._color=color;if(this._material){this._material.color.set(this._color)}},get:function get(){return this._color}}]);return HelpersBorder}(THREE.Object3D);exports.default=HelpersBorder},{}],112:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersBoundingBox=function(_THREE$Object3D){_inherits(HelpersBoundingBox,_THREE$Object3D);function HelpersBoundingBox(stack){_classCallCheck(this,HelpersBoundingBox);var _this=_possibleConstructorReturn(this,(HelpersBoundingBox.__proto__||Object.getPrototypeOf(HelpersBoundingBox)).call(this));_this._stack=stack;_this._visible=true;_this._color=16777215;_this._material=null;_this._geometry=null;_this._mesh=null;_this._meshStack=null;_this._create();return _this}_createClass(HelpersBoundingBox,[{key:"_create",value:function _create(){var dimensions=this._stack.dimensionsIJK;var halfDimensions=this._stack.halfDimensionsIJK;var offset=new _three.Vector3(-.5,-.5,-.5);var geometry=new THREE.BoxGeometry(dimensions.x,dimensions.y,dimensions.z);geometry.applyMatrix((new _three.Matrix4).makeTranslation(halfDimensions.x+offset.x,halfDimensions.y+offset.y,halfDimensions.z+offset.z));this._geometry=geometry;this._material=new THREE.MeshBasicMaterial({wireframe:true});var mesh=new THREE.Mesh(this._geometry,null);mesh.applyMatrix(this._stack.ijk2LPS);mesh.visible=this._visible;this._meshStack=mesh;this._mesh=new THREE.BoxHelper(this._meshStack,this._color);this._material=this._mesh.material;this.add(this._mesh)}},{key:"_update",value:function _update(){if(this._mesh){this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh.geometry=null;this._mesh.material.dispose();this._mesh.material=null;this._mesh=null}this._create()}},{key:"dispose",value:function dispose(){this._mesh.material.dispose();this._mesh.material=null;this._geometry.dispose();this._geometry=null;this._material.dispose();this._material=null}},{key:"visible",set:function set(visible){this._visible=visible;if(this._mesh){this._mesh.visible=this._visible}},get:function get(){return this._visible}},{key:"color",set:function set(color){this._color=color;if(this._material){this._material.color.set(this._color)}},get:function get(){return this._color}}]);return HelpersBoundingBox}(THREE.Object3D);exports.default=HelpersBoundingBox},{three:81}],113:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _helpers=require("./helpers.border");var _helpers2=_interopRequireDefault(_helpers);var _helpers3=require("./helpers.boundingbox");var _helpers4=_interopRequireDefault(_helpers3);var _helpers5=require("./helpers.localizer");var _helpers6=_interopRequireDefault(_helpers5);var _helpers7=require("./helpers.lut");var _helpers8=_interopRequireDefault(_helpers7);var _helpers9=require("./helpers.segmentationlut");var _helpers10=_interopRequireDefault(_helpers9);var _helpers11=require("./helpers.progressbar");var _helpers12=_interopRequireDefault(_helpers11);var _helpersProgressbar=require("./helpers.progressbar.eventbased");var _helpersProgressbar2=_interopRequireDefault(_helpersProgressbar);var _helpers13=require("./helpers.slice");var _helpers14=_interopRequireDefault(_helpers13);var _helpers15=require("./helpers.stack");var _helpers16=_interopRequireDefault(_helpers15);var _helpers17=require("./helpers.volumerendering");var _helpers18=_interopRequireDefault(_helpers17);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Border:_helpers2.default,BoundingBox:_helpers4.default,Localizer:_helpers6.default,Lut:_helpers8.default,SegmentationLut:_helpers10.default,ProgressBar:_helpers12.default,ProgressBarEventBased:_helpersProgressbar2.default,Slice:_helpers14.default,Stack:_helpers16.default,VolumeRendering:_helpers18.default}},{"./helpers.border":111,"./helpers.boundingbox":112,"./helpers.localizer":114,"./helpers.lut":115,"./helpers.progressbar":118,"./helpers.progressbar.eventbased":117,"./helpers.segmentationlut":119,"./helpers.slice":120,"./helpers.stack":121,"./helpers.volumerendering":122}],114:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shadersLocalizer=require("../shaders/shaders.localizer.uniform");var _shadersLocalizer2=_interopRequireDefault(_shadersLocalizer);var _shadersLocalizer3=require("../shaders/shaders.localizer.vertex");var _shadersLocalizer4=_interopRequireDefault(_shadersLocalizer3);var _shadersLocalizer5=require("../shaders/shaders.localizer.fragment");var _shadersLocalizer6=_interopRequireDefault(_shadersLocalizer5);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersLocalizer=function(_THREE$Object3D){_inherits(HelpersLocalizer,_THREE$Object3D);function HelpersLocalizer(stack,geometry,referencePlane){_classCallCheck(this,HelpersLocalizer);var _this=_possibleConstructorReturn(this,(HelpersLocalizer.__proto__||Object.getPrototypeOf(HelpersLocalizer)).call(this));_this._stack=stack;_this._referencePlane=referencePlane;_this._plane1=null;_this._color1=null;_this._plane2=null;_this._color2=null;_this._plane3=null;_this._color3=null;_this._canvasWidth=0;_this._canvasHeight=0;_this._shadersFragment=_shadersLocalizer6.default;_this._shadersVertex=_shadersLocalizer4.default;_this._uniforms=_shadersLocalizer2.default.uniforms();_this._material=null;_this._geometry=geometry;_this._create();return _this}_createClass(HelpersLocalizer,[{key:"_create",value:function _create(){this._prepareMaterial();this._mesh=new THREE.Mesh(this._geometry,this._material);this._mesh.applyMatrix(this._stack._ijk2LPS);this.add(this._mesh)}},{key:"_prepareMaterial",value:function _prepareMaterial(){if(!this.material){this._uniforms.uSlice.value=this._referencePlane;if(this._plane1){this._uniforms.uPlane1.value=this._plane1;this._uniforms.uPlaneColor1.value=this._color1}if(this._plane2){this._uniforms.uPlane2.value=this._plane2;this._uniforms.uPlaneColor2.value=this._color2}if(this._plane3){this._uniforms.uPlane3.value=this._plane3;this._uniforms.uPlaneColor3.value=this._color3}this._uniforms.uCanvasWidth.value=this._canvasWidth;this._uniforms.uCanvasHeight.value=this._canvasHeight;var fs=new _shadersLocalizer6.default(this._uniforms);var vs=new _shadersLocalizer4.default;this._material=new THREE.ShaderMaterial({side:THREE.DoubleSide,uniforms:this._uniforms,vertexShader:vs.compute(),fragmentShader:fs.compute()});this._material.transparent=true}}},{key:"update",value:function update(){if(this._mesh){this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh.geometry=null;this._mesh=null}this._create()}},{key:"geometry",get:function get(){return this._geometry},set:function set(geometry){this._geometry=geometry;if(this._mesh){this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh.geometry=null;this._mesh=null}this._create()}},{key:"referencePlane",get:function get(){return this._referencePlane},set:function set(referencePlane){this._referencePlane=referencePlane;this._uniforms.uSlice.value=this._referencePlane}},{key:"plane1",get:function get(){return this._plane1},set:function set(plane1){this._plane1=plane1;this._uniforms.uPlane1.value=this._plane1}},{key:"color1",get:function get(){return this._color1},set:function set(color1){this._color1=color1;this._uniforms.uPlaneColor1.value=this._color1}},{key:"plane2",get:function get(){return this._plane2},set:function set(plane2){this._plane2=plane2;this._uniforms.uPlane2.value=this._plane2}},{key:"color2",get:function get(){return this._color2},set:function set(color2){this._color2=color2;this._uniforms.uPlaneColor2.value=this._color2}},{key:"plane3",get:function get(){return this._plane3},set:function set(plane3){this._plane3=plane3;this._uniforms.uPlane3.value=this._plane3}},{key:"color3",get:function get(){return this._color3},set:function set(color3){this._color3=color3;this._uniforms.uPlaneColor3.value=this._color3}},{key:"canvasWidth",get:function get(){return this._canvasWidth},set:function set(canvasWidth){this._canvasWidth=canvasWidth;this._uniforms.uCanvasWidth.value=this._canvasWidth}},{key:"canvasHeight",get:function get(){return this._canvasHeight},set:function set(canvasHeight){this._canvasHeight=canvasHeight;this._uniforms.uCanvasHeight.value=this._canvasHeight}}]);return HelpersLocalizer}(THREE.Object3D);exports.default=HelpersLocalizer},{"../shaders/shaders.localizer.fragment":158,"../shaders/shaders.localizer.uniform":159,"../shaders/shaders.localizer.vertex":160}],115:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("../core/core.utils");var _core2=_interopRequireDefault(_core);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var HelpersLut=function(){function HelpersLut(domTarget){var lut=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"default";var lutO=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"linear";var color=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[[0,0,0,0],[1,1,1,1]];var opacity=arguments.length>4&&arguments[4]!==undefined?arguments[4]:[[0,0],[1,1]];var discrete=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;_classCallCheck(this,HelpersLut);if(_core2.default.isString(domTarget)){this._dom=document.getElementById(domTarget)}else{this._dom=domTarget}this._discrete=discrete;this._color=color;this._lut=lut;this._luts=_defineProperty({},lut,color);this._opacity=opacity;this._lutO=lutO;this._lutsO=_defineProperty({},lutO,opacity);this.initCanvas();this.paintCanvas()}_createClass(HelpersLut,[{key:"initCanvas",value:function initCanvas(){this._canvasContainer=this.initCanvasContainer(this._dom);this._canvasBg=this.createCanvas();this._canvasContainer.appendChild(this._canvasBg);this._canvas=this.createCanvas();this._canvasContainer.appendChild(this._canvas)}},{key:"initCanvasContainer",value:function initCanvasContainer(dom){var canvasContainer=dom;canvasContainer.style.width="256 px";canvasContainer.style.height="128 px";canvasContainer.style.border="1px solid #F9F9F9";return canvasContainer}},{key:"createCanvas",value:function createCanvas(){var canvas=document.createElement("canvas");canvas.height=16;canvas.width=256;return canvas}},{key:"paintCanvas",value:function paintCanvas(){var ctx=this._canvas.getContext("2d");ctx.clearRect(0,0,this._canvas.width,this._canvas.height);ctx.globalCompositeOperation="source-over";if(!this._discrete){var color=ctx.createLinearGradient(0,0,this._canvas.width,this._canvas.height);for(var i=0;i<this._color.length;i++){color.addColorStop(this._color[i][0],"rgba( "+Math.round(this._color[i][1]*255)+", "+Math.round(this._color[i][2]*255)+", "+Math.round(this._color[i][3]*255)+", 1)")}ctx.fillStyle=color;ctx.fillRect(0,0,this._canvas.width,this._canvas.height)}else{ctx.lineWidth=2*this._canvas.height;for(var _i=0;_i<this._color.length;_i++){var currentPos=this._color[_i][0];var nextPos=1;if(_i<this._color.length-1){nextPos=this._color[_i+1][0]}var previousPos=0;if(_i>0){previousPos=this._color[_i-1][0]}var from=previousPos+(currentPos-previousPos)/2;var to=currentPos+(nextPos-currentPos)/2;var _color=this._color[_i];var opacity=this._opacity[_i]?this._opacity[_i][1]:1;ctx.beginPath();ctx.strokeStyle="rgba( "+Math.round(_color[1]*255)+", "+Math.round(_color[2]*255)+", "+Math.round(_color[3]*255)+", "+opacity+")";ctx.moveTo(from*this._canvas.width,0);ctx.lineTo(to*this._canvas.width,0);ctx.stroke();ctx.closePath()}}if(!this._discrete){ctx.globalCompositeOperation="destination-in";var _opacity=ctx.createLinearGradient(0,0,this._canvas.width,this._canvas.height);for(var _i2=0;_i2<this._opacity.length;_i2++){_opacity.addColorStop(this._opacity[_i2][0],"rgba(255, 255, 255, "+this._opacity[_i2][1]+")")}ctx.fillStyle=_opacity;ctx.fillRect(0,0,this._canvas.width,this._canvas.height)}}},{key:"lutsAvailable",value:function lutsAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"color";var available=[];var luts=this._luts;if(type!=="color"){luts=this._lutsO}for(var i in luts){available.push(i)}return available}},{key:"texture",get:function get(){var texture=new THREE.Texture(this._canvas);texture.mapping=THREE.UVMapping;texture.wrapS=texture.wrapT=THREE.ClampToEdgeWrapping;texture.magFilter=texture.minFilter=THREE.NearestFilter;texture.premultiplyAlpha=true;texture.needsUpdate=true;return texture}},{key:"lut",set:function set(targetLUT){this._color=this._luts[targetLUT];this._lut=targetLUT;this.paintCanvas()},get:function get(){return this._lut}},{key:"luts",set:function set(newLuts){this._luts=newLuts},get:function get(){return this._luts}},{key:"lutO",set:function set(targetLUTO){this._opacity=this._lutsO[targetLUTO];this._lutO=targetLUTO;this.paintCanvas()},get:function get(){return this._lutO}},{key:"lutsO",set:function set(newLutsO){this._lutsO=newLutsO},get:function get(){return this._lutsO}},{key:"discrete",set:function set(discrete){this._discrete=discrete;this.paintCanvas()},get:function get(){return this._discrete}}],[{key:"presetLuts",value:function presetLuts(){return{default:[[0,0,0,0],[1,1,1,1]],spectrum:[[0,0,0,0],[.1,0,0,1],[.33,0,1,1],[.5,0,1,0],[.66,1,1,0],[.9,1,0,0],[1,1,1,1]],hot_and_cold:[[0,0,0,1],[.15,0,1,1],[.3,0,1,0],[.45,0,0,0],[.5,0,0,0],[.55,0,0,0],[.7,1,1,0],[.85,1,0,0],[1,1,1,1]],gold:[[0,0,0,0],[.13,.19,.03,0],[.25,.39,.12,0],[.38,.59,.26,0],[.5,.8,.46,.08],[.63,.99,.71,.21],[.75,.99,.88,.34],[.88,.99,.99,.48],[1,.9,.95,.61]],red:[[0,.75,0,0],[.5,1,.5,0],[.95,1,1,0],[1,1,1,1]],green:[[0,0,.75,0],[.5,.5,1,0],[.95,1,1,0],[1,1,1,1]],blue:[[0,0,0,1],[.5,0,.5,1],[.95,0,1,1],[1,1,1,1]],walking_dead:[[0,.1,1,1],[1,1,1,1]],random:[[0,0,0,0],[.27,.18,.18,.18],[.41,1,1,1],[.7,1,0,0],[1,1,1,1]]}}},{key:"presetLutsO",value:function presetLutsO(){return{linear:[[0,0],[1,1]],lowpass:[[0,.8],[.2,.6],[.3,.1],[1,0]],bandpass:[[0,0],[.4,.8],[.6,.8],[1,0]],highpass:[[0,0],[.7,.1],[.8,.6],[1,.8]],flat:[[0,.7],[1,1]],random:[[0,0],[.38,0],[.55,1],[.72,1],[1,.05]]}}}]);return HelpersLut}();exports.default=HelpersLut},{"../core/core.utils":106}],116:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HerlpersMaterialMixin=function HerlpersMaterialMixin(superclass){return function(_superclass){_inherits(_class,_superclass);function _class(){_classCallCheck(this,_class);return _possibleConstructorReturn(this,(_class.__proto__||Object.getPrototypeOf(_class)).apply(this,arguments))}_createClass(_class,[{key:"_createMaterial",value:function _createMaterial(extraOptions){var fs=new this._shadersFragment(this._uniforms);var vs=new this._shadersVertex;var globalOptions={uniforms:this._uniforms,vertexShader:vs.compute(),fragmentShader:fs.compute()};var options=Object.assign(extraOptions,globalOptions);this._material=new THREE.ShaderMaterial(options);this._material.needsUpdate=true}},{key:"_updateMaterial",value:function _updateMaterial(){var fs=new this._shadersFragment(this._uniforms);var vs=new this._shadersVertex;this._material.vertexShader=vs.compute();this._material.fragmentShader=fs.compute();this._material.needsUpdate=true}},{key:"_prepareTexture",value:function _prepareTexture(){this._textures=[];for(var m=0;m<this._stack._rawData.length;m++){var tex=new THREE.DataTexture(this._stack.rawData[m],this._stack.textureSize,this._stack.textureSize,this._stack.textureType,THREE.UnsignedByteType,THREE.UVMapping,THREE.ClampToEdgeWrapping,THREE.ClampToEdgeWrapping,THREE.NearestFilter,THREE.NearestFilter);tex.needsUpdate=true;tex.flipY=true;this._textures.push(tex)}}}]);return _class}(superclass)};exports.default=HerlpersMaterialMixin},{}],117:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("../core/core.utils");var _core2=_interopRequireDefault(_core);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var HelpersProgressBarEventBased=function(){function HelpersProgressBarEventBased(emitter,domTarget){_classCallCheck(this,HelpersProgressBarEventBased);if(!emitter||!this._isFunction(emitter.emit)){console.error("please give the this._emitter instance");return}if(_core2.default.isString(domTarget)){this._dom=document.getElementById(domTarget)}else{this._dom=domTarget}if(!_core2.default.isElement(this._dom)){console.error("please give the id of container dom or directly a dom instance");return}this._emitter=emitter;this.initContainerDom();this.initEventListenner();this.loaded=0;this.totalFile=0}_createClass(HelpersProgressBarEventBased,[{key:"_isFunction",value:function _isFunction(fn){return Object.prototype.toString.call(fn)==="[object Function]"}},{key:"initEventListenner",value:function initEventListenner(){var self=this;this._emitter.on("load-start",function(event){var totalFiles=event.totalFiles;self.totalFile=totalFiles;self._domTotalFile.innerHTML=totalFiles});this._emitter.on("fetch-start",function(event){var fetchLi=document.createElement("li");var fileTag=document.createElement("div");fileTag.innerHTML="file: "+event.file;fileTag.style.color="#ffffff";fetchLi.append(fileTag);fetchLi.className="fetch-file";fetchLi.id="file-"+event.file;fetchLi.style.marginBottom="7px";fetchLi.style.border="1px solid #ffffff;";fetchLi.style.width="60%";var fetchprogress=document.createElement("div");fetchprogress.id="file-fetch-"+event.file;fetchprogress.style.width="0%";fetchLi.append(fetchprogress);self._domProcessList.append(fetchLi)});this._emitter.on("fetch-progress",function(event){var id="file-fetch-"+event.file;var fileFetchDom=document.getElementById(id);fileFetchDom.style.width=event.loaded/event.total*100+"%";fileFetchDom.style.border="1px solid red"});this._emitter.on("fetch-success",function(event){var liParent=document.getElementById("file-"+event.file);var result=document.createElement("div");result.id="file-result-"+event.file;result.innerHTML="fetch-success";result.style.color="#ffffff";liParent.append(result)});this._emitter.on("fetch-error",function(event){});this._emitter.on("fetch-abort",function(event){});this._emitter.on("fetch-end",function(event){});this._emitter.on("fetch-timeout",function(event){});this._emitter.on("parse-start",function(event){var liParent=document.getElementById("file-"+event.file);var parseprogress=document.createElement("div");parseprogress.id="file-parse-"+event.file;parseprogress.style.width="0%";liParent.append(parseprogress)});this._emitter.on("parsing",function(event){var id="file-parse-"+event.file;var fileParseDom=document.getElementById(id);fileParseDom.style.width=event.parsed/event.total*100+"%";fileParseDom.style.border="1px solid yellow"});this._emitter.on("parse-success",function(event){self.loaded+=1;self._domCurrentFile.innerHTML=self.loaded;self._domCurrentProgress.style.width=self.loaded/self.totalFile*100+"%";var liParent=document.getElementById("file-"+event.file);var result=document.createElement("div");result.id="file-result-"+event.file;result.innerHTML="parse-success";result.style.color="#ffffff";liParent.append(result)})}},{key:"initContainerDom",value:function initContainerDom(){var containerDom='\n
\n
\n <label for="progress-bar" id="progress-label" style="width: 60%; border: 1px solid #ffffff; text-align: center;">\n 0\n 0\n </label>\n
\n
\n
\n
\n
    \n
\n
';var wrap=document.createElement("div");wrap.innerHTML=containerDom;this._dom.append(wrap);this._domCurrentFile=document.getElementById("current-file-index");this._domTotalFile=document.getElementById("total-file");this._domProcessList=document.getElementById("process-list");this._domCurrentProgress=document.getElementById("current-progress")}}]);return HelpersProgressBarEventBased}();exports.default=HelpersProgressBarEventBased},{"../core/core.utils":106}],118:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var HelpersProgressBar=function(){function HelpersProgressBar(container){_classCallCheck(this,HelpersProgressBar);this._container=container;this._modes={load:{name:"load",color:"#FFF56F"},parse:{name:"parse",color:"#2196F3"}};this.requestAnimationFrameID=null;this._mode=null;this._value=null;this._total=null;this.init()}_createClass(HelpersProgressBar,[{key:"free",value:function free(){var progressContainers=this._container.getElementsByClassName("progress container");if(progressContainers.length>0){progressContainers[0].parentNode.removeChild(progressContainers[0])}progressContainers=null;window.cancelAnimationFrame(this.requestAnimationFrameID)}},{key:"init",value:function init(){var progressContainer=this._domContainer();for(var mode in this._modes){if(this._modes.hasOwnProperty(mode)){var bar=this._domBar(this._modes[mode]);progressContainer.appendChild(bar);bar=null}}this._container.appendChild(progressContainer);progressContainer=null;this.updateUI()}},{key:"update",value:function update(value,total,mode){this._mode=mode;this._value=value;if(total===0){this._total=value;this._value=Math.random()*value}else{this._total=total}}},{key:"updateUI",value:function updateUI(){var _this=this;this.requestAnimationFrameID=requestAnimationFrame(function(){_this.updateUI()});if(!(this._modes.hasOwnProperty(this._mode)&&this._modes[this._mode].hasOwnProperty("name")&&this._modes[this._mode].hasOwnProperty("color"))){return false}var message="";var progress=Math.round(this._value/this._total*100);var color=this._modes[this._mode].color;var progressBar=this._container.getElementsByClassName("progress "+this._modes[this._mode].name);if(progressBar.length>0){progressBar[0].style.borderColor=color;progressBar[0].style.width=progress+"%"}progressBar=null}},{key:"_domContainer",value:function _domContainer(){var container=document.createElement("div");container.classList.add("progress");container.classList.add("container");container.style.width="100%";container.style.height="8px";container.style.position="absolute";container.style.backgroundColor="rgba(158, 158, 158, 0.5)";container.style.top="0";container.style.zIndex="1";return container}},{key:"_domBar",value:function _domBar(mode){if(!(mode.hasOwnProperty("name")&&mode.hasOwnProperty("color"))){window.console.log("Invalid mode provided.");window.console.log(mode);return false}var bar=document.createElement("div");bar.classList.add(mode.name);bar.classList.add("progress");bar.style.border="2px solid "+mode.color;bar.style.width="0%";return bar}}]);return HelpersProgressBar}();exports.default=HelpersProgressBar},{}],119:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _core=require("../core/core.utils");var _core2=_interopRequireDefault(_core);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var defaultSegmentation={0:{color:[0,0,0],opacity:0,label:"background"},1:{color:[255,0,0],opacity:1,label:"white matter"}};var HelpersSegmentationLut=function(){function HelpersSegmentationLut(domTarget){

var segID=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"Freesurfer";var segmentation=arguments.length>2&&arguments[2]!==undefined?arguments[2]:defaultSegmentation;_classCallCheck(this,HelpersSegmentationLut);if(_core2.default.isString(domTarget)){this._dom=document.getElementById(domTarget)}else{this._dom=domTarget}this._segmentation=segmentation;this.initCanvas();this.paintCanvas()}_createClass(HelpersSegmentationLut,[{key:"initCanvas",value:function initCanvas(){this._canvasContainer=this.initCanvasContainer(this._dom);this._canvasBg=this.createCanvas();this._canvasContainer.appendChild(this._canvasBg);this._canvas=this.createCanvas();this._canvasContainer.appendChild(this._canvas)}},{key:"initCanvasContainer",value:function initCanvasContainer(dom){var canvasContainer=dom;canvasContainer.style.width="256 px";canvasContainer.style.height="128 px";canvasContainer.style.border="1px solid #F9F9F9";return canvasContainer}},{key:"createCanvas",value:function createCanvas(){var canvas=document.createElement("canvas");canvas.height=128;canvas.width=256;return canvas}},{key:"paintCanvas",value:function paintCanvas(){var ctx=this._canvas.getContext("2d");ctx.clearRect(0,0,this._canvas.width,this._canvas.height);ctx.globalCompositeOperation="source-over";ctx.lineWidth=1;for(var i in this._segmentation){var xCoord=i%this._canvas.width;var yCoord=Math.floor(i/this._canvas.width);var opacity=typeof this._segmentation[i]["opacity"]!="undefined"?this._segmentation[i]["opacity"]:1;var color=this._segmentation[i]["color"];ctx.fillStyle="rgba( "+Math.round(color[0])+", "+Math.round(color[1])+", "+Math.round(color[2])+", "+opacity+")";ctx.fillRect(xCoord,yCoord,1,1)}}},{key:"texture",get:function get(){var texture=new THREE.Texture(this._canvas);texture.mapping=THREE.UVMapping;texture.wrapS=texture.wrapT=THREE.ClampToEdgeWrapping;texture.magFilter=texture.minFilter=THREE.NearestFilter;texture.premultiplyAlpha=true;texture.needsUpdate=true;return texture}},{key:"segmentation",set:function set(segmentation){this._segmentation=segmentation;this.paintCanvas()},get:function get(){return this._segmentation}}]);return HelpersSegmentationLut}();exports.default=HelpersSegmentationLut},{"../core/core.utils":106}],120:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _geometries=require("../geometries/geometries.slice");var _geometries2=_interopRequireDefault(_geometries);var _shadersData=require("../shaders/shaders.data.uniform");var _shadersData2=_interopRequireDefault(_shadersData);var _shadersData3=require("../shaders/shaders.data.vertex");var _shadersData4=_interopRequireDefault(_shadersData3);var _shadersData5=require("../shaders/shaders.data.fragment");var _shadersData6=_interopRequireDefault(_shadersData5);var _helpersMaterial=require("../helpers/helpers.material.mixin");var _helpersMaterial2=_interopRequireDefault(_helpersMaterial);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersSlice=function(_HelpersMaterialMixin){_inherits(HelpersSlice,_HelpersMaterialMixin);function HelpersSlice(stack){var index=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var position=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new _three.Vector3(0,0,0);var direction=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new _three.Vector3(0,0,1);var aabbSpace=arguments.length>4&&arguments[4]!==undefined?arguments[4]:"IJK";_classCallCheck(this,HelpersSlice);var _this=_possibleConstructorReturn(this,(HelpersSlice.__proto__||Object.getPrototypeOf(HelpersSlice)).call(this));_this._stack=stack;_this._invert=_this._stack.invert;_this._lut="none";_this._lutTexture=null;_this._intensityAuto=true;_this._interpolation=1;_this._index=index;_this._windowWidth=null;_this._windowCenter=null;_this._rescaleSlope=null;_this._rescaleIntercept=null;_this._canvasWidth=0;_this._canvasHeight=0;_this._borderColor=null;_this._planePosition=position;_this._planeDirection=direction;_this._aaBBspace=aabbSpace;_this._material=null;_this._textures=[];_this._shadersFragment=_shadersData6.default;_this._shadersVertex=_shadersData4.default;_this._uniforms=_shadersData2.default.uniforms();_this._geometry=null;_this._mesh=null;_this._visible=true;_this._init();_this._create();return _this}_createClass(HelpersSlice,[{key:"_init",value:function _init(){if(!this._stack||!this._stack._prepared||!this._stack._packed){return}if(this._aaBBspace==="IJK"){this._halfDimensions=this._stack.halfDimensionsIJK;this._center=new _three.Vector3(this._stack.halfDimensionsIJK.x-.5,this._stack.halfDimensionsIJK.y-.5,this._stack.halfDimensionsIJK.z-.5);this._toAABB=new _three.Matrix4}else{var aaBBox=this._stack.AABBox();this._halfDimensions=aaBBox.clone().multiplyScalar(.5);this._center=this._stack.centerAABBox();this._toAABB=this._stack.lps2AABB}}},{key:"_create",value:function _create(){if(!this._stack||!this._stack.prepared||!this._stack.packed){return}try{this._geometry=new _geometries2.default(this._halfDimensions,this._center,this._planePosition,this._planeDirection,this._toAABB)}catch(e){window.console.log(e);window.console.log("invalid slice geometry - exiting...");return}if(!this._geometry.vertices){return}if(!this._material){this._uniforms.uTextureSize.value=this._stack.textureSize;this._uniforms.uDataDimensions.value=[this._stack.dimensionsIJK.x,this._stack.dimensionsIJK.y,this._stack.dimensionsIJK.z];this._uniforms.uWorldToData.value=this._stack.lps2IJK;this._uniforms.uNumberOfChannels.value=this._stack.numberOfChannels;this._uniforms.uPixelType.value=this._stack.pixelType;this._uniforms.uBitsAllocated.value=this._stack.bitsAllocated;this._uniforms.uPackedPerPixel.value=this._stack.packedPerPixel;this._prepareTexture();this._uniforms.uTextureContainer.value=this._textures;this._createMaterial({side:THREE.DoubleSide})}this.updateIntensitySettings();this.updateIntensitySettingsUniforms();this._mesh=new THREE.Mesh(this._geometry,this._material);if(this._aaBBspace==="IJK"){this._mesh.applyMatrix(this._stack.ijk2LPS)}this._mesh.visible=this._visible;this.add(this._mesh)}},{key:"updateIntensitySettings",value:function updateIntensitySettings(){if(this._intensityAuto){this.updateIntensitySetting("windowCenter");this.updateIntensitySetting("windowWidth");this.updateIntensitySetting("rescaleSlope");this.updateIntensitySetting("rescaleIntercept")}else{if(this._windowCenter===null){this._windowCenter=this._stack.windowCenter}if(this.__windowWidth===null){this._windowWidth=this._stack.windowWidth}if(this._rescaleSlope===null){this._rescaleSlope=this._stack.rescaleSlope}if(this._rescaleIntercept===null){this._rescaleIntercept=this._stack.rescaleIntercept}}}},{key:"updateIntensitySettingsUniforms",value:function updateIntensitySettingsUniforms(){var offset=0;if(this._stack._minMax[0]<0){offset-=this._stack._minMax[0]}this._uniforms.uRescaleSlopeIntercept.value=[this._rescaleSlope,this._rescaleIntercept];this._uniforms.uWindowCenterWidth.value=[offset+this._windowCenter,this._windowWidth];this._uniforms.uInvert.value=this._invert===true?1:0;this._uniforms.uInterpolation.value=this._interpolation;if(this._lut==="none"){this._uniforms.uLut.value=0}else{this._uniforms.uLut.value=1;this._uniforms.uTextureLUT.value=this._lutTexture}}},{key:"updateIntensitySetting",value:function updateIntensitySetting(setting){if(this._stack.frame[this._index]&&this._stack.frame[this._index][setting]){this["_"+setting]=this._stack.frame[this._index][setting]}else{this["_"+setting]=this._stack[setting]}}},{key:"_update",value:function _update(){if(this._mesh){this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh.geometry=null;this._mesh=null}this._create()}},{key:"dispose",value:function dispose(){for(var j=0;j<this._textures.length;j++){this._textures[j].dispose();this._textures[j]=null}this._textures=null;this._shadersFragment=null;this._shadersVertex=null;this._uniforms=null;this.remove(this._mesh);this._mesh.geometry.dispose();this._mesh.geometry=null;this._mesh.material.dispose();this._mesh.material=null;this._mesh=null;this._geometry.dispose();this._geometry=null;this._material.vertexShader=null;this._material.fragmentShader=null;this._material.uniforms=null;this._material.dispose();this._material=null;this._stack=null}},{key:"cartesianEquation",value:function cartesianEquation(){if(!this._geometry||!this._geometry.vertices||this._geometry.vertices.length<3){return new _three.Vector4}var vertices=this._geometry.vertices;var dataToWorld=this._stack.ijk2LPS;var p1=new _three.Vector3(vertices[0].x,vertices[0].y,vertices[0].z).applyMatrix4(dataToWorld);var p2=new _three.Vector3(vertices[1].x,vertices[1].y,vertices[1].z).applyMatrix4(dataToWorld);var p3=new _three.Vector3(vertices[2].x,vertices[2].y,vertices[2].z).applyMatrix4(dataToWorld);var v1=new _three.Vector3;var v2=new _three.Vector3;var normal=v1.subVectors(p3,p2).cross(v2.subVectors(p1,p2)).normalize();return new _three.Vector4(normal.x,normal.y,normal.z,-normal.dot(p1))}},{key:"stack",get:function get(){return this._stack},set:function set(stack){this._stack=stack}},{key:"windowWidth",get:function get(){return this._windowWidth},set:function set(windowWidth){this._windowWidth=windowWidth;this.updateIntensitySettingsUniforms()}},{key:"windowCenter",get:function get(){return this._windowCenter},set:function set(windowCenter){this._windowCenter=windowCenter;this.updateIntensitySettingsUniforms()}},{key:"rescaleSlope",get:function get(){return this._rescaleSlope},set:function set(rescaleSlope){this._rescaleSlope=rescaleSlope;this.updateIntensitySettingsUniforms()}},{key:"rescaleIntercept",get:function get(){return this._rescaleIntercept},set:function set(rescaleIntercept){this._rescaleIntercept=rescaleIntercept;this.updateIntensitySettingsUniforms()}},{key:"invert",get:function get(){return this._invert},set:function set(invert){this._invert=invert;this.updateIntensitySettingsUniforms()}},{key:"lut",get:function get(){return this._lut},set:function set(lut){this._lut=lut}},{key:"lutTexture",get:function get(){return this._lutTexture},set:function set(lutTexture){this._lutTexture=lutTexture;this.updateIntensitySettingsUniforms()}},{key:"intensityAuto",get:function get(){return this._intensityAuto},set:function set(intensityAuto){this._intensityAuto=intensityAuto;this.updateIntensitySettings();this.updateIntensitySettingsUniforms()}},{key:"interpolation",get:function get(){return this._interpolation},set:function set(interpolation){this._interpolation=interpolation;this.updateIntensitySettingsUniforms();this._updateMaterial()}},{key:"index",get:function get(){return this._index},set:function set(index){this._index=index;this._update()}},{key:"planePosition",set:function set(position){this._planePosition=position;this._update()},get:function get(){return this._planePosition}},{key:"planeDirection",set:function set(direction){this._planeDirection=direction;this._update()},get:function get(){return this._planeDirection}},{key:"halfDimensions",set:function set(halfDimensions){this._halfDimensions=halfDimensions},get:function get(){return this._halfDimensions}},{key:"center",set:function set(center){this._center=center},get:function get(){return this._center}},{key:"aabbSpace",set:function set(aabbSpace){this._aaBBspace=aabbSpace;this._init()},get:function get(){return this._aaBBspace}},{key:"mesh",set:function set(mesh){this._mesh=mesh},get:function get(){return this._mesh}},{key:"geometry",set:function set(geometry){this._geometry=geometry},get:function get(){return this._geometry}},{key:"canvasWidth",set:function set(canvasWidth){this._canvasWidth=canvasWidth;this._uniforms.uCanvasWidth.value=this._canvasWidth},get:function get(){return this._canvasWidth}},{key:"canvasHeight",set:function set(canvasHeight){this._canvasHeight=canvasHeight;this._uniforms.uCanvasHeight.value=this._canvasHeight},get:function get(){return this._canvasHeight}},{key:"borderColor",set:function set(borderColor){this._borderColor=borderColor;this._uniforms.uBorderColor.value=new _three.Color(borderColor)},get:function get(){return this._borderColor}}]);return HelpersSlice}((0,_helpersMaterial2.default)(THREE.Object3D));exports.default=HelpersSlice},{"../geometries/geometries.slice":109,"../helpers/helpers.material.mixin":116,"../shaders/shaders.data.fragment":151,"../shaders/shaders.data.uniform":152,"../shaders/shaders.data.vertex":153,three:81}],121:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _helpers=require("../helpers/helpers.border");var _helpers2=_interopRequireDefault(_helpers);var _helpers3=require("../helpers/helpers.boundingbox");var _helpers4=_interopRequireDefault(_helpers3);var _helpers5=require("../helpers/helpers.slice");var _helpers6=_interopRequireDefault(_helpers5);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersStack=function(_THREE$Object3D){_inherits(HelpersStack,_THREE$Object3D);function HelpersStack(stack){_classCallCheck(this,HelpersStack);var _this=_possibleConstructorReturn(this,(HelpersStack.__proto__||Object.getPrototypeOf(HelpersStack)).call(this));_this._stack=stack;_this._bBox=null;_this._slice=null;_this._border=null;_this._dummy=null;_this._orientation=0;_this._index=0;_this._uniforms=null;_this._autoWindowLevel=false;_this._outOfBounds=false;_this._orientationMaxIndex=0;_this._canvasWidth=0;_this._canvasHeight=0;_this._borderColor=null;_this._create();return _this}_createClass(HelpersStack,[{key:"_create",value:function _create(){if(this._stack){this._prepareStack();this._prepareBBox();this._prepareSlice();this._prepareBorder()}else{window.console.log("no stack to be prepared...")}}},{key:"_computeOrientationMaxIndex",value:function _computeOrientationMaxIndex(){var dimensionsIJK=this._stack.dimensionsIJK;this._orientationMaxIndex=0;switch(this._orientation){case 0:this._orientationMaxIndex=dimensionsIJK.z-1;break;case 1:this._orientationMaxIndex=dimensionsIJK.x-1;break;case 2:this._orientationMaxIndex=dimensionsIJK.y-1;break;default:break}}},{key:"_isIndexOutOfBounds",value:function _isIndexOutOfBounds(){this._computeOrientationMaxIndex();if(this._index>=this._orientationMaxIndex||this._index<0){this._outOfBounds=true}else{this._outOfBounds=false}}},{key:"_prepareStack",value:function _prepareStack(){if(!this._stack.prepared){this._stack.prepare()}if(!this._stack.packed){this._stack.pack()}}},{key:"_prepareBBox",value:function _prepareBBox(){this._bBox=new _helpers4.default(this._stack);this.add(this._bBox)}},{key:"_prepareBorder",value:function _prepareBorder(){this._border=new _helpers2.default(this._slice);this.add(this._border)}},{key:"_prepareSlice",value:function _prepareSlice(){var halfDimensionsIJK=this._stack.halfDimensionsIJK;this._index=this._prepareSliceIndex(halfDimensionsIJK);var position=this._prepareSlicePosition(halfDimensionsIJK,this._index);var direction=this._prepareDirection(this._orientation);this._slice=new _helpers6.default(this._stack,this._index,position,direction);this.add(this._slice)}},{key:"_prepareSliceIndex",value:function _prepareSliceIndex(indices){var index=0;switch(this._orientation){case 0:index=Math.floor(indices.z);break;case 1:index=Math.floor(indices.x);break;case 2:index=Math.floor(indices.y);break;default:break}return index}},{key:"_prepareSlicePosition",value:function _prepareSlicePosition(rPosition,index){var position=new _three.Vector3(0,0,0);switch(this._orientation){case 0:position=new _three.Vector3(Math.floor(rPosition.x),Math.floor(rPosition.y),index);break;case 1:position=new _three.Vector3(index,Math.floor(rPosition.y),Math.floor(rPosition.z));break;case 2:position=new _three.Vector3(Math.floor(rPosition.x),index,Math.floor(rPosition.z));break;default:break}return position}},{key:"_prepareDirection",value:function _prepareDirection(orientation){var direction=new _three.Vector3(0,0,1);switch(orientation){case 0:direction=new _three.Vector3(0,0,1);break;case 1:direction=new _three.Vector3(1,0,0);break;case 2:direction=new _three.Vector3(0,1,0);break;default:break}return direction}},{key:"dispose",value:function dispose(){this.remove(this._slice);this._slice.dispose();this._slice=null;this._bBox.dispose();this._bBox=null;this._border.dispose();this._border=null}},{key:"stack",get:function get(){return this._stack},set:function set(stack){this._stack=stack}},{key:"bbox",get:function get(){return this._bBox}},{key:"slice",get:function get(){return this._slice}},{key:"border",get:function get(){return this._border}},{key:"index",get:function get(){return this._index},set:function set(index){this._index=index;this._slice.index=index;var halfDimensions=this._stack.halfDimensionsIJK;this._slice.planePosition=this._prepareSlicePosition(halfDimensions,this._index);this._border.helpersSlice=this._slice;this._isIndexOutOfBounds()}},{key:"orientation",set:function set(orientation){this._orientation=orientation;this._computeOrientationMaxIndex();this._slice.planeDirection=this._prepareDirection(this._orientation);this._border.helpersSlice=this._slice},get:function get(){return this._orientation}},{key:"outOfBounds",set:function set(outOfBounds){this._outOfBounds=outOfBounds},get:function get(){return this._outOfBounds}},{key:"orientationMaxIndex",set:function set(orientationMaxIndex){this._orientationMaxIndex=orientationMaxIndex},get:function get(){return this._orientationMaxIndex}},{key:"canvasWidth",set:function set(canvasWidth){this._canvasWidth=canvasWidth;this._slice.canvasWidth=this._canvasWidth},get:function get(){return this._canvasWidth}},{key:"canvasHeight",set:function set(canvasHeight){this._canvasHeight=canvasHeight;this._slice.canvasHeight=this._canvasHeight},get:function get(){return this._canvasHeight}},{key:"borderColor",set:function set(borderColor){this._borderColor=borderColor;this._border.color=borderColor;this._slice.borderColor=this._borderColor},get:function get(){return this._borderColor}}]);return HelpersStack}(THREE.Object3D);exports.default=HelpersStack},{"../helpers/helpers.border":111,"../helpers/helpers.boundingbox":112,"../helpers/helpers.slice":120,three:81}],122:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shadersVr=require("../shaders/shaders.vr.uniform");var _shadersVr2=_interopRequireDefault(_shadersVr);var _shadersVr3=require("../shaders/shaders.vr.vertex");var _shadersVr4=_interopRequireDefault(_shadersVr3);var _shadersVr5=require("../shaders/shaders.vr.fragment");var _shadersVr6=_interopRequireDefault(_shadersVr5);var _helpersMaterial=require("../helpers/helpers.material.mixin");var _helpersMaterial2=_interopRequireDefault(_helpersMaterial);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var HelpersVolumeRendering=function(_HelpersMaterialMixin){_inherits(HelpersVolumeRendering,_HelpersMaterialMixin);function HelpersVolumeRendering(stack){_classCallCheck(this,HelpersVolumeRendering);var _this=_possibleConstructorReturn(this,(HelpersVolumeRendering.__proto__||Object.getPrototypeOf(HelpersVolumeRendering)).call(this));_this._stack=stack;_this._textures=[];_this._shadersFragment=_shadersVr6.default;_this._shadersVertex=_shadersVr4.default;_this._uniforms=_shadersVr2.default.uniforms();_this._material=null;_this._geometry=null;_this._interpolation=1;_this._create();return _this}_createClass(HelpersVolumeRendering,[{key:"_create",value:function _create(){this._prepareStack();this._prepareTexture();this._prepareMaterial();this._prepareGeometry();this._mesh=new THREE.Mesh(this._geometry,this._material);this.add(this._mesh)}},{key:"_prepareStack",value:function _prepareStack(){if(!this._stack.prepared){this._stack.prepare()}if(!this._stack.packed){this._stack.pack()}}},{key:"_prepareMaterial",value:function _prepareMaterial(){var offset=0;if(this._stack._minMax[0]<0){offset=this._stack._minMax[0]}this._uniforms=_shadersVr2.default.uniforms();this._uniforms.uWorldBBox.value=this._stack.worldBoundingBox();this._uniforms.uTextureSize.value=this._stack.textureSize;this._uniforms.uTextureContainer.value=this._textures;this._uniforms.uWorldToData.value=this._stack.lps2IJK;this._uniforms.uNumberOfChannels.value=this._stack.numberOfChannels;this._uniforms.uPixelType.value=this._stack.pixelType;this._uniforms.uBitsAllocated.value=this._stack.bitsAllocated;this._uniforms.uPackedPerPixel.value=this._stack.packedPerPixel;this._uniforms.uWindowCenterWidth.value=[offset+this._stack.windowCenter,this._stack.windowWidth*.8];this._uniforms.uRescaleSlopeIntercept.value=[this._stack.rescaleSlope,this._stack.rescaleIntercept];this._uniforms.uDataDimensions.value=[this._stack.dimensionsIJK.x,this._stack.dimensionsIJK.y,this._stack.dimensionsIJK.z];this._uniforms.uInterpolation.value=this._interpolation;this._createMaterial({side:THREE.FrontSide,transparent:true})}},{key:"_prepareGeometry",value:function _prepareGeometry(){var worldBBox=this._stack.worldBoundingBox();var centerLPS=this._stack.worldCenter();this._geometry=new THREE.BoxGeometry(worldBBox[1]-worldBBox[0],worldBBox[3]-worldBBox[2],worldBBox[5]-worldBBox[4]);this._geometry.applyMatrix((new _three.Matrix4).makeTranslation(centerLPS.x,centerLPS.y,centerLPS.z))}},{key:"uniforms",get:function get(){return this._uniforms},set:function set(uniforms){this._uniforms=uniforms}},{key:"stack",get:function get(){return this._stack},set:function set(stack){this._stack=stack}},{key:"interpolation",get:function get(){return this._interpolation},set:function set(interpolation){this._interpolation=interpolation;this._uniforms.uInterpolation.value=this._interpolation;this._updateMaterial()}}]);return HelpersVolumeRendering}((0,_helpersMaterial2.default)(THREE.Object3D));exports.default=HelpersVolumeRendering},{"../helpers/helpers.material.mixin":116,"../shaders/shaders.vr.fragment":161,"../shaders/shaders.vr.uniform":162,"../shaders/shaders.vr.vertex":163,three:81}],123:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _helpers=require("../helpers/helpers.progressbar");var _helpers2=_interopRequireDefault(_helpers);var _events=require("events");var _events2=_interopRequireDefault(_events);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var LoadersBase=function(_EventEmitter){_inherits(LoadersBase,_EventEmitter);function LoadersBase(){var container=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var ProgressBar=arguments.length>1&&arguments[1]!==undefined?arguments[1]:_helpers2.default;_classCallCheck(this,LoadersBase);var _this=_possibleConstructorReturn(this,(LoadersBase.__proto__||Object.getPrototypeOf(LoadersBase)).call(this));_this._loaded=-1;_this._totalLoaded=-1;_this._parsed=-1;_this._totalParsed=-1;_this._data=[];_this._container=container;_this._progressBar=null;if(_this._container&&ProgressBar){_this._progressBar=new ProgressBar(_this._container)}return _this}_createClass(LoadersBase,[{key:"free",value:function free(){this._container=null;if(this._progressBar){this._progressBar.free();this._progressBar=null}}},{key:"fetch",value:function fetch(url){var _this2=this;return new Promise(function(resolve,reject){var request=new XMLHttpRequest;request.open("GET",url);request.crossOrigin=true;request.responseType="arraybuffer";request.onloadstart=function(event){_this2.emit("fetch-start",{file:url,time:new Date})};request.onload=function(event){if(request.status===200){_this2._loaded=event.loaded;_this2._totalLoaded=event.total;if(_this2._progressBar){_this2._progressBar.update(_this2._loaded,_this2._totalLoaded,"load")}var buffer=request.response;var response={url:url,buffer:buffer};_this2.emit("fetch-success",{file:url,time:new Date,totalLoaded:event.total});resolve(response)}else{reject(request.statusText)}};request.onerror=function(){_this2.emit("fetch-error",{file:url,time:new Date});reject(request.statusText)};request.onabort=function(event){_this2.emit("fetch-abort",{file:url,time:new Date});reject(request.statusText)};request.ontimeout=function(){_this2.emit("fetch-timeout",{file:url,time:new Date});reject(request.statusText)};request.onprogress=function(event){_this2._loaded=event.loaded;_this2._totalLoaded=event.total;_this2.emit("fetch-progress",{file:url,total:event.total,loaded:event.loaded,time:new Date});if(_this2._progressBar){_this2._progressBar.update(_this2._loaded,_this2._totalLoaded,"load")}};request.onloadend=function(event){_this2.emit("fetch-end",{file:url,time:new Date})};request.send()})}},{key:"parse",value:function parse(response){return new Promise(function(resolve,reject){resolve(response)})}},{key:"loadSequenceGroup",value:function loadSequenceGroup(url){var _this3=this;var fetchSequence=[];url.forEach(function(file){fetchSequence.push(_this3.fetch(file))});return Promise.all(fetchSequence).then(function(rawdata){return _this3.parse(rawdata)}).then(function(data){_this3._data.push(data);return data}).catch(function(error){window.console.log("oops... something went wrong...");window.console.log(error)})}},{key:"loadSequence",value:function loadSequence(url){var _this4=this;return this.fetch(url).then(function(rawdata){return _this4.parse(rawdata)}).then(function(data){_this4._data.push(data);return data}).catch(function(error){ window.console.log("oops... something went wrong...");window.console.log(error)})}},{key:"load",value:function load(url){var _this5=this;if(!Array.isArray(url)){url=[url]}this.emit("load-start",{files:url,time:new Date});var loadSequences=[];url.forEach(function(file){if(!Array.isArray(file)){loadSequences.push(_this5.loadSequence(file))}else{loadSequences.push(_this5.loadSequenceGroup(file))}});return Promise.all(loadSequences)}},{key:"data",set:function set(data){this._data=data},get:function get(){return this._data}}]);return LoadersBase}(_events2.default);exports.default=LoadersBase},{"../helpers/helpers.progressbar":118,events:26}],124:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _loaders=require("./loaders.volume");var _loaders2=_interopRequireDefault(_loaders);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Volume:_loaders2.default}},{"./loaders.volume":125}],125:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _loaders=require("./loaders.base");var _loaders2=_interopRequireDefault(_loaders);var _core=require("../core/core.utils");var _core2=_interopRequireDefault(_core);var _models=require("../models/models.series");var _models2=_interopRequireDefault(_models);var _models3=require("../models/models.stack");var _models4=_interopRequireDefault(_models3);var _models5=require("../models/models.frame");var _models6=_interopRequireDefault(_models5);var _parsers=require("../parsers/parsers.dicom");var _parsers2=_interopRequireDefault(_parsers);var _parsers3=require("../parsers/parsers.mhd");var _parsers4=_interopRequireDefault(_parsers3);var _parsers5=require("../parsers/parsers.nifti");var _parsers6=_interopRequireDefault(_parsers5);var _parsers7=require("../parsers/parsers.nrrd");var _parsers8=_interopRequireDefault(_parsers7);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var PAKO=require("pako");var LoadersVolumes=function(_LoadersBase){_inherits(LoadersVolumes,_LoadersBase);function LoadersVolumes(){_classCallCheck(this,LoadersVolumes);return _possibleConstructorReturn(this,(LoadersVolumes.__proto__||Object.getPrototypeOf(LoadersVolumes)).apply(this,arguments))}_createClass(LoadersVolumes,[{key:"parse",value:function parse(response){var _this2=this;this.emit("parse-start",{file:response.url,time:new Date});if(this._progressBar){this._progressBar.update(0,100,"parse")}return new Promise(function(resolve,reject){window.setTimeout(function(){resolve(new Promise(function(resolve,reject){var data=response;if(!Array.isArray(data)){data=[data]}data.forEach(function(dataset){_this2._preprocess(dataset)});if(data.length===1){data=data[0]}else{var mhdFile=data.filter(_this2._filterByExtension.bind(null,"MHD"));var rawFile=data.filter(_this2._filterByExtension.bind(null,"RAW"));if(data.length===2&&mhdFile.length===1&&rawFile.length===1){data.url=mhdFile[0].url;data.extension=mhdFile[0].extension;data.mhdBuffer=mhdFile[0].buffer;data.rawBuffer=rawFile[0].buffer}}var Parser=_this2._parser(data.extension);if(!Parser){_this2.emit("parse-error",{file:response.url,time:new Date,error:data.filename+"can not be parsed."});reject(data.filename+" can not be parsed.")}var volumeParser=null;try{volumeParser=new Parser(data,0)}catch(e){window.console.log(e);_this2.emit("parse-error",{file:response.url,time:new Date,error:e});reject(e)}var series=new _models2.default;series.seriesInstanceUID=volumeParser.seriesInstanceUID();series.transferSyntaxUID=volumeParser.transferSyntaxUID();series.seriesDate=volumeParser.seriesDate();series.seriesDescription=volumeParser.seriesDescription();series.studyDate=volumeParser.studyDate();series.studyDescription=volumeParser.studyDescription();series.numberOfFrames=volumeParser.numberOfFrames();if(!series.numberOfFrames){series.numberOfFrames=1}series.numberOfChannels=volumeParser.numberOfChannels();series.modality=volumeParser.modality();if(series.modality==="SEG"){series.segmentationType=volumeParser.segmentationType();series.segmentationSegments=volumeParser.segmentationSegments()}series.patientID=volumeParser.patientID();series.patientName=volumeParser.patientName();series.patientAge=volumeParser.patientAge();series.patientBirthdate=volumeParser.patientBirthdate();series.patientSex=volumeParser.patientSex();var stack=new _models4.default;stack.numberOfChannels=volumeParser.numberOfChannels();stack.pixelRepresentation=volumeParser.pixelRepresentation();stack.pixelType=volumeParser.pixelType();stack.invert=volumeParser.invert();stack.spacingBetweenSlices=volumeParser.spacingBetweenSlices();stack.modality=series.modality;if(stack.modality==="SEG"){stack.segmentationType=series.segmentationType;stack.segmentationSegments=series.segmentationSegments}series.stack.push(stack);setTimeout(_this2.parseFrame(series,stack,response.url,0,volumeParser,resolve,reject),0)}))},10)})}},{key:"parseFrame",value:function parseFrame(series,stack,url,i,dataParser,resolve,reject){var frame=new _models6.default;frame.sopInstanceUID=dataParser.sopInstanceUID(i);frame.url=url;frame.index=i;frame.rows=dataParser.rows(i);frame.columns=dataParser.columns(i);frame.numberOfChannels=stack.numberOfChannels;frame.pixelRepresentation=stack.pixelRepresentation;frame.pixelType=stack.pixelType;frame.pixelData=dataParser.extractPixelData(i);frame.pixelSpacing=dataParser.pixelSpacing(i);frame.spacingBetweenSlices=dataParser.spacingBetweenSlices(i);frame.sliceThickness=dataParser.sliceThickness(i);frame.imageOrientation=dataParser.imageOrientation(i);frame.rightHanded=dataParser.rightHanded();stack.rightHanded=frame.rightHanded;if(frame.imageOrientation===null){frame.imageOrientation=[1,0,0,0,1,0]}frame.imagePosition=dataParser.imagePosition(i);if(frame.imagePosition===null){frame.imagePosition=[0,0,i]}frame.dimensionIndexValues=dataParser.dimensionIndexValues(i);frame.bitsAllocated=dataParser.bitsAllocated(i);frame.instanceNumber=dataParser.instanceNumber(i);frame.windowCenter=dataParser.windowCenter(i);frame.windowWidth=dataParser.windowWidth(i);frame.rescaleSlope=dataParser.rescaleSlope(i);frame.rescaleIntercept=dataParser.rescaleIntercept(i);frame.minMax=dataParser.minMaxPixelData(frame.pixelData);if(series.modality==="SEG"){frame.referencedSegmentNumber=dataParser.referencedSegmentNumber(i)}stack.frame.push(frame);this._parsed=i+1;this._totalParsed=series.numberOfFrames;if(this._progressBar){this._progressBar.update(this._parsed,this._totalParsed,"parse")}this.emit("parsing",{file:url,total:this._totalParsed,parsed:this._parsed,time:new Date});if(this._parsed===this._totalParsed){this.emit("parse-success",{file:url,total:this._totalParsed,parsed:this._parsed,time:new Date});resolve(series)}else{setTimeout(this.parseFrame(series,stack,url,this._parsed,dataParser,resolve,reject),0)}}},{key:"_parser",value:function _parser(extension){var Parser=null;switch(extension.toUpperCase()){case"NII":case"NII_":Parser=_parsers6.default;break;case"DCM":case"DICOM":case"IMA":case"":Parser=_parsers2.default;break;case"MHD":Parser=_parsers4.default;break;case"NRRD":Parser=_parsers8.default;break;default:window.console.log("unsupported extension: "+extension);return false}return Parser}},{key:"_preprocess",value:function _preprocess(data){var parsedUrl=_core2.default.parseUrl(data.url);data.filename=parsedUrl.filename;data.extension=parsedUrl.extension;data.pathname=parsedUrl.pathname;data.query=parsedUrl.query;if(data.extension==="gz"){data.gzcompressed=true;data.extension=data.filename.split(".gz").shift().split(".").pop();var decompressedData=PAKO.inflate(data.buffer);data.buffer=decompressedData.buffer}else{data.gzcompressed=false}}},{key:"_filterByExtension",value:function _filterByExtension(extension,item){if(item.extension.toUpperCase()===extension.toUpperCase()){return true}return false}}]);return LoadersVolumes}(_loaders2.default);exports.default=LoadersVolumes},{"../core/core.utils":106,"../models/models.frame":127,"../models/models.series":129,"../models/models.stack":130,"../parsers/parsers.dicom":132,"../parsers/parsers.mhd":134,"../parsers/parsers.nifti":135,"../parsers/parsers.nrrd":136,"./loaders.base":123,pako:51}],126:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ModelsBase=function(){function ModelsBase(){_classCallCheck(this,ModelsBase);this._id=-1}_createClass(ModelsBase,[{key:"mergeModels",value:function mergeModels(referenceArray,targetArray){if(!(this._validateModelArray(referenceArray)&&this._validateModelArray(targetArray))){window.console.log("invalid inputs provided.");return false}for(var i=0;i<targetArray.length;i++){for(var j=0;j<referenceArray.length;j++){if(referenceArray[j].merge(targetArray[i])){break}else if(j===referenceArray.length-1){referenceArray.push(targetArray[i])}}}return true}},{key:"merge",value:function merge(model){if(!this.validate(model)){return false}if(this._id===model._id){return true}return false}},{key:"validate",value:function validate(model){if(!(model&&model!==null&&typeof model.merge==="function")){return false}return true}},{key:"_validateModelArray",value:function _validateModelArray(modelArray){if(!(modelArray!==null&&Array===modelArray.constructor)){window.console.log("invalid model array provided.");return false}for(var i=0;i<modelArray.length;i++){if(!(modelArray[i]&&modelArray[i]!==null&&typeof modelArray[i].validate==="function"&&modelArray[i].validate(modelArray[i]))){return false}}return true}}]);return ModelsBase}();exports.default=ModelsBase},{}],127:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _models=require("../models/models.base");var _models2=_interopRequireDefault(_models);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var ModelsFrame=function(_ModelsBase){_inherits(ModelsFrame,_ModelsBase);function ModelsFrame(){_classCallCheck(this,ModelsFrame);var _this=_possibleConstructorReturn(this,(ModelsFrame.__proto__||Object.getPrototypeOf(ModelsFrame)).call(this));_this._sopInstanceUID=null;_this._url=null;_this._stackID=-1;_this._rows=0;_this._columns=0;_this._dimensionIndexValues=[];_this._imagePosition=null;_this._imageOrientation=null;_this._rightHanded=true;_this._sliceThickness=1;_this._spacingBetweenSlices=null;_this._pixelRepresentation=0;_this._pixelType=0;_this._pixelSpacing=null;_this._pixelAspectRatio=null;_this._pixelData=null;_this._instanceNumber=null;_this._windowCenter=null;_this._windowWidth=null;_this._rescaleSlope=null;_this._rescaleIntercept=null;_this._bitsAllocated=8;_this._minMax=null;_this._dist=null;_this._index=-1;_this._referencedSegmentNumber=-1;return _this}_createClass(ModelsFrame,[{key:"validate",value:function validate(model){if(!(_get(ModelsFrame.prototype.__proto__||Object.getPrototypeOf(ModelsFrame.prototype),"validate",this).call(this,model)&&typeof model.cosines==="function"&&typeof model.spacingXY==="function"&&model.hasOwnProperty("_sopInstanceUID")&&model.hasOwnProperty("_dimensionIndexValues")&&model.hasOwnProperty("_imageOrientation")&&model.hasOwnProperty("_imagePosition"))){return false}return true}},{key:"merge",value:function merge(frame){if(!this.validate(frame)){return false}if(this._compareArrays(this._dimensionIndexValues,frame.dimensionIndexValues)&&this._compareArrays(this._imageOrientation,frame.imageOrientation)&&this._compareArrays(this._imagePosition,frame.imagePosition)&&this._instanceNumber===frame.instanceNumber&&this._sopInstanceUID===frame.sopInstanceUID){return true}else{return false}}},{key:"cosines",value:function cosines(){var cosines=[new _three.Vector3(1,0,0),new _three.Vector3(0,1,0),new _three.Vector3(0,0,1)];if(this._imageOrientation&&this._imageOrientation.length===6){var xCos=new _three.Vector3(this._imageOrientation[0],this._imageOrientation[1],this._imageOrientation[2]);var yCos=new _three.Vector3(this._imageOrientation[3],this._imageOrientation[4],this._imageOrientation[5]);if(xCos.length()>0&&yCos.length()>0){cosines[0]=xCos;cosines[1]=yCos;cosines[2]=new _three.Vector3(0,0,0).crossVectors(cosines[0],cosines[1]).normalize()}}else{window.console.log("No valid image orientation for frame");window.console.log(this);window.console.log("Returning default orientation.")}if(!this._rightHanded){cosines[2].negate()}return cosines}},{key:"spacingXY",value:function spacingXY(){var spacingXY=[1,1];if(this.pixelSpacing){spacingXY[0]=this.pixelSpacing[0];spacingXY[1]=this.pixelSpacing[1]}else if(this.pixelAspectRatio){spacingXY[0]=1;spacingXY[1]=1*this.pixelAspectRatio[1]/this.pixelAspectRatio[0]}return spacingXY}},{key:"getPixelData",value:function getPixelData(column,row){return this.pixelData[column+this._columns*row]}},{key:"setPixelData",value:function setPixelData(column,row,value){this.pixelData[column+this._columns*row]=value}},{key:"_compareArrays",value:function _compareArrays(reference,target){if(reference===target){return true}if(reference&&target&&reference.join()===target.join()){return true}return false}},{key:"rows",get:function get(){return this._rows},set:function set(rows){this._rows=rows}},{key:"columns",get:function get(){return this._columns},set:function set(columns){this._columns=columns}},{key:"spacingBetweenSlices",get:function get(){return this._spacingBetweenSlices},set:function set(spacingBetweenSlices){this._spacingBetweenSlices=spacingBetweenSlices}},{key:"sliceThickness",get:function get(){return this._sliceThickness},set:function set(sliceThickness){this._sliceThickness=sliceThickness}},{key:"imagePosition",get:function get(){return this._imagePosition},set:function set(imagePosition){this._imagePosition=imagePosition}},{key:"imageOrientation",get:function get(){return this._imageOrientation},set:function set(imageOrientation){this._imageOrientation=imageOrientation}},{key:"windowWidth",get:function get(){return this._windowWidth},set:function set(windowWidth){this._windowWidth=windowWidth}},{key:"windowCenter",get:function get(){return this._windowCenter},set:function set(windowCenter){this._windowCenter=windowCenter}},{key:"rescaleSlope",get:function get(){return this._rescaleSlope},set:function set(rescaleSlope){this._rescaleSlope=rescaleSlope}},{key:"rescaleIntercept",get:function get(){return this._rescaleIntercept},set:function set(rescaleIntercept){this._rescaleIntercept=rescaleIntercept}},{key:"bitsAllocated",get:function get(){return this._bitsAllocated},set:function set(bitsAllocated){this._bitsAllocated=bitsAllocated}},{key:"dist",get:function get(){return this._dist},set:function set(dist){this._dist=dist}},{key:"pixelSpacing",get:function get(){return this._pixelSpacing},set:function set(pixelSpacing){this._pixelSpacing=pixelSpacing}},{key:"pixelAspectRatio",get:function get(){return this._pixelAspectRatio},set:function set(pixelAspectRatio){this._pixelAspectRatio=pixelAspectRatio}},{key:"minMax",get:function get(){return this._minMax},set:function set(minMax){this._minMax=minMax}},{key:"dimensionIndexValues",get:function get(){return this._dimensionIndexValues},set:function set(dimensionIndexValues){this._dimensionIndexValues=dimensionIndexValues}},{key:"instanceNumber",get:function get(){return this._instanceNumber},set:function set(instanceNumber){this._instanceNumber=instanceNumber}},{key:"pixelData",get:function get(){return this._pixelData},set:function set(pixelData){this._pixelData=pixelData}},{key:"sopInstanceUID",set:function set(sopInstanceUID){this._sopInstanceUID=sopInstanceUID},get:function get(){return this._sopInstanceUID}},{key:"pixelRepresentation",get:function get(){return this._pixelRepresentation},set:function set(pixelRepresentation){this._pixelRepresentation=pixelRepresentation}},{key:"pixelType",get:function get(){return this._pixelType},set:function set(pixelType){this._pixelType=pixelType}},{key:"url",get:function get(){return this._url},set:function set(url){this._url=url}},{key:"referencedSegmentNumber",get:function get(){return this._referencedSegmentNumber},set:function set(referencedSegmentNumber){this._referencedSegmentNumber=referencedSegmentNumber}},{key:"rightHanded",get:function get(){return this._rightHanded},set:function set(rightHanded){this._rightHanded=rightHanded}},{key:"index",get:function get(){return this._index},set:function set(index){this._index=index}}]);return ModelsFrame}(_models2.default);exports.default=ModelsFrame},{"../models/models.base":126,three:81}],128:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _models=require("./models.frame");var _models2=_interopRequireDefault(_models);var _models3=require("./models.stack");var _models4=_interopRequireDefault(_models3);var _models5=require("./models.series");var _models6=_interopRequireDefault(_models5);var _models7=require("./models.voxel");var _models8=_interopRequireDefault(_models7);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Frame:_models2.default,Stack:_models4.default,Series:_models6.default,Voxel:_models8.default}},{"./models.frame":127,"./models.series":129,"./models.stack":130,"./models.voxel":131}],129:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _models=require("../models/models.base");var _models2=_interopRequireDefault(_models);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var ModelsSeries=function(_ModelsBase){_inherits(ModelsSeries,_ModelsBase);function ModelsSeries(){_classCallCheck(this,ModelsSeries);var _this=_possibleConstructorReturn(this,(ModelsSeries.__proto__||Object.getPrototypeOf(ModelsSeries)).call(this));_this._concatenationUID=-1;_this._seriesInstanceUID=-1;_this._transferSyntaxUID="";_this._seriesNumber=-1;_this._seriesDescription="";_this._seriesDate="";_this._studyDescription="";_this._studyDate="";_this._accessionNumber=-1;_this._modality="Modality not set";_this._dimensionIndexSequence=[];_this._numberOfFrames=0;_this._numberOfChannels=1;_this._patientID="";_this._patientName="";_this._patientAge="";_this._patientBirthdate="";_this._patientSex="";_this._segmentationType=null;_this._segmentationSegments=[];_this._stack=[];return _this}_createClass(ModelsSeries,[{key:"validate",value:function validate(model){if(!(_get(ModelsSeries.prototype.__proto__||Object.getPrototypeOf(ModelsSeries.prototype),"validate",this).call(this,model)&&typeof model.mergeSeries==="function"&&model.hasOwnProperty("_seriesInstanceUID")&&model.hasOwnProperty("_numberOfFrames")&&model.hasOwnProperty("_numberOfChannels")&&model.hasOwnProperty("_stack")&&typeof model._stack!=="undefined"&&Array===model._stack.constructor)){return false}return true}},{key:"merge",value:function merge(series){if(!this.validate(series)){return false}if(this._seriesInstanceUID===series.seriesInstanceUID){return this.mergeModels(this._stack,series.stack)}else{return false}}},{key:"mergeSeries",value:function mergeSeries(target){var seriesContainer=[this];this.mergeModels(seriesContainer,target);return seriesContainer}},{key:"seriesInstanceUID",set:function set(seriesInstanceUID){this._seriesInstanceUID=seriesInstanceUID},get:function get(){return this._seriesInstanceUID}},{key:"transferSyntaxUID",set:function set(transferSyntaxUID){this._transferSyntaxUID=transferSyntaxUID},get:function get(){return this._transferSyntaxUID}},{key:"transferSyntaxUIDLabel",get:function get(){switch(this._transferSyntaxUID){case"1.2.840.10008.1.2.4.90":return"JPEG 2000 Lossless";case"1.2.840.10008.1.2.4.91":return"JPEG 2000 Lossy";case"1.2.840.10008.1.2.4.57":return"JPEG Lossless, Nonhierarchical (Processes 14)";case"1.2.840.10008.1.2.4.70":return"JPEG Lossless, Nonhierarchical (Processes 14 [Selection 1])";case"1.2.840.10008.1.2.4.50":return"JPEG Baseline lossy process 1 (8 bit)";case"1.2.840.10008.1.2.4.51":return"JPEG Baseline lossy process 2 & 4 (12 bit)";case"1.2.840.10008.1.2":return"Implicit VR Little Endian";case"1.2.840.10008.1.2.1":return"Explicit VR Little Endian";case"1.2.840.10008.1.2.2":return"Explicit VR Big Endian";default:return"Unknown transfersyntax: "+this._transferSyntaxUID}}},{key:"studyDate",set:function set(studyDate){this._studyDate=studyDate},get:function get(){return this._studyDate}},{key:"studyDescription",set:function set(studyDescription){this._studyDescription=studyDescription},get:function get(){return this._studyDescription}},{key:"seriesDate",set:function set(seriesDate){this._seriesDate=seriesDate},get:function get(){return this._seriesDate}},{key:"seriesDescription",set:function set(seriesDescription){this._seriesDescription=seriesDescription},get:function get(){return this._seriesDescription}},{key:"patientID",set:function set(patientID){this._patientID=patientID},get:function get(){return this._patientID}},{key:"patientName",set:function set(patientName){this._patientName=patientName},get:function get(){return this._patientName}},{key:"patientAge",set:function set(patientAge){this._patientAge=patientAge},get:function get(){return this._patientAge}},{key:"patientBirthdate",set:function set(patientBirthdate){this._patientBirthdate=patientBirthdate},get:function get(){return this._patientBirthdate}},{key:"patientSex",set:function set(patientSex){this._patientSex=patientSex},get:function get(){return this._patientSex}},{key:"numberOfFrames",set:function set(numberOfFrames){this._numberOfFrames=numberOfFrames},get:function get(){return this._numberOfFrames}},{key:"numberOfChannels",set:function set(numberOfChannels){this._numberOfChannels=numberOfChannels},get:function get(){return this._numberOfChannels}},{key:"stack",set:function set(stack){this._stack=stack},get:function get(){return this._stack}},{key:"modality",set:function set(modality){this._modality=modality},get:function get(){return this._modality}},{key:"segmentationType",set:function set(segmentationType){this._segmentationType=segmentationType},get:function get(){return this._segmentationType}},{key:"segmentationSegments",set:function set(segmentationSegments){this._segmentationSegments=segmentationSegments},get:function get(){return this._segmentationSegments}}]);return ModelsSeries}(_models2.default);exports.default=ModelsSeries},{"../models/models.base":126}],130:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");var _core=require("../core/core.colors");var _core2=_interopRequireDefault(_core);var _core3=require("../core/core.utils");var _core4=_interopRequireDefault(_core3);var _models=require("../models/models.base");var _models2=_interopRequireDefault(_models);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i]}return arr2}else{return Array.from(arr)}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var binaryString=require("math-float32-to-binary-string");var ModelsStack=function(_ModelsBase){_inherits(ModelsStack,_ModelsBase);function ModelsStack(){_classCallCheck(this,ModelsStack);var _this=_possibleConstructorReturn(this,(ModelsStack.__proto__||Object.getPrototypeOf(ModelsStack)).call(this));_this._uid=null;_this._stackID=-1;_this._frame=[];_this._numberOfFrames=0;_this._rows=0;_this._columns=0;_this._numberOfChannels=1;_this._bitsAllocated=8;_this._pixelType=0;_this._pixelRepresentation=0;_this._textureSize=4096;_this._nbTextures=7;_this._rawData=[];_this._windowCenter=0;_this._windowWidth=0;_this._rescaleSlope=1;_this._rescaleIntercept=0;_this._minMax=[Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY];_this._regMatrix=new _three.Matrix4;_this._ijk2LPS=null;_this._lps2IJK=null;_this._aabb2LPS=null;_this._lps2AABB=null;_this._dimensionsIJK=null;_this._halfDimensionsIJK=null

_this._spacing=new _three.Vector3(1,1,1);_this._spacingBetweenSlices=0;_this._sliceThickness=0;_this._origin=null;_this._rightHanded=true;_this._xCosine=new _three.Vector3(1,0,0);_this._yCosine=new _three.Vector3(0,1,0);_this._zCosine=new _three.Vector3(0,0,1);_this._prepared=false;_this._packed=false;_this._packedPerPixel=1;_this._modality="Modality not set";_this._segmentationType=null;_this._segmentationSegments=[];_this._segmentationDefaultColor=[63,174,128];_this._frameSegment=[];_this._segmentationLUT=[];_this._segmentationLUTO=[];_this._invert=false;return _this}_createClass(ModelsStack,[{key
"prepareSegmentation",value:function prepareSegmentation(){this._frameSegment=this._frame;var mergedFrames=[];this.computeCosines();this._frame.map(this._computeDistanceArrayMap.bind(null,this._zCosine));this._frame.sort(this._sortDistanceArraySort);var prevIndex=-1;for(var i=0;i<this._frame.length;i++){if(!mergedFrames[prevIndex]||mergedFrames[prevIndex]._dist!=this._frame[i]._dist){mergedFrames.push(this._frame[i]);prevIndex++;for(var k=0;k<mergedFrames[prevIndex]._rows*mergedFrames[prevIndex]._columns;k++){mergedFrames[prevIndex]._pixelData[k]*=this._frame[i]._referencedSegmentNumber}}else{for(var _k=0;_k<mergedFrames[prevIndex]._rows*mergedFrames[prevIndex]._columns;_k++){mergedFrames[prevIndex]._pixelData[_k]+=this._frame[i].pixelData[_k]*this._frame[i]._referencedSegmentNumber}}mergedFrames[prevIndex].minMax=_core4.default.minMax(mergedFrames[prevIndex]._pixelData)}var dict={};var max=0;for(var _i=0;_i<this._segmentationSegments.length;_i++){max=Math.max(max,parseInt(this._segmentationSegments[_i].segmentNumber,10));var color=this._segmentationSegments[_i].recommendedDisplayCIELab;if(color===null){dict[this._segmentationSegments[_i].segmentNumber]=this._segmentationDefaultColor}else{dict[this._segmentationSegments[_i].segmentNumber]=_core2.default.cielab2RGB.apply(_core2.default,_toConsumableArray(color))}}for(var _i2=0;_i2<=max;_i2++){var index=_i2/max;var opacity=_i2?1:0;var rgb=[0,0,0];if(dict.hasOwnProperty(_i2.toString())){rgb=dict[_i2.toString()]}rgb[0]/=255;rgb[1]/=255;rgb[2]/=255;this._segmentationLUT.push([index].concat(_toConsumableArray(rgb)));this._segmentationLUTO.push([index,opacity])}this._frame=mergedFrames}},{key:"prepare",value:function prepare(){if(this._modality==="SEG"){this.prepareSegmentation()}if(this._frame&&this._frame.length>0){this._numberOfFrames=this._frame.length}else{window.console.log("_frame doesn't contain anything....");window.console.log(this._frame);return false}this._rows=this._frame[0].rows;this._columns=this._frame[0].columns;this._dimensionsIJK=new _three.Vector3(this._columns,this._rows,this._numberOfFrames);this._halfDimensionsIJK=new _three.Vector3(this._dimensionsIJK.x/2,this._dimensionsIJK.y/2,this._dimensionsIJK.z/2);this._spacingBetweenSlices=this._frame[0].spacingBetweenSlices;this._sliceThickness=this._frame[0].sliceThickness;this.computeCosines();this.orderFrames();this.computeSpacing();if(!this._frame[0].imagePosition){this._frame[0].imagePosition=[0,0,0]}if(!this._frame[0].imageOrientation){this._frame[0].imageOrientation=[1,0,0,0,1,0]}this._origin=this._arrayToVector3(this._frame[0].imagePosition,0);this.computeIJK2LPS();this.computeLPS2AABB();this._rescaleSlope=this._frame[0].rescaleSlope||1;this._rescaleIntercept=this._frame[0].rescaleIntercept||0;this.computeMinMaxIntensities();this._minMax[0]=_core4.default.rescaleSlopeIntercept(this._minMax[0],this._rescaleSlope,this._rescaleIntercept);this._minMax[1]=_core4.default.rescaleSlopeIntercept(this._minMax[1],this._rescaleSlope,this._rescaleIntercept);var width=this._frame[0].windowWidth*this._rescaleSlope||this._minMax[1]-this._minMax[0];this._windowWidth=width+this._rescaleIntercept;var center=this._frame[0].windowCenter*this._rescaleSlope||this._minMax[0]+width/2;this._windowCenter=center+this._rescaleIntercept;this._bitsAllocated=this._frame[0].bitsAllocated;this._prepared=true}},{key:"packEchos",value:function packEchos(){var echos=4;var packedEcho=[];for(var i=0;i<this._frame.length;i+=echos){var frame=this._frame[i];for(var k=0;k<this._rows*this._columns;k++){for(var j=1;j<echos;j++){frame.pixelData[k]+=this._frame[i+j].pixelData[k]}frame.pixelData[k]/=echos}packedEcho.push(frame)}this._frame=packedEcho;this._numberOfFrames=this._frame.length;this._dimensionsIJK=new _three.Vector3(this._columns,this._rows,this._numberOfFrames);this._halfDimensionsIJK=new _three.Vector3(this._dimensionsIJK.x/2,this._dimensionsIJK.y/2,this._dimensionsIJK.z/2)}},{key:"computeCosines",value:function computeCosines(){if(this._frame&&this._frame[0]){var cosines=this._frame[0].cosines();this._xCosine=cosines[0];this._yCosine=cosines[1];this._zCosine=cosines[2]}}},{key:"orderFrames",value:function orderFrames(){if(this._frame[0].dimensionIndexValues){this._frame.sort(this._orderFrameOnDimensionIndicesArraySort)}else if(this._frame[0].imagePosition&&this._frame[0].imageOrientation&&this._frame[1]&&this._frame[1].imagePosition&&this._frame[1].imageOrientation&&this._frame[0].imagePosition.join()!==this._frame[1].imagePosition.join()){this._frame.map(this._computeDistanceArrayMap.bind(null,this._zCosine));this._frame.sort(this._sortDistanceArraySort)}else if(this._frame[0].instanceNumber!==null&&this._frame[1]&&this._frame[1].instanceNumber!==null&&this._frame[0].instanceNumber!==this._frame[1].instanceNumber){this._frame.sort(this._sortInstanceNumberArraySort)}else if(this._frame[0].sopInstanceUID&&this._frame[1]&&this._frame[1].sopInstanceUID&&this._frame[0].sopInstanceUID!==this._frame[1].sopInstanceUID){this._frame.sort(this._sortSopInstanceUIDArraySort)}else{window.console.log("do not know how to order the frames...")}}},{key:"computeSpacing",value:function computeSpacing(){this.xySpacing();this.zSpacing()}},{key:"zSpacing",value:function zSpacing(){if(this._numberOfFrames>1){if(this._frame[0].pixelSpacing&&this._frame[0].pixelSpacing[2]){this._spacing.z=this._frame[0].pixelSpacing[2]}else{this._frame.map(this._computeDistanceArrayMap.bind(null,this._zCosine));if(this._frame[1].dist!==this._frame[0].dist){this._frame.sort(this._sortDistanceArraySort);this._spacing.z=this._frame[1].dist-this._frame[0].dist}else if(this._spacingBetweenSlices){this._spacing.z=this._spacingBetweenSlices}else if(this._frame[0].sliceThickness){this._spacing.z=this._frame[0].sliceThickness}}}if(this._spacing.z===0){this._spacing.z=1}}},{key:"xySpacing",value:function xySpacing(){if(this._frame&&this._frame[0]){var spacingXY=this._frame[0].spacingXY();this._spacing.x=spacingXY[0];this._spacing.y=spacingXY[1]}}},{key:"computeMinMaxIntensities",value:function computeMinMaxIntensities(){for(var i=0;i<this._frame.length;i++){var min=this._frame[i].minMax[0];if(!Number.isNaN(min)){this._minMax[0]=Math.min(this._minMax[0],min)}var max=this._frame[i].minMax[1];if(!Number.isNaN(max)){this._minMax[1]=Math.max(this._minMax[1],max)}}}},{key:"computeIJK2LPS",value:function computeIJK2LPS(){this._ijk2LPS=_core4.default.ijk2LPS(this._xCosine,this._yCosine,this._zCosine,this._spacing,this._origin,this._regMatrix);this._lps2IJK=new _three.Matrix4;this._lps2IJK.getInverse(this._ijk2LPS)}},{key:"computeLPS2AABB",value:function computeLPS2AABB(){this._aabb2LPS=_core4.default.aabb2LPS(this._xCosine,this._yCosine,this._zCosine,this._origin);this._lps2AABB=new _three.Matrix4;this._lps2AABB.getInverse(this._aabb2LPS)}},{key:"merge",value:function merge(stack){if(this._stackID===stack.stackID){return this.mergeModels(this._frame,stack.frame)}else{return false}}},{key:"pack",value:function pack(){var nbVoxels=this._dimensionsIJK.x*this._dimensionsIJK.y*this._dimensionsIJK.z;if(this._bitsAllocated===16&&this._numberOfChannels===1){this._packedPerPixel=2}var textureDimension=this._textureSize*this._textureSize;var requiredTextures=Math.ceil(nbVoxels/(textureDimension*this._packedPerPixel));var voxelIndexStart=0;var voxelIndexStop=this._packedPerPixel*textureDimension;if(voxelIndexStop>nbVoxels){voxelIndexStop=nbVoxels}for(var ii=0;ii<requiredTextures;ii++){var packed=this._packTo8Bits(this._numberOfChannels,this._frame,this._textureSize,voxelIndexStart,voxelIndexStop);this._textureType=packed.textureType;this._rawData.push(packed.data);voxelIndexStart+=this._packedPerPixel*textureDimension;voxelIndexStop+=this._packedPerPixel*textureDimension;if(voxelIndexStop>nbVoxels){voxelIndexStop=nbVoxels}}this._packed=true}},{key:"_packTo8Bits",value:function _packTo8Bits(channels,frame,textureSize,startVoxel,stopVoxel){var packed={textureType:null,data:null};var bitsAllocated=frame[0].bitsAllocated;var pixelType=frame[0].pixelType;var offset=0;if(this._minMax[0]<0){offset-=this._minMax[0]}var packIndex=0;var frameIndex=0;var inFrameIndex=0;var frameDimension=frame[0].rows*frame[0].columns;if(bitsAllocated===8&&channels===1||bitsAllocated===1){var data=new Uint8Array(textureSize*textureSize*1);for(var i=startVoxel;i<stopVoxel;i++){frameIndex=~~(i/frameDimension);inFrameIndex=i%frameDimension;var raw=frame[frameIndex].pixelData[inFrameIndex]+=offset;if(!Number.isNaN(raw)){data[packIndex]=raw}packIndex++}packed.textureType=THREE.LuminanceFormat;packed.data=data}else if(bitsAllocated===16&&channels===1){var _data=new Uint8Array(textureSize*textureSize*4);var coordinate=0;var channelOffset=0;for(var _i3=startVoxel;_i3<stopVoxel;_i3++){frameIndex=~~(_i3/frameDimension);inFrameIndex=_i3%frameDimension;var _raw=frame[frameIndex].pixelData[inFrameIndex]+offset;if(!Number.isNaN(_raw)){_data[4*coordinate+2*channelOffset]=_raw&255;_data[4*coordinate+2*channelOffset+1]=_raw>>>8&255}packIndex++;coordinate=Math.floor(packIndex/2);channelOffset=packIndex%2}packed.textureType=THREE.RGBAFormat;packed.data=_data}else if(bitsAllocated===32&&channels===1&&pixelType===0){var _data2=new Uint8Array(textureSize*textureSize*4);for(var _i4=startVoxel;_i4<stopVoxel;_i4++){frameIndex=~~(_i4/frameDimension);inFrameIndex=_i4%frameDimension;var _raw2=frame[frameIndex].pixelData[inFrameIndex]+offset;if(!Number.isNaN(_raw2)){_data2[4*packIndex]=_raw2&255;_data2[4*packIndex+1]=_raw2>>>8&255;_data2[4*packIndex+2]=_raw2>>>16&255;_data2[4*packIndex+3]=_raw2>>>24&255}packIndex++}packed.textureType=THREE.RGBAFormat;packed.data=_data2}else if(bitsAllocated===32&&channels===1&&pixelType===1){var _data3=new Uint8Array(textureSize*textureSize*4);for(var _i5=startVoxel;_i5<stopVoxel;_i5++){frameIndex=~~(_i5/frameDimension);inFrameIndex=_i5%frameDimension;var _raw3=frame[frameIndex].pixelData[inFrameIndex]+offset;if(!Number.isNaN(_raw3)){var bitString=binaryString(_raw3);var bitStringArray=bitString.match(/.{1,8}/g);_data3[4*packIndex]=parseInt(bitStringArray[0],2);_data3[4*packIndex+1]=parseInt(bitStringArray[1],2);_data3[4*packIndex+2]=parseInt(bitStringArray[2],2);_data3[4*packIndex+3]=parseInt(bitStringArray[3],2)}packIndex++}packed.textureType=THREE.RGBAFormat;packed.data=_data3}else if(bitsAllocated===8&&channels===3){var _data4=new Uint8Array(textureSize*textureSize*3);for(var _i6=startVoxel;_i6<stopVoxel;_i6++){frameIndex=~~(_i6/frameDimension);inFrameIndex=_i6%frameDimension;_data4[3*packIndex]=frame[frameIndex].pixelData[3*inFrameIndex];_data4[3*packIndex+1]=frame[frameIndex].pixelData[3*inFrameIndex+1];_data4[3*packIndex+2]=frame[frameIndex].pixelData[3*inFrameIndex+2];packIndex++}packed.textureType=THREE.RGBFormat;packed.data=_data4}return packed}},{key:"worldCenter",value:function worldCenter(){var center=this._halfDimensionsIJK.clone().addScalar(-.5).applyMatrix4(this._ijk2LPS);return center}},{key:"worldBoundingBox",value:function worldBoundingBox(){var bbox=[Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY];var dims=this._dimensionsIJK;for(var i=0;i<=dims.x;i+=dims.x){for(var j=0;j<=dims.y;j+=dims.y){for(var k=0;k<=dims.z;k+=dims.z){var world=new _three.Vector3(i,j,k).applyMatrix4(this._ijk2LPS);bbox=[Math.min(bbox[0],world.x),Math.max(bbox[1],world.x),Math.min(bbox[2],world.y),Math.max(bbox[3],world.y),Math.min(bbox[4],world.z),Math.max(bbox[5],world.z)]}}}return bbox}},{key:"AABBox",value:function AABBox(){var world0=(new _three.Vector3).addScalar(-.5).applyMatrix4(this._ijk2LPS).applyMatrix4(this._lps2AABB);var world7=this._dimensionsIJK.clone().addScalar(-.5).applyMatrix4(this._ijk2LPS).applyMatrix4(this._lps2AABB);var minBBox=new _three.Vector3(Math.abs(world0.x-world7.x),Math.abs(world0.y-world7.y),Math.abs(world0.z-world7.z));return minBBox}},{key:"centerAABBox",value:function centerAABBox(){var centerBBox=this.worldCenter();centerBBox.applyMatrix4(this._lps2AABB);return centerBBox}},{key:"_arrayToVector3",value:function _arrayToVector3(array,index){return new _three.Vector3(array[index],array[index+1],array[index+2])}},{key:"_orderFrameOnDimensionIndicesArraySort",value:function _orderFrameOnDimensionIndicesArraySort(a,b){if("dimensionIndexValues"in a&&Object.prototype.toString.call(a.dimensionIndexValues)==="[object Array]"&&"dimensionIndexValues"in b&&Object.prototype.toString.call(b.dimensionIndexValues)==="[object Array]"){for(var i=0;i<a.dimensionIndexValues.length;i++){if(parseInt(a.dimensionIndexValues[i],10)>parseInt(b.dimensionIndexValues[i],10)){return 1}if(parseInt(a.dimensionIndexValues[i],10)<parseInt(b.dimensionIndexValues[i],10)){return-1}}}else{window.console.log("One of the frames doesn't have a dimensionIndexValues array.");window.console.log(a);window.console.log(b)}return 0}},{key:"_computeDistanceArrayMap",value:function _computeDistanceArrayMap(normal,frame){frame.dist=frame.imagePosition[0]*normal.x+frame.imagePosition[1]*normal.y+frame.imagePosition[2]*normal.z;return frame}},{key:"_sortDistanceArraySort",value:function _sortDistanceArraySort(a,b){return a.dist-b.dist}},{key:"_sortInstanceNumberArraySort",value:function _sortInstanceNumberArraySort(a,b){return a.instanceNumber-b.instanceNumber}},{key:"_sortSopInstanceUIDArraySort",value:function _sortSopInstanceUIDArraySort(a,b){return a.sopInstanceUID-b.sopInstanceUID}},{key:"numberOfChannels",set:function set(numberOfChannels){this._numberOfChannels=numberOfChannels},get:function get(){return this._numberOfChannels}},{key:"frame",set:function set(frame){this._frame=frame},get:function get(){return this._frame}},{key:"prepared",set:function set(prepared){this._prepared=prepared},get:function get(){return this._prepared}},{key:"packed",set:function set(packed){this._packed=packed},get:function get(){return this._packed}},{key:"packedPerPixel",set:function set(packedPerPixel){this._packedPerPixel=packedPerPixel},get:function get(){return this._packedPerPixel}},{key:"dimensionsIJK",set:function set(dimensionsIJK){this._dimensionsIJK=dimensionsIJK},get:function get(){return this._dimensionsIJK}},{key:"halfDimensionsIJK",set:function set(halfDimensionsIJK){this._halfDimensionsIJK=halfDimensionsIJK},get:function get(){return this._halfDimensionsIJK}},{key:"regMatrix",set:function set(regMatrix){this._regMatrix=regMatrix},get:function get(){return this._regMatrix}},{key:"ijk2LPS",set:function set(ijk2LPS){this._ijk2LPS=ijk2LPS},get:function get(){return this._ijk2LPS}},{key:"lps2IJK",set:function set(lps2IJK){this._lps2IJK=lps2IJK},get:function get(){return this._lps2IJK}},{key:"lps2AABB",set:function set(lps2AABB){this._lps2AABB=lps2AABB},get:function get(){return this._lps2AABB}},{key:"textureSize",set:function set(textureSize){this._textureSize=textureSize},get:function get(){return this._textureSize}},{key:"textureType",set:function set(textureType){this._textureType=textureType},get:function get(){return this._textureType}},{key:"bitsAllocated",set:function set(bitsAllocated){this._bitsAllocated=bitsAllocated},get:function get(){return this._bitsAllocated}},{key:"rawData",set:function set(rawData){this._rawData=rawData},get:function get(){return this._rawData}},{key:"windowWidth",get:function get(){return this._windowWidth},set:function set(windowWidth){this._windowWidth=windowWidth}},{key:"windowCenter",get:function get(){return this._windowCenter},set:function set(windowCenter){this._windowCenter=windowCenter}},{key:"rescaleSlope",get:function get(){return this._rescaleSlope},set:function set(rescaleSlope){this._rescaleSlope=rescaleSlope}},{key:"rescaleIntercept",get:function get(){return this._rescaleIntercept},set:function set(rescaleIntercept){this._rescaleIntercept=rescaleIntercept}},{key:"xCosine",get:function get(){return this._xCosine},set:function set(xCosine){this._xCosine=xCosine}},{key:"yCosine",get:function get(){return this._yCosine},set:function set(yCosine){this._yCosine=yCosine}},{key:"zCosine",get:function get(){return this._zCosine},set:function set(zCosine){this._zCosine=zCosine}},{key:"minMax",get:function get(){return this._minMax},set:function set(minMax){this._minMax=minMax}},{key:"stackID",get:function get(){return this._stackID},set:function set(stackID){this._stackID=stackID}},{key:"pixelType",get:function get(){return this._pixelType},set:function set(pixelType){this._pixelType=pixelType}},{key:"pixelRepresentation",get:function get(){return this._pixelRepresentation},set:function set(pixelRepresentation){this._pixelRepresentation=pixelRepresentation}},{key:"invert",set:function set(invert){this._invert=invert},get:function get(){return this._invert}},{key:"modality",set:function set(modality){this._modality=modality},get:function get(){return this._modality}},{key:"rightHanded",get:function get(){return this._rightHanded},set:function set(rightHanded){this._rightHanded=rightHanded}},{key:"spacingBetweenSlices",get:function get(){return this._spacingBetweenSlices},set:function set(spacingBetweenSlices){this._spacingBetweenSlices=spacingBetweenSlices}},{key:"segmentationSegments",set:function set(segmentationSegments){this._segmentationSegments=segmentationSegments},get:function get(){return this._segmentationSegments}},{key:"segmentationType",set:function set(segmentationType){this._segmentationType=segmentationType},get:function get(){return this._segmentationType}},{key:"segmentationLUT",set:function set(segmentationLUT){this._segmentationLUT=segmentationLUT},get:function get(){return this._segmentationLUT}},{key:"segmentationLUTO",set:function set(segmentationLUTO){this._segmentationLUTO=segmentationLUTO},get:function get(){return this._segmentationLUTO}}],[{key:"indexInDimensions",value:function indexInDimensions(index,dimensions){if(index.x>=0&&index.y>=0&&index.z>=0&&index.x<dimensions.x&&index.y<dimensions.y&&index.z<dimensions.z){return true}return false}},{key:"value",value:function value(stack,coordinate){console.warn("models.stack.value is deprecated.\n Please use core.utils.value instead.");return _core4.default.value(stack,coordinate)}},{key:"valueRescaleSlopeIntercept",value:function valueRescaleSlopeIntercept(value,slope,intercept){console.warn("models.stack.valueRescaleSlopeIntercept is deprecated.\n Please use core.utils.rescaleSlopeIntercept instead.");return _core4.default.rescaleSlopeIntercept(value,slope,intercept)}},{key:"worldToData",value:function worldToData(stack,worldCoordinates){console.warn("models.stack.worldToData is deprecated.\n Please use core.utils.worldToData instead.");return _core4.default.worldToData(stack._lps2IJK,worldCoordinates)}}]);return ModelsStack}(_models2.default);exports.default=ModelsStack},{"../core/core.colors":102,"../core/core.utils":106,"../models/models.base":126,"math-float32-to-binary-string":43,three:81}],131:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ModelsVoxel=function(){function ModelsVoxel(){_classCallCheck(this,ModelsVoxel);this._id=-1;this._worldCoordinates=null;this._dataCoordinates=null;this._screenCoordinates=null;this._value=null}_createClass(ModelsVoxel,[{key:"worldCoordinates",set:function set(worldCoordinates){this._worldCoordinates=worldCoordinates},get:function get(){return this._worldCoordinates}},{key:"dataCoordinates",set:function set(dataCoordinates){this._dataCoordinates=dataCoordinates},get:function get(){return this._dataCoordinates}},{key:"screenCoordinates",set:function set(screenCoordinates){this._screenCoordinates=screenCoordinates},get:function get(){return this._screenCoordinates}},{key:"value",set:function set(value){this._value=value},get:function get(){return this._value}},{key:"id",set:function set(id){this._id=id},get:function get(){return this._id}}]);return ModelsVoxel}();exports.default=ModelsVoxel},{}],132:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _parsers=require("./parsers.volume");var _parsers2=_interopRequireDefault(_parsers);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var DicomParser=require("dicom-parser");var Jpeg=require("jpeg-lossless-decoder-js");var JpegBaseline=require("../../external/scripts/jpeg");var Jpx=require("../../external/scripts/jpx");var ParsersDicom=function(_ParsersVolume){_inherits(ParsersDicom,_ParsersVolume);function ParsersDicom(data,id){_classCallCheck(this,ParsersDicom);var _this=_possibleConstructorReturn(this,(ParsersDicom.__proto__||Object.getPrototypeOf(ParsersDicom)).call(this));_this._id=id;_this._arrayBuffer=data.buffer;var byteArray=new Uint8Array(_this._arrayBuffer);_this._dataSet=null;try{_this._dataSet=DicomParser.parseDicom(byteArray)}catch(e){window.console.log(e);throw"parsers.dicom could not parse the file"}return _this}_createClass(ParsersDicom,[{key:"seriesInstanceUID",value:function seriesInstanceUID(){return this._dataSet.string("x0020000e")}},{key:"studyInstanceUID",value:function studyInstanceUID(){return this._dataSet.string("x0020000d")}},{key:"modality",value:function modality(){return this._dataSet.string("x00080060")}},{key:"segmentationType",value:function segmentationType(){return this._dataSet.string("x00620001")}},{key:"segmentationSegments",value:function segmentationSegments(){var segmentationSegments=[];var segmentSequence=this._dataSet.elements.x00620002;if(!segmentSequence){return segmentationSegments}for(var i=0;i<segmentSequence.items.length;i++){var recommendedDisplayCIELab=this._recommendedDisplayCIELab(segmentSequence.items[i]);var segmentationCode=this._segmentationCode(segmentSequence.items[i]);var segmentNumber=segmentSequence.items[i].dataSet.uint16("x00620004");var segmentLabel=segmentSequence.items[i].dataSet.string("x00620005");var segmentAlgorithmType=segmentSequence.items[i].dataSet.string("x00620008");segmentationSegments.push({recommendedDisplayCIELab:recommendedDisplayCIELab,segmentationCodeDesignator:segmentationCode["segmentationCodeDesignator"],segmentationCodeValue:segmentationCode["segmentationCodeValue"],segmentationCodeMeaning:segmentationCode["segmentationCodeMeaning"],segmentNumber:segmentNumber,segmentLabel:segmentLabel,segmentAlgorithmType:segmentAlgorithmType})}return segmentationSegments}},{key:"_segmentationCode",value:function _segmentationCode(segment){var segmentationCodeDesignator="unknown";var segmentationCodeValue="unknown";var segmentationCodeMeaning="unknown";var element=segment.dataSet.elements.x00082218;if(element&&element.items&&element.items.length>0){segmentationCodeDesignator=element.items[0].dataSet.string("x00080102");segmentationCodeValue=element.items[0].dataSet.string("x00080100");segmentationCodeMeaning=element.items[0].dataSet.string("x00080104")}return{segmentationCodeDesignator:segmentationCodeDesignator,segmentationCodeValue:segmentationCodeValue,segmentationCodeMeaning:segmentationCodeMeaning}}},{key:"_recommendedDisplayCIELab",value:function _recommendedDisplayCIELab(segment){if(!segment.dataSet.elements.x0062000d){return null}var offset=segment.dataSet.elements.x0062000d.dataOffset;var length=segment.dataSet.elements.x0062000d.length;var byteArray=segment.dataSet.byteArray.slice(offset,offset+length);var CIELabScaled=new Uint16Array(length/2);for(var i=0;i<length/2;i++){CIELabScaled[i]=(byteArray[2*i+1]<<8)+byteArray[2*i]}var CIELabNormalized=[CIELabScaled[0]/65535*100,CIELabScaled[1]/65535*255-128,CIELabScaled[2]/65535*255-128];return CIELabNormalized}},{key:"sopInstanceUID",value:function sopInstanceUID(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var sopInstanceUID=this._findStringEverywhere("x2005140f","x00080018",frameIndex);return sopInstanceUID}},{key:"transferSyntaxUID",value:function transferSyntaxUID(){return this._dataSet.string("x00020010")}},{key:"studyDate",value:function studyDate(){return this._dataSet.string("x00080020")}},{key:"studyDescription",value:function studyDescription(){return this._dataSet.string("x00081030")}},{key:"seriesDate",value:function seriesDate(){return this._dataSet.string("x00080021")}},{key:"seriesDescription",value:function seriesDescription(){return this._dataSet.string("x0008103e")}},{key:"patientName",value:function patientName(){return this._dataSet.string("x00100010")}},{key:"patientID",value:function patientID(){return this._dataSet.string("x00100020")}},{key:"patientBirthdate",value:function patientBirthdate(){return this._dataSet.string("x00100030")}},{key:"patientSex",value:function patientSex(){return this._dataSet.string("x00100040")}},{key:"patientAge",value:function patientAge(){return this._dataSet.string("x00101010")}},{key:"photometricInterpretation",value:function photometricInterpretation(){return this._dataSet.string("x00280004")}},{key:"planarConfiguration",value:function planarConfiguration(){var planarConfiguration=this._dataSet.uint16("x00280006");if(typeof planarConfiguration==="undefined"){planarConfiguration=null}return planarConfiguration}},{key:"samplesPerPixel",value:function samplesPerPixel(){return this._dataSet.uint16("x00280002")}},{key:"numberOfFrames",value:function numberOfFrames(){var numberOfFrames=this._dataSet.intString("x00280008");if(typeof numberOfFrames==="undefined"){numberOfFrames=null}return numberOfFrames}},{key:"numberOfChannels",value:function numberOfChannels(){var numberOfChannels=1;var photometricInterpretation=this.photometricInterpretation();if(!(photometricInterpretation!=="RGB"&&photometricInterpretation!=="PALETTE COLOR"&&photometricInterpretation!=="YBR_FULL"&&photometricInterpretation!=="YBR_FULL_422"&&photometricInterpretation!=="YBR_PARTIAL_422"&&photometricInterpretation!=="YBR_PARTIAL_420"&&photometricInterpretation!=="YBR_RCT")){numberOfChannels=3}return numberOfChannels}},{key:"invert",value:function invert(){var photometricInterpretation=this.photometricInterpretation();return photometricInterpretation==="MONOCHROME1"?true:false}},{key:"imageOrientation",value:function imageOrientation(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var imageOrientation=this._findStringEverywhere("x00209116","x00200037",frameIndex);if(imageOrientation){imageOrientation=imageOrientation.split("\\").map(Number)}return imageOrientation}},{key:"referencedSegmentNumber",value:function referencedSegmentNumber(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var referencedSegmentNumber=-1;var referencedSegmentNumberElement=this._findInGroupSequence("x52009230","x0062000a",frameIndex);if(referencedSegmentNumberElement!==null){referencedSegmentNumber=referencedSegmentNumberElement.uint16("x0062000b")}return referencedSegmentNumber}},{key:"pixelAspectRatio",value:function pixelAspectRatio(){var pixelAspectRatio=[this._dataSet.intString("x00280034",0),this._dataSet.intString("x00280034",1)];if(typeof pixelAspectRatio[0]==="undefined"){pixelAspectRatio=null}return pixelAspectRatio}},{key:"imagePosition",value:function imagePosition(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var imagePosition=this._findStringEverywhere("x00209113","x00200032",frameIndex);if(imagePosition){imagePosition=imagePosition.split("\\").map(Number)}return imagePosition}},{key:"instanceNumber",value:function instanceNumber(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var instanceNumber=null;var perFrameFunctionnalGroupSequence=this._dataSet.elements.x52009230;if(typeof perFrameFunctionnalGroupSequence!=="undefined"){if(perFrameFunctionnalGroupSequence.items[frameIndex].dataSet.elements.x2005140f){var planeOrientationSequence=perFrameFunctionnalGroupSequence.items[frameIndex].dataSet.elements.x2005140f.items[0].dataSet;instanceNumber=planeOrientationSequence.intString("x00200013")}else{instanceNumber=this._dataSet.intString("x00200013");if(typeof instanceNumber==="undefined"){instanceNumber=null}}}else{instanceNumber=this._dataSet.intString("x00200013");if(typeof instanceNumber==="undefined"){instanceNumber=null}}return instanceNumber}},{key:"pixelSpacing",value:function pixelSpacing(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var pixelSpacing=this._findStringEverywhere("x00289110","x00280030",frameIndex);if(pixelSpacing){pixelSpacing=pixelSpacing.split("\\").map(Number)}return pixelSpacing}},{key:"rows",value:function rows(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var rows=this._dataSet.uint16("x00280010");if(typeof rows==="undefined"){rows=null}return rows}},{key:"columns",value:function columns(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var columns=this._dataSet.uint16("x00280011");if(typeof columns==="undefined"){columns=null}return columns}},{key:"pixelType",value:function pixelType(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return 0}},{key:"pixelRepresentation",value:function pixelRepresentation(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0
var pixelRepresentation=this._dataSet.uint16("x00280103");return pixelRepresentation}},{key
"bitsAllocated",value:function bitsAllocated(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var bitsAllocated=this._dataSet.uint16("x00280100");return bitsAllocated}},{key:"highBit",value:function highBit(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var highBit=this._dataSet.uint16("x00280102");return highBit}},{key:"rescaleIntercept",value:function rescaleIntercept(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._findFloatStringInFrameGroupSequence("x00289145","x00281052",frameIndex)}},{key:"rescaleSlope",value:function rescaleSlope(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._findFloatStringInFrameGroupSequence("x00289145","x00281053",frameIndex)}},{key:"windowCenter",value:function windowCenter(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._findFloatStringInFrameGroupSequence("x00289132","x00281050",frameIndex)}},{key:"windowWidth",value:function windowWidth(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._findFloatStringInFrameGroupSequence("x00289132","x00281051",frameIndex)}},{key:"sliceThickness",value:function sliceThickness(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._findFloatStringInFrameGroupSequence("x00289110","x00180050",frameIndex)}},{key:"spacingBetweenSlices",value:function spacingBetweenSlices(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var spacing=this._dataSet.intString("x00180088");if(typeof spacing==="undefined"){spacing=null}return spacing}},{key:"dimensionIndexValues",value:function dimensionIndexValues(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var dimensionIndexValues=null;var perFrameFunctionnalGroupSequence=this._dataSet.elements.x52009230;if(typeof perFrameFunctionnalGroupSequence!=="undefined"){var frameContentSequence=perFrameFunctionnalGroupSequence.items[frameIndex].dataSet.elements.x00209111;if(frameContentSequence!==undefined&&frameContentSequence!==null){frameContentSequence=frameContentSequence.items[0].dataSet;var dimensionIndexValuesElt=frameContentSequence.elements.x00209157;if(dimensionIndexValuesElt!==undefined&&dimensionIndexValuesElt!==null){var nbValues=dimensionIndexValuesElt.length/4;dimensionIndexValues=[];for(var i=0;i<nbValues;i++){dimensionIndexValues.push(frameContentSequence.uint32("x00209157",i))}}}}return dimensionIndexValues}},{key:"inStackPositionNumber",value:function inStackPositionNumber(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var inStackPositionNumber=null;var perFrameFunctionnalGroupSequence=this._dataSet.elements.x52009230;if(typeof perFrameFunctionnalGroupSequence!=="undefined"){var philipsPrivateSequence=perFrameFunctionnalGroupSequence.items[frameIndex].dataSet.elements.x00209111.items[0].dataSet;inStackPositionNumber=philipsPrivateSequence.uint32("x00209057")}else{inStackPositionNumber=null}console.log("instack position "+inStackPositionNumber);return inStackPositionNumber}},{key:"stackID",value:function stackID(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var stackID=null;var perFrameFunctionnalGroupSequence=this._dataSet.elements.x52009230;if(typeof perFrameFunctionnalGroupSequence!=="undefined"){var philipsPrivateSequence=perFrameFunctionnalGroupSequence.items[frameIndex].dataSet.elements.x00209111.items[0].dataSet;stackID=philipsPrivateSequence.intString("x00209056")}else{stackID=null}return stackID}},{key:"extractPixelData",value:function extractPixelData(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var decompressedData=this._decodePixelData(frameIndex);var numberOfChannels=this.numberOfChannels();if(numberOfChannels>1){return this._convertColorSpace(decompressedData)}else{return decompressedData}}},{key:"_findInGroupSequence",value:function _findInGroupSequence(sequence,subsequence,index){var functionalGroupSequence=this._dataSet.elements[sequence];if(typeof functionalGroupSequence!=="undefined"){var inSequence=functionalGroupSequence.items[index].dataSet.elements[subsequence];if(typeof inSequence!=="undefined"){return inSequence.items[0].dataSet}}return null}},{key:"_findStringInGroupSequence",value:function _findStringInGroupSequence(sequence,subsequence,tag,index){var dataSet=this._findInGroupSequence(sequence,subsequence,index);if(dataSet!==null){return dataSet.string(tag)}return null}},{key:"_findStringInFrameGroupSequence",value:function _findStringInFrameGroupSequence(subsequence,tag,index){return this._findStringInGroupSequence("x52009229",subsequence,tag,0)||this._findStringInGroupSequence("x52009230",subsequence,tag,index)}},{key:"_findStringEverywhere",value:function _findStringEverywhere(subsequence,tag,index){var targetString=this._findStringInFrameGroupSequence(subsequence,tag,index);if(targetString===null){targetString=this._dataSet.string(tag)}if(typeof targetString==="undefined"){targetString=null}return targetString}},{key:"_findFloatStringInGroupSequence",value:function _findFloatStringInGroupSequence(sequence,subsequence,tag,index){var dataInGroupSequence=this._dataSet.floatString(tag);if(typeof dataInGroupSequence==="undefined"){dataInGroupSequence=this._findInGroupSequence(sequence,subsequence,index);if(dataInGroupSequence!==null){return dataInGroupSequence.floatString(tag)}else{return null}}return dataInGroupSequence}},{key:"_findFloatStringInFrameGroupSequence",value:function _findFloatStringInFrameGroupSequence(subsequence,tag,index){return this._findFloatStringInGroupSequence("x52009229",subsequence,tag,0)||this._findFloatStringInGroupSequence("x52009230",subsequence,tag,index)}},{key:"_decodePixelData",value:function _decodePixelData(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var transferSyntaxUID=this.transferSyntaxUID();if(transferSyntaxUID==="1.2.840.10008.1.2.4.90"||transferSyntaxUID==="1.2.840.10008.1.2.4.91"){return this._decodeJ2K(frameIndex)}else if(transferSyntaxUID==="1.2.840.10008.1.2.4.57"||transferSyntaxUID==="1.2.840.10008.1.2.4.70"){return this._decodeJPEGLossless(frameIndex)}else if(transferSyntaxUID==="1.2.840.10008.1.2.4.50"||transferSyntaxUID==="1.2.840.10008.1.2.4.51"){return this._decodeJPEGBaseline(frameIndex)}else if(transferSyntaxUID==="1.2.840.10008.1.2"||transferSyntaxUID==="1.2.840.10008.1.2.1"){return this._decodeUncompressed(frameIndex)}else if(transferSyntaxUID==="1.2.840.10008.1.2.2"){var frame=this._decodeUncompressed(frameIndex);return this._swapFrame(frame)}else{throw{error:"no decoder for transfer syntax "+transferSyntaxUID}}}},{key:"framesAreFragmented",value:function framesAreFragmented(dataSet){var numberOfFrames=dataSet.intString("x00280008");var pixelDataElement=dataSet.elements.x7fe00010;return numberOfFrames!==pixelDataElement.fragments.length}},{key:"_decodeJ2K",value:function _decodeJ2K(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var encodedPixelData=null;if(this._dataSet.elements.x7fe00010.basicOffsetTable.length){encodedPixelData=DicomParser.readEncapsulatedImageFrame(this._dataSet,this._dataSet.elements.x7fe00010,frameIndex)}else if(this.framesAreFragmented(this._dataSet)){var basicOffsetTable=DicomParser.createJPEGBasicOffsetTable(this._dataSet,this._dataSet.elements.x7fe00010);encodedPixelData=DicomParser.readEncapsulatedImageFrame(this._dataSet,this._dataSet.elements.x7fe00010,frameIndex,basicOffsetTable)}else{encodedPixelData=DicomParser.readEncapsulatedPixelDataFromFragments(this._dataSet,this._dataSet.elements.x7fe00010,frameIndex)}var jpxImage=new Jpx;jpxImage.parse(encodedPixelData);var componentsCount=jpxImage.componentsCount;if(componentsCount!==1){throw"JPEG2000 decoder returned a componentCount of ${componentsCount}, when 1 is expected"}var tileCount=jpxImage.tiles.length;if(tileCount!==1){throw"JPEG2000 decoder returned a tileCount of ${tileCount}, when 1 is expected"}var tileComponents=jpxImage.tiles[0];var pixelData=tileComponents.items;return pixelData}},{key:"_decodeJPEGLossless",value:function _decodeJPEGLossless(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var encodedPixelData=DicomParser.readEncapsulatedPixelData(this._dataSet,this._dataSet.elements.x7fe00010,frameIndex);var pixelRepresentation=this.pixelRepresentation(frameIndex);var bitsAllocated=this.bitsAllocated(frameIndex);var byteOutput=bitsAllocated<=8?1:2;var decoder=new Jpeg.lossless.Decoder;var decompressedData=decoder.decode(encodedPixelData.buffer,encodedPixelData.byteOffset,encodedPixelData.length,byteOutput);if(pixelRepresentation===0){if(byteOutput===2){return new Uint16Array(decompressedData.buffer)}else{return new Uint8Array(decompressedData.buffer)}}else{return new Int16Array(decompressedData.buffer)}}},{key:"_decodeJPEGBaseline",value:function _decodeJPEGBaseline(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var encodedPixelData=DicomParser.readEncapsulatedPixelData(this._dataSet,this._dataSet.elements.x7fe00010,frameIndex);var rows=this.rows(frameIndex);var columns=this.columns(frameIndex);var bitsAllocated=this.bitsAllocated(frameIndex);var jpegBaseline=new JpegBaseline;jpegBaseline.parse(encodedPixelData);if(bitsAllocated===8){return jpegBaseline.getData(columns,rows)}else if(bitsAllocated===16){return jpegBaseline.getData16(columns,rows)}}},{key:"_decodeUncompressed",value:function _decodeUncompressed(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var pixelRepresentation=this.pixelRepresentation(frameIndex);var bitsAllocated=this.bitsAllocated(frameIndex);var pixelDataElement=this._dataSet.elements.x7fe00010;var pixelDataOffset=pixelDataElement.dataOffset;var numberOfChannels=this.numberOfChannels();var numPixels=this.rows(frameIndex)*this.columns(frameIndex)*numberOfChannels;var frameOffset=0;var buffer=this._dataSet.byteArray.buffer;if(pixelRepresentation===0&&bitsAllocated===8){frameOffset=pixelDataOffset+frameIndex*numPixels;return new Uint8Array(buffer,frameOffset,numPixels)}else if(pixelRepresentation===0&&bitsAllocated===16){frameOffset=pixelDataOffset+frameIndex*numPixels*2;return new Uint16Array(buffer,frameOffset,numPixels)}else if(pixelRepresentation===1&&bitsAllocated===16){frameOffset=pixelDataOffset+frameIndex*numPixels*2;return new Int16Array(buffer,frameOffset,numPixels)}else if(pixelRepresentation===0&&bitsAllocated===32){frameOffset=pixelDataOffset+frameIndex*numPixels*4;return new Uint32Array(buffer,frameOffset,numPixels)}else if(pixelRepresentation===0&&bitsAllocated===1){var newBuffer=new ArrayBuffer(numPixels);var newArray=new Uint8Array(newBuffer);frameOffset=pixelDataOffset+frameIndex*numPixels;var index=0;var bitStart=frameIndex*numPixels;var bitEnd=frameIndex*numPixels+numPixels;var byteStart=Math.floor(bitStart/8);var bitStartOffset=bitStart-byteStart*8;var byteEnd=Math.ceil(bitEnd/8);var targetBuffer=new Uint8Array(buffer,pixelDataOffset);for(var i=byteStart;i<=byteEnd;i++){while(bitStartOffset<8){switch(bitStartOffset){case 0:newArray[index]=targetBuffer[i]&1;break;case 1:newArray[index]=targetBuffer[i]>>>1&1;break;case 2:newArray[index]=targetBuffer[i]>>>2&1;break;case 3:newArray[index]=targetBuffer[i]>>>3&1;break;case 4:newArray[index]=targetBuffer[i]>>>4&1;break;case 5:newArray[index]=targetBuffer[i]>>>5&1;break;case 6:newArray[index]=targetBuffer[i]>>>6&1;break;case 7:newArray[index]=targetBuffer[i]>>>7&1;break;default:break}bitStartOffset++;index++;if(index>=numPixels){return newArray}}bitStartOffset=0}}}},{key:"_convertColorSpace",value:function _convertColorSpace(uncompressedData){var rgbData=null;var photometricInterpretation=this.photometricInterpretation();var planarConfiguration=this.planarConfiguration();if(photometricInterpretation==="RGB"&&planarConfiguration===0){rgbData=uncompressedData}else if(photometricInterpretation==="RGB"&&planarConfiguration===1){if(uncompressedData instanceof Int8Array){rgbData=new Int8Array(uncompressedData.length)}else if(uncompressedData instanceof Uint8Array){rgbData=new Uint8Array(uncompressedData.length)}else if(uncompressedData instanceof Int16Array){rgbData=new Int16Array(uncompressedData.length)}else if(uncompressedData instanceof Uint16Array){rgbData=new Uint16Array(uncompressedData.length)}else{throw"unsuported typed array: ${uncompressedData}"}var numPixels=uncompressedData.length/3;var rgbaIndex=0;var rIndex=0;var gIndex=numPixels;var bIndex=numPixels*2;for(var i=0;i<numPixels;i++){rgbData[rgbaIndex++]=uncompressedData[rIndex++];rgbData[rgbaIndex++]=uncompressedData[gIndex++];rgbData[rgbaIndex++]=uncompressedData[bIndex++]}}else if(photometricInterpretation==="YBR_FULL"){if(uncompressedData instanceof Int8Array){rgbData=new Int8Array(uncompressedData.length)}else if(uncompressedData instanceof Uint8Array){rgbData=new Uint8Array(uncompressedData.length)}else if(uncompressedData instanceof Int16Array){rgbData=new Int16Array(uncompressedData.length)}else if(uncompressedData instanceof Uint16Array){rgbData=new Uint16Array(uncompressedData.length)}else{throw"unsuported typed array: ${uncompressedData}"}var nPixels=uncompressedData.length/3;var ybrIndex=0;var _rgbaIndex=0;for(var _i=0;_i<nPixels;_i++){var y=uncompressedData[ybrIndex++];var cb=uncompressedData[ybrIndex++];var cr=uncompressedData[ybrIndex++];rgbData[_rgbaIndex++]=y+1.402*(cr-128);rgbData[_rgbaIndex++]=y-.34414*(cb-128)-.71414*(cr-128);rgbData[_rgbaIndex++]=y+1.772*(cb-128)}}else{throw"photometric interpolation not supported: ${photometricInterpretation}"}return rgbData}},{key:"_swapFrame",value:function _swapFrame(frame){var bitsAllocated=this.bitsAllocated();if(bitsAllocated===16){for(var i=0;i<frame.length;i++){frame[i]=this._swap16(frame[i])}}else if(bitsAllocated===32){for(var _i2=0;_i2<frame.length;_i2++){frame[_i2]=this._swap32(frame[_i2])}}return frame}}]);return ParsersDicom}(_parsers2.default);exports.default=ParsersDicom},{"../../external/scripts/jpeg":1,"../../external/scripts/jpx":2,"./parsers.volume":137,"dicom-parser":25,"jpeg-lossless-decoder-js":35}],133:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _parsers=require("./parsers.dicom");var _parsers2=_interopRequireDefault(_parsers);var _parsers3=require("./parsers.nifti");var _parsers4=_interopRequireDefault(_parsers3);var _parsers5=require("./parsers.nrrd");var _parsers6=_interopRequireDefault(_parsers5);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Dicom:_parsers2.default,Nifti:_parsers4.default,Nrrd:_parsers6.default}},{"./parsers.dicom":132,"./parsers.nifti":135,"./parsers.nrrd":136}],134:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _parsers=require("./parsers.volume");var _parsers2=_interopRequireDefault(_parsers);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var ParsersMHD=function(_ParsersVolume){_inherits(ParsersMHD,_ParsersVolume);function ParsersMHD(data,id){_classCallCheck(this,ParsersMHD);var _this=_possibleConstructorReturn(this,(ParsersMHD.__proto__||Object.getPrototypeOf(ParsersMHD)).call(this));_this._id=id;_this._url=data.url;_this._header={};_this._buffer=null;try{var lines=(new TextDecoder).decode(data.mhdBuffer).split("\n");lines.forEach(function(line){var keyvalue=line.split("=");if(keyvalue.length===2){_this._header[keyvalue[0].trim()]=keyvalue[1].trim()}});_this._header.DimSize=_this._header.DimSize.split(" ");_this._header.ElementSpacing=_this._header.ElementSpacing.split(" ");_this._header.TransformMatrix=_this._header.TransformMatrix.split(" ");_this._header.Offset=_this._header.Offset.split(" ");_this._buffer=data.rawBuffer}catch(error){window.console.log("ooops... :(")}return _this}_createClass(ParsersMHD,[{key:"rightHanded",value:function rightHanded(){var anatomicalOrientation=this._header.AnatomicalOrientation;if(anatomicalOrientation==="RAS"||anatomicalOrientation==="RPI"||anatomicalOrientation==="LPS"||anatomicalOrientation==="LAI"){this._rightHanded=true}else{this._rightHanded=false}return this._rightHanded}},{key:"seriesInstanceUID",value:function seriesInstanceUID(){return this._url}},{key:"numberOfFrames",value:function numberOfFrames(){return parseInt(this._header.DimSize[2],10)}},{key:"sopInstanceUID",value:function sopInstanceUID(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return frameIndex}},{key:"rows",value:function rows(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return parseInt(this._header.DimSize[1],10)}},{key:"columns",value:function columns(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return parseInt(this._header.DimSize[0],10)}},{key:"pixelType",value:function pixelType(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return 0}},{key:"bitsAllocated",value:function bitsAllocated(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var bitsAllocated=1;if(this._header.ElementType==="MET_UCHAR"||this._header.ElementType==="MET_CHAR"){bitsAllocated=8}else if(this._header.ElementType==="MET_USHORT"||this._header.ElementType==="MET_SHORT"){bitsAllocated=16}else if(this._header.ElementType==="MET_UFLOAT"||this._header.ElementType==="MET_FLOAT"){bitsAllocated=32}return bitsAllocated}},{key:"pixelSpacing",value:function pixelSpacing(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var x=parseFloat(this._header.ElementSpacing[0],10);var y=parseFloat(this._header.ElementSpacing[1],10);var z=parseFloat(this._header.ElementSpacing[2],10);return[x,y,z]}},{key:"imageOrientation",value:function imageOrientation(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var invertX=this._header.AnatomicalOrientation.match(/L/)?-1:1;var invertY=this._header.AnatomicalOrientation.match(/P/)?-1:1;var x=new _three.Vector3(parseFloat(this._header.TransformMatrix[0])*invertX,parseFloat(this._header.TransformMatrix[1])*invertY,parseFloat(this._header.TransformMatrix[2]));x.normalize();var y=new _three.Vector3(parseFloat(this._header.TransformMatrix[3])*invertX,parseFloat(this._header.TransformMatrix[4])*invertY,parseFloat(this._header.TransformMatrix[5]));y.normalize();return[x.x,x.y,x.z,y.x,y.y,y.z]}},{key:"imagePosition",value:function imagePosition(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return[parseFloat(this._header.Offset[0]),parseFloat(this._header.Offset[1]),parseFloat(this._header.Offset[2])]}},{key:"extractPixelData",value:function extractPixelData(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._decompressUncompressed(frameIndex)}},{key:"_decompressUncompressed",value:function _decompressUncompressed(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var buffer=this._buffer;var numberOfChannels=this.numberOfChannels();var numPixels=this.rows(frameIndex)*this.columns(frameIndex)*numberOfChannels;if(!this.rightHanded()){frameIndex=this.numberOfFrames()-1-frameIndex}var frameOffset=frameIndex*numPixels;if(this._header.ElementType==="MET_CHAR"){frameOffset=frameOffset;return new Int8Array(buffer,frameOffset,numPixels)}else if(this._header.ElementType==="MET_UCHAR"){frameOffset=frameOffset;return new Uint8Array(buffer,frameOffset,numPixels)}else if(this._header.ElementType==="MET_SHORT"){frameOffset=frameOffset*2;return new Int16Array(buffer,frameOffset,numPixels)}else if(this._header.ElementType==="MET_USHORT"){frameOffset=frameOffset*2;return new Uint16Array(buffer,frameOffset,numPixels)}else if(this._header.ElementType==="MET_FLOAT"){frameOffset=frameOffset*4;return new Float32Array(buffer,frameOffset,numPixels)}}}]);return ParsersMHD}(_parsers2.default);exports.default=ParsersMHD},{"./parsers.volume":137,three:81}],135:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _parsers=require("./parsers.volume");var _parsers2=_interopRequireDefault(_parsers);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var NiftiReader=require("nifti-reader-js");var ParsersNifti=function(_ParsersVolume){_inherits(ParsersNifti,_ParsersVolume);function ParsersNifti(data,id){_classCallCheck(this,ParsersNifti);var _this=_possibleConstructorReturn(this,(ParsersNifti.__proto__||Object.getPrototypeOf(ParsersNifti)).call(this));_this._id=id;_this._arrayBuffer=data.buffer;_this._url=data.url;_this._dataSet=null;_this._niftiHeader=null;_this._niftiImage=null;_this._ordered=true;_this._orderedData=null;_this._qfac=1;if(NiftiReader.isNIFTI(_this._arrayBuffer)){_this._dataSet=NiftiReader.readHeader(_this._arrayBuffer);_this._niftiImage=NiftiReader.readImage(_this._dataSet,_this._arrayBuffer)}else{throw"parsers.nifti could not parse the file"}return _this}_createClass(ParsersNifti,[{key:"seriesInstanceUID",value:function seriesInstanceUID(){return this._url}},{key:"numberOfFrames",value:function numberOfFrames(){return this._dataSet.dims[3]}},{key:"numberOfChannels",value:function numberOfChannels(){var numberOfChannels=1;if(this._dataSet.dims[0]>=5){numberOfChannels=this._dataSet.dims[5];this._ordered=false}else if(this._dataSet.datatypeCode===128){numberOfChannels=3}else if(this._dataSet.datatypeCode===2304){numberOfChannels=4}return numberOfChannels}},{key:"sopInstanceUID",value:function sopInstanceUID(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return frameIndex}},{key:"rows",value:function rows(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.dims[2]}},{key:"columns",value:function columns(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.dims[1]}},{key:"pixelType",value:function pixelType(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var pixelType=0;if(this._dataSet.datatypeCode===16||this._dataSet.datatypeCode===64||this._dataSet.datatypeCode===1536){pixelType=1}return pixelType}},{key:"bitsAllocated",value:function bitsAllocated(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.numBitsPerVoxel}},{key:"pixelSpacing",value:function pixelSpacing(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return[this._dataSet.pixDims[1],this._dataSet.pixDims[2],this._dataSet.pixDims[3]]}},{key:"sliceThickness",value:function sliceThickness(){return null}},{key:"imageOrientation",value:function imageOrientation(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;if(this._dataSet.qform_code>0){var a=0;var b=this._dataSet.quatern_b;var c=this._dataSet.quatern_c;var d=this._dataSet.quatern_d;a=1-(b*b+c*c+d*d);if(a<1e-7){a=1/Math.sqrt(b*b+c*c+d*d);b*=a;c*=a;d*=a;a=0}else{a=Math.sqrt(a)}if(this._dataSet.pixDims[0]<0){this._rightHanded=false}return[-(a*a+b*b-c*c-d*d),-2*(b*c+a*d),2*(b*d-a*c),-2*(b*c-a*d),-(a*a+c*c-b*b-d*d),2*(c*d+a*b)]}else if(this._dataSet.sform_code>0){console.log("sform > 0");var sx=this._dataSet.srow_x;var sy=this._dataSet.srow_y;var sz=this._dataSet.srow_z}else if(this._dataSet.qform_code===0){console.log("qform === 0")}return[1,0,0,0,1,0]}},{key:"imagePosition",value:function imagePosition(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return[-this._dataSet.qoffset_x,-this._dataSet.qoffset_y,this._dataSet.qoffset_z]}},{key:"dimensionIndexValues",value:function dimensionIndexValues(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"instanceNumber",value:function instanceNumber(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return frameIndex}},{key:"windowCenter",value:function windowCenter(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"windowWidth",value:function windowWidth(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"rescaleSlope",value:function rescaleSlope(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.scl_slope}},{key:"rescaleIntercept",value:function rescaleIntercept(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.scl_intercept}},{key:"extractPixelData",value:function extractPixelData(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._decompressUncompressed(frameIndex)}},{key:"_decompressUncompressed",value:function _decompressUncompressed(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var numberOfChannels=this.numberOfChannels();var numPixels=this.rows(frameIndex)*this.columns(frameIndex)*numberOfChannels;var frameOffset=frameIndex*numPixels;var buffer=this._niftiImage;if(!this._ordered&&this._orderedData===null){this._reorderData()}if(this._orderedData!==null){return this._orderedData.slice(frameOffset,frameOffset+numPixels)}else if(this._dataSet.datatypeCode===2){return new Uint8Array(buffer,frameOffset,numPixels)}else if(this._dataSet.datatypeCode===256){return new Int8Array(buffer,frameOffset,numPixels)}else if(this._dataSet.datatypeCode===512){frameOffset=frameOffset*2;return new Uint16Array(buffer,frameOffset,numPixels)}else if(this._dataSet.datatypeCode===4){frameOffset=frameOffset*2;return new Int16Array(buffer,frameOffset,numPixels)}else if(this._dataSet.datatypeCode===8){frameOffset=frameOffset*4;return new Int32Array(buffer,frameOffset,numPixels)}else if(this._dataSet.datatypeCode===16){frameOffset=frameOffset*4;return new Float32Array(buffer,frameOffset,numPixels)}else{console.log("Unknown data type: datatypeCode : "+this._dataSet.datatypeCode)}}},{key:"_reorderData",value:function _reorderData(){window.console.log("re-order");var numberOfChannels=this.numberOfChannels();var numPixels=this.rows()*this.columns()*numberOfChannels;var buffer=this._niftiImage;var totalNumPixels=numPixels*this.numberOfFrames();var tmp=null;this._orderedData=null;if(this._dataSet.datatypeCode===2){tmp=new Uint8Array(buffer,0,totalNumPixels);this._orderedData=new Uint8Array(tmp.length)}else if(this._dataSet.datatypeCode===256){tmp=new Int8Array(buffer,0,totalNumPixels);this._orderedData=new Int8Array(tmp.length)}else if(this._dataSet.datatypeCode===512){tmp=new Uint16Array(buffer,0,totalNumPixels);this._orderedData=new Uint16Array(tmp.length)}else if(this._dataSet.datatypeCode===4){tmp=new Int16Array(buffer,0,totalNumPixels);this._orderedData=new Int16Array(tmp.length)}else if(this._dataSet.datatypeCode===16){tmp=new Float32Array(buffer,0,totalNumPixels);this._orderedData=new Float32Array(tmp.length)}var numPixels2=tmp.length/3;var rgbaIndex=0;var rIndex=0;var gIndex=numPixels2;var bIndex=numPixels2*2;for(var i=0;i<numPixels2;i++){this._orderedData[rgbaIndex++]=tmp[rIndex++];this._orderedData[rgbaIndex++]=tmp[gIndex++];this._orderedData[rgbaIndex++]=tmp[bIndex++]}this._ordered=true}}]);return ParsersNifti}(_parsers2.default);exports.default=ParsersNifti},{"./parsers.volume":137,"nifti-reader-js":46}],136:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _parsers=require("./parsers.volume");var _parsers2=_interopRequireDefault(_parsers);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}

function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var pako=require("pako");var NrrdReader=require("nrrd-js");var ParsersNifti=function(_ParsersVolume){_inherits(ParsersNifti,_ParsersVolume);function ParsersNifti(data,id){_classCallCheck(this,ParsersNifti);var _this=_possibleConstructorReturn(this,(ParsersNifti.__proto__||Object.getPrototypeOf(ParsersNifti)).call(this));_this._id=id;_this._arrayBuffer=data.buffer;_this._url=data.url;_this._dataSet=null;_this._unpackedData=null;try{_this._dataSet=NrrdReader.parse(_this._arrayBuffer)}catch(error){window.console.log("ooops... :(")}window.console.log(_this._dataSet);return _this}_createClass(ParsersNifti,[{key:"rightHanded",value:function rightHanded(){if(this._dataSet.space.match(/^right-anterior-superior/)||this._dataSet.space.match(/^left-posterior-superior/)){this._rightHanded=true}else{this._rightHanded=false}return this._rightHanded}},{key:"seriesInstanceUID",value:function seriesInstanceUID(){return this._url}},{key:"numberOfFrames",value:function numberOfFrames(){return this._dataSet.sizes[2]}},{key:"numberOfChannels",value:function numberOfChannels(){return 1}},{key:"sopInstanceUID",value:function sopInstanceUID(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return frameIndex}},{key:"rows",value:function rows(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.sizes[1]}},{key:"columns",value:function columns(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._dataSet.sizes[0]}},{key:"pixelType",value:function pixelType(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var pixelType=0;if(this._dataSet.type==="float"){pixelType=1}return pixelType}},{key:"bitsAllocated",value:function bitsAllocated(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var bitsAllocated=1;if(this._dataSet.type==="int8"||this._dataSet.type==="uint8"||this._dataSet.type==="char"){bitsAllocated=8}else if(this._dataSet.type==="int16"||this._dataSet.type==="uint16"||this._dataSet.type==="short"){bitsAllocated=16}else if(this._dataSet.type==="int32"||this._dataSet.type==="uint32"||this._dataSet.type==="float"){bitsAllocated=32}return bitsAllocated}},{key:"pixelSpacing",value:function pixelSpacing(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var x=new _three.Vector3(this._dataSet.spaceDirections[1][0],this._dataSet.spaceDirections[1][1],this._dataSet.spaceDirections[1][2]);var y=new _three.Vector3(this._dataSet.spaceDirections[2][0],this._dataSet.spaceDirections[2][1],this._dataSet.spaceDirections[2][2]);var z=new _three.Vector3(this._dataSet.spaceDirections[2][0],this._dataSet.spaceDirections[2][1],this._dataSet.spaceDirections[2][2]);return[x.length(),y.length(),z.length()]}},{key:"imageOrientation",value:function imageOrientation(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var invertX=this._dataSet.space.match(/right/)?-1:1;var invertY=this._dataSet.space.match(/anterior/)?-1:1;var x=new _three.Vector3(this._dataSet.spaceDirections[0][0]*invertX,this._dataSet.spaceDirections[0][1]*invertY,this._dataSet.spaceDirections[0][2]);x.normalize();var y=new _three.Vector3(this._dataSet.spaceDirections[1][0]*invertX,this._dataSet.spaceDirections[1][1]*invertY,this._dataSet.spaceDirections[1][2]);y.normalize();return[x.x,x.y,x.z,y.x,y.y,y.z]}},{key:"imagePosition",value:function imagePosition(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return[this._dataSet.spaceOrigin[0],this._dataSet.spaceOrigin[1],this._dataSet.spaceOrigin[2]]}},{key:"extractPixelData",value:function extractPixelData(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return this._decompressUncompressed(frameIndex)}},{key:"_decompressUncompressed",value:function _decompressUncompressed(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var buffer=this._dataSet.buffer;var numberOfChannels=this.numberOfChannels();var numPixels=this.rows(frameIndex)*this.columns(frameIndex)*numberOfChannels;if(!this.rightHanded()){frameIndex=this.numberOfFrames()-1-frameIndex}var frameOffset=frameIndex*numPixels;if(this._unpackedData===null&&this._dataSet.encoding==="gzip"){var unpackedData=pako.inflate(this._dataSet.buffer);this._unpackedData=unpackedData.buffer;buffer=this._unpackedData}else if(this._dataSet.encoding==="gzip"){buffer=this._unpackedData}if(this._dataSet.type==="int8"||this._dataSet.type==="char"){frameOffset=frameOffset;return new Int8Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="uint8"){frameOffset=frameOffset;return new Uint8Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="int16"||this._dataSet.type==="short"){frameOffset=frameOffset*2;return new Int16Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="uint16"){frameOffset=frameOffset*2;return new Uint16Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="int32"){frameOffset=frameOffset*4;return new Int32Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="uint32"){frameOffset=frameOffset*4;return new Uint32Array(buffer,frameOffset,numPixels)}else if(this._dataSet.type==="float"){frameOffset=frameOffset*4;return new Float32Array(buffer,frameOffset,numPixels)}}}]);return ParsersNifti}(_parsers2.default);exports.default=ParsersNifti},{"./parsers.volume":137,"nrrd-js":50,pako:51,three:81}],137:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ParsersVolume=function(){function ParsersVolume(){_classCallCheck(this,ParsersVolume);this._rightHanded=true}_createClass(ParsersVolume,[{key:"pixelRepresentation",value:function pixelRepresentation(){return 0}},{key:"modality",value:function modality(){return"unknown"}},{key:"segmentationType",value:function segmentationType(){return"unknown"}},{key:"segmentationSegments",value:function segmentationSegments(){return[]}},{key:"referencedSegmentNumber",value:function referencedSegmentNumber(frameIndex){return-1}},{key:"rightHanded",value:function rightHanded(){return this._rightHanded}},{key:"spacingBetweenSlices",value:function spacingBetweenSlices(){return null}},{key:"numberOfChannels",value:function numberOfChannels(){return 1}},{key:"sliceThickness",value:function sliceThickness(){return null}},{key:"dimensionIndexValues",value:function dimensionIndexValues(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"instanceNumber",value:function instanceNumber(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return frameIndex}},{key:"windowCenter",value:function windowCenter(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"windowWidth",value:function windowWidth(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return null}},{key:"rescaleSlope",value:function rescaleSlope(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return 1}},{key:"rescaleIntercept",value:function rescaleIntercept(){var frameIndex=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return 0}},{key:"_decompressUncompressed",value:function _decompressUncompressed(){}},{key:"_swap16",value:function _swap16(val){return(val&255)<<8|val>>8&255}},{key:"_swap32",value:function _swap32(val){return(val&255)<<24|(val&65280)<<8|val>>8&65280|val>>24&255}},{key:"invert",value:function invert(){return false}},{key:"transferSyntaxUID",value:function transferSyntaxUID(){return"no value provided"}},{key:"studyDate",value:function studyDate(){return"no value provided"}},{key:"studyDescription",value:function studyDescription(){return"no value provided"}},{key:"seriesDate",value:function seriesDate(){return"no value provided"}},{key:"seriesDescription",value:function seriesDescription(){return"no value provided"}},{key:"patientID",value:function patientID(){return"no value provided"}},{key:"patientName",value:function patientName(){return"no value provided"}},{key:"patientAge",value:function patientAge(){return"no value provided"}},{key:"patientBirthdate",value:function patientBirthdate(){return"no value provided"}},{key:"patientSex",value:function patientSex(){return"no value provided"}},{key:"minMaxPixelData",value:function minMaxPixelData(){var pixelData=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var minMax=[Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY];var numPixels=pixelData.length;for(var index=0;index<numPixels;index++){var spv=pixelData[index];minMax[0]=Math.min(minMax[0],spv);minMax[1]=Math.max(minMax[1],spv)}return minMax}}]);return ParsersVolume}();exports.default=ParsersVolume},{}],138:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _presets=require("./presets.segmentation");var _presets2=_interopRequireDefault(_presets);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Segmentation:_presets2.default}},{"./presets.segmentation":140}],139:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var segmentationFs={0:{color:[0,0,0],opacity:0,label:"Unknown"},1:{color:[70,130,180],opacity:1,label:"Left-Cerebral-Exterior"},2:{color:[245,245,245],opacity:1,label:"Left-Cerebral-White-Matter"},3:{color:[205,62,78],opacity:1,label:"Left-Cerebral-Cortex"},4:{color:[120,18,134],opacity:1,label:"Left-Lateral-Ventricle"},5:{color:[196,58,250],opacity:1,label:"Left-Inf-Lat-Vent"},6:{color:[0,148,0],opacity:1,label:"Left-Cerebellum-Exterior"},7:{color:[220,248,164],opacity:1,label:"Left-Cerebellum-White-Matter"},8:{color:[230,148,34],opacity:1,label:"Left-Cerebellum-Cortex"},9:{color:[0,118,14],opacity:1,label:"Left-Thalamus"},10:{color:[0,118,14],opacity:1,label:"Left-Thalamus-Proper"},11:{color:[122,186,220],opacity:1,label:"Left-Caudate"},12:{color:[236,13,176],opacity:1,label:"Left-Putamen"},13:{color:[12,48,255],opacity:1,label:"Left-Pallidum"},14:{color:[204,182,142],opacity:1,label:"3rd-Ventricle"},15:{color:[42,204,164],opacity:1,label:"4th-Ventricle"},16:{color:[119,159,176],opacity:1,label:"Brain-Stem"},17:{color:[220,216,20],opacity:1,label:"Left-Hippocampus"},18:{color:[103,255,255],opacity:1,label:"Left-Amygdala"},19:{color:[80,196,98],opacity:1,label:"Left-Insula"},20:{color:[60,58,210],opacity:1,label:"Left-Operculum"},21:{color:[60,58,210],opacity:1,label:"Line-1"},22:{color:[60,58,210],opacity:1,label:"Line-2"},23:{color:[60,58,210],opacity:1,label:"Line-3"},24:{color:[60,60,60],opacity:1,label:"CSF"},25:{color:[255,165,0],opacity:1,label:"Left-Lesion"},26:{color:[255,165,0],opacity:1,label:"Left-Accumbens-area"},27:{color:[0,255,127],opacity:1,label:"Left-Substancia-Nigra"},28:{color:[165,42,42],opacity:1,label:"Left-VentralDC"},29:{color:[135,206,235],opacity:1,label:"Left-undetermined"},30:{color:[160,32,240],opacity:1,label:"Left-vessel"},31:{color:[0,200,200],opacity:1,label:"Left-choroid-plexus"},32:{color:[100,50,100],opacity:1,label:"Left-F3orb"},33:{color:[135,50,74],opacity:1,label:"Left-lOg"},34:{color:[122,135,50],opacity:1,label:"Left-aOg"},35:{color:[51,50,135],opacity:1,label:"Left-mOg"},36:{color:[74,155,60],opacity:1,label:"Left-pOg"},37:{color:[120,62,43],opacity:1,label:"Left-Stellate"},38:{color:[74,155,60],opacity:1,label:"Left-Porg"},39:{color:[122,135,50],opacity:1,label:"Left-Aorg"},40:{color:[70,130,180],opacity:1,label:"Right-Cerebral-Exterior"},41:{color:[245,245,245],opacity:1,label:"Right-Cerebral-White-Matter"},42:{color:[205,62,78],opacity:1,label:"Right-Cerebral-Cortex"},43:{color:[120,18,134],opacity:1,label:"Right-Lateral-Ventricle"},44:{color:[196,58,250],opacity:1,label:"Right-Inf-Lat-Vent"},45:{color:[0,148,0],opacity:1,label:"Right-Cerebellum-Exterior"},46:{color:[220,248,164],opacity:1,label:"Right-Cerebellum-White-Matter"},47:{color:[230,148,34],opacity:1,label:"Right-Cerebellum-Cortex"},48:{color:[0,118,14],opacity:1,label:"Right-Thalamus"},49:{color:[0,118,14],opacity:1,label:"Right-Thalamus-Proper"},50:{color:[122,186,220],opacity:1,label:"Right-Caudate"},51:{color:[236,13,176],opacity:1,label:"Right-Putamen"},52:{color:[13,48,255],opacity:1,label:"Right-Pallidum"},53:{color:[220,216,20],opacity:1,label:"Right-Hippocampus"},54:{color:[103,255,255],opacity:1,label:"Right-Amygdala"},55:{color:[80,196,98],opacity:1,label:"Right-Insula"},56:{color:[60,58,210],opacity:1,label:"Right-Operculum"},57:{color:[255,165,0],opacity:1,label:"Right-Lesion"},58:{color:[255,165,0],opacity:1,label:"Right-Accumbens-area"},59:{color:[0,255,127],opacity:1,label:"Right-Substancia-Nigra"},60:{color:[165,42,42],opacity:1,label:"Right-VentralDC"},61:{color:[135,206,235],opacity:1,label:"Right-undetermined"},62:{color:[160,32,240],opacity:1,label:"Right-vessel"},63:{color:[0,200,221],opacity:1,label:"Right-choroid-plexus"},64:{color:[100,50,100],opacity:1,label:"Right-F3orb"},65:{color:[135,50,74],opacity:1,label:"Right-lOg"},66:{color:[122,135,50],opacity:1,label:"Right-aOg"},67:{color:[51,50,135],opacity:1,label:"Right-mOg"},68:{color:[74,155,60],opacity:1,label:"Right-pOg"},69:{color:[120,62,43],opacity:1,label:"Right-Stellate"},70:{color:[74,155,60],opacity:1,label:"Right-Porg"},71:{color:[122,135,50],opacity:1,label:"Right-Aorg"},72:{color:[120,190,150],opacity:1,label:"5th-Ventricle"},73:{color:[122,135,50],opacity:1,label:"Left-Interior"},74:{color:[122,135,50],opacity:1,label:"Right-Interior"},77:{color:[200,70,255],opacity:1,label:"WM-hypointensities"},78:{color:[255,148,10],opacity:1,label:"Left-WM-hypointensities"},79:{color:[255,148,10],opacity:1,label:"Right-WM-hypointensities"},80:{color:[164,108,226],opacity:1,label:"non-WM-hypointensities"},81:{color:[164,108,226],opacity:1,label:"Left-non-WM-hypointensities"},82:{color:[164,108,226],opacity:1,label:"Right-non-WM-hypointensities"},83:{color:[255,218,185],opacity:1,label:"Left-F1"},84:{color:[255,218,185],opacity:1,label:"Right-F1"},85:{color:[234,169,30],opacity:1,label:"Optic-Chiasm"},192:{color:[250,255,50],opacity:1,label:"Corpus_Callosum"},86:{color:[200,120,255],opacity:1,label:"Left_future_WMSA"},87:{color:[200,121,255],opacity:1,label:"Right_future_WMSA"},88:{color:[200,122,255],opacity:1,label:"future_WMSA"},96:{color:[205,10,125],opacity:1,label:"Left-Amygdala-Anterior"},97:{color:[205,10,125],opacity:1,label:"Right-Amygdala-Anterior"},98:{color:[160,32,240],opacity:1,label:"Dura"},100:{color:[124,140,178],opacity:1,label:"Left-wm-intensity-abnormality"},101:{color:[125,140,178],opacity:1,label:"Left-caudate-intensity-abnormality"},102:{color:[126,140,178],opacity:1,label:"Left-putamen-intensity-abnormality"},103:{color:[127,140,178],opacity:1,label:"Left-accumbens-intensity-abnormality"},104:{color:[124,141,178],opacity:1,label:"Left-pallidum-intensity-abnormality"},105:{color:[124,142,178],opacity:1,label:"Left-amygdala-intensity-abnormality"},106:{color:[124,143,178],opacity:1,label:"Left-hippocampus-intensity-abnormality"},107:{color:[124,144,178],opacity:1,label:"Left-thalamus-intensity-abnormality"},108:{color:[124,140,179],opacity:1,label:"Left-VDC-intensity-abnormality"},109:{color:[124,140,178],opacity:1,label:"Right-wm-intensity-abnormality"},110:{color:[125,140,178],opacity:1,label:"Right-caudate-intensity-abnormality"},111:{color:[126,140,178],opacity:1,label:"Right-putamen-intensity-abnormality"},112:{color:[127,140,178],opacity:1,label:"Right-accumbens-intensity-abnormality"},113:{color:[124,141,178],opacity:1,label:"Right-pallidum-intensity-abnormality"},114:{color:[124,142,178],opacity:1,label:"Right-amygdala-intensity-abnormality"},115:{color:[124,143,178],opacity:1,label:"Right-hippocampus-intensity-abnormality"},116:{color:[124,144,178],opacity:1,label:"Right-thalamus-intensity-abnormality"},117:{color:[124,140,179],opacity:1,label:"Right-VDC-intensity-abnormality"},118:{color:[255,20,147],opacity:1,label:"Epidermis"},119:{color:[205,179,139],opacity:1,label:"Conn-Tissue"},120:{color:[238,238,209],opacity:1,label:"SC-Fat-Muscle"},121:{color:[200,200,200],opacity:1,label:"Cranium"},122:{color:[74,255,74],opacity:1,label:"CSF-SA"},123:{color:[238,0,0],opacity:1,label:"Muscle"},124:{color:[0,0,139],opacity:1,label:"Ear"},125:{color:[173,255,47],opacity:1,label:"Adipose"},126:{color:[133,203,229],opacity:1,label:"Spinal-Cord"},127:{color:[26,237,57],opacity:1,label:"Soft-Tissue"},128:{color:[34,139,34],opacity:1,label:"Nerve"},129:{color:[30,144,255],opacity:1,label:"Bone"},130:{color:[147,19,173],opacity:1,label:"Air"},131:{color:[238,59,59],opacity:1,label:"Orbital-Fat"},132:{color:[221,39,200],opacity:1,label:"Tongue"},133:{color:[238,174,238],opacity:1,label:"Nasal-Structures"},134:{color:[255,0,0],opacity:1,label:"Globe"},135:{color:[72,61,139],opacity:1,label:"Teeth"},136:{color:[21,39,132],opacity:1,label:"Left-Caudate-Putamen"},137:{color:[21,39,132],opacity:1,label:"Right-Caudate-Putamen"},138:{color:[65,135,20],opacity:1,label:"Left-Claustrum"},139:{color:[65,135,20],opacity:1,label:"Right-Claustrum"},140:{color:[134,4,160],opacity:1,label:"Cornea"},142:{color:[221,226,68],opacity:1,label:"Diploe"},143:{color:[255,255,254],opacity:1,label:"Vitreous-Humor"},144:{color:[52,209,226],opacity:1,label:"Lens"},145:{color:[239,160,223],opacity:1,label:"Aqueous-Humor"},146:{color:[70,130,180],opacity:1,label:"Outer-Table"},147:{color:[70,130,181],opacity:1,label:"Inner-Table"},148:{color:[139,121,94],opacity:1,label:"Periosteum"},149:{color:[224,224,224],opacity:1,label:"Endosteum"},150:{color:[255,0,0],opacity:1,label:"R-C-S"},151:{color:[205,205,0],opacity:1,label:"Iris"},152:{color:[238,238,209],opacity:1,label:"SC-Adipose-Muscle"},153:{color:[139,121,94],opacity:1,label:"SC-Tissue"},154:{color:[238,59,59],opacity:1,label:"Orbital-Adipose"},155:{color:[238,59,59],opacity:1,label:"Left-IntCapsule-Ant"},156:{color:[238,59,59],opacity:1,label:"Right-IntCapsule-Ant"},157:{color:[62,10,205],opacity:1,label:"Left-IntCapsule-Pos"},158:{color:[62,10,205],opacity:1,label:"Right-IntCapsule-Pos"},159:{color:[0,118,14],opacity:1,label:"Left-Cerebral-WM-unmyelinated"},160:{color:[0,118,14],opacity:1,label:"Right-Cerebral-WM-unmyelinated"},161:{color:[220,216,21],opacity:1,label:"Left-Cerebral-WM-myelinated"},162:{color:[220,216,21],opacity:1,label:"Right-Cerebral-WM-myelinated"},163:{color:[122,186,220],opacity:1,label:"Left-Subcortical-Gray-Matter"},164:{color:[122,186,220],opacity:1,label:"Right-Subcortical-Gray-Matter"},165:{color:[120,120,120],opacity:1,label:"Skull"},166:{color:[14,48,255],opacity:1,label:"Posterior-fossa"},167:{color:[166,42,42],opacity:1,label:"Scalp"},168:{color:[121,18,134],opacity:1,label:"Hematoma"},169:{color:[236,13,127],opacity:1,label:"Left-Basal-Ganglia"},176:{color:[236,13,126],opacity:1,label:"Right-Basal-Ganglia"},170:{color:[119,159,176],opacity:1,label:"brainstem"},171:{color:[119,0,176],opacity:1,label:"DCG"},172:{color:[119,100,176],opacity:1,label:"Vermis"},173:{color:[242,104,76],opacity:1,label:"Midbrain"},174:{color:[206,195,58],opacity:1,label:"Pons"},175:{color:[119,159,176],opacity:1,label:"Medulla"},177:{color:[119,50,176],opacity:1,label:"Vermis-White-Matter"},178:{color:[142,182,0],opacity:1,label:"SCP"},179:{color:[19,100,176],opacity:1,label:"Floculus"},180:{color:[73,61,139],opacity:1,label:"Left-Cortical-Dysplasia"},181:{color:[73,62,139],opacity:1,label:"Right-Cortical-Dysplasia"},182:{color:[10,100,176],opacity:1,label:"CblumNodulus"},193:{color:[0,196,255],opacity:1,label:"Left-hippocampal_fissure"},194:{color:[255,164,164],opacity:1,label:"Left-CADG-head"},195:{color:[196,196,0],opacity:1,label:"Left-subiculum"},196:{color:[0,100,255],opacity:1,label:"Left-fimbria"},197:{color:[128,196,164],opacity:1,label:"Right-hippocampal_fissure"},198:{color:[0,126,75],opacity:1,label:"Right-CADG-head"},199:{color:[128,96,64],opacity:1,label:"Right-subiculum"},200:{color:[0,50,128],opacity:1,label:"Right-fimbria"},201:{color:[255,204,153],opacity:1,label:"alveus"},202:{color:[255,128,128],opacity:1,label:"perforant_pathway"},203:{color:[255,255,0],opacity:1,label:"parasubiculum"},204:{color:[64,0,64],opacity:1,label:"presubiculum"},205:{color:[0,0,255],opacity:1,label:"subiculum"},206:{color:[255,0,0],opacity:1,label:"CA1"},207:{color:[128,128,255],opacity:1,label:"CA2"},208:{color:[0,128,0],opacity:1,label:"CA3"},209:{color:[196,160,128],opacity:1,label:"CA4"},210:{color:[32,200,255],opacity:1,label:"GC-DG"},211:{color:[128,255,128],opacity:1,label:"HATA"},212:{color:[204,153,204],opacity:1,label:"fimbria"},213:{color:[121,17,136],opacity:1,label:"lateral_ventricle"},214:{color:[128,0,0],opacity:1,label:"molecular_layer_HP"},215:{color:[128,32,255],opacity:1,label:"hippocampal_fissure"},216:{color:[255,204,102],opacity:1,label:"entorhinal_cortex"},217:{color:[128,128,128],opacity:1,label:"molecular_layer_subiculum"},218:{color:[104,255,255],opacity:1,label:"Amygdala"},219:{color:[0,226,0],opacity:1,label:"Cerebral_White_Matter"},220:{color:[205,63,78],opacity:1,label:"Cerebral_Cortex"},221:{color:[197,58,250],opacity:1,label:"Inf_Lat_Vent"},222:{color:[33,150,250],opacity:1,label:"Perirhinal"},223:{color:[226,0,0],opacity:1,label:"Cerebral_White_Matter_Edge"},224:{color:[100,100,100],opacity:1,label:"Background"},225:{color:[197,150,250],opacity:1,label:"Ectorhinal"},226:{color:[170,170,255],opacity:1,label:"HP_tail"},250:{color:[255,0,0],opacity:1,label:"Fornix"},251:{color:[0,0,64],opacity:1,label:"CC_Posterior"},252:{color:[0,0,112],opacity:1,label:"CC_Mid_Posterior"},253:{color:[0,0,160],opacity:1,label:"CC_Central"},254:{color:[0,0,208],opacity:1,label:"CC_Mid_Anterior"},255:{color:[0,0,255],opacity:1,label:"CC_Anterior"},256:{color:[0,0,0],opacity:1,label:"Voxel-Unchanged"},257:{color:[60,60,60],opacity:1,label:"CSF-ExtraCerebral"},258:{color:[150,150,200],opacity:1,label:"Head-ExtraCerebral"},259:{color:[120,120,120],opacity:1,label:"SkullApprox"},260:{color:[119,159,176],opacity:1,label:"BoneOrAir"},261:{color:[120,18,134],opacity:1,label:"PossibleFluid"},262:{color:[119,159,176],opacity:1,label:"Sinus"},263:{color:[119,159,176],opacity:1,label:"Left-Eustachian"},264:{color:[119,159,176],opacity:1,label:"Right-Eustachian"},331:{color:[255,0,0],opacity:1,label:"Aorta"},332:{color:[255,80,0],opacity:1,label:"Left-Common-IliacA"},333:{color:[255,160,0],opacity:1,label:"Right-Common-IliacA"},334:{color:[255,255,0],opacity:1,label:"Left-External-IliacA"},335:{color:[0,255,0],opacity:1,label:"Right-External-IliacA"},336:{color:[255,0,160],opacity:1,label:"Left-Internal-IliacA"},337:{color:[255,0,255],opacity:1,label:"Right-Internal-IliacA"},338:{color:[255,50,80],opacity:1,label:"Left-Lateral-SacralA"},339:{color:[80,255,50],opacity:1,label:"Right-Lateral-SacralA"},340:{color:[160,255,50],opacity:1,label:"Left-ObturatorA"},341:{color:[160,200,255],opacity:1,label:"Right-ObturatorA"},342:{color:[0,255,160],opacity:1,label:"Left-Internal-PudendalA"},343:{color:[0,0,255],opacity:1,label:"Right-Internal-PudendalA"},344:{color:[80,50,255],opacity:1,label:"Left-UmbilicalA"},345:{color:[160,0,255],opacity:1,label:"Right-UmbilicalA"},346:{color:[255,210,0],opacity:1,label:"Left-Inf-RectalA"},347:{color:[0,160,255],opacity:1,label:"Right-Inf-RectalA"},348:{color:[255,200,80],opacity:1,label:"Left-Common-IliacV"},349:{color:[255,200,160],opacity:1,label:"Right-Common-IliacV"},350:{color:[255,80,200],opacity:1,label:"Left-External-IliacV"},351:{color:[255,160,200],opacity:1,label:"Right-External-IliacV"},352:{color:[30,255,80],opacity:1,label:"Left-Internal-IliacV"},353:{color:[80,200,255],opacity:1,label:"Right-Internal-IliacV"},354:{color:[80,255,200],opacity:1,label:"Left-ObturatorV"},355:{color:[195,255,200],opacity:1,label:"Right-ObturatorV"},356:{color:[120,200,20],opacity:1,label:"Left-Internal-PudendalV"},357:{color:[170,10,200],opacity:1,label:"Right-Internal-PudendalV"},358:{color:[20,130,180],opacity:1,label:"Pos-Lymph"},359:{color:[20,180,130],opacity:1,label:"Neg-Lymph"},400:{color:[206,62,78],opacity:1,label:"V1"},401:{color:[121,18,134],opacity:1,label:"V2"},402:{color:[199,58,250],opacity:1,label:"BA44"},403:{color:[1,148,0],opacity:1,label:"BA45"},404:{color:[221,248,164],opacity:1,label:"BA4a"},405:{color:[231,148,34],opacity:1,label:"BA4p"},406:{color:[1,118,14],opacity:1,label:"BA6"},407:{color:[120,118,14],opacity:1,label:"BA2"},408:{color:[123,186,221],opacity:1,label:"BA1_old"},409:{color:[238,13,177],opacity:1,label:"BAun2"},410:{color:[123,186,220],opacity:1,label:"BA1"},411:{color:[138,13,206],opacity:1,label:"BA2b"},412:{color:[238,130,176],opacity:1,label:"BA3a"},413:{color:[218,230,76],opacity:1,label:"BA3b"},414:{color:[38,213,176],opacity:1,label:"MT"},415:{color:[1,225,176],opacity:1,label:"AIPS_AIP_l"},416:{color:[1,225,176],opacity:1,label:"AIPS_AIP_r"},417:{color:[200,2,100],opacity:1,label:"AIPS_VIP_l"},418:{color:[200,2,100],opacity:1,label:"AIPS_VIP_r"},419:{color:[5,200,90],opacity:1,label:"IPL_PFcm_l"},420:{color:[5,200,90],opacity:1,label:"IPL_PFcm_r"},421:{color:[100,5,200],opacity:1,label:"IPL_PF_l"},422:{color:[25,255,100],opacity:1,label:"IPL_PFm_l"},423:{color:[25,255,100],opacity:1,label:"IPL_PFm_r"},424:{color:[230,7,100],opacity:1,label:"IPL_PFop_l"},425:{color:[230,7,100],opacity:1,label:"IPL_PFop_r"},426:{color:[100,5,200],opacity:1,label:"IPL_PF_r"},427:{color:[150,10,200],opacity:1,label:"IPL_PFt_l"},428:{color:[150,10,200],opacity:1,label:"IPL_PFt_r"},429:{color:[175,10,176],opacity:1,label:"IPL_PGa_l"},430:{color:[175,10,176],opacity:1,label:"IPL_PGa_r"},431:{color:[10,100,255],opacity:1,label:"IPL_PGp_l"},432:{color:[10,100,255],opacity:1,label:"IPL_PGp_r"},433:{color:[150,45,70],opacity:1,label:"Visual_V3d_l"},434:{color:[150,45,70],opacity:1,label:"Visual_V3d_r"},435:{color:[45,200,15],opacity:1,label:"Visual_V4_l"},436:{color:[45,200,15],opacity:1,label:"Visual_V4_r"},437:{color:[227,45,100],opacity:1,label:"Visual_V5_b"},438:{color:[227,45,100],opacity:1,label:"Visual_VP_l"},439:{color:[227,45,100],opacity:1,label:"Visual_VP_r"},498:{color:[143,188,143],opacity:1,label:"wmsa"},499:{color:[255,248,220],opacity:1,label:"other_wmsa"},500:{color:[17,85,136],opacity:1,label:"right_CA2_3"},501:{color:[119,187,102],opacity:1,label:"right_alveus"},502:{color:[204,68,34],opacity:1,label:"right_CA1"},503:{color:[204,0,255],opacity:1,label:"right_fimbria"},504:{color:[221,187,17],opacity:1,label:"right_presubiculum"},505:{color:[153,221,238],opacity:1,label:"right_hippocampal_fissure"},506:{color:[51,17,17],opacity:1,label:"right_CA4_DG"},507:{color:[0,119,85],opacity:1,label:"right_subiculum"},508:{color:[20,100,200],opacity:1,label:"right_fornix"},550:{color:[17,85,137],opacity:1,label:"left_CA2_3"},551:{color:[119,187,103],opacity:1,label:"left_alveus"},552:{color:[204,68,35],opacity:1,label:"left_CA1"},553:{color:[204,0,254],opacity:1,label:"left_fimbria"},554:{color:[221,187,16],opacity:1,label:"left_presubiculum"},555:{color:[153,221,239],opacity:1,label:"left_hippocampal_fissure"},556:{color:[51,17,18],opacity:1,label:"left_CA4_DG"},557:{color:[0,119,86],opacity:1,label:"left_subiculum"},558:{color:[20,100,201],opacity:1,label:"left_fornix"},600:{color:[254,254,254],opacity:1,label:"Tumor"},601:{color:[70,130,180],opacity:1,label:"Cbm_Left_I_IV"},602:{color:[245,245,245],opacity:1,label:"Cbm_Right_I_IV"},603:{color:[205,62,78],opacity:1,label:"Cbm_Left_V"},604:{color:[120,18,134],opacity:1,label:"Cbm_Right_V"},605:{color:[196,58,250],opacity:1,label:"Cbm_Left_VI"},606:{color:[0,148,0],opacity:1,label:"Cbm_Vermis_VI"},607:{color:[220,248,164],opacity:1,label:"Cbm_Right_VI"},608:{color:[230,148,34],opacity:1,label:"Cbm_Left_CrusI"},609:{color:[0,118,14],opacity:1,label:"Cbm_Vermis_CrusI"},610:{color:[0,118,14],opacity:1,label:"Cbm_Right_CrusI"},611:{color:[122,186,220],opacity:1,label:"Cbm_Left_CrusII"},612:{color:[236,13,176],opacity:1,label:"Cbm_Vermis_CrusII"},613:{color:[12,48,255],opacity:1,label:"Cbm_Right_CrusII"},614:{color:[204,182,142],opacity:1,label:"Cbm_Left_VIIb"},615:{color:[42,204,164],opacity:1,label:"Cbm_Vermis_VIIb"},616:{color:[119,159,176],opacity:1,label:"Cbm_Right_VIIb"},617:{color:[220,216,20],opacity:1,label:"Cbm_Left_VIIIa"},618:{color:[103,255,255],opacity:1,label:"Cbm_Vermis_VIIIa"},619:{color:[80,196,98],opacity:1,label:"Cbm_Right_VIIIa"},620:{color:[60,58,210],opacity:1,label:"Cbm_Left_VIIIb"},621:{color:[60,58,210],opacity:1,label:"Cbm_Vermis_VIIIb"},622:{color:[60,58,210],opacity:1,label:"Cbm_Right_VIIIb"},623:{color:[60,58,210],opacity:1,label:"Cbm_Left_IX"},624:{color:[60,60,60],opacity:1,label:"Cbm_Vermis_IX"},625:{color:[255,165,0],opacity:1,label:"Cbm_Right_IX"},626:{color:[255,165,0],opacity:1,label:"Cbm_Left_X"},627:{color:[0,255,127],opacity:1,label:"Cbm_Vermis_X"},628:{color:[165,42,42],opacity:1,label:"Cbm_Right_X"},640:{color:[204,0,0],opacity:1,label:"Cbm_Right_I_V_med"},641:{color:[255,0,0],opacity:1,label:"Cbm_Right_I_V_mid"},642:{color:[0,0,255],opacity:1,label:"Cbm_Right_VI_med"},643:{color:[30,144,255],opacity:1,label:"Cbm_Right_VI_mid"},644:{color:[100,212,237],opacity:1,label:"Cbm_Right_VI_lat"},645:{color:[218,165,32],opacity:1,label:"Cbm_Right_CrusI_med"},646:{color:[255,215,0],opacity:1,label:"Cbm_Right_CrusI_mid"},647:{color:[255,255,166],opacity:1,label:"Cbm_Right_CrusI_lat"},648:{color:[153,0,204],opacity:1,label:"Cbm_Right_CrusII_med"},649:{color:[153,141,209],opacity:1,label:"Cbm_Right_CrusII_mid"},650:{color:[204,204,255],opacity:1,label:"Cbm_Right_CrusII_lat"},651:{color:[31,212,194],opacity:1,label:"Cbm_Right_7med"},652:{color:[3,255,237],opacity:1,label:"Cbm_Right_7mid"},653:{color:[204,255,255],opacity:1,label:"Cbm_Right_7lat"},654:{color:[86,74,147],opacity:1,label:"Cbm_Right_8med"},655:{color:[114,114,190],opacity:1,label:"Cbm_Right_8mid"},656:{color:[184,178,255],opacity:1,label:"Cbm_Right_8lat"},657:{color:[126,138,37],opacity:1,label:"Cbm_Right_PUNs"},658:{color:[189,197,117],opacity:1,label:"Cbm_Right_TONs"},659:{color:[240,230,140],opacity:1,label:"Cbm_Right_FLOs"},660:{color:[204,0,0],opacity:1,label:"Cbm_Left_I_V_med"},661:{color:[255,0,0],opacity:1,label:"Cbm_Left_I_V_mid"},662:{color:[0,0,255],opacity:1,label:"Cbm_Left_VI_med"},663:{color:[30,144,255],opacity:1,label:"Cbm_Left_VI_mid"},664:{color:[100,212,237],opacity:1,label:"Cbm_Left_VI_lat"},665:{color:[218,165,32],opacity:1,label:"Cbm_Left_CrusI_med"},666:{color:[255,215,0],opacity:1,label:"Cbm_Left_CrusI_mid"},667:{color:[255,255,166],opacity:1,label:"Cbm_Left_CrusI_lat"},668:{color:[153,0,204], opacity:1,label:"Cbm_Left_CrusII_med"},669:{color:[153,141,209],opacity:1,label:"Cbm_Left_CrusII_mid"},670:{color:[204,204,255],opacity:1,label:"Cbm_Left_CrusII_lat"},671:{color:[31,212,194],opacity:1,label:"Cbm_Left_7med"},672:{color:[3,255,237],opacity:1,label:"Cbm_Left_7mid"},673:{color:[204,255,255],opacity:1,label:"Cbm_Left_7lat"},674:{color:[86,74,147],opacity:1,label:"Cbm_Left_8med"},675:{color:[114,114,190],opacity:1,label:"Cbm_Left_8mid"},676:{color:[184,178,255],opacity:1,label:"Cbm_Left_8lat"},677:{color:[126,138,37],opacity:1,label:"Cbm_Left_PUNs"},678:{color:[189,197,117],opacity:1,label:"Cbm_Left_TONs"},679:{color:[240,230,140],opacity:1,label:"Cbm_Left_FLOs"},690:{color:[122,135,50],opacity:1,label:"CbmWM_Gyri_Left"},691:{color:[122,135,50],opacity:1,label:"CbmWM_Gyri_Right"},701:{color:[120,18,134],opacity:1,label:"CSF-FSL-FAST"},702:{color:[205,62,78],opacity:1,label:"GrayMatter-FSL-FAST"},703:{color:[0,225,0],opacity:1,label:"WhiteMatter-FSL-FAST"},999:{color:[255,100,100],opacity:1,label:"SUSPICIOUS"},1e3:{color:[25,5,25],opacity:1,label:"ctx-lh-unknown"},1001:{color:[25,100,40],opacity:1,label:"ctx-lh-bankssts"},1002:{color:[125,100,160],opacity:1,label:"ctx-lh-caudalanteriorcingulate"},1003:{color:[100,25,0],opacity:1,label:"ctx-lh-caudalmiddlefrontal"},1004:{color:[120,70,50],opacity:1,label:"ctx-lh-corpuscallosum"},1005:{color:[220,20,100],opacity:1,label:"ctx-lh-cuneus"},1006:{color:[220,20,10],opacity:1,label:"ctx-lh-entorhinal"},1007:{color:[180,220,140],opacity:1,label:"ctx-lh-fusiform"},1008:{color:[220,60,220],opacity:1,label:"ctx-lh-inferiorparietal"},1009:{color:[180,40,120],opacity:1,label:"ctx-lh-inferiortemporal"},1010:{color:[140,20,140],opacity:1,label:"ctx-lh-isthmuscingulate"},1011:{color:[20,30,140],opacity:1,label:"ctx-lh-lateraloccipital"},1012:{color:[35,75,50],opacity:1,label:"ctx-lh-lateralorbitofrontal"},1013:{color:[225,140,140],opacity:1,label:"ctx-lh-lingual"},1014:{color:[200,35,75],opacity:1,label:"ctx-lh-medialorbitofrontal"},1015:{color:[160,100,50],opacity:1,label:"ctx-lh-middletemporal"},1016:{color:[20,220,60],opacity:1,label:"ctx-lh-parahippocampal"},1017:{color:[60,220,60],opacity:1,label:"ctx-lh-paracentral"},1018:{color:[220,180,140],opacity:1,label:"ctx-lh-parsopercularis"},1019:{color:[20,100,50],opacity:1,label:"ctx-lh-parsorbitalis"},1020:{color:[220,60,20],opacity:1,label:"ctx-lh-parstriangularis"},1021:{color:[120,100,60],opacity:1,label:"ctx-lh-pericalcarine"},1022:{color:[220,20,20],opacity:1,label:"ctx-lh-postcentral"},1023:{color:[220,180,220],opacity:1,label:"ctx-lh-posteriorcingulate"},1024:{color:[60,20,220],opacity:1,label:"ctx-lh-precentral"},1025:{color:[160,140,180],opacity:1,label:"ctx-lh-precuneus"},1026:{color:[80,20,140],opacity:1,label:"ctx-lh-rostralanteriorcingulate"},1027:{color:[75,50,125],opacity:1,label:"ctx-lh-rostralmiddlefrontal"},1028:{color:[20,220,160],opacity:1,label:"ctx-lh-superiorfrontal"},1029:{color:[20,180,140],opacity:1,label:"ctx-lh-superiorparietal"},1030:{color:[140,220,220],opacity:1,label:"ctx-lh-superiortemporal"},1031:{color:[80,160,20],opacity:1,label:"ctx-lh-supramarginal"},1032:{color:[100,0,100],opacity:1,label:"ctx-lh-frontalpole"},1033:{color:[70,70,70],opacity:1,label:"ctx-lh-temporalpole"},1034:{color:[150,150,200],opacity:1,label:"ctx-lh-transversetemporal"},1035:{color:[255,192,32],opacity:1,label:"ctx-lh-insula"},2e3:{color:[25,5,25],opacity:1,label:"ctx-rh-unknown"},2001:{color:[25,100,40],opacity:1,label:"ctx-rh-bankssts"},2002:{color:[125,100,160],opacity:1,label:"ctx-rh-caudalanteriorcingulate"},2003:{color:[100,25,0],opacity:1,label:"ctx-rh-caudalmiddlefrontal"},2004:{color:[120,70,50],opacity:1,label:"ctx-rh-corpuscallosum"},2005:{color:[220,20,100],opacity:1,label:"ctx-rh-cuneus"},2006:{color:[220,20,10],opacity:1,label:"ctx-rh-entorhinal"},2007:{color:[180,220,140],opacity:1,label:"ctx-rh-fusiform"},2008:{color:[220,60,220],opacity:1,label:"ctx-rh-inferiorparietal"},2009:{color:[180,40,120],opacity:1,label:"ctx-rh-inferiortemporal"},2010:{color:[140,20,140],opacity:1,label:"ctx-rh-isthmuscingulate"},2011:{color:[20,30,140],opacity:1,label:"ctx-rh-lateraloccipital"},2012:{color:[35,75,50],opacity:1,label:"ctx-rh-lateralorbitofrontal"},2013:{color:[225,140,140],opacity:1,label:"ctx-rh-lingual"},2014:{color:[200,35,75],opacity:1,label:"ctx-rh-medialorbitofrontal"},2015:{color:[160,100,50],opacity:1,label:"ctx-rh-middletemporal"},2016:{color:[20,220,60],opacity:1,label:"ctx-rh-parahippocampal"},2017:{color:[60,220,60],opacity:1,label:"ctx-rh-paracentral"},2018:{color:[220,180,140],opacity:1,label:"ctx-rh-parsopercularis"},2019:{color:[20,100,50],opacity:1,label:"ctx-rh-parsorbitalis"},2020:{color:[220,60,20],opacity:1,label:"ctx-rh-parstriangularis"},2021:{color:[120,100,60],opacity:1,label:"ctx-rh-pericalcarine"},2022:{color:[220,20,20],opacity:1,label:"ctx-rh-postcentral"},2023:{color:[220,180,220],opacity:1,label:"ctx-rh-posteriorcingulate"},2024:{color:[60,20,220],opacity:1,label:"ctx-rh-precentral"},2025:{color:[160,140,180],opacity:1,label:"ctx-rh-precuneus"},2026:{color:[80,20,140],opacity:1,label:"ctx-rh-rostralanteriorcingulate"},2027:{color:[75,50,125],opacity:1,label:"ctx-rh-rostralmiddlefrontal"},2028:{color:[20,220,160],opacity:1,label:"ctx-rh-superiorfrontal"},2029:{color:[20,180,140],opacity:1,label:"ctx-rh-superiorparietal"},2030:{color:[140,220,220],opacity:1,label:"ctx-rh-superiortemporal"},2031:{color:[80,160,20],opacity:1,label:"ctx-rh-supramarginal"},2032:{color:[100,0,100],opacity:1,label:"ctx-rh-frontalpole"},2033:{color:[70,70,70],opacity:1,label:"ctx-rh-temporalpole"},2034:{color:[150,150,200],opacity:1,label:"ctx-rh-transversetemporal"},2035:{color:[255,192,32],opacity:1,label:"ctx-rh-insula"},3e3:{color:[230,250,230],opacity:1,label:"wm-lh-unknown"},3001:{color:[230,155,215],opacity:1,label:"wm-lh-bankssts"},3002:{color:[130,155,95],opacity:1,label:"wm-lh-caudalanteriorcingulate"},3003:{color:[155,230,255],opacity:1,label:"wm-lh-caudalmiddlefrontal"},3004:{color:[135,185,205],opacity:1,label:"wm-lh-corpuscallosum"},3005:{color:[35,235,155],opacity:1,label:"wm-lh-cuneus"},3006:{color:[35,235,245],opacity:1,label:"wm-lh-entorhinal"},3007:{color:[75,35,115],opacity:1,label:"wm-lh-fusiform"},3008:{color:[35,195,35],opacity:1,label:"wm-lh-inferiorparietal"},3009:{color:[75,215,135],opacity:1,label:"wm-lh-inferiortemporal"},3010:{color:[115,235,115],opacity:1,label:"wm-lh-isthmuscingulate"},3011:{color:[235,225,115],opacity:1,label:"wm-lh-lateraloccipital"},3012:{color:[220,180,205],opacity:1,label:"wm-lh-lateralorbitofrontal"},3013:{color:[30,115,115],opacity:1,label:"wm-lh-lingual"},3014:{color:[55,220,180],opacity:1,label:"wm-lh-medialorbitofrontal"},3015:{color:[95,155,205],opacity:1,label:"wm-lh-middletemporal"},3016:{color:[235,35,195],opacity:1,label:"wm-lh-parahippocampal"},3017:{color:[195,35,195],opacity:1,label:"wm-lh-paracentral"},3018:{color:[35,75,115],opacity:1,label:"wm-lh-parsopercularis"},3019:{color:[235,155,205],opacity:1,label:"wm-lh-parsorbitalis"},3020:{color:[35,195,235],opacity:1,label:"wm-lh-parstriangularis"},3021:{color:[135,155,195],opacity:1,label:"wm-lh-pericalcarine"},3022:{color:[35,235,235],opacity:1,label:"wm-lh-postcentral"},3023:{color:[35,75,35],opacity:1,label:"wm-lh-posteriorcingulate"},3024:{color:[195,235,35],opacity:1,label:"wm-lh-precentral"},3025:{color:[95,115,75],opacity:1,label:"wm-lh-precuneus"},3026:{color:[175,235,115],opacity:1,label:"wm-lh-rostralanteriorcingulate"},3027:{color:[180,205,130],opacity:1,label:"wm-lh-rostralmiddlefrontal"},3028:{color:[235,35,95],opacity:1,label:"wm-lh-superiorfrontal"},3029:{color:[235,75,115],opacity:1,label:"wm-lh-superiorparietal"},3030:{color:[115,35,35],opacity:1,label:"wm-lh-superiortemporal"},3031:{color:[175,95,235],opacity:1,label:"wm-lh-supramarginal"},3032:{color:[155,255,155],opacity:1,label:"wm-lh-frontalpole"},3033:{color:[185,185,185],opacity:1,label:"wm-lh-temporalpole"},3034:{color:[105,105,55],opacity:1,label:"wm-lh-transversetemporal"},3035:{color:[20,220,160],opacity:1,label:"wm-lh-insula"},4e3:{color:[230,250,230],opacity:1,label:"wm-rh-unknown"},4001:{color:[230,155,215],opacity:1,label:"wm-rh-bankssts"},4002:{color:[130,155,95],opacity:1,label:"wm-rh-caudalanteriorcingulate"},4003:{color:[155,230,255],opacity:1,label:"wm-rh-caudalmiddlefrontal"},4004:{color:[135,185,205],opacity:1,label:"wm-rh-corpuscallosum"},4005:{color:[35,235,155],opacity:1,label:"wm-rh-cuneus"},4006:{color:[35,235,245],opacity:1,label:"wm-rh-entorhinal"},4007:{color:[75,35,115],opacity:1,label:"wm-rh-fusiform"},4008:{color:[35,195,35],opacity:1,label:"wm-rh-inferiorparietal"},4009:{color:[75,215,135],opacity:1,label:"wm-rh-inferiortemporal"},4010:{color:[115,235,115],opacity:1,label:"wm-rh-isthmuscingulate"},4011:{color:[235,225,115],opacity:1,label:"wm-rh-lateraloccipital"},4012:{color:[220,180,205],opacity:1,label:"wm-rh-lateralorbitofrontal"},4013:{color:[30,115,115],opacity:1,label:"wm-rh-lingual"},4014:{color:[55,220,180],opacity:1,label:"wm-rh-medialorbitofrontal"},4015:{color:[95,155,205],opacity:1,label:"wm-rh-middletemporal"},4016:{color:[235,35,195],opacity:1,label:"wm-rh-parahippocampal"},4017:{color:[195,35,195],opacity:1,label:"wm-rh-paracentral"},4018:{color:[35,75,115],opacity:1,label:"wm-rh-parsopercularis"},4019:{color:[235,155,205],opacity:1,label:"wm-rh-parsorbitalis"},4020:{color:[35,195,235],opacity:1,label:"wm-rh-parstriangularis"},4021:{color:[135,155,195],opacity:1,label:"wm-rh-pericalcarine"},4022:{color:[35,235,235],opacity:1,label:"wm-rh-postcentral"},4023:{color:[35,75,35],opacity:1,label:"wm-rh-posteriorcingulate"},4024:{color:[195,235,35],opacity:1,label:"wm-rh-precentral"},4025:{color:[95,115,75],opacity:1,label:"wm-rh-precuneus"},4026:{color:[175,235,115],opacity:1,label:"wm-rh-rostralanteriorcingulate"},4027:{color:[180,205,130],opacity:1,label:"wm-rh-rostralmiddlefrontal"},4028:{color:[235,35,95],opacity:1,label:"wm-rh-superiorfrontal"},4029:{color:[235,75,115],opacity:1,label:"wm-rh-superiorparietal"},4030:{color:[115,35,35],opacity:1,label:"wm-rh-superiortemporal"},4031:{color:[175,95,235],opacity:1,label:"wm-rh-supramarginal"},4032:{color:[155,255,155],opacity:1,label:"wm-rh-frontalpole"},4033:{color:[185,185,185],opacity:1,label:"wm-rh-temporalpole"},4034:{color:[105,105,55],opacity:1,label:"wm-rh-transversetemporal"},4035:{color:[20,220,160],opacity:1,label:"wm-rh-insula"},3201:{color:[235,35,95],opacity:1,label:"wm-lh-frontal-lobe"},3203:{color:[35,75,35],opacity:1,label:"wm-lh-cingulate-lobe"},3204:{color:[135,155,195],opacity:1,label:"wm-lh-occiptal-lobe"},3205:{color:[115,35,35],opacity:1,label:"wm-lh-temporal-lobe"},3206:{color:[35,195,35],opacity:1,label:"wm-lh-parietal-lobe"},3207:{color:[20,220,160],opacity:1,label:"wm-lh-insula-lobe"},4201:{color:[235,35,95],opacity:1,label:"wm-rh-frontal-lobe"},4203:{color:[35,75,35],opacity:1,label:"wm-rh-cingulate-lobe"},4204:{color:[135,155,195],opacity:1,label:"wm-rh-occiptal-lobe"},4205:{color:[115,35,35],opacity:1,label:"wm-rh-temporal-lobe"},4206:{color:[35,195,35],opacity:1,label:"wm-rh-parietal-lobe"},4207:{color:[20,220,160],opacity:1,label:"wm-rh-insula-lobe"},1100:{color:[0,0,0],opacity:1,label:"ctx-lh-Unknown"},1101:{color:[50,50,50],opacity:1,label:"ctx-lh-Corpus_callosum"},1102:{color:[180,20,30],opacity:1,label:"ctx-lh-G_and_S_Insula_ONLY_AVERAGE"},1103:{color:[60,25,25],opacity:1,label:"ctx-lh-G_cingulate-Isthmus"},1104:{color:[25,60,60],opacity:1,label:"ctx-lh-G_cingulate-Main_part"},1200:{color:[25,60,61],opacity:1,label:"ctx-lh-G_cingulate-caudal_ACC"},1201:{color:[25,90,60],opacity:1,label:"ctx-lh-G_cingulate-rostral_ACC"},1202:{color:[25,120,60],opacity:1,label:"ctx-lh-G_cingulate-posterior"},1205:{color:[25,150,60],opacity:1,label:"ctx-lh-S_cingulate-caudal_ACC"},1206:{color:[25,180,60],opacity:1,label:"ctx-lh-S_cingulate-rostral_ACC"},1207:{color:[25,210,60],opacity:1,label:"ctx-lh-S_cingulate-posterior"},1210:{color:[25,150,90],opacity:1,label:"ctx-lh-S_pericallosal-caudal"},1211:{color:[25,180,90],opacity:1,label:"ctx-lh-S_pericallosal-rostral"},1212:{color:[25,210,90],opacity:1,label:"ctx-lh-S_pericallosal-posterior"},1105:{color:[180,20,20],opacity:1,label:"ctx-lh-G_cuneus"},1106:{color:[220,20,100],opacity:1,label:"ctx-lh-G_frontal_inf-Opercular_part"},1107:{color:[140,60,60],opacity:1,label:"ctx-lh-G_frontal_inf-Orbital_part"},1108:{color:[180,220,140],opacity:1,label:"ctx-lh-G_frontal_inf-Triangular_part"},1109:{color:[140,100,180],opacity:1,label:"ctx-lh-G_frontal_middle"},1110:{color:[180,20,140],opacity:1,label:"ctx-lh-G_frontal_superior"},1111:{color:[140,20,140],opacity:1,label:"ctx-lh-G_frontomarginal"},1112:{color:[21,10,10],opacity:1,label:"ctx-lh-G_insular_long"},1113:{color:[225,140,140],opacity:1,label:"ctx-lh-G_insular_short"},1114:{color:[23,60,180],opacity:1,label:"ctx-lh-G_and_S_occipital_inferior"},1115:{color:[180,60,180],opacity:1,label:"ctx-lh-G_occipital_middle"},1116:{color:[20,220,60],opacity:1,label:"ctx-lh-G_occipital_superior"},1117:{color:[60,20,140],opacity:1,label:"ctx-lh-G_occipit-temp_lat-Or_fusiform"},1118:{color:[220,180,140],opacity:1,label:"ctx-lh-G_occipit-temp_med-Lingual_part"},1119:{color:[65,100,20],opacity:1,label:"ctx-lh-G_occipit-temp_med-Parahippocampal_part"},1120:{color:[220,60,20],opacity:1,label:"ctx-lh-G_orbital"},1121:{color:[60,100,60],opacity:1,label:"ctx-lh-G_paracentral"},1122:{color:[20,60,220],opacity:1,label:"ctx-lh-G_parietal_inferior-Angular_part"},1123:{color:[100,100,60],opacity:1,label:"ctx-lh-G_parietal_inferior-Supramarginal_part"},1124:{color:[220,180,220],opacity:1,label:"ctx-lh-G_parietal_superior"},1125:{color:[20,180,140],opacity:1,label:"ctx-lh-G_postcentral"},1126:{color:[60,140,180],opacity:1,label:"ctx-lh-G_precentral"},1127:{color:[25,20,140],opacity:1,label:"ctx-lh-G_precuneus"},1128:{color:[20,60,100],opacity:1,label:"ctx-lh-G_rectus"},1129:{color:[60,220,20],opacity:1,label:"ctx-lh-G_subcallosal"},1130:{color:[60,20,220],opacity:1,label:"ctx-lh-G_subcentral"},1131:{color:[220,220,100],opacity:1,label:"ctx-lh-G_temporal_inferior"},1132:{color:[180,60,60],opacity:1,label:"ctx-lh-G_temporal_middle"},1133:{color:[60,60,220],opacity:1,label:"ctx-lh-G_temp_sup-G_temp_transv_and_interm_S"},1134:{color:[220,60,220],opacity:1,label:"ctx-lh-G_temp_sup-Lateral_aspect"},1135:{color:[65,220,60],opacity:1,label:"ctx-lh-G_temp_sup-Planum_polare"},1136:{color:[25,140,20],opacity:1,label:"ctx-lh-G_temp_sup-Planum_tempolare"},1137:{color:[13,0,250],opacity:1,label:"ctx-lh-G_and_S_transverse_frontopolar"},1138:{color:[61,20,220],opacity:1,label:"ctx-lh-Lat_Fissure-ant_sgt-ramus_horizontal"},1139:{color:[61,20,60],opacity:1,label:"ctx-lh-Lat_Fissure-ant_sgt-ramus_vertical"},1140:{color:[61,60,100],opacity:1,label:"ctx-lh-Lat_Fissure-post_sgt"},1141:{color:[25,25,25],opacity:1,label:"ctx-lh-Medial_wall"},1142:{color:[140,20,60],opacity:1,label:"ctx-lh-Pole_occipital"},1143:{color:[220,180,20],opacity:1,label:"ctx-lh-Pole_temporal"},1144:{color:[63,180,180],opacity:1,label:"ctx-lh-S_calcarine"},1145:{color:[221,20,10],opacity:1,label:"ctx-lh-S_central"},1146:{color:[21,220,20],opacity:1,label:"ctx-lh-S_central_insula"},1147:{color:[183,100,20],opacity:1,label:"ctx-lh-S_cingulate-Main_part_and_Intracingulate"},1148:{color:[221,20,100],opacity:1,label:"ctx-lh-S_cingulate-Marginalis_part"},1149:{color:[221,60,140],opacity:1,label:"ctx-lh-S_circular_insula_anterior"},1150:{color:[221,20,220],opacity:1,label:"ctx-lh-S_circular_insula_inferior"},1151:{color:[61,220,220],opacity:1,label:"ctx-lh-S_circular_insula_superior"},1152:{color:[100,200,200],opacity:1,label:"ctx-lh-S_collateral_transverse_ant"},1153:{color:[10,200,200],opacity:1,label:"ctx-lh-S_collateral_transverse_post"},1154:{color:[221,220,20],opacity:1,label:"ctx-lh-S_frontal_inferior"},1155:{color:[141,20,100],opacity:1,label:"ctx-lh-S_frontal_middle"},1156:{color:[61,220,100],opacity:1,label:"ctx-lh-S_frontal_superior"},1157:{color:[21,220,60],opacity:1,label:"ctx-lh-S_frontomarginal"},1158:{color:[141,60,20],opacity:1,label:"ctx-lh-S_intermedius_primus-Jensen"},1159:{color:[143,20,220],opacity:1,label:"ctx-lh-S_intraparietal-and_Parietal_transverse"},1160:{color:[61,20,180],opacity:1,label:"ctx-lh-S_occipital_anterior"},1161:{color:[101,60,220],opacity:1,label:"ctx-lh-S_occipital_middle_and_Lunatus"},1162:{color:[21,20,140],opacity:1,label:"ctx-lh-S_occipital_superior_and_transversalis"},1163:{color:[221,140,20],opacity:1,label:"ctx-lh-S_occipito-temporal_lateral"},1164:{color:[141,100,220],opacity:1,label:"ctx-lh-S_occipito-temporal_medial_and_S_Lingual"},1165:{color:[101,20,20],opacity:1,label:"ctx-lh-S_orbital-H_shapped"},1166:{color:[221,100,20],opacity:1,label:"ctx-lh-S_orbital_lateral"},1167:{color:[181,200,20],opacity:1,label:"ctx-lh-S_orbital_medial-Or_olfactory"},1168:{color:[21,180,140],opacity:1,label:"ctx-lh-S_paracentral"},1169:{color:[101,100,180],opacity:1,label:"ctx-lh-S_parieto_occipital"},1170:{color:[181,220,20],opacity:1,label:"ctx-lh-S_pericallosal"},1171:{color:[21,140,200],opacity:1,label:"ctx-lh-S_postcentral"},1172:{color:[21,20,240],opacity:1,label:"ctx-lh-S_precentral-Inferior-part"},1173:{color:[21,20,200],opacity:1,label:"ctx-lh-S_precentral-Superior-part"},1174:{color:[61,180,60],opacity:1,label:"ctx-lh-S_subcentral_ant"},1175:{color:[61,180,250],opacity:1,label:"ctx-lh-S_subcentral_post"},1176:{color:[21,20,60],opacity:1,label:"ctx-lh-S_suborbital"},1177:{color:[101,60,60],opacity:1,label:"ctx-lh-S_subparietal"},1178:{color:[21,220,220],opacity:1,label:"ctx-lh-S_supracingulate"},1179:{color:[21,180,180],opacity:1,label:"ctx-lh-S_temporal_inferior"},1180:{color:[223,220,60],opacity:1,label:"ctx-lh-S_temporal_superior"},1181:{color:[221,60,60],opacity:1,label:"ctx-lh-S_temporal_transverse"},2100:{color:[0,0,0],opacity:1,label:"ctx-rh-Unknown"},2101:{color:[50,50,50],opacity:1,label:"ctx-rh-Corpus_callosum"},2102:{color:[180,20,30],opacity:1,label:"ctx-rh-G_and_S_Insula_ONLY_AVERAGE"},2103:{color:[60,25,25],opacity:1,label:"ctx-rh-G_cingulate-Isthmus"},2104:{color:[25,60,60],opacity:1,label:"ctx-rh-G_cingulate-Main_part"},2105:{color:[180,20,20],opacity:1,label:"ctx-rh-G_cuneus"},2106:{color:[220,20,100],opacity:1,label:"ctx-rh-G_frontal_inf-Opercular_part"},2107:{color:[140,60,60],opacity:1,label:"ctx-rh-G_frontal_inf-Orbital_part"},2108:{color:[180,220,140],opacity:1,label:"ctx-rh-G_frontal_inf-Triangular_part"},2109:{color:[140,100,180],opacity:1,label:"ctx-rh-G_frontal_middle"},2110:{color:[180,20,140],opacity:1,label:"ctx-rh-G_frontal_superior"},2111:{color:[140,20,140],opacity:1,label:"ctx-rh-G_frontomarginal"},2112:{color:[21,10,10],opacity:1,label:"ctx-rh-G_insular_long"},2113:{color:[225,140,140],opacity:1,label:"ctx-rh-G_insular_short"},2114:{color:[23,60,180],opacity:1,label:"ctx-rh-G_and_S_occipital_inferior"},2115:{color:[180,60,180],opacity:1,label:"ctx-rh-G_occipital_middle"},2116:{color:[20,220,60],opacity:1,label:"ctx-rh-G_occipital_superior"},2117:{color:[60,20,140],opacity:1,label:"ctx-rh-G_occipit-temp_lat-Or_fusiform"},2118:{color:[220,180,140],opacity:1,label:"ctx-rh-G_occipit-temp_med-Lingual_part"},2119:{color:[65,100,20],opacity:1,label:"ctx-rh-G_occipit-temp_med-Parahippocampal_part"},2120:{color:[220,60,20],opacity:1,label:"ctx-rh-G_orbital"},2121:{color:[60,100,60],opacity:1,label:"ctx-rh-G_paracentral"},2122:{color:[20,60,220],opacity:1,label:"ctx-rh-G_parietal_inferior-Angular_part"},2123:{color:[100,100,60],opacity:1,label:"ctx-rh-G_parietal_inferior-Supramarginal_part"},2124:{color:[220,180,220],opacity:1,label:"ctx-rh-G_parietal_superior"},2125:{color:[20,180,140],opacity:1,label:"ctx-rh-G_postcentral"},2126:{color:[60,140,180],opacity:1,label:"ctx-rh-G_precentral"},2127:{color:[25,20,140],opacity:1,label:"ctx-rh-G_precuneus"},2128:{color:[20,60,100],opacity:1,label:"ctx-rh-G_rectus"},2129:{color:[60,220,20],opacity:1,label:"ctx-rh-G_subcallosal"},2130:{color:[60,20,220],opacity:1,label:"ctx-rh-G_subcentral"},2131:{color:[220,220,100],opacity:1,label:"ctx-rh-G_temporal_inferior"},2132:{color:[180,60,60],opacity:1,label:"ctx-rh-G_temporal_middle"},2133:{color:[60,60,220],opacity:1,label:"ctx-rh-G_temp_sup-G_temp_transv_and_interm_S"},2134:{color:[220,60,220],opacity:1,label:"ctx-rh-G_temp_sup-Lateral_aspect"},2135:{color:[65,220,60],opacity:1,label:"ctx-rh-G_temp_sup-Planum_polare"},2136:{color:[25,140,20],opacity:1,label:"ctx-rh-G_temp_sup-Planum_tempolare"},2137:{color:[13,0,250],opacity:1,label:"ctx-rh-G_and_S_transverse_frontopolar"},2138:{color:[61,20,220],opacity:1,label:"ctx-rh-Lat_Fissure-ant_sgt-ramus_horizontal"},2139:{color:[61,20,60],opacity:1,label:"ctx-rh-Lat_Fissure-ant_sgt-ramus_vertical"},2140:{color:[61,60,100],opacity:1,label:"ctx-rh-Lat_Fissure-post_sgt"},2141:{color:[25,25,25],opacity:1,label:"ctx-rh-Medial_wall"},2142:{color:[140,20,60],opacity:1,label:"ctx-rh-Pole_occipital"},2143:{color:[220,180,20],opacity:1,label:"ctx-rh-Pole_temporal"},2144:{color:[63,180,180],opacity:1,label:"ctx-rh-S_calcarine"},2145:{color:[221,20,10],opacity:1,label:"ctx-rh-S_central"},2146:{color:[21,220,20],opacity:1,label:"ctx-rh-S_central_insula"},2147:{color:[183,100,20],opacity:1,label:"ctx-rh-S_cingulate-Main_part_and_Intracingulate"},2148:{color:[221,20,100],opacity:1,label:"ctx-rh-S_cingulate-Marginalis_part"},2149:{color:[221,60,140],opacity:1,label:"ctx-rh-S_circular_insula_anterior"},2150:{color:[221,20,220],opacity:1,label:"ctx-rh-S_circular_insula_inferior"},2151:{color:[61,220,220],opacity:1,label:"ctx-rh-S_circular_insula_superior"},2152:{color:[100,200,200],opacity:1,label:"ctx-rh-S_collateral_transverse_ant"},2153:{color:[10,200,200],opacity:1,label:"ctx-rh-S_collateral_transverse_post"},2154:{color:[221,220,20],opacity:1,label:"ctx-rh-S_frontal_inferior"},2155:{color:[141,20,100],opacity:1,label:"ctx-rh-S_frontal_middle"},2156:{color:[61,220,100],opacity:1,label:"ctx-rh-S_frontal_superior"},2157:{color:[21,220,60],opacity:1,label:"ctx-rh-S_frontomarginal"},2158:{color:[141,60,20],opacity:1,label:"ctx-rh-S_intermedius_primus-Jensen"},2159:{color:[143,20,220],opacity:1,label:"ctx-rh-S_intraparietal-and_Parietal_transverse"},2160:{color:[61,20,180],opacity:1,label:"ctx-rh-S_occipital_anterior"},2161:{color:[101,60,220],opacity:1,label:"ctx-rh-S_occipital_middle_and_Lunatus"},2162:{color:[21,20,140],opacity:1,label:"ctx-rh-S_occipital_superior_and_transversalis"},2163:{color:[221,140,20],opacity:1,label:"ctx-rh-S_occipito-temporal_lateral"},2164:{color:[141,100,220],opacity:1,label:"ctx-rh-S_occipito-temporal_medial_and_S_Lingual"},2165:{color:[101,20,20],opacity:1,label:"ctx-rh-S_orbital-H_shapped"},2166:{color:[221,100,20],opacity:1,label:"ctx-rh-S_orbital_lateral"},2167:{color:[181,200,20],opacity:1,label:"ctx-rh-S_orbital_medial-Or_olfactory"},2168:{color:[21,180,140],opacity:1,label:"ctx-rh-S_paracentral"},2169:{color:[101,100,180],opacity:1,label:"ctx-rh-S_parieto_occipital"},2170:{color:[181,220,20],opacity:1,label:"ctx-rh-S_pericallosal"},2171:{color:[21,140,200],opacity:1,label:"ctx-rh-S_postcentral"},2172:{color:[21,20,240],opacity:1,label:"ctx-rh-S_precentral-Inferior-part"},2173:{color:[21,20,200],opacity:1,label:"ctx-rh-S_precentral-Superior-part"},2174:{color:[61,180,60],opacity:1,label:"ctx-rh-S_subcentral_ant"},2175:{color:[61,180,250],opacity:1,label:"ctx-rh-S_subcentral_post"},2176:{color:[21,20,60],opacity:1,label:"ctx-rh-S_suborbital"},2177:{color:[101,60,60],opacity:1,label:"ctx-rh-S_subparietal"},2178:{color:[21,220,220],opacity:1,label:"ctx-rh-S_supracingulate"},2179:{color:[21,180,180],opacity:1,label:"ctx-rh-S_temporal_inferior"},2180:{color:[223,220,60],opacity:1,label:"ctx-rh-S_temporal_superior"},2181:{color:[221,60,60],opacity:1,label:"ctx-rh-S_temporal_transverse"},2200:{color:[25,60,61],opacity:1,label:"ctx-rh-G_cingulate-caudal_ACC"},2201:{color:[25,90,60],opacity:1,label:"ctx-rh-G_cingulate-rostral_ACC"},2202:{color:[25,120,60],opacity:1,label:"ctx-rh-G_cingulate-posterior"},2205:{color:[25,150,60],opacity:1,label:"ctx-rh-S_cingulate-caudal_ACC"},2206:{color:[25,180,60],opacity:1,label:"ctx-rh-S_cingulate-rostral_ACC"},2207:{color:[25,210,60],opacity:1,label:"ctx-rh-S_cingulate-posterior"},2210:{color:[25,150,90],opacity:1,label:"ctx-rh-S_pericallosal-caudal"},2211:{color:[25,180,90],opacity:1,label:"ctx-rh-S_pericallosal-rostral"},2212:{color:[25,210,90],opacity:1,label:"ctx-rh-S_pericallosal-posterior"},3100:{color:[0,0,0],opacity:1,label:"wm-lh-Unknown"},3101:{color:[50,50,50],opacity:1,label:"wm-lh-Corpus_callosum"},3102:{color:[180,20,30],opacity:1,label:"wm-lh-G_and_S_Insula_ONLY_AVERAGE"},3103:{color:[60,25,25],opacity:1,label:"wm-lh-G_cingulate-Isthmus"},3104:{color:[25,60,60],opacity:1,label:"wm-lh-G_cingulate-Main_part"},3105:{color:[180,20,20],opacity:1,label:"wm-lh-G_cuneus"},3106:{color:[220,20,100],opacity:1,label:"wm-lh-G_frontal_inf-Opercular_part"},3107:{color:[140,60,60],opacity:1,label:"wm-lh-G_frontal_inf-Orbital_part"},3108:{color:[180,220,140],opacity:1,label:"wm-lh-G_frontal_inf-Triangular_part"},3109:{color:[140,100,180],opacity:1,label:"wm-lh-G_frontal_middle"},3110:{color:[180,20,140],opacity:1,label:"wm-lh-G_frontal_superior"},3111:{color:[140,20,140],opacity:1,label:"wm-lh-G_frontomarginal"},3112:{color:[21,10,10],opacity:1,label:"wm-lh-G_insular_long"},3113:{color:[225,140,140],opacity:1,label:"wm-lh-G_insular_short"},3114:{color:[23,60,180],opacity:1,label:"wm-lh-G_and_S_occipital_inferior"},3115:{color:[180,60,180],opacity:1,label:"wm-lh-G_occipital_middle"},3116:{color:[20,220,60],opacity:1,label:"wm-lh-G_occipital_superior"},3117:{color:[60,20,140],opacity:1,label:"wm-lh-G_occipit-temp_lat-Or_fusiform"},3118:{color:[220,180,140],opacity:1,label:"wm-lh-G_occipit-temp_med-Lingual_part"},3119:{color:[65,100,20],opacity:1,label:"wm-lh-G_occipit-temp_med-Parahippocampal_part"},3120:{color:[220,60,20],opacity:1,label:"wm-lh-G_orbital"},3121:{color:[60,100,60],opacity:1,label:"wm-lh-G_paracentral"},3122:{color:[20,60,220],opacity:1,label:"wm-lh-G_parietal_inferior-Angular_part"},3123:{color:[100,100,60],opacity:1,label:"wm-lh-G_parietal_inferior-Supramarginal_part"},3124:{color:[220,180,220],opacity:1,label:"wm-lh-G_parietal_superior"},3125:{color:[20,180,140],opacity:1,label:"wm-lh-G_postcentral"},3126:{color:[60,140,180],opacity:1,label:"wm-lh-G_precentral"},3127:{color:[25,20,140],opacity:1,label:"wm-lh-G_precuneus"},3128:{color:[20,60,100],opacity:1,label:"wm-lh-G_rectus"},3129:{color:[60,220,20],opacity:1,label:"wm-lh-G_subcallosal"},3130:{color:[60,20,220],opacity:1,label:"wm-lh-G_subcentral"},3131:{color:[220,220,100],opacity:1,label:"wm-lh-G_temporal_inferior"},3132:{color:[180,60,60],opacity:1,label:"wm-lh-G_temporal_middle"},3133:{color:[60,60,220],opacity:1,label:"wm-lh-G_temp_sup-G_temp_transv_and_interm_S"},3134:{color:[220,60,220],opacity:1,label:"wm-lh-G_temp_sup-Lateral_aspect"},3135:{color:[65,220,60],opacity:1,label:"wm-lh-G_temp_sup-Planum_polare"},3136:{color:[25,140,20],opacity:1,label:"wm-lh-G_temp_sup-Planum_tempolare"},3137:{color:[13,0,250],opacity:1,label:"wm-lh-G_and_S_transverse_frontopolar"},3138:{color:[61,20,220],opacity:1,label:"wm-lh-Lat_Fissure-ant_sgt-ramus_horizontal"},3139:{color:[61,20,60],opacity:1,label:"wm-lh-Lat_Fissure-ant_sgt-ramus_vertical"},3140:{color:[61,60,100],opacity:1,label:"wm-lh-Lat_Fissure-post_sgt"},3141:{color:[25,25,25],opacity:1,label:"wm-lh-Medial_wall"},3142:{color:[140,20,60],opacity:1,label:"wm-lh-Pole_occipital"},3143:{color:[220,180,20],opacity:1,label:"wm-lh-Pole_temporal"},3144:{color:[63,180,180],opacity:1,label:"wm-lh-S_calcarine"},3145:{color:[221,20,10],opacity:1,label:"wm-lh-S_central"},3146:{color:[21,220,20],opacity:1,label:"wm-lh-S_central_insula"},3147:{color:[183,100,20],opacity:1,label:"wm-lh-S_cingulate-Main_part_and_Intracingulate"},3148:{color:[221,20,100],opacity:1,label:"wm-lh-S_cingulate-Marginalis_part"},3149:{color:[221,60,140],opacity:1,label:"wm-lh-S_circular_insula_anterior"},3150:{color:[221,20,220],opacity:1,label:"wm-lh-S_circular_insula_inferior"},3151:{color:[61,220,220],opacity:1,label:"wm-lh-S_circular_insula_superior"},3152:{color:[100,200,200],opacity:1,label:"wm-lh-S_collateral_transverse_ant"},3153:{color:[10,200,200],opacity:1,label:"wm-lh-S_collateral_transverse_post"},3154:{color:[221,220,20],opacity:1,label:"wm-lh-S_frontal_inferior"},3155:{color:[141,20,100],opacity:1,label:"wm-lh-S_frontal_middle"},3156:{color:[61,220,100],opacity:1,label:"wm-lh-S_frontal_superior"},3157:{color:[21,220,60],opacity:1,label:"wm-lh-S_frontomarginal"},3158:{color:[141,60,20],opacity:1,label:"wm-lh-S_intermedius_primus-Jensen"},3159:{color:[143,20,220],opacity:1,label:"wm-lh-S_intraparietal-and_Parietal_transverse"},3160:{color:[61,20,180],opacity:1,label:"wm-lh-S_occipital_anterior"},3161:{color:[101,60,220],opacity:1,label:"wm-lh-S_occipital_middle_and_Lunatus"},3162:{color:[21,20,140],opacity:1,label:"wm-lh-S_occipital_superior_and_transversalis"},3163:{color:[221,140,20],opacity:1,label:"wm-lh-S_occipito-temporal_lateral"},3164:{color:[141,100,220],opacity:1,label:"wm-lh-S_occipito-temporal_medial_and_S_Lingual"},3165:{color:[101,20,20],opacity:1,label:"wm-lh-S_orbital-H_shapped"},3166:{color:[221,100,20],opacity:1,label:"wm-lh-S_orbital_lateral"},3167:{color:[181,200,20],opacity:1,label:"wm-lh-S_orbital_medial-Or_olfactory"},3168:{color:[21,180,140],opacity:1,label:"wm-lh-S_paracentral"},3169:{color:[101,100,180],opacity:1,label:"wm-lh-S_parieto_occipital"},3170:{color:[181,220,20],opacity:1,label:"wm-lh-S_pericallosal"},3171:{color:[21,140,200],opacity:1,label:"wm-lh-S_postcentral"},3172:{color:[21,20,240],opacity:1,label:"wm-lh-S_precentral-Inferior-part"},3173:{color:[21,20,200],opacity:1,label:"wm-lh-S_precentral-Superior-part"},3174:{color:[61,180,60],opacity:1,label:"wm-lh-S_subcentral_ant"},3175:{color:[61,180,250],opacity:1,label:"wm-lh-S_subcentral_post"},3176:{color:[21,20,60],opacity:1,label:"wm-lh-S_suborbital"},3177:{color:[101,60,60],opacity:1,label:"wm-lh-S_subparietal"},3178:{color:[21,220,220],opacity:1,label:"wm-lh-S_supracingulate"},3179:{color:[21,180,180],opacity:1,label:"wm-lh-S_temporal_inferior"},3180:{color:[223,220,60],opacity:1,label:"wm-lh-S_temporal_superior"},3181:{color:[221,60,60],opacity:1,label:"wm-lh-S_temporal_transverse"},4100:{color:[0,0,0],opacity:1,label:"wm-rh-Unknown"},4101:{color:[50,50,50],opacity:1,label:"wm-rh-Corpus_callosum"},4102:{color:[180,20,30],opacity:1,label:"wm-rh-G_and_S_Insula_ONLY_AVERAGE"},4103:{color:[60,25,25],opacity:1,label:"wm-rh-G_cingulate-Isthmus"},4104:{color:[25,60,60],opacity:1,label:"wm-rh-G_cingulate-Main_part"},4105:{color:[180,20,20],opacity:1,label:"wm-rh-G_cuneus"},4106:{color:[220,20,100],opacity:1,label:"wm-rh-G_frontal_inf-Opercular_part"},4107:{color:[140,60,60],opacity:1,label:"wm-rh-G_frontal_inf-Orbital_part"},4108:{color:[180,220,140],opacity:1,label:"wm-rh-G_frontal_inf-Triangular_part"},4109:{color:[140,100,180],opacity:1,label:"wm-rh-G_frontal_middle"},4110:{color:[180,20,140],opacity:1,label:"wm-rh-G_frontal_superior"},4111:{color:[140,20,140],opacity:1,label:"wm-rh-G_frontomarginal"},4112:{color:[21,10,10],opacity:1,label:"wm-rh-G_insular_long"},4113:{color:[225,140,140],opacity:1,label:"wm-rh-G_insular_short"},4114:{color:[23,60,180],opacity:1,label:"wm-rh-G_and_S_occipital_inferior"},4115:{color:[180,60,180],opacity:1,label:"wm-rh-G_occipital_middle"},4116:{color:[20,220,60],opacity:1,label:"wm-rh-G_occipital_superior"},4117:{color:[60,20,140],opacity:1,label:"wm-rh-G_occipit-temp_lat-Or_fusiform"},4118:{color:[220,180,140],opacity:1,label:"wm-rh-G_occipit-temp_med-Lingual_part"},4119:{color:[65,100,20],opacity:1,label:"wm-rh-G_occipit-temp_med-Parahippocampal_part"},4120:{color:[220,60,20],opacity:1,label:"wm-rh-G_orbital"},4121:{color:[60,100,60],opacity:1,label:"wm-rh-G_paracentral"},4122:{color:[20,60,220],opacity:1,label:"wm-rh-G_parietal_inferior-Angular_part"},4123:{color:[100,100,60],opacity:1, label:"wm-rh-G_parietal_inferior-Supramarginal_part"},4124:{color:[220,180,220],opacity:1,label:"wm-rh-G_parietal_superior"},4125:{color:[20,180,140],opacity:1,label:"wm-rh-G_postcentral"},4126:{color:[60,140,180],opacity:1,label:"wm-rh-G_precentral"},4127:{color:[25,20,140],opacity:1,label:"wm-rh-G_precuneus"},4128:{color:[20,60,100],opacity:1,label:"wm-rh-G_rectus"},4129:{color:[60,220,20],opacity:1,label:"wm-rh-G_subcallosal"},4130:{color:[60,20,220],opacity:1,label:"wm-rh-G_subcentral"},4131:{color:[220,220,100],opacity:1,label:"wm-rh-G_temporal_inferior"},4132:{color:[180,60,60],opacity:1,label:"wm-rh-G_temporal_middle"},4133:{color:[60,60,220],opacity:1,label:"wm-rh-G_temp_sup-G_temp_transv_and_interm_S"},4134:{color:[220,60,220],opacity:1,label:"wm-rh-G_temp_sup-Lateral_aspect"},4135:{color:[65,220,60],opacity:1,label:"wm-rh-G_temp_sup-Planum_polare"},4136:{color:[25,140,20],opacity:1,label:"wm-rh-G_temp_sup-Planum_tempolare"},4137:{color:[13,0,250],opacity:1,label:"wm-rh-G_and_S_transverse_frontopolar"},4138:{color:[61,20,220],opacity:1,label:"wm-rh-Lat_Fissure-ant_sgt-ramus_horizontal"},4139:{color:[61,20,60],opacity:1,label:"wm-rh-Lat_Fissure-ant_sgt-ramus_vertical"},4140:{color:[61,60,100],opacity:1,label:"wm-rh-Lat_Fissure-post_sgt"},4141:{color:[25,25,25],opacity:1,label:"wm-rh-Medial_wall"},4142:{color:[140,20,60],opacity:1,label:"wm-rh-Pole_occipital"},4143:{color:[220,180,20],opacity:1,label:"wm-rh-Pole_temporal"},4144:{color:[63,180,180],opacity:1,label:"wm-rh-S_calcarine"},4145:{color:[221,20,10],opacity:1,label:"wm-rh-S_central"},4146:{color:[21,220,20],opacity:1,label:"wm-rh-S_central_insula"},4147:{color:[183,100,20],opacity:1,label:"wm-rh-S_cingulate-Main_part_and_Intracingulate"},4148:{color:[221,20,100],opacity:1,label:"wm-rh-S_cingulate-Marginalis_part"},4149:{color:[221,60,140],opacity:1,label:"wm-rh-S_circular_insula_anterior"},4150:{color:[221,20,220],opacity:1,label:"wm-rh-S_circular_insula_inferior"},4151:{color:[61,220,220],opacity:1,label:"wm-rh-S_circular_insula_superior"},4152:{color:[100,200,200],opacity:1,label:"wm-rh-S_collateral_transverse_ant"},4153:{color:[10,200,200],opacity:1,label:"wm-rh-S_collateral_transverse_post"},4154:{color:[221,220,20],opacity:1,label:"wm-rh-S_frontal_inferior"},4155:{color:[141,20,100],opacity:1,label:"wm-rh-S_frontal_middle"},4156:{color:[61,220,100],opacity:1,label:"wm-rh-S_frontal_superior"},4157:{color:[21,220,60],opacity:1,label:"wm-rh-S_frontomarginal"},4158:{color:[141,60,20],opacity:1,label:"wm-rh-S_intermedius_primus-Jensen"},4159:{color:[143,20,220],opacity:1,label:"wm-rh-S_intraparietal-and_Parietal_transverse"},4160:{color:[61,20,180],opacity:1,label:"wm-rh-S_occipital_anterior"},4161:{color:[101,60,220],opacity:1,label:"wm-rh-S_occipital_middle_and_Lunatus"},4162:{color:[21,20,140],opacity:1,label:"wm-rh-S_occipital_superior_and_transversalis"},4163:{color:[221,140,20],opacity:1,label:"wm-rh-S_occipito-temporal_lateral"},4164:{color:[141,100,220],opacity:1,label:"wm-rh-S_occipito-temporal_medial_and_S_Lingual"},4165:{color:[101,20,20],opacity:1,label:"wm-rh-S_orbital-H_shapped"},4166:{color:[221,100,20],opacity:1,label:"wm-rh-S_orbital_lateral"},4167:{color:[181,200,20],opacity:1,label:"wm-rh-S_orbital_medial-Or_olfactory"},4168:{color:[21,180,140],opacity:1,label:"wm-rh-S_paracentral"},4169:{color:[101,100,180],opacity:1,label:"wm-rh-S_parieto_occipital"},4170:{color:[181,220,20],opacity:1,label:"wm-rh-S_pericallosal"},4171:{color:[21,140,200],opacity:1,label:"wm-rh-S_postcentral"},4172:{color:[21,20,240],opacity:1,label:"wm-rh-S_precentral-Inferior-part"},4173:{color:[21,20,200],opacity:1,label:"wm-rh-S_precentral-Superior-part"},4174:{color:[61,180,60],opacity:1,label:"wm-rh-S_subcentral_ant"},4175:{color:[61,180,250],opacity:1,label:"wm-rh-S_subcentral_post"},4176:{color:[21,20,60],opacity:1,label:"wm-rh-S_suborbital"},4177:{color:[101,60,60],opacity:1,label:"wm-rh-S_subparietal"},4178:{color:[21,220,220],opacity:1,label:"wm-rh-S_supracingulate"},4179:{color:[21,180,180],opacity:1,label:"wm-rh-S_temporal_inferior"},4180:{color:[223,220,60],opacity:1,label:"wm-rh-S_temporal_superior"},4181:{color:[221,60,60],opacity:1,label:"wm-rh-S_temporal_transverse"},5001:{color:[20,30,40],opacity:1,label:"Left-UnsegmentedWhiteMatter"},5002:{color:[20,30,40],opacity:1,label:"Right-UnsegmentedWhiteMatter"},5100:{color:[204,102,102],opacity:1,label:"fmajor"},5101:{color:[204,102,102],opacity:1,label:"fminor"},5102:{color:[255,255,102],opacity:1,label:"lh.atr"},5103:{color:[153,204,0],opacity:1,label:"lh.cab"},5104:{color:[0,153,153],opacity:1,label:"lh.ccg"},5105:{color:[204,153,255],opacity:1,label:"lh.cst"},5106:{color:[255,153,51],opacity:1,label:"lh.ilf"},5107:{color:[204,204,204],opacity:1,label:"lh.slfp"},5108:{color:[153,255,255],opacity:1,label:"lh.slft"},5109:{color:[102,153,255],opacity:1,label:"lh.unc"},5110:{color:[255,255,102],opacity:1,label:"rh.atr"},5111:{color:[153,204,0],opacity:1,label:"rh.cab"},5112:{color:[0,153,153],opacity:1,label:"rh.ccg"},5113:{color:[204,153,255],opacity:1,label:"rh.cst"},5114:{color:[255,153,51],opacity:1,label:"rh.ilf"},5115:{color:[204,204,204],opacity:1,label:"rh.slfp"},5116:{color:[153,255,255],opacity:1,label:"rh.slft"},5117:{color:[102,153,255],opacity:1,label:"rh.unc"},5200:{color:[204,102,102],opacity:1,label:"CC-ForcepsMajor"},5201:{color:[204,102,102],opacity:1,label:"CC-ForcepsMinor"},5202:{color:[255,255,102],opacity:1,label:"LAntThalRadiation"},5203:{color:[153,204,0],opacity:1,label:"LCingulumAngBundle"},5204:{color:[0,153,153],opacity:1,label:"LCingulumCingGyrus"},5205:{color:[204,153,255],opacity:1,label:"LCorticospinalTract"},5206:{color:[255,153,51],opacity:1,label:"LInfLongFas"},5207:{color:[204,204,204],opacity:1,label:"LSupLongFasParietal"},5208:{color:[153,255,255],opacity:1,label:"LSupLongFasTemporal"},5209:{color:[102,153,255],opacity:1,label:"LUncinateFas"},5210:{color:[255,255,102],opacity:1,label:"RAntThalRadiation"},5211:{color:[153,204,0],opacity:1,label:"RCingulumAngBundle"},5212:{color:[0,153,153],opacity:1,label:"RCingulumCingGyrus"},5213:{color:[204,153,255],opacity:1,label:"RCorticospinalTract"},5214:{color:[255,153,51],opacity:1,label:"RInfLongFas"},5215:{color:[204,204,204],opacity:1,label:"RSupLongFasParietal"},5216:{color:[153,255,255],opacity:1,label:"RSupLongFasTemporal"},5217:{color:[102,153,255],opacity:1,label:"RUncinateFas"},6e3:{color:[0,255,0],opacity:1,label:"CST-orig"},6001:{color:[255,255,0],opacity:1,label:"CST-hammer"},6002:{color:[0,255,255],opacity:1,label:"CST-CVS"},6003:{color:[0,0,255],opacity:1,label:"CST-flirt"},6010:{color:[236,16,231],opacity:1,label:"Left-SLF1"},6020:{color:[237,18,232],opacity:1,label:"Right-SLF1"},6030:{color:[236,13,227],opacity:1,label:"Left-SLF3"},6040:{color:[236,17,228],opacity:1,label:"Right-SLF3"},6050:{color:[1,255,1],opacity:1,label:"Left-CST"},6060:{color:[2,255,1],opacity:1,label:"Right-CST"},6070:{color:[236,14,230],opacity:1,label:"Left-SLF2"},6080:{color:[237,14,230],opacity:1,label:"Right-SLF2"},7001:{color:[72,132,181],opacity:1,label:"Lateral-nucleus"},7002:{color:[243,243,243],opacity:1,label:"Basolateral-nucleus"},7003:{color:[207,63,79],opacity:1,label:"Basal-nucleus"},7004:{color:[121,20,135],opacity:1,label:"Centromedial-nucleus"},7005:{color:[197,60,248],opacity:1,label:"Central-nucleus"},7006:{color:[2,149,2],opacity:1,label:"Medial-nucleus"},7007:{color:[221,249,166],opacity:1,label:"Cortical-nucleus"},7008:{color:[232,146,35],opacity:1,label:"Accessory-Basal-nucleus"},7009:{color:[20,60,120],opacity:1,label:"Corticoamygdaloid-transitio"},7010:{color:[250,250,0],opacity:1,label:"Anterior-amygdaloid-area-AAA"},7011:{color:[122,187,222],opacity:1,label:"Fusion-amygdala-HP-FAH"},7012:{color:[237,12,177],opacity:1,label:"Hippocampal-amygdala-transition-HATA"},7013:{color:[10,49,255],opacity:1,label:"Endopiriform-nucleus"},7014:{color:[205,184,144],opacity:1,label:"Lateral-nucleus-olfactory-tract"},7015:{color:[45,205,165],opacity:1,label:"Paralaminar-nucleus"},7016:{color:[117,160,175],opacity:1,label:"Intercalated-nucleus"},7017:{color:[221,217,21],opacity:1,label:"Prepiriform-cortex"},7018:{color:[20,60,120],opacity:1,label:"Periamygdaloid-cortex"},7019:{color:[141,21,100],opacity:1,label:"Envelope-Amygdala"},7020:{color:[225,140,141],opacity:1,label:"Extranuclear-Amydala"},7100:{color:[42,201,168],opacity:1,label:"Brainstem-inferior-colliculus"},7101:{color:[168,104,162],opacity:1,label:"Brainstem-cochlear-nucleus"},8001:{color:[74,130,181],opacity:1,label:"Thalamus-Anterior"},8002:{color:[242,241,240],opacity:1,label:"Thalamus-Ventral-anterior"},8003:{color:[206,65,78],opacity:1,label:"Thalamus-Lateral-dorsal"},8004:{color:[120,21,133],opacity:1,label:"Thalamus-Lateral-posterior"},8005:{color:[195,61,246],opacity:1,label:"Thalamus-Ventral-lateral"},8006:{color:[3,147,6],opacity:1,label:"Thalamus-Ventral-posterior-medial"},8007:{color:[220,251,163],opacity:1,label:"Thalamus-Ventral-posterior-lateral"},8008:{color:[232,146,33],opacity:1,label:"Thalamus-intralaminar"},8009:{color:[4,114,14],opacity:1,label:"Thalamus-centromedian"},8010:{color:[121,184,220],opacity:1,label:"Thalamus-mediodorsal"},8011:{color:[235,11,175],opacity:1,label:"Thalamus-medial"},8012:{color:[12,46,250],opacity:1,label:"Thalamus-pulvinar"},8013:{color:[203,182,143],opacity:1,label:"Thalamus-lateral-geniculate"},8014:{color:[42,204,167],opacity:1,label:"Thalamus-medial-geniculate"},9e3:{color:[50,100,30],opacity:1,label:"ctx-lh-prefrontal"},9001:{color:[30,100,45],opacity:1,label:"ctx-lh-primary-motor"},9002:{color:[130,100,165],opacity:1,label:"ctx-lh-premotor"},9003:{color:[105,25,5],opacity:1,label:"ctx-lh-temporal"},9004:{color:[125,70,55],opacity:1,label:"ctx-lh-posterior-parietal"},9005:{color:[225,20,105],opacity:1,label:"ctx-lh-prim-sec-somatosensory"},9006:{color:[225,20,15],opacity:1,label:"ctx-lh-occipital"},9500:{color:[50,200,30],opacity:1,label:"ctx-rh-prefrontal"},9501:{color:[30,150,45],opacity:1,label:"ctx-rh-primary-motor"},9502:{color:[130,150,165],opacity:1,label:"ctx-rh-premotor"},9503:{color:[105,75,5],opacity:1,label:"ctx-rh-temporal"},9504:{color:[125,120,55],opacity:1,label:"ctx-rh-posterior-parietal"},9505:{color:[225,70,105],opacity:1,label:"ctx-rh-prim-sec-somatosensory"},9506:{color:[225,70,15],opacity:1,label:"ctx-rh-occipital"},11100:{color:[0,0,0],opacity:1,label:"ctx_lh_Unknown"},11101:{color:[23,220,60],opacity:1,label:"ctx_lh_G_and_S_frontomargin"},11102:{color:[23,60,180],opacity:1,label:"ctx_lh_G_and_S_occipital_inf"},11103:{color:[63,100,60],opacity:1,label:"ctx_lh_G_and_S_paracentral"},11104:{color:[63,20,220],opacity:1,label:"ctx_lh_G_and_S_subcentral"},11105:{color:[13,0,250],opacity:1,label:"ctx_lh_G_and_S_transv_frontopol"},11106:{color:[26,60,0],opacity:1,label:"ctx_lh_G_and_S_cingul-Ant"},11107:{color:[26,60,75],opacity:1,label:"ctx_lh_G_and_S_cingul-Mid-Ant"},11108:{color:[26,60,150],opacity:1,label:"ctx_lh_G_and_S_cingul-Mid-Post"},11109:{color:[25,60,250],opacity:1,label:"ctx_lh_G_cingul-Post-dorsal"},11110:{color:[60,25,25],opacity:1,label:"ctx_lh_G_cingul-Post-ventral"},11111:{color:[180,20,20],opacity:1,label:"ctx_lh_G_cuneus"},11112:{color:[220,20,100],opacity:1,label:"ctx_lh_G_front_inf-Opercular"},11113:{color:[140,60,60],opacity:1,label:"ctx_lh_G_front_inf-Orbital"},11114:{color:[180,220,140],opacity:1,label:"ctx_lh_G_front_inf-Triangul"},11115:{color:[140,100,180],opacity:1,label:"ctx_lh_G_front_middle"},11116:{color:[180,20,140],opacity:1,label:"ctx_lh_G_front_sup"},11117:{color:[23,10,10],opacity:1,label:"ctx_lh_G_Ins_lg_and_S_cent_ins"},11118:{color:[225,140,140],opacity:1,label:"ctx_lh_G_insular_short"},11119:{color:[180,60,180],opacity:1,label:"ctx_lh_G_occipital_middle"},11120:{color:[20,220,60],opacity:1,label:"ctx_lh_G_occipital_sup"},11121:{color:[60,20,140],opacity:1,label:"ctx_lh_G_oc-temp_lat-fusifor"},11122:{color:[220,180,140],opacity:1,label:"ctx_lh_G_oc-temp_med-Lingual"},11123:{color:[65,100,20],opacity:1,label:"ctx_lh_G_oc-temp_med-Parahip"},11124:{color:[220,60,20],opacity:1,label:"ctx_lh_G_orbital"},11125:{color:[20,60,220],opacity:1,label:"ctx_lh_G_pariet_inf-Angular"},11126:{color:[100,100,60],opacity:1,label:"ctx_lh_G_pariet_inf-Supramar"},11127:{color:[220,180,220],opacity:1,label:"ctx_lh_G_parietal_sup"},11128:{color:[20,180,140],opacity:1,label:"ctx_lh_G_postcentral"},11129:{color:[60,140,180],opacity:1,label:"ctx_lh_G_precentral"},11130:{color:[25,20,140],opacity:1,label:"ctx_lh_G_precuneus"},11131:{color:[20,60,100],opacity:1,label:"ctx_lh_G_rectus"},11132:{color:[60,220,20],opacity:1,label:"ctx_lh_G_subcallosal"},11133:{color:[60,60,220],opacity:1,label:"ctx_lh_G_temp_sup-G_T_transv"},11134:{color:[220,60,220],opacity:1,label:"ctx_lh_G_temp_sup-Lateral"},11135:{color:[65,220,60],opacity:1,label:"ctx_lh_G_temp_sup-Plan_polar"},11136:{color:[25,140,20],opacity:1,label:"ctx_lh_G_temp_sup-Plan_tempo"},11137:{color:[220,220,100],opacity:1,label:"ctx_lh_G_temporal_inf"},11138:{color:[180,60,60],opacity:1,label:"ctx_lh_G_temporal_middle"},11139:{color:[61,20,220],opacity:1,label:"ctx_lh_Lat_Fis-ant-Horizont"},11140:{color:[61,20,60],opacity:1,label:"ctx_lh_Lat_Fis-ant-Vertical"},11141:{color:[61,60,100],opacity:1,label:"ctx_lh_Lat_Fis-post"},11142:{color:[25,25,25],opacity:1,label:"ctx_lh_Medial_wall"},11143:{color:[140,20,60],opacity:1,label:"ctx_lh_Pole_occipital"},11144:{color:[220,180,20],opacity:1,label:"ctx_lh_Pole_temporal"},11145:{color:[63,180,180],opacity:1,label:"ctx_lh_S_calcarine"},11146:{color:[221,20,10],opacity:1,label:"ctx_lh_S_central"},11147:{color:[221,20,100],opacity:1,label:"ctx_lh_S_cingul-Marginalis"},11148:{color:[221,60,140],opacity:1,label:"ctx_lh_S_circular_insula_ant"},11149:{color:[221,20,220],opacity:1,label:"ctx_lh_S_circular_insula_inf"},11150:{color:[61,220,220],opacity:1,label:"ctx_lh_S_circular_insula_sup"},11151:{color:[100,200,200],opacity:1,label:"ctx_lh_S_collat_transv_ant"},11152:{color:[10,200,200],opacity:1,label:"ctx_lh_S_collat_transv_post"},11153:{color:[221,220,20],opacity:1,label:"ctx_lh_S_front_inf"},11154:{color:[141,20,100],opacity:1,label:"ctx_lh_S_front_middle"},11155:{color:[61,220,100],opacity:1,label:"ctx_lh_S_front_sup"},11156:{color:[141,60,20],opacity:1,label:"ctx_lh_S_interm_prim-Jensen"},11157:{color:[143,20,220],opacity:1,label:"ctx_lh_S_intrapariet_and_P_trans"},11158:{color:[101,60,220],opacity:1,label:"ctx_lh_S_oc_middle_and_Lunatus"},11159:{color:[21,20,140],opacity:1,label:"ctx_lh_S_oc_sup_and_transversal"},11160:{color:[61,20,180],opacity:1,label:"ctx_lh_S_occipital_ant"},11161:{color:[221,140,20],opacity:1,label:"ctx_lh_S_oc-temp_lat"},11162:{color:[141,100,220],opacity:1,label:"ctx_lh_S_oc-temp_med_and_Lingual"},11163:{color:[221,100,20],opacity:1,label:"ctx_lh_S_orbital_lateral"},11164:{color:[181,200,20],opacity:1,label:"ctx_lh_S_orbital_med-olfact"},11165:{color:[101,20,20],opacity:1,label:"ctx_lh_S_orbital-H_Shaped"},11166:{color:[101,100,180],opacity:1,label:"ctx_lh_S_parieto_occipital"},11167:{color:[181,220,20],opacity:1,label:"ctx_lh_S_pericallosal"},11168:{color:[21,140,200],opacity:1,label:"ctx_lh_S_postcentral"},11169:{color:[21,20,240],opacity:1,label:"ctx_lh_S_precentral-inf-part"},11170:{color:[21,20,200],opacity:1,label:"ctx_lh_S_precentral-sup-part"},11171:{color:[21,20,60],opacity:1,label:"ctx_lh_S_suborbital"},11172:{color:[101,60,60],opacity:1,label:"ctx_lh_S_subparietal"},11173:{color:[21,180,180],opacity:1,label:"ctx_lh_S_temporal_inf"},11174:{color:[223,220,60],opacity:1,label:"ctx_lh_S_temporal_sup"},11175:{color:[221,60,60],opacity:1,label:"ctx_lh_S_temporal_transverse"},12100:{color:[0,0,0],opacity:1,label:"ctx_rh_Unknown"},12101:{color:[23,220,60],opacity:1,label:"ctx_rh_G_and_S_frontomargin"},12102:{color:[23,60,180],opacity:1,label:"ctx_rh_G_and_S_occipital_inf"},12103:{color:[63,100,60],opacity:1,label:"ctx_rh_G_and_S_paracentral"},12104:{color:[63,20,220],opacity:1,label:"ctx_rh_G_and_S_subcentral"},12105:{color:[13,0,250],opacity:1,label:"ctx_rh_G_and_S_transv_frontopol"},12106:{color:[26,60,0],opacity:1,label:"ctx_rh_G_and_S_cingul-Ant"},12107:{color:[26,60,75],opacity:1,label:"ctx_rh_G_and_S_cingul-Mid-Ant"},12108:{color:[26,60,150],opacity:1,label:"ctx_rh_G_and_S_cingul-Mid-Post"},12109:{color:[25,60,250],opacity:1,label:"ctx_rh_G_cingul-Post-dorsal"},12110:{color:[60,25,25],opacity:1,label:"ctx_rh_G_cingul-Post-ventral"},12111:{color:[180,20,20],opacity:1,label:"ctx_rh_G_cuneus"},12112:{color:[220,20,100],opacity:1,label:"ctx_rh_G_front_inf-Opercular"},12113:{color:[140,60,60],opacity:1,label:"ctx_rh_G_front_inf-Orbital"},12114:{color:[180,220,140],opacity:1,label:"ctx_rh_G_front_inf-Triangul"},12115:{color:[140,100,180],opacity:1,label:"ctx_rh_G_front_middle"},12116:{color:[180,20,140],opacity:1,label:"ctx_rh_G_front_sup"},12117:{color:[23,10,10],opacity:1,label:"ctx_rh_G_Ins_lg_and_S_cent_ins"},12118:{color:[225,140,140],opacity:1,label:"ctx_rh_G_insular_short"},12119:{color:[180,60,180],opacity:1,label:"ctx_rh_G_occipital_middle"},12120:{color:[20,220,60],opacity:1,label:"ctx_rh_G_occipital_sup"},12121:{color:[60,20,140],opacity:1,label:"ctx_rh_G_oc-temp_lat-fusifor"},12122:{color:[220,180,140],opacity:1,label:"ctx_rh_G_oc-temp_med-Lingual"},12123:{color:[65,100,20],opacity:1,label:"ctx_rh_G_oc-temp_med-Parahip"},12124:{color:[220,60,20],opacity:1,label:"ctx_rh_G_orbital"},12125:{color:[20,60,220],opacity:1,label:"ctx_rh_G_pariet_inf-Angular"},12126:{color:[100,100,60],opacity:1,label:"ctx_rh_G_pariet_inf-Supramar"},12127:{color:[220,180,220],opacity:1,label:"ctx_rh_G_parietal_sup"},12128:{color:[20,180,140],opacity:1,label:"ctx_rh_G_postcentral"},12129:{color:[60,140,180],opacity:1,label:"ctx_rh_G_precentral"},12130:{color:[25,20,140],opacity:1,label:"ctx_rh_G_precuneus"},12131:{color:[20,60,100],opacity:1,label:"ctx_rh_G_rectus"},12132:{color:[60,220,20],opacity:1,label:"ctx_rh_G_subcallosal"},12133:{color:[60,60,220],opacity:1,label:"ctx_rh_G_temp_sup-G_T_transv"},12134:{color:[220,60,220],opacity:1,label:"ctx_rh_G_temp_sup-Lateral"},12135:{color:[65,220,60],opacity:1,label:"ctx_rh_G_temp_sup-Plan_polar"},12136:{color:[25,140,20],opacity:1,label:"ctx_rh_G_temp_sup-Plan_tempo"},12137:{color:[220,220,100],opacity:1,label:"ctx_rh_G_temporal_inf"},12138:{color:[180,60,60],opacity:1,label:"ctx_rh_G_temporal_middle"},12139:{color:[61,20,220],opacity:1,label:"ctx_rh_Lat_Fis-ant-Horizont"},12140:{color:[61,20,60],opacity:1,label:"ctx_rh_Lat_Fis-ant-Vertical"},12141:{color:[61,60,100],opacity:1,label:"ctx_rh_Lat_Fis-post"},12142:{color:[25,25,25],opacity:1,label:"ctx_rh_Medial_wall"},12143:{color:[140,20,60],opacity:1,label:"ctx_rh_Pole_occipital"},12144:{color:[220,180,20],opacity:1,label:"ctx_rh_Pole_temporal"},12145:{color:[63,180,180],opacity:1,label:"ctx_rh_S_calcarine"},12146:{color:[221,20,10],opacity:1,label:"ctx_rh_S_central"},12147:{color:[221,20,100],opacity:1,label:"ctx_rh_S_cingul-Marginalis"},12148:{color:[221,60,140],opacity:1,label:"ctx_rh_S_circular_insula_ant"},12149:{color:[221,20,220],opacity:1,label:"ctx_rh_S_circular_insula_inf"},12150:{color:[61,220,220],opacity:1,label:"ctx_rh_S_circular_insula_sup"},12151:{color:[100,200,200],opacity:1,label:"ctx_rh_S_collat_transv_ant"},12152:{color:[10,200,200],opacity:1,label:"ctx_rh_S_collat_transv_post"},12153:{color:[221,220,20],opacity:1,label:"ctx_rh_S_front_inf"},12154:{color:[141,20,100],opacity:1,label:"ctx_rh_S_front_middle"},12155:{color:[61,220,100],opacity:1,label:"ctx_rh_S_front_sup"},12156:{color:[141,60,20],opacity:1,label:"ctx_rh_S_interm_prim-Jensen"},12157:{color:[143,20,220],opacity:1,label:"ctx_rh_S_intrapariet_and_P_trans"},12158:{color:[101,60,220],opacity:1,label:"ctx_rh_S_oc_middle_and_Lunatus"},12159:{color:[21,20,140],opacity:1,label:"ctx_rh_S_oc_sup_and_transversal"},12160:{color:[61,20,180],opacity:1,label:"ctx_rh_S_occipital_ant"},12161:{color:[221,140,20],opacity:1,label:"ctx_rh_S_oc-temp_lat"},12162:{color:[141,100,220],opacity:1,label:"ctx_rh_S_oc-temp_med_and_Lingual"},12163:{color:[221,100,20],opacity:1,label:"ctx_rh_S_orbital_lateral"},12164:{color:[181,200,20],opacity:1,label:"ctx_rh_S_orbital_med-olfact"},12165:{color:[101,20,20],opacity:1,label:"ctx_rh_S_orbital-H_Shaped"},12166:{color:[101,100,180],opacity:1,label:"ctx_rh_S_parieto_occipital"},12167:{color:[181,220,20],opacity:1,label:"ctx_rh_S_pericallosal"},12168:{color:[21,140,200],opacity:1,label:"ctx_rh_S_postcentral"},12169:{color:[21,20,240],opacity:1,label:"ctx_rh_S_precentral-inf-part"},12170:{color:[21,20,200],opacity:1,label:"ctx_rh_S_precentral-sup-part"},12171:{color:[21,20,60],opacity:1,label:"ctx_rh_S_suborbital"},12172:{color:[101,60,60],opacity:1,label:"ctx_rh_S_subparietal"},12173:{color:[21,180,180],opacity:1,label:"ctx_rh_S_temporal_inf"},12174:{color:[223,220,60],opacity:1,label:"ctx_rh_S_temporal_sup"},12175:{color:[221,60,60],opacity:1,label:"ctx_rh_S_temporal_transverse"},13100:{color:[0,0,0],opacity:1,label:"wm_lh_Unknown"},13101:{color:[23,220,60],opacity:1,label:"wm_lh_G_and_S_frontomargin"},13102:{color:[23,60,180],opacity:1,label:"wm_lh_G_and_S_occipital_inf"},13103:{color:[63,100,60],opacity:1,label:"wm_lh_G_and_S_paracentral"},13104:{color:[63,20,220],opacity:1,label:"wm_lh_G_and_S_subcentral"},13105:{color:[13,0,250],opacity:1,label:"wm_lh_G_and_S_transv_frontopol"},13106:{color:[26,60,0],opacity:1,label:"wm_lh_G_and_S_cingul-Ant"},13107:{color:[26,60,75],opacity:1,label:"wm_lh_G_and_S_cingul-Mid-Ant"},13108:{color:[26,60,150],opacity:1,label:"wm_lh_G_and_S_cingul-Mid-Post"},13109:{color:[25,60,250],opacity:1,label:"wm_lh_G_cingul-Post-dorsal"},13110:{color:[60,25,25],opacity:1,label:"wm_lh_G_cingul-Post-ventral"},13111:{color:[180,20,20],opacity:1,label:"wm_lh_G_cuneus"},13112:{color:[220,20,100],opacity:1,label:"wm_lh_G_front_inf-Opercular"},13113:{color:[140,60,60],opacity:1,label:"wm_lh_G_front_inf-Orbital"},13114:{color:[180,220,140],opacity:1,label:"wm_lh_G_front_inf-Triangul"},13115:{color:[140,100,180],opacity:1,label:"wm_lh_G_front_middle"},13116:{color:[180,20,140],opacity:1,label:"wm_lh_G_front_sup"},13117:{color:[23,10,10],opacity:1,label:"wm_lh_G_Ins_lg_and_S_cent_ins"},13118:{color:[225,140,140],opacity:1,label:"wm_lh_G_insular_short"},13119:{color:[180,60,180],opacity:1,label:"wm_lh_G_occipital_middle"},13120:{color:[20,220,60],opacity:1,label:"wm_lh_G_occipital_sup"},13121:{color:[60,20,140],opacity:1,label:"wm_lh_G_oc-temp_lat-fusifor"},13122:{color:[220,180,140],opacity:1,label:"wm_lh_G_oc-temp_med-Lingual"},13123:{color:[65,100,20],opacity:1,label:"wm_lh_G_oc-temp_med-Parahip"},13124:{color:[220,60,20],opacity:1,label:"wm_lh_G_orbital"},13125:{color:[20,60,220],opacity:1,label:"wm_lh_G_pariet_inf-Angular"},13126:{color:[100,100,60],opacity:1,label:"wm_lh_G_pariet_inf-Supramar"},13127:{color:[220,180,220],opacity:1,label:"wm_lh_G_parietal_sup"},13128:{color:[20,180,140],opacity:1,label:"wm_lh_G_postcentral"},13129:{color:[60,140,180],opacity:1,label:"wm_lh_G_precentral"},13130:{color:[25,20,140],opacity:1,label:"wm_lh_G_precuneus"},13131:{color:[20,60,100],opacity:1,label:"wm_lh_G_rectus"},13132:{color:[60,220,20],opacity:1,label:"wm_lh_G_subcallosal"},13133:{color:[60,60,220],opacity:1,label:"wm_lh_G_temp_sup-G_T_transv"},13134:{color:[220,60,220],opacity:1,label:"wm_lh_G_temp_sup-Lateral"},13135:{color:[65,220,60],opacity:1,label:"wm_lh_G_temp_sup-Plan_polar"},13136:{color:[25,140,20],opacity:1,label:"wm_lh_G_temp_sup-Plan_tempo"},13137:{color:[220,220,100],opacity:1,label:"wm_lh_G_temporal_inf"},13138:{color:[180,60,60],opacity:1,label:"wm_lh_G_temporal_middle"},13139:{color:[61,20,220],opacity:1,label:"wm_lh_Lat_Fis-ant-Horizont"},13140:{color:[61,20,60],opacity:1,label:"wm_lh_Lat_Fis-ant-Vertical"},13141:{color:[61,60,100],opacity:1,label:"wm_lh_Lat_Fis-post"},13142:{color:[25,25,25],opacity:1,label:"wm_lh_Medial_wall"},13143:{color:[140,20,60],opacity:1,label:"wm_lh_Pole_occipital"},13144:{color:[220,180,20],opacity:1,label:"wm_lh_Pole_temporal"},13145:{color:[63,180,180],opacity:1,label:"wm_lh_S_calcarine"},13146:{color:[221,20,10],opacity:1,label:"wm_lh_S_central"},13147:{color:[221,20,100],opacity:1,label:"wm_lh_S_cingul-Marginalis"},13148:{color:[221,60,140],opacity:1,label:"wm_lh_S_circular_insula_ant"},13149:{color:[221,20,220],opacity:1,label:"wm_lh_S_circular_insula_inf"},13150:{color:[61,220,220],opacity:1,label:"wm_lh_S_circular_insula_sup"},13151:{color:[100,200,200],opacity:1,label:"wm_lh_S_collat_transv_ant"},13152:{color:[10,200,200],opacity:1,label:"wm_lh_S_collat_transv_post"},13153:{color:[221,220,20],opacity:1,label:"wm_lh_S_front_inf"},13154:{color:[141,20,100],opacity:1,label:"wm_lh_S_front_middle"},13155:{color:[61,220,100],opacity:1,label:"wm_lh_S_front_sup"},13156:{color:[141,60,20],opacity:1,label:"wm_lh_S_interm_prim-Jensen"},13157:{color:[143,20,220],opacity:1,label:"wm_lh_S_intrapariet_and_P_trans"},13158:{color:[101,60,220],opacity:1,label:"wm_lh_S_oc_middle_and_Lunatus"},13159:{color:[21,20,140],opacity:1,label:"wm_lh_S_oc_sup_and_transversal"},13160:{color:[61,20,180],opacity:1,label:"wm_lh_S_occipital_ant"},13161:{color:[221,140,20],opacity:1,label:"wm_lh_S_oc-temp_lat"},13162:{color:[141,100,220],opacity:1,label:"wm_lh_S_oc-temp_med_and_Lingual"},13163:{color:[221,100,20],opacity:1,label:"wm_lh_S_orbital_lateral"},13164:{color:[181,200,20],opacity:1,label:"wm_lh_S_orbital_med-olfact"},13165:{color:[101,20,20],opacity:1,label:"wm_lh_S_orbital-H_Shaped"},13166:{color:[101,100,180],opacity:1,label:"wm_lh_S_parieto_occipital"},13167:{color:[181,220,20],opacity:1,label:"wm_lh_S_pericallosal"},13168:{color:[21,140,200],opacity:1,label:"wm_lh_S_postcentral"},13169:{color:[21,20,240],opacity:1,label:"wm_lh_S_precentral-inf-part"},13170:{color:[21,20,200],opacity:1,label:"wm_lh_S_precentral-sup-part"},13171:{color:[21,20,60],opacity:1,label:"wm_lh_S_suborbital"},13172:{color:[101,60,60],opacity:1,label:"wm_lh_S_subparietal"},13173:{color:[21,180,180],opacity:1,label:"wm_lh_S_temporal_inf"},13174:{color:[223,220,60],opacity:1,label:"wm_lh_S_temporal_sup"},13175:{color:[221,60,60],opacity:1,label:"wm_lh_S_temporal_transverse"},14100:{color:[0,0,0],opacity:1,label:"wm_rh_Unknown"},14101:{color:[23,220,60],opacity:1,label:"wm_rh_G_and_S_frontomargin"},14102:{color:[23,60,180],opacity:1,label:"wm_rh_G_and_S_occipital_inf"},14103:{color:[63,100,60],opacity:1,label:"wm_rh_G_and_S_paracentral"},14104:{color:[63,20,220],opacity:1,label:"wm_rh_G_and_S_subcentral"},14105:{color:[13,0,250],opacity:1,label:"wm_rh_G_and_S_transv_frontopol"},14106:{color:[26,60,0],opacity:1,label:"wm_rh_G_and_S_cingul-Ant"},14107:{color:[26,60,75],opacity:1,label:"wm_rh_G_and_S_cingul-Mid-Ant"},14108:{color:[26,60,150],opacity:1,label:"wm_rh_G_and_S_cingul-Mid-Post"},14109:{color:[25,60,250],opacity:1,label:"wm_rh_G_cingul-Post-dorsal"},14110:{color:[60,25,25],opacity:1,label:"wm_rh_G_cingul-Post-ventral"},14111:{color:[180,20,20],opacity:1,label:"wm_rh_G_cuneus"},14112:{color:[220,20,100],opacity:1,label:"wm_rh_G_front_inf-Opercular"},14113:{color:[140,60,60],opacity:1,label:"wm_rh_G_front_inf-Orbital"},14114:{color:[180,220,140],opacity:1,label:"wm_rh_G_front_inf-Triangul"},14115:{color:[140,100,180],opacity:1,label:"wm_rh_G_front_middle"},14116:{color:[180,20,140],opacity:1,label:"wm_rh_G_front_sup"},14117:{color:[23,10,10],opacity:1,label:"wm_rh_G_Ins_lg_and_S_cent_ins"},14118:{color:[225,140,140],opacity:1,label:"wm_rh_G_insular_short"},14119:{color:[180,60,180],opacity:1,label:"wm_rh_G_occipital_middle"},14120:{color:[20,220,60],opacity:1,label:"wm_rh_G_occipital_sup"},14121:{color:[60,20,140],opacity:1,label:"wm_rh_G_oc-temp_lat-fusifor"},14122:{color:[220,180,140],opacity:1,label:"wm_rh_G_oc-temp_med-Lingual"},14123:{color:[65,100,20],opacity:1,label:"wm_rh_G_oc-temp_med-Parahip"},14124:{color:[220,60,20],opacity:1,label:"wm_rh_G_orbital"},14125:{color:[20,60,220],opacity:1,label:"wm_rh_G_pariet_inf-Angular"},14126:{color:[100,100,60],opacity:1,label:"wm_rh_G_pariet_inf-Supramar"},14127:{color:[220,180,220],opacity:1,label:"wm_rh_G_parietal_sup"},14128:{color:[20,180,140],opacity:1,label:"wm_rh_G_postcentral"},14129:{color:[60,140,180],opacity:1,label:"wm_rh_G_precentral"},14130:{color:[25,20,140],opacity:1,label:"wm_rh_G_precuneus"},14131:{color:[20,60,100],opacity:1,label:"wm_rh_G_rectus"},14132:{color:[60,220,20],opacity:1,label:"wm_rh_G_subcallosal"},14133:{color:[60,60,220],opacity:1,label:"wm_rh_G_temp_sup-G_T_transv"},14134:{color:[220,60,220],opacity:1,label:"wm_rh_G_temp_sup-Lateral"},14135:{color:[65,220,60],opacity:1,label:"wm_rh_G_temp_sup-Plan_polar"},14136:{color:[25,140,20],opacity:1,label:"wm_rh_G_temp_sup-Plan_tempo"},14137:{color:[220,220,100],opacity:1,label:"wm_rh_G_temporal_inf"},14138:{color:[180,60,60],opacity:1,label:"wm_rh_G_temporal_middle"},14139:{color:[61,20,220],opacity:1,label:"wm_rh_Lat_Fis-ant-Horizont"},14140:{color:[61,20,60],opacity:1,label:"wm_rh_Lat_Fis-ant-Vertical"},14141:{color:[61,60,100],opacity:1,label:"wm_rh_Lat_Fis-post"},14142:{color:[25,25,25],opacity:1,label:"wm_rh_Medial_wall"},14143:{color:[140,20,60],opacity:1,label:"wm_rh_Pole_occipital"},14144:{color:[220,180,20],opacity:1,label:"wm_rh_Pole_temporal"},14145:{color:[63,180,180],opacity:1,label:"wm_rh_S_calcarine"},14146:{color:[221,20,10],opacity:1,label:"wm_rh_S_central"},14147:{color:[221,20,100],opacity:1,label:"wm_rh_S_cingul-Marginalis"},14148:{color:[221,60,140],opacity:1,label:"wm_rh_S_circular_insula_ant"},14149:{color:[221,20,220],opacity:1,label:"wm_rh_S_circular_insula_inf"},14150:{color:[61,220,220],opacity:1,label:"wm_rh_S_circular_insula_sup"},14151:{color:[100,200,200],opacity:1,label:"wm_rh_S_collat_transv_ant"},14152:{color:[10,200,200],opacity:1,label:"wm_rh_S_collat_transv_post"},14153:{color:[221,220,20],opacity:1,label:"wm_rh_S_front_inf"},14154:{color:[141,20,100],opacity:1,label:"wm_rh_S_front_middle"},14155:{color:[61,220,100],opacity:1,label:"wm_rh_S_front_sup"},14156:{color:[141,60,20],opacity:1,label:"wm_rh_S_interm_prim-Jensen"},14157:{color:[143,20,220],opacity:1,label:"wm_rh_S_intrapariet_and_P_trans"},14158:{color:[101,60,220],opacity:1,label:"wm_rh_S_oc_middle_and_Lunatus"},14159:{color:[21,20,140],opacity:1,label:"wm_rh_S_oc_sup_and_transversal"},14160:{color:[61,20,180],opacity:1,label:"wm_rh_S_occipital_ant"},14161:{color:[221,140,20],opacity:1,label:"wm_rh_S_oc-temp_lat"},14162:{color:[141,100,220],opacity:1,label:"wm_rh_S_oc-temp_med_and_Lingual"},14163:{color:[221,100,20],opacity:1,label:"wm_rh_S_orbital_lateral"},14164:{color:[181,200,20],opacity:1,label:"wm_rh_S_orbital_med-olfact"},14165:{color:[101,20,20],opacity:1,label:"wm_rh_S_orbital-H_Shaped"},14166:{color:[101,100,180],opacity:1,label:"wm_rh_S_parieto_occipital"},14167:{color:[181,220,20],opacity:1,label:"wm_rh_S_pericallosal"},14168:{color:[21,140,200],opacity:1,label:"wm_rh_S_postcentral"},14169:{color:[21,20,240],opacity:1,label:"wm_rh_S_precentral-inf-part"},14170:{color:[21,20,200],opacity:1,label:"wm_rh_S_precentral-sup-part"},14171:{color:[21,20,60],opacity:1,label:"wm_rh_S_suborbital"},14172:{color:[101,60,60],opacity:1,label:"wm_rh_S_subparietal"},14173:{color:[21,180,180],opacity:1,label:"wm_rh_S_temporal_inf"},14174:{color:[223,220,60],opacity:1,label:"wm_rh_S_temporal_sup"},14175:{color:[221,60,60],opacity:1,label:"wm_rh_S_temporal_transverse"}};exports.default=segmentationFs},{}],140:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}()

var _presetsSegmentation=require("./presets.segmentation.freesurfer");var _presetsSegmentation2=_interopRequireDefault(_presetsSegmentation);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj
{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var PresetsSegmentation=function(){function PresetsSegmentation(){var presetID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"Freesurfer";_classCallCheck(this,PresetsSegmentation);this._presetID=presetID;this._presets=this.presetSegs()}_createClass(PresetsSegmentation,[{key:"fetchPreset",value:function fetchPreset(presetID){var presets=this._presets;return presets[presetID]}},{key:"addPreset",value:function addPreset(presetObj){this._presets.push(presetObj)}},{key:"presetsAvailable",value:function presetsAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"segmentation";var available=[];var presets=this._presets;for(var i in presets){available.push(i)}return available}},{key:"presetSegs",value:function presetSegs(){return{Freesurfer:_presetsSegmentation2.default}}},{key:"preset",set:function set(targetPreset){this._presetID=targetPreset},get:function get(){return this.fetchPreset(this._presetID)}}]);return PresetsSegmentation}();exports.default=PresetsSegmentation},{"./presets.segmentation.freesurfer":139}],141:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("../shaders.base");var _shaders2=_interopRequireDefault(_shaders);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var IntersectBox=function(_ShadersBase){_inherits(IntersectBox,_ShadersBase);function IntersectBox(){_classCallCheck(this,IntersectBox);var _this=_possibleConstructorReturn(this,(IntersectBox.__proto__||Object.getPrototypeOf(IntersectBox)).call(this));_this.name="intersectBox";_this._rayOrigin="rayOrigin";_this._rayDirection="rayDirection";_this._aabbMin="aabbMin";_this._aabbMax="aabbMax";_this._tNear="tNear";_this._tFar="tFar";_this._intersect="intersect";return _this}_createClass(IntersectBox,[{key:"api",value:function api(){var baseFragment=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this._base;var rayOrigin=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._rayOrigin;var rayDirection=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._rayDirection;var aabbMin=arguments.length>3&&arguments[3]!==undefined?arguments[3]:this._aabbMin;var aabbMax=arguments.length>4&&arguments[4]!==undefined?arguments[4]:this._aabbMax;var tNear=arguments.length>5&&arguments[5]!==undefined?arguments[5]:this._tNear;var tFar=arguments.length>6&&arguments[6]!==undefined?arguments[6]:this._tFar;var intersect=arguments.length>7&&arguments[7]!==undefined?arguments[7]:this._intersect;this._base=baseFragment;return this.compute(rayOrigin,rayDirection,aabbMin,aabbMax,tNear,tFar,intersect)}},{key:"compute",value:function compute(rayOrigin,rayDirection,aabbMin,aabbMax,tNear,tFar,intersect){this.computeDefinition();this._base._functions[this._name]=this._definition;return this._name+"("+rayOrigin+", "+rayDirection+", "+aabbMin+", "+aabbMax+", "+tNear+", "+tFar+", "+intersect+");"}},{key:"computeDefinition",value:function computeDefinition(){this._definition="\nvoid "+this._name+"(vec3 rayOrigin, vec3 rayDirection, vec3 boxMin, vec3 boxMax, out float tNear, out float tFar, out bool intersect){\n // compute intersection of ray with all six bbox planes\n vec3 invRay = vec3(1.) / rayDirection;\n vec3 tBot = invRay * (boxMin - rayOrigin);\n vec3 tTop = invRay * (boxMax - rayOrigin);\n // re-order intersections to find smallest and largest on each axis\n vec3 tMin = min(tTop, tBot);\n vec3 tMax = max(tTop, tBot);\n // find the largest tMin and the smallest tMax\n float largest_tMin = max(max(tMin.x, tMin.y), max(tMin.x, tMin.z));\n float smallest_tMax = min(min(tMax.x, tMax.y), min(tMax.x, tMax.z));\n tNear = largest_tMin;\n tFar = smallest_tMax;\n intersect = smallest_tMax > largest_tMin;\n}\n\n "}}]);return IntersectBox}(_shaders2.default);exports.default=new IntersectBox},{"../shaders.base":147}],142:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("../shaders.base");var _shaders2=_interopRequireDefault(_shaders);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Texture3d=function(_ShadersBase){_inherits(Texture3d,_ShadersBase);function Texture3d(){_classCallCheck(this,Texture3d);var _this=_possibleConstructorReturn(this,(Texture3d.__proto__||Object.getPrototypeOf(Texture3d)).call(this));_this.name="texture3d";_this._dataCoordinates="dataCoordinates";_this._dataValue="dataValue";_this._offset="offset";return _this}_createClass(Texture3d,[{key:"api",value:function api(){var baseFragment=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this._base;var dataCoordinates=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._dataCoordinates;var dataValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._dataValue;var offset=arguments.length>3&&arguments[3]!==undefined?arguments[3]:this._offset;this._base=baseFragment;return this.compute(dataCoordinates,dataValue,offset)}},{key:"compute",value:function compute(dataCoordinates,dataValue,offset){this.computeDefinition();this._base._functions[this._name]=this._definition;return this._name+"("+dataCoordinates+", "+dataValue+", "+offset+");"}},{key:"computeDefinition",value:function computeDefinition(){this._definition="\nvoid "+this._name+"(in ivec3 dataCoordinates, out vec4 dataValue, out int offset){\n \n int index = dataCoordinates.x\n + dataCoordinates.y * uDataDimensions.x\n + dataCoordinates.z * uDataDimensions.y * uDataDimensions.x;\n int indexP = int(index/uPackedPerPixel);\n offset = index - 2*indexP;\n\n // Map data index to right sampler2D texture\n int voxelsPerTexture = uTextureSize*uTextureSize;\n int textureIndex = int(floor(float(indexP) / float(voxelsPerTexture)));\n // modulo seems incorrect sometimes...\n // int inTextureIndex = int(mod(float(index), float(textureSize*textureSize)));\n int inTextureIndex = indexP - voxelsPerTexture*textureIndex;\n\n // Get row and column in the texture\n int colIndex = int(mod(float(inTextureIndex), float(uTextureSize)));\n int rowIndex = int(floor(float(inTextureIndex)/float(uTextureSize)));\n\n // Map row and column to uv\n vec2 uv = vec2(0,0);\n uv.x = (0.5 + float(colIndex)) / float(uTextureSize);\n uv.y = 1. - (0.5 + float(rowIndex)) / float(uTextureSize);\n\n //\n if(textureIndex == 0){ dataValue = texture2D(uTextureContainer[0], uv); }\n else if(textureIndex == 1){dataValue = texture2D(uTextureContainer[1], uv);}\n else if(textureIndex == 2){ dataValue = texture2D(uTextureContainer[2], uv); }\n else if(textureIndex == 3){ dataValue = texture2D(uTextureContainer[3], uv); }\n else if(textureIndex == 4){ dataValue = texture2D(uTextureContainer[4], uv); }\n else if(textureIndex == 5){ dataValue = texture2D(uTextureContainer[5], uv); }\n else if(textureIndex == 6){ dataValue = texture2D(uTextureContainer[6], uv); }\n\n}\n "}}]);return Texture3d}(_shaders2.default);exports.default=new Texture3d},{"../shaders.base":147}],143:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("../shaders.base");var _shaders2=_interopRequireDefault(_shaders);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Unpack=function(_ShadersBase){_inherits(Unpack,_ShadersBase);function Unpack(){_classCallCheck(this,Unpack);var _this=_possibleConstructorReturn(this,(Unpack.__proto__||Object.getPrototypeOf(Unpack)).call(this));_this.name="unpack";_this._packedData="packedData";_this._offset="offset";_this._unpackedData="unpackedData";_this._base._uniforms={uNumberOfChannels:{value:1},uBitsAllocated:{value:16},uPixelType:{value:0}};return _this}_createClass(Unpack,[{key:"api",value:function api(){var baseFragment=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this._base;var packedData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._packedData;var offset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._offset;var unpackedData=arguments.length>3&&arguments[3]!==undefined?arguments[3]:this._unpackedData;this._base=baseFragment;return this.compute(packedData,offset,unpackedData)}},{key:"compute",value:function compute(packedData,offset,unpackedData){this.computeDefinition();this._base._functions[this._name]=this._definition;return this._name+"("+packedData+", "+offset+", "+unpackedData+");"}},{key:"computeDefinition",value:function computeDefinition(){var content="";if(this._base._uniforms.uNumberOfChannels.value===1){switch(this._base._uniforms.uBitsAllocated.value){case 1:case 8:content=this.upack8();break;case 16:content=this.upack16();break;case 32:content=this.upack32();break;default:content=this.upackDefault();break}}else{content=this.upackIdentity()}this._definition="\nvoid "+this._name+"(in vec4 packedData, in int offset, out vec4 unpackedData){\n\n"+content+"\n\n} \n "}},{key:"upack8",value:function upack8(){this._base._functions["uInt8"]=this.uInt8();return"\nuInt8(\n packedData.r,\n unpackedData.x);\n "}},{key:"upack16",value:function upack16(){this._base._functions["uInt16"]=this.uInt16();return"\nuInt16(\n packedData.r * float( 1 - offset) + packedData.b * float(offset),\n packedData.g * float( 1 - offset) + packedData.a * float(offset),\n unpackedData.x);\n "}},{key:"upack32",value:function upack32(){if(this._base._uniforms.uPixelType.value===0){this._base._functions["uInt32"]=this.uInt32();return"\nuInt32(\n packedData.r,\n packedData.g,\n packedData.b,\n packedData.a,\n unpackedData.x);\n "}else{this._base._functions["uFloat32"]=this.uFloat32();return"\nuFloat32(\n packedData.r,\n packedData.g,\n packedData.b,\n packedData.a,\n unpackedData.x);\n "}}},{key:"upackIdentity",value:function upackIdentity(){return"\nunpackedData = packedData;\n "}},{key:"uInt8",value:function uInt8(){return"\nvoid uInt8(in float r, out float value){\n value = r * 255.;\n}\n "}},{key:"uInt16",value:function uInt16(){return"\nvoid uInt16(in float r, in float a, out float value){\n value = r * 255. + a * 255. * 256.;\n}\n "}},{key:"uInt32",value:function uInt32(){return"\nvoid uInt32(in float r, in float g, in float b, in float a, out float value){\n value = r * 255. + g * 255. * 256. + b * 255. * 256. * 256. + a * 255. * 256. * 256. * 256.;\n // value = r * 255. + g * 65025. + b * 16581375. + a * 4228250625.;\n}\n "}},{key:"uFloat32",value:function uFloat32(){return"\nvoid uFloat32(in float r, in float g, in float b, in float a, out float value){\n\n // create arrays containing bits for rgba values\n // value between 0 and 255\n value = r * 255.;\n int bytemeR[8];\n bytemeR[0] = int(floor(value / 128.));\n value -= float(bytemeR[0] * 128);\n bytemeR[1] = int(floor(value / 64.));\n value -= float(bytemeR[1] * 64);\n bytemeR[2] = int(floor(value / 32.));\n value -= float(bytemeR[2] * 32);\n bytemeR[3] = int(floor(value / 16.));\n value -= float(bytemeR[3] * 16);\n bytemeR[4] = int(floor(value / 8.));\n value -= float(bytemeR[4] * 8);\n bytemeR[5] = int(floor(value / 4.));\n value -= float(bytemeR[5] * 4);\n bytemeR[6] = int(floor(value / 2.));\n value -= float(bytemeR[6] * 2);\n bytemeR[7] = int(floor(value));\n\n value = g * 255.;\n int bytemeG[8];\n bytemeG[0] = int(floor(value / 128.));\n value -= float(bytemeG[0] * 128);\n bytemeG[1] = int(floor(value / 64.));\n value -= float(bytemeG[1] * 64);\n bytemeG[2] = int(floor(value / 32.));\n value -= float(bytemeG[2] * 32);\n bytemeG[3] = int(floor(value / 16.));\n value -= float(bytemeG[3] * 16);\n bytemeG[4] = int(floor(value / 8.));\n value -= float(bytemeG[4] * 8);\n bytemeG[5] = int(floor(value / 4.));\n value -= float(bytemeG[5] * 4);\n bytemeG[6] = int(floor(value / 2.));\n value -= float(bytemeG[6] * 2);\n bytemeG[7] = int(floor(value));\n\n value = b * 255.;\n int bytemeB[8];\n bytemeB[0] = int(floor(value / 128.));\n value -= float(bytemeB[0] * 128);\n bytemeB[1] = int(floor(value / 64.));\n value -= float(bytemeB[1] * 64);\n bytemeB[2] = int(floor(value / 32.));\n value -= float(bytemeB[2] * 32);\n bytemeB[3] = int(floor(value / 16.));\n value -= float(bytemeB[3] * 16);\n bytemeB[4] = int(floor(value / 8.));\n value -= float(bytemeB[4] * 8);\n bytemeB[5] = int(floor(value / 4.));\n value -= float(bytemeB[5] * 4);\n bytemeB[6] = int(floor(value / 2.));\n value -= float(bytemeB[6] * 2);\n bytemeB[7] = int(floor(value));\n\n value = a * 255.;\n int bytemeA[8];\n bytemeA[0] = int(floor(value / 128.));\n value -= float(bytemeA[0] * 128);\n bytemeA[1] = int(floor(value / 64.));\n value -= float(bytemeA[1] * 64);\n bytemeA[2] = int(floor(value / 32.));\n value -= float(bytemeA[2] * 32);\n bytemeA[3] = int(floor(value / 16.));\n value -= float(bytemeA[3] * 16);\n bytemeA[4] = int(floor(value / 8.));\n value -= float(bytemeA[4] * 8);\n bytemeA[5] = int(floor(value / 4.));\n value -= float(bytemeA[5] * 4);\n bytemeA[6] = int(floor(value / 2.));\n value -= float(bytemeA[6] * 2);\n bytemeA[7] = int(floor(value));\n\n // compute float32 value from bit arrays\n\n // sign\n int issigned = 1 - 2 * bytemeR[0];\n // issigned = int(pow(-1., float(bytemeR[0])));\n\n // exponent\n int exponent = 0;\n\n exponent += bytemeR[1] * int(pow(2., 7.));\n exponent += bytemeR[2] * int(pow(2., 6.));\n exponent += bytemeR[3] * int(pow(2., 5.));\n exponent += bytemeR[4] * int(pow(2., 4.));\n exponent += bytemeR[5] * int(pow(2., 3.));\n exponent += bytemeR[6] * int(pow(2., 2.));\n exponent += bytemeR[7] * int(pow(2., 1.));\n\n exponent += bytemeG[0];\n\n\n // fraction\n float fraction = 0.;\n\n fraction = float(bytemeG[1]) * pow(2., -1.);\n fraction += float(bytemeG[2]) * pow(2., -2.);\n fraction += float(bytemeG[3]) * pow(2., -3.);\n fraction += float(bytemeG[4]) * pow(2., -4.);\n fraction += float(bytemeG[5]) * pow(2., -5.);\n fraction += float(bytemeG[6]) * pow(2., -6.);\n fraction += float(bytemeG[7]) * pow(2., -7.);\n\n fraction += float(bytemeB[0]) * pow(2., -8.);\n fraction += float(bytemeB[1]) * pow(2., -9.);\n fraction += float(bytemeB[2]) * pow(2., -10.);\n fraction += float(bytemeB[3]) * pow(2., -11.);\n fraction += float(bytemeB[4]) * pow(2., -12.);\n fraction += float(bytemeB[5]) * pow(2., -13.);\n fraction += float(bytemeB[6]) * pow(2., -14.);\n fraction += float(bytemeB[7]) * pow(2., -15.);\n\n fraction += float(bytemeA[0]) * pow(2., -16.);\n fraction += float(bytemeA[1]) * pow(2., -17.);\n fraction += float(bytemeA[2]) * pow(2., -18.);\n fraction += float(bytemeA[3]) * pow(2., -19.);\n fraction += float(bytemeA[4]) * pow(2., -20.);\n fraction += float(bytemeA[5]) * pow(2., -21.);\n fraction += float(bytemeA[6]) * pow(2., -22.);\n fraction += float(bytemeA[7]) * pow(2., -23.);\n\n value = float(issigned) * pow( 2., float(exponent - 127)) * (1. + fraction);\n}\n "}}]);return Unpack}(_shaders2.default);exports.default=new Unpack},{"../shaders.base":147}],144:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("../shaders.base");var _shaders2=_interopRequireDefault(_shaders);var _shadersHelpers=require("../helpers/shaders.helpers.unpack");var _shadersHelpers2=_interopRequireDefault(_shadersHelpers);var _shadersHelpers3=require("../helpers/shaders.helpers.texture3d");var _shadersHelpers4=_interopRequireDefault(_shadersHelpers3);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var InterpolationIdentity=function(_ShadersBase){_inherits(InterpolationIdentity,_ShadersBase);function InterpolationIdentity(){_classCallCheck(this,InterpolationIdentity);var _this=_possibleConstructorReturn(this,(InterpolationIdentity.__proto__||Object.getPrototypeOf(InterpolationIdentity)).call(this));_this.name="interpolationIdentity";_this._currentVoxel="currentVoxel";_this._dataValue="dataValue";return _this}_createClass(InterpolationIdentity,[{key:"api",value:function api(){var baseFragment=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this._base;var currentVoxel=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._currentVoxel;var dataValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._dataValue;this._base=baseFragment;return this.compute(currentVoxel,dataValue)}},{key:"compute",value:function compute(currentVoxel,dataValue){this.computeDefinition();this._base._functions[this._name]=this._definition;return this._name+"("+currentVoxel+", "+dataValue+");"}},{key:"computeDefinition",value:function computeDefinition(){this._definition="\nvoid "+this._name+"(in vec3 currentVoxel, out vec4 dataValue){\n // lower bound\n vec3 rcurrentVoxel = vec3(floor(currentVoxel.x + 0.5 ), floor(currentVoxel.y + 0.5 ), floor(currentVoxel.z + 0.5 ));\n ivec3 voxel = ivec3(int(rcurrentVoxel.x), int(rcurrentVoxel.y), int(rcurrentVoxel.z));\n\n vec4 tmp = vec4(0., 0., 0., 0.);\n int offset = 0;\n\n "+_shadersHelpers4.default.api(this._base,"voxel","tmp","offset")+"\n "+_shadersHelpers2.default.api(this._base,"tmp","offset","dataValue")+"\n}\n "}}]);return InterpolationIdentity}(_shaders2.default);exports.default=new InterpolationIdentity},{"../helpers/shaders.helpers.texture3d":142,"../helpers/shaders.helpers.unpack":143,"../shaders.base":147}],145:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _shadersInterpolation=require("./shaders.interpolation.identity");var _shadersInterpolation2=_interopRequireDefault(_shadersInterpolation);var _shadersInterpolation3=require("./shaders.interpolation.trilinear");var _shadersInterpolation4=_interopRequireDefault(_shadersInterpolation3);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function shadersInterpolation(baseFragment,currentVoxel,dataValue,gradient){switch(baseFragment._uniforms.uInterpolation.value){case 0:return _shadersInterpolation2.default.api(baseFragment,currentVoxel,dataValue);case 1:return _shadersInterpolation4.default.api(baseFragment,currentVoxel,dataValue,gradient);default:return _shadersInterpolation2.default.api(baseFragment,currentVoxel,dataValue)}}exports.default=shadersInterpolation},{"./shaders.interpolation.identity":144,"./shaders.interpolation.trilinear":146}],146:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("../shaders.base");var _shaders2=_interopRequireDefault(_shaders);var _shadersInterpolation=require("./shaders.interpolation.identity");var _shadersInterpolation2=_interopRequireDefault(_shadersInterpolation);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var InterpolationTrilinear=function(_ShadersBase){_inherits(InterpolationTrilinear,_ShadersBase);function InterpolationTrilinear(){_classCallCheck(this,InterpolationTrilinear);var _this=_possibleConstructorReturn(this,(InterpolationTrilinear.__proto__||Object.getPrototypeOf(InterpolationTrilinear)).call(this));_this.name="interpolationTrilinear";_this._currentVoxel="currentVoxel";_this._dataValue="dataValue";_this._gradient="gradient";return _this}_createClass(InterpolationTrilinear,[{key:"api",value:function api(){var baseFragment=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this._base;var currentVoxel=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._currentVoxel;var dataValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._dataValue;var gradient=arguments.length>3&&arguments[3]!==undefined?arguments[3]:this._gradient;this._base=baseFragment;return this.compute(currentVoxel,dataValue,gradient)}},{key:"compute",value:function compute(currentVoxel,dataValue,gradient){this.computeDefinition();this._base._functions[this._name]=this._definition;return this._name+"("+currentVoxel+", "+dataValue+", "+gradient+");"}},{key:"computeDefinition",value:function computeDefinition(){this._definition="\nvoid "+this._name+"(in vec3 currentVoxel, out vec4 dataValue, out vec3 gradient){\n\n // https://en.wikipedia.org/wiki/Trilinear_interpolation\n vec3 lower_bound = vec3(floor(currentVoxel.x), floor(currentVoxel.y), floor(currentVoxel.z));\n if(lower_bound.x < 0.){\n lower_bound.x = 0.;\n }\n if(lower_bound.y < 0.){\n lower_bound.y = 0.;\n }\n if(lower_bound.z < 0.){\n lower_bound.z = 0.;\n }\n \n vec3 higher_bound = lower_bound + vec3(1);\n\n float xd = ( currentVoxel.x - lower_bound.x ) / ( higher_bound.x - lower_bound.x );\n float yd = ( currentVoxel.y - lower_bound.y ) / ( higher_bound.y - lower_bound.y );\n float zd = ( currentVoxel.z - lower_bound.z ) / ( higher_bound.z - lower_bound.z );\n\n //\n // c00\n //\n\n //\n\n vec4 v000 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c000 = vec3(lower_bound.x, lower_bound.y, lower_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c000","v000")+"\n vec3 g000 = v000.r * vec3(-1., -1., -1.);\n\n //\n\n vec4 v100 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c100 = vec3(higher_bound.x, lower_bound.y, lower_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c100","v100")+"\n vec3 g100 = v100.r * vec3(1., -1., -1.);\n\n vec4 c00 = v000 * ( 1.0 - xd ) + v100 * xd;\n\n //\n // c01\n //\n vec4 v001 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c001 = vec3(lower_bound.x, lower_bound.y, higher_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c001","v001")+"\n vec3 g001 = v001.r * vec3(-1., -1., 1.);\n\n vec4 v101 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c101 = vec3(higher_bound.x, lower_bound.y, higher_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c101","v101")+"\n vec3 g101 = v101.r * vec3(1., -1., 1.);\n\n vec4 c01 = v001 * ( 1.0 - xd ) + v101 * xd;\n\n //\n // c10\n //\n vec4 v010 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c010 = vec3(lower_bound.x, higher_bound.y, lower_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c010","v010")+"\n vec3 g010 = v010.r * vec3(-1., 1., -1.);\n\n vec4 v110 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c110 = vec3(higher_bound.x, higher_bound.y, lower_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c110","v110")+"\n vec3 g110 = v110.r * vec3(1., 1., -1.);\n\n vec4 c10 = v010 * ( 1.0 - xd ) + v110 * xd;\n\n //\n // c11\n //\n vec4 v011 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c011 = vec3(lower_bound.x, higher_bound.y, higher_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c011","v011")+"\n vec3 g011 = v011.r * vec3(-1., 1., 1.);\n\n vec4 v111 = vec4(0.0, 0.0, 0.0, 0.0);\n vec3 c111 = vec3(higher_bound.x, higher_bound.y, higher_bound.z);\n "+_shadersInterpolation2.default.api(this._base,"c111","v111")+"\n vec3 g111 = v111.r * vec3(1., 1., 1.);\n\n vec4 c11 = v011 * ( 1.0 - xd ) + v111 * xd;\n\n // c0 and c1\n vec4 c0 = c00 * ( 1.0 - yd) + c10 * yd;\n vec4 c1 = c01 * ( 1.0 - yd) + c11 * yd;\n\n // c\n vec4 c = c0 * ( 1.0 - zd) + c1 * zd;\n dataValue = c;\n\n // compute gradient\n gradient = g000 + g100 + g010 + g110 + g011 + g111 + g110 + g011;\n // gradientMagnitude = length(gradient);\n // // https://en.wikipedia.org/wiki/Normal_(geometry)#Transforming_normals\n // vec3 localNormal = (-1. / gradientMagnitude) * gradient;\n // normal = normalize(normalPixelToPatient"+this.id+" * localNormal);\n //normal = gradient;\n\n}\n "}}])
return InterpolationTrilinear}(_shaders2.default);exports.default=new InterpolationTrilinear},{"../shaders.base"
147,"./shaders.interpolation.identity":144}],147:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersBase=function(){function ShadersBase(){_classCallCheck(this,ShadersBase);this._name="shadersBase";this._base={_functions:{},_uniforms:{}};this._definition=""}_createClass(ShadersBase,[{key:"name",get:function get(){return this._name},set:function set(name){this._name=name}}]);return ShadersBase}();exports.default=ShadersBase},{}],148:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersFragment=function(){function ShadersFragment(uniforms){_classCallCheck(this,ShadersFragment);this._uniforms=uniforms;this._functions={};this._main=""}_createClass(ShadersFragment,[{key:"functions",value:function functions(){if(this._main===""){this.main()}var content="";for(var property in this._functions){content+=this._functions[property]+"\n"}return content}},{key:"uniforms",value:function uniforms(){var content="";for(var property in this._uniforms){var uniform=this._uniforms[property];content+="uniform "+uniform.typeGLSL+" "+property;if(uniform&&uniform.length){content+="["+uniform.length+"]"}content+=";\n"}return content}},{key:"main",value:function main(){this._main="\n\nfloat luma (vec3 rgb) {\n return (rgb.r + rgb.g + rgb.b)/3.0;\n}\n\nconst float T = 0.04;\nconst float M = 1.0;\nconst float L = 0.002;\n\nvoid main(void) {\n\n vec2 texCoord = vec2(((vProjectedCoords.x / vProjectedCoords.w) + 1.0 ) / 2.0,\n ((vProjectedCoords.y / vProjectedCoords.w) + 1.0 ) / 2.0 );\n\n float borderWidth = uWidth; // in px\n float step_u = borderWidth * 1.0 / uCanvasWidth;\n float step_v = borderWidth * 1.0 / uCanvasHeight;\n vec4 centerPixel = texture2D(uTextureFilled, texCoord);\n\n vec4 rightPixel = texture2D(uTextureFilled, texCoord + vec2(step_u, 0.0));\n vec4 bottomPixel = texture2D(uTextureFilled, texCoord + vec2(0.0, step_v));\n\n // now manually compute the derivatives\n float _dFdX = length(rightPixel - centerPixel) / step_u;\n float _dFdY = length(bottomPixel - centerPixel) / step_v;\n\n // gl_FragColor.r = _dFdX;\n // gl_FragColor.g = _dFdY;\n gl_FragColor.r = max(max(centerPixel.r, rightPixel.r), bottomPixel.r);\n gl_FragColor.g = max(max(centerPixel.g, rightPixel.g), bottomPixel.g);\n gl_FragColor.b = max(max(centerPixel.b, rightPixel.b), bottomPixel.b);\n gl_FragColor.a = max(_dFdX, _dFdY);\n\n return;\n // float h = 1./uCanvasHeight;\n // float w = 1./uCanvasWidth;\n // vec4 n[9];\n // n[0] = texture2D(uTextureFilled, vProjectedTextCoords + vec2( -w, -h));\n // n[1] = texture2D(uTextureFilled, vProjectedTextCoords + vec2(0.0, -h));\n // n[2] = texture2D(uTextureFilled, vProjectedTextCoords + vec2( w, -h));\n // n[3] = texture2D(uTextureFilled, vProjectedTextCoords + vec2( -w, 0.0));\n // n[4] = texture2D(uTextureFilled, vProjectedTextCoords);\n // n[5] = texture2D(uTextureFilled, texCoord + vec2( w, 0.0));\n // n[6] = texture2D(uTextureFilled, texCoord + vec2( -w, h));\n // n[7] = texture2D(uTextureFilled, texCoord + vec2(0.0, h));\n // n[8] = texture2D(uTextureFilled, texCoord + vec2( w, h));\n // vec4 sobel_horizEdge = n[2] + (2.0*n[5]) + n[8] - (n[0] + (2.0*n[3]) + n[6]);\n // vec4 sobel_vertEdge = n[0] + (2.0*n[1]) + n[2] - (n[6] + (2.0*n[7]) + n[8]);\n // vec3 sobel = sqrt((sobel_horizEdge.rgb * sobel_horizEdge.rgb) + (sobel_vertEdge.rgb * sobel_vertEdge.rgb));\n // gl_FragColor = vec4( sobel, max(max(sobel.r, sobel.g), sobel.b) );\n\n return;\n}\n "}},{key:"compute",value:function compute(){var shaderInterpolation="";return"\n// uniforms\n"+this.uniforms()+"\n\n// varying (should fetch it from vertex directly)\nvarying vec4 vProjectedCoords;\n\n// tailored functions\n"+this.functions()+"\n\n// main loop\n"+this._main+"\n "}}]);return ShadersFragment}();exports.default=ShadersFragment},{}],149:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersUniform=function(){function ShadersUniform(){_classCallCheck(this,ShadersUniform)}_createClass(ShadersUniform,null,[{key:"uniforms",value:function uniforms(){return{uCanvasWidth:{type:"f",value:0,typeGLSL:"float"},uCanvasHeight:{type:"f",value:0,typeGLSL:"float"},uWidth:{type:"f",value:1,typeGLSL:"float"},uTextureFilled:{type:"t",value:[],typeGLSL:"sampler2D"}}}}]);return ShadersUniform}();exports.default=ShadersUniform},{}],150:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersVertex=function(){function ShadersVertex(){_classCallCheck(this,ShadersVertex)}_createClass(ShadersVertex,[{key:"compute",value:function compute(){return"\nvarying vec4 vProjectedCoords;\n\n//\n// main\n//\nvoid main() {\n\n vec4 vPos = modelMatrix * vec4(position, 1.0 );\n mat4 vProjectionViewMatrix = projectionMatrix * viewMatrix;\n vProjectedCoords = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );\n\n}\n "}}]);return ShadersVertex}();exports.default=ShadersVertex},{}],151:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("./interpolation/shaders.interpolation");var _shaders2=_interopRequireDefault(_shaders);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersFragment=function(){function ShadersFragment(uniforms){_classCallCheck(this,ShadersFragment);this._uniforms=uniforms;this._functions={};this._main=""}_createClass(ShadersFragment,[{key:"functions",value:function functions(){if(this._main===""){this.main()}var content="";for(var property in this._functions){content+=this._functions[property]+"\n"}return content}},{key:"uniforms",value:function uniforms(){var content="";for(var property in this._uniforms){var uniform=this._uniforms[property];content+="uniform "+uniform.typeGLSL+" "+property;if(uniform&&uniform.length){content+="["+uniform.length+"]"}content+=";\n"}return content}},{key:"main",value:function main(){this._main="\nvoid main(void) {\n\n // draw border if slice is cropped\n // float uBorderDashLength = 10.;\n\n if( uCanvasWidth > 0. &&\n ((gl_FragCoord.x > uBorderMargin && (gl_FragCoord.x - uBorderMargin) < uBorderWidth) ||\n (gl_FragCoord.x < (uCanvasWidth - uBorderMargin) && (gl_FragCoord.x + uBorderMargin) > (uCanvasWidth - uBorderWidth) ))){\n float valueY = mod(gl_FragCoord.y, 2. * uBorderDashLength);\n if( valueY < uBorderDashLength && gl_FragCoord.y > uBorderMargin && gl_FragCoord.y < (uCanvasHeight - uBorderMargin) ){\n gl_FragColor = vec4(uBorderColor, 1.);\n return;\n }\n }\n\n if( uCanvasHeight > 0. &&\n ((gl_FragCoord.y > uBorderMargin && (gl_FragCoord.y - uBorderMargin) < uBorderWidth) ||\n (gl_FragCoord.y < (uCanvasHeight - uBorderMargin) && (gl_FragCoord.y + uBorderMargin) > (uCanvasHeight - uBorderWidth) ))){\n float valueX = mod(gl_FragCoord.x, 2. * uBorderDashLength);\n if( valueX < uBorderDashLength && gl_FragCoord.x > uBorderMargin && gl_FragCoord.x < (uCanvasWidth - uBorderMargin) ){\n gl_FragColor = vec4(uBorderColor, 1.);\n return;\n }\n }\n\n // get texture coordinates of current pixel\n vec4 dataCoordinates = uWorldToData * vPos;\n vec3 currentVoxel = dataCoordinates.xyz;\n vec4 dataValue = vec4(0., 0., 0., 0.);\n vec3 gradient = vec3(0., 0., 0.);\n "+(0,_shaders2.default)(this,"currentVoxel","dataValue","gradient")+"\n\n // how do we deal wil more than 1 channel?\n float intensity = dataValue.r;\n if(uNumberOfChannels == 1){\n float normalizedIntensity = dataValue.r;\n\n // rescale/slope\n normalizedIntensity =\n normalizedIntensity*uRescaleSlopeIntercept[0] + uRescaleSlopeIntercept[1];\n\n float windowMin = uWindowCenterWidth[0] - uWindowCenterWidth[1] * 0.5;\n float windowMax = uWindowCenterWidth[0] + uWindowCenterWidth[1] * 0.5;\n normalizedIntensity =\n ( normalizedIntensity - windowMin ) / uWindowCenterWidth[1];\n\n dataValue.r = dataValue.g = dataValue.b = normalizedIntensity;\n dataValue.a = 1.0;\n }\n\n // Apply LUT table...\n //\n if(uLut == 1){\n // should opacity be grabbed there?\n dataValue = texture2D( uTextureLUT, vec2( dataValue.r , 1.0) );\n }\n\n if(uLutSegmentation == 1){\n // should opacity be grabbed there?\n //\n float textureWidth = 256.;\n float textureHeight = 128.;\n float min = 0.;\n // start at 0!\n int adjustedIntensity = int(floor(intensity + 0.5));\n\n // Get row and column in the texture\n int colIndex = int(mod(float(adjustedIntensity), textureWidth));\n int rowIndex = int(floor(float(adjustedIntensity)/textureWidth));\n\n float texWidth = 1./textureWidth;\n float texHeight = 1./textureHeight;\n \n // Map row and column to uv\n vec2 uv = vec2(0,0);\n uv.x = 0.5 * texWidth + (texWidth * float(colIndex));\n uv.y = 1. - (0.5 * texHeight + float(rowIndex) * texHeight);\n\n dataValue = texture2D( uTextureLUTSegmentation, uv );\n // uv.x = (0.5 + float(colIndex)) / textureWidth;\n // uv.y = 1. - (0.5 + float(rowIndex)) / textureHeight;\n // dataValue = texture2D( uTextureLUTSegmentation, uv );\n }\n\n if(uInvert == 1){\n dataValue = vec4(1.) - dataValue;\n // how do we deal with that and opacity?\n dataValue.a = 1.;\n }\n\n gl_FragColor = dataValue;\n\n // if on edge, draw line\n // float xPos = gl_FragCoord.x/512.;\n // float yPos = gl_FragCoord.y/512.;\n // if( xPos < 0.05 || xPos > .95 || yPos < 0.05 || yPos > .95){\n // gl_FragColor = vec4(xPos, yPos, 0., 1.);//dataValue;\n // //return;\n // }\n\n}\n "}},{key:"compute",value:function compute(){var shaderInterpolation="";return"\n// uniforms\n"+this.uniforms()+"\n\n// varying (should fetch it from vertex directly)\nvarying vec4 vPos;\n\n// tailored functions\n"+this.functions()+"\n\n// main loop\n"+this._main+"\n "}}]);return ShadersFragment}();exports.default=ShadersFragment},{"./interpolation/shaders.interpolation":145}],152:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersUniform=function(){function ShadersUniform(){_classCallCheck(this,ShadersUniform)}_createClass(ShadersUniform,null,[{key:"uniforms",value:function uniforms(){return{uTextureSize:{type:"i",value:0,typeGLSL:"int"},uTextureContainer:{type:"tv",value:[],typeGLSL:"sampler2D",length:7},uDataDimensions:{type:"iv",value:[0,0,0],typeGLSL:"ivec3"},uWorldToData:{type:"m4",value:new _three.Matrix4,typeGLSL:"mat4"},uWindowCenterWidth:{type:"fv1",value:[0,0],typeGLSL:"float",length:2},uRescaleSlopeIntercept:{type:"fv1",value:[0,0],typeGLSL:"float",length:2},uNumberOfChannels:{type:"i",value:1,typeGLSL:"int"},uBitsAllocated:{type:"i",value:8,typeGLSL:"int"},uInvert:{type:"i",value:0,typeGLSL:"int"},uLut:{type:"i",value:0,typeGLSL:"int"},uTextureLUT:{type:"t",value:[],typeGLSL:"sampler2D"},uLutSegmentation:{type:"i",value:0,typeGLSL:"int"},uTextureLUTSegmentation:{type:"t",value:[],typeGLSL:"sampler2D"},uPixelType:{type:"i",value:0,typeGLSL:"int"},uPackedPerPixel:{type:"i",value:1,typeGLSL:"int"},uInterpolation:{type:"i",value:1,typeGLSL:"int"},uCanvasWidth:{type:"f",value:0,typeGLSL:"float"},uCanvasHeight:{type:"f",value:0,typeGLSL:"float"},uBorderColor:{type:"v3",value:[1,0,.5],typeGLSL:"vec3"},uBorderWidth:{type:"f",value:2,typeGLSL:"float"},uBorderMargin:{type:"f",value:2,typeGLSL:"float"},uBorderDashLength:{type:"f",value:10,typeGLSL:"float"}}}}]);return ShadersUniform}();exports.default=ShadersUniform},{three:81}],153:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersVertex=function(){function ShadersVertex(){_classCallCheck(this,ShadersVertex)}_createClass(ShadersVertex,[{key:"compute",value:function compute(){return"\nvarying vec4 vPos;\n\n//\n// main\n//\nvoid main() {\n\n vPos = modelMatrix * vec4(position, 1.0 );\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );\n\n}\n "}}]);return ShadersVertex}();exports.default=ShadersVertex},{}],154:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _shadersContour=require("./shaders.contour.uniform");var _shadersContour2=_interopRequireDefault(_shadersContour);var _shadersContour3=require("./shaders.contour.fragment");var _shadersContour4=_interopRequireDefault(_shadersContour3);var _shadersContour5=require("./shaders.contour.vertex");var _shadersContour6=_interopRequireDefault(_shadersContour5);var _shadersData=require("./shaders.data.uniform");var _shadersData2=_interopRequireDefault(_shadersData);var _shadersData3=require("./shaders.data.fragment");var _shadersData4=_interopRequireDefault(_shadersData3);var _shadersData5=require("./shaders.data.vertex");var _shadersData6=_interopRequireDefault(_shadersData5);var _shadersVr=require("./shaders.vr.uniform");var _shadersVr2=_interopRequireDefault(_shadersVr);var _shadersVr3=require("./shaders.vr.fragment");var _shadersVr4=_interopRequireDefault(_shadersVr3);var _shadersVr5=require("./shaders.vr.vertex");var _shadersVr6=_interopRequireDefault(_shadersVr5);var _shadersLayer=require("./shaders.layer.uniform");var _shadersLayer2=_interopRequireDefault(_shadersLayer);var _shadersLayer3=require("./shaders.layer.fragment");var _shadersLayer4=_interopRequireDefault(_shadersLayer3);var _shadersLayer5=require("./shaders.layer.vertex");var _shadersLayer6=_interopRequireDefault(_shadersLayer5);var _shadersLocalizer=require("./shaders.localizer.uniform");var _shadersLocalizer2=_interopRequireDefault(_shadersLocalizer);var _shadersLocalizer3=require("./shaders.localizer.fragment");var _shadersLocalizer4=_interopRequireDefault(_shadersLocalizer3);var _shadersLocalizer5=require("./shaders.localizer.vertex");var _shadersLocalizer6=_interopRequireDefault(_shadersLocalizer5);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={ContourUniform:_shadersContour2.default,ContourFragment:_shadersContour4.default,ContourVertex:_shadersContour6.default,DataUniform:_shadersData2.default,DataFragment:_shadersData4.default,DataVertex:_shadersData6.default,VRUniform:_shadersVr2.default,VRFragment:_shadersVr4.default,VRVertex:_shadersVr6.default,LayerUniform:_shadersLayer2.default,LayerFragment:_shadersLayer4.default,LayerVertex:_shadersLayer6.default,LocalizerUniform:_shadersLocalizer2.default,LocalizerFragment:_shadersLocalizer4.default,LocalizerVertex:_shadersLocalizer6.default}},{"./shaders.contour.fragment":148,"./shaders.contour.uniform":149,"./shaders.contour.vertex":150,"./shaders.data.fragment":151,"./shaders.data.uniform":152,"./shaders.data.vertex":153,"./shaders.layer.fragment":155,"./shaders.layer.uniform":156,"./shaders.layer.vertex":157,"./shaders.localizer.fragment":158,"./shaders.localizer.uniform":159,"./shaders.localizer.vertex":160,"./shaders.vr.fragment":161,"./shaders.vr.uniform":162,"./shaders.vr.vertex":163}],155:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersFragment=function(){function ShadersFragment(uniforms){_classCallCheck(this,ShadersFragment);this._uniforms=uniforms;this._functions={};this._main=""}_createClass(ShadersFragment,[{key:"functions",value:function functions(){if(this._main===""){this.main()}var content="";for(var property in this._functions){content+=this._functions[property]+"\n"}return content}},{key:"uniforms",value:function uniforms(){var content="";for(var property in this._uniforms){var uniform=this._uniforms[property];content+="uniform "+uniform.typeGLSL+" "+property;if(uniform&&uniform.length){content+="["+uniform.length+"]"}content+=";\n"}return content}},{key:"main",value:function main(){this._main="\nvoid main(void) {\n\n vec2 texc = vec2(((vProjectedCoords.x / vProjectedCoords.w) + 1.0 ) / 2.0,\n ((vProjectedCoords.y / vProjectedCoords.w) + 1.0 ) / 2.0 );\n\n // just silence warning for\n // vec4 dummy = vPos;\n\n //The back position is the world space position stored in the texture.\n vec4 baseColor0 = texture2D(uTextureBackTest0, texc);\n vec4 baseColor1 = texture2D(uTextureBackTest1, texc);\n\n if( uTrackMouse == 1 ){\n\n if( vProjectedCoords.x < uMouse.x ){\n\n gl_FragColor = baseColor0;\n\n }\n else{\n\n gl_FragColor = mix( baseColor0, baseColor1, uOpacity1 );\n\n }\n\n }\n else{\n\n if( uType1 == 0 ){\n\n //merge an image into\n gl_FragColor = mix( baseColor0, baseColor1, uOpacity1 );\n\n }\n else{\n\n float opacity = baseColor1.a;\n gl_FragColor = mix( baseColor0, baseColor1, opacity * uOpacity1 );\n\n }\n\n }\n\n return;\n}\n "}},{key:"compute",value:function compute(){var shaderInterpolation="";return"\n// uniforms\n"+this.uniforms()+"\n\n// varying (should fetch it from vertex directly)\n// varying vec4 vPos;\nvarying vec4 vProjectedCoords;\n\n// tailored functions\n"+this.functions()+"\n\n// main loop\n"+this._main+"\n "}}]);return ShadersFragment}();exports.default=ShadersFragment},{}],156:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersUniform=function(){function ShadersUniform(){_classCallCheck(this,ShadersUniform)}_createClass(ShadersUniform,null,[{key:"uniforms",value:function uniforms(){return{uTextureBackTest0:{type:"t",value:[],typeGLSL:"sampler2D"},uTextureBackTest1:{type:"t",value:[],typeGLSL:"sampler2D"},uOpacity0:{type:"f",value:1,typeGLSL:"float"},uOpacity1:{type:"f",value:1,typeGLSL:"float"},uType0:{type:"i",value:0,typeGLSL:"int"},uType1:{type:"i",value:1,typeGLSL:"int"},uTrackMouse:{type:"i",value:0,typeGLSL:"int"},uMouse:{type:"v2",value:new _three.Vector2,typeGLSL:"vec2"}}}}]);return ShadersUniform}();exports.default=ShadersUniform},{three:81}],157:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersVertex=function(){function ShadersVertex(){_classCallCheck(this,ShadersVertex)}_createClass(ShadersVertex,[{key:"compute",value:function compute(){return"\n// varying vec4 vPos;\nvarying vec4 vProjectedCoords;\n\n//\n// main\n//\nvoid main() {\n\n vec4 vPos = modelMatrix * vec4(position, 1.0 );\n vProjectedCoords = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );\n\n}\n "}}]);return ShadersVertex}();exports.default=ShadersVertex},{}],158:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _class=function(){function _class(uniforms){_classCallCheck(this,_class);this._uniforms=uniforms;this._functions={};this._main=""}_createClass(_class,[{key:"functions",value:function functions(){if(this._main===""){this.main()}var content="";for(var property in this._functions){content+=this._functions[property]+"\n"}return content}},{key:"uniforms",value:function uniforms(){var content="";for(var property in this._uniforms){var uniform=this._uniforms[property];content+="uniform "+uniform.typeGLSL+" "+property;if(uniform&&uniform.length){content+="["+uniform.length+"]"}content+=";\n"}return content}},{key:"main",value:function main(){this._main="\nvoid intersectionProjection(\n in vec4 plane,\n in vec4 slice,\n out vec3 intersectionProjection){\n\n vec3 intersectionDirection = normalize(cross(plane.xyz, slice.xyz));\n vec3 intersectionPoint = \n cross(intersectionDirection,slice.xyz) * plane.w +\n cross(plane.xyz, intersectionDirection) * slice.w;\n\n intersectionProjection =\n intersectionPoint.xyz +\n (dot(vPos.xyz - intersectionPoint, intersectionDirection)\n * intersectionDirection);\n\n}\n\nvoid main(void) {\n vec4 c1 = vec4(0., 0., 0., 0.);\n vec4 c2 = vec4(0., 0., 0., 0.);\n vec4 c3 = vec4(0., 0., 0., 0.);\n\n // localizer #1\n // must be normalized!\n if(length(uPlane1.xyz) > 0.5) {\n vec3 projection1 = vec3(1.);\n intersectionProjection(\n uPlane1,\n uSlice,\n projection1\n );\n\n vec4 projInter1 = (vProjectionViewMatrix * vec4(projection1, 1.));\n vec3 ndc1 = projInter1.xyz / projInter1.w;\n vec2 screenSpace1 = (ndc1.xy * .5 + .5) * vec2(uCanvasWidth, uCanvasHeight);\n\n float d1 = distance(gl_FragCoord.xy, screenSpace1.xy);\n c1 = vec4(uPlaneColor1, 1. - smoothstep(.5, .7, d1));\n }\n\n // localizer #2\n if(length(uPlane2.xyz) > 0.5) {\n vec3 projection2 = vec3(1.);\n intersectionProjection(\n uPlane2,\n uSlice,\n projection2\n );\n\n vec4 projInter2 = (vProjectionViewMatrix * vec4(projection2, 1.));\n vec3 ndc2 = projInter2.xyz / projInter2.w;\n vec2 screenSpace2 = (ndc2.xy * .5 + .5) * vec2(uCanvasWidth, uCanvasHeight);\n\n float d2 = distance(gl_FragCoord.xy, screenSpace2.xy);\n c2 = vec4(uPlaneColor2, 1. - smoothstep(.5, .7, d2));\n }\n\n // localizer #3\n if(length(uPlane3.xyz) > 0.5) {\n vec3 projection3 = vec3(1.);\n intersectionProjection(\n uPlane3,\n uSlice,\n projection3\n );\n\n vec4 projInter3 = (vProjectionViewMatrix * vec4(projection3, 1.));\n vec3 ndc3 = projInter3.xyz / projInter3.w;\n vec2 screenSpace3 = (ndc3.xy * .5 + .5) * vec2(uCanvasWidth, uCanvasHeight);\n\n float d3 = distance(gl_FragCoord.xy, screenSpace3.xy);\n c3 = vec4(uPlaneColor3, 1. - smoothstep(.5, .7, d3));\n }\n\n // float uBorderDashLength = 10.0;\n // float uBorderWidth = 2.0;\n // float valueX = mod(gl_FragCoord.x, 2. * uBorderDashLength);\n // float valueY = mod(gl_FragCoord.y, 2. * uBorderDashLength);\n // if( valueX < uBorderDashLength || valueY < uBorderDashLength ){\n vec3 colorMix = c1.xyz*c1.w + c2.xyz*c2.w + c3.xyz*c3.w;\n gl_FragColor = vec4(colorMix, max(max(c1.w, c2.w),c3.w)*0.5);\n return;\n // }\n \n // gl_FragColor = vec4(0., 0., 0., 0.);\n // return;\n}\n "}},{key:"compute",value:function compute(){return"\n// uniforms\n"+this.uniforms()+"\n\n// varying (should fetch it from vertex directly)\nvarying vec4 vPos;\nvarying mat4 vProjectionViewMatrix;\n\n// tailored functions\n"+this.functions()+"\n\n// main loop\n"+this._main+"\n "}}]);return _class}();exports.default=_class},{}],159:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _class=function(){function _class(){_classCallCheck(this,_class)}_createClass(_class,null,[{key:"uniforms",value:function uniforms(){return{uCanvasWidth:{type:"f",value:0,typeGLSL:"float"},uCanvasHeight:{type:"f",value:0,typeGLSL:"float"},uSlice:{type:"v4",value:[0,0,0,0],typeGLSL:"vec4"},uPlane1:{type:"v4",value:[0,0,0,0],typeGLSL:"vec4"},uPlaneColor1:{type:"v3",value:[1,1,0],typeGLSL:"vec3"},uPlane2:{type:"v4",value:[0,0,0,0],typeGLSL:"vec4"},uPlaneColor2:{type:"v3",value:[1,1,0],typeGLSL:"vec3"},uPlane3:{type:"v4",value:[0,0,0,0],typeGLSL:"vec4"},uPlaneColor3:{type:"v3",value:[1,1,0],typeGLSL:"vec3"}}}}]);return _class}();exports.default=_class},{}],160:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){

if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _class=function(){function _class(){_classCallCheck(this,_class)}_createClass(_class,[{key:"compute",value:function compute(){return"\nvarying vec4 vPos;\nvarying mat4 vProjectionViewMatrix;\n\n//\n// main\n//\nvoid main() {\n\n vPos = modelMatrix * vec4(position, 1.0 );\n vProjectionViewMatrix = projectionMatrix * viewMatrix;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );\n\n}\n "}}]);return _class}();exports.default=_class},{}],161:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _shaders=require("./interpolation/shaders.interpolation");var _shaders2=_interopRequireDefault(_shaders);var _shadersHelpers=require("./helpers/shaders.helpers.intersectBox");var _shadersHelpers2=_interopRequireDefault(_shadersHelpers);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersFragment=function(){function ShadersFragment(uniforms){_classCallCheck(this,ShadersFragment);this._uniforms=uniforms;this._functions={};this._main=""}_createClass(ShadersFragment,[{key:"functions",value:function functions(){if(this._main===""){this.main()}var content="";for(var property in this._functions){content+=this._functions[property]+"\n"}return content}},{key:"uniforms",value:function uniforms(){var content="";for(var property in this._uniforms){var uniform=this._uniforms[property];content+="uniform "+uniform.typeGLSL+" "+property;if(uniform&&uniform.length){content+="["+uniform.length+"]"}content+=";\n"}return content}},{key:"main",value:function main(){this._main="\nvoid getIntensity(in vec3 dataCoordinates, out float intensity, out vec3 gradient){\n\n vec4 dataValue = vec4(0., 0., 0., 0.);\n "+(0,_shaders2.default)(this,"dataCoordinates","dataValue","gradient")+"\n\n intensity = dataValue.r;\n\n // rescale/slope\n intensity = intensity*uRescaleSlopeIntercept[0] + uRescaleSlopeIntercept[1];\n // window level\n float windowMin = uWindowCenterWidth[0] - uWindowCenterWidth[1] * 0.5;\n intensity = ( intensity - windowMin ) / uWindowCenterWidth[1];\n}\n\nvoid main(void) {\n const int maxSteps = 1024;\n\n // the ray\n vec3 rayOrigin = cameraPosition;\n vec3 rayDirection = normalize(vPos.xyz - rayOrigin);\n\n // the Axe-Aligned B-Box\n vec3 AABBMin = vec3(uWorldBBox[0], uWorldBBox[2], uWorldBBox[4]);\n vec3 AABBMax = vec3(uWorldBBox[1], uWorldBBox[3], uWorldBBox[5]);\n\n // Intersection ray/bbox\n float tNear, tFar;\n bool intersect = false;\n "+_shadersHelpers2.default.api(this,"rayOrigin","rayDirection","AABBMin","AABBMax","tNear","tFar","intersect")+"\n if (tNear < 0.0) tNear = 0.0;\n\n // init the ray marching\n float tCurrent = tNear;\n float tStep = (tFar - tNear) / float(uSteps);\n vec4 accumulatedColor = vec4(0.0);\n float accumulatedAlpha = 0.0;\n\n for(int rayStep = 0; rayStep < maxSteps; rayStep++){\n vec3 currentPosition = rayOrigin + rayDirection * tCurrent;\n // some non-linear FUN\n // some occlusion issue to be fixed\n vec3 transformedPosition = currentPosition; //transformPoint(currentPosition, uAmplitude, uFrequence);\n // world to data coordinates\n // rounding trick\n // first center of first voxel in data space is CENTERED on (0,0,0)\n vec4 dataCoordinatesRaw = uWorldToData * vec4(transformedPosition, 1.0);\n vec3 currentVoxel = vec3(dataCoordinatesRaw.x, dataCoordinatesRaw.y, dataCoordinatesRaw.z);\n float intensity = 0.0;\n vec3 gradient = vec3(0., 0., 0.);\n getIntensity(currentVoxel, intensity, gradient);\n\n vec4 colorSample;\n float alphaSample;\n if(uLut == 1){\n vec4 colorFromLUT = texture2D( uTextureLUT, vec2( intensity, 1.0) );\n // 256 colors\n colorSample = colorFromLUT;\n alphaSample = colorFromLUT.a;\n }\n else{\n alphaSample = intensity;\n colorSample.r = colorSample.g = colorSample.b = intensity * alphaSample;\n }\n\n alphaSample = alphaSample * uAlphaCorrection;\n alphaSample *= (1.0 - accumulatedAlpha);\n\n accumulatedColor += alphaSample * colorSample;\n accumulatedAlpha += alphaSample;\n\n tCurrent += tStep;\n\n if(tCurrent > tFar || accumulatedAlpha >= 1.0 ) break;\n }\n\n gl_FragColor = vec4(accumulatedColor.xyz, accumulatedAlpha);\n}\n "}},{key:"compute",value:function compute(){var shaderInterpolation="";return"\n// uniforms\n"+this.uniforms()+"\n\n// varying (should fetch it from vertex directly)\nvarying vec4 vPos;\n\n// tailored functions\n"+this.functions()+"\n\n// main loop\n"+this._main+"\n "}}]);return ShadersFragment}();exports.default=ShadersFragment},{"./helpers/shaders.helpers.intersectBox":141,"./interpolation/shaders.interpolation":145}],162:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _three=require("three");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersUniform=function(){function ShadersUniform(){_classCallCheck(this,ShadersUniform)}_createClass(ShadersUniform,null,[{key:"uniforms",value:function uniforms(){return{uTextureSize:{type:"i",value:0,typeGLSL:"int"},uTextureContainer:{type:"tv",value:[],typeGLSL:"sampler2D",length:7},uDataDimensions:{type:"iv",value:[0,0,0],typeGLSL:"ivec3"},uWorldToData:{type:"m4",value:new _three.Matrix4,typeGLSL:"mat4"},uWindowCenterWidth:{type:"fv1",value:[0,0],typeGLSL:"float",length:2},uRescaleSlopeIntercept:{type:"fv1",value:[0,0],typeGLSL:"float",length:2},uNumberOfChannels:{type:"i",value:1,typeGLSL:"int"},uBitsAllocated:{type:"i",value:8,typeGLSL:"int"},uInvert:{type:"i",value:0,typeGLSL:"int"},uLut:{type:"i",value:0,typeGLSL:"int"},uTextureLUT:{type:"t",value:[],typeGLSL:"sampler2D"},uPixelType:{type:"i",value:0,typeGLSL:"int"},uPackedPerPixel:{type:"i",value:1,typeGLSL:"int"},uInterpolation:{type:"i",value:1,typeGLSL:"int"},uWorldBBox:{type:"fv1",value:[0,0,0,0,0,0],typeGLSL:"float",length:6},uSteps:{type:"i",value:256,typeGLSL:"int"},uAlphaCorrection:{type:"f",value:.5,typeGLSL:"float"},uFrequence:{type:"f",value:0,typeGLSL:"float"},uAmplitude:{type:"f",value:0,typeGLSL:"float"}}}}]);return ShadersUniform}();exports.default=ShadersUniform},{three:81}],163:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var ShadersVertex=function(){function ShadersVertex(){_classCallCheck(this,ShadersVertex)}_createClass(ShadersVertex,[{key:"compute",value:function compute(){return"\nvarying vec4 vPos;\n\n//\n// main\n//\nvoid main() {\n\n vPos = modelMatrix * vec4(position, 1.0 );\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0 );\n\n}\n "}}]);return ShadersVertex}();exports.default=ShadersVertex},{}],164:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _widgets3=require("./widgets.handle");var _widgets4=_interopRequireDefault(_widgets3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsAnnotation=function(_WidgetsBase){_inherits(WidgetsAnnotation,_WidgetsBase);function WidgetsAnnotation(targetMesh,controls,camera,container){_classCallCheck(this,WidgetsAnnotation);var _this=_possibleConstructorReturn(this,(WidgetsAnnotation.__proto__||Object.getPrototypeOf(WidgetsAnnotation)).call(this));_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._container=container;_this._active=true;_this._worldPosition=new _three.Vector3;if(_this._targetMesh!==null){_this._worldPosition=_this._targetMesh.position}_this._material=null;_this._geometry=null;_this._mesh=null;_this._line=null;_this._label=null;_this._cone=null;_this._labeltext=null;_this._alreadycreated=null;_this._movinglabel=null;_this._labelmoved=false;_this._labelhovered=false;_this._domHovered=false;_this._hovered=true;_this._manuallabeldisplay=false;_this._labelpositionx=null;_this._labelpositiony=null;_this._differencemousecenterlabelx=0;_this._differencemousecenterlabely=0;_this._handles=[];var firstHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);firstHandle.worldPosition=_this._worldPosition;firstHandle.hovered=true;_this.add(firstHandle);_this._handles.push(firstHandle);var secondHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);secondHandle.worldPosition=_this._worldPosition;secondHandle.hovered=true;secondHandle.active=true;secondHandle.tracking=true;_this.add(secondHandle);_this._handles.push(secondHandle);_this.create();_this.onEnd=_this.onEnd.bind(_this);_this.onMove=_this.onMove.bind(_this);_this.onHoverlabel=_this.onHoverlabel.bind(_this);_this.notonHoverlabel=_this.notonHoverlabel.bind(_this);_this.changelabeltext=_this.changelabeltext.bind(_this);_this.movelabel=_this.movelabel.bind(_this);_this.notmovelabel=_this.notmovelabel.bind(_this);_this.addEventListeners();return _this}_createClass(WidgetsAnnotation,[{key:"addEventListeners",value:function addEventListeners(){this._label.addEventListener("mouseenter",this.onHoverlabel);this._label.addEventListener("mouseleave",this.notonHoverlabel);this._label.addEventListener("dblclick",this.changelabeltext);this._label.addEventListener("mousedown",this.movelabel);this._container.addEventListener("mouseup",this.notmovelabel);this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove)}},{key:"movelabel",value:function movelabel(){if(this._labelhovered){this._movinglabel=true;this._labelmoved=true;var mousey=-(-event.clientY+this._container.offsetHeight);var mousex=event.clientX;this._differencemousecenterlabelx=Math.abs(Math.abs(mousex)-Math.abs(this._labelpositionx));this._differencemousecenterlabely=Math.abs(Math.abs(mousey)-Math.abs(this._labelpositiony))}}},{key:"notmovelabel",value:function notmovelabel(){this._movinglabel=false;this._handles[0]._controls.enabled=true;this._handles[1]._controls.enabled=true;this._differencemousecenterlabelx=0;this._differencemousecenterlabely=0}},{key:"onHoverlabel",value:function onHoverlabel(){this._labelhovered=true}},{key:"notonHoverlabel",value:function notonHoverlabel(){this._labelhovered=false}},{key:"onMove",value:function onMove(evt){if(this._movinglabel){this._handles[0]._controls.enabled=false;this._handles[1]._controls.enabled=false}this._dragged=true;this._handles[0].onMove(evt);this._handles[1].onMove(evt);this._hovered=this._handles[0].hovered||this._handles[1].hovered||this._labelhovered;this.update()}},{key:"onStart",value:function onStart(evt){this._dragged=false;this._handles[0].onStart(evt);this._handles[1].onStart(evt);this._active=this._handles[0].active||this._handles[1].active;this.update()}},{key:"setlabeltext",value:function setlabeltext(){this._labeltext=prompt("Please enter the name of the label","");if(typeof this._labeltext=="string"){if(this._labeltext.length>0){this._label.innerHTML=this._labeltext;this._label.style.display="";this._dashline.style.display=""}else{this._label.innerHTML=this._labeltext;this._label.style.display="none";this._dashline.style.display="none"}}}},{key:"changelabeltext",value:function changelabeltext(){this._labeltext=prompt("Please enter new name of the label",this._label.innerHTML);if(typeof this._labeltext=="string"){if(this._labeltext.length>0){this._label.innerHTML=this._labeltext;this._label.style.display="";this._dashline.style.display=""}else{this._label.innerHTML=this._labeltext;this._label.style.display="none";this._dashline.style.display="none"}}}},{key:"displaylabel",value:function displaylabel(){if(typeof this._labeltext=="string"){this._label.innerHTML=this._labeltext;this._label.style.display="";this._dashline.style.display="";this._label.style.transform="translate3D("+this._labelpositionx+"px,"+this._labelpositiony+"px, 0)"}}},{key:"onEnd",value:function onEnd(evt){this._handles[0].onEnd(evt);if(this._dragged||!this._handles[1].tracking){this._handles[1].tracking=false;this._handles[1].onEnd(evt)}else{this._handles[1].tracking=false}if(!this._alreadycreated){this.setlabeltext();this._alreadycreated=true}this._active=this._handles[0].active||this._handles[1].active;this.update()}},{key:"create",value:function create(){this.createMesh();this.createDOM()}},{key:"update",value:function update(){this.updateColor();this.updateMeshColor();this.updateMeshPosition();this.updateDOMPosition();this.updateDOMColor()}},{key:"createMesh",value:function createMesh(){this._geometry=new THREE.Geometry;this._geometry.vertices.push(this._handles[0].worldPosition);this._geometry.vertices.push(this._handles[1].worldPosition);this._material=new THREE.LineBasicMaterial;this.updateMeshColor();this._meshline=new THREE.Line(this._geometry,this._material);this._meshline.visible=true;this.add(this._meshline);this._conegeometry=new THREE.CylinderGeometry(0,2,10);this._conegeometry.translate(0,-5,0);this._conegeometry.rotateX(-Math.PI/2);this._cone=new THREE.Mesh(this._conegeometry,this._material);this._cone.visible=true;this.add(this._cone)}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}}},{key:"updateMeshPosition",value:function updateMeshPosition(){if(this._geometry){this._geometry.verticesNeedUpdate=true}}},{key:"createDOM",value:function createDOM(){this._line=document.createElement("div");this._line.setAttribute("class","widgets handle line");this._line.style.position="absolute";this._line.style.transformOrigin="0 100%";this._line.style.marginTop="-1px";this._line.style.height="2px";this._line.style.width="3px";this._container.appendChild(this._line);this._dashline=document.createElement("div");this._dashline.setAttribute("class","widgets handle dashline");this._dashline.style.position="absolute";this._dashline.style.border="none";this._dashline.style.borderTop="2.5px dashed #F9F9F9";this._dashline.style.transformOrigin="0 100%";this._dashline.style.height="1px";this._dashline.style.width="50%";this._dashline.style.display="none";this._container.appendChild(this._dashline);this._label=document.createElement("div");this._label.setAttribute("id",this.uuid);this._label.setAttribute("class","widgets handle label");this._label.style.border="2px solid #F9F9F9";this._label.style.backgroundColor="#F9F9F9";this._label.style.color="#353535";this._label.style.padding="4px";this._label.style.position="absolute";this._label.style.transformOrigin="0 100%";this._label.innerHTML="Hello, world!";this._label.style.display="none";this._container.appendChild(this._label);this.updateDOMColor()}},{key:"updateDOMPosition",value:function updateDOMPosition(){var x1=this._handles[0].screenPosition.x;var y1=this._handles[0].screenPosition.y;var x2=this._handles[1].screenPosition.x;var y2=this._handles[1].screenPosition.y;var x0=x1+(x2-x1)/2;var y0=y1+(y2-y1)/2;var length=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));var angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;var posY=y1-this._container.offsetHeight;var transform="translate3D("+x1+"px,"+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._line.style.transform=transform;this._line.style.width=length+"px";var mousex=0;var mousey=0;var posY0=void 0;posY0=y0-this._container.offsetHeight-this._label.offsetHeight/2;x0-=this._label.offsetWidth/2;var x=void 0;var y=void 0;if(!this._labelmoved){var transform2="translate3D("+Math.round(x0)+"px,"+Math.round(posY0)+"px, 0)";this._label.style.transform=transform2;this._labelpositionx=Math.round(x0);this._labelpositiony=Math.round(posY0)}if(this._movinglabel){mousex=event.clientX;mousey=-(-event.clientY+this._container.offsetHeight);this._label.style.transform="translate3D("+(mousex-this._differencemousecenterlabelx)+"px,"+(mousey-this._differencemousecenterlabely)+"px, 0)";this._labelpositionx=mousex-this._differencemousecenterlabelx;this._labelpositiony=mousey-this._differencemousecenterlabely}if(this._manuallabeldisplay){this.displaylabel()}var w0=this._handles[0].worldPosition;var w1=this._handles[1].worldPosition;this._cone.position.set(w1.x,w1.y,w1.z);this._cone.lookAt(w0);x1=this._handles[0].screenPosition.x;y1=this._handles[0].screenPosition.y;x2=this._labelpositionx;y2=this._labelpositiony+this._container.offsetHeight;var labelheight=this._label.offsetHeight;var labelwidth=this._label.offsetWidth;var centerlabelx=0;var centerlabely=0;if(isFinite(labelwidth)&&isFinite(labelheight)){centerlabelx=labelwidth/2;centerlabely=labelheight/2}x2+=centerlabelx;y2+=centerlabely;var x1_tail=this._handles[0].screenPosition.x;var y1_tail=this._handles[0].screenPosition.y;var x1_body=(this._handles[0].screenPosition.x+this._handles[1].screenPosition.x)/2;var y1_body=(this._handles[0].screenPosition.y+this._handles[1].screenPosition.y)/2;var x1_nose=this._handles[1].screenPosition.x;var y1_nose=this._handles[1].screenPosition.y;var lengthtaillabel=Math.sqrt((x1_tail-x2)*(x1_tail-x2)+(y1_tail-y2)*(y1_tail-y2));var lengthbodylabel=Math.sqrt((x1_body-x2)*(x1_body-x2)+(y1_body-y2)*(y1_body-y2));var lengthnoselabel=Math.sqrt((x1_nose-x2)*(x1_nose-x2)+(y1_nose-y2)*(y1_nose-y2));var lengths=[lengthtaillabel,lengthbodylabel,lengthnoselabel];var minlength=Math.min(lengthtaillabel,lengthbodylabel,lengthnoselabel);var minlengthindex=lengths.indexOf(minlength);if(minlengthindex==0){x1=x1_tail;y1=y1_tail}if(minlengthindex==1){x1=x1_body;y1=y1_body}if(minlengthindex==2){x1=x1_nose;y1=y1_nose}var lengthdashline=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));var angledashline=Math.atan2(y2-y1,x2-x1)*180/Math.PI;var posYdashline=y1-this._container.offsetHeight;var transformdashline="translate3D("+x1+"px,"+posYdashline+"px, 0)";transformdashline+=" rotate("+angledashline+"deg)";this._dashline.style.transform=transformdashline;this._dashline.style.width=lengthdashline+"px"}},{key:"updateDOMColor",value:function updateDOMColor(){this._line.style.backgroundColor=""+this._color;this._dashline.style.borderTop="2.5px dashed "+(""+this._color);this._label.style.borderColor=""+this._color}},{key:"hideDOM",value:function hideDOM(){this._line.style.display="none";this._dashline.style.display="none";this._label.style.display="none"}},{key:"showDOM",value:function showDOM(){this._line.style.display="";this._dashline.style.display="";this._label.style.display=""}},{key:"hideMesh",value:function hideMesh(){this.visible=false}},{key:"showMesh",value:function showMesh(){this.visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"worldPosition",get:function get(){return this._worldPosition},set:function set(worldPosition){this._worldPosition=worldPosition;this._handles[0].worldPosition=this._worldPosition;this._handles[1].worldPosition=this._worldPosition;this.update()}}]);return WidgetsAnnotation}(_widgets2.default);exports.default=WidgetsAnnotation},{"./widgets.base":165,"./widgets.handle":167,three:81}],165:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsBase=function(_THREE$Object3D){_inherits(WidgetsBase,_THREE$Object3D);function WidgetsBase(container){_classCallCheck(this,WidgetsBase);var _this=_possibleConstructorReturn(this,(WidgetsBase.__proto__||Object.getPrototypeOf(WidgetsBase)).call(this));_this._enabled=true;_this._selected=false;_this._hovered=false;_this._active=false;_this._colors={default:"#00B0FF",active:"#FFEB3B",hover:"#F50057",select:"#76FF03"};_this._color=_this._colors.default;_this._dragged=false;_this._displayed=true;_this._container=container;return _this}_createClass(WidgetsBase,[{key:"initOffsets",value:function initOffsets(){var box=this._container.getBoundingClientRect();var body=document.body;var docEl=document.documentElement;var scrollTop=window.pageYOffset||docEl.scrollTop||body.scrollTop;var scrollLeft=window.pageXOffset||docEl.scrollLeft||body.scrollLeft;var clientTop=docEl.clientTop||body.clientTop||0;var clientLeft=docEl.clientLeft||body.clientLeft||0;var top=box.top+scrollTop-clientTop;var left=box.left+scrollLeft-clientLeft;this._offsets={top:Math.round(top),left:Math.round(left)}}},{key:"offsetChanged",value:function offsetChanged(){this.initOffsets();this.update()}},{key:"getMouseOffsets",value:function getMouseOffsets(event,container){return{x:(event.clientX-this._offsets.left)/container.offsetWidth*2-1,y:-((event.clientY-this._offsets.top)/container.offsetHeight)*2+1,screenX:event.clientX-this._offsets.left,screenY:event.clientY-this._offsets.top}}},{key:"update",value:function update(){window.console.log("update() should be overloaded!")}},{key:"free",value:function free(){this._container=null}},{key:"updateColor",value:function updateColor(){if(this._active){this._color=this._colors.active}else if(this._hovered){this._color=this._colors.hover}else if(this._selected){this._color=this._colors.select}else{this._color=this._colors.default}}},{key:"enabled",get:function get(){return this._enabled},set:function set(enabled){this._enabled=enabled;this.update()}},{key:"selected",get:function get(){return this._selected},set:function set(selected){this._selected=selected;this.update()}},{key:"hovered",get:function get(){return this._hovered},set:function set(hovered){this._hovered=hovered;this.update()}},{key:"dragged",get:function get(){return this._dragged},set:function set(dragged){this._dragged=dragged;this.update()}},{key:"displayed",get:function get(){return this._displayed},set:function set(displayed){this._displayed=displayed;this.update()}},{key:"active",get:function get(){return this._active},set:function set(active){this._active=active;this.update()}},{key:"color",get:function get(){return this._color},set:function set(color){this._color=color;this.update()}}]);return WidgetsBase}(THREE.Object3D);exports.default=WidgetsBase},{}],166:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _widgets3=require("./widgets.handle");var _widgets4=_interopRequireDefault(_widgets3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsBiRuler=function(_WidgetsBase){_inherits(WidgetsBiRuler,_WidgetsBase);function WidgetsBiRuler(targetMesh,controls,camera,container){_classCallCheck(this,WidgetsBiRuler);var _this=_possibleConstructorReturn(this,(WidgetsBiRuler.__proto__||Object.getPrototypeOf(WidgetsBiRuler)).call(this));_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._container=container;_this._active=true;_this._initOrtho=false;_this._worldPosition=new _three.Vector3;if(_this._targetMesh!==null){_this._worldPosition=_this._targetMesh.position}_this._material=null;_this._geometry=null;_this._mesh=null;_this._line=null;_this._distance=null;_this._handles=[];var firstHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);firstHandle.worldPosition=_this._worldPosition;firstHandle.hovered=true;_this.add(firstHandle);_this._handles.push(firstHandle);var secondHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);secondHandle.worldPosition=_this._worldPosition;secondHandle.hovered=true;secondHandle.active=true;secondHandle.tracking=true;_this.add(secondHandle);_this._handles.push(secondHandle);var thirdHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);thirdHandle.worldPosition=_this._worldPosition;thirdHandle.hovered=true;_this.add(thirdHandle);_this._handles.push(thirdHandle);var fourthHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);fourthHandle.worldPosition=_this._worldPosition;fourthHandle.hovered=true;_this.add(fourthHandle);_this._handles.push(fourthHandle);_this.create();_this.onMove=_this.onMove.bind(_this);_this.addEventListeners();_this._orientation=null;_this._slice=null;return _this}_createClass(WidgetsBiRuler,[{key:"addEventListeners",value:function addEventListeners(){this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove)}},{key:"onMove",value:function onMove(evt){this._dragged=true;this._handles[0].onMove(evt);this._handles[1].onMove(evt);this._handles[2].onMove(evt);this._handles[3].onMove(evt);this._hovered=this._handles[0].hovered||this._handles[1].hovered||this._handles[2].hovered||this._handles[3].hovered;this.update()}},{key:"onStart",value:function onStart(evt){this._dragged=false;this._handles[0].onStart(evt);this._handles[1].onStart(evt);this._handles[2].onStart(evt);this._handles[3].onStart(evt)

this._active=this._handles[0].active||this._handles[1].active||this._handles[2].active||this._handles[3].active;this.update()}},{key
"onEnd",value:function onEnd(evt){this._handles[0].onEnd(evt);this._handles[2].onEnd(evt);this._handles[3].onEnd(evt);window.console.log(this);if(this._dragged||!this._handles[1].tracking){this._handles[1].tracking=false;this._handles[1].onEnd(evt)}else{this._handles[1].tracking=false}this._active=this._handles[0].active||this._handles[1].active||this._handles[2].active||this._handles[3].active;this.update()}},{key:"create",value:function create(){this.createMesh();this.createDOM()}},{key:"hideDOM",value:function hideDOM(){this._line.style.display="none";this._distance.style.display="none";this._line2.style.display="none";this._distance2.style.display="none";for(var index in this._handles){this._handles[index].hideDOM()}this._dashline.style.display="none"}},{key:"showDOM",value:function showDOM(){this._line.style.display="";this._distance.style.display="";this._line2.style.display="";this._distance2.style.display="";for(var index in this._handles){this._handles[index].showDOM()}this._dashline.style.display=""}},{key:"hideMesh",value:function hideMesh(){this._mesh.visible=false;this._mesh2.visible=false;this._handles[0].visible=false;this._handles[1].visible=false;this._handles[2].visible=false;this._handles[3].visible=false}},{key:"showMesh",value:function showMesh(){this._mesh.visible=true;this._mesh2.visible=true;this._handles[0].visible=true;this._handles[1].visible=true;this._handles[2].visible=true;this._handles[3].visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"update",value:function update(){this.updateColor();this.updateMeshColor();this.updateMeshPosition();this.updateDOMPosition();this.updateDOMColor()}},{key:"createMesh",value:function createMesh(){this._geometry=new THREE.Geometry;this._geometry.vertices.push(this._handles[0].worldPosition);this._geometry.vertices.push(this._handles[1].worldPosition);this._geometry2=new THREE.Geometry;this._geometry2.vertices.push(this._handles[2].worldPosition);this._geometry2.vertices.push(this._handles[3].worldPosition);this._material=new THREE.LineBasicMaterial;this._material2=new THREE.LineBasicMaterial;this.updateMeshColor();this._mesh=new THREE.Line(this._geometry,this._material);this._mesh.visible=true;this._mesh2=new THREE.Line(this._geometry2,this._material2);this._mesh2.visible=true;this.add(this._mesh);this.add(this._mesh2)}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}if(this._material2){this._material2.color.set(this._color)}}},{key:"updateMeshPosition",value:function updateMeshPosition(){if(this._geometry){this._geometry.verticesNeedUpdate=true}if(this._geometry2){this._geometry2.verticesNeedUpdate=true}}},{key:"createDOM",value:function createDOM(){this._line=document.createElement("div");this._line.setAttribute("class","widgets handle line");this._line.style.position="absolute";this._line.style.transformOrigin="0 100%";this._line.style.marginTop="-1px";this._line.style.height="2px";this._line.style.width="3px";this._container.appendChild(this._line);this._distance=document.createElement("div");this._distance.setAttribute("class","widgets handle distance");this._distance.style.border="2px solid";this._distance.style.backgroundColor="#F9F9F9";this._distance.style.color="#353535";this._distance.style.padding="4px";this._distance.style.position="absolute";this._distance.style.transformOrigin="0 100%";this._distance.innerHTML="Hello, world!";this._container.appendChild(this._distance);this._line2=document.createElement("div");this._line2.setAttribute("class","widgets handle line");this._line2.style.position="absolute";this._line2.style.transformOrigin="0 100%";this._line2.style.marginTop="-1px";this._line2.style.height="2px";this._line2.style.width="3px";this._container.appendChild(this._line2);this._distance2=document.createElement("div");this._distance2.setAttribute("class","widgets handle distance");this._distance.style.border="2px solid";this._distance.style.backgroundColor="#F9F9F9";this._distance2.style.color="#353535";this._distance2.style.padding="4px";this._distance2.style.position="absolute";this._distance2.style.transformOrigin="0 100%";this._distance2.innerHTML="Hello, world!";this._container.appendChild(this._distance2);this._dashline=document.createElement("div");this._dashline.setAttribute("class","widgets handle dashline");this._dashline.style.position="absolute";this._dashline.style.border="none";this._dashline.style.borderTop="2.5px dashed #F9F9F9";this._dashline.style.transformOrigin="0 100%";this._dashline.style.height="1px";this._dashline.style.width="50%";this._container.appendChild(this._dashline);this.updateDOMColor()}},{key:"updateDOMPosition",value:function updateDOMPosition(){var x1=this._handles[0].screenPosition.x;var y1=this._handles[0].screenPosition.y;var x2=this._handles[1].screenPosition.x;var y2=this._handles[1].screenPosition.y;var x0=x2;var y0=y2;if(y1>=y2){y0=y2-30}else{y0=y2+30}var length=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));var angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;var posY=y1-this._container.offsetHeight;var transform="translate3D("+x1+"px,"+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._line.style.transform=transform;this._line.style.width=length+"px";var w0=this._handles[0].worldPosition;var w1=this._handles[1].worldPosition;this._distance.innerHTML=Math.sqrt((w0.x-w1.x)*(w0.x-w1.x)+(w0.y-w1.y)*(w0.y-w1.y)+(w0.z-w1.z)*(w0.z-w1.z)).toFixed(2)+" mm";this._distanceValue=Math.sqrt((w0.x-w1.x)*(w0.x-w1.x)+(w0.y-w1.y)*(w0.y-w1.y)+(w0.z-w1.z)*(w0.z-w1.z)).toFixed(2);var posY0=y0-this._container.offsetHeight-this._distance.offsetHeight/2;x0-=this._distance.offsetWidth/2;var transform2="translate3D("+Math.round(x0)+"px,"+Math.round(posY0)+"px, 0)";this._distance.style.transform=transform2;var x3=this._handles[2].screenPosition.x;var y3=this._handles[2].screenPosition.y;var x4=this._handles[3].screenPosition.x;var y4=this._handles[3].screenPosition.y;var x02=x4;var y02=y4;if(y3>=y4){y02=y4-30}else{y02=y4+30}length=Math.sqrt((x3-x4)*(x3-x4)+(y3-y4)*(y3-y4));angle=Math.atan2(y4-y3,x4-x3)*180/Math.PI;posY=y3-this._container.offsetHeight;transform="translate3D("+x3+"px,"+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._line2.style.transform=transform;this._line2.style.width=length+"px";var w02=this._handles[2].worldPosition;var w12=this._handles[3].worldPosition;this._distance2.innerHTML=Math.sqrt((w02.x-w12.x)*(w02.x-w12.x)+(w02.y-w12.y)*(w02.y-w12.y)+(w02.z-w12.z)*(w02.z-w12.z)).toFixed(2)+" mm";this._distance2Value=Math.sqrt((w02.x-w12.x)*(w02.x-w12.x)+(w02.y-w12.y)*(w02.y-w12.y)+(w02.z-w12.z)*(w02.z-w12.z)).toFixed(2);var posY02=y02-this._container.offsetHeight-this._distance2.offsetHeight/2;x02-=this._distance2.offsetWidth/2;transform2="translate3D("+Math.round(x02)+"px,"+Math.round(posY02)+"px, 0)";this._distance2.style.transform=transform2;var l1center=this.getPointInBetweenByPerc(this._handles[0].worldPosition,this._handles[1].worldPosition,.5);var l2center=this.getPointInBetweenByPerc(this._handles[2].worldPosition,this._handles[3].worldPosition,.5);var screen1=this._handles[0].worldToScreen(l1center,this._camera,this._container);var screen2=this._handles[0].worldToScreen(l2center,this._camera,this._container);x1=screen1.x;y1=screen1.y;x2=screen2.x;y2=screen2.y;length=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;posY=y1-this._container.offsetHeight;transform="translate3D("+x1+"px,"+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._dashline.style.transform=transform;this._dashline.style.width=length+"px"}},{key:"updateDOMColor",value:function updateDOMColor(){this._line.style.backgroundColor=""+this._color;this._distance.style.borderColor=""+this._color;this._line2.style.backgroundColor=""+this._color;this._distance2.style.borderColor=""+this._color}},{key:"getPointInBetweenByPerc",value:function getPointInBetweenByPerc(pointA,pointB,percentage){var dir=pointB.clone().sub(pointA);var len=dir.length();dir=dir.normalize().multiplyScalar(len*percentage);return pointA.clone().add(dir)}},{key:"initOrtho",value:function initOrtho(){this._initOrtho=true;var pcenter=this.getPointInBetweenByPerc(this._handles[0].worldPosition,this._handles[1].worldPosition,.5);this._handles[2].worldPosition=this.getPointInBetweenByPerc(this._handles[0].worldPosition,this._handles[1].worldPosition,.25);this._handles[3].worldPosition=this.getPointInBetweenByPerc(this._handles[0].worldPosition,this._handles[1].worldPosition,.75);this._handles[2].worldPosition.x=pcenter.x-Math.sqrt((pcenter.y-this._handles[2].worldPosition.y)*(pcenter.y-this._handles[2].worldPosition.y));this._handles[2].worldPosition.y=pcenter.y+Math.sqrt((pcenter.x-this._handles[2].worldPosition.x)*(pcenter.x-this._handles[2].worldPosition.x));this._handles[3].worldPosition.x=pcenter.x+Math.sqrt((pcenter.y-this._handles[2].worldPosition.y)*(pcenter.y-this._handles[2].worldPosition.y));this._handles[3].worldPosition.y=pcenter.y-Math.sqrt((pcenter.x-this._handles[2].worldPosition.x)*(pcenter.x-this._handles[2].worldPosition.x))}},{key:"worldPosition",get:function get(){return this._worldPosition},set:function set(worldPosition){this._worldPosition=worldPosition;this._handles[0].worldPosition=this._worldPosition;this._handles[1].worldPosition=this._worldPosition;this._handles[2].worldPosition=this._worldPosition;this._handles[3].worldPosition=this._worldPosition;this.update()}},{key:"shotestDistance",get:function get(){return this._distanceValue<this._distance2Value?this._distanceValue:this._distance2Value}},{key:"longestDistance",get:function get(){return this._distanceValue>this._distance2Value?this._distanceValue:this._distance2Value}}]);return WidgetsBiRuler}(_widgets2.default);exports.default=WidgetsBiRuler},{"./widgets.base":165,"./widgets.handle":167,three:81}],167:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _core=require("../core/core.intersections");var _core2=_interopRequireDefault(_core);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsHandle=function(_WidgetsBase){_inherits(WidgetsHandle,_WidgetsBase);function WidgetsHandle(targetMesh,controls,camera,container){_classCallCheck(this,WidgetsHandle);var _this=_possibleConstructorReturn(this,(WidgetsHandle.__proto__||Object.getPrototypeOf(WidgetsHandle)).call(this,container));_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._plane={position:new _three.Vector3,direction:new _three.Vector3};_this._offset=new _three.Vector3;_this._raycaster=new THREE.Raycaster;_this._tracking=false;_this._mouse=new _three.Vector2;_this._lastEvent=null;_this._worldPosition=new _three.Vector3;_this._screenPosition=new _three.Vector2;_this._material=null;_this._geometry=null;_this._mesh=null;_this._meshDisplayed=true;_this._meshHovered=false;_this._meshStyle="sphere";_this._dom=null;_this._domDisplayed=true;_this._domHovered=false;_this._domStyle="circle";if(_this._targetMesh!==null){_this._worldPosition.copy(_this._targetMesh.position)}_this._screenPosition=_this.worldToScreen(_this._worldPosition,_this._camera,_this._container);_this.create();_this.initOffsets();_this.onMove=_this.onMove.bind(_this);_this.onHover=_this.onHover.bind(_this);_this.onEndControl=_this.onEndControl.bind(_this);_this.addEventListeners();return _this}_createClass(WidgetsHandle,[{key:"addEventListeners",value:function addEventListeners(){this._dom.addEventListener("mouseenter",this.onHover);this._dom.addEventListener("mouseleave",this.onHover);this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove);this._controls.addEventListener("end",this.onEndControl)}},{key:"removeEventListeners",value:function removeEventListeners(){this._dom.removeEventListener("mouseenter",this.onHover);this._dom.removeEventListener("mouseleave",this.onHover);this._container.removeEventListener("mousewheel",this.onMove);this._container.removeEventListener("DOMMouseScroll",this.onMove);this._controls.removeEventListener("end",this.onEndControl)}},{key:"create",value:function create(){this.createMesh();this.createDOM()}},{key:"onStart",value:function onStart(evt){this._lastEvent=evt;evt.preventDefault();var offsets=this.getMouseOffsets(evt,this._container);this._mouse.set(offsets.x,offsets.y);this._raycaster.setFromCamera(this._mouse,this._camera);this._raycaster.ray.position=this._raycaster.ray.origin;if(this._hovered){this._active=true;this._controls.enabled=false;if(this._targetMesh){var intersectsTarget=this._raycaster.intersectObject(this._targetMesh);if(intersectsTarget.length>0){this._offset.copy(intersectsTarget[0].point).sub(this._worldPosition)}}else{this._plane.position.copy(this._worldPosition);this._plane.direction.copy(this._camera.getWorldDirection());var intersection=_core2.default.rayPlane(this._raycaster.ray,this._plane);if(intersection!==null){this._offset.copy(intersection).sub(this._plane.position)}}this.update()}}},{key:"onEnd",value:function onEnd(evt){this._lastEvent=evt;evt.preventDefault();if(this._tracking===true){return}if(!this._dragged&&this._active){this._selected=!this._selected}this._active=false;this._dragged=false;this._controls.enabled=true;this.update()}},{key:"onEndControl",value:function onEndControl(){var _this2=this;if(!this._lastEvent){return}window.requestAnimationFrame(function(){_this2.onMove(_this2._lastEvent)})}},{key:"onMove",value:function onMove(evt){this._lastEvent=evt;evt.preventDefault();var offsets=this.getMouseOffsets(evt,this._container);this._mouse.set(offsets.x,offsets.y);this._raycaster.setFromCamera(this._mouse,this._camera);this._raycaster.ray.position=this._raycaster.ray.origin;if(this._active){this._dragged=true;if(this._targetMesh!==null){var intersectsTarget=this._raycaster.intersectObject(this._targetMesh);if(intersectsTarget.length>0){this._worldPosition.copy(intersectsTarget[0].point.sub(this._offset))}}else{if(this._plane.direction.length()===0){this._plane.position.copy(this._worldPosition);this._plane.direction.copy(this._camera.getWorldDirection())}var intersection=_core2.default.rayPlane(this._raycaster.ray,this._plane);if(intersection!==null){this._worldPosition.copy(intersection.sub(this._offset))}}}else{this.onHover(null)}this.update()}},{key:"onHover",value:function onHover(evt){if(evt){this._lastEvent=evt;evt.preventDefault();this.hoverDom(evt)}this.hoverMesh();this._hovered=this._meshHovered||this._domHovered;this._container.style.cursor=this._hovered?"pointer":"default"}},{key:"update",value:function update(){this.updateColor();this._screenPosition=this.worldToScreen(this._worldPosition,this._camera,this._container);this.updateMeshColor();this.updateMeshPosition();this.updateDOMColor();this.updateDOMPosition()}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}}},{key:"updateMeshPosition",value:function updateMeshPosition(){if(this._mesh){this._mesh.position.x=this._worldPosition.x;this._mesh.position.y=this._worldPosition.y;this._mesh.position.z=this._worldPosition.z}}},{key:"hoverMesh",value:function hoverMesh(){var intersectsHandle=this._raycaster.intersectObject(this._mesh);this._meshHovered=intersectsHandle.length>0}},{key:"hoverDom",value:function hoverDom(evt){this._domHovered=evt.type==="mouseenter"}},{key:"worldToScreen",value:function worldToScreen(worldCoordinate,camera,canvas){var screenCoordinates=worldCoordinate.clone();screenCoordinates.project(camera);screenCoordinates.x=Math.round((screenCoordinates.x+1)*canvas.offsetWidth/2);screenCoordinates.y=Math.round((-screenCoordinates.y+1)*canvas.offsetHeight/2);screenCoordinates.z=0;return screenCoordinates}},{key:"createMesh",value:function createMesh(){this._geometry=new THREE.SphereGeometry(1,16,16);this._material=new THREE.MeshBasicMaterial({wireframe:true,wireframeLinewidth:2});this._mesh=new THREE.Mesh(this._geometry,this._material);this._mesh.position.x=this._worldPosition.x;this._mesh.position.y=this._worldPosition.y;this._mesh.position.z=this._worldPosition.z;this._mesh.visible=true;this.updateMeshColor();this.add(this._mesh)}},{key:"createDOM",value:function createDOM(){this._dom=document.createElement("div");this._dom.setAttribute("id",this.uuid);this._dom.setAttribute("class","AMI Widget Handle");this._dom.style.border="2px solid";this._dom.style.backgroundColor="#F9F9F9";this._dom.style.color="#F9F9F9";this._dom.style.position="absolute";this._dom.style.width="12px";this._dom.style.height="12px";this._dom.style.margin="-6px";this._dom.style.borderRadius="50%";this._dom.style.transformOrigin="0 100%";var posY=this._screenPosition.y-this._container.offsetHeight;this._dom.style.transform="translate3D("+this._screenPosition.x+"px, "+posY+"px, 0)";this.updateDOMColor();this._container.appendChild(this._dom)}},{key:"updateDOMPosition",value:function updateDOMPosition(){if(this._dom){var posY=this._screenPosition.y-this._container.offsetHeight;this._dom.style.transform="translate3D("+this._screenPosition.x+"px, "+posY+"px, 0)"}}},{key:"updateDOMColor",value:function updateDOMColor(){this._dom.style.borderColor=""+this._color}},{key:"free",value:function free(){this._container.removeChild(this._dom);this.removeEventListeners();_get(WidgetsHandle.prototype.__proto__||Object.getPrototypeOf(WidgetsHandle.prototype),"free",this).call(this)}},{key:"hideDOM",value:function hideDOM(){this._dom.style.display="none"}},{key:"showDOM",value:function showDOM(){this._dom.style.display=""}},{key:"hideMesh",value:function hideMesh(){this.visible=false}},{key:"showMesh",value:function showMesh(){this.visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"worldPosition",set:function set(worldPosition){this._worldPosition.copy(worldPosition);this.update()},get:function get(){return this._worldPosition}},{key:"screenPosition",set:function set(screenPosition){this._screenPosition=screenPosition},get:function get(){return this._screenPosition}},{key:"active",get:function get(){return this._active},set:function set(active){this._active=active;this._controls.enabled=!this._active;this.update()}},{key:"tracking",get:function get(){return this._tracking},set:function set(tracking){this._tracking=tracking;this.update()}}]);return WidgetsHandle}(_widgets2.default);exports.default=WidgetsHandle},{"../core/core.intersections":103,"./widgets.base":165,three:81}],168:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _widgets=require("./widgets.annotation");var _widgets2=_interopRequireDefault(_widgets);var _widgets3=require("./widgets.biruler");var _widgets4=_interopRequireDefault(_widgets3);var _widgets5=require("./widgets.handle");var _widgets6=_interopRequireDefault(_widgets5);var _widgets7=require("./widgets.roi");var _widgets8=_interopRequireDefault(_widgets7);var _widgets9=require("./widgets.ruler");var _widgets10=_interopRequireDefault(_widgets9);var _widgets11=require("./widgets.voxelProbe");var _widgets12=_interopRequireDefault(_widgets11);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default={Annotation:_widgets2.default,BiRuler:_widgets4.default,Handle:_widgets6.default,Roi:_widgets8.default,Ruler:_widgets10.default,VoxelProbe:_widgets12.default}},{"./widgets.annotation":164,"./widgets.biruler":166,"./widgets.handle":167,"./widgets.roi":169,"./widgets.ruler":170,"./widgets.voxelProbe":171}],169:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _widgets3=require("./widgets.handle");var _widgets4=_interopRequireDefault(_widgets3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsRoi=function(_WidgetsBase){_inherits(WidgetsRoi,_WidgetsBase);function WidgetsRoi(targetMesh,controls,camera,container){_classCallCheck(this,WidgetsRoi);var _this=_possibleConstructorReturn(this,(WidgetsRoi.__proto__||Object.getPrototypeOf(WidgetsRoi)).call(this));_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._container=container;_this._active=true;_this._init=false;_this._worldPosition=new _three.Vector3;if(_this._targetMesh!==null){_this._worldPosition=_this._targetMesh.position}_this._material=null;_this._geometry=null;_this._mesh=null;_this._lines=[];_this._area=null;_this._handles=[];var firstHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);firstHandle.worldPosition=_this._worldPosition;firstHandle.hovered=true;_this.add(firstHandle);_this._handles.push(firstHandle);_this.create();_this.onMove=_this.onMove.bind(_this);_this.addEventListeners();_this._orientation=null;_this._slice=null;return _this}_createClass(WidgetsRoi,[{key:"addEventListeners",value:function addEventListeners(){this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove)}},{key:"onMove",value:function onMove(evt){this._dragged=true;var numHandles=this._handles.length;if(this.active&&!this._init){var lastHandle=this._handles[numHandles-1];lastHandle.hovered=false;lastHandle.active=false;lastHandle.tracking=false;var nextHandle=new _widgets4.default(this._targetMesh,this._controls,this._camera,this._container);nextHandle.worldPosition=this._worldPosition;nextHandle.hovered=true;nextHandle.active=true;nextHandle.tracking=true;this.add(nextHandle);this._handles.push(nextHandle);var newLine=document.createElement("div");newLine.setAttribute("class","widgets handle line");newLine.style.position="absolute";newLine.style.transformOrigin="0 100%";newLine.style.marginTop="-1px";newLine.style.height="2px";newLine.style.width="3px";newLine.style.backgroundColor="#F9F9F9";this._lines.push(newLine);this._container.appendChild(newLine)}var hovered=false;for(var index in this._handles){this._handles[index].onMove(evt);hovered=hovered||this._handles[index].hovered}this._hovered=hovered;if(this.active&&numHandles>2){this.pushPopHandle()}this.update()}},{key:"onStart",value:function onStart(evt){this._dragged=false;var active=false;for(var index in this._handles){this._handles[index].onStart(evt);active=active||this._handles[index].active}this._active=active;this.update()}},{key:"onEnd",value:function onEnd(evt){var active=false;for(var index in this._handles.slice(0,this._handles.length-2)){this._handles[index].onEnd(evt);active=active||this._handles[index].active}if(this._dragged||!this._handles[this._handles.length-1].tracking){this._handles[this._handles.length-1].tracking=false;this._handles[this._handles.length-1].onEnd(evt)}else{this._handles[this._handles.length-1].tracking=false}active=active||this._handles[this._handles.length-1].active;this._active=active;if(this._lines.length<this._handles.length){var newLine=document.createElement("div");newLine.setAttribute("class","widgets handle line");newLine.style.position="absolute";newLine.style.transformOrigin="0 100%";newLine.style.marginTop="-1px";newLine.style.height="2px";newLine.style.width="3px";newLine.style.backgroundColor="#F9F9F9";this._lines.push(newLine);this._container.appendChild(newLine)}this._init=true;this.update()}},{key:"create",value:function create(){this.createMesh();this.createDOM()}},{key:"hideDOM",value:function hideDOM(){for(var index in this._handles){this._handles[index].hideDOM()}for(var _index in this._lines){this._lines[_index].style.display="none"}}},{key:"showDOM",value:function showDOM(){for(var index in this._handles){this._handles[index].showDOM()}for(var _index2 in this._lines){this._lines[_index2].style.display=""}}},{key:"hideMesh",value:function hideMesh(){this.visible=false}},{key:"showMesh",value:function showMesh(){this.visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"update",value:function update(){this.updateColor();for(var index in this._handles){this._handles[index].update()}this.updateMeshColor();this.updateMeshPosition();this.updateDOMPosition();this.updateDOMColor()}},{key:"createMesh",value:function createMesh(){this._geometry=new THREE.Geometry;for(var index in this._handles){this._geometry.vertices.push(this._handles[index].worldPosition)}this._material=new THREE.LineBasicMaterial;this.updateMeshColor();this._mesh=new THREE.Line(this._geometry,this._material);this._mesh.visible=true;this.add(this._mesh)}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}}},{key:"updateMeshPosition",value:function updateMeshPosition(){if(this._geometry){this._geometry.verticesNeedUpdate=true}}},{key:"createDOM",value:function createDOM(){this._line=document.createElement("div");this._line.setAttribute("class","widgets handle line");this._line.style.position="absolute";this._line.style.transformOrigin="0 100%";this._line.style.marginTop="-1px";this._line.style.height="2px";this._line.style.width="3px";this._container.appendChild(this._line);this._distance=document.createElement("div");this._distance.setAttribute("class","widgets handle distance");this._distance.style.border="2px solid";this._distance.style.backgroundColor="#F9F9F9";this._distance.style.color="#353535";this._distance.style.padding="4px";this._distance.style.position="absolute";this._distance.style.transformOrigin="0 100%";this._distance.innerHTML="Hello, world!";this._container.appendChild(this._distance);this.updateDOMColor()}},{key:"isPointOnLine",value:function isPointOnLine(pointA,pointB,pointToCheck){var c=new _three.Vector3;c.crossVectors(pointA.clone().sub(pointToCheck),pointB.clone().sub(pointToCheck));return!c.length()}},{key:"pushPopHandle",value:function pushPopHandle(){var handle0=this._handles[this._handles.length-3];var handle1=this._handles[this._handles.length-2];var newhandle=this._handles[this._handles.length-1];var isOnLine=this.isPointOnLine(handle0.worldPosition,handle1.worldPosition,newhandle.worldPosition);if(isOnLine){handle1._dom.style.display="none";this.remove(handle1);this._handles[this._handles.length-2]=newhandle;this._handles.pop();var tempLine=this._lines.pop();tempLine.style.display="none";this._container.removeChild(tempLine)}return isOnLine}},{key:"updateLineDOM",value:function updateLineDOM(lineIndex,handle0Index,handle1Index){var x1=this._handles[handle0Index].screenPosition.x;var y1=this._handles[handle0Index].screenPosition.y;var x2=this._handles[handle1Index].screenPosition.x;var y2=this._handles[handle1Index].screenPosition.y;var x0=x2;var y0=y2;if(y1>=y2){y0=y2-30}else{y0=y2+30}var length=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));var angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;var posY=y1-this._container.offsetHeight;var transform="translate3D("+x1+"px, "+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._lines[lineIndex].style.transform=transform;this._lines[lineIndex].style.width=length}},{key:"updateDOMPosition",value:function updateDOMPosition(){if(this._handles.length>=2){for(var index in this._lines){this.updateLineDOM(index,index,parseInt(index)+1==this._handles.length?0:parseInt(index)+1)}}}},{key:"updateDOMColor",value:function updateDOMColor(){this._line.style.backgroundColor=""+this._color;this._distance.style.borderColor=""+this._color}},{key:"getPointInBetweenByPerc",value:function getPointInBetweenByPerc(pointA,pointB,percentage){var dir=pointB.clone().sub(pointA);var len=dir.length();dir=dir.normalize().multiplyScalar(len*percentage);return pointA.clone().add(dir)}},{key:"worldPosition",get:function get(){return this._worldPosition},set:function set(worldPosition){this._worldPosition=worldPosition
for(var index in this._handles){this._handles[index]._worldPosition=this._worldPosition}this.update()}}]);return WidgetsRoi}(_widgets2.default);exports.default=WidgetsRoi},{"./widgets.base"
165,"./widgets.handle":167,three:81}],170:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _widgets3=require("./widgets.handle");var _widgets4=_interopRequireDefault(_widgets3);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsRuler=function(_WidgetsBase){_inherits(WidgetsRuler,_WidgetsBase);function WidgetsRuler(targetMesh,controls,camera,container){_classCallCheck(this,WidgetsRuler);var _this=_possibleConstructorReturn(this,(WidgetsRuler.__proto__||Object.getPrototypeOf(WidgetsRuler)).call(this,container));_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._active=true;_this._lastEvent=null;_this._worldPosition=new _three.Vector3;if(_this._targetMesh!==null){_this._worldPosition=_this._targetMesh.position}_this._material=null;_this._geometry=null;_this._mesh=null;_this._line=null;_this._distance=null;_this._handles=[];var firstHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);firstHandle.worldPosition=_this._worldPosition;firstHandle.hovered=true;_this.add(firstHandle);_this._handles.push(firstHandle);var secondHandle=new _widgets4.default(_this._targetMesh,_this._controls,_this._camera,_this._container);secondHandle.worldPosition=_this._worldPosition;secondHandle.hovered=true;secondHandle.active=true;secondHandle.tracking=true;_this.add(secondHandle);_this._handles.push(secondHandle);_this.create();_this.initOffsets();_this.onMove=_this.onMove.bind(_this);_this.onEndControl=_this.onEndControl.bind(_this);_this.addEventListeners();return _this}_createClass(WidgetsRuler,[{key:"addEventListeners",value:function addEventListeners(){this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove);this._controls.addEventListener("end",this.onEndControl)}},{key:"removeEventListeners",value:function removeEventListeners(){this._container.removeEventListener("mousewheel",this.onMove);this._container.removeEventListener("DOMMouseScroll",this.onMove);this._controls.removeEventListener("end",this.onEndControl)}},{key:"onMove",value:function onMove(evt){this._lastEvent=evt;this._dragged=true;this._handles[0].onMove(evt);this._handles[1].onMove(evt);this._hovered=this._handles[0].hovered||this._handles[1].hovered;this.update()}},{key:"onStart",value:function onStart(evt){this._lastEvent=evt;this._dragged=false;this._handles[0].onStart(evt);this._handles[1].onStart(evt);this._active=this._handles[0].active||this._handles[1].active;this.update()}},{key:"onEnd",value:function onEnd(evt){this._lastEvent=evt;this._handles[0].onEnd(evt);if(this._dragged||!this._handles[1].tracking){this._handles[1].tracking=false;this._handles[1].onEnd(evt)}else{this._handles[1].tracking=false}this._active=this._handles[0].active||this._handles[1].active;this.update()}},{key:"onEndControl",value:function onEndControl(){var _this2=this;if(!this._lastEvent){return}window.requestAnimationFrame(function(){_this2.onMove(_this2._lastEvent)})}},{key:"create",value:function create(){this.createMesh();this.createDOM()}},{key:"hideDOM",value:function hideDOM(){this._line.style.display="none";this._distance.style.display="none";for(var index in this._handles){this._handles[index].hideDOM()}}},{key:"showDOM",value:function showDOM(){this._line.style.display="";this._distance.style.display="";for(var index in this._handles){this._handles[index].showDOM()}}},{key:"hideMesh",value:function hideMesh(){this.visible=false}},{key:"showMesh",value:function showMesh(){this.visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"update",value:function update(){this.updateColor();this._handles[0].update();this._handles[1].update();this.updateMeshColor();this.updateMeshPosition();this.updateDOMColor();this.updateDOMPosition()}},{key:"createMesh",value:function createMesh(){this._geometry=new THREE.Geometry;this._geometry.vertices.push(this._handles[0].worldPosition);this._geometry.vertices.push(this._handles[1].worldPosition);this._material=new THREE.LineBasicMaterial;this.updateMeshColor();this._mesh=new THREE.Line(this._geometry,this._material);this._mesh.visible=true;this.add(this._mesh)}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}}},{key:"updateMeshPosition",value:function updateMeshPosition(){if(this._geometry){this._geometry.verticesNeedUpdate=true}}},{key:"createDOM",value:function createDOM(){this._line=document.createElement("div");this._line.setAttribute("id",this.uuid);this._line.setAttribute("class","AMI Widget Ruler");this._line.style.position="absolute";this._line.style.transformOrigin="0 100%";this._line.style.marginTop="-1px";this._line.style.height="2px";this._line.style.width="3px";this._container.appendChild(this._line);this._distance=document.createElement("div");this._distance.setAttribute("class","widgets handle distance");this._distance.style.border="2px solid";this._distance.style.backgroundColor="#F9F9F9";this._distance.style.color="#353535";this._distance.style.padding="4px";this._distance.style.position="absolute";this._distance.style.transformOrigin="0 100%";this._distance.innerHTML="Hello, world!";this._container.appendChild(this._distance);this.updateDOMColor()}},{key:"updateDOMPosition",value:function updateDOMPosition(){var x1=this._handles[0].screenPosition.x;var y1=this._handles[0].screenPosition.y;var x2=this._handles[1].screenPosition.x;var y2=this._handles[1].screenPosition.y;var x0=x2;var y0=y2;if(y1>=y2){y0=y2-30}else{y0=y2+30}var length=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));var angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;var posY=y1-this._container.offsetHeight;var transform="translate3D("+x1+"px,"+posY+"px, 0)";transform+=" rotate("+angle+"deg)";this._line.style.transform=transform;this._line.style.width=length+"px";var w0=this._handles[0].worldPosition;var w1=this._handles[1].worldPosition;this._distance.innerHTML=Math.sqrt((w0.x-w1.x)*(w0.x-w1.x)+(w0.y-w1.y)*(w0.y-w1.y)+(w0.z-w1.z)*(w0.z-w1.z)).toFixed(2)+" mm";var posY0=y0-this._container.offsetHeight-this._distance.offsetHeight/2;x0-=this._distance.offsetWidth/2;var transform2="translate3D("+Math.round(x0)+"px,"+Math.round(posY0)+"px, 0)";this._distance.style.transform=transform2}},{key:"updateDOMColor",value:function updateDOMColor(){this._line.style.backgroundColor=""+this._color;this._distance.style.borderColor=""+this._color}},{key:"free",value:function free(){this._container.removeEventListener("mousewheel",this.onMove);this._container.removeEventListener("DOMMouseScroll",this.onMove);this._handles.forEach(function(h){h.free()});this._handles=[];this._container.removeChild(this._line);this._container.removeChild(this._distance);this.remove(this._mesh);_get(WidgetsRuler.prototype.__proto__||Object.getPrototypeOf(WidgetsRuler.prototype),"free",this).call(this)}},{key:"worldPosition",get:function get(){return this._worldPosition},set:function set(worldPosition){this._worldPosition=worldPosition;this._handles[0].worldPosition=this._worldPosition;this._handles[1].worldPosition=this._worldPosition;this.update()}}]);return WidgetsRuler}(_widgets2.default);exports.default=WidgetsRuler},{"./widgets.base":165,"./widgets.handle":167,three:81}],171:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor}}();var _get=function get(object,property,receiver){if(object===null)object=Function.prototype;var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else if("value"in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}};var _widgets=require("./widgets.base");var _widgets2=_interopRequireDefault(_widgets);var _geometries=require("../geometries/geometries.voxel");var _geometries2=_interopRequireDefault(_geometries);var _models=require("../models/models.stack");var _models2=_interopRequireDefault(_models);var _models3=require("../models/models.voxel");var _models4=_interopRequireDefault(_models3);var _core=require("../core/core.intersections");var _core2=_interopRequireDefault(_core);var _three=require("three");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&((typeof call==="undefined"?"undefined":_typeof(call))==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof(superClass)))}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var WidgetsVoxelProbe=function(_WidgetsBase){_inherits(WidgetsVoxelProbe,_WidgetsBase);function WidgetsVoxelProbe(stack,targetMesh,controls,camera,container){_classCallCheck(this,WidgetsVoxelProbe);var _this=_possibleConstructorReturn(this,(WidgetsVoxelProbe.__proto__||Object.getPrototypeOf(WidgetsVoxelProbe)).call(this,container));_this._stack=stack;_this._targetMesh=targetMesh;_this._controls=controls;_this._camera=camera;_this._plane={position:new _three.Vector3,direction:new _three.Vector3};_this._offset=new _three.Vector3;_this._raycaster=new THREE.Raycaster;_this._tracking=false;_this._mouse=new _three.Vector2;_this._lastEvent=null;_this._worldPosition=new _three.Vector3;_this._screenPosition=new _three.Vector2;_this._material=null;_this._geometry=null;_this._mesh=null;_this._meshDisplayed=true;_this._meshHovered=false;_this._meshStyle="sphere";_this._dom=null;_this._domDisplayed=true;_this._domHovered=false;_this._domStyle="circle";if(_this._targetMesh!==null){_this._worldPosition.copy(_this._targetMesh.position)}_this._screenPosition=_this.worldToScreen(_this._worldPosition,_this._camera,_this._container);_this.create();_this.initOffsets();_this.onMove=_this.onMove.bind(_this);_this.onHover=_this.onHover.bind(_this);_this.onEndControl=_this.onEndControl.bind(_this);_this.addEventListeners();return _this}_createClass(WidgetsVoxelProbe,[{key:"addEventListeners",value:function addEventListeners(){this._dom.addEventListener("mouseenter",this.onHover);this._dom.addEventListener("mouseleave",this.onHover);this._container.addEventListener("mousewheel",this.onMove);this._container.addEventListener("DOMMouseScroll",this.onMove);this._controls.addEventListener("end",this.onEndControl)}},{key:"removeEventListeners",value:function removeEventListeners(){this._dom.removeEventListener("mouseenter",this.onHover);this._dom.removeEventListener("mouseleave",this.onHover);this._container.removeEventListener("mousewheel",this.onMove);this._container.removeEventListener("DOMMouseScroll",this.onMove);this._controls.removeEventListener("end",this.onEndControl)}},{key:"onStart",value:function onStart(evt){this._lastEvent=evt;evt.preventDefault();var offsets=this.getMouseOffsets(evt,this._container);this._mouse.set(offsets.x,offsets.y);this._raycaster.setFromCamera(this._mouse,this._camera);this._raycaster.ray.position=this._raycaster.ray.origin;if(this._hovered){this._active=true;this._controls.enabled=false;if(this._targetMesh){var intersectsTarget=this._raycaster.intersectObject(this._targetMesh);if(intersectsTarget.length>0){this._offset.copy(intersectsTarget[0].point).sub(this._worldPosition)}}else{this._plane.position.copy(this._worldPosition);this._plane.direction.copy(this._camera.getWorldDirection());var intersection=_core2.default.rayPlane(this._raycaster.ray,this._plane);if(intersection!==null){this._offset.copy(intersection).sub(this._plane.position)}}this.update()}}},{key:"onEnd",value:function onEnd(evt){this._lastEvent=evt;evt.preventDefault();if(this._tracking===true){return}if(!this._dragged&&this._active){this._selected=!this._selected}this._active=false;this._dragged=false;this._controls.enabled=true;this.update()}},{key:"onEndControl",value:function onEndControl(){var _this2=this;if(!this._lastEvent){return}window.requestAnimationFrame(function(){_this2.onMove(_this2._lastEvent)})}},{key:"onMove",value:function onMove(evt){this._lastEvent=evt;evt.preventDefault();var offsets=this.getMouseOffsets(evt,this._container);this._mouse.set(offsets.x,offsets.y);this._raycaster.setFromCamera(this._mouse,this._camera);this._raycaster.ray.position=this._raycaster.ray.origin;if(this._active){this._dragged=true;if(this._targetMesh!==null){var intersectsTarget=this._raycaster.intersectObject(this._targetMesh);if(intersectsTarget.length>0){this._worldPosition.copy(intersectsTarget[0].point.sub(this._offset))}}else{if(this._plane.direction.length()===0){this._plane.position.copy(this._worldPosition);this._plane.direction.copy(this._camera.getWorldDirection())}var intersection=_core2.default.rayPlane(this._raycaster.ray,this._plane);if(intersection!==null){this._worldPosition.copy(intersection.sub(this._offset))}}}else{this.onHover(null)}this.update()}},{key:"onHover",value:function onHover(evt){if(evt){this._lastEvent=evt;evt.preventDefault();this.hoverDom(evt)}this.hoverMesh();this._hovered=this._meshHovered||this._domHovered;this._container.style.cursor=this._hovered?"pointer":"default"}},{key:"hoverMesh",value:function hoverMesh(){var intersectsHandle=this._raycaster.intersectObject(this._mesh);this._meshHovered=intersectsHandle.length>0}},{key:"hoverDom",value:function hoverDom(evt){this._domHovered=evt.type==="mouseenter"}},{key:"worldToScreen",value:function worldToScreen(worldCoordinate,camera,canvas){var screenCoordinates=worldCoordinate.clone();screenCoordinates.project(camera);screenCoordinates.x=Math.round((screenCoordinates.x+1)*canvas.offsetWidth/2);screenCoordinates.y=Math.round((-screenCoordinates.y+1)*canvas.offsetHeight/2);screenCoordinates.z=0;return screenCoordinates}},{key:"create",value:function create(){this.createVoxel();this.createMesh();this.createDOM()}},{key:"createVoxel",value:function createVoxel(){this._voxel=new _models4.default;this._voxel.id=this.id;this._voxel.worldCoordinates=this._worldCoordinates}},{key:"createMesh",value:function createMesh(){var dataCoordinates=_models2.default.worldToData(this._stack,this._worldPosition);this._geometry=new _geometries2.default(dataCoordinates);this._material=new THREE.MeshBasicMaterial({wireframe:true,wireframeLinewidth:1});this._mesh=new THREE.Mesh(this._geometry,this._material);this._mesh.applyMatrix(this._stack.ijk2LPS);this._mesh.visible=true;this.updateMeshColor();this.add(this._mesh)}},{key:"updateMeshColor",value:function updateMeshColor(){if(this._material){this._material.color.set(this._color)}}},{key:"createDOM",value:function createDOM(){this._dom=document.createElement("div");this._dom.setAttribute("id",this.uuid);this._dom.setAttribute("class","AMI Widget VoxelProbe");this._dom.style.border="2px solid #000";this._dom.style.backgroundColor="rgb(249, 249, 249)";this._dom.style.color="#212121";this._dom.style.position="absolute";this._dom.style.transformOrigin="0px 100% 0px";var measurementsContainer=document.createElement("div");var lpsContainer=document.createElement("div");lpsContainer.setAttribute("id","lpsPosition");measurementsContainer.appendChild(lpsContainer);var ijkContainer=document.createElement("div");ijkContainer.setAttribute("id","ijkPosition");measurementsContainer.appendChild(ijkContainer);var valueContainer=document.createElement("div");valueContainer.setAttribute("id","value");measurementsContainer.appendChild(valueContainer);this.updateDOMColor();this._dom.appendChild(measurementsContainer);this._container.appendChild(this._dom)}},{key:"updateDOMContent",value:function updateDOMContent(){var rasContainer=this._dom.querySelector("#lpsPosition");rasContainer.innerHTML="LPS: \n "+this._voxel.worldCoordinates.x.toFixed(2)+" :\n "+this._voxel.worldCoordinates.y.toFixed(2)+" :\n "+this._voxel.worldCoordinates.z.toFixed(2);var ijkContainer=this._dom.querySelector("#ijkPosition");ijkContainer.innerHTML="IJK: \n "+this._voxel.dataCoordinates.x+" :\n "+this._voxel.dataCoordinates.y+" :\n "+this._voxel.dataCoordinates.z;var valueContainer=this._dom.querySelector("#value");valueContainer.innerHTML="Value: "+this._voxel.value}},{key:"update",value:function update(){this.updateColor();this._screenPosition=this.worldToScreen(this._worldPosition,this._camera,this._container);this.updateVoxel(this._worldPosition);this.updateMeshColor();if(this._mesh&&this._mesh.geometry){this._mesh.geometry.location=this._voxel.dataCoordinates;this._mesh.updateMatrix()}this.updateDOMContent();this.updateDOMColor();this.updateDOMPosition()}},{key:"updateVoxel",value:function updateVoxel(worldCoordinates){this._voxel.worldCoordinates=worldCoordinates;this._voxel.dataCoordinates=_models2.default.worldToData(this._stack,this._voxel.worldCoordinates);var value=_models2.default.value(this._stack,this._voxel.dataCoordinates);this._voxel.value=_models2.default.valueRescaleSlopeIntercept(value,this._stack.rescaleSlope,this._stack.rescaleIntercept)}},{key:"updateDOMPosition",value:function updateDOMPosition(){if(this._dom){var posY=this._screenPosition.y-this._container.offsetHeight;this._dom.style.transform="translate3D("+this._screenPosition.x+"px, "+posY+"px, 0)"}}},{key:"updateDOMColor",value:function updateDOMColor(){this._dom.style.borderColor=""+this._color}},{key:"free",value:function free(){this._container.removeEventListener("mouseup",this.onMouseUpHandler,false);this._container.removeEventListener("mousemove",this.onMouseMoveHandler,false);this._container.removeEventListener("mousewheel",this.onMouseMoveHandler,false);this._container.removeEventListener("DOMMouseScroll",this.onMouseMoveHandler,false);this._voxel.removeTest();this.remove(this._voxel);this._voxel=null;_get(WidgetsVoxelProbe.prototype.__proto__||Object.getPrototypeOf(WidgetsVoxelProbe.prototype),"free",this).call(this)}},{key:"hoverVoxel",value:function hoverVoxel(mouseScreenCoordinates,currentDataCoordinates){var dx=mouseScreenCoordinates.screenX-this._voxel.voxel.screenCoordinates.x;var dy=mouseScreenCoordinates.screenY-this._voxel.voxel.screenCoordinates.y;var distance=Math.sqrt(dx*dx+dy*dy);this._voxel.distance=distance;if(distance>=0&&distance<10){this._hover=true}else{this._hover=false}}},{key:"hideDOM",value:function hideDOM(){this._dom.style.display="none"}},{key:"showDOM",value:function showDOM(){this._dom.style.display=""}},{key:"hideMesh",value:function hideMesh(){this.visible=false}},{key:"showMesh",value:function showMesh(){this.visible=true}},{key:"show",value:function show(){this.showDOM();this.showMesh()}},{key:"hide",value:function hide(){this.hideDOM();this.hideMesh()}},{key:"worldPosition",set:function set(worldPosition){this._worldPosition.copy(worldPosition);this.update()}},{key:"defaultColor",set:function set(defaultColor){this._defaultColor=defaultColor;this.update()},get:function get(){return this._defaultColor}},{key:"activeColor",set:function set(activeColor){this._activeColor=activeColor;this.update()},get:function get(){return this._activeColor}},{key:"hoverColor",set:function set(hoverColor){this._hoverColor=hoverColor;this.update()},get:function get(){return this._hoverColor}},{key:"selectedColor",set:function set(selectedColor){this._selectedColor=selectedColor;this.update()},get:function get(){return this._selectedColor}},{key:"showVoxel",set:function set(showVoxel){this._showVoxel=showVoxel;this.update()},get:function get(){return this._showVoxel}},{key:"showDomSVG",set:function set(showDomSVG){this._showDomSVG=showDomSVG;this.update()},get:function get(){return this._showDomSVG}},{key:"showDomMeasurements",set:function set(showDomMeasurements){this._showDomMeasurements=showDomMeasurements;this.update()},get:function get(){return this._showDomMeasurements}}]);return WidgetsVoxelProbe}(_widgets2.default);exports.default=WidgetsVoxelProbe},{"../core/core.intersections":103,"../geometries/geometries.voxel":110,"../models/models.stack":130,"../models/models.voxel":131,"./widgets.base":165,three:81}]},{},[96])(96)});